dioxus-core 0.8.0-alpha.3

Build fullstack web, desktop, and mobile apps with a single codebase.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::{
    any::{Any, TypeId},
    hash::{Hash, Hasher},
};

use crate::{Attribute, AttributeValue, DynamicNode, DynamicValues, Template, VNode, VText};
#[cfg(feature = "serialize")]
use dioxus_core_template::deserialize_string_leaky;

#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
#[derive(Debug, PartialEq, Clone)]
/// A literal value that can be replayed during hot reload.
pub enum HotReloadLiteral {
    /// A formatted string literal.
    Fmted(FmtedSegments),
    /// A floating point literal.
    Float(f64),
    /// An integer literal.
    Int(i64),
    /// A boolean literal.
    Bool(bool),
}

impl HotReloadLiteral {
    /// Return the formatted string segments if this is a formatted literal.
    pub fn as_fmted(&self) -> Option<&FmtedSegments> {
        match self {
            Self::Fmted(segments) => Some(segments),
            _ => None,
        }
    }

    /// Return the float value if this is a float literal.
    pub fn as_float(&self) -> Option<f64> {
        match self {
            Self::Float(f) => Some(*f),
            _ => None,
        }
    }

    /// Return the integer value if this is an integer literal.
    pub fn as_int(&self) -> Option<i64> {
        match self {
            Self::Int(i) => Some(*i),
            _ => None,
        }
    }

    /// Return the boolean value if this is a boolean literal.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }
}

impl Hash for HotReloadLiteral {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Self::Fmted(segments) => segments.hash(state),
            Self::Float(f) => f.to_bits().hash(state),
            Self::Int(i) => i.hash(state),
            Self::Bool(b) => b.hash(state),
        }
    }
}

#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
/// A formatted string split into static and dynamic segments.
pub struct FmtedSegments {
    pub(crate) segments: Vec<FmtSegment>,
}

impl FmtedSegments {
    /// Create formatted string segments.
    pub fn new(segments: Vec<FmtSegment>) -> Self {
        Self { segments }
    }

    /// Render the formatted string by stitching together the segments
    pub(crate) fn render_with(&self, dynamic_text: &[String]) -> String {
        let mut out = String::new();

        for segment in &self.segments {
            match segment {
                FmtSegment::Literal { value } => out.push_str(value),
                FmtSegment::Dynamic { id } => out.push_str(&dynamic_text[*id]),
            }
        }

        out
    }
}

type StaticStr = &'static str;

#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
/// One segment of a formatted string used by hot reload.
pub enum FmtSegment {
    /// A static string segment.
    Literal {
        /// The static string value.
        #[cfg_attr(
            feature = "serialize",
            serde(deserialize_with = "deserialize_string_leaky")
        )]
        value: StaticStr,
    },
    /// A dynamic string segment.
    Dynamic {
        /// The dynamic text value index.
        id: usize,
    },
}

// let __pool = DynamicValuePool::new(
//     vec![...],
//     vec![...],
//     vec![...],
// );
// Hot reload templates carry a decoded Template plus dynamic node/attribute mappings.

// Open questions:
// - How do we handle type coercion for different sized component property integers?
// - Should non-string hot literals go through the centralized pool?
// - Should formatted strings be a runtime concept?

#[doc(hidden)]
pub struct DynamicLiteralPool {
    dynamic_text: Box<[String]>,
}

impl DynamicLiteralPool {
    /// Create a dynamic literal pool from dynamic text values.
    pub fn new(dynamic_text: Vec<String>) -> Self {
        Self {
            dynamic_text: dynamic_text.into_boxed_slice(),
        }
    }

    /// Get a component property from a hot-reload literal.
    fn get_component_property<'a, T>(
        &self,
        id: usize,
        hot_reload: &'a HotReloadedTemplate,
        f: impl FnOnce(&'a HotReloadLiteral) -> Option<T>,
    ) -> Option<T> {
        let value = hot_reload.component_values.get(id)?;
        f(value)
    }

