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) u64);
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    /// The chart paint stylesheet: no script, only the styles that chart marks share
302    /// beyond the plain ones: the colours of gradients, glow, draw and grow motion (off
303    /// when the reader asks for less motion), the points and columns of a sparkline, and
304    /// a progress bar drawn as a meter.
305    pub const CHART_PAINT: Self = Self(1 << 32);
306    /// The count-up module: a number that counts up to its value when it comes into
307    /// view. The value is written in the page, so it reads the same with no script and
308    /// when the reader asks for less motion.
309    pub const COUNT_UP: Self = Self(1 << 33);
310    /// The radial charts' stylesheet: no script, only the styles of rings, gauges and the
311    /// day clock: their tracks and arcs, the words in the middle sized by the ring, and the
312    /// size each takes from a screen width up.
313    pub const CHART_RADIAL: Self = Self(1 << 34);
314    /// The linear chart stylesheet: no script, only the styles of the meter, the mini
315    /// columns, the colour strip, the range scale and the trend indicator. The ones with
316    /// a tooltip link the charts module as well.
317    pub const CHART_LINEAR: Self = Self(1 << 35);
318    /// The grid charts stylesheet: no script of its own, only the styles of the calendar and
319    /// matrix heat maps and of the scatter plot, linked on a page that draws one. The charts
320    /// module moves between their cells and points.
321    pub const CHART_GRIDS: Self = Self(1 << 36);
322    /// The app blocks stylesheet: no script of its own, only the styles of a figure tile's
323    /// icon, unit, status and ring, the info tip, the chart skeletons, the breathing guide
324    /// and the dock, linked on a page that draws one. An info tip links the overlay module.
325    pub const APP_BLOCKS: Self = Self(1 << 37);
326    /// The marketing stylesheet: no script, only the styles of the blocks of a public site,
327    /// its header, hero, sections, pricing, questions, frames and footer, linked on a page
328    /// that draws one. A part of a block that needs a script, such as a form, loads its own.
329    pub const MARKETING: Self = Self(1 << 40);
330
331    /// Both sets together.
332    #[must_use]
333    pub const fn with(self, other: Self) -> Self {
334        Self(self.0 | other.0)
335    }
336
337    /// Whether every bit of `other` is here.
338    pub const fn has(self, other: Self) -> bool {
339        self.0 & other.0 == other.0
340    }
341
342    /// Whether any bit of `other` is here.
343    pub const fn meets(self, other: Self) -> bool {
344        self.0 & other.0 != 0
345    }
346
347    /// Whether this is [`Uses::NONE`].
348    pub const fn is_none(self) -> bool {
349        self.0 == 0
350    }
351}
352
353/// Whether `key` can be a hotkey: one character that a key types, neither a space
354/// nor a control character.
355pub(crate) fn valid_hotkey(key: &str) -> bool {
356    let mut chars = key.chars();
357    matches!((chars.next(), chars.next()), (Some(c), None) if !c.is_whitespace() && !c.is_control())
358}
359
360/// One attribute. Names are static, and written without escaping.
361#[derive(Clone, Debug, PartialEq, Eq)]
362pub struct Attr {
363    /// The name.
364    pub name: &'static str,
365    /// The value.
366    pub value: AttrValue,
367}
368
369/// An HTML element.
370#[derive(Clone, Debug)]
371pub struct Element {
372    pub(crate) tag: &'static str,
373    pub(crate) attrs: Vec<Attr>,
374    pub(crate) children: Vec<Node>,
375    pub(crate) uses: Uses,
376}
377
378/// Elements a page never writes through the tree: each loads something, runs
379/// something or moves the page. The head has its own writer, in `view`.
380fn is_refused_tag(tag: &str) -> bool {
381    [
382        "script", "style", "link", "meta", "base", "iframe", "object", "embed",
383    ]
384    .iter()
385    .any(|refused| refused.eq_ignore_ascii_case(tag))
386}
387
388/// An element named `tag`. A refused one comes out as a `div`.
389#[inline]
390pub fn el(tag: &'static str) -> Element {
391    let tag = if is_refused_tag(tag) {
392        debug_assert!(false, "`<{tag}>` is not allowed in a page's tree");
393        "div"
394    } else {
395        tag
396    };
397    Element {
398        tag,
399        attrs: Vec::new(),
400        children: Vec::new(),
401        uses: Uses::NONE,
402    }
403}
404
405/// Attributes that hold URLs: their values go through [`Href`].
406fn is_url_attr(name: &str) -> bool {
407    [
408        "href",
409        "src",
410        "action",
411        "formaction",
412        "poster",
413        "cite",
414        "ping",
415        "data",
416        "background",
417        "xlink:href",
418    ]
419    .iter()
420    .any(|url| url.eq_ignore_ascii_case(name))
421}
422
423/// Attributes that are never written: inline style and handlers break the
424/// content security policy, and `srcdoc` is a document in an attribute.
425fn is_refused_attr(name: &str) -> bool {
426    name.eq_ignore_ascii_case("style")
427        || name.eq_ignore_ascii_case("srcdoc")
428        || name
429            .as_bytes()
430            .get(..2)
431            .is_some_and(|start| start.eq_ignore_ascii_case(b"on"))
432}
433
434impl Element {
435    /// The element's tag name.
436    pub fn tag(&self) -> &'static str {
437        self.tag
438    }
439
440    /// The attributes, in order.
441    pub fn attrs(&self) -> &[Attr] {
442        &self.attrs
443    }
444
445    /// The children, in order.
446    pub fn child_nodes(&self) -> &[Node] {
447        &self.children
448    }
449
450    /// The value of attribute `name`, when set.
451    pub fn get(&self, name: &str) -> Option<&AttrValue> {
452        self.attrs
453            .iter()
454            .find(|attr| attr.name == name)
455            .map(|attr| &attr.value)
456    }
457
458    /// Sets attribute `name`. A URL attribute is checked like an [`Href`];
459    /// `style`, `srcdoc` and `on*` are dropped.
460    #[inline]
461    #[must_use]
462    pub fn attr(mut self, name: &'static str, value: impl Into<AttrValue>) -> Self {
463        if is_refused_attr(name) {
464            debug_assert!(
465                false,
466                "`{name}` is not allowed under the content security policy"
467            );
468            return self;
469        }
470        let mut value = value.into();
471        if is_url_attr(name)
472            && let Some(text) = value.as_text()
473        {
474            value = Href::from(text.as_ref()).into();
475        }
476        self.attrs.push(Attr { name, value });
477        self
478    }
479
480    /// Sets attribute `name` when `value` is `Some`.
481    #[inline]
482    #[must_use]
483    pub fn attr_opt(self, name: &'static str, value: Option<impl Into<AttrValue>>) -> Self {
484        match value {
485            Some(value) => self.attr(name, value),
486            None => self,
487        }
488    }
489
490    /// Sets an attribute with no value (`disabled`, `data-open`) when `on`.
491    #[inline]
492    #[must_use]
493    pub fn flag(mut self, name: &'static str, on: bool) -> Self {
494        if on && !is_refused_attr(name) {
495            self.attrs.push(Attr {
496                name,
497                value: AttrValue::Flag,
498            });
499        }
500        self
501    }
502
503    /// Sets `data-slot`: what this part is.
504    #[inline]
505    #[must_use]
506    pub fn slot(self, slot: &'static str) -> Self {
507        self.attr("data-slot", slot)
508    }
509
510    /// Sets `id`.
511    #[inline]
512    #[must_use]
513    pub fn id(self, id: impl Into<AttrValue>) -> Self {
514        self.attr("id", id)
515    }
516
517    /// Sets `href`, already checked.
518    #[inline]
519    #[must_use]
520    pub fn href(mut self, href: impl Into<Href>) -> Self {
521        self.attrs.push(Attr {
522            name: "href",
523            value: href.into().into(),
524        });
525        self
526    }
527
528    /// Says this link may be fetched ahead of a click, on hover or focus. Only mark
529    /// a link whose `GET` changes nothing: a request goes out with no click at all.
530    #[inline]
531    #[must_use]
532    pub fn prefetch(self) -> Self {
533        self.flag("data-ui-prefetch", true)
534    }
535
536    /// Says this link is fetched as soon as the page is quiet, with no hover: for the
537    /// one or two places a user almost always goes next. It costs that page's bytes on
538    /// every visit, so nothing is fetched this way unless a link asks; the runtime takes
539    /// at most four a page, and none on a slow or data-saving connection.
540    ///
541    /// It pays most for a page that is the same for every user and says so with
542    /// `View::cache("public, max-age=60")`. A page that differs per user stays
543    /// `no-store`, and what was fetched for it stands in for a click only for a few
544    /// seconds. Only mark a link whose `GET` changes nothing.
545    #[inline]
546    #[must_use]
547    pub fn prefetch_eager(self) -> Self {
548        self.attr("data-ui-prefetch", "eager")
549    }
550
551    /// Runs `commands` in the browser when this element is clicked, with no
552    /// request to the server.
553    #[must_use]
554    pub fn on_click(self, commands: impl Into<Commands>) -> Self {
555        self.on(crate::cmd::Trigger::Click, commands)
556    }
557
558    /// Runs `commands` in the browser when `trigger` happens on this element.
559    #[must_use]
560    ///
561    /// Called again for the same trigger, or after [`on_click`](Self::on_click), it adds to
562    /// the list: every command runs, in the order given.
563    pub fn on(mut self, trigger: crate::cmd::Trigger, commands: impl Into<Commands>) -> Self {
564        self.uses = self.uses.with(Uses::CORE);
565        let json = commands.into().to_json();
566        let name = trigger.attribute();
567        if let Some(attr) = self.attrs.iter_mut().find(|attr| attr.name == name) {
568            // Two lists the same code wrote, so one list is the first's items and then
569            // the second's.
570            let old = attr
571                .value
572                .as_text()
573                .map(|text| text.into_owned())
574                .unwrap_or_default();
575            let merged = match (old.as_str(), json.as_str()) {
576                ("" | "[]", _) => json,
577                (_, "[]") => old,
578                (old, new) => format!("{},{}", &old[..old.len() - 1], &new[1..]),
579            };
580            attr.value = AttrValue::Text(merged.into_boxed_str());
581            return self;
582        }
583        self.attrs.push(Attr {
584            name,
585            value: AttrValue::Text(json.into_boxed_str()),
586        });
587        self
588    }
589
590    /// Runs one command when clicked.
591    #[must_use]
592    pub fn on_click_one(self, command: Cmd) -> Self {
593        self.on_click(vec![command])
594    }
595
596    /// Says [`Cmd::fill`] writes the text of the row's cell in column `column` here: the
597    /// column of a [`DataTable`](crate::DataTable) by its field's name, or, in a list that
598    /// isn't a table, the row's element with that `data-col`. A hidden field gets it as
599    /// its value.
600    #[must_use]
601    pub fn fill_cell(self, column: &'static str) -> Self {
602        self.attr("data-ui-cell", column)
603    }
604
605    /// Lets [`Cmd::value`] set this hidden field: the state a set of buttons changes, such
606    /// as the column a form sorts by. A hidden field without it, such as a form's token or
607    /// method, can't be changed by a command.
608    #[must_use]
609    pub fn settable(self) -> Self {
610        self.flag("data-ui-value", true)
611    }
612
613    /// Says [`Cmd::fill`] writes the row's key here. A hidden field gets it as its value,
614    /// so a form in the dialog posts which row it acts on.
615    #[must_use]
616    pub fn fill_key(self) -> Self {
617        self.flag("data-ui-row-key", true)
618    }
619
620    /// Makes `key` a shortcut for this element: pressed anywhere on the page, it clicks
621    /// the element, or focuses it if it is a field. It never fires while someone types in
622    /// a field or edits text, while a modifier other than Shift is held, during an input
623    /// method's composition, or from outside a modal dialog that is open, so a single
624    /// letter is safe. `aria-keyshortcuts` tells assistive technology.
625    ///
626    /// A key is one character a keyboard types: a letter, a digit or a sign such as `/`
627    /// or `?` (uppercase letters mean Shift). Anything else, a space or a word, is
628    /// refused, and the element is left as it was. When two elements name the same key,
629    /// the first in the page that can take it does.
630    ///
631    /// ```
632    /// use navree_ui::{el, render};
633    ///
634    /// let html = render(&el("a").href("/inbox/8").hotkey("j").child("Next").into());
635    /// assert!(html.contains(r#"data-ui-hotkey="j""#));
636    /// assert!(html.contains(r#"aria-keyshortcuts="j""#));
637    /// ```
638    #[must_use]
639    pub fn hotkey(self, key: &str) -> Self {
640        if !valid_hotkey(key) {
641            return self;
642        }
643        self.attr("data-ui-hotkey", key.to_owned())
644            .attr("aria-keyshortcuts", key.to_owned())
645            .uses(Uses::KEYS)
646    }
647
648    /// Makes `key` a shortcut for this element, as [`hotkey`](Self::hotkey) does, that
649    /// works only while the focus is inside the element whose id is `scope`: for a key
650    /// that changes something, such as closing the conversation the reader is in, so it
651    /// can't act from anywhere on the page. An invalid key or scope leaves the element as
652    /// it was.
653    ///
654    /// Single keys need a way to be turned off for the people who can't use them (WCAG
655    /// 2.1.4): keep each person's choice, and draw no hotkeys for someone who turned them
656    /// off.
657    ///
658    /// ```
659    /// use navree_ui::{el, render};
660    ///
661    /// let html = render(&el("button").hotkey_within("e", "thread").child("Close").into());
662    /// assert!(html.contains(r#"data-ui-hotkey="e" aria-keyshortcuts="e" data-ui-hotkey-scope="thread""#));
663    /// ```
664    #[must_use]
665    pub fn hotkey_within(self, key: &str, scope: &str) -> Self {
666        let scope_ok = !scope.is_empty()
667            && scope.len() <= 64
668            && scope
669                .chars()
670                .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.'));
671        if !valid_hotkey(key) || !scope_ok {
672            return self;
673        }
674        self.hotkey(key)
675            .attr("data-ui-hotkey-scope", scope.to_owned())
676    }
677
678    /// Says this page must load `uses` when this element is on it.
679    #[inline]
680    #[must_use]
681    pub fn uses(mut self, uses: Uses) -> Self {
682        self.uses = self.uses.with(uses);
683        self
684    }
685
686    /// Adds one child.
687    #[inline]
688    #[must_use]
689    pub fn child(mut self, child: impl IntoNodes) -> Self {
690        child.push_into(&mut self.children);
691        self
692    }
693
694    /// Adds children: a tuple, a list, an `Option`, or one node.
695    #[inline]
696    #[must_use]
697    pub fn children(self, children: impl IntoNodes) -> Self {
698        self.child(children)
699    }
700
701    /// Reserves room for `count` more children, when you know how many.
702    #[inline]
703    #[must_use]
704    pub fn with_child_capacity(mut self, count: usize) -> Self {
705        self.children.reserve_exact(count);
706        self
707    }
708}
709
710impl From<Element> for Node {
711    #[inline]
712    fn from(element: Element) -> Self {
713        Self::Element(element)
714    }
715}
716
717impl From<&'static str> for Node {
718    #[inline]
719    fn from(text: &'static str) -> Self {
720        Self::Text(Cow::Borrowed(text))
721    }
722}
723
724impl From<String> for Node {
725    #[inline]
726    fn from(text: String) -> Self {
727        Self::Text(Cow::Owned(text))
728    }
729}
730
731impl From<Cow<'static, str>> for Node {
732    #[inline]
733    fn from(text: Cow<'static, str>) -> Self {
734        Self::Text(text)
735    }
736}
737
738impl From<i64> for Node {
739    #[inline]
740    fn from(value: i64) -> Self {
741        Self::Int(value)
742    }
743}
744
745impl From<SafeHtml> for Node {
746    fn from(html: SafeHtml) -> Self {
747        Self::Raw(html)
748    }
749}
750
751/// What can stand as children: one node, a tuple, a list, an `Option`.
752pub trait IntoNodes {
753    /// Appends the nodes to `out`.
754    fn push_into(self, out: &mut Vec<Node>);
755}
756
757impl<T: Into<Node>> IntoNodes for T {
758    #[inline]
759    fn push_into(self, out: &mut Vec<Node>) {
760        out.push(self.into());
761    }
762}
763
764impl<T: IntoNodes> IntoNodes for Vec<T> {
765    #[inline]
766    fn push_into(self, out: &mut Vec<Node>) {
767        out.reserve(self.len());
768        for item in self {
769            item.push_into(out);
770        }
771    }
772}
773
774impl<T: IntoNodes, const N: usize> IntoNodes for [T; N] {
775    #[inline]
776    fn push_into(self, out: &mut Vec<Node>) {
777        out.reserve(N);
778        for item in self {
779            item.push_into(out);
780        }
781    }
782}
783
784impl<T: IntoNodes> IntoNodes for Option<T> {
785    #[inline]
786    fn push_into(self, out: &mut Vec<Node>) {
787        if let Some(item) = self {
788            item.push_into(out);
789        }
790    }
791}
792
793macro_rules! tuples {
794    ($($name:ident)+) => {
795        impl<$($name: IntoNodes),+> IntoNodes for ($($name,)+) {
796            #[inline]
797            #[allow(non_snake_case)]
798            fn push_into(self, out: &mut Vec<Node>) {
799                let ($($name,)+) = self;
800                $($name.push_into(out);)+
801            }
802        }
803    };
804}
805
806tuples!(A);
807tuples!(A B);
808tuples!(A B C);
809tuples!(A B C D);
810tuples!(A B C D E);
811tuples!(A B C D E F);
812tuples!(A B C D E F G);
813tuples!(A B C D E F G H);
814tuples!(A B C D E F G H I);
815tuples!(A B C D E F G H I J);
816tuples!(A B C D E F G H I J K);
817tuples!(A B C D E F G H I J K L);
818
819/// Implements `From<$type> for Node` by calling the type's `into_node`.
820macro_rules! into_node {
821    ($($type:ty),+ $(,)?) => {
822        $(impl From<$type> for $crate::node::Node {
823            #[inline]
824            fn from(value: $type) -> Self {
825                value.into_node()
826            }
827        })+
828    };
829}
830pub(crate) use into_node;
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    #[test]
837    fn urls_in_attributes_are_checked() {
838        let element = el("a").attr("href", "javascript:alert(1)");
839        assert_eq!(element.get("href"), Some(&AttrValue::Text("#".into())));
840        let element = el("a").attr("href", "/ok".to_owned());
841        assert_eq!(element.get("href"), Some(&AttrValue::Text("/ok".into())));
842    }
843
844    #[test]
845    fn children_take_tuples_lists_and_options() {
846        let element =
847            el("div").children(("a", Some("b"), None::<&'static str>, vec!["c", "d"], 7_i64));
848        assert_eq!(element.child_nodes().len(), 5);
849        assert_eq!(Node::from(element).text_content(), "abcd7");
850    }
851
852    #[test]
853    fn commands_ask_for_the_core_runtime() {
854        assert!(el("div").uses.is_none());
855        let element = el("button").on_click_one(Cmd::toggle("menu"));
856        assert!(element.uses.has(Uses::CORE));
857    }
858
859    #[test]
860    fn a_hotkey_is_one_typed_character_and_loads_the_keys_module() {
861        for key in ["j", "K", "/", "?", "1", "é"] {
862            let element = el("a").hotkey(key);
863            assert_eq!(
864                element.get("data-ui-hotkey"),
865                Some(&AttrValue::Text(key.into()))
866            );
867            assert_eq!(
868                element.get("aria-keyshortcuts"),
869                Some(&AttrValue::Text(key.into()))
870            );
871            assert!(element.uses.has(Uses::KEYS));
872        }
873        for bad in ["", " ", "jk", "Enter", "\n", "\u{7}", "ctrl+k"] {
874            let element = el("a").hotkey(bad);
875            assert!(element.get("data-ui-hotkey").is_none(), "{bad:?}");
876            assert!(element.uses.is_none(), "{bad:?}");
877        }
878    }
879
880    #[test]
881    fn a_scoped_hotkey_names_its_scope_and_refuses_a_bad_one() {
882        let html = crate::render(&el("button").hotkey_within("e", "thread").into());
883        assert!(html.contains(r#"data-ui-hotkey="e""#), "{html}");
884        assert!(html.contains(r#"data-ui-hotkey-scope="thread""#), "{html}");
885        for bad in ["", "a b", "x\"y", &"z".repeat(65)] {
886            let html = crate::render(&el("button").hotkey_within("e", bad).into());
887            assert!(!html.contains("data-ui-hotkey"), "{bad}: {html}");
888        }
889        let html = crate::render(&el("button").hotkey_within("two", "thread").into());
890        assert!(!html.contains("data-ui-hotkey"), "{html}");
891    }
892
893    #[test]
894    fn the_new_modules_have_bits_of_their_own() {
895        let known = [
896            Uses::CORE,
897            Uses::SIDEBAR,
898            Uses::OVERLAY,
899            Uses::TABLE,
900            Uses::SELECT,
901            Uses::MENUS,
902            Uses::LIVE,
903            Uses::DATES,
904            Uses::PHONE,
905            Uses::THEME_BUILDER,
906            Uses::SLIDER,
907            Uses::TREE,
908            Uses::TOOLBAR,
909            Uses::SORTABLE,
910        ];
911        for module in [Uses::SPLIT, Uses::KEYS, Uses::LAZY] {
912            assert!(known.iter().all(|other| other.0 & module.0 == 0));
913        }
914        assert_eq!(Uses::SPLIT.0 & Uses::KEYS.0, 0);
915        assert_eq!((Uses::SPLIT.0 | Uses::KEYS.0) & Uses::LAZY.0, 0);
916    }
917
918    #[test]
919    fn the_markdown_upload_code_carousel_and_menu_bar_modules_have_bits_of_their_own() {
920        let older = [
921            Uses::CORE,
922            Uses::SIDEBAR,
923            Uses::OVERLAY,
924            Uses::TABLE,
925            Uses::SELECT,
926            Uses::MENUS,
927            Uses::LIVE,
928            Uses::DATES,
929            Uses::PHONE,
930            Uses::THEME_BUILDER,
931            Uses::SLIDER,
932            Uses::TREE,
933            Uses::TOOLBAR,
934            Uses::SORTABLE,
935            Uses::SPLIT,
936            Uses::KEYS,
937            Uses::LAZY,
938        ];
939        let newer = [
940            Uses::MARKDOWN,
941            Uses::UPLOAD,
942            Uses::OTP,
943            Uses::CAROUSEL,
944            Uses::MENUBAR,
945            Uses::PARTS,
946            Uses::PARTS_STYLES,
947            Uses::GENUI,
948        ];
949        for (at, module) in newer.iter().enumerate() {
950            assert_eq!(module.0.count_ones(), 1);
951            assert!(older.iter().all(|other| other.0 & module.0 == 0));
952            assert!(newer[at + 1..].iter().all(|other| other.0 & module.0 == 0));
953        }
954    }
955
956    #[test]
957    fn a_node_stays_small() {
958        // Children hold nodes inline, so one size change touches every page.
959        assert!(
960            std::mem::size_of::<Node>() <= 72,
961            "{}",
962            std::mem::size_of::<Node>()
963        );
964    }
965}