nodes.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. use crate::{
  2. any_props::AnyProps, arena::ElementId, Element, Event, LazyNodes, ScopeId, ScopeState,
  3. };
  4. use bumpalo::boxed::Box as BumpBox;
  5. use bumpalo::Bump;
  6. use std::{
  7. any::{Any, TypeId},
  8. cell::{self, Cell, RefCell, UnsafeCell},
  9. fmt::{Arguments, Debug},
  10. future::Future,
  11. };
  12. pub type TemplateId = &'static str;
  13. /// The actual state of the component's most recent computation
  14. ///
  15. /// Because Dioxus accepts components in the form of `async fn(Scope) -> Result<VNode>`, we need to support both
  16. /// sync and async versions.
  17. ///
  18. /// Dioxus will do its best to immediately resolve any async components into a regular Element, but as an implementor
  19. /// you might need to handle the case where there's no node immediately ready.
  20. pub enum RenderReturn<'a> {
  21. /// A currently-available element
  22. Ready(VNode<'a>),
  23. /// The component aborted rendering early. It might've thrown an error.
  24. ///
  25. /// In its place we've produced a placeholder to locate its spot in the dom when
  26. /// it recovers.
  27. Aborted(VPlaceholder),
  28. /// An ongoing future that will resolve to a [`Element`]
  29. Pending(BumpBox<'a, dyn Future<Output = Element<'a>> + 'a>),
  30. }
  31. impl<'a> Default for RenderReturn<'a> {
  32. fn default() -> Self {
  33. RenderReturn::Aborted(VPlaceholder::default())
  34. }
  35. }
  36. /// A reference to a template along with any context needed to hydrate it
  37. ///
  38. /// The dynamic parts of the template are stored separately from the static parts. This allows faster diffing by skipping
  39. /// static parts of the template.
  40. #[derive(Debug, Clone)]
  41. pub struct VNode<'a> {
  42. /// The key given to the root of this template.
  43. ///
  44. /// In fragments, this is the key of the first child. In other cases, it is the key of the root.
  45. pub key: Option<&'a str>,
  46. /// When rendered, this template will be linked to its parent manually
  47. pub parent: Option<ElementId>,
  48. /// The static nodes and static descriptor of the template
  49. pub template: Cell<Template<'static>>,
  50. /// The IDs for the roots of this template - to be used when moving the template around and removing it from
  51. /// the actual Dom
  52. pub root_ids: BoxedCellSlice,
  53. /// The dynamic parts of the template
  54. pub dynamic_nodes: &'a [DynamicNode<'a>],
  55. /// The dynamic parts of the template
  56. pub dynamic_attrs: &'a [Attribute<'a>],
  57. }
  58. // Saftey: There is no way to get references to the internal data of this struct so no refrences will be invalidated by mutating the data with a immutable reference (The same principle behind Cell)
  59. #[derive(Debug, Default)]
  60. pub struct BoxedCellSlice(UnsafeCell<Option<Box<[ElementId]>>>);
  61. impl Clone for BoxedCellSlice {
  62. fn clone(&self) -> Self {
  63. Self(UnsafeCell::new(unsafe { (*self.0.get()).clone() }))
  64. }
  65. }
  66. impl BoxedCellSlice {
  67. pub fn last(&self) -> Option<ElementId> {
  68. unsafe {
  69. (*self.0.get())
  70. .as_ref()
  71. .and_then(|inner| inner.as_ref().last().copied())
  72. }
  73. }
  74. pub fn get(&self, idx: usize) -> Option<ElementId> {
  75. unsafe {
  76. (*self.0.get())
  77. .as_ref()
  78. .and_then(|inner| inner.as_ref().get(idx).copied())
  79. }
  80. }
  81. pub unsafe fn get_unchecked(&self, idx: usize) -> Option<ElementId> {
  82. (*self.0.get())
  83. .as_ref()
  84. .and_then(|inner| inner.as_ref().get(idx).copied())
  85. }
  86. pub fn set(&self, idx: usize, new: ElementId) {
  87. unsafe {
  88. if let Some(inner) = &mut *self.0.get() {
  89. inner[idx] = new;
  90. }
  91. }
  92. }
  93. pub fn intialize(&self, contents: Box<[ElementId]>) {
  94. unsafe {
  95. *self.0.get() = Some(contents);
  96. }
  97. }
  98. pub fn transfer(&self, other: &Self) {
  99. unsafe {
  100. *self.0.get() = (*other.0.get()).clone();
  101. }
  102. }
  103. pub fn take_from(&self, other: &Self) {
  104. unsafe {
  105. *self.0.get() = (*other.0.get()).take();
  106. }
  107. }
  108. pub fn len(&self) -> usize {
  109. unsafe {
  110. (*self.0.get())
  111. .as_ref()
  112. .map(|inner| inner.len())
  113. .unwrap_or(0)
  114. }
  115. }
  116. }
  117. impl<'a> IntoIterator for &'a BoxedCellSlice {
  118. type Item = ElementId;
  119. type IntoIter = BoxedCellSliceIter<'a>;
  120. fn into_iter(self) -> Self::IntoIter {
  121. BoxedCellSliceIter {
  122. index: 0,
  123. borrow: self,
  124. }
  125. }
  126. }
  127. pub struct BoxedCellSliceIter<'a> {
  128. index: usize,
  129. borrow: &'a BoxedCellSlice,
  130. }
  131. impl Iterator for BoxedCellSliceIter<'_> {
  132. type Item = ElementId;
  133. fn next(&mut self) -> Option<Self::Item> {
  134. let result = self.borrow.get(self.index);
  135. if result.is_some() {
  136. self.index += 1;
  137. }
  138. result
  139. }
  140. }
  141. impl<'a> VNode<'a> {
  142. /// Create a template with no nodes that will be skipped over during diffing
  143. pub fn empty() -> Element<'a> {
  144. Some(VNode {
  145. key: None,
  146. parent: None,
  147. root_ids: BoxedCellSlice::default(),
  148. dynamic_nodes: &[],
  149. dynamic_attrs: &[],
  150. template: Cell::new(Template {
  151. name: "dioxus-empty",
  152. roots: &[],
  153. node_paths: &[],
  154. attr_paths: &[],
  155. }),
  156. })
  157. }
  158. /// Load a dynamic root at the given index
  159. ///
  160. /// Returns [`None`] if the root is actually a static node (Element/Text)
  161. pub fn dynamic_root(&self, idx: usize) -> Option<&'a DynamicNode<'a>> {
  162. match &self.template.get().roots[idx] {
  163. TemplateNode::Element { .. } | TemplateNode::Text { text: _ } => None,
  164. TemplateNode::Dynamic { id } | TemplateNode::DynamicText { id } => {
  165. Some(&self.dynamic_nodes[*id])
  166. }
  167. }
  168. }
  169. pub(crate) fn clear_listeners(&self) {
  170. for attr in self.dynamic_attrs {
  171. if let AttributeValue::Listener(l) = &attr.value {
  172. l.borrow_mut().take();
  173. }
  174. }
  175. }
  176. }
  177. /// A static layout of a UI tree that describes a set of dynamic and static nodes.
  178. ///
  179. /// This is the core innovation in Dioxus. Most UIs are made of static nodes, yet participate in diffing like any
  180. /// dynamic node. This struct can be created at compile time. It promises that its name is unique, allow Dioxus to use
  181. /// its static description of the UI to skip immediately to the dynamic nodes during diffing.
  182. ///
  183. /// For this to work properly, the [`Template::name`] *must* be unique across your entire project. This can be done via variety of
  184. /// ways, with the suggested approach being the unique code location (file, line, col, etc).
  185. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  186. #[derive(Debug, Clone, Copy, PartialEq, Hash, Eq, PartialOrd, Ord)]
  187. pub struct Template<'a> {
  188. /// The name of the template. This must be unique across your entire program for template diffing to work properly
  189. ///
  190. /// If two templates have the same name, it's likely that Dioxus will panic when diffing.
  191. #[cfg_attr(
  192. feature = "serialize",
  193. serde(deserialize_with = "deserialize_string_leaky")
  194. )]
  195. pub name: &'a str,
  196. /// The list of template nodes that make up the template
  197. ///
  198. /// Unlike react, calls to `rsx!` can have multiple roots. This list supports that paradigm.
  199. #[cfg_attr(feature = "serialize", serde(deserialize_with = "deserialize_leaky"))]
  200. pub roots: &'a [TemplateNode<'a>],
  201. /// The paths of each node relative to the root of the template.
  202. ///
  203. /// These will be one segment shorter than the path sent to the renderer since those paths are relative to the
  204. /// topmost element, not the `roots` field.
  205. #[cfg_attr(
  206. feature = "serialize",
  207. serde(deserialize_with = "deserialize_bytes_leaky")
  208. )]
  209. pub node_paths: &'a [&'a [u8]],
  210. /// The paths of each dynamic attribute relative to the root of the template
  211. ///
  212. /// These will be one segment shorter than the path sent to the renderer since those paths are relative to the
  213. /// topmost element, not the `roots` field.
  214. #[cfg_attr(
  215. feature = "serialize",
  216. serde(deserialize_with = "deserialize_bytes_leaky")
  217. )]
  218. pub attr_paths: &'a [&'a [u8]],
  219. }
  220. #[cfg(feature = "serialize")]
  221. fn deserialize_string_leaky<'a, 'de, D>(deserializer: D) -> Result<&'a str, D::Error>
  222. where
  223. D: serde::Deserializer<'de>,
  224. {
  225. use serde::Deserialize;
  226. let deserialized = String::deserialize(deserializer)?;
  227. Ok(&*Box::leak(deserialized.into_boxed_str()))
  228. }
  229. #[cfg(feature = "serialize")]
  230. fn deserialize_bytes_leaky<'a, 'de, D>(deserializer: D) -> Result<&'a [&'a [u8]], D::Error>
  231. where
  232. D: serde::Deserializer<'de>,
  233. {
  234. use serde::Deserialize;
  235. let deserialized = Vec::<Vec<u8>>::deserialize(deserializer)?;
  236. let deserialized = deserialized
  237. .into_iter()
  238. .map(|v| &*Box::leak(v.into_boxed_slice()))
  239. .collect::<Vec<_>>();
  240. Ok(&*Box::leak(deserialized.into_boxed_slice()))
  241. }
  242. #[cfg(feature = "serialize")]
  243. fn deserialize_leaky<'a, 'de, T: serde::Deserialize<'de>, D>(
  244. deserializer: D,
  245. ) -> Result<&'a [T], D::Error>
  246. where
  247. T: serde::Deserialize<'de>,
  248. D: serde::Deserializer<'de>,
  249. {
  250. use serde::Deserialize;
  251. let deserialized = Box::<[T]>::deserialize(deserializer)?;
  252. Ok(&*Box::leak(deserialized))
  253. }
  254. impl<'a> Template<'a> {
  255. /// Is this template worth caching at all, since it's completely runtime?
  256. ///
  257. /// There's no point in saving templates that are completely dynamic, since they'll be recreated every time anyway.
  258. pub fn is_completely_dynamic(&self) -> bool {
  259. use TemplateNode::*;
  260. self.roots
  261. .iter()
  262. .all(|root| matches!(root, Dynamic { .. } | DynamicText { .. }))
  263. }
  264. }
  265. /// A statically known node in a layout.
  266. ///
  267. /// This can be created at compile time, saving the VirtualDom time when diffing the tree
  268. #[derive(Debug, Clone, Copy, PartialEq, Hash, Eq, PartialOrd, Ord)]
  269. #[cfg_attr(
  270. feature = "serialize",
  271. derive(serde::Serialize, serde::Deserialize),
  272. serde(tag = "type")
  273. )]
  274. pub enum TemplateNode<'a> {
  275. /// An statically known element in the dom.
  276. ///
  277. /// In HTML this would be something like `<div id="123"> </div>`
  278. Element {
  279. /// The name of the element
  280. ///
  281. /// IE for a div, it would be the string "div"
  282. tag: &'a str,
  283. /// The namespace of the element
  284. ///
  285. /// In HTML, this would be a valid URI that defines a namespace for all elements below it
  286. /// SVG is an example of this namespace
  287. namespace: Option<&'a str>,
  288. /// A list of possibly dynamic attribues for this element
  289. ///
  290. /// An attribute on a DOM node, such as `id="my-thing"` or `href="https://example.com"`.
  291. #[cfg_attr(feature = "serialize", serde(deserialize_with = "deserialize_leaky"))]
  292. attrs: &'a [TemplateAttribute<'a>],
  293. /// A list of template nodes that define another set of template nodes
  294. #[cfg_attr(feature = "serialize", serde(deserialize_with = "deserialize_leaky"))]
  295. children: &'a [TemplateNode<'a>],
  296. },
  297. /// This template node is just a piece of static text
  298. Text {
  299. /// The actual text
  300. text: &'a str,
  301. },
  302. /// This template node is unknown, and needs to be created at runtime.
  303. Dynamic {
  304. /// The index of the dynamic node in the VNode's dynamic_nodes list
  305. id: usize,
  306. },
  307. /// This template node is known to be some text, but needs to be created at runtime
  308. ///
  309. /// This is separate from the pure Dynamic variant for various optimizations
  310. DynamicText {
  311. /// The index of the dynamic node in the VNode's dynamic_nodes list
  312. id: usize,
  313. },
  314. }
  315. /// A node created at runtime
  316. ///
  317. /// This node's index in the DynamicNode list on VNode should match its repsective `Dynamic` index
  318. #[derive(Debug)]
  319. pub enum DynamicNode<'a> {
  320. /// A component node
  321. ///
  322. /// Most of the time, Dioxus will actually know which component this is as compile time, but the props and
  323. /// assigned scope are dynamic.
  324. ///
  325. /// The actual VComponent can be dynamic between two VNodes, though, allowing implementations to swap
  326. /// the render function at runtime
  327. Component(VComponent<'a>),
  328. /// A text node
  329. Text(VText<'a>),
  330. /// A placeholder
  331. ///
  332. /// Used by suspense when a node isn't ready and by fragments that don't render anything
  333. ///
  334. /// In code, this is just an ElementId whose initial value is set to 0 upon creation
  335. Placeholder(VPlaceholder),
  336. /// A list of VNodes.
  337. ///
  338. /// Note that this is not a list of dynamic nodes. These must be VNodes and created through conditional rendering
  339. /// or iterators.
  340. Fragment(&'a [VNode<'a>]),
  341. }
  342. impl Default for DynamicNode<'_> {
  343. fn default() -> Self {
  344. Self::Placeholder(Default::default())
  345. }
  346. }
  347. /// An instance of a child component
  348. pub struct VComponent<'a> {
  349. /// The name of this component
  350. pub name: &'static str,
  351. /// Are the props valid for the 'static lifetime?
  352. ///
  353. /// Internally, this is used as a guarantee. Externally, this might be incorrect, so don't count on it.
  354. ///
  355. /// This flag is assumed by the [`crate::Properties`] trait which is unsafe to implement
  356. pub static_props: bool,
  357. /// The assigned Scope for this component
  358. pub scope: Cell<Option<ScopeId>>,
  359. /// The function pointer of the component, known at compile time
  360. ///
  361. /// It is possible that components get folded at comppile time, so these shouldn't be really used as a key
  362. pub render_fn: *const (),
  363. pub(crate) props: RefCell<Option<Box<dyn AnyProps<'a> + 'a>>>,
  364. }
  365. impl<'a> std::fmt::Debug for VComponent<'a> {
  366. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  367. f.debug_struct("VComponent")
  368. .field("name", &self.name)
  369. .field("static_props", &self.static_props)
  370. .field("scope", &self.scope)
  371. .finish()
  372. }
  373. }
  374. /// An instance of some text, mounted to the DOM
  375. #[derive(Debug)]
  376. pub struct VText<'a> {
  377. /// The actual text itself
  378. pub value: &'a str,
  379. /// The ID of this node in the real DOM
  380. pub id: Cell<Option<ElementId>>,
  381. }
  382. /// A placeholder node, used by suspense and fragments
  383. #[derive(Debug, Default)]
  384. pub struct VPlaceholder {
  385. /// The ID of this node in the real DOM
  386. pub id: Cell<Option<ElementId>>,
  387. }
  388. /// An attribute of the TemplateNode, created at compile time
  389. #[derive(Debug, PartialEq, Hash, Eq, PartialOrd, Ord)]
  390. #[cfg_attr(
  391. feature = "serialize",
  392. derive(serde::Serialize, serde::Deserialize),
  393. serde(tag = "type")
  394. )]
  395. pub enum TemplateAttribute<'a> {
  396. /// This attribute is entirely known at compile time, enabling
  397. Static {
  398. /// The name of this attribute.
  399. ///
  400. /// For example, the `href` attribute in `href="https://example.com"`, would have the name "href"
  401. name: &'a str,
  402. /// The value of this attribute, known at compile time
  403. ///
  404. /// Currently this only accepts &str, so values, even if they're known at compile time, are not known
  405. value: &'a str,
  406. /// The namespace of this attribute. Does not exist in the HTML spec
  407. namespace: Option<&'a str>,
  408. },
  409. /// The attribute in this position is actually determined dynamically at runtime
  410. ///
  411. /// This is the index into the dynamic_attributes field on the container VNode
  412. Dynamic {
  413. /// The index
  414. id: usize,
  415. },
  416. }
  417. /// An attribute on a DOM node, such as `id="my-thing"` or `href="https://example.com"`
  418. #[derive(Debug)]
  419. pub struct Attribute<'a> {
  420. /// The name of the attribute.
  421. pub name: &'a str,
  422. /// The value of the attribute
  423. pub value: AttributeValue<'a>,
  424. /// The namespace of the attribute.
  425. ///
  426. /// Doesn’t exist in the html spec. Used in Dioxus to denote “style” tags and other attribute groups.
  427. pub namespace: Option<&'static str>,
  428. /// The element in the DOM that this attribute belongs to
  429. pub mounted_element: Cell<ElementId>,
  430. /// An indication of we should always try and set the attribute. Used in controlled components to ensure changes are propagated
  431. pub volatile: bool,
  432. }
  433. /// Any of the built-in values that the Dioxus VirtualDom supports as dynamic attributes on elements
  434. ///
  435. /// These are built-in to be faster during the diffing process. To use a custom value, use the [`AttributeValue::Any`]
  436. /// variant.
  437. pub enum AttributeValue<'a> {
  438. /// Text attribute
  439. Text(&'a str),
  440. /// A float
  441. Float(f64),
  442. /// Signed integer
  443. Int(i64),
  444. /// Boolean
  445. Bool(bool),
  446. /// A listener, like "onclick"
  447. Listener(RefCell<Option<ListenerCb<'a>>>),
  448. /// An arbitrary value that implements PartialEq and is static
  449. Any(RefCell<Option<BumpBox<'a, dyn AnyValue>>>),
  450. /// A "none" value, resulting in the removal of an attribute from the dom
  451. None,
  452. }
  453. pub type ListenerCb<'a> = BumpBox<'a, dyn FnMut(Event<dyn Any>) + 'a>;
  454. /// Any of the built-in values that the Dioxus VirtualDom supports as dynamic attributes on elements that are borrowed
  455. ///
  456. /// These varients are used to communicate what the value of an attribute is that needs to be updated
  457. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  458. #[cfg_attr(feature = "serialize", serde(untagged))]
  459. pub enum BorrowedAttributeValue<'a> {
  460. /// Text attribute
  461. Text(&'a str),
  462. /// A float
  463. Float(f64),
  464. /// Signed integer
  465. Int(i64),
  466. /// Boolean
  467. Bool(bool),
  468. /// An arbitrary value that implements PartialEq and is static
  469. #[cfg_attr(
  470. feature = "serialize",
  471. serde(
  472. deserialize_with = "deserialize_any_value",
  473. serialize_with = "serialize_any_value"
  474. )
  475. )]
  476. Any(std::cell::Ref<'a, dyn AnyValue>),
  477. /// A "none" value, resulting in the removal of an attribute from the dom
  478. None,
  479. }
  480. impl<'a> From<&'a AttributeValue<'a>> for BorrowedAttributeValue<'a> {
  481. fn from(value: &'a AttributeValue<'a>) -> Self {
  482. match value {
  483. AttributeValue::Text(value) => BorrowedAttributeValue::Text(value),
  484. AttributeValue::Float(value) => BorrowedAttributeValue::Float(*value),
  485. AttributeValue::Int(value) => BorrowedAttributeValue::Int(*value),
  486. AttributeValue::Bool(value) => BorrowedAttributeValue::Bool(*value),
  487. AttributeValue::Listener(_) => {
  488. panic!("A listener cannot be turned into a borrowed value")
  489. }
  490. AttributeValue::Any(value) => {
  491. let value = value.borrow();
  492. BorrowedAttributeValue::Any(std::cell::Ref::map(value, |value| {
  493. &**value.as_ref().unwrap()
  494. }))
  495. }
  496. AttributeValue::None => BorrowedAttributeValue::None,
  497. }
  498. }
  499. }
  500. impl Debug for BorrowedAttributeValue<'_> {
  501. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  502. match self {
  503. Self::Text(arg0) => f.debug_tuple("Text").field(arg0).finish(),
  504. Self::Float(arg0) => f.debug_tuple("Float").field(arg0).finish(),
  505. Self::Int(arg0) => f.debug_tuple("Int").field(arg0).finish(),
  506. Self::Bool(arg0) => f.debug_tuple("Bool").field(arg0).finish(),
  507. Self::Any(_) => f.debug_tuple("Any").field(&"...").finish(),
  508. Self::None => write!(f, "None"),
  509. }
  510. }
  511. }
  512. impl PartialEq for BorrowedAttributeValue<'_> {
  513. fn eq(&self, other: &Self) -> bool {
  514. match (self, other) {
  515. (Self::Text(l0), Self::Text(r0)) => l0 == r0,
  516. (Self::Float(l0), Self::Float(r0)) => l0 == r0,
  517. (Self::Int(l0), Self::Int(r0)) => l0 == r0,
  518. (Self::Bool(l0), Self::Bool(r0)) => l0 == r0,
  519. (Self::Any(l0), Self::Any(r0)) => l0.any_cmp(&**r0),
  520. _ => core::mem::discriminant(self) == core::mem::discriminant(other),
  521. }
  522. }
  523. }
  524. #[cfg(feature = "serialize")]
  525. fn serialize_any_value<S>(_: &cell::Ref<'_, dyn AnyValue>, _: S) -> Result<S::Ok, S::Error>
  526. where
  527. S: serde::Serializer,
  528. {
  529. panic!("Any cannot be serialized")
  530. }
  531. #[cfg(feature = "serialize")]
  532. fn deserialize_any_value<'de, 'a, D>(_: D) -> Result<cell::Ref<'a, dyn AnyValue>, D::Error>
  533. where
  534. D: serde::Deserializer<'de>,
  535. {
  536. panic!("Any cannot be deserialized")
  537. }
  538. impl<'a> std::fmt::Debug for AttributeValue<'a> {
  539. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  540. match self {
  541. Self::Text(arg0) => f.debug_tuple("Text").field(arg0).finish(),
  542. Self::Float(arg0) => f.debug_tuple("Float").field(arg0).finish(),
  543. Self::Int(arg0) => f.debug_tuple("Int").field(arg0).finish(),
  544. Self::Bool(arg0) => f.debug_tuple("Bool").field(arg0).finish(),
  545. Self::Listener(_) => f.debug_tuple("Listener").finish(),
  546. Self::Any(_) => f.debug_tuple("Any").finish(),
  547. Self::None => write!(f, "None"),
  548. }
  549. }
  550. }
  551. impl<'a> PartialEq for AttributeValue<'a> {
  552. fn eq(&self, other: &Self) -> bool {
  553. match (self, other) {
  554. (Self::Text(l0), Self::Text(r0)) => l0 == r0,
  555. (Self::Float(l0), Self::Float(r0)) => l0 == r0,
  556. (Self::Int(l0), Self::Int(r0)) => l0 == r0,
  557. (Self::Bool(l0), Self::Bool(r0)) => l0 == r0,
  558. (Self::Listener(_), Self::Listener(_)) => true,
  559. (Self::Any(l0), Self::Any(r0)) => {
  560. let l0 = l0.borrow();
  561. let r0 = r0.borrow();
  562. l0.as_ref().unwrap().any_cmp(&**r0.as_ref().unwrap())
  563. }
  564. _ => false,
  565. }
  566. }
  567. }
  568. #[doc(hidden)]
  569. pub trait AnyValue: 'static {
  570. fn any_cmp(&self, other: &dyn AnyValue) -> bool;
  571. fn as_any(&self) -> &dyn Any;
  572. fn type_id(&self) -> TypeId {
  573. self.as_any().type_id()
  574. }
  575. }
  576. impl<T: Any + PartialEq + 'static> AnyValue for T {
  577. fn any_cmp(&self, other: &dyn AnyValue) -> bool {
  578. if let Some(other) = other.as_any().downcast_ref() {
  579. self == other
  580. } else {
  581. false
  582. }
  583. }
  584. fn as_any(&self) -> &dyn Any {
  585. self
  586. }
  587. }
  588. #[doc(hidden)]
  589. pub trait ComponentReturn<'a, A = ()> {
  590. fn into_return(self, cx: &'a ScopeState) -> RenderReturn<'a>;
  591. }
  592. impl<'a> ComponentReturn<'a> for Element<'a> {
  593. fn into_return(self, _cx: &ScopeState) -> RenderReturn<'a> {
  594. match self {
  595. Some(node) => RenderReturn::Ready(node),
  596. None => RenderReturn::default(),
  597. }
  598. }
  599. }
  600. #[doc(hidden)]
  601. pub struct AsyncMarker;
  602. impl<'a, F> ComponentReturn<'a, AsyncMarker> for F
  603. where
  604. F: Future<Output = Element<'a>> + 'a,
  605. {
  606. fn into_return(self, cx: &'a ScopeState) -> RenderReturn<'a> {
  607. let f: &mut dyn Future<Output = Element<'a>> = cx.bump().alloc(self);
  608. RenderReturn::Pending(unsafe { BumpBox::from_raw(f) })
  609. }
  610. }
  611. impl<'a> RenderReturn<'a> {
  612. pub(crate) unsafe fn extend_lifetime_ref<'c>(&self) -> &'c RenderReturn<'c> {
  613. unsafe { std::mem::transmute(self) }
  614. }
  615. pub(crate) unsafe fn extend_lifetime<'c>(self) -> RenderReturn<'c> {
  616. unsafe { std::mem::transmute(self) }
  617. }
  618. }
  619. /// A trait that allows various items to be converted into a dynamic node for the rsx macro
  620. pub trait IntoDynNode<'a, A = ()> {
  621. /// Consume this item along with a scopestate and produce a DynamicNode
  622. ///
  623. /// You can use the bump alloactor of the scopestate to creat the dynamic node
  624. fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a>;
  625. }
  626. impl<'a> IntoDynNode<'a> for () {
  627. fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
  628. DynamicNode::default()
  629. }
  630. }
  631. impl<'a> IntoDynNode<'a> for VNode<'a> {
  632. fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
  633. DynamicNode::Fragment(_cx.bump().alloc([self]))
  634. }
  635. }
  636. impl<'a> IntoDynNode<'a> for DynamicNode<'a> {
  637. fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
  638. self
  639. }
  640. }
  641. impl<'a, T: IntoDynNode<'a>> IntoDynNode<'a> for Option<T> {
  642. fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
  643. match self {
  644. Some(val) => val.into_vnode(_cx),
  645. None => DynamicNode::default(),
  646. }
  647. }
  648. }
  649. impl<'a> IntoDynNode<'a> for &Element<'a> {
  650. fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
  651. match self.as_ref() {
  652. Some(val) => val.clone().into_vnode(_cx),
  653. _ => DynamicNode::default(),
  654. }
  655. }
  656. }
  657. impl<'a, 'b> IntoDynNode<'a> for LazyNodes<'a, 'b> {
  658. fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
  659. DynamicNode::Fragment(cx.bump().alloc([self.call(cx)]))
  660. }
  661. }
  662. impl<'a> IntoDynNode<'_> for &'a str {
  663. fn into_vnode(self, cx: &ScopeState) -> DynamicNode {
  664. cx.text_node(format_args!("{}", self))
  665. }
  666. }
  667. impl IntoDynNode<'_> for String {
  668. fn into_vnode(self, cx: &ScopeState) -> DynamicNode {
  669. cx.text_node(format_args!("{}", self))
  670. }
  671. }
  672. impl<'b> IntoDynNode<'b> for Arguments<'_> {
  673. fn into_vnode(self, cx: &'b ScopeState) -> DynamicNode<'b> {
  674. cx.text_node(self)
  675. }
  676. }
  677. impl<'a> IntoDynNode<'a> for &'a VNode<'a> {
  678. fn into_vnode(self, _cx: &'a ScopeState) -> DynamicNode<'a> {
  679. DynamicNode::Fragment(_cx.bump().alloc([VNode {
  680. parent: self.parent,
  681. template: self.template.clone(),
  682. root_ids: self.root_ids.clone(),
  683. key: self.key,
  684. dynamic_nodes: self.dynamic_nodes,
  685. dynamic_attrs: self.dynamic_attrs,
  686. }]))
  687. }
  688. }
  689. pub trait IntoTemplate<'a> {
  690. fn into_template(self, _cx: &'a ScopeState) -> VNode<'a>;
  691. }
  692. impl<'a> IntoTemplate<'a> for VNode<'a> {
  693. fn into_template(self, _cx: &'a ScopeState) -> VNode<'a> {
  694. self
  695. }
  696. }
  697. impl<'a> IntoTemplate<'a> for Element<'a> {
  698. fn into_template(self, _cx: &'a ScopeState) -> VNode<'a> {
  699. match self {
  700. Some(val) => val.into_template(_cx),
  701. _ => VNode::empty().unwrap(),
  702. }
  703. }
  704. }
  705. impl<'a, 'b> IntoTemplate<'a> for LazyNodes<'a, 'b> {
  706. fn into_template(self, cx: &'a ScopeState) -> VNode<'a> {
  707. self.call(cx)
  708. }
  709. }
  710. // Note that we're using the E as a generic but this is never crafted anyways.
  711. #[doc(hidden)]
  712. pub struct FromNodeIterator;
  713. impl<'a, T, I> IntoDynNode<'a, FromNodeIterator> for T
  714. where
  715. T: Iterator<Item = I>,
  716. I: IntoTemplate<'a>,
  717. {
  718. fn into_vnode(self, cx: &'a ScopeState) -> DynamicNode<'a> {
  719. let mut nodes = bumpalo::collections::Vec::new_in(cx.bump());
  720. nodes.extend(self.into_iter().map(|node| node.into_template(cx)));
  721. match nodes.into_bump_slice() {
  722. children if children.is_empty() => DynamicNode::default(),
  723. children => DynamicNode::Fragment(children),
  724. }
  725. }
  726. }
  727. /// A value that can be converted into an attribute value
  728. pub trait IntoAttributeValue<'a> {
  729. /// Convert into an attribute value
  730. fn into_value(self, bump: &'a Bump) -> AttributeValue<'a>;
  731. }
  732. impl<'a> IntoAttributeValue<'a> for AttributeValue<'a> {
  733. fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
  734. self
  735. }
  736. }
  737. impl<'a> IntoAttributeValue<'a> for &'a str {
  738. fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
  739. AttributeValue::Text(self)
  740. }
  741. }
  742. impl<'a> IntoAttributeValue<'a> for f64 {
  743. fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
  744. AttributeValue::Float(self)
  745. }
  746. }
  747. impl<'a> IntoAttributeValue<'a> for i64 {
  748. fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
  749. AttributeValue::Int(self)
  750. }
  751. }
  752. impl<'a> IntoAttributeValue<'a> for bool {
  753. fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
  754. AttributeValue::Bool(self)
  755. }
  756. }
  757. impl<'a> IntoAttributeValue<'a> for Arguments<'_> {
  758. fn into_value(self, bump: &'a Bump) -> AttributeValue<'a> {
  759. use bumpalo::core_alloc::fmt::Write;
  760. let mut str_buf = bumpalo::collections::String::new_in(bump);
  761. str_buf.write_fmt(self).unwrap();
  762. AttributeValue::Text(str_buf.into_bump_str())
  763. }
  764. }
  765. impl<'a> IntoAttributeValue<'a> for BumpBox<'a, dyn AnyValue> {
  766. fn into_value(self, _: &'a Bump) -> AttributeValue<'a> {
  767. AttributeValue::Any(RefCell::new(Some(self)))
  768. }
  769. }