1use std::borrow::Cow;
21
22use serde::Serialize;
23
24use crate::cmd::{Cmd, Commands};
25use crate::extension::UiExtension;
26use crate::html::{Href, LocalHref, SafeHtml};
27
28#[derive(Clone, Debug, Default)]
30pub enum Node {
31 #[default]
33 Empty,
34 Text(Cow<'static, str>),
36 Int(i64),
38 Raw(SafeHtml),
40 Static(&'static str),
42 Element(Element),
44 Fragment(Vec<Node>),
46}
47
48impl Drop for Node {
52 fn drop(&mut self) {
53 let kids = match self {
54 Self::Element(element) => &mut element.children,
55 Self::Fragment(nodes) => nodes,
56 _ => return,
57 };
58 if kids.iter().all(Self::is_leaf) {
59 return;
60 }
61 let mut stack = std::mem::take(kids);
62 while let Some(mut node) = stack.pop() {
63 match &mut node {
64 Self::Element(element) => stack.append(&mut element.children),
65 Self::Fragment(nodes) => stack.append(nodes),
66 _ => {}
67 }
68 }
69 }
70}
71
72impl Node {
73 fn is_leaf(&self) -> bool {
75 match self {
76 Self::Element(element) => element.children.is_empty(),
77 Self::Fragment(nodes) => nodes.is_empty(),
78 _ => true,
79 }
80 }
81
82 pub(crate) fn into_element(mut self) -> Option<Element> {
84 match &mut self {
85 Self::Element(element) => Some(std::mem::replace(element, el("div"))),
86 _ => None,
87 }
88 }
89
90 pub fn text(text: impl Into<Cow<'static, str>>) -> Self {
92 Self::Text(text.into())
93 }
94
95 pub fn list(items: impl IntoNodes) -> Self {
97 let mut nodes = Vec::new();
98 items.push_into(&mut nodes);
99 Self::Fragment(nodes)
100 }
101
102 pub fn text_content(&self) -> String {
104 let mut out = String::new();
105 self.collect_text(&mut out);
106 out
107 }
108
109 fn collect_text(&self, out: &mut String) {
110 match self {
111 Self::Empty | Self::Static(_) => {}
112 Self::Raw(html) => {
113 let mut inside = false;
115 let mut text = String::new();
116 for c in html.as_str().chars() {
117 match c {
118 '<' => inside = true,
119 '>' => inside = false,
120 _ if !inside => text.push(c),
121 _ => {}
122 }
123 }
124 out.push_str(
125 &text
126 .replace("<", "<")
127 .replace(">", ">")
128 .replace(""", "\"")
129 .replace("'", "'")
130 .replace("&", "&"),
131 );
132 }
133 Self::Text(text) => out.push_str(text),
134 Self::Int(value) => out.push_str(&value.to_string()),
135 Self::Element(element) => {
136 for child in &element.children {
137 child.collect_text(out);
138 }
139 }
140 Self::Fragment(nodes) => {
141 for node in nodes {
142 node.collect_text(out);
143 }
144 }
145 }
146 }
147}
148
149#[derive(Clone, Debug, PartialEq, Eq)]
151pub enum AttrValue {
152 Flag,
154 Static(&'static str),
156 Text(Box<str>),
158 Int(i64),
160}
161
162impl AttrValue {
163 pub fn as_text(&self) -> Option<Cow<'_, str>> {
165 match self {
166 Self::Flag => None,
167 Self::Static(text) => Some(Cow::Borrowed(text)),
168 Self::Text(text) => Some(Cow::Borrowed(text)),
169 Self::Int(value) => Some(Cow::Owned(value.to_string())),
170 }
171 }
172}
173
174impl From<&'static str> for AttrValue {
175 fn from(text: &'static str) -> Self {
176 Self::Static(text)
177 }
178}
179
180impl From<String> for AttrValue {
181 fn from(text: String) -> Self {
182 Self::Text(text.into_boxed_str())
183 }
184}
185
186impl From<Cow<'static, str>> for AttrValue {
187 fn from(text: Cow<'static, str>) -> Self {
188 match text {
189 Cow::Borrowed(text) => Self::Static(text),
190 Cow::Owned(text) => Self::from(text),
191 }
192 }
193}
194
195impl From<i64> for AttrValue {
196 fn from(value: i64) -> Self {
197 Self::Int(value)
198 }
199}
200
201impl From<u32> for AttrValue {
202 fn from(value: u32) -> Self {
203 Self::Int(i64::from(value))
204 }
205}
206
207impl From<Href> for AttrValue {
208 fn from(href: Href) -> Self {
209 Self::Text(href.into_inner())
210 }
211}
212
213#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
216pub struct Uses(pub(crate) u64);
217
218impl Uses {
219 pub const NONE: Self = Self(0);
221 pub const CORE: Self = Self(1);
223 pub const SIDEBAR: Self = Self(1 << 1);
225 pub const OVERLAY: Self = Self(1 << 2);
227 pub const TABLE: Self = Self(1 << 3);
229 pub const SELECT: Self = Self(1 << 4);
231 pub const LIVE: Self = Self(1 << 6);
234 pub const DATES: Self = Self(1 << 7);
236 pub const DATE_TEXT: Self = Self(1 << 26);
239 pub const TIME: Self = Self(1 << 25);
241 pub const MENUS: Self = Self(1 << 5);
244 pub const PHONE: Self = Self(1 << 8);
247 pub const THEME_BUILDER: Self = Self(1 << 9);
250 pub const CHARTS: Self = Self(1 << 11);
254 pub const SLIDER: Self = Self(1 << 12);
257 pub const TREE: Self = Self(1 << 13);
260 pub const TOOLBAR: Self = Self(1 << 14);
263 pub const SORTABLE: Self = Self(1 << 15);
266 pub const SPLIT: Self = Self(1 << 16);
269 pub const KEYS: Self = Self(1 << 17);
272 pub const LAZY: Self = Self(1 << 18);
275 pub const MARKDOWN: Self = Self(1 << 19);
278 pub const UPLOAD: Self = Self(1 << 20);
281 pub const OTP: Self = Self(1 << 21);
284 pub const CAROUSEL: Self = Self(1 << 22);
287 pub const MENUBAR: Self = Self(1 << 23);
290 pub const ISLAND: Self = Self(1 << 10);
293 pub const PARTS: Self = Self(1 << 28);
297 pub const PARTS_STYLES: Self = Self(1 << 29);
301 pub const GENUI: Self = Self(1 << 24);
304 pub const CHART_PAINT: Self = Self(1 << 32);
309 pub const COUNT_UP: Self = Self(1 << 33);
313 pub const CHART_RADIAL: Self = Self(1 << 34);
317 pub const CHART_LINEAR: Self = Self(1 << 35);
321 pub const CHART_GRIDS: Self = Self(1 << 36);
325 pub const APP_BLOCKS: Self = Self(1 << 37);
329 pub const MARKETING: Self = Self(1 << 40);
333 pub const SORTABLE_GRID: Self = Self(1 << 41);
337 pub const SORTABLE_GRID_STYLES: Self = Self(1 << 42);
340 pub const EXTENSIONS: Self = Self(1 << 43);
343 pub const EXTENSION_SHEETS: Self = Self(1 << 44);
345
346 #[must_use]
348 pub const fn with(self, other: Self) -> Self {
349 Self(self.0 | other.0)
350 }
351
352 pub const fn has(self, other: Self) -> bool {
354 self.0 & other.0 == other.0
355 }
356
357 pub const fn meets(self, other: Self) -> bool {
359 self.0 & other.0 != 0
360 }
361
362 pub const fn is_none(self) -> bool {
364 self.0 == 0
365 }
366
367 pub(crate) const fn extension_bits(self) -> Self {
369 Self(self.0 & (Self::EXTENSIONS.0 | Self::EXTENSION_SHEETS.0))
370 }
371
372 pub(crate) const fn without_extensions(self) -> Self {
374 Self(self.0 & !(Self::EXTENSIONS.0 | Self::EXTENSION_SHEETS.0))
375 }
376}
377
378pub(crate) fn valid_hotkey(key: &str) -> bool {
381 let mut chars = key.chars();
382 matches!((chars.next(), chars.next()), (Some(c), None) if !c.is_whitespace() && !c.is_control())
383}
384
385#[derive(Clone, Debug, PartialEq, Eq)]
387pub struct Attr {
388 pub name: &'static str,
390 pub value: AttrValue,
392}
393
394#[derive(Clone, Debug)]
396pub struct Element {
397 pub(crate) tag: &'static str,
398 pub(crate) attrs: Vec<Attr>,
399 pub(crate) children: Vec<Node>,
400 pub(crate) uses: Uses,
401}
402
403fn is_refused_tag(tag: &str) -> bool {
406 [
407 "script", "style", "link", "meta", "base", "iframe", "object", "embed",
408 ]
409 .iter()
410 .any(|refused| refused.eq_ignore_ascii_case(tag))
411}
412
413#[inline]
415pub fn el(tag: &'static str) -> Element {
416 let tag = if is_refused_tag(tag) {
417 debug_assert!(false, "`<{tag}>` is not allowed in a page's tree");
418 "div"
419 } else {
420 tag
421 };
422 Element {
423 tag,
424 attrs: Vec::new(),
425 children: Vec::new(),
426 uses: Uses::NONE,
427 }
428}
429
430fn is_url_attr(name: &str) -> bool {
432 [
433 "href",
434 "src",
435 "action",
436 "formaction",
437 "poster",
438 "cite",
439 "ping",
440 "data",
441 "background",
442 "xlink:href",
443 ]
444 .iter()
445 .any(|url| url.eq_ignore_ascii_case(name))
446}
447
448fn is_refused_attr(name: &str) -> bool {
451 name.eq_ignore_ascii_case("style")
452 || name.eq_ignore_ascii_case("srcdoc")
453 || name
454 .as_bytes()
455 .get(..2)
456 .is_some_and(|start| start.eq_ignore_ascii_case(b"on"))
457}
458
459fn has_encoded_slash(path: &str) -> bool {
461 path.as_bytes()
462 .windows(3)
463 .any(|window| window.eq_ignore_ascii_case(b"%2f") || window.eq_ignore_ascii_case(b"%5c"))
464}
465
466fn has_dot_segment(path: &str) -> bool {
468 path.split('/').any(|segment| {
469 if segment == "." || segment == ".." {
470 return true;
471 }
472 if !segment.contains('%') || segment.len() > 6 {
473 return false;
474 }
475 let bytes = segment.as_bytes();
476 let mut dots = 0_usize;
477 let mut i = 0;
478 while i < bytes.len() {
479 if bytes[i] == b'.' {
480 dots += 1;
481 i += 1;
482 } else if bytes
483 .get(i..i + 3)
484 .is_some_and(|esc| esc.eq_ignore_ascii_case(b"%2e"))
485 {
486 dots += 1;
487 i += 3;
488 } else {
489 return false;
490 }
491 }
492 dots == 1 || dots == 2
493 })
494}
495
496impl Element {
497 #[cfg_attr(not(feature = "native-preview"), allow(unused_variables, unused_mut))]
509 pub fn presented(mut self, how: crate::Presented) -> Self {
510 #[cfg(feature = "native-preview")]
511 self.say(|hints| hints.presented = Some(how));
512 self
513 }
514
515 #[cfg(feature = "native-preview")]
520 pub(crate) fn say(&mut self, set: impl FnOnce(&mut crate::hint::Hints)) {
521 let Some(request) = crate::native::scope::native() else {
522 return;
523 };
524 let held = self.children.iter().find_map(crate::hint::key_of);
525 let key = request.hint(held.unwrap_or(0), set);
526 if held.is_none()
527 && let Some(mark) = crate::hint::key_mark(key)
528 {
529 self.children.push(mark);
530 }
531 }
532
533 #[cfg(feature = "native-preview")]
535 pub(crate) fn said(&self) -> Option<crate::hint::Hints> {
536 let key = self.children.iter().find_map(crate::hint::key_of)?;
537 crate::native::scope::native()?.hinted(key)
538 }
539
540 pub fn tag(&self) -> &'static str {
542 self.tag
543 }
544
545 pub fn attrs(&self) -> &[Attr] {
547 &self.attrs
548 }
549
550 pub fn child_nodes(&self) -> &[Node] {
552 &self.children
553 }
554
555 pub fn get(&self, name: &str) -> Option<&AttrValue> {
557 self.attrs
558 .iter()
559 .find(|attr| attr.name == name)
560 .map(|attr| &attr.value)
561 }
562
563 #[inline]
566 #[must_use]
567 pub fn attr(mut self, name: &'static str, value: impl Into<AttrValue>) -> Self {
568 if is_refused_attr(name) {
569 debug_assert!(
570 false,
571 "`{name}` is not allowed under the content security policy"
572 );
573 return self;
574 }
575 let mut value = value.into();
576 if is_url_attr(name)
577 && let Some(text) = value.as_text()
578 {
579 value = Href::from(text.as_ref()).into();
580 }
581 self.attrs.push(Attr { name, value });
582 self
583 }
584
585 #[inline]
587 #[must_use]
588 pub fn attr_opt(self, name: &'static str, value: Option<impl Into<AttrValue>>) -> Self {
589 match value {
590 Some(value) => self.attr(name, value),
591 None => self,
592 }
593 }
594
595 #[inline]
597 #[must_use]
598 pub fn flag(mut self, name: &'static str, on: bool) -> Self {
599 if on && !is_refused_attr(name) {
600 self.attrs.push(Attr {
601 name,
602 value: AttrValue::Flag,
603 });
604 }
605 self
606 }
607
608 #[inline]
610 #[must_use]
611 pub fn slot(self, slot: &'static str) -> Self {
612 self.attr("data-slot", slot)
613 }
614
615 #[inline]
617 #[must_use]
618 pub fn id(self, id: impl Into<AttrValue>) -> Self {
619 self.attr("id", id)
620 }
621
622 #[inline]
624 #[must_use]
625 pub fn href(mut self, href: impl Into<Href>) -> Self {
626 self.attrs.push(Attr {
627 name: "href",
628 value: href.into().into(),
629 });
630 self
631 }
632
633 #[inline]
636 #[must_use]
637 pub fn prefetch(self) -> Self {
638 self.flag("data-ui-prefetch", true)
639 }
640
641 #[inline]
651 #[must_use]
652 pub fn prefetch_eager(self) -> Self {
653 self.attr("data-ui-prefetch", "eager")
654 }
655
656 #[must_use]
659 pub fn on_click(self, commands: impl Into<Commands>) -> Self {
660 self.on(crate::cmd::Trigger::Click, commands)
661 }
662
663 #[must_use]
665 pub fn on(mut self, trigger: crate::cmd::Trigger, commands: impl Into<Commands>) -> Self {
669 self.uses = self.uses.with(Uses::CORE);
670 let json = commands.into().to_json();
671 let name = trigger.attribute();
672 if let Some(attr) = self.attrs.iter_mut().find(|attr| attr.name == name) {
673 let old = attr
676 .value
677 .as_text()
678 .map(|text| text.into_owned())
679 .unwrap_or_default();
680 let merged = match (old.as_str(), json.as_str()) {
681 ("" | "[]", _) => json,
682 (_, "[]") => old,
683 (old, new) => format!("{},{}", &old[..old.len() - 1], &new[1..]),
684 };
685 attr.value = AttrValue::Text(merged.into_boxed_str());
686 return self;
687 }
688 self.attrs.push(Attr {
689 name,
690 value: AttrValue::Text(json.into_boxed_str()),
691 });
692 self
693 }
694
695 #[must_use]
697 pub fn on_click_one(self, command: Cmd) -> Self {
698 self.on_click(vec![command])
699 }
700
701 #[must_use]
706 pub fn fill_cell(self, column: &'static str) -> Self {
707 self.attr("data-ui-cell", column)
708 }
709
710 #[must_use]
714 pub fn settable(self) -> Self {
715 self.flag("data-ui-value", true)
716 }
717
718 #[must_use]
721 pub fn fill_key(self) -> Self {
722 self.flag("data-ui-row-key", true)
723 }
724
725 #[must_use]
744 pub fn hotkey(self, key: &str) -> Self {
745 if !valid_hotkey(key) {
746 return self;
747 }
748 self.attr("data-ui-hotkey", key.to_owned())
749 .attr("aria-keyshortcuts", key.to_owned())
750 .uses(Uses::KEYS)
751 }
752
753 #[must_use]
770 pub fn hotkey_within(self, key: &str, scope: &str) -> Self {
771 let scope_ok = !scope.is_empty()
772 && scope.len() <= 64
773 && scope
774 .chars()
775 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.'));
776 if !valid_hotkey(key) || !scope_ok {
777 return self;
778 }
779 self.hotkey(key)
780 .attr("data-ui-hotkey-scope", scope.to_owned())
781 }
782
783 #[inline]
785 #[must_use]
786 pub fn uses(mut self, uses: Uses) -> Self {
787 self.uses = self.uses.with(uses);
788 self
789 }
790
791 #[must_use]
809 pub fn extension(self, extension: &'static UiExtension) -> Self {
810 self.named_extension(extension, None)
811 }
812
813 #[must_use]
834 pub fn extension_with(self, extension: &'static UiExtension, props: &impl Serialize) -> Self {
835 let json = serde_json::to_string(props).unwrap_or_else(|_| "null".to_owned());
836 self.named_extension(extension, Some(json))
837 }
838
839 #[must_use]
854 pub fn extension_call(mut self, href: impl Into<LocalHref>) -> Self {
855 let href = href.into();
856 let path = href.as_str().split(['?', '#']).next().unwrap_or_default();
857 if !path.starts_with('/')
858 || path.contains('\\')
859 || path.bytes().any(|byte| byte <= b' ')
860 || path.chars().any(char::is_whitespace)
861 || has_encoded_slash(path)
862 || has_dot_segment(path)
863 {
864 return self;
865 }
866 let token = format!("={path}");
867 let held = self
868 .get("data-ui-ext-routes")
869 .and_then(AttrValue::as_text)
870 .map(Cow::into_owned);
871 match held {
872 Some(list) if list.split(' ').any(|have| have == token) => {}
873 Some(list) => self.put("data-ui-ext-routes", format!("{list} {token}")),
874 None => self.put("data-ui-ext-routes", token),
875 }
876 self
877 }
878
879 fn put(&mut self, name: &'static str, value: String) {
881 let value = AttrValue::Text(value.into_boxed_str());
882 match self.attrs.iter_mut().find(|attr| attr.name == name) {
883 Some(attr) => attr.value = value,
884 None => self.attrs.push(Attr { name, value }),
885 }
886 }
887
888 fn named_extension(mut self, extension: &'static UiExtension, props: Option<String>) -> Self {
893 const OWN: [&str; 4] = [
894 "data-ui-ext",
895 "data-ui-ext-sheet",
896 "data-ui-ext-routes",
897 "data-ui-props",
898 ];
899 if self.attrs.iter().any(|attr| attr.name == "data-ui-island") {
902 debug_assert!(
903 extension.script_file().is_none(),
904 "an element is an island or carries an extension script, not both"
905 );
906 self.uses = Uses(self.uses.0 & !Uses::EXTENSION_SHEETS.0);
907 self.attrs.retain(|attr| attr.name != "data-ui-ext-sheet");
908 if let Some(sheet) = extension.sheet_url() {
909 self.put("data-ui-ext-sheet", sheet.to_owned());
910 self.uses = self.uses.with(Uses::EXTENSION_SHEETS);
911 }
912 return self;
913 }
914 self.uses = self.uses.without_extensions();
915 self.attrs.retain(|attr| !OWN.contains(&attr.name));
916 if let Some(script) = extension.script_url() {
917 self.put("data-ui-ext", script.to_owned());
918 self.uses = self.uses.with(Uses::EXTENSIONS).with(Uses::CORE);
919 }
920 if let Some(sheet) = extension.sheet_url() {
921 self.put("data-ui-ext-sheet", sheet.to_owned());
922 self.uses = self.uses.with(Uses::EXTENSION_SHEETS);
923 }
924 if !extension.routes_of().is_empty() {
925 self.put("data-ui-ext-routes", extension.routes_of().join(" "));
926 }
927 let mut kept: Vec<String> = Vec::new();
928 let held = self
929 .get("data-ui-keep-attrs")
930 .and_then(AttrValue::as_text)
931 .map(Cow::into_owned);
932 let tokens = held
933 .iter()
934 .flat_map(|held| held.split_whitespace())
935 .chain(["data-ui-mounted", "data-ui-failed"])
936 .chain(extension.keeps_of().iter().copied());
937 for token in tokens {
938 if !kept.iter().any(|have| have == token) {
939 kept.push(token.to_owned());
940 }
941 }
942 self.put("data-ui-keep-attrs", kept.join(" "));
943 if let Some(json) = props {
944 self.put("data-ui-props", json);
945 }
946 self
947 }
948
949 #[inline]
951 #[must_use]
952 pub fn child(mut self, child: impl IntoNodes) -> Self {
953 child.push_into(&mut self.children);
954 self
955 }
956
957 #[inline]
959 #[must_use]
960 pub fn children(self, children: impl IntoNodes) -> Self {
961 self.child(children)
962 }
963
964 #[inline]
966 #[must_use]
967 pub fn with_child_capacity(mut self, count: usize) -> Self {
968 self.children.reserve_exact(count);
969 self
970 }
971}
972
973impl From<Element> for Node {
974 #[inline]
975 fn from(element: Element) -> Self {
976 Self::Element(element)
977 }
978}
979
980impl From<&'static str> for Node {
981 #[inline]
982 fn from(text: &'static str) -> Self {
983 Self::Text(Cow::Borrowed(text))
984 }
985}
986
987impl From<String> for Node {
988 #[inline]
989 fn from(text: String) -> Self {
990 Self::Text(Cow::Owned(text))
991 }
992}
993
994impl From<Cow<'static, str>> for Node {
995 #[inline]
996 fn from(text: Cow<'static, str>) -> Self {
997 Self::Text(text)
998 }
999}
1000
1001impl From<i64> for Node {
1002 #[inline]
1003 fn from(value: i64) -> Self {
1004 Self::Int(value)
1005 }
1006}
1007
1008impl From<SafeHtml> for Node {
1009 fn from(html: SafeHtml) -> Self {
1010 Self::Raw(html)
1011 }
1012}
1013
1014pub trait IntoNodes {
1016 fn push_into(self, out: &mut Vec<Node>);
1018}
1019
1020impl<T: Into<Node>> IntoNodes for T {
1021 #[inline]
1022 fn push_into(self, out: &mut Vec<Node>) {
1023 out.push(self.into());
1024 }
1025}
1026
1027impl<T: IntoNodes> IntoNodes for Vec<T> {
1028 #[inline]
1029 fn push_into(self, out: &mut Vec<Node>) {
1030 out.reserve(self.len());
1031 for item in self {
1032 item.push_into(out);
1033 }
1034 }
1035}
1036
1037impl<T: IntoNodes, const N: usize> IntoNodes for [T; N] {
1038 #[inline]
1039 fn push_into(self, out: &mut Vec<Node>) {
1040 out.reserve(N);
1041 for item in self {
1042 item.push_into(out);
1043 }
1044 }
1045}
1046
1047impl<T: IntoNodes> IntoNodes for Option<T> {
1048 #[inline]
1049 fn push_into(self, out: &mut Vec<Node>) {
1050 if let Some(item) = self {
1051 item.push_into(out);
1052 }
1053 }
1054}
1055
1056macro_rules! tuples {
1057 ($($name:ident)+) => {
1058 impl<$($name: IntoNodes),+> IntoNodes for ($($name,)+) {
1059 #[inline]
1060 #[allow(non_snake_case)]
1061 fn push_into(self, out: &mut Vec<Node>) {
1062 let ($($name,)+) = self;
1063 $($name.push_into(out);)+
1064 }
1065 }
1066 };
1067}
1068
1069tuples!(A);
1070tuples!(A B);
1071tuples!(A B C);
1072tuples!(A B C D);
1073tuples!(A B C D E);
1074tuples!(A B C D E F);
1075tuples!(A B C D E F G);
1076tuples!(A B C D E F G H);
1077tuples!(A B C D E F G H I);
1078tuples!(A B C D E F G H I J);
1079tuples!(A B C D E F G H I J K);
1080tuples!(A B C D E F G H I J K L);
1081
1082#[macro_export]
1113macro_rules! component_node {
1114 ($($type:ty),+ $(,)?) => {
1115 $(impl ::core::convert::From<$type> for $crate::Node {
1116 #[inline]
1117 fn from(value: $type) -> Self {
1118 value.into_node()
1119 }
1120 })+
1121 };
1122}
1123pub(crate) use crate::component_node as into_node;
1124
1125#[cfg(test)]
1126mod tests {
1127 use super::*;
1128
1129 #[test]
1130 fn urls_in_attributes_are_checked() {
1131 let element = el("a").attr("href", "javascript:alert(1)");
1132 assert_eq!(element.get("href"), Some(&AttrValue::Text("#".into())));
1133 let element = el("a").attr("href", "/ok".to_owned());
1134 assert_eq!(element.get("href"), Some(&AttrValue::Text("/ok".into())));
1135 }
1136
1137 #[test]
1138 fn children_take_tuples_lists_and_options() {
1139 let element =
1140 el("div").children(("a", Some("b"), None::<&'static str>, vec!["c", "d"], 7_i64));
1141 assert_eq!(element.child_nodes().len(), 5);
1142 assert_eq!(Node::from(element).text_content(), "abcd7");
1143 }
1144
1145 #[test]
1146 fn commands_ask_for_the_core_runtime() {
1147 assert!(el("div").uses.is_none());
1148 let element = el("button").on_click_one(Cmd::toggle("menu"));
1149 assert!(element.uses.has(Uses::CORE));
1150 }
1151
1152 #[test]
1153 fn a_hotkey_is_one_typed_character_and_loads_the_keys_module() {
1154 for key in ["j", "K", "/", "?", "1", "é"] {
1155 let element = el("a").hotkey(key);
1156 assert_eq!(
1157 element.get("data-ui-hotkey"),
1158 Some(&AttrValue::Text(key.into()))
1159 );
1160 assert_eq!(
1161 element.get("aria-keyshortcuts"),
1162 Some(&AttrValue::Text(key.into()))
1163 );
1164 assert!(element.uses.has(Uses::KEYS));
1165 }
1166 for bad in ["", " ", "jk", "Enter", "\n", "\u{7}", "ctrl+k"] {
1167 let element = el("a").hotkey(bad);
1168 assert!(element.get("data-ui-hotkey").is_none(), "{bad:?}");
1169 assert!(element.uses.is_none(), "{bad:?}");
1170 }
1171 }
1172
1173 #[test]
1174 fn a_scoped_hotkey_names_its_scope_and_refuses_a_bad_one() {
1175 let html = crate::render(&el("button").hotkey_within("e", "thread").into());
1176 assert!(html.contains(r#"data-ui-hotkey="e""#), "{html}");
1177 assert!(html.contains(r#"data-ui-hotkey-scope="thread""#), "{html}");
1178 for bad in ["", "a b", "x\"y", &"z".repeat(65)] {
1179 let html = crate::render(&el("button").hotkey_within("e", bad).into());
1180 assert!(!html.contains("data-ui-hotkey"), "{bad}: {html}");
1181 }
1182 let html = crate::render(&el("button").hotkey_within("two", "thread").into());
1183 assert!(!html.contains("data-ui-hotkey"), "{html}");
1184 }
1185
1186 #[test]
1187 fn the_new_modules_have_bits_of_their_own() {
1188 let known = [
1189 Uses::CORE,
1190 Uses::SIDEBAR,
1191 Uses::OVERLAY,
1192 Uses::TABLE,
1193 Uses::SELECT,
1194 Uses::MENUS,
1195 Uses::LIVE,
1196 Uses::DATES,
1197 Uses::PHONE,
1198 Uses::THEME_BUILDER,
1199 Uses::SLIDER,
1200 Uses::TREE,
1201 Uses::TOOLBAR,
1202 Uses::SORTABLE,
1203 ];
1204 for module in [Uses::SPLIT, Uses::KEYS, Uses::LAZY] {
1205 assert!(known.iter().all(|other| other.0 & module.0 == 0));
1206 }
1207 assert_eq!(Uses::SPLIT.0 & Uses::KEYS.0, 0);
1208 assert_eq!((Uses::SPLIT.0 | Uses::KEYS.0) & Uses::LAZY.0, 0);
1209 }
1210
1211 #[test]
1212 fn the_markdown_upload_code_carousel_and_menu_bar_modules_have_bits_of_their_own() {
1213 let older = [
1214 Uses::CORE,
1215 Uses::SIDEBAR,
1216 Uses::OVERLAY,
1217 Uses::TABLE,
1218 Uses::SELECT,
1219 Uses::MENUS,
1220 Uses::LIVE,
1221 Uses::DATES,
1222 Uses::PHONE,
1223 Uses::THEME_BUILDER,
1224 Uses::SLIDER,
1225 Uses::TREE,
1226 Uses::TOOLBAR,
1227 Uses::SORTABLE,
1228 Uses::SPLIT,
1229 Uses::KEYS,
1230 Uses::LAZY,
1231 ];
1232 let newer = [
1233 Uses::MARKDOWN,
1234 Uses::UPLOAD,
1235 Uses::OTP,
1236 Uses::CAROUSEL,
1237 Uses::MENUBAR,
1238 Uses::PARTS,
1239 Uses::PARTS_STYLES,
1240 Uses::GENUI,
1241 ];
1242 for (at, module) in newer.iter().enumerate() {
1243 assert_eq!(module.0.count_ones(), 1);
1244 assert!(older.iter().all(|other| other.0 & module.0 == 0));
1245 assert!(newer[at + 1..].iter().all(|other| other.0 & module.0 == 0));
1246 }
1247 }
1248
1249 #[test]
1250 fn a_node_stays_small() {
1251 assert!(
1253 std::mem::size_of::<Node>() <= 72,
1254 "{}",
1255 std::mem::size_of::<Node>()
1256 );
1257 }
1258
1259 use crate::extension::ExtensionFile;
1260
1261 static MAP: UiExtension = UiExtension::new("geo", "map")
1263 .script(ExtensionFile::__new(
1264 b"export const contract = 1; export function mount() {}",
1265 "e1613860bbf0",
1266 None,
1267 ))
1268 .sheet(ExtensionFile::__new(
1269 b"/* the map's stylesheet, scoped for geo */",
1270 "bbefcf02ae04",
1271 Some("geo"),
1272 ))
1273 .contract(1)
1274 .keeps(&["data-moving"])
1275 .routes(&["/geo/"]);
1276 static BADGE: UiExtension = UiExtension::new("geo", "badge").sheet(ExtensionFile::__new(
1277 b"/* the badge's stylesheet, scoped for geo */",
1278 "ea46b024fa00",
1279 Some("geo"),
1280 ));
1281
1282 const MAP_ATTRIBUTES: &str = r#" data-ui-ext="/_navree/ui/ext/geo.map-e1613860bbf0.js" data-ui-ext-sheet="/_navree/ui/ext/geo.map-bbefcf02ae04.css" data-ui-ext-routes="/geo/""#;
1283
1284 #[test]
1285 fn an_element_with_an_extension_names_its_files_and_asks_for_the_modules() {
1286 let element = el("div").slot("geo:map").extension(&MAP);
1287 assert_eq!(
1288 crate::render(&element.clone().into()),
1289 format!(
1290 r#"<div data-slot="geo:map"{MAP_ATTRIBUTES} data-ui-keep-attrs="data-ui-mounted data-ui-failed data-moving"></div>"#
1291 )
1292 );
1293 assert!(element.uses.has(Uses::EXTENSIONS));
1294 assert!(element.uses.has(Uses::EXTENSION_SHEETS));
1295 assert!(element.uses.has(Uses::CORE));
1296
1297 let held = el("div")
1299 .attr("data-ui-keep-attrs", "data-collapsed")
1300 .slot("geo:map")
1301 .extension(&MAP);
1302 assert_eq!(
1303 held.get("data-ui-keep-attrs"),
1304 Some(&AttrValue::Text(
1305 "data-collapsed data-ui-mounted data-ui-failed data-moving".into()
1306 ))
1307 );
1308 let repeated = el("div")
1309 .attr("data-ui-keep-attrs", "data-moving data-ui-failed")
1310 .extension(&MAP);
1311 assert_eq!(
1312 repeated.get("data-ui-keep-attrs"),
1313 Some(&AttrValue::Text(
1314 "data-moving data-ui-failed data-ui-mounted".into()
1315 ))
1316 );
1317
1318 let replaced = el("div")
1320 .extension_with(&MAP, &serde_json::json!({ "zoom": 15 }))
1321 .extension(&BADGE);
1322 assert!(replaced.get("data-ui-ext").is_none());
1323 assert!(replaced.get("data-ui-ext-routes").is_none());
1324 assert!(replaced.get("data-ui-props").is_none());
1325 assert_eq!(
1326 replaced.get("data-ui-ext-sheet"),
1327 Some(&AttrValue::Text(
1328 "/_navree/ui/ext/geo.badge-ea46b024fa00.css".into()
1329 ))
1330 );
1331 assert!(replaced.uses.has(Uses::EXTENSION_SHEETS));
1332 assert!(!replaced.uses.has(Uses::EXTENSIONS));
1333 }
1334
1335 #[test]
1336 fn a_sheet_only_extension_asks_for_no_script() {
1337 let element = el("span").extension(&BADGE);
1338 assert_eq!(
1339 crate::render(&element.clone().into()),
1340 r#"<span data-ui-ext-sheet="/_navree/ui/ext/geo.badge-ea46b024fa00.css" data-ui-keep-attrs="data-ui-mounted data-ui-failed"></span>"#
1341 );
1342 assert_eq!(element.uses, Uses::EXTENSION_SHEETS);
1343 }
1344
1345 #[test]
1346 fn an_island_names_the_sheet_and_keeps_its_own_script_and_props() {
1347 let island = || {
1348 el("div")
1349 .attr("data-ui-island", "/_navree/ui/island/clock-0123456789ab.js")
1350 .attr("data-ui-props", "{}")
1351 .uses(Uses::ISLAND)
1352 };
1353 let styled = island().extension(&BADGE);
1354 assert_eq!(
1355 crate::render(&styled.clone().into()),
1356 r#"<div data-ui-island="/_navree/ui/island/clock-0123456789ab.js" data-ui-props="{}" data-ui-ext-sheet="/_navree/ui/ext/geo.badge-ea46b024fa00.css"></div>"#
1357 );
1358 assert!(styled.uses.has(Uses::ISLAND));
1359 assert!(styled.uses.has(Uses::EXTENSION_SHEETS));
1360 assert!(!styled.uses.has(Uses::EXTENSIONS));
1361 }
1362
1363 #[test]
1366 fn a_plugins_island_keeps_the_extensions_module_when_it_names_a_sheet() {
1367 use crate::island::{Island, IslandScript};
1368
1369 static CLOCK: IslandScript =
1370 IslandScript::new("clock", b"export function mount() {}", 1024).namespace("geo");
1371 static PLAIN_CLOCK: IslandScript =
1372 IslandScript::new("clock", b"export function mount() {}", 1024);
1373 let element = |island: Island| {
1374 Node::from(island)
1375 .into_element()
1376 .expect("an island is one element")
1377 };
1378
1379 let plugins = element(Island::new("clock", &CLOCK));
1380 assert_eq!(plugins.uses, Uses::ISLAND.with(Uses::EXTENSIONS));
1381 let styled = plugins.extension(&BADGE);
1382 assert_eq!(
1383 styled.uses,
1384 Uses::ISLAND
1385 .with(Uses::EXTENSIONS)
1386 .with(Uses::EXTENSION_SHEETS)
1387 );
1388 assert_eq!(
1390 styled.extension(&BADGE).uses,
1391 Uses::ISLAND
1392 .with(Uses::EXTENSIONS)
1393 .with(Uses::EXTENSION_SHEETS)
1394 );
1395
1396 let apps = element(Island::new("clock", &PLAIN_CLOCK));
1397 assert_eq!(apps.uses, Uses::ISLAND);
1398 assert_eq!(
1399 apps.extension(&BADGE).uses,
1400 Uses::ISLAND.with(Uses::EXTENSION_SHEETS)
1401 );
1402 }
1403
1404 #[cfg(debug_assertions)]
1406 #[test]
1407 #[should_panic(expected = "an element is an island or carries an extension script, not both")]
1408 fn an_island_with_an_extension_script_is_refused_in_a_debug_build() {
1409 let _ = el("div")
1410 .attr("data-ui-island", "/_navree/ui/island/clock-0123456789ab.js")
1411 .extension(&MAP);
1412 }
1413
1414 #[test]
1415 fn extension_call_adds_one_exact_address() {
1416 let plain = crate::render(&el("div").extension(&MAP).into());
1417 let called = crate::render(
1418 &el("div")
1419 .extension(&MAP)
1420 .extension_call("/deliveries/42/drop?from=table")
1421 .into(),
1422 );
1423 assert_eq!(
1424 called,
1425 plain.replace(
1426 r#"data-ui-ext-routes="/geo/""#,
1427 r#"data-ui-ext-routes="/geo/ =/deliveries/42/drop""#
1428 )
1429 );
1430 let twice = el("div")
1432 .extension(&MAP)
1433 .extension_call("/deliveries/42/drop")
1434 .extension_call("/deliveries/42/drop#top")
1435 .extension_call("/deliveries/43/drop");
1436 assert_eq!(
1437 twice.get("data-ui-ext-routes"),
1438 Some(&AttrValue::Text(
1439 "/geo/ =/deliveries/42/drop =/deliveries/43/drop".into()
1440 ))
1441 );
1442 let only = el("div")
1444 .extension(&BADGE)
1445 .extension_call("/deliveries/42/drop");
1446 assert_eq!(
1447 only.get("data-ui-ext-routes"),
1448 Some(&AttrValue::Text("=/deliveries/42/drop".into()))
1449 );
1450 for refused in [
1452 "relative",
1453 "#",
1454 "?x=1",
1455 "//other.example/geo/x",
1456 "https://other.example/geo/x",
1457 "/deliveries/42 /drop",
1458 "",
1459 ] {
1460 let element = el("div").extension(&MAP).extension_call(refused);
1461 assert_eq!(crate::render(&element.into()), plain, "{refused:?}");
1462 }
1463 }
1464
1465 #[test]
1466 fn extension_props_are_escaped_json() {
1467 #[derive(serde::Serialize)]
1468 struct Props {
1469 note: &'static str,
1470 city: &'static str,
1471 }
1472 let props = Props {
1473 note: "</div><script>alert(1)</script>",
1474 city: "Ludhiana",
1475 };
1476 let html = crate::render(&el("div").extension_with(&MAP, &props).into());
1477 assert!(
1478 html.contains(
1479 r#" data-ui-props="{"note":"</div><script>alert(1)</script>","city":"Ludhiana"}""#
1480 ),
1481 "{html}"
1482 );
1483 assert!(!html.contains("<script"), "{html}");
1484 let pairs = std::collections::BTreeMap::from([((1, 2), "x")]);
1486 let html = crate::render(&el("div").extension_with(&MAP, &pairs).into());
1487 assert!(html.contains(r#" data-ui-props="null""#), "{html}");
1488 }
1489
1490 #[test]
1491 fn the_extension_bits_are_two_modules_of_their_own() {
1492 assert_eq!(Uses::EXTENSIONS.0.count_ones(), 1);
1493 assert_eq!(Uses::EXTENSION_SHEETS.0.count_ones(), 1);
1494 assert_ne!(Uses::EXTENSIONS, Uses::EXTENSION_SHEETS);
1495 let both = Uses::EXTENSIONS
1496 .with(Uses::EXTENSION_SHEETS)
1497 .with(Uses::CORE);
1498 assert_eq!(
1499 both.extension_bits(),
1500 Uses::EXTENSIONS.with(Uses::EXTENSION_SHEETS)
1501 );
1502 assert_eq!(both.without_extensions(), Uses::CORE);
1503 }
1504}