ps-dioxus-native-dom 0.7.4

Core headless native renderer for Dioxus based on blitz
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Integration between Dioxus and Blitz
use crate::{NodeId, qual_name, trace, write_once_attr::WriteOnceAttr};
use blitz_dom::{BaseDocument, Document, DocumentMutator, Widget};
use blitz_traits::events::DomEventKind;
use dioxus_core::{
    AttributeValue, ElementId, Template, TemplateAttribute, TemplateNode, WriteMutations,
};
use rustc_hash::FxHashMap;
use std::str::FromStr as _;

/// The state of the Dioxus integration with the RealDom
#[derive(Debug)]
pub struct DioxusState {
    /// Store of templates keyed by unique name
    pub(crate) templates: FxHashMap<Template, Vec<NodeId>>,
    /// Stack machine state for applying dioxus mutations
    pub(crate) stack: Vec<NodeId>,
    /// Mapping from vdom ElementId -> rdom NodeId
    pub(crate) node_id_mapping: Vec<Option<NodeId>>,
    /// Reverse mapping from rdom NodeId -> vdom ElementId
    pub(crate) element_id_mapping: FxHashMap<NodeId, ElementId>,
    /// Count of each handler type (indexed by `DomEventKind` discriminant)
    pub(crate) event_handler_counts: [u32; 64],
    /// Mounted events queued as elements are mounted
    pub(crate) queued_mounted_events: Vec<ElementId>,
}

impl DioxusState {
    /// Initialize the DioxusState in the RealDom
    pub fn create(root_id: NodeId) -> Self {
        Self {
            templates: FxHashMap::default(),
            stack: vec![root_id],
            node_id_mapping: vec![Some(root_id)],
            element_id_mapping: FxHashMap::from_iter([(root_id, ElementId(0))]),
            event_handler_counts: [0; 64],
            queued_mounted_events: Vec::new(),
        }
    }

    /// Convert an ElementId to a NodeId
    pub fn element_to_node_id(&self, element_id: ElementId) -> NodeId {
        self.try_element_to_node_id(element_id).unwrap()
    }

    /// Attempt to convert an ElementId to a NodeId. This will return None if the ElementId is not in the RealDom.
    pub fn try_element_to_node_id(&self, element_id: ElementId) -> Option<NodeId> {
        self.node_id_mapping.get(element_id.0).copied().flatten()
    }

    pub(crate) fn anchor_and_nodes(&mut self, id: ElementId, m: usize) -> (NodeId, Vec<NodeId>) {
        let anchor_node_id = self.element_to_node_id(id);
        let new_nodes = self.m_stack_nodes(m);
        (anchor_node_id, new_nodes)
    }

    pub(crate) fn m_stack_nodes(&mut self, m: usize) -> Vec<NodeId> {
        self.stack.split_off(self.stack.len() - m)
    }

    pub(crate) fn queue_mount_event(&mut self, id: ElementId) {
        self.queued_mounted_events.push(id);
    }
}

/// A writer for mutations that can be used with the RealDom.
pub struct MutationWriter<'a> {
    /// The realdom associated with this writer
    pub docm: DocumentMutator<'a>,
    /// The state associated with this writer
    pub state: &'a mut DioxusState,
}

impl<'a> MutationWriter<'a> {
    pub fn new(doc: &'a mut BaseDocument, state: &'a mut DioxusState) -> Self {
        MutationWriter {
            docm: doc.mutate(),
            state,
        }
    }
}

impl MutationWriter<'_> {
    /// Update an ElementId -> NodeId mapping
    fn set_id_mapping(&mut self, node_id: NodeId, element_id: ElementId) {
        let element_id: usize = element_id.0;

        // Ensure node_id_mapping is large enough to contain element_id
        if self.state.node_id_mapping.len() <= element_id {
            self.state.node_id_mapping.resize(element_id + 1, None);
        }

        // Set the new mapping (and keep the reverse mapping in sync)
        if let Some(old_node_id) = self.state.node_id_mapping[element_id].replace(node_id)
            && self.state.element_id_mapping.get(&old_node_id) == Some(&ElementId(element_id))
        {
            self.state.element_id_mapping.remove(&old_node_id);
        }
        self.state
            .element_id_mapping
            .insert(node_id, ElementId(element_id));
    }

    /// Create a ElementId -> NodeId mapping and push the node to the stack
    fn map_new_node(&mut self, node_id: NodeId, element_id: ElementId) {
        self.set_id_mapping(node_id, element_id);
        self.state.stack.push(node_id);
    }

    /// Find a child in the document by child index path
    fn load_child(&self, path: &[u8]) -> NodeId {
        let top_of_stack_node_id = *self.state.stack.last().unwrap();
        self.docm.node_at_path(top_of_stack_node_id, path)
    }
}

