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
459impl Element {
460 #[cfg_attr(not(feature = "native-preview"), allow(unused_variables, unused_mut))]
472 pub fn presented(mut self, how: crate::Presented) -> Self {
473 #[cfg(feature = "native-preview")]
474 self.say(|hints| hints.presented = Some(how));
475 self
476 }
477
478 #[cfg(feature = "native-preview")]
483 pub(crate) fn say(&mut self, set: impl FnOnce(&mut crate::hint::Hints)) {
484 let Some(request) = crate::native::scope::native() else {
485 return;
486 };
487 let held = self.children.iter().find_map(crate::hint::key_of);
488 let key = request.hint(held.unwrap_or(0), set);
489 if held.is_none()
490 && let Some(mark) = crate::hint::key_mark(key)
491 {
492 self.children.push(mark);
493 }
494 }
495
496 #[cfg(feature = "native-preview")]
498 pub(crate) fn said(&self) -> Option<crate::hint::Hints> {
499 let key = self.children.iter().find_map(crate::hint::key_of)?;
500 crate::native::scope::native()?.hinted(key)
501 }
502
503 pub fn tag(&self) -> &'static str {
505 self.tag
506 }
507
508 pub fn attrs(&self) -> &[Attr] {
510 &self.attrs
511 }
512
513 pub fn child_nodes(&self) -> &[Node] {
515 &self.children
516 }
517
518 pub fn get(&self, name: &str) -> Option<&AttrValue> {
520 self.attrs
521 .iter()
522 .find(|attr| attr.name == name)
523 .map(|attr| &attr.value)
524 }
525
526 #[inline]
529 #[must_use]
530 pub fn attr(mut self, name: &'static str, value: impl Into<AttrValue>) -> Self {
531 if is_refused_attr(name) {
532 debug_assert!(
533 false,
534 "`{name}` is not allowed under the content security policy"
535 );
536 return self;
537 }
538 let mut value = value.into();
539 if is_url_attr(name)
540 && let Some(text) = value.as_text()
541 {
542 value = Href::from(text.as_ref()).into();
543 }
544 self.attrs.push(Attr { name, value });
545 self
546 }
547
548 #[inline]
550 #[must_use]
551 pub fn attr_opt(self, name: &'static str, value: Option<impl Into<AttrValue>>) -> Self {
552 match value {
553 Some(value) => self.attr(name, value),
554 None => self,
555 }
556 }
557
558 #[inline]
560 #[must_use]
561 pub fn flag(mut self, name: &'static str, on: bool) -> Self {
562 if on && !is_refused_attr(name) {
563 self.attrs.push(Attr {
564 name,
565 value: AttrValue::Flag,
566 });
567 }
568 self
569 }
570
571 #[inline]
573 #[must_use]
574 pub fn slot(self, slot: &'static str) -> Self {
575 self.attr("data-slot", slot)
576 }
577
578 #[inline]
580 #[must_use]
581 pub fn id(self, id: impl Into<AttrValue>) -> Self {
582 self.attr("id", id)
583 }
584
585 #[inline]
587 #[must_use]
588 pub fn href(mut self, href: impl Into<Href>) -> Self {
589 self.attrs.push(Attr {
590 name: "href",
591 value: href.into().into(),
592 });
593 self
594 }
595
596 #[inline]
599 #[must_use]
600 pub fn prefetch(self) -> Self {
601 self.flag("data-ui-prefetch", true)
602 }
603
604 #[inline]
614 #[must_use]
615 pub fn prefetch_eager(self) -> Self {
616 self.attr("data-ui-prefetch", "eager")
617 }
618
619 #[must_use]
622 pub fn on_click(self, commands: impl Into<Commands>) -> Self {
623 self.on(crate::cmd::Trigger::Click, commands)
624 }
625
626 #[must_use]
628 pub fn on(mut self, trigger: crate::cmd::Trigger, commands: impl Into<Commands>) -> Self {
632 self.uses = self.uses.with(Uses::CORE);
633 let json = commands.into().to_json();
634 let name = trigger.attribute();
635 if let Some(attr) = self.attrs.iter_mut().find(|attr| attr.name == name) {
636 let old = attr
639 .value
640 .as_text()
641 .map(|text| text.into_owned())
642 .unwrap_or_default();
643 let merged = match (old.as_str(), json.as_str()) {
644 ("" | "[]", _) => json,
645 (_, "[]") => old,
646 (old, new) => format!("{},{}", &old[..old.len() - 1], &new[1..]),
647 };
648 attr.value = AttrValue::Text(merged.into_boxed_str());
649 return self;
650 }
651 self.attrs.push(Attr {
652 name,
653 value: AttrValue::Text(json.into_boxed_str()),
654 });
655 self
656 }
657
658 #[must_use]
660 pub fn on_click_one(self, command: Cmd) -> Self {
661 self.on_click(vec![command])
662 }
663
664 #[must_use]
669 pub fn fill_cell(self, column: &'static str) -> Self {
670 self.attr("data-ui-cell", column)
671 }
672
673 #[must_use]
677 pub fn settable(self) -> Self {
678 self.flag("data-ui-value", true)
679 }
680
681 #[must_use]
684 pub fn fill_key(self) -> Self {
685 self.flag("data-ui-row-key", true)
686 }
687
688 #[must_use]
707 pub fn hotkey(self, key: &str) -> Self {
708 if !valid_hotkey(key) {
709 return self;
710 }
711 self.attr("data-ui-hotkey", key.to_owned())
712 .attr("aria-keyshortcuts", key.to_owned())
713 .uses(Uses::KEYS)
714 }
715
716 #[must_use]
733 pub fn hotkey_within(self, key: &str, scope: &str) -> Self {
734 let scope_ok = !scope.is_empty()
735 && scope.len() <= 64
736 && scope
737 .chars()
738 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.'));
739 if !valid_hotkey(key) || !scope_ok {
740 return self;
741 }
742 self.hotkey(key)
743 .attr("data-ui-hotkey-scope", scope.to_owned())
744 }
745
746 #[inline]
748 #[must_use]
749 pub fn uses(mut self, uses: Uses) -> Self {
750 self.uses = self.uses.with(uses);
751 self
752 }
753
754 #[must_use]
772 pub fn extension(self, extension: &'static UiExtension) -> Self {
773 self.named_extension(extension, None)
774 }
775
776 #[must_use]
796 pub fn extension_with(self, extension: &'static UiExtension, props: &impl Serialize) -> Self {
797 let json = serde_json::to_string(props).unwrap_or_else(|_| "null".to_owned());
798 self.named_extension(extension, Some(json))
799 }
800
801 #[must_use]
815 pub fn extension_call(mut self, href: impl Into<LocalHref>) -> Self {
816 let href = href.into();
817 let path = href.as_str().split(['?', '#']).next().unwrap_or_default();
818 if !path.starts_with('/') || path.chars().any(char::is_whitespace) {
819 return self;
820 }
821 let token = format!("={path}");
822 let held = self
823 .get("data-ui-ext-routes")
824 .and_then(AttrValue::as_text)
825 .map(Cow::into_owned);
826 match held {
827 Some(list) if list.split(' ').any(|have| have == token) => {}
828 Some(list) => self.put("data-ui-ext-routes", format!("{list} {token}")),
829 None => self.put("data-ui-ext-routes", token),
830 }
831 self
832 }
833
834 fn put(&mut self, name: &'static str, value: String) {
836 let value = AttrValue::Text(value.into_boxed_str());
837 match self.attrs.iter_mut().find(|attr| attr.name == name) {
838 Some(attr) => attr.value = value,
839 None => self.attrs.push(Attr { name, value }),
840 }
841 }
842
843 fn named_extension(mut self, extension: &'static UiExtension, props: Option<String>) -> Self {
848 const OWN: [&str; 4] = [
849 "data-ui-ext",
850 "data-ui-ext-sheet",
851 "data-ui-ext-routes",
852 "data-ui-props",
853 ];
854 if self.attrs.iter().any(|attr| attr.name == "data-ui-island") {
857 debug_assert!(
858 extension.script_file().is_none(),
859 "an element is an island or carries an extension script, not both"
860 );
861 self.uses = Uses(self.uses.0 & !Uses::EXTENSION_SHEETS.0);
862 self.attrs.retain(|attr| attr.name != "data-ui-ext-sheet");
863 if let Some(sheet) = extension.sheet_url() {
864 self.put("data-ui-ext-sheet", sheet.to_owned());
865 self.uses = self.uses.with(Uses::EXTENSION_SHEETS);
866 }
867 return self;
868 }
869 self.uses = self.uses.without_extensions();
870 self.attrs.retain(|attr| !OWN.contains(&attr.name));
871 if let Some(script) = extension.script_url() {
872 self.put("data-ui-ext", script.to_owned());
873 self.uses = self.uses.with(Uses::EXTENSIONS).with(Uses::CORE);
874 }
875 if let Some(sheet) = extension.sheet_url() {
876 self.put("data-ui-ext-sheet", sheet.to_owned());
877 self.uses = self.uses.with(Uses::EXTENSION_SHEETS);
878 }
879 if !extension.routes_of().is_empty() {
880 self.put("data-ui-ext-routes", extension.routes_of().join(" "));
881 }
882 let mut kept: Vec<String> = Vec::new();
883 let held = self
884 .get("data-ui-keep-attrs")
885 .and_then(AttrValue::as_text)
886 .map(Cow::into_owned);
887 let tokens = held
888 .iter()
889 .flat_map(|held| held.split_whitespace())
890 .chain(["data-ui-mounted", "data-ui-failed"])
891 .chain(extension.keeps_of().iter().copied());
892 for token in tokens {
893 if !kept.iter().any(|have| have == token) {
894 kept.push(token.to_owned());
895 }
896 }
897 self.put("data-ui-keep-attrs", kept.join(" "));
898 if let Some(json) = props {
899 self.put("data-ui-props", json);
900 }
901 self
902 }
903
904 #[inline]
906 #[must_use]
907 pub fn child(mut self, child: impl IntoNodes) -> Self {
908 child.push_into(&mut self.children);
909 self
910 }
911
912 #[inline]
914 #[must_use]
915 pub fn children(self, children: impl IntoNodes) -> Self {
916 self.child(children)
917 }
918
919 #[inline]
921 #[must_use]
922 pub fn with_child_capacity(mut self, count: usize) -> Self {
923 self.children.reserve_exact(count);
924 self
925 }
926}
927
928impl From<Element> for Node {
929 #[inline]
930 fn from(element: Element) -> Self {
931 Self::Element(element)
932 }
933}
934
935impl From<&'static str> for Node {
936 #[inline]
937 fn from(text: &'static str) -> Self {
938 Self::Text(Cow::Borrowed(text))
939 }
940}
941
942impl From<String> for Node {
943 #[inline]
944 fn from(text: String) -> Self {
945 Self::Text(Cow::Owned(text))
946 }
947}
948
949impl From<Cow<'static, str>> for Node {
950 #[inline]
951 fn from(text: Cow<'static, str>) -> Self {
952 Self::Text(text)
953 }
954}
955
956impl From<i64> for Node {
957 #[inline]
958 fn from(value: i64) -> Self {
959 Self::Int(value)
960 }
961}
962
963impl From<SafeHtml> for Node {
964 fn from(html: SafeHtml) -> Self {
965 Self::Raw(html)
966 }
967}
968
969pub trait IntoNodes {
971 fn push_into(self, out: &mut Vec<Node>);
973}
974
975impl<T: Into<Node>> IntoNodes for T {
976 #[inline]
977 fn push_into(self, out: &mut Vec<Node>) {
978 out.push(self.into());
979 }
980}
981
982impl<T: IntoNodes> IntoNodes for Vec<T> {
983 #[inline]
984 fn push_into(self, out: &mut Vec<Node>) {
985 out.reserve(self.len());
986 for item in self {
987 item.push_into(out);
988 }
989 }
990}
991
992impl<T: IntoNodes, const N: usize> IntoNodes for [T; N] {
993 #[inline]
994 fn push_into(self, out: &mut Vec<Node>) {
995 out.reserve(N);
996 for item in self {
997 item.push_into(out);
998 }
999 }
1000}
1001
1002impl<T: IntoNodes> IntoNodes for Option<T> {
1003 #[inline]
1004 fn push_into(self, out: &mut Vec<Node>) {
1005 if let Some(item) = self {
1006 item.push_into(out);
1007 }
1008 }
1009}
1010
1011macro_rules! tuples {
1012 ($($name:ident)+) => {
1013 impl<$($name: IntoNodes),+> IntoNodes for ($($name,)+) {
1014 #[inline]
1015 #[allow(non_snake_case)]
1016 fn push_into(self, out: &mut Vec<Node>) {
1017 let ($($name,)+) = self;
1018 $($name.push_into(out);)+
1019 }
1020 }
1021 };
1022}
1023
1024tuples!(A);
1025tuples!(A B);
1026tuples!(A B C);
1027tuples!(A B C D);
1028tuples!(A B C D E);
1029tuples!(A B C D E F);
1030tuples!(A B C D E F G);
1031tuples!(A B C D E F G H);
1032tuples!(A B C D E F G H I);
1033tuples!(A B C D E F G H I J);
1034tuples!(A B C D E F G H I J K);
1035tuples!(A B C D E F G H I J K L);
1036
1037#[macro_export]
1068macro_rules! component_node {
1069 ($($type:ty),+ $(,)?) => {
1070 $(impl ::core::convert::From<$type> for $crate::Node {
1071 #[inline]
1072 fn from(value: $type) -> Self {
1073 value.into_node()
1074 }
1075 })+
1076 };
1077}
1078pub(crate) use crate::component_node as into_node;
1079
1080#[cfg(test)]
1081mod tests {
1082 use super::*;
1083
1084 #[test]
1085 fn urls_in_attributes_are_checked() {
1086 let element = el("a").attr("href", "javascript:alert(1)");
1087 assert_eq!(element.get("href"), Some(&AttrValue::Text("#".into())));
1088 let element = el("a").attr("href", "/ok".to_owned());
1089 assert_eq!(element.get("href"), Some(&AttrValue::Text("/ok".into())));
1090 }
1091
1092 #[test]
1093 fn children_take_tuples_lists_and_options() {
1094 let element =
1095 el("div").children(("a", Some("b"), None::<&'static str>, vec!["c", "d"], 7_i64));
1096 assert_eq!(element.child_nodes().len(), 5);
1097 assert_eq!(Node::from(element).text_content(), "abcd7");
1098 }
1099
1100 #[test]
1101 fn commands_ask_for_the_core_runtime() {
1102 assert!(el("div").uses.is_none());
1103 let element = el("button").on_click_one(Cmd::toggle("menu"));
1104 assert!(element.uses.has(Uses::CORE));
1105 }
1106
1107 #[test]
1108 fn a_hotkey_is_one_typed_character_and_loads_the_keys_module() {
1109 for key in ["j", "K", "/", "?", "1", "é"] {
1110 let element = el("a").hotkey(key);
1111 assert_eq!(
1112 element.get("data-ui-hotkey"),
1113 Some(&AttrValue::Text(key.into()))
1114 );
1115 assert_eq!(
1116 element.get("aria-keyshortcuts"),
1117 Some(&AttrValue::Text(key.into()))
1118 );
1119 assert!(element.uses.has(Uses::KEYS));
1120 }
1121 for bad in ["", " ", "jk", "Enter", "\n", "\u{7}", "ctrl+k"] {
1122 let element = el("a").hotkey(bad);
1123 assert!(element.get("data-ui-hotkey").is_none(), "{bad:?}");
1124 assert!(element.uses.is_none(), "{bad:?}");
1125 }
1126 }
1127
1128 #[test]
1129 fn a_scoped_hotkey_names_its_scope_and_refuses_a_bad_one() {
1130 let html = crate::render(&el("button").hotkey_within("e", "thread").into());
1131 assert!(html.contains(r#"data-ui-hotkey="e""#), "{html}");
1132 assert!(html.contains(r#"data-ui-hotkey-scope="thread""#), "{html}");
1133 for bad in ["", "a b", "x\"y", &"z".repeat(65)] {
1134 let html = crate::render(&el("button").hotkey_within("e", bad).into());
1135 assert!(!html.contains("data-ui-hotkey"), "{bad}: {html}");
1136 }
1137 let html = crate::render(&el("button").hotkey_within("two", "thread").into());
1138 assert!(!html.contains("data-ui-hotkey"), "{html}");
1139 }
1140
1141 #[test]
1142 fn the_new_modules_have_bits_of_their_own() {
1143 let known = [
1144 Uses::CORE,
1145 Uses::SIDEBAR,
1146 Uses::OVERLAY,
1147 Uses::TABLE,
1148 Uses::SELECT,
1149 Uses::MENUS,
1150 Uses::LIVE,
1151 Uses::DATES,
1152 Uses::PHONE,
1153 Uses::THEME_BUILDER,
1154 Uses::SLIDER,
1155 Uses::TREE,
1156 Uses::TOOLBAR,
1157 Uses::SORTABLE,
1158 ];
1159 for module in [Uses::SPLIT, Uses::KEYS, Uses::LAZY] {
1160 assert!(known.iter().all(|other| other.0 & module.0 == 0));
1161 }
1162 assert_eq!(Uses::SPLIT.0 & Uses::KEYS.0, 0);
1163 assert_eq!((Uses::SPLIT.0 | Uses::KEYS.0) & Uses::LAZY.0, 0);
1164 }
1165
1166 #[test]
1167 fn the_markdown_upload_code_carousel_and_menu_bar_modules_have_bits_of_their_own() {
1168 let older = [
1169 Uses::CORE,
1170 Uses::SIDEBAR,
1171 Uses::OVERLAY,
1172 Uses::TABLE,
1173 Uses::SELECT,
1174 Uses::MENUS,
1175 Uses::LIVE,
1176 Uses::DATES,
1177 Uses::PHONE,
1178 Uses::THEME_BUILDER,
1179 Uses::SLIDER,
1180 Uses::TREE,
1181 Uses::TOOLBAR,
1182 Uses::SORTABLE,
1183 Uses::SPLIT,
1184 Uses::KEYS,
1185 Uses::LAZY,
1186 ];
1187 let newer = [
1188 Uses::MARKDOWN,
1189 Uses::UPLOAD,
1190 Uses::OTP,
1191 Uses::CAROUSEL,
1192 Uses::MENUBAR,
1193 Uses::PARTS,
1194 Uses::PARTS_STYLES,
1195 Uses::GENUI,
1196 ];
1197 for (at, module) in newer.iter().enumerate() {
1198 assert_eq!(module.0.count_ones(), 1);
1199 assert!(older.iter().all(|other| other.0 & module.0 == 0));
1200 assert!(newer[at + 1..].iter().all(|other| other.0 & module.0 == 0));
1201 }
1202 }
1203
1204 #[test]
1205 fn a_node_stays_small() {
1206 assert!(
1208 std::mem::size_of::<Node>() <= 72,
1209 "{}",
1210 std::mem::size_of::<Node>()
1211 );
1212 }
1213
1214 use crate::extension::ExtensionFile;
1215
1216 static MAP: UiExtension = UiExtension::new("geo", "map")
1218 .script(ExtensionFile::__new(
1219 b"export const contract = 1; export function mount() {}",
1220 "1a2b3c4d5e6f",
1221 None,
1222 ))
1223 .sheet(ExtensionFile::__new(
1224 b"/* the map's stylesheet, scoped for geo */",
1225 "0f9e8d7c6b5a",
1226 Some("geo"),
1227 ))
1228 .contract(1)
1229 .keeps(&["data-moving"])
1230 .routes(&["/geo/"]);
1231 static BADGE: UiExtension = UiExtension::new("geo", "badge").sheet(ExtensionFile::__new(
1232 b"/* the badge's stylesheet, scoped for geo */",
1233 "aaaaaaaaaaaa",
1234 Some("geo"),
1235 ));
1236
1237 const MAP_ATTRIBUTES: &str = r#" data-ui-ext="/_navree/ui/ext/geo.map-1a2b3c4d5e6f.js" data-ui-ext-sheet="/_navree/ui/ext/geo.map-0f9e8d7c6b5a.css" data-ui-ext-routes="/geo/""#;
1238
1239 #[test]
1240 fn an_element_with_an_extension_names_its_files_and_asks_for_the_modules() {
1241 let element = el("div").slot("geo:map").extension(&MAP);
1242 assert_eq!(
1243 crate::render(&element.clone().into()),
1244 format!(
1245 r#"<div data-slot="geo:map"{MAP_ATTRIBUTES} data-ui-keep-attrs="data-ui-mounted data-ui-failed data-moving"></div>"#
1246 )
1247 );
1248 assert!(element.uses.has(Uses::EXTENSIONS));
1249 assert!(element.uses.has(Uses::EXTENSION_SHEETS));
1250 assert!(element.uses.has(Uses::CORE));
1251
1252 let held = el("div")
1254 .attr("data-ui-keep-attrs", "data-collapsed")
1255 .slot("geo:map")
1256 .extension(&MAP);
1257 assert_eq!(
1258 held.get("data-ui-keep-attrs"),
1259 Some(&AttrValue::Text(
1260 "data-collapsed data-ui-mounted data-ui-failed data-moving".into()
1261 ))
1262 );
1263 let repeated = el("div")
1264 .attr("data-ui-keep-attrs", "data-moving data-ui-failed")
1265 .extension(&MAP);
1266 assert_eq!(
1267 repeated.get("data-ui-keep-attrs"),
1268 Some(&AttrValue::Text(
1269 "data-moving data-ui-failed data-ui-mounted".into()
1270 ))
1271 );
1272
1273 let replaced = el("div")
1275 .extension_with(&MAP, &serde_json::json!({ "zoom": 15 }))
1276 .extension(&BADGE);
1277 assert!(replaced.get("data-ui-ext").is_none());
1278 assert!(replaced.get("data-ui-ext-routes").is_none());
1279 assert!(replaced.get("data-ui-props").is_none());
1280 assert_eq!(
1281 replaced.get("data-ui-ext-sheet"),
1282 Some(&AttrValue::Text(
1283 "/_navree/ui/ext/geo.badge-aaaaaaaaaaaa.css".into()
1284 ))
1285 );
1286 assert!(replaced.uses.has(Uses::EXTENSION_SHEETS));
1287 assert!(!replaced.uses.has(Uses::EXTENSIONS));
1288 }
1289
1290 #[test]
1291 fn a_sheet_only_extension_asks_for_no_script() {
1292 let element = el("span").extension(&BADGE);
1293 assert_eq!(
1294 crate::render(&element.clone().into()),
1295 r#"<span data-ui-ext-sheet="/_navree/ui/ext/geo.badge-aaaaaaaaaaaa.css" data-ui-keep-attrs="data-ui-mounted data-ui-failed"></span>"#
1296 );
1297 assert_eq!(element.uses, Uses::EXTENSION_SHEETS);
1298 }
1299
1300 #[test]
1301 fn an_island_names_the_sheet_and_keeps_its_own_script_and_props() {
1302 let island = || {
1303 el("div")
1304 .attr("data-ui-island", "/_navree/ui/island/clock-0123456789ab.js")
1305 .attr("data-ui-props", "{}")
1306 .uses(Uses::ISLAND)
1307 };
1308 let styled = island().extension(&BADGE);
1309 assert_eq!(
1310 crate::render(&styled.clone().into()),
1311 r#"<div data-ui-island="/_navree/ui/island/clock-0123456789ab.js" data-ui-props="{}" data-ui-ext-sheet="/_navree/ui/ext/geo.badge-aaaaaaaaaaaa.css"></div>"#
1312 );
1313 assert!(styled.uses.has(Uses::ISLAND));
1314 assert!(styled.uses.has(Uses::EXTENSION_SHEETS));
1315 assert!(!styled.uses.has(Uses::EXTENSIONS));
1316 }
1317
1318 #[test]
1321 fn a_plugins_island_keeps_the_extensions_module_when_it_names_a_sheet() {
1322 use crate::island::{Island, IslandScript};
1323
1324 static CLOCK: IslandScript =
1325 IslandScript::new("clock", b"export function mount() {}", 1024).namespace("geo");
1326 static PLAIN_CLOCK: IslandScript =
1327 IslandScript::new("clock", b"export function mount() {}", 1024);
1328 let element = |island: Island| {
1329 Node::from(island)
1330 .into_element()
1331 .expect("an island is one element")
1332 };
1333
1334 let plugins = element(Island::new("clock", &CLOCK));
1335 assert_eq!(plugins.uses, Uses::ISLAND.with(Uses::EXTENSIONS));
1336 let styled = plugins.extension(&BADGE);
1337 assert_eq!(
1338 styled.uses,
1339 Uses::ISLAND
1340 .with(Uses::EXTENSIONS)
1341 .with(Uses::EXTENSION_SHEETS)
1342 );
1343 assert_eq!(
1345 styled.extension(&BADGE).uses,
1346 Uses::ISLAND
1347 .with(Uses::EXTENSIONS)
1348 .with(Uses::EXTENSION_SHEETS)
1349 );
1350
1351 let apps = element(Island::new("clock", &PLAIN_CLOCK));
1352 assert_eq!(apps.uses, Uses::ISLAND);
1353 assert_eq!(
1354 apps.extension(&BADGE).uses,
1355 Uses::ISLAND.with(Uses::EXTENSION_SHEETS)
1356 );
1357 }
1358
1359 #[cfg(debug_assertions)]
1361 #[test]
1362 #[should_panic(expected = "an element is an island or carries an extension script, not both")]
1363 fn an_island_with_an_extension_script_is_refused_in_a_debug_build() {
1364 let _ = el("div")
1365 .attr("data-ui-island", "/_navree/ui/island/clock-0123456789ab.js")
1366 .extension(&MAP);
1367 }
1368
1369 #[test]
1370 fn extension_call_adds_one_exact_address() {
1371 let plain = crate::render(&el("div").extension(&MAP).into());
1372 let called = crate::render(
1373 &el("div")
1374 .extension(&MAP)
1375 .extension_call("/deliveries/42/drop?from=table")
1376 .into(),
1377 );
1378 assert_eq!(
1379 called,
1380 plain.replace(
1381 r#"data-ui-ext-routes="/geo/""#,
1382 r#"data-ui-ext-routes="/geo/ =/deliveries/42/drop""#
1383 )
1384 );
1385 let twice = el("div")
1387 .extension(&MAP)
1388 .extension_call("/deliveries/42/drop")
1389 .extension_call("/deliveries/42/drop#top")
1390 .extension_call("/deliveries/43/drop");
1391 assert_eq!(
1392 twice.get("data-ui-ext-routes"),
1393 Some(&AttrValue::Text(
1394 "/geo/ =/deliveries/42/drop =/deliveries/43/drop".into()
1395 ))
1396 );
1397 let only = el("div")
1399 .extension(&BADGE)
1400 .extension_call("/deliveries/42/drop");
1401 assert_eq!(
1402 only.get("data-ui-ext-routes"),
1403 Some(&AttrValue::Text("=/deliveries/42/drop".into()))
1404 );
1405 for refused in [
1407 "relative",
1408 "#",
1409 "?x=1",
1410 "//other.example/geo/x",
1411 "https://other.example/geo/x",
1412 "/deliveries/42 /drop",
1413 "",
1414 ] {
1415 let element = el("div").extension(&MAP).extension_call(refused);
1416 assert_eq!(crate::render(&element.into()), plain, "{refused:?}");
1417 }
1418 }
1419
1420 #[test]
1421 fn extension_props_are_escaped_json() {
1422 #[derive(serde::Serialize)]
1423 struct Props {
1424 note: &'static str,
1425 city: &'static str,
1426 }
1427 let props = Props {
1428 note: "</div><script>alert(1)</script>",
1429 city: "Ludhiana",
1430 };
1431 let html = crate::render(&el("div").extension_with(&MAP, &props).into());
1432 assert!(
1433 html.contains(
1434 r#" data-ui-props="{"note":"</div><script>alert(1)</script>","city":"Ludhiana"}""#
1435 ),
1436 "{html}"
1437 );
1438 assert!(!html.contains("<script"), "{html}");
1439 let pairs = std::collections::BTreeMap::from([((1, 2), "x")]);
1441 let html = crate::render(&el("div").extension_with(&MAP, &pairs).into());
1442 assert!(html.contains(r#" data-ui-props="null""#), "{html}");
1443 }
1444
1445 #[test]
1446 fn the_extension_bits_are_two_modules_of_their_own() {
1447 assert_eq!(Uses::EXTENSIONS.0.count_ones(), 1);
1448 assert_eq!(Uses::EXTENSION_SHEETS.0.count_ones(), 1);
1449 assert_ne!(Uses::EXTENSIONS, Uses::EXTENSION_SHEETS);
1450 let both = Uses::EXTENSIONS
1451 .with(Uses::EXTENSION_SHEETS)
1452 .with(Uses::CORE);
1453 assert_eq!(
1454 both.extension_bits(),
1455 Uses::EXTENSIONS.with(Uses::EXTENSION_SHEETS)
1456 );
1457 assert_eq!(both.without_extensions(), Uses::CORE);
1458 }
1459}