Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions crates/vertigo-macro/src/html_parser/commons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,16 @@ pub(super) fn parse_block_of_statements(
quote! { into() }
};

// If the last statement is a reference, use it as the value
// Otherwise, try to unwrap single statement block or use the whole block as the value
let value = dereferenced.unwrap_or_else(|| unwrap_block_if_single(block));
// For multi-statement blocks ending with a reference, keep the whole block so that
// preceding statements (e.g. `let mut x = ...; x += 1; &x`) are not lost.
// For single-statement reference blocks (e.g. `{&my_var}`), use the inner expression
// directly so `.clone()` applies to the value, not to a double-reference.
// For non-reference blocks, unwrap single-statement blocks or use the whole block.
let value = match &dereferenced {
Some(inner) if block.stmts.len() > 1 => block.to_token_stream(),
Some(inner) => inner.clone(),
None => unwrap_block_if_single(block),
};

(key, value, method)
}
Expand Down Expand Up @@ -237,14 +244,24 @@ mod tests {

#[test]
fn test_parse_block_of_statements_reference_value() {
// Reference: key and value are the inner expr; method is clone()
// Single-statement reference: inner expr used as value so `.clone()` applies correctly
let block: Block = syn::parse_quote! { { &my_var } };
let (key, value, method) = parse_block_of_statements(&block);
assert_eq!(key.to_string(), "my_var");
assert_eq!(value.to_string(), "my_var");
assert_eq!(method.to_string(), "clone ()");
}

#[test]
fn test_parse_block_of_statements_reference_with_preceding_stmts() {
// Multi-statement block ending with a reference: whole block preserved as value
let block: Block = syn::parse_quote! { { let mut x = 1; x += 1; &x } };
let (key, value, method) = parse_block_of_statements(&block);
assert_eq!(key.to_string(), "x");
assert_eq!(value.to_string(), "{ let mut x = 1 ; x += 1 ; & x }");
assert_eq!(method.to_string(), "clone ()");
}

#[test]
fn test_extract_spread_block_with_spread() {
// Spread block: last stmt is a range like `..expr`
Expand Down
1 change: 1 addition & 0 deletions crates/vertigo-macro/src/html_parser/group_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ fn attr_to_group_variant(key: impl AsRef<str>, value: TokenStream2) -> TokenStre
"hook_key_down" => quote! { vertigo::AttrGroupValue::hook_key_down(#value) },
"on_blur" => quote! { vertigo::AttrGroupValue::on_blur(#value) },
"on_change" => quote! { vertigo::AttrGroupValue::on_change(#value) },
"on_change_file" => quote! { vertigo::AttrGroupValue::on_change_file(#value) },
"on_click" => quote! { vertigo::AttrGroupValue::on_click(#value) },
"on_dropfile" => quote! { vertigo::AttrGroupValue::on_dropfile(#value) },
"on_input" => quote! { vertigo::AttrGroupValue::on_input(#value) },
Expand Down
6 changes: 3 additions & 3 deletions crates/vertigo-macro/src/html_parser/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,9 @@ fn push_attribute(
}

let method_str = match name.as_str() {
"hook_key_down" | "on_blur" | "on_change" | "on_click" | "on_dropfile" | "on_input"
| "on_key_down" | "on_load" | "on_mouse_down" | "on_mouse_enter" | "on_mouse_leave"
| "on_mouse_up" | "on_submit" => &name,
"hook_key_down" | "on_blur" | "on_change" | "on_change_file" | "on_click"
| "on_dropfile" | "on_input" | "on_key_down" | "on_load" | "on_mouse_down"
| "on_mouse_enter" | "on_mouse_leave" | "on_mouse_up" | "on_submit" => &name,

"form" => "on_submit",

Expand Down
37 changes: 37 additions & 0 deletions crates/vertigo/src/dom/dom_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ impl DomElement {
("on_dropfile", AttrGroupValue::OnDropfile(on_dropfile)) => {
self.on_dropfile_rc(on_dropfile)
}
("on_change_file", AttrGroupValue::OnChangeFile(on_change_file)) => {
self.on_change_file_rc(on_change_file)
}
("on_input", AttrGroupValue::OnInput(on_input)) => self.on_input_rc(on_input),
("on_key_down", AttrGroupValue::OnKeyDown(on_key_down)) => {
self.on_key_down_rc(on_key_down)
Expand Down Expand Up @@ -274,6 +277,40 @@ impl DomElement {
})
}

pub fn on_change_file(self, on_change_file: impl Into<Callback1<DropFileEvent, ()>>) -> Self {
self.on_change_file_rc(Rc::new(on_change_file.into()))
}

pub fn on_change_file_rc(self, on_change_file: Rc<Callback1<DropFileEvent, ()>>) -> Self {
let on_change_file = self.install_callback1(on_change_file);

self.add_event_listener("change_file", move |data| {
let params = data.map_list(|mut params: JsJsonListDecoder| {
let files = params.get_vec("change file", |item: JsJson| {
item.map_list(|mut item: JsJsonListDecoder| {
let name = item.get_string("name")?;
let data = item.get_buffer("data")?;

Ok(DropFileItem::new(name, data))
})
})?;

Ok(DropFileEvent::new(files))
});

match params {
Ok(params) => {
on_change_file(params);
}
Err(error) => {
log::error!("on_change_file -> params decode error -> {error}");
}
};

JsJson::Null
})
}

pub fn on_click(self, on_click: impl Into<Callback1<ClickEvent, ()>>) -> Self {
self.on_click_rc(Rc::new(on_click.into()))
}
Expand Down
2 changes: 2 additions & 0 deletions crates/vertigo/src/dom_macro/dom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub enum AttrGroupValue {
OnChange(Rc<Callback1<String, ()>>),
OnClick(Rc<Callback1<ClickEvent, ()>>),
OnDropfile(Rc<Callback1<DropFileEvent, ()>>),
OnChangeFile(Rc<Callback1<DropFileEvent, ()>>),
OnInput(Rc<Callback1<String, ()>>),
OnKeyDown(Rc<Callback1<KeyDownEvent, bool>>),
OnLoad(Rc<Callback<()>>),
Expand Down Expand Up @@ -88,6 +89,7 @@ impl AttrGroupValue {
group_value_constructor!(on_change, Callback1<String, ()>, OnChange);
group_value_constructor!(on_click, Callback1<ClickEvent, ()>, OnClick);
group_value_constructor!(on_dropfile, Callback1<DropFileEvent, ()>, OnDropfile);
group_value_constructor!(on_change_file, Callback1<DropFileEvent, ()>, OnChangeFile);
group_value_constructor!(on_input, Callback1<String, ()>, OnInput);
group_value_constructor!(on_key_down, Callback1<KeyDownEvent, bool>, OnKeyDown);
group_value_constructor!(on_load, Callback<()>, OnLoad);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ export class CallbackManager {
return this.load(event, callback_id);
}

if (event_name === 'change_file') {
return this.changeFile(event, callback_id);
}

console.error(`No support for the event ${event_name}`);
};

Expand All @@ -82,7 +86,8 @@ export class CallbackManager {
document.addEventListener('keydown', callback, false);
} else {
const node = nodes.get('callback_add', id);
node.addEventListener(event_name, callback, false);
const domEventName = event_name === 'change_file' ? 'change' : event_name;
node.addEventListener(domEventName, callback, false);
}
}

Expand All @@ -99,7 +104,8 @@ export class CallbackManager {
document.removeEventListener('keydown', callback);
} else {
const node = nodes.get('callback_remove', id);
node.removeEventListener(event_name, callback);
const domEventName = event_name === 'change_file' ? 'change' : event_name;
node.removeEventListener(domEventName, callback);
}
}

Expand Down Expand Up @@ -154,6 +160,41 @@ export class CallbackManager {
console.warn('event input ignore', target);
}

private changeFile(event: Event, callback_id: CallbackId) {
const target = event.target;

if (target instanceof HTMLInputElement && target.files !== null && target.files.length > 0) {
const promises: Array<Promise<{ name: string, data: Uint8Array }>> = [];

for (let i = 0; i < target.files.length; i++) {
const file = target.files[i];
if (file !== undefined) {
promises.push(
file.arrayBuffer().then((buf) => ({
name: file.name,
data: new Uint8Array(buf),
}))
);
}
}

if (promises.length > 0) {
Promise.all(promises).then((files) => {
const params = [];
for (const f of files) {
params.push([f.name, Array.from(f.data)]);
}
this.wasmCallback(callback_id, [params]);
}).catch((err) => console.error('changeFile ->', err));
}

target.value = '';
return;
}

console.warn('changeFile: not a file input or no files', target);
}

private blur(_event: Event, callback_id: CallbackId) {
this.wasmCallback(callback_id, undefined);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/vertigo/src/driver_module/wasm_run.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion crates/vertigo/src/driver_module/wasm_run.js.map

Large diffs are not rendered by default.

51 changes: 27 additions & 24 deletions crates/vertigo/src/tests/dom/component_namespaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
/// This test checks if component can be used when not in local scope
/// (whole name does not start with capital letter)
fn test_namespaces() {
use crate::{self as vertigo, DomNode, dom};
use crate::dev::inspect::{DomDebugFragment, log_start};
use crate::{self as vertigo, dom};

mod my_module {
pub mod inner {
Expand All @@ -16,23 +17,15 @@ fn test_namespaces() {
}
}

let ret = dom! {
log_start();
let _el = dom! {
<my_module::inner::Hello name={"world"} />
};

match ret {
DomNode::Node { node } => {
match node.get_children().pop_back() {
// If node has text child, then component "Hello" was embedded correctly
Some(child) => match child {
DomNode::Text { node: _ } => {}
_ => panic!("Expected text child"),
},
_ => panic!("Expected child node"),
}
}
_ => panic!("Expected DomNode::Node"),
}
let html = DomDebugFragment::from_log().to_pseudo_html();
assert_eq!(
html,
"<span v-component='my_module::inner::Hello'>Hello world</span>"
);
}

#[test]
Expand All @@ -48,13 +41,18 @@ fn test_pub_super() {
}
}

use crate::{self as vertigo, DomNode, dom};
use crate::dev::inspect::{DomDebugFragment, log_start};
use crate::{self as vertigo, dom};

let ret = dom! {
log_start();
let _el = dom! {
<p><sub_module::Hello name={"world"} /></p>
};

assert!(matches!(ret, DomNode::Node { node: _ }));
let html = DomDebugFragment::from_log().to_pseudo_html();
assert_eq!(
html,
"<p><span v-component='sub_module::Hello'>Hello world</span></p>"
);
}

#[test]
Expand All @@ -71,11 +69,16 @@ fn test_pub_crate() {
}
}

use crate::{self as vertigo, DomNode, dom};
use crate::dev::inspect::{DomDebugFragment, log_start};
use crate::{self as vertigo, dom};

let ret = dom! {
log_start();
let _el = dom! {
<p><sub_module::sub_sub_module::Hello name={"world"} /></p>
};

assert!(matches!(ret, DomNode::Node { node: _ }));
let html = DomDebugFragment::from_log().to_pseudo_html();
assert_eq!(
html,
"<p><span v-component='sub_module::sub_sub_module::Hello'>Hello world</span></p>"
);
}
Loading
Loading