impl WriteMutations for MutationWriter<'_> {
    fn assign_node_id(&mut self, path: &'static [u8], id: ElementId) {
        trace!("assign_node_id path:{:?} id:{}", path, id.0);

        // If there is an existing node already mapped to that ID and it has no parent, then drop it.
        // Dropping the node also drops all of its descendants, so clear the mappings of every
        // dropped node to prevent them dangling and aliasing onto unrelated nodes when the
        // underlying slab slots are reused.
        // TODO: more automated GC/ref-counted semantics for node lifetimes
        if let Some(node_id) = self.state.try_element_to_node_id(id) {
            let state = &mut *self.state;
            self.docm
                .remove_node_if_unparented_with(node_id, &mut |dropped_node_id| {
                    if let Some(element_id) = state.element_id_mapping.remove(&dropped_node_id)
                        && state.node_id_mapping.get(element_id.0).copied().flatten()
                            == Some(dropped_node_id)
                    {
                        state.node_id_mapping[element_id.0] = None;
                    }
                });
        }

        // Map the node at specified path
        self.set_id_mapping(self.load_child(path), id);
    }

    fn create_placeholder(&mut self, id: ElementId) {
        trace!("create_placeholder id:{}", id.0);
        let node_id = self.docm.create_comment_node("");
        self.map_new_node(node_id, id);
    }

    fn create_text_node(&mut self, value: &str, id: ElementId) {
        trace!("create_text_node id:{} text:{}", id.0, value);
        let node_id = self.docm.create_text_node(value);
        self.map_new_node(node_id, id);
    }

    fn append_children(&mut self, id: ElementId, m: usize) {
        trace!("append_children id:{} m:{}", id.0, m);
        let (parent_id, child_node_ids) = self.state.anchor_and_nodes(id, m);
        self.docm.append_children(parent_id, &child_node_ids);
    }

    fn insert_nodes_after(&mut self, id: ElementId, m: usize) {
        trace!("insert_nodes_after id:{} m:{}", id.0, m);
        let (anchor_node_id, new_node_ids) = self.state.anchor_and_nodes(id, m);
        self.docm.insert_nodes_after(anchor_node_id, &new_node_ids);
    }

    fn insert_nodes_before(&mut self, id: ElementId, m: usize) {
        trace!("insert_nodes_before id:{} m:{}", id.0, m);
        let (anchor_node_id, new_node_ids) = self.state.anchor_and_nodes(id, m);
        self.docm.insert_nodes_before(anchor_node_id, &new_node_ids);
    }

    fn replace_node_with(&mut self, id: ElementId, m: usize) {
        trace!("replace_node_with id:{} m:{}", id.0, m);
        let (anchor_node_id, new_node_ids) = self.state.anchor_and_nodes(id, m);
        self.docm.replace_node_with(anchor_node_id, &new_node_ids);
    }

    fn replace_placeholder_with_nodes(&mut self, path: &'static [u8], m: usize) {
        trace!("replace_placeholder_with_nodes path:{:?} m:{}", path, m);
        // WARNING: DO NOT REORDER
        // The order of the following two lines is very important as "m_stack_nodes" mutates
        // the stack and then "load_child" reads from the top of the stack.
        let new_node_ids = self.state.m_stack_nodes(m);
        let anchor_node_id = self.load_child(path);
        self.docm.replace_node_with(anchor_node_id, &new_node_ids);
    }

    fn remove_node(&mut self, id: ElementId) {
        trace!("remove_node id:{}", id.0);
        let node_id = self.state.element_to_node_id(id);
        self.docm.remove_node(node_id);
    }

    fn push_root(&mut self, id: ElementId) {
        trace!("push_root id:{}", id.0);
        let node_id = self.state.element_to_node_id(id);
        self.state.stack.push(node_id);
    }

    fn set_node_text(&mut self, value: &str, id: ElementId) {
        trace!("set_node_text id:{} value:{}", id.0, value);
        let node_id = self.state.element_to_node_id(id);
        self.docm.set_node_text(node_id, value);
    }

    fn set_attribute(
        &mut self,
        local_name: &'static str,
        ns: Option<&'static str>,
        value: &AttributeValue,
        id: ElementId,
    ) {
        let node_id = self.state.element_to_node_id(id);
        fn is_falsy(val: &AttributeValue) -> bool {
            match val {
                AttributeValue::None => true,
                AttributeValue::Text(val) => val == "false",
                AttributeValue::Bool(val) => !val,
                AttributeValue::Int(val) => *val == 0,
                AttributeValue::Float(val) => *val == 0.0,
                _ => false,
            }
        }

        // Set/unset subdocument for <web-view __webview_document>
        if local_name == "__webview_document" {
            match value {
                AttributeValue::Any(value) => {
                    if let Some(value) = value
                        .as_any()
                        .downcast_ref::<WriteOnceAttr<Box<dyn Document>>>()
                        && let Some(mut sub_document) = value.take()
                    {
                        sub_document
                            .inner_mut()
                            .set_shell_provider(self.docm.doc.shell_provider.clone());
                        self.docm.set_sub_document(node_id, sub_document);
                    }
                }
                _ => self.docm.remove_sub_document(node_id),
            }
        }

        // Set/unset custom widget for <object data>
        if local_name == "data" {
            let element_name = self.docm.element_name(node_id).unwrap();
            if element_name.local.as_ref() == "object" {
                match value {
                    AttributeValue::Any(value) => {
                        if let Some(value) = value
                            .as_any()
                            .downcast_ref::<WriteOnceAttr<Box<dyn Widget>>>()
                            && let Some(widget) = value.take()
                        {
                            self.docm.set_custom_widget(node_id, widget);
                        }
                    }
                    _ => self.docm.remove_custom_widget(node_id),
                }
            }
        }

        let falsy = is_falsy(value);
        match value {
            AttributeValue::None => {
                set_attribute_inner(&mut self.docm, local_name, ns, None, falsy, node_id)
            }
            AttributeValue::Text(value) => {
                set_attribute_inner(&mut self.docm, local_name, ns, Some(value), falsy, node_id)
            }
            AttributeValue::Float(value) => {
                let value = value.to_string();
                set_attribute_inner(&mut self.docm, local_name, ns, Some(&value), falsy, node_id);
            }
            AttributeValue::Int(value) => {
                let value = value.to_string();
                set_attribute_inner(&mut self.docm, local_name, ns, Some(&value), falsy, node_id);
            }
            AttributeValue::Bool(value) => {
                let value = value.to_string();
                set_attribute_inner(&mut self.docm, local_name, ns, Some(&value), falsy, node_id);
            }
            _ => {
                // FIXME: support all attribute types
            }
        };
    }

    fn load_template(&mut self, template: Template, index: usize, id: ElementId) {
        // TODO: proper template node support
        let template_entry = self.state.templates.entry(template).or_insert_with(|| {
            let template_root_ids: Vec<NodeId> = template
                .roots
                .iter()
                .map(|root| create_template_node(&mut self.docm, root))
                .collect();

            template_root_ids
        });

        let template_node_id = template_entry[index];
        let clone_id = self.docm.deep_clone_node(template_node_id);

        trace!("load_template template_node_id:{template_node_id} clone_id:{clone_id}");
        self.map_new_node(clone_id, id);
    }

    fn create_event_listener(&mut self, name: &'static str, id: ElementId) {
        // Mounted events are fired immediately after the element is mounted.
        if name == "mounted" {
            self.state.queue_mount_event(id);
            return;
        }

        // We're going to actually set the listener here as a placeholder - in JS this would also be a placeholder
        // we might actually just want to attach the attribute to the root element (delegation)
        let value = AttributeValue::Text("<rust func>".into());
        self.set_attribute(name, None, &value, id);

        // Also set the data-dioxus-id attribute so we can find the element later
        let value = AttributeValue::Text(id.0.to_string());
        self.set_attribute("data-dioxus-id", None, &value, id);

        // node.add_event_listener(name);

        if let Ok(kind) = DomEventKind::from_str(name) {
            let idx = kind.discriminant() as usize;
            self.state.event_handler_counts[idx] += 1;
        }
    }

    fn remove_event_listener(&mut self, name: &'static str, _id: ElementId) {
        if let Ok(kind) = DomEventKind::from_str(name) {
            let idx = kind.discriminant() as usize;
            self.state.event_handler_counts[idx] -= 1;
        }
    }
}

