Skip to main content

navree_ui/
node.rs

1//! The tree every component builds: [`Node`], [`Element`] and the attribute
2//! contract.
3//!
4//! Components are plain structs with builder methods that turn into one
5//! non-generic [`Node`], so pages have one type and no generic bloat.
6//!
7//! **The attribute contract.** Style and behaviour meet at attributes:
8//! - `data-slot="button"`: what a part is. Set with [`Element::slot`].
9//! - `data-variant`, `data-size`, `data-tone`: a closed choice, from a Rust enum.
10//! - `data-open`, `data-checked`, `data-selected`, `data-disabled`,
11//!   `data-active`, `data-invalid`, `data-pending`: states, present or absent.
12//! - `data-ui-*`: the runtime's hooks.
13//!
14//! Attribute names are `&'static str`, so a request can't choose one. `style`,
15//! `srcdoc` and `on*` are refused in any case (the content security policy would
16//! block them anyway), URL attributes go through [`Href`], and elements that load
17//! or navigate (`script`, `style`, `link`, `meta`, `base`, `iframe`, `object`,
18//! `embed`) can't be built.
19
20use std::borrow::Cow;
21
22use crate::cmd::{Cmd, Commands};
23use crate::html::{Href, SafeHtml};
24
25/// One thing in a page.
26#[derive(Clone, Debug, Default)]
27pub enum Node {
28    /// Nothing.
29    #[default]
30    Empty,
31    /// Text, escaped when written.
32    Text(Cow<'static, str>),
33    /// An integer, written without allocating.
34    Int(i64),
35    /// Markup written as it is.
36    Raw(SafeHtml),
37    /// Compile-time markup written as it is, such as an icon's shapes.
38    Static(&'static str),
39    /// An element.
40    Element(Element),
41    /// Several nodes in a row.
42    Fragment(Vec<Node>),
43}
44
45/// Dropping a tree takes no stack per level: however deep an app built it from its
46/// data, a free walks an explicit list and can't overflow. Shallow nodes, nearly all
47/// of them, are the first check.
48impl 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    /// Whether this holds no children, so dropping it can't recurse.
71    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    /// The element this is, or nothing.
80    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    /// A text node.
88    pub fn text(text: impl Into<Cow<'static, str>>) -> Self {
89        Self::Text(text.into())
90    }
91
92    /// Several nodes in a row.
93    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    /// The text inside this node, as a user reads it.
100    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                // Tests read this: tags go, and the entities the escaping path writes.
111                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("&lt;", "<")
124                        .replace("&gt;", ">")
125                        .replace("&quot;", "\"")
126                        .replace("&#39;", "'")
127                        .replace("&amp;", "&"),
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/// An attribute's value.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub enum AttrValue {
149    /// Present with no value (`disabled`).
150    Flag,
151    /// Text known at compile time.
152    Static(&'static str),
153    /// Text, escaped when written.
154    Text(Box<str>),
155    /// An integer.
156    Int(i64),
157}
158
159impl AttrValue {
160    /// The value as text, when it has one (`None` for a flag).
161    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/// What a page must load for the elements in it: a small set of bits, so
211/// finding out allocates nothing.
212#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
213pub struct Uses(pub(crate) u32);
214
215impl Uses {
216    /// Nothing: the page ships no script.
217    pub const NONE: Self = Self(0);
218    /// The core runtime: commands, ops, morph, link boosting, pending states.
219    pub const CORE: Self = Self(1);
220    /// The sidebar module: collapse, `Ctrl/Cmd+B`, the phone sheet.
221    pub const SIDEBAR: Self = Self(1 << 1);
222    /// The overlay module: tooltip and hover card, placement where CSS can't.
223    pub const OVERLAY: Self = Self(1 << 2);
224    /// The table module: selection, resizing and reordering columns.
225    pub const TABLE: Self = Self(1 << 3);
226    /// The select module: Select, Combobox, MultiSelect and the command palette.
227    pub const SELECT: Self = Self(1 << 4);
228    /// The live module: regions and tables that fetch themselves again when a
229    /// server-sent event stream speaks.
230    pub const LIVE: Self = Self(1 << 6);
231    /// The dates module: calendars, range pickers and the calendar of a date picker.
232    pub const DATES: Self = Self(1 << 7);
233    /// The date box module: the box a person types a date in, read by the server's
234    /// rules in the page's language, with what it can't take said at the box.
235    pub const DATE_TEXT: Self = Self(1 << 26);
236    /// The time module: time pickers, their typed times and their list of times.
237    pub const TIME: Self = Self(1 << 25);
238    /// The menus module: the keys of tabs, toggle groups and dropdown menus, and
239    /// tab switching in the page.
240    pub const MENUS: Self = Self(1 << 5);
241    /// The phone module: the country list, formatting as you type and the
242    /// number in E.164.
243    pub const PHONE: Self = Self(1 << 8);
244    /// The theme builder's stylesheet: no script, only its styles, linked on a
245    /// page that draws the builder.
246    pub const THEME_BUILDER: Self = Self(1 << 9);
247    /// The charts module: tooltips, the crosshair and the keys that move through a
248    /// chart's values. Its stylesheet comes with it, and with a chart that is loading,
249    /// failed or empty.
250    pub const CHARTS: Self = Self(1 << 11);
251    /// The slider module: the filled part, the value as text, a gap between the
252    /// two thumbs of a range and a click on its track.
253    pub const SLIDER: Self = Self(1 << 12);
254    /// The tree module: the keys of a tree view, expanding, choosing and children
255    /// loaded as they are opened.
256    pub const TREE: Self = Self(1 << 13);
257    /// The toolbar module: one tab stop with the arrow keys, and what does not fit
258    /// moved into a menu.
259    pub const TOOLBAR: Self = Self(1 << 14);
260    /// The sortable module: lists and boards whose items move by pointer, touch
261    /// or keys, each move posted to the server.
262    pub const SORTABLE: Self = Self(1 << 15);
263    /// The split module: separators that resize panes by pointer and by the keys of
264    /// the window splitter pattern, collapsing panes, and saving the sizes.
265    pub const SPLIT: Self = Self(1 << 16);
266    /// The keys module: single-key shortcuts ([`Element::hotkey`]) that click or focus
267    /// what names them, never while someone types.
268    pub const KEYS: Self = Self(1 << 17);
269    /// The lazy module: lists that load pages by cursor as they are read, keep the
270    /// reader's place, drop what is far off screen, and merge live changes.
271    pub const LAZY: Self = Self(1 << 18);
272    /// The markdown stylesheet: no script, only the styles of rendered Markdown and of
273    /// a highlighted code block, linked on a page that draws one.
274    pub const MARKDOWN: Self = Self(1 << 19);
275    /// The upload module: a drop area, a list of the chosen files, progress over a
276    /// plain form post, and large files sent in chunks. Its stylesheet comes with it.
277    pub const UPLOAD: Self = Self(1 << 20);
278    /// The one-time code module: digits only, a pasted code cleaned, and a form sent
279    /// when the code is whole. Its stylesheet comes with it.
280    pub const OTP: Self = Self(1 << 21);
281    /// The carousel module: the buttons, the slide pickers, the keys of the pattern and
282    /// automatic rotation that stops for the reader. Its stylesheet comes with it.
283    pub const CAROUSEL: Self = Self(1 << 22);
284    /// The menu bar module: context menus, menu bars and the navigation menu, on the
285    /// dropdown menu's own popups. Its stylesheet comes with it.
286    pub const MENUBAR: Self = Self(1 << 23);
287    /// The islands module: imports the script of each [`Island`](crate::Island) on the
288    /// page, mounts it, gives it new props and lets it go when it leaves.
289    pub const ISLAND: Self = Self(1 << 10);
290    /// The parts module: the colour picker keeping its fields and swatches in step, a
291    /// clear button, a checkbox that is indeterminate and an avatar whose picture did not
292    /// load. Its stylesheet is [`Uses::PARTS_STYLES`].
293    pub const PARTS: Self = Self(1 << 28);
294    /// The parts stylesheet: no script, only the styles of the parts that need none, such
295    /// as an avatar group, a trace, a questionnaire, an alert's close button and actions,
296    /// and a sparkline in a table cell.
297    pub const PARTS_STYLES: Self = Self(1 << 29);
298    /// The conversation module: Enter sends from a composer, and a conversation the
299    /// reader is at the end of stays there while an answer grows.
300    pub const GENUI: Self = Self(1 << 24);
301
302    /// Both sets together.
303    #[must_use]
304    pub const fn with(self, other: Self) -> Self {
305        Self(self.0 | other.0)
306    }
307
308    /// Whether every bit of `other` is here.
309    pub const fn has(self, other: Self) -> bool {
310        self.0 & other.0 == other.0
311    }
312
313    /// Whether any bit of `other` is here.
314    pub const fn meets(self, other: Self) -> bool {
315        self.0 & other.0 != 0
316    }
317
318    /// Whether this is [`Uses::NONE`].
319    pub const fn is_none(self) -> bool {
320        self.0 == 0
321    }
322}
323
324/// Whether `key` can be a hotkey: one character that a key types, neither a space
325/// nor a control character.
326pub(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/// One attribute. Names are static, and written without escaping.
332#[derive(Clone, Debug, PartialEq, Eq)]
333pub struct Attr {
334    /// The name.
335    pub name: &'static str,
336    /// The value.
337    pub value: AttrValue,
338}
339
340/// An HTML element.
341#[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
349/// Elements a page never writes through the tree: each loads something, runs
350/// something or moves the page. The head has its own writer, in `view`.
351fn 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/// An element named `tag`. A refused one comes out as a `div`.
360#[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
376/// Attributes that hold URLs: their values go through [`Href`].
377fn 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
394/// Attributes that are never written: inline style and handlers break the
395/// content security policy, and `srcdoc` is a document in an attribute.
396fn 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    /// The element's tag name.
407    pub fn tag(&self) -> &'static str {
408        self.tag
409    }
410
411    /// The attributes, in order.
412    pub fn attrs(&self) -> &[Attr] {
413        &self.attrs
414    }
415
416    /// The children, in order.
417    pub fn child_nodes(&self) -> &[Node] {
418        &self.children
419    }
420
421    /// The value of attribute `name`, when set.
422    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    /// Sets attribute `name`. A URL attribute is checked like an [`Href`];
430    /// `style`, `srcdoc` and `on*` are dropped.
431    #[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    /// Sets attribute `name` when `value` is `Some`.
452    #[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    /// Sets an attribute with no value (`disabled`, `data-open`) when `on`.
462    #[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    /// Sets `data-slot`: what this part is.
475    #[inline]
476    #[must_use]
477    pub fn slot(self, slot: &'static str) -> Self {
478        self.attr("data-slot", slot)
479    }
480
481    /// Sets `id`.
482    #[inline]
483    #[must_use]
484    pub fn id(self, id: impl Into<AttrValue>) -> Self {
485        self.attr("id", id)
486    }
487
488    /// Sets `href`, already checked.
489    #[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    /// Says this link may be fetched ahead of a click, on hover or focus. Only mark
500    /// a link whose `GET` changes nothing: a request goes out with no click at all.
501    #[inline]
502    #[must_use]
503    pub fn prefetch(self) -> Self {
504        self.flag("data-ui-prefetch", true)
505    }
506
507    /// Says this link is fetched as soon as the page is quiet, with no hover: for the
508    /// one or two places a user almost always goes next. It costs that page's bytes on
509    /// every visit, so nothing is fetched this way unless a link asks; the runtime takes
510    /// at most four a page, and none on a slow or data-saving connection.
511    ///
512    /// It pays most for a page that is the same for every user and says so with
513    /// `View::cache("public, max-age=60")`. A page that differs per user stays
514    /// `no-store`, and what was fetched for it stands in for a click only for a few
515    /// seconds. Only mark a link whose `GET` changes nothing.
516    #[inline]
517    #[must_use]
518    pub fn prefetch_eager(self) -> Self {
519        self.attr("data-ui-prefetch", "eager")
520    }
521
522    /// Runs `commands` in the browser when this element is clicked, with no
523    /// request to the server.
524    #[must_use]
525    pub fn on_click(self, commands: impl Into<Commands>) -> Self {
526        self.on(crate::cmd::Trigger::Click, commands)
527    }
528
529    /// Runs `commands` in the browser when `trigger` happens on this element.
530    #[must_use]
531    ///
532    /// Called again for the same trigger, or after [`on_click`](Self::on_click), it adds to
533    /// the list: every command runs, in the order given.
534    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            // Two lists the same code wrote, so one list is the first's items and then
540            // the second's.
541            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    /// Runs one command when clicked.
562    #[must_use]
563    pub fn on_click_one(self, command: Cmd) -> Self {
564        self.on_click(vec![command])
565    }
566
567    /// Says [`Cmd::fill`] writes the text of the row's cell in column `column` here: the
568    /// column of a [`DataTable`](crate::DataTable) by its field's name, or, in a list that
569    /// isn't a table, the row's element with that `data-col`. A hidden field gets it as
570    /// its value.
571    #[must_use]
572    pub fn fill_cell(self, column: &'static str) -> Self {
573        self.attr("data-ui-cell", column)
574    }
575
576    /// Lets [`Cmd::value`] set this hidden field: the state a set of buttons changes, such
577    /// as the column a form sorts by. A hidden field without it, such as a form's token or
578    /// method, can't be changed by a command.
579    #[must_use]
580    pub fn settable(self) -> Self {
581        self.flag("data-ui-value", true)
582    }
583
584    /// Says [`Cmd::fill`] writes the row's key here. A hidden field gets it as its value,
585    /// so a form in the dialog posts which row it acts on.
586    #[must_use]
587    pub fn fill_key(self) -> Self {
588        self.flag("data-ui-row-key", true)
589    }
590
591    /// Makes `key` a shortcut for this element: pressed anywhere on the page, it clicks
592    /// the element, or focuses it if it is a field. It never fires while someone types in
593    /// a field or edits text, while a modifier other than Shift is held, during an input
594    /// method's composition, or from outside a modal dialog that is open, so a single
595    /// letter is safe. `aria-keyshortcuts` tells assistive technology.
596    ///
597    /// A key is one character a keyboard types: a letter, a digit or a sign such as `/`
598    /// or `?` (uppercase letters mean Shift). Anything else, a space or a word, is
599    /// refused, and the element is left as it was. When two elements name the same key,
600    /// the first in the page that can take it does.
601    ///
602    /// ```
603    /// use navree_ui::{el, render};
604    ///
605    /// let html = render(&el("a").href("/inbox/8").hotkey("j").child("Next").into());
606    /// assert!(html.contains(r#"data-ui-hotkey="j""#));
607    /// assert!(html.contains(r#"aria-keyshortcuts="j""#));
608    /// ```
609    #[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    /// Makes `key` a shortcut for this element, as [`hotkey`](Self::hotkey) does, that
620    /// works only while the focus is inside the element whose id is `scope`: for a key
621    /// that changes something, such as closing the conversation the reader is in, so it
622    /// can't act from anywhere on the page. An invalid key or scope leaves the element as
623    /// it was.
624    ///
625    /// Single keys need a way to be turned off for the people who can't use them (WCAG
626    /// 2.1.4): keep each person's choice, and draw no hotkeys for someone who turned them
627    /// off.
628    ///
629    /// ```
630    /// use navree_ui::{el, render};
631    ///
632    /// let html = render(&el("button").hotkey_within("e", "thread").child("Close").into());
633    /// assert!(html.contains(r#"data-ui-hotkey="e" aria-keyshortcuts="e" data-ui-hotkey-scope="thread""#));
634    /// ```
635    #[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    /// Says this page must load `uses` when this element is on it.
650    #[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    /// Adds one child.
658    #[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    /// Adds children: a tuple, a list, an `Option`, or one node.
666    #[inline]
667    #[must_use]
668    pub fn children(self, children: impl IntoNodes) -> Self {
669        self.child(children)
670    }
671
672    /// Reserves room for `count` more children, when you know how many.
673    #[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
722/// What can stand as children: one node, a tuple, a list, an `Option`.
723pub trait IntoNodes {
724    /// Appends the nodes to `out`.
725    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
790/// Implements `From<$type> for Node` by calling the type's `into_node`.
791macro_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        // Children hold nodes inline, so one size change touches every page.
930        assert!(
931            std::mem::size_of::<Node>() <= 72,
932            "{}",
933            std::mem::size_of::<Node>()
934        );
935    }
936}