    fn get_component_property_or_default<'a, T: Default>(
        &self,
        id: usize,
        hot_reload: &'a HotReloadedTemplate,
        f: impl FnOnce(&'a HotReloadLiteral) -> Option<T>,
    ) -> Option<T> {
        // If the component was removed since the last hot reload, the hot reload template may not
        // have the property. If that is the case, just use a default value since the component is
        // never rendered.
        if id >= hot_reload.component_values.len() {
            return Some(T::default());
        }
        self.get_component_property(id, hot_reload, f)
    }

    /// Get a component property of a specific type at the component property index
    pub fn component_property<T: 'static>(
        &mut self,
        id: usize,
        hot_reload: &HotReloadedTemplate,
        // We pass in the original value for better type inference
        // For example, if the original literal is `0i128`, we know the output must be the type `i128`
        _coherse_type: T,
    ) -> T {
        fn assert_type<T: 'static, T2: 'static>(t: T) -> T2 {
            *(Box::new(t) as Box<dyn Any>).downcast::<T2>().unwrap()
        }
        let grab_float = || {
            self.get_component_property_or_default(id, hot_reload, HotReloadLiteral::as_float).unwrap_or_else(|| {
                tracing::error!("Expected a float component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id));
                Default::default()
            })
        };
        let grab_int = || {
            self.get_component_property_or_default(id, hot_reload, HotReloadLiteral::as_int).unwrap_or_else(|| {
                tracing::error!("Expected a integer component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id));
                Default::default()
            })
        };
        let grab_bool = || {
            self.get_component_property_or_default(id, hot_reload, HotReloadLiteral::as_bool).unwrap_or_else(|| {
                tracing::error!("Expected a bool component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id));
                Default::default()
            })
        };
        let grab_fmted = || {
            self.get_component_property_or_default(id, hot_reload, |fmted| HotReloadLiteral::as_fmted(fmted).map(|segments| self.render_formatted(segments))).unwrap_or_else(|| {
                tracing::error!("Expected a string component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id));
                Default::default()
            })
        };
        match TypeId::of::<T>() {
            // Any string types that accept a literal
            _ if TypeId::of::<String>() == TypeId::of::<T>() => assert_type(grab_fmted()),
            _ if TypeId::of::<&str>() == TypeId::of::<T>() => {
                assert_type(Box::leak(grab_fmted().into_boxed_str()) as &'static str)
            }
            // Any integer types that accept a literal
            _ if TypeId::of::<i128>() == TypeId::of::<T>() => assert_type(grab_int() as i128),
            _ if TypeId::of::<i64>() == TypeId::of::<T>() => assert_type(grab_int()),
            _ if TypeId::of::<i32>() == TypeId::of::<T>() => assert_type(grab_int() as i32),
            _ if TypeId::of::<i16>() == TypeId::of::<T>() => assert_type(grab_int() as i16),
            _ if TypeId::of::<i8>() == TypeId::of::<T>() => assert_type(grab_int() as i8),
            _ if TypeId::of::<isize>() == TypeId::of::<T>() => assert_type(grab_int() as isize),
            _ if TypeId::of::<u128>() == TypeId::of::<T>() => assert_type(grab_int() as u128),
            _ if TypeId::of::<u64>() == TypeId::of::<T>() => assert_type(grab_int() as u64),
            _ if TypeId::of::<u32>() == TypeId::of::<T>() => assert_type(grab_int() as u32),
            _ if TypeId::of::<u16>() == TypeId::of::<T>() => assert_type(grab_int() as u16),
            _ if TypeId::of::<u8>() == TypeId::of::<T>() => assert_type(grab_int() as u8),
            _ if TypeId::of::<usize>() == TypeId::of::<T>() => assert_type(grab_int() as usize),
            // Any float types that accept a literal
            _ if TypeId::of::<f64>() == TypeId::of::<T>() => assert_type(grab_float()),
            _ if TypeId::of::<f32>() == TypeId::of::<T>() => assert_type(grab_float() as f32),
            // Any bool types that accept a literal
            _ if TypeId::of::<bool>() == TypeId::of::<T>() => assert_type(grab_bool()),
            _ => panic!("Unsupported component property type"),
        }
    }

    /// Render formatted segments using the current dynamic text pool.
    fn render_formatted(&self, segments: &FmtedSegments) -> String {
        segments.render_with(&self.dynamic_text)
    }
}
#[doc(hidden)]
pub struct DynamicValuePool {
    dynamic_attributes: Box<[Box<[Attribute]>]>,
    dynamic_nodes: Box<[DynamicNode]>,
    literal_pool: DynamicLiteralPool,
}

impl DynamicValuePool {
    /// Create a dynamic node/attribute value pool.
    fn new(
        dynamic_nodes: Vec<DynamicNode>,
        dynamic_attributes: Vec<Box<[Attribute]>>,
        literal_pool: DynamicLiteralPool,
    ) -> Self {
        Self {
            dynamic_attributes: dynamic_attributes.into_boxed_slice(),
            dynamic_nodes: dynamic_nodes.into_boxed_slice(),
            literal_pool,
        }
    }

    /// Create a dynamic node/attribute value pool from a vnode.
    pub fn from_vnode(vnode: &VNode, literal_pool: DynamicLiteralPool) -> Self {
        let dynamic_nodes = vnode.dynamic_node_values().to_vec();
        let dynamic_attributes = vnode.dynamic_attr_values().to_vec();

        Self::new(dynamic_nodes, dynamic_attributes, literal_pool)
    }

    /// Render a vnode from a hot-reloaded template.
    pub fn render_with(&mut self, hot_reload: &HotReloadedTemplate) -> VNode {
        let key = hot_reload
            .key
            .as_ref()
            .map(|key| self.literal_pool.render_formatted(key));
        let dynamic_nodes = hot_reload
            .dynamic_nodes
            .iter()
            .map(|node| self.render_dynamic_node(node))
            .collect::<Vec<_>>();
        let dynamic_attributes = hot_reload
            .dynamic_attributes
            .iter()
            .map(|attr| self.render_attribute(attr))
            .collect::<Vec<_>>();

        VNode::new(
            hot_reload.template,
            DynamicValues::from_parts(
                key,
                dynamic_nodes.into_boxed_slice(),
                dynamic_attributes.into_boxed_slice(),
            ),
        )
    }

    fn render_dynamic_node(&mut self, node: &HotReloadDynamicNode) -> DynamicNode {
        match node {
            // If the node is dynamic, take it from the pool and return it
            HotReloadDynamicNode::Dynamic(id) => self.dynamic_nodes[*id].clone(),
            // Otherwise, format the text node and return it
            HotReloadDynamicNode::Formatted(segments) => DynamicNode::Text(VText {
                value: self.literal_pool.render_formatted(segments),
            }),
        }
    }

    fn render_attribute(&mut self, attr: &HotReloadDynamicAttribute) -> Box<[Attribute]> {
        match attr {
            HotReloadDynamicAttribute::Dynamic(id) => self.dynamic_attributes[*id].clone(),
            HotReloadDynamicAttribute::Named(NamedAttribute {
                name,
                namespace,
                value,
            }) => Box::new([Attribute {
                name,
                namespace: *namespace,
                value: match value {
                    HotReloadAttributeValue::Literal(HotReloadLiteral::Fmted(segments)) => {
                        AttributeValue::Text(self.literal_pool.render_formatted(segments))
                    }
                    HotReloadAttributeValue::Literal(HotReloadLiteral::Float(f)) => {
                        AttributeValue::Float(*f)
                    }
                    HotReloadAttributeValue::Literal(HotReloadLiteral::Int(i)) => {
                        AttributeValue::Int(*i)
                    }
                    HotReloadAttributeValue::Literal(HotReloadLiteral::Bool(b)) => {
                        AttributeValue::Bool(*b)
                    }
                    HotReloadAttributeValue::Dynamic(id) => {
                        self.dynamic_attributes[*id][0].value.clone()
                    }
                },
                volatile: false,
            }]),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
/// A hot-reloaded template with its source location key.
pub struct HotReloadTemplateWithLocation {
    /// The source location key.
    pub key: TemplateGlobalKey,
    /// The hot-reloaded template.
    pub template: HotReloadedTemplate,
}

#[derive(Debug, Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
/// Source location key for a hot-reload template.
pub struct TemplateGlobalKey {
    /// Source file path.
    pub file: String,
    /// Source line.
    pub line: usize,
    /// Source column.
    pub column: usize,
    /// Template index at the source location.
    pub index: usize,
}

#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[doc(hidden)]
/// Template data and dynamic node/attribute mappings for hot reload.
pub struct HotReloadedTemplate {
    /// Optional dynamic key segments.
    pub key: Option<FmtedSegments>,
    /// Dynamic node mappings.
    pub dynamic_nodes: Vec<HotReloadDynamicNode>,
    /// Dynamic attribute mappings.
    pub dynamic_attributes: Vec<HotReloadDynamicAttribute>,
    /// Component literal values.
    pub component_values: Vec<HotReloadLiteral>,
    template: Template,
}

impl HotReloadedTemplate {
    /// Create hot-reload data from a template and dynamic node/attribute mappings.
    pub fn from_template(
        key: Option<FmtedSegments>,
        dynamic_nodes: Vec<HotReloadDynamicNode>,
        dynamic_attributes: Vec<HotReloadDynamicAttribute>,
        component_values: Vec<HotReloadLiteral>,
        template: Template,
    ) -> Self {
        Self {
            key,
            dynamic_nodes,
            dynamic_attributes,
            component_values,
            template,
        }
    }

    /// Return the number of root positions in the template.
    pub fn root_count(&self) -> usize {
        self.template.root_count()
    }

    /// Return decoded template operations for inspection.
    pub fn decoded_ops(&self) -> Vec<dioxus_core_template::DecodedTemplateOp> {
        self.template.decoded_ops().collect()
    }

    /// Return the static string pool for inspection.
    pub fn static_strings(&self) -> &'static [&'static str] {
        self.template.strings()
    }
}

#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for HotReloadedTemplate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        struct SerializedHotReloadedTemplate {
            key: Option<FmtedSegments>,
            dynamic_nodes: Vec<HotReloadDynamicNode>,
            dynamic_attributes: Vec<HotReloadDynamicAttribute>,
            component_values: Vec<HotReloadLiteral>,
            template: Template,
        }

        let serialized = SerializedHotReloadedTemplate::deserialize(deserializer)?;
        Ok(Self::from_template(
            serialized.key,
            serialized.dynamic_nodes,
            serialized.dynamic_attributes,
            serialized.component_values,
            serialized.template,
        ))
    }
}

#[derive(Debug, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
/// Dynamic node source for hot reload.
pub enum HotReloadDynamicNode {
    /// Reuse a dynamic node by index.
    Dynamic(usize),
    /// Create a text node from formatted segments.
    Formatted(FmtedSegments),
}

#[derive(Debug, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
/// Dynamic attribute source for hot reload.
pub enum HotReloadDynamicAttribute {
    /// Reuse a dynamic attribute by index.
    Dynamic(usize),
    /// Create an attribute from a named value.
    Named(NamedAttribute),
}

#[derive(Debug, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
/// A named attribute generated for hot reload.
pub struct NamedAttribute {
    /// The name of this attribute.
    #[cfg_attr(
        feature = "serialize",
        serde(deserialize_with = "dioxus_core_template::deserialize_string_leaky")
    )]
    name: StaticStr,
    /// The namespace of this attribute. Does not exist in the HTML spec
    #[cfg_attr(
        feature = "serialize",
        serde(deserialize_with = "dioxus_core_template::deserialize_option_leaky")
    )]
    namespace: Option<StaticStr>,
    /// Attribute value.
    value: HotReloadAttributeValue,
}

impl NamedAttribute {
    /// Create a named hot-reload attribute.
    pub fn new(
        name: &'static str,
        namespace: Option<&'static str>,
        value: HotReloadAttributeValue,
    ) -> Self {
        Self {
            name,
            namespace,
            value,
        }
    }
}

#[derive(Debug, PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(hidden)]
/// Attribute value source for hot reload.
pub enum HotReloadAttributeValue {
    /// Literal attribute value.
    Literal(HotReloadLiteral),
    /// Reuse a dynamic attribute value by index.
    Dynamic(usize),
}