fn create_template_node(docm: &mut DocumentMutator<'_>, node: &TemplateNode) -> NodeId {
    match node {
        TemplateNode::Element {
            tag,
            namespace,
            attrs,
            children,
        } => {
            let name = qual_name(tag, *namespace);
            // let attrs = attrs.iter().filter_map(map_template_attr).collect();
            let node_id = docm.create_element(name, Vec::new());

            for attr in attrs.iter() {
                let TemplateAttribute::Static {
                    name,
                    value,
                    namespace,
                } = attr
                else {
                    continue;
                };
                let falsy = *value == "false";
                set_attribute_inner(docm, name, *namespace, Some(value), falsy, node_id);
            }

            let child_ids: Vec<NodeId> = children
                .iter()
                .map(|child| create_template_node(docm, child))
                .collect();

            docm.append_children(node_id, &child_ids);

            node_id
        }
        TemplateNode::Text { text } => docm.create_text_node(text),
        TemplateNode::Dynamic { .. } => docm.create_comment_node(""),
    }
}

fn set_attribute_inner(
    docm: &mut DocumentMutator<'_>,
    local_name: &'static str,
    ns: Option<&'static str>,
    value: Option<&str>,
    is_falsy: bool,
    node_id: NodeId,
) {
    trace!("set_attribute node_id:{node_id} ns: {ns:?} name:{local_name}, value:{value:?}");

    // Dioxus has overloaded the style namespace to accumulate style attributes without a `style` block
    // TODO: accumulate style attributes into a single style element.
    if ns == Some("style") {
        match value {
            Some(value) => docm.set_style_property(node_id, local_name, value),
            None => docm.remove_style_property(node_id, local_name),
        }
        return;
    }

    let name = qual_name(local_name, ns);

    // FIXME: more principled handling of special case attributes
    match value {
        None => docm.clear_attribute(node_id, name),
        Some(value) => {
            if local_name == "checked" && is_falsy {
                docm.clear_attribute(node_id, name);
            } else if local_name == "dangerous_inner_html" {
                docm.set_inner_html(node_id, value);
            } else {
                docm.set_attribute(node_id, name, value);
            }
        }
    }
}