1use std::borrow::Cow;
21
22use crate::cmd::{Cmd, Commands};
23use crate::html::{Href, SafeHtml};
24
25#[derive(Clone, Debug, Default)]
27pub enum Node {
28 #[default]
30 Empty,
31 Text(Cow<'static, str>),
33 Int(i64),
35 Raw(SafeHtml),
37 Static(&'static str),
39 Element(Element),
41 Fragment(Vec<Node>),
43}
44
45impl Drop for Node {
49 fn drop(&mut self) {
50 let kids = match self {
51 Self::Element(element) => &mut element.children,
52 Self::Fragment(nodes) => nodes,
53 _ => return,
54 };
55 if kids.iter().all(Self::is_leaf) {
56 return;
57 }
58 let mut stack = std::mem::take(kids);
59 while let Some(mut node) = stack.pop() {
60 match &mut node {
61 Self::Element(element) => stack.append(&mut element.children),
62 Self::Fragment(nodes) => stack.append(nodes),
63 _ => {}
64 }
65 }
66 }
67}
68
69impl Node {
70 fn is_leaf(&self) -> bool {
72 match self {
73 Self::Element(element) => element.children.is_empty(),
74 Self::Fragment(nodes) => nodes.is_empty(),
75 _ => true,
76 }
77 }
78
79 pub(crate) fn into_element(mut self) -> Option<Element> {
81 match &mut self {
82 Self::Element(element) => Some(std::mem::replace(element, el("div"))),
83 _ => None,
84 }
85 }
86
87 pub fn text(text: impl Into<Cow<'static, str>>) -> Self {
89 Self::Text(text.into())
90 }
91
92 pub fn list(items: impl IntoNodes) -> Self {
94 let mut nodes = Vec::new();
95 items.push_into(&mut nodes);
96 Self::Fragment(nodes)
97 }
98
99 pub fn text_content(&self) -> String {
101 let mut out = String::new();
102 self.collect_text(&mut out);
103 out
104 }
105
106 fn collect_text(&self, out: &mut String) {
107 match self {
108 Self::Empty | Self::Static(_) => {}
109 Self::Raw(html) => {
110 let mut inside = false;
112 let mut text = String::new();
113 for c in html.as_str().chars() {
114 match c {
115 '<' => inside = true,
116 '>' => inside = false,
117 _ if !inside => text.push(c),
118 _ => {}
119 }
120 }
121 out.push_str(
122 &text
123 .replace("<", "<")
124 .replace(">", ">")
125 .replace(""", "\"")
126 .replace("'", "'")
127 .replace("&", "&"),
128 );
129 }
130 Self::Text(text) => out.push_str(text),
131 Self::Int(value) => out.push_str(&value.to_string()),
132 Self::Element(element) => {
133 for child in &element.children {
134 child.collect_text(out);
135 }
136 }
137 Self::Fragment(nodes) => {
138 for node in nodes {
139 node.collect_text(out);
140 }
141 }
142 }
143 }
144}
145
146#[derive(Clone, Debug, PartialEq, Eq)]
148pub enum AttrValue {
149 Flag,
151 Static(&'static str),
153 Text(Box<str>),
155 Int(i64),
157}
158
159impl AttrValue {
160 pub fn as_text(&self) -> Option<Cow<'_, str>> {
162 match self {
163 Self::Flag => None,
164 Self::Static(text) => Some(Cow::Borrowed(text)),
165 Self::Text(text) => Some(Cow::Borrowed(text)),
166 Self::Int(value) => Some(Cow::Owned(value.to_string())),
167 }
168 }
169}
170
171impl From<&'static str> for AttrValue {
172 fn from(text: &'static str) -> Self {
173 Self::Static(text)
174 }
175}
176
177impl From<String> for AttrValue {
178 fn from(text: String) -> Self {
179 Self::Text(text.into_boxed_str())
180 }
181}
182
183impl From<Cow<'static, str>> for AttrValue {
184 fn from(text: Cow<'static, str>) -> Self {
185 match text {
186 Cow::Borrowed(text) => Self::Static(text),
187 Cow::Owned(text) => Self::from(text),
188 }
189 }
190}
191
192impl From<i64> for AttrValue {
193 fn from(value: i64) -> Self {
194 Self::Int(value)
195 }
196}
197
198impl From<u32> for AttrValue {
199 fn from(value: u32) -> Self {
200 Self::Int(i64::from(value))
201 }
202}
203
204impl From<Href> for AttrValue {
205 fn from(href: Href) -> Self {
206 Self::Text(href.into_inner())
207 }
208}
209
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
213pub struct Uses(pub(crate) u32);
214
215impl Uses {
216 pub const NONE: Self = Self(0);
218 pub const CORE: Self = Self(1);
220 pub const SIDEBAR: Self = Self(1 << 1);
222 pub const OVERLAY: Self = Self(1 << 2);
224 pub const TABLE: Self = Self(1 << 3);
226 pub const SELECT: Self = Self(1 << 4);
228 pub const LIVE: Self = Self(1 << 6);
231 pub const DATES: Self = Self(1 << 7);
233 pub const DATE_TEXT: Self = Self(1 << 26);
236 pub const TIME: Self = Self(1 << 25);
238 pub const MENUS: Self = Self(1 << 5);
241 pub const PHONE: Self = Self(1 << 8);
244 pub const THEME_BUILDER: Self = Self(1 << 9);
247 pub const CHARTS: Self = Self(1 << 11);
251 pub const SLIDER: Self = Self(1 << 12);
254 pub const TREE: Self = Self(1 << 13);
257 pub const TOOLBAR: Self = Self(1 << 14);
260 pub const SORTABLE: Self = Self(1 << 15);
263 pub const SPLIT: Self = Self(1 << 16);
266 pub const KEYS: Self = Self(1 << 17);
269 pub const LAZY: Self = Self(1 << 18);
272 pub const MARKDOWN: Self = Self(1 << 19);
275 pub const UPLOAD: Self = Self(1 << 20);
278 pub const OTP: Self = Self(1 << 21);
281 pub const CAROUSEL: Self = Self(1 << 22);
284 pub const MENUBAR: Self = Self(1 << 23);
287 pub const ISLAND: Self = Self(1 << 10);
290 pub const PARTS: Self = Self(1 << 28);
294 pub const PARTS_STYLES: Self = Self(1 << 29);
298 pub const GENUI: Self = Self(1 << 24);
301
302 #[must_use]
304 pub const fn with(self, other: Self) -> Self {
305 Self(self.0 | other.0)
306 }
307
308 pub const fn has(self, other: Self) -> bool {
310 self.0 & other.0 == other.0
311 }
312
313 pub const fn meets(self, other: Self) -> bool {
315 self.0 & other.0 != 0
316 }
317
318 pub const fn is_none(self) -> bool {
320 self.0 == 0
321 }
322}
323
324pub(crate) fn valid_hotkey(key: &str) -> bool {
327 let mut chars = key.chars();
328 matches!((chars.next(), chars.next()), (Some(c), None) if !c.is_whitespace() && !c.is_control())
329}
330
331#[derive(Clone, Debug, PartialEq, Eq)]
333pub struct Attr {
334 pub name: &'static str,
336 pub value: AttrValue,
338}
339
340#[derive(Clone, Debug)]
342pub struct Element {
343 pub(crate) tag: &'static str,
344 pub(crate) attrs: Vec<Attr>,
345 pub(crate) children: Vec<Node>,
346 pub(crate) uses: Uses,
347}
348
349fn is_refused_tag(tag: &str) -> bool {
352 [
353 "script", "style", "link", "meta", "base", "iframe", "object", "embed",
354 ]
355 .iter()
356 .any(|refused| refused.eq_ignore_ascii_case(tag))
357}
358
359#[inline]
361pub fn el(tag: &'static str) -> Element {
362 let tag = if is_refused_tag(tag) {
363 debug_assert!(false, "`<{tag}>` is not allowed in a page's tree");
364 "div"
365 } else {
366 tag
367 };
368 Element {
369 tag,
370 attrs: Vec::new(),
371 children: Vec::new(),
372 uses: Uses::NONE,
373 }
374}
375
376fn is_url_attr(name: &str) -> bool {
378 [
379 "href",
380 "src",
381 "action",
382 "formaction",
383 "poster",
384 "cite",
385 "ping",
386 "data",
387 "background",
388 "xlink:href",
389 ]
390 .iter()
391 .any(|url| url.eq_ignore_ascii_case(name))
392}
393
394fn is_refused_attr(name: &str) -> bool {
397 name.eq_ignore_ascii_case("style")
398 || name.eq_ignore_ascii_case("srcdoc")
399 || name
400 .as_bytes()
401 .get(..2)
402 .is_some_and(|start| start.eq_ignore_ascii_case(b"on"))
403}
404
405impl Element {
406 pub fn tag(&self) -> &'static str {
408 self.tag
409 }
410
411 pub fn attrs(&self) -> &[Attr] {
413 &self.attrs
414 }
415
416 pub fn child_nodes(&self) -> &[Node] {
418 &self.children
419 }
420
421 pub fn get(&self, name: &str) -> Option<&AttrValue> {
423 self.attrs
424 .iter()
425 .find(|attr| attr.name == name)
426 .map(|attr| &attr.value)
427 }
428
429 #[inline]
432 #[must_use]
433 pub fn attr(mut self, name: &'static str, value: impl Into<AttrValue>) -> Self {
434 if is_refused_attr(name) {
435 debug_assert!(
436 false,
437 "`{name}` is not allowed under the content security policy"
438 );
439 return self;
440 }
441 let mut value = value.into();
442 if is_url_attr(name)
443 && let Some(text) = value.as_text()
444 {
445 value = Href::from(text.as_ref()).into();
446 }
447 self.attrs.push(Attr { name, value });
448 self
449 }
450
451 #[inline]
453 #[must_use]
454 pub fn attr_opt(self, name: &'static str, value: Option<impl Into<AttrValue>>) -> Self {
455 match value {
456 Some(value) => self.attr(name, value),
457 None => self,
458 }
459 }
460
461 #[inline]
463 #[must_use]
464 pub fn flag(mut self, name: &'static str, on: bool) -> Self {
465 if on && !is_refused_attr(name) {
466 self.attrs.push(Attr {
467 name,
468 value: AttrValue::Flag,
469 });
470 }
471 self
472 }
473
474 #[inline]
476 #[must_use]
477 pub fn slot(self, slot: &'static str) -> Self {
478 self.attr("data-slot", slot)
479 }
480
481 #[inline]
483 #[must_use]
484 pub fn id(self, id: impl Into<AttrValue>) -> Self {
485 self.attr("id", id)
486 }
487
488 #[inline]
490 #[must_use]
491 pub fn href(mut self, href: impl Into<Href>) -> Self {
492 self.attrs.push(Attr {
493 name: "href",
494 value: href.into().into(),
495 });
496 self
497 }
498
499 #[inline]
502 #[must_use]
503 pub fn prefetch(self) -> Self {
504 self.flag("data-ui-prefetch", true)
505 }
506
507 #[inline]
517 #[must_use]
518 pub fn prefetch_eager(self) -> Self {
519 self.attr("data-ui-prefetch", "eager")
520 }
521
522 #[must_use]
525 pub fn on_click(self, commands: impl Into<Commands>) -> Self {
526 self.on(crate::cmd::Trigger::Click, commands)
527 }
528
529 #[must_use]
531 pub fn on(mut self, trigger: crate::cmd::Trigger, commands: impl Into<Commands>) -> Self {
535 self.uses = self.uses.with(Uses::CORE);
536 let json = commands.into().to_json();
537 let name = trigger.attribute();
538 if let Some(attr) = self.attrs.iter_mut().find(|attr| attr.name == name) {
539 let old = attr
542 .value
543 .as_text()
544 .map(|text| text.into_owned())
545 .unwrap_or_default();
546 let merged = match (old.as_str(), json.as_str()) {
547 ("" | "[]", _) => json,
548 (_, "[]") => old,
549 (old, new) => format!("{},{}", &old[..old.len() - 1], &new[1..]),
550 };
551 attr.value = AttrValue::Text(merged.into_boxed_str());
552 return self;
553 }
554 self.attrs.push(Attr {
555 name,
556 value: AttrValue::Text(json.into_boxed_str()),
557 });
558 self
559 }
560
561 #[must_use]
563 pub fn on_click_one(self, command: Cmd) -> Self {
564 self.on_click(vec![command])
565 }
566
567 #[must_use]
572 pub fn fill_cell(self, column: &'static str) -> Self {
573 self.attr("data-ui-cell", column)
574 }
575
576 #[must_use]
580 pub fn settable(self) -> Self {
581 self.flag("data-ui-value", true)
582 }
583
584 #[must_use]
587 pub fn fill_key(self) -> Self {
588 self.flag("data-ui-row-key", true)
589 }
590
591 #[must_use]
610 pub fn hotkey(self, key: &str) -> Self {
611 if !valid_hotkey(key) {
612 return self;
613 }
614 self.attr("data-ui-hotkey", key.to_owned())
615 .attr("aria-keyshortcuts", key.to_owned())
616 .uses(Uses::KEYS)
617 }
618
619 #[must_use]
636 pub fn hotkey_within(self, key: &str, scope: &str) -> Self {
637 let scope_ok = !scope.is_empty()
638 && scope.len() <= 64
639 && scope
640 .chars()
641 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.'));
642 if !valid_hotkey(key) || !scope_ok {
643 return self;
644 }
645 self.hotkey(key)
646 .attr("data-ui-hotkey-scope", scope.to_owned())
647 }
648
649 #[inline]
651 #[must_use]
652 pub fn uses(mut self, uses: Uses) -> Self {
653 self.uses = self.uses.with(uses);
654 self
655 }
656
657 #[inline]
659 #[must_use]
660 pub fn child(mut self, child: impl IntoNodes) -> Self {
661 child.push_into(&mut self.children);
662 self
663 }
664
665 #[inline]
667 #[must_use]
668 pub fn children(self, children: impl IntoNodes) -> Self {
669 self.child(children)
670 }
671
672 #[inline]
674 #[must_use]
675 pub fn with_child_capacity(mut self, count: usize) -> Self {
676 self.children.reserve_exact(count);
677 self
678 }
679}
680
681impl From<Element> for Node {
682 #[inline]
683 fn from(element: Element) -> Self {
684 Self::Element(element)
685 }
686}
687
688impl From<&'static str> for Node {
689 #[inline]
690 fn from(text: &'static str) -> Self {
691 Self::Text(Cow::Borrowed(text))
692 }
693}
694
695impl From<String> for Node {
696 #[inline]
697 fn from(text: String) -> Self {
698 Self::Text(Cow::Owned(text))
699 }
700}
701
702impl From<Cow<'static, str>> for Node {
703 #[inline]
704 fn from(text: Cow<'static, str>) -> Self {
705 Self::Text(text)
706 }
707}
708
709impl From<i64> for Node {
710 #[inline]
711 fn from(value: i64) -> Self {
712 Self::Int(value)
713 }
714}
715
716impl From<SafeHtml> for Node {
717 fn from(html: SafeHtml) -> Self {
718 Self::Raw(html)
719 }
720}
721
722pub trait IntoNodes {
724 fn push_into(self, out: &mut Vec<Node>);
726}
727
728impl<T: Into<Node>> IntoNodes for T {
729 #[inline]
730 fn push_into(self, out: &mut Vec<Node>) {
731 out.push(self.into());
732 }
733}
734
735impl<T: IntoNodes> IntoNodes for Vec<T> {
736 #[inline]
737 fn push_into(self, out: &mut Vec<Node>) {
738 out.reserve(self.len());
739 for item in self {
740 item.push_into(out);
741 }
742 }
743}
744
745impl<T: IntoNodes, const N: usize> IntoNodes for [T; N] {
746 #[inline]
747 fn push_into(self, out: &mut Vec<Node>) {
748 out.reserve(N);
749 for item in self {
750 item.push_into(out);
751 }
752 }
753}
754
755impl<T: IntoNodes> IntoNodes for Option<T> {
756 #[inline]
757 fn push_into(self, out: &mut Vec<Node>) {
758 if let Some(item) = self {
759 item.push_into(out);
760 }
761 }
762}
763
764macro_rules! tuples {
765 ($($name:ident)+) => {
766 impl<$($name: IntoNodes),+> IntoNodes for ($($name,)+) {
767 #[inline]
768 #[allow(non_snake_case)]
769 fn push_into(self, out: &mut Vec<Node>) {
770 let ($($name,)+) = self;
771 $($name.push_into(out);)+
772 }
773 }
774 };
775}
776
777tuples!(A);
778tuples!(A B);
779tuples!(A B C);
780tuples!(A B C D);
781tuples!(A B C D E);
782tuples!(A B C D E F);
783tuples!(A B C D E F G);
784tuples!(A B C D E F G H);
785tuples!(A B C D E F G H I);
786tuples!(A B C D E F G H I J);
787tuples!(A B C D E F G H I J K);
788tuples!(A B C D E F G H I J K L);
789
790macro_rules! into_node {
792 ($($type:ty),+ $(,)?) => {
793 $(impl From<$type> for $crate::node::Node {
794 #[inline]
795 fn from(value: $type) -> Self {
796 value.into_node()
797 }
798 })+
799 };
800}
801pub(crate) use into_node;
802
803#[cfg(test)]
804mod tests {
805 use super::*;
806
807 #[test]
808 fn urls_in_attributes_are_checked() {
809 let element = el("a").attr("href", "javascript:alert(1)");
810 assert_eq!(element.get("href"), Some(&AttrValue::Text("#".into())));
811 let element = el("a").attr("href", "/ok".to_owned());
812 assert_eq!(element.get("href"), Some(&AttrValue::Text("/ok".into())));
813 }
814
815 #[test]
816 fn children_take_tuples_lists_and_options() {
817 let element =
818 el("div").children(("a", Some("b"), None::<&'static str>, vec!["c", "d"], 7_i64));
819 assert_eq!(element.child_nodes().len(), 5);
820 assert_eq!(Node::from(element).text_content(), "abcd7");
821 }
822
823 #[test]
824 fn commands_ask_for_the_core_runtime() {
825 assert!(el("div").uses.is_none());
826 let element = el("button").on_click_one(Cmd::toggle("menu"));
827 assert!(element.uses.has(Uses::CORE));
828 }
829
830 #[test]
831 fn a_hotkey_is_one_typed_character_and_loads_the_keys_module() {
832 for key in ["j", "K", "/", "?", "1", "é"] {
833 let element = el("a").hotkey(key);
834 assert_eq!(
835 element.get("data-ui-hotkey"),
836 Some(&AttrValue::Text(key.into()))
837 );
838 assert_eq!(
839 element.get("aria-keyshortcuts"),
840 Some(&AttrValue::Text(key.into()))
841 );
842 assert!(element.uses.has(Uses::KEYS));
843 }
844 for bad in ["", " ", "jk", "Enter", "\n", "\u{7}", "ctrl+k"] {
845 let element = el("a").hotkey(bad);
846 assert!(element.get("data-ui-hotkey").is_none(), "{bad:?}");
847 assert!(element.uses.is_none(), "{bad:?}");
848 }
849 }
850
851 #[test]
852 fn a_scoped_hotkey_names_its_scope_and_refuses_a_bad_one() {
853 let html = crate::render(&el("button").hotkey_within("e", "thread").into());
854 assert!(html.contains(r#"data-ui-hotkey="e""#), "{html}");
855 assert!(html.contains(r#"data-ui-hotkey-scope="thread""#), "{html}");
856 for bad in ["", "a b", "x\"y", &"z".repeat(65)] {
857 let html = crate::render(&el("button").hotkey_within("e", bad).into());
858 assert!(!html.contains("data-ui-hotkey"), "{bad}: {html}");
859 }
860 let html = crate::render(&el("button").hotkey_within("two", "thread").into());
861 assert!(!html.contains("data-ui-hotkey"), "{html}");
862 }
863
864 #[test]
865 fn the_new_modules_have_bits_of_their_own() {
866 let known = [
867 Uses::CORE,
868 Uses::SIDEBAR,
869 Uses::OVERLAY,
870 Uses::TABLE,
871 Uses::SELECT,
872 Uses::MENUS,
873 Uses::LIVE,
874 Uses::DATES,
875 Uses::PHONE,
876 Uses::THEME_BUILDER,
877 Uses::SLIDER,
878 Uses::TREE,
879 Uses::TOOLBAR,
880 Uses::SORTABLE,
881 ];
882 for module in [Uses::SPLIT, Uses::KEYS, Uses::LAZY] {
883 assert!(known.iter().all(|other| other.0 & module.0 == 0));
884 }
885 assert_eq!(Uses::SPLIT.0 & Uses::KEYS.0, 0);
886 assert_eq!((Uses::SPLIT.0 | Uses::KEYS.0) & Uses::LAZY.0, 0);
887 }
888
889 #[test]
890 fn the_markdown_upload_code_carousel_and_menu_bar_modules_have_bits_of_their_own() {
891 let older = [
892 Uses::CORE,
893 Uses::SIDEBAR,
894 Uses::OVERLAY,
895 Uses::TABLE,
896 Uses::SELECT,
897 Uses::MENUS,
898 Uses::LIVE,
899 Uses::DATES,
900 Uses::PHONE,
901 Uses::THEME_BUILDER,
902 Uses::SLIDER,
903 Uses::TREE,
904 Uses::TOOLBAR,
905 Uses::SORTABLE,
906 Uses::SPLIT,
907 Uses::KEYS,
908 Uses::LAZY,
909 ];
910 let newer = [
911 Uses::MARKDOWN,
912 Uses::UPLOAD,
913 Uses::OTP,
914 Uses::CAROUSEL,
915 Uses::MENUBAR,
916 Uses::PARTS,
917 Uses::PARTS_STYLES,
918 Uses::GENUI,
919 ];
920 for (at, module) in newer.iter().enumerate() {
921 assert_eq!(module.0.count_ones(), 1);
922 assert!(older.iter().all(|other| other.0 & module.0 == 0));
923 assert!(newer[at + 1..].iter().all(|other| other.0 & module.0 == 0));
924 }
925 }
926
927 #[test]
928 fn a_node_stays_small() {
929 assert!(
931 std::mem::size_of::<Node>() <= 72,
932 "{}",
933 std::mem::size_of::<Node>()
934 );
935 }
936}