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 serde::Serialize;
23
24use crate::cmd::{Cmd, Commands};
25use crate::extension::UiExtension;
26use crate::html::{Href, LocalHref, SafeHtml};
27
28/// One thing in a page.
29#[derive(Clone, Debug, Default)]
30pub enum Node {
31    /// Nothing.
32    #[default]
33    Empty,
34    /// Text, escaped when written.
35    Text(Cow<'static, str>),
36    /// An integer, written without allocating.
37    Int(i64),
38    /// Markup written as it is.
39    Raw(SafeHtml),
40    /// Compile-time markup written as it is, such as an icon's shapes.
41    Static(&'static str),
42    /// An element.
43    Element(Element),
44    /// Several nodes in a row.
45    Fragment(Vec<Node>),
46}
47
48/// Dropping a tree takes no stack per level: however deep an app built it from its
49/// data, a free walks an explicit list and can't overflow. Shallow nodes, nearly all
50/// of them, are the first check.
51impl 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    /// Whether this holds no children, so dropping it can't recurse.
74    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    /// The element this is, or nothing.
83    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    /// A text node.
91    pub fn text(text: impl Into<Cow<'static, str>>) -> Self {
92        Self::Text(text.into())
93    }
94
95    /// Several nodes in a row.
96    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    /// The text inside this node, as a user reads it.
103    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                // Tests read this: tags go, and the entities the escaping path writes.
114                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("&lt;", "<")
127                        .replace("&gt;", ">")
128                        .replace("&quot;", "\"")
129                        .replace("&#39;", "'")
130                        .replace("&amp;", "&"),
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/// An attribute's value.
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub enum AttrValue {
152    /// Present with no value (`disabled`).
153    Flag,
154    /// Text known at compile time.
155    Static(&'static str),
156    /// Text, escaped when written.
157    Text(Box<str>),
158    /// An integer.
159    Int(i64),
160}
161
162impl AttrValue {
163    /// The value as text, when it has one (`None` for a flag).
164    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/// What a page must load for the elements in it: a small set of bits, so
214/// finding out allocates nothing.
215#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
216pub struct Uses(pub(crate) u64);
217
218impl Uses {
219    /// Nothing: the page ships no script.
220    pub const NONE: Self = Self(0);
221    /// The core runtime: commands, ops, morph, link boosting, pending states.
222    pub const CORE: Self = Self(1);
223    /// The sidebar module: collapse, `Ctrl/Cmd+B`, the phone sheet.
224    pub const SIDEBAR: Self = Self(1 << 1);
225    /// The overlay module: tooltip and hover card, placement where CSS can't.
226    pub const OVERLAY: Self = Self(1 << 2);
227    /// The table module: selection, resizing and reordering columns.
228    pub const TABLE: Self = Self(1 << 3);
229    /// The select module: Select, Combobox, MultiSelect and the command palette.
230    pub const SELECT: Self = Self(1 << 4);
231    /// The live module: regions and tables that fetch themselves again when a
232    /// server-sent event stream speaks.
233    pub const LIVE: Self = Self(1 << 6);
234    /// The dates module: calendars, range pickers and the calendar of a date picker.
235    pub const DATES: Self = Self(1 << 7);
236    /// The date box module: the box a person types a date in, read by the server's
237    /// rules in the page's language, with what it can't take said at the box.
238    pub const DATE_TEXT: Self = Self(1 << 26);
239    /// The time module: time pickers, their typed times and their list of times.
240    pub const TIME: Self = Self(1 << 25);
241    /// The menus module: the keys of tabs, toggle groups and dropdown menus, and
242    /// tab switching in the page.
243    pub const MENUS: Self = Self(1 << 5);
244    /// The phone module: the country list, formatting as you type and the
245    /// number in E.164.
246    pub const PHONE: Self = Self(1 << 8);
247    /// The theme builder's stylesheet: no script, only its styles, linked on a
248    /// page that draws the builder.
249    pub const THEME_BUILDER: Self = Self(1 << 9);
250    /// The charts module: tooltips, the crosshair and the keys that move through a
251    /// chart's values. Its stylesheet comes with it, and with a chart that is loading,
252    /// failed or empty.
253    pub const CHARTS: Self = Self(1 << 11);
254    /// The slider module: the filled part, the value as text, a gap between the
255    /// two thumbs of a range and a click on its track.
256    pub const SLIDER: Self = Self(1 << 12);
257    /// The tree module: the keys of a tree view, expanding, choosing and children
258    /// loaded as they are opened.
259    pub const TREE: Self = Self(1 << 13);
260    /// The toolbar module: one tab stop with the arrow keys, and what does not fit
261    /// moved into a menu.
262    pub const TOOLBAR: Self = Self(1 << 14);
263    /// The sortable module: lists and boards whose items move by pointer, touch
264    /// or keys, each move posted to the server.
265    pub const SORTABLE: Self = Self(1 << 15);
266    /// The split module: separators that resize panes by pointer and by the keys of
267    /// the window splitter pattern, collapsing panes, and saving the sizes.
268    pub const SPLIT: Self = Self(1 << 16);
269    /// The keys module: single-key shortcuts ([`Element::hotkey`]) that click or focus
270    /// what names them, never while someone types.
271    pub const KEYS: Self = Self(1 << 17);
272    /// The lazy module: lists that load pages by cursor as they are read, keep the
273    /// reader's place, drop what is far off screen, and merge live changes.
274    pub const LAZY: Self = Self(1 << 18);
275    /// The markdown stylesheet: no script, only the styles of rendered Markdown and of
276    /// a highlighted code block, linked on a page that draws one.
277    pub const MARKDOWN: Self = Self(1 << 19);
278    /// The upload module: a drop area, a list of the chosen files, progress over a
279    /// plain form post, and large files sent in chunks. Its stylesheet comes with it.
280    pub const UPLOAD: Self = Self(1 << 20);
281    /// The one-time code module: digits only, a pasted code cleaned, and a form sent
282    /// when the code is whole. Its stylesheet comes with it.
283    pub const OTP: Self = Self(1 << 21);
284    /// The carousel module: the buttons, the slide pickers, the keys of the pattern and
285    /// automatic rotation that stops for the reader. Its stylesheet comes with it.
286    pub const CAROUSEL: Self = Self(1 << 22);
287    /// The menu bar module: context menus, menu bars and the navigation menu, on the
288    /// dropdown menu's own popups. Its stylesheet comes with it.
289    pub const MENUBAR: Self = Self(1 << 23);
290    /// The islands module: imports the script of each [`Island`](crate::Island) on the
291    /// page, mounts it, gives it new props and lets it go when it leaves.
292    pub const ISLAND: Self = Self(1 << 10);
293    /// The parts module: the colour picker keeping its fields and swatches in step, a
294    /// clear button, a checkbox that is indeterminate and an avatar whose picture did not
295    /// load. Its stylesheet is [`Uses::PARTS_STYLES`].
296    pub const PARTS: Self = Self(1 << 28);
297    /// The parts stylesheet: no script, only the styles of the parts that need none, such
298    /// as an avatar group, a trace, a questionnaire, an alert's close button and actions,
299    /// and a sparkline in a table cell.
300    pub const PARTS_STYLES: Self = Self(1 << 29);
301    /// The conversation module: Enter sends from a composer, and a conversation the
302    /// reader is at the end of stays there while an answer grows.
303    pub const GENUI: Self = Self(1 << 24);
304    /// The chart paint stylesheet: no script, only the styles that chart marks share
305    /// beyond the plain ones: the colours of gradients, glow, draw and grow motion (off
306    /// when the reader asks for less motion), the points and columns of a sparkline, and
307    /// a progress bar drawn as a meter.
308    pub const CHART_PAINT: Self = Self(1 << 32);
309    /// The count-up module: a number that counts up to its value when it comes into
310    /// view. The value is written in the page, so it reads the same with no script and
311    /// when the reader asks for less motion.
312    pub const COUNT_UP: Self = Self(1 << 33);
313    /// The radial charts' stylesheet: no script, only the styles of rings, gauges and the
314    /// day clock: their tracks and arcs, the words in the middle sized by the ring, and the
315    /// size each takes from a screen width up.
316    pub const CHART_RADIAL: Self = Self(1 << 34);
317    /// The linear chart stylesheet: no script, only the styles of the meter, the mini
318    /// columns, the colour strip, the range scale and the trend indicator. The ones with
319    /// a tooltip link the charts module as well.
320    pub const CHART_LINEAR: Self = Self(1 << 35);
321    /// The grid charts stylesheet: no script of its own, only the styles of the calendar and
322    /// matrix heat maps and of the scatter plot, linked on a page that draws one. The charts
323    /// module moves between their cells and points.
324    pub const CHART_GRIDS: Self = Self(1 << 36);
325    /// The app blocks stylesheet: no script of its own, only the styles of a figure tile's
326    /// icon, unit, status and ring, the info tip, the chart skeletons, the breathing guide
327    /// and the dock, linked on a page that draws one. An info tip links the overlay module.
328    pub const APP_BLOCKS: Self = Self(1 << 37);
329    /// The marketing stylesheet: no script, only the styles of the blocks of a public site,
330    /// its header, hero, sections, pricing, questions, frames and footer, linked on a page
331    /// that draws one. A part of a block that needs a script, such as a form, loads its own.
332    pub const MARKETING: Self = Self(1 << 40);
333    /// The sortable grid module: tiles that move by pointer, touch or keys and are taken
334    /// away, with the whole order posted a moment after the last change. Its stylesheet is
335    /// [`Uses::SORTABLE_GRID_STYLES`].
336    pub const SORTABLE_GRID: Self = Self(1 << 41);
337    /// The sortable grid's stylesheet: the grid, its tiles and their tools, linked with
338    /// every sortable grid, one that doesn't move too.
339    pub const SORTABLE_GRID_STYLES: Self = Self(1 << 42);
340    /// The extensions module: mounts the scripts elements name, links sheets that arrive
341    /// later, and seals what a script draws. It needs the core runtime.
342    pub const EXTENSIONS: Self = Self(1 << 43);
343    /// No script: the head links the stylesheets the page's elements name.
344    pub const EXTENSION_SHEETS: Self = Self(1 << 44);
345
346    /// Both sets together.
347    #[must_use]
348    pub const fn with(self, other: Self) -> Self {
349        Self(self.0 | other.0)
350    }
351
352    /// Whether every bit of `other` is here.
353    pub const fn has(self, other: Self) -> bool {
354        self.0 & other.0 == other.0
355    }
356
357    /// Whether any bit of `other` is here.
358    pub const fn meets(self, other: Self) -> bool {
359        self.0 & other.0 != 0
360    }
361
362    /// Whether this is [`Uses::NONE`].
363    pub const fn is_none(self) -> bool {
364        self.0 == 0
365    }
366
367    /// The extension bits of these, and nothing else.
368    pub(crate) const fn extension_bits(self) -> Self {
369        Self(self.0 & (Self::EXTENSIONS.0 | Self::EXTENSION_SHEETS.0))
370    }
371
372    /// These without the extension bits.
373    pub(crate) const fn without_extensions(self) -> Self {
374        Self(self.0 & !(Self::EXTENSIONS.0 | Self::EXTENSION_SHEETS.0))
375    }
376}
377
378/// Whether `key` can be a hotkey: one character that a key types, neither a space
379/// nor a control character.
380pub(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/// One attribute. Names are static, and written without escaping.
386#[derive(Clone, Debug, PartialEq, Eq)]
387pub struct Attr {
388    /// The name.
389    pub name: &'static str,
390    /// The value.
391    pub value: AttrValue,
392}
393
394/// An HTML element.
395#[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
403/// Elements a page never writes through the tree: each loads something, runs
404/// something or moves the page. The head has its own writer, in `view`.
405fn 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/// An element named `tag`. A refused one comes out as a `div`.
414#[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
430/// Attributes that hold URLs: their values go through [`Href`].
431fn 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
448/// Attributes that are never written: inline style and handlers break the
449/// content security policy, and `srcdoc` is a document in an attribute.
450fn 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
459/// Whether `path` holds an encoded slash or backslash (`%2f` or `%5c`, in any case).
460fn has_encoded_slash(path: &str) -> bool {
461    path.as_bytes()
462        .windows(3)
463        .any(|window| window.eq_ignore_ascii_case(b"%2f") || window.eq_ignore_ascii_case(b"%5c"))
464}
465
466/// Whether `path` holds a `.` or `..` segment, written plainly or with `%2e` in any case.
467fn has_dot_segment(path: &str) -> bool {
468    path.split('/').any(|segment| {
469        if segment == "." || segment == ".." {
470            return true;
471        }
472        if !segment.contains('%') || segment.len() > 6 {
473            return false;
474        }
475        let bytes = segment.as_bytes();
476        let mut dots = 0_usize;
477        let mut i = 0;
478        while i < bytes.len() {
479            if bytes[i] == b'.' {
480                dots += 1;
481                i += 1;
482            } else if bytes
483                .get(i..i + 3)
484                .is_some_and(|esc| esc.eq_ignore_ascii_case(b"%2e"))
485            {
486                dots += 1;
487                i += 3;
488            } else {
489                return false;
490            }
491        }
492        dots == 1 || dots == 2
493    })
494}
495
496impl Element {
497    /// Says how the screen this link leads to is presented by a native client, when the
498    /// page knows: a form to fill in is a [`Task`](crate::Presented::Task), a record to
499    /// glance at is a [`Sheet`](crate::Presented::Sheet). Without it the shell's routes
500    /// decide. It writes no HTML: a browser's page is the page it was.
501    ///
502    /// ```
503    /// use navree_ui::{Presented, el, render};
504    ///
505    /// let link = el("a").href("/orders/new").child("New order").presented(Presented::Task);
506    /// assert_eq!(render(&link.into()), r#"<a href="/orders/new">New order</a>"#);
507    /// ```
508    #[cfg_attr(not(feature = "native-preview"), allow(unused_variables, unused_mut))]
509    pub fn presented(mut self, how: crate::Presented) -> Self {
510        #[cfg(feature = "native-preview")]
511        self.say(|hints| hints.presented = Some(how));
512        self
513    }
514
515    /// Says what a tap on this control starts on the device of a native app, in place of
516    /// what the control does in a browser: a passkey in the system's own sheet where a
517    /// browser goes to the passkey page. See [`NativeCall`](crate::NativeCall).
518    ///
519    /// The call is written only for a native client whose app can start it
520    /// ([`native_client_with`](crate::native_client_with) says which: it lists the call's
521    /// feature among its capabilities, and for a passkey `passkey_options` too), and only
522    /// when every path of the call is one on this site.
523    /// Every other client gets the control as it is, and so does a browser: it writes no
524    /// HTML. A link keeps its address as what the client does where its build can't start
525    /// the call after all.
526    ///
527    /// ```
528    /// use navree_ui::{NativeCall, NativeThen, el, render};
529    ///
530    /// let call = NativeCall::passkey_sign_in(
531    ///     "/sign-in/passkey/native/options",
532    ///     NativeThen::new("/sign-in/passkey/native", "sealed-by-the-server", 1_794_000_000),
533    /// );
534    /// let link = el("a").href("/sign-in/passkey").child("Sign in with a passkey").native_call(call);
535    /// assert_eq!(
536    ///     render(&link.into()),
537    ///     r#"<a href="/sign-in/passkey">Sign in with a passkey</a>"#
538    /// );
539    /// ```
540    #[cfg_attr(not(feature = "native-preview"), allow(unused_variables, unused_mut))]
541    pub fn native_call(mut self, call: crate::NativeCall) -> Self {
542        #[cfg(feature = "native-preview")]
543        if let Some(device) = call.for_the_client() {
544            self.say(|hints| hints.device = Some(device));
545        }
546        self
547    }
548
549    /// Sets a hint for a native client, when one is asking. What is said is kept with the
550    /// request, and the element carries its key as a child that writes nothing (a
551    /// zero-length slice of a text of the toolkit's own), so an element is no larger and
552    /// the HTML is the HTML of the element without it.
553    #[cfg(feature = "native-preview")]
554    pub(crate) fn say(&mut self, set: impl FnOnce(&mut crate::hint::Hints)) {
555        let Some(request) = crate::native::scope::native() else {
556            return;
557        };
558        let held = self.children.iter().find_map(crate::hint::key_of);
559        let key = request.hint(held.unwrap_or(0), set);
560        if held.is_none()
561            && let Some(mark) = crate::hint::key_mark(key)
562        {
563            self.children.push(mark);
564        }
565    }
566
567    /// What was said of this element to the native client the current request is from.
568    #[cfg(feature = "native-preview")]
569    pub(crate) fn said(&self) -> Option<crate::hint::Hints> {
570        let key = self.children.iter().find_map(crate::hint::key_of)?;
571        crate::native::scope::native()?.hinted(key)
572    }
573
574    /// The element's tag name.
575    pub fn tag(&self) -> &'static str {
576        self.tag
577    }
578
579    /// The attributes, in order.
580    pub fn attrs(&self) -> &[Attr] {
581        &self.attrs
582    }
583
584    /// The children, in order.
585    pub fn child_nodes(&self) -> &[Node] {
586        &self.children
587    }
588
589    /// The value of attribute `name`, when set.
590    pub fn get(&self, name: &str) -> Option<&AttrValue> {
591        self.attrs
592            .iter()
593            .find(|attr| attr.name == name)
594            .map(|attr| &attr.value)
595    }
596
597    /// Sets attribute `name`. A URL attribute is checked like an [`Href`];
598    /// `style`, `srcdoc` and `on*` are dropped.
599    #[inline]
600    #[must_use]
601    pub fn attr(mut self, name: &'static str, value: impl Into<AttrValue>) -> Self {
602        if is_refused_attr(name) {
603            debug_assert!(
604                false,
605                "`{name}` is not allowed under the content security policy"
606            );
607            return self;
608        }
609        let mut value = value.into();
610        if is_url_attr(name)
611            && let Some(text) = value.as_text()
612        {
613            value = Href::from(text.as_ref()).into();
614        }
615        self.attrs.push(Attr { name, value });
616        self
617    }
618
619    /// Sets attribute `name` when `value` is `Some`.
620    #[inline]
621    #[must_use]
622    pub fn attr_opt(self, name: &'static str, value: Option<impl Into<AttrValue>>) -> Self {
623        match value {
624            Some(value) => self.attr(name, value),
625            None => self,
626        }
627    }
628
629    /// Sets an attribute with no value (`disabled`, `data-open`) when `on`.
630    #[inline]
631    #[must_use]
632    pub fn flag(mut self, name: &'static str, on: bool) -> Self {
633        if on && !is_refused_attr(name) {
634            self.attrs.push(Attr {
635                name,
636                value: AttrValue::Flag,
637            });
638        }
639        self
640    }
641
642    /// Sets `data-slot`: what this part is.
643    #[inline]
644    #[must_use]
645    pub fn slot(self, slot: &'static str) -> Self {
646        self.attr("data-slot", slot)
647    }
648
649    /// Sets `id`.
650    #[inline]
651    #[must_use]
652    pub fn id(self, id: impl Into<AttrValue>) -> Self {
653        self.attr("id", id)
654    }
655
656    /// Sets `href`, already checked.
657    #[inline]
658    #[must_use]
659    pub fn href(mut self, href: impl Into<Href>) -> Self {
660        self.attrs.push(Attr {
661            name: "href",
662            value: href.into().into(),
663        });
664        self
665    }
666
667    /// Says this link may be fetched ahead of a click, on hover or focus. Only mark
668    /// a link whose `GET` changes nothing: a request goes out with no click at all.
669    #[inline]
670    #[must_use]
671    pub fn prefetch(self) -> Self {
672        self.flag("data-ui-prefetch", true)
673    }
674
675    /// Says this link is fetched as soon as the page is quiet, with no hover: for the
676    /// one or two places a user almost always goes next. It costs that page's bytes on
677    /// every visit, so nothing is fetched this way unless a link asks; the runtime takes
678    /// at most four a page, and none on a slow or data-saving connection.
679    ///
680    /// It pays most for a page that is the same for every user and says so with
681    /// `View::cache("public, max-age=60")`. A page that differs per user stays
682    /// `no-store`, and what was fetched for it stands in for a click only for a few
683    /// seconds. Only mark a link whose `GET` changes nothing.
684    #[inline]
685    #[must_use]
686    pub fn prefetch_eager(self) -> Self {
687        self.attr("data-ui-prefetch", "eager")
688    }
689
690    /// Runs `commands` in the browser when this element is clicked, with no
691    /// request to the server.
692    #[must_use]
693    pub fn on_click(self, commands: impl Into<Commands>) -> Self {
694        self.on(crate::cmd::Trigger::Click, commands)
695    }
696
697    /// Runs `commands` in the browser when `trigger` happens on this element.
698    #[must_use]
699    ///
700    /// Called again for the same trigger, or after [`on_click`](Self::on_click), it adds to
701    /// the list: every command runs, in the order given.
702    pub fn on(mut self, trigger: crate::cmd::Trigger, commands: impl Into<Commands>) -> Self {
703        self.uses = self.uses.with(Uses::CORE);
704        let json = commands.into().to_json();
705        let name = trigger.attribute();
706        if let Some(attr) = self.attrs.iter_mut().find(|attr| attr.name == name) {
707            // Two lists the same code wrote, so one list is the first's items and then
708            // the second's.
709            let old = attr
710                .value
711                .as_text()
712                .map(|text| text.into_owned())
713                .unwrap_or_default();
714            let merged = match (old.as_str(), json.as_str()) {
715                ("" | "[]", _) => json,
716                (_, "[]") => old,
717                (old, new) => format!("{},{}", &old[..old.len() - 1], &new[1..]),
718            };
719            attr.value = AttrValue::Text(merged.into_boxed_str());
720            return self;
721        }
722        self.attrs.push(Attr {
723            name,
724            value: AttrValue::Text(json.into_boxed_str()),
725        });
726        self
727    }
728
729    /// Runs one command when clicked.
730    #[must_use]
731    pub fn on_click_one(self, command: Cmd) -> Self {
732        self.on_click(vec![command])
733    }
734
735    /// Says [`Cmd::fill`] writes the text of the row's cell in column `column` here: the
736    /// column of a [`DataTable`](crate::DataTable) by its field's name, or, in a list that
737    /// isn't a table, the row's element with that `data-col`. A hidden field gets it as
738    /// its value.
739    #[must_use]
740    pub fn fill_cell(self, column: &'static str) -> Self {
741        self.attr("data-ui-cell", column)
742    }
743
744    /// Lets [`Cmd::value`] set this hidden field: the state a set of buttons changes, such
745    /// as the column a form sorts by. A hidden field without it, such as a form's token or
746    /// method, can't be changed by a command.
747    #[must_use]
748    pub fn settable(self) -> Self {
749        self.flag("data-ui-value", true)
750    }
751
752    /// Says [`Cmd::fill`] writes the row's key here. A hidden field gets it as its value,
753    /// so a form in the dialog posts which row it acts on.
754    #[must_use]
755    pub fn fill_key(self) -> Self {
756        self.flag("data-ui-row-key", true)
757    }
758
759    /// Makes `key` a shortcut for this element: pressed anywhere on the page, it clicks
760    /// the element, or focuses it if it is a field. It never fires while someone types in
761    /// a field or edits text, while a modifier other than Shift is held, during an input
762    /// method's composition, or from outside a modal dialog that is open, so a single
763    /// letter is safe. `aria-keyshortcuts` tells assistive technology.
764    ///
765    /// A key is one character a keyboard types: a letter, a digit or a sign such as `/`
766    /// or `?` (uppercase letters mean Shift). Anything else, a space or a word, is
767    /// refused, and the element is left as it was. When two elements name the same key,
768    /// the first in the page that can take it does.
769    ///
770    /// ```
771    /// use navree_ui::{el, render};
772    ///
773    /// let html = render(&el("a").href("/inbox/8").hotkey("j").child("Next").into());
774    /// assert!(html.contains(r#"data-ui-hotkey="j""#));
775    /// assert!(html.contains(r#"aria-keyshortcuts="j""#));
776    /// ```
777    #[must_use]
778    pub fn hotkey(self, key: &str) -> Self {
779        if !valid_hotkey(key) {
780            return self;
781        }
782        self.attr("data-ui-hotkey", key.to_owned())
783            .attr("aria-keyshortcuts", key.to_owned())
784            .uses(Uses::KEYS)
785    }
786
787    /// Makes `key` a shortcut for this element, as [`hotkey`](Self::hotkey) does, that
788    /// works only while the focus is inside the element whose id is `scope`: for a key
789    /// that changes something, such as closing the conversation the reader is in, so it
790    /// can't act from anywhere on the page. An invalid key or scope leaves the element as
791    /// it was.
792    ///
793    /// Single keys need a way to be turned off for the people who can't use them (WCAG
794    /// 2.1.4): keep each person's choice, and draw no hotkeys for someone who turned them
795    /// off.
796    ///
797    /// ```
798    /// use navree_ui::{el, render};
799    ///
800    /// let html = render(&el("button").hotkey_within("e", "thread").child("Close").into());
801    /// assert!(html.contains(r#"data-ui-hotkey="e" aria-keyshortcuts="e" data-ui-hotkey-scope="thread""#));
802    /// ```
803    #[must_use]
804    pub fn hotkey_within(self, key: &str, scope: &str) -> Self {
805        let scope_ok = !scope.is_empty()
806            && scope.len() <= 64
807            && scope
808                .chars()
809                .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.'));
810        if !valid_hotkey(key) || !scope_ok {
811            return self;
812        }
813        self.hotkey(key)
814            .attr("data-ui-hotkey-scope", scope.to_owned())
815    }
816
817    /// Says this page must load `uses` when this element is on it.
818    #[inline]
819    #[must_use]
820    pub fn uses(mut self, uses: Uses) -> Self {
821        self.uses = self.uses.with(uses);
822        self
823    }
824
825    /// Makes this element the root of `extension`: it carries the addresses of the extension's
826    /// script and stylesheet, the route prefixes its script may call, and the attributes a
827    /// morph from the server leaves as the script set them. The page links the stylesheet and
828    /// preloads the script, and the browser mounts the script on this element once. Give the
829    /// element a slot of the namespace, a colon and a word (`geo:map`), which is what the
830    /// stylesheet is scoped to.
831    ///
832    /// A second call replaces what the first wrote. An element that is an island names the
833    /// extension's stylesheet only: its script is the island's own.
834    ///
835    /// ```ignore
836    /// use navree_ui::{el, render};
837    ///
838    /// // `MAP` is the extension of plugins/geo, whose tests prove this example.
839    /// let html = render(&el("div").slot("geo:map").extension(&MAP).into());
840    /// assert!(html.contains("data-ui-ext="));
841    /// ```
842    #[must_use]
843    pub fn extension(self, extension: &'static UiExtension) -> Self {
844        self.named_extension(extension, None)
845    }
846
847    /// [`extension`](Self::extension) with props for the script: any value that serializes to
848    /// JSON. They go in an attribute, escaped as every attribute is, and the script receives
849    /// them parsed, so a value can't become markup or code. A value that can't be written as
850    /// JSON is written as `null`. There is no size limit when the element is drawn; keep props
851    /// under 64 KB and fetch the rest from a route (`kit::problems` reports props over that).
852    ///
853    /// ```ignore
854    /// use navree_ui::{el, render};
855    ///
856    /// #[derive(serde::Serialize)]
857    /// struct Place {
858    ///     city: &'static str,
859    ///     zoom: u8,
860    /// }
861    ///
862    /// // `MAP` is the extension of plugins/geo, whose tests prove this example.
863    /// let place = Place { city: "Ludhiana", zoom: 12 };
864    /// let html = render(&el("div").slot("geo:map").extension_with(&MAP, &place).into());
865    /// assert!(html.contains("data-ui-props="));
866    /// ```
867    #[must_use]
868    pub fn extension_with(self, extension: &'static UiExtension, props: &impl Serialize) -> Self {
869        let json = serde_json::to_string(props).unwrap_or_else(|_| "null".to_owned());
870        self.named_extension(extension, Some(json))
871    }
872
873    /// Lets this element's script call exactly `href`, beside its extension's route
874    /// prefixes: for an address only the server can name, such as the drop of one delivery.
875    /// The query and the fragment are left out, and so is an address that is not a path of this
876    /// site, holds whitespace, or has a `.` or `..` segment (write whitespace percent-encoded).
877    /// Call it after [`extension`](Self::extension), which replaces the addresses an earlier call
878    /// wrote.
879    ///
880    /// ```ignore
881    /// use navree_ui::{el, render};
882    ///
883    /// // `MAP` is the extension of plugins/geo, whose tests prove this example.
884    /// let element = el("div").slot("geo:map").extension(&MAP).extension_call("/deliveries/42/drop");
885    /// assert!(render(&element.into()).contains("=/deliveries/42/drop"));
886    /// ```
887    #[must_use]
888    pub fn extension_call(mut self, href: impl Into<LocalHref>) -> Self {
889        let href = href.into();
890        let path = href.as_str().split(['?', '#']).next().unwrap_or_default();
891        if !path.starts_with('/')
892            || path.contains('\\')
893            || path.bytes().any(|byte| byte <= b' ')
894            || path.chars().any(char::is_whitespace)
895            || has_encoded_slash(path)
896            || has_dot_segment(path)
897        {
898            return self;
899        }
900        let token = format!("={path}");
901        let held = self
902            .get("data-ui-ext-routes")
903            .and_then(AttrValue::as_text)
904            .map(Cow::into_owned);
905        match held {
906            Some(list) if list.split(' ').any(|have| have == token) => {}
907            Some(list) => self.put("data-ui-ext-routes", format!("{list} {token}")),
908            None => self.put("data-ui-ext-routes", token),
909        }
910        self
911    }
912
913    /// Sets attribute `name` to `value`, in place when the element has it already.
914    fn put(&mut self, name: &'static str, value: String) {
915        let value = AttrValue::Text(value.into_boxed_str());
916        match self.attrs.iter_mut().find(|attr| attr.name == name) {
917            Some(attr) => attr.value = value,
918            None => self.attrs.push(Attr { name, value }),
919        }
920    }
921
922    /// Writes what an element carries for `extension`, in this order, each only as it applies:
923    /// the script's address, the stylesheet's, the route prefixes, the attributes a morph leaves
924    /// (the toolkit's two and the extension's own, joined to any the element has), and the
925    /// props. What an earlier call wrote is replaced.
926    fn named_extension(mut self, extension: &'static UiExtension, props: Option<String>) -> Self {
927        const OWN: [&str; 4] = [
928            "data-ui-ext",
929            "data-ui-ext-sheet",
930            "data-ui-ext-routes",
931            "data-ui-props",
932        ];
933        // An island's script, props and kept attributes are its own: only the sheet is named. A
934        // plugin's island keeps the extensions module, which seals its body.
935        if self.attrs.iter().any(|attr| attr.name == "data-ui-island") {
936            debug_assert!(
937                extension.script_file().is_none(),
938                "an element is an island or carries an extension script, not both"
939            );
940            self.uses = Uses(self.uses.0 & !Uses::EXTENSION_SHEETS.0);
941            self.attrs.retain(|attr| attr.name != "data-ui-ext-sheet");
942            if let Some(sheet) = extension.sheet_url() {
943                self.put("data-ui-ext-sheet", sheet.to_owned());
944                self.uses = self.uses.with(Uses::EXTENSION_SHEETS);
945            }
946            return self;
947        }
948        self.uses = self.uses.without_extensions();
949        self.attrs.retain(|attr| !OWN.contains(&attr.name));
950        if let Some(script) = extension.script_url() {
951            self.put("data-ui-ext", script.to_owned());
952            self.uses = self.uses.with(Uses::EXTENSIONS).with(Uses::CORE);
953        }
954        if let Some(sheet) = extension.sheet_url() {
955            self.put("data-ui-ext-sheet", sheet.to_owned());
956            self.uses = self.uses.with(Uses::EXTENSION_SHEETS);
957        }
958        if !extension.routes_of().is_empty() {
959            self.put("data-ui-ext-routes", extension.routes_of().join(" "));
960        }
961        let mut kept: Vec<String> = Vec::new();
962        let held = self
963            .get("data-ui-keep-attrs")
964            .and_then(AttrValue::as_text)
965            .map(Cow::into_owned);
966        let tokens = held
967            .iter()
968            .flat_map(|held| held.split_whitespace())
969            .chain(["data-ui-mounted", "data-ui-failed"])
970            .chain(extension.keeps_of().iter().copied());
971        for token in tokens {
972            if !kept.iter().any(|have| have == token) {
973                kept.push(token.to_owned());
974            }
975        }
976        self.put("data-ui-keep-attrs", kept.join(" "));
977        if let Some(json) = props {
978            self.put("data-ui-props", json);
979        }
980        self
981    }
982
983    /// Adds one child.
984    #[inline]
985    #[must_use]
986    pub fn child(mut self, child: impl IntoNodes) -> Self {
987        child.push_into(&mut self.children);
988        self
989    }
990
991    /// Adds children: a tuple, a list, an `Option`, or one node.
992    #[inline]
993    #[must_use]
994    pub fn children(self, children: impl IntoNodes) -> Self {
995        self.child(children)
996    }
997
998    /// Reserves room for `count` more children, when you know how many.
999    #[inline]
1000    #[must_use]
1001    pub fn with_child_capacity(mut self, count: usize) -> Self {
1002        self.children.reserve_exact(count);
1003        self
1004    }
1005}
1006
1007impl From<Element> for Node {
1008    #[inline]
1009    fn from(element: Element) -> Self {
1010        Self::Element(element)
1011    }
1012}
1013
1014impl From<&'static str> for Node {
1015    #[inline]
1016    fn from(text: &'static str) -> Self {
1017        Self::Text(Cow::Borrowed(text))
1018    }
1019}
1020
1021impl From<String> for Node {
1022    #[inline]
1023    fn from(text: String) -> Self {
1024        Self::Text(Cow::Owned(text))
1025    }
1026}
1027
1028impl From<Cow<'static, str>> for Node {
1029    #[inline]
1030    fn from(text: Cow<'static, str>) -> Self {
1031        Self::Text(text)
1032    }
1033}
1034
1035impl From<i64> for Node {
1036    #[inline]
1037    fn from(value: i64) -> Self {
1038        Self::Int(value)
1039    }
1040}
1041
1042impl From<SafeHtml> for Node {
1043    fn from(html: SafeHtml) -> Self {
1044        Self::Raw(html)
1045    }
1046}
1047
1048/// What can stand as children: one node, a tuple, a list, an `Option`.
1049pub trait IntoNodes {
1050    /// Appends the nodes to `out`.
1051    fn push_into(self, out: &mut Vec<Node>);
1052}
1053
1054impl<T: Into<Node>> IntoNodes for T {
1055    #[inline]
1056    fn push_into(self, out: &mut Vec<Node>) {
1057        out.push(self.into());
1058    }
1059}
1060
1061impl<T: IntoNodes> IntoNodes for Vec<T> {
1062    #[inline]
1063    fn push_into(self, out: &mut Vec<Node>) {
1064        out.reserve(self.len());
1065        for item in self {
1066            item.push_into(out);
1067        }
1068    }
1069}
1070
1071impl<T: IntoNodes, const N: usize> IntoNodes for [T; N] {
1072    #[inline]
1073    fn push_into(self, out: &mut Vec<Node>) {
1074        out.reserve(N);
1075        for item in self {
1076            item.push_into(out);
1077        }
1078    }
1079}
1080
1081impl<T: IntoNodes> IntoNodes for Option<T> {
1082    #[inline]
1083    fn push_into(self, out: &mut Vec<Node>) {
1084        if let Some(item) = self {
1085            item.push_into(out);
1086        }
1087    }
1088}
1089
1090macro_rules! tuples {
1091    ($($name:ident)+) => {
1092        impl<$($name: IntoNodes),+> IntoNodes for ($($name,)+) {
1093            #[inline]
1094            #[allow(non_snake_case)]
1095            fn push_into(self, out: &mut Vec<Node>) {
1096                let ($($name,)+) = self;
1097                $($name.push_into(out);)+
1098            }
1099        }
1100    };
1101}
1102
1103tuples!(A);
1104tuples!(A B);
1105tuples!(A B C);
1106tuples!(A B C D);
1107tuples!(A B C D E);
1108tuples!(A B C D E F);
1109tuples!(A B C D E F G);
1110tuples!(A B C D E F G H);
1111tuples!(A B C D E F G H I);
1112tuples!(A B C D E F G H I J);
1113tuples!(A B C D E F G H I J K);
1114tuples!(A B C D E F G H I J K L);
1115
1116/// Turns each type named into a `Node` by calling its own `into_node` method, so the component
1117/// can be given wherever a node goes: as a child, as a page's body, in a table's cell. It is
1118/// the last step of a component of your own, once its root element is built; the toolkit's own
1119/// components end the same way.
1120///
1121/// ```
1122/// use navree_ui::{Element, Node, el};
1123///
1124/// /// A badge with a city in it.
1125/// pub struct CityBadge {
1126///     el: Element,
1127///     city: &'static str,
1128/// }
1129///
1130/// navree_ui::component_node!(CityBadge);
1131///
1132/// impl CityBadge {
1133///     /// A badge for `city`.
1134///     pub fn new(city: &'static str) -> Self {
1135///         Self { el: el("span").slot("app:city-badge"), city }
1136///     }
1137///
1138///     fn into_node(self) -> Node {
1139///         self.el.child(self.city).into()
1140///     }
1141/// }
1142///
1143/// let page = navree_ui::View::new("Depots").body(CityBadge::new("Ludhiana"));
1144/// assert!(page.to_html().contains("Ludhiana"));
1145/// ```
1146#[macro_export]
1147macro_rules! component_node {
1148    ($($type:ty),+ $(,)?) => {
1149        $(impl ::core::convert::From<$type> for $crate::Node {
1150            #[inline]
1151            fn from(value: $type) -> Self {
1152                value.into_node()
1153            }
1154        })+
1155    };
1156}
1157pub(crate) use crate::component_node as into_node;
1158
1159#[cfg(test)]
1160mod tests {
1161    use super::*;
1162
1163    #[test]
1164    fn urls_in_attributes_are_checked() {
1165        let element = el("a").attr("href", "javascript:alert(1)");
1166        assert_eq!(element.get("href"), Some(&AttrValue::Text("#".into())));
1167        let element = el("a").attr("href", "/ok".to_owned());
1168        assert_eq!(element.get("href"), Some(&AttrValue::Text("/ok".into())));
1169    }
1170
1171    #[test]
1172    fn children_take_tuples_lists_and_options() {
1173        let element =
1174            el("div").children(("a", Some("b"), None::<&'static str>, vec!["c", "d"], 7_i64));
1175        assert_eq!(element.child_nodes().len(), 5);
1176        assert_eq!(Node::from(element).text_content(), "abcd7");
1177    }
1178
1179    #[test]
1180    fn commands_ask_for_the_core_runtime() {
1181        assert!(el("div").uses.is_none());
1182        let element = el("button").on_click_one(Cmd::toggle("menu"));
1183        assert!(element.uses.has(Uses::CORE));
1184    }
1185
1186    #[test]
1187    fn a_hotkey_is_one_typed_character_and_loads_the_keys_module() {
1188        for key in ["j", "K", "/", "?", "1", "é"] {
1189            let element = el("a").hotkey(key);
1190            assert_eq!(
1191                element.get("data-ui-hotkey"),
1192                Some(&AttrValue::Text(key.into()))
1193            );
1194            assert_eq!(
1195                element.get("aria-keyshortcuts"),
1196                Some(&AttrValue::Text(key.into()))
1197            );
1198            assert!(element.uses.has(Uses::KEYS));
1199        }
1200        for bad in ["", " ", "jk", "Enter", "\n", "\u{7}", "ctrl+k"] {
1201            let element = el("a").hotkey(bad);
1202            assert!(element.get("data-ui-hotkey").is_none(), "{bad:?}");
1203            assert!(element.uses.is_none(), "{bad:?}");
1204        }
1205    }
1206
1207    #[test]
1208    fn a_scoped_hotkey_names_its_scope_and_refuses_a_bad_one() {
1209        let html = crate::render(&el("button").hotkey_within("e", "thread").into());
1210        assert!(html.contains(r#"data-ui-hotkey="e""#), "{html}");
1211        assert!(html.contains(r#"data-ui-hotkey-scope="thread""#), "{html}");
1212        for bad in ["", "a b", "x\"y", &"z".repeat(65)] {
1213            let html = crate::render(&el("button").hotkey_within("e", bad).into());
1214            assert!(!html.contains("data-ui-hotkey"), "{bad}: {html}");
1215        }
1216        let html = crate::render(&el("button").hotkey_within("two", "thread").into());
1217        assert!(!html.contains("data-ui-hotkey"), "{html}");
1218    }
1219
1220    #[test]
1221    fn the_new_modules_have_bits_of_their_own() {
1222        let known = [
1223            Uses::CORE,
1224            Uses::SIDEBAR,
1225            Uses::OVERLAY,
1226            Uses::TABLE,
1227            Uses::SELECT,
1228            Uses::MENUS,
1229            Uses::LIVE,
1230            Uses::DATES,
1231            Uses::PHONE,
1232            Uses::THEME_BUILDER,
1233            Uses::SLIDER,
1234            Uses::TREE,
1235            Uses::TOOLBAR,
1236            Uses::SORTABLE,
1237        ];
1238        for module in [Uses::SPLIT, Uses::KEYS, Uses::LAZY] {
1239            assert!(known.iter().all(|other| other.0 & module.0 == 0));
1240        }
1241        assert_eq!(Uses::SPLIT.0 & Uses::KEYS.0, 0);
1242        assert_eq!((Uses::SPLIT.0 | Uses::KEYS.0) & Uses::LAZY.0, 0);
1243    }
1244
1245    #[test]
1246    fn the_markdown_upload_code_carousel_and_menu_bar_modules_have_bits_of_their_own() {
1247        let older = [
1248            Uses::CORE,
1249            Uses::SIDEBAR,
1250            Uses::OVERLAY,
1251            Uses::TABLE,
1252            Uses::SELECT,
1253            Uses::MENUS,
1254            Uses::LIVE,
1255            Uses::DATES,
1256            Uses::PHONE,
1257            Uses::THEME_BUILDER,
1258            Uses::SLIDER,
1259            Uses::TREE,
1260            Uses::TOOLBAR,
1261            Uses::SORTABLE,
1262            Uses::SPLIT,
1263            Uses::KEYS,
1264            Uses::LAZY,
1265        ];
1266        let newer = [
1267            Uses::MARKDOWN,
1268            Uses::UPLOAD,
1269            Uses::OTP,
1270            Uses::CAROUSEL,
1271            Uses::MENUBAR,
1272            Uses::PARTS,
1273            Uses::PARTS_STYLES,
1274            Uses::GENUI,
1275        ];
1276        for (at, module) in newer.iter().enumerate() {
1277            assert_eq!(module.0.count_ones(), 1);
1278            assert!(older.iter().all(|other| other.0 & module.0 == 0));
1279            assert!(newer[at + 1..].iter().all(|other| other.0 & module.0 == 0));
1280        }
1281    }
1282
1283    #[test]
1284    fn a_node_stays_small() {
1285        // Children hold nodes inline, so one size change touches every page.
1286        assert!(
1287            std::mem::size_of::<Node>() <= 72,
1288            "{}",
1289            std::mem::size_of::<Node>()
1290        );
1291    }
1292
1293    use crate::extension::ExtensionFile;
1294
1295    /// A map with a script and a stylesheet, and a badge with a stylesheet only.
1296    static MAP: UiExtension = UiExtension::new("geo", "map")
1297        .script(ExtensionFile::__new(
1298            b"export const contract = 1; export function mount() {}",
1299            "e1613860bbf0",
1300            None,
1301        ))
1302        .sheet(ExtensionFile::__new(
1303            b"/* the map's stylesheet, scoped for geo */",
1304            "bbefcf02ae04",
1305            Some("geo"),
1306        ))
1307        .contract(1)
1308        .keeps(&["data-moving"])
1309        .routes(&["/geo/"]);
1310    static BADGE: UiExtension = UiExtension::new("geo", "badge").sheet(ExtensionFile::__new(
1311        b"/* the badge's stylesheet, scoped for geo */",
1312        "ea46b024fa00",
1313        Some("geo"),
1314    ));
1315
1316    const MAP_ATTRIBUTES: &str = r#" data-ui-ext="/_navree/ui/ext/geo.map-e1613860bbf0.js" data-ui-ext-sheet="/_navree/ui/ext/geo.map-bbefcf02ae04.css" data-ui-ext-routes="/geo/""#;
1317
1318    #[test]
1319    fn an_element_with_an_extension_names_its_files_and_asks_for_the_modules() {
1320        let element = el("div").slot("geo:map").extension(&MAP);
1321        assert_eq!(
1322            crate::render(&element.clone().into()),
1323            format!(
1324                r#"<div data-slot="geo:map"{MAP_ATTRIBUTES} data-ui-keep-attrs="data-ui-mounted data-ui-failed data-moving"></div>"#
1325            )
1326        );
1327        assert!(element.uses.has(Uses::EXTENSIONS));
1328        assert!(element.uses.has(Uses::EXTENSION_SHEETS));
1329        assert!(element.uses.has(Uses::CORE));
1330
1331        // What the element kept already stays in front of what the extension keeps.
1332        let held = el("div")
1333            .attr("data-ui-keep-attrs", "data-collapsed")
1334            .slot("geo:map")
1335            .extension(&MAP);
1336        assert_eq!(
1337            held.get("data-ui-keep-attrs"),
1338            Some(&AttrValue::Text(
1339                "data-collapsed data-ui-mounted data-ui-failed data-moving".into()
1340            ))
1341        );
1342        let repeated = el("div")
1343            .attr("data-ui-keep-attrs", "data-moving data-ui-failed")
1344            .extension(&MAP);
1345        assert_eq!(
1346            repeated.get("data-ui-keep-attrs"),
1347            Some(&AttrValue::Text(
1348                "data-moving data-ui-failed data-ui-mounted".into()
1349            ))
1350        );
1351
1352        // A second call replaces the attributes and the extension bits of the first.
1353        let replaced = el("div")
1354            .extension_with(&MAP, &serde_json::json!({ "zoom": 15 }))
1355            .extension(&BADGE);
1356        assert!(replaced.get("data-ui-ext").is_none());
1357        assert!(replaced.get("data-ui-ext-routes").is_none());
1358        assert!(replaced.get("data-ui-props").is_none());
1359        assert_eq!(
1360            replaced.get("data-ui-ext-sheet"),
1361            Some(&AttrValue::Text(
1362                "/_navree/ui/ext/geo.badge-ea46b024fa00.css".into()
1363            ))
1364        );
1365        assert!(replaced.uses.has(Uses::EXTENSION_SHEETS));
1366        assert!(!replaced.uses.has(Uses::EXTENSIONS));
1367    }
1368
1369    #[test]
1370    fn a_sheet_only_extension_asks_for_no_script() {
1371        let element = el("span").extension(&BADGE);
1372        assert_eq!(
1373            crate::render(&element.clone().into()),
1374            r#"<span data-ui-ext-sheet="/_navree/ui/ext/geo.badge-ea46b024fa00.css" data-ui-keep-attrs="data-ui-mounted data-ui-failed"></span>"#
1375        );
1376        assert_eq!(element.uses, Uses::EXTENSION_SHEETS);
1377    }
1378
1379    #[test]
1380    fn an_island_names_the_sheet_and_keeps_its_own_script_and_props() {
1381        let island = || {
1382            el("div")
1383                .attr("data-ui-island", "/_navree/ui/island/clock-0123456789ab.js")
1384                .attr("data-ui-props", "{}")
1385                .uses(Uses::ISLAND)
1386        };
1387        let styled = island().extension(&BADGE);
1388        assert_eq!(
1389            crate::render(&styled.clone().into()),
1390            r#"<div data-ui-island="/_navree/ui/island/clock-0123456789ab.js" data-ui-props="{}" data-ui-ext-sheet="/_navree/ui/ext/geo.badge-ea46b024fa00.css"></div>"#
1391        );
1392        assert!(styled.uses.has(Uses::ISLAND));
1393        assert!(styled.uses.has(Uses::EXTENSION_SHEETS));
1394        assert!(!styled.uses.has(Uses::EXTENSIONS));
1395    }
1396
1397    /// A plugin's island has the page load the extensions module, which seals its body, and a
1398    /// sheet named on it does not take that away. An app's island loads no extensions module.
1399    #[test]
1400    fn a_plugins_island_keeps_the_extensions_module_when_it_names_a_sheet() {
1401        use crate::island::{Island, IslandScript};
1402
1403        static CLOCK: IslandScript =
1404            IslandScript::new("clock", b"export function mount() {}", 1024).namespace("geo");
1405        static PLAIN_CLOCK: IslandScript =
1406            IslandScript::new("clock", b"export function mount() {}", 1024);
1407        let element = |island: Island| {
1408            Node::from(island)
1409                .into_element()
1410                .expect("an island is one element")
1411        };
1412
1413        let plugins = element(Island::new("clock", &CLOCK));
1414        assert_eq!(plugins.uses, Uses::ISLAND.with(Uses::EXTENSIONS));
1415        let styled = plugins.extension(&BADGE);
1416        assert_eq!(
1417            styled.uses,
1418            Uses::ISLAND
1419                .with(Uses::EXTENSIONS)
1420                .with(Uses::EXTENSION_SHEETS)
1421        );
1422        // A second sheet replaces the first and keeps the module.
1423        assert_eq!(
1424            styled.extension(&BADGE).uses,
1425            Uses::ISLAND
1426                .with(Uses::EXTENSIONS)
1427                .with(Uses::EXTENSION_SHEETS)
1428        );
1429
1430        let apps = element(Island::new("clock", &PLAIN_CLOCK));
1431        assert_eq!(apps.uses, Uses::ISLAND);
1432        assert_eq!(
1433            apps.extension(&BADGE).uses,
1434            Uses::ISLAND.with(Uses::EXTENSION_SHEETS)
1435        );
1436    }
1437
1438    /// An island and an extension script on one element is a mistake that a debug build reports.
1439    #[cfg(debug_assertions)]
1440    #[test]
1441    #[should_panic(expected = "an element is an island or carries an extension script, not both")]
1442    fn an_island_with_an_extension_script_is_refused_in_a_debug_build() {
1443        let _ = el("div")
1444            .attr("data-ui-island", "/_navree/ui/island/clock-0123456789ab.js")
1445            .extension(&MAP);
1446    }
1447
1448    #[test]
1449    fn extension_call_adds_one_exact_address() {
1450        let plain = crate::render(&el("div").extension(&MAP).into());
1451        let called = crate::render(
1452            &el("div")
1453                .extension(&MAP)
1454                .extension_call("/deliveries/42/drop?from=table")
1455                .into(),
1456        );
1457        assert_eq!(
1458            called,
1459            plain.replace(
1460                r#"data-ui-ext-routes="/geo/""#,
1461                r#"data-ui-ext-routes="/geo/ =/deliveries/42/drop""#
1462            )
1463        );
1464        // The same address twice is one address; another one is another.
1465        let twice = el("div")
1466            .extension(&MAP)
1467            .extension_call("/deliveries/42/drop")
1468            .extension_call("/deliveries/42/drop#top")
1469            .extension_call("/deliveries/43/drop");
1470        assert_eq!(
1471            twice.get("data-ui-ext-routes"),
1472            Some(&AttrValue::Text(
1473                "/geo/ =/deliveries/42/drop =/deliveries/43/drop".into()
1474            ))
1475        );
1476        // An extension with no prefixes gets the attribute from the call.
1477        let only = el("div")
1478            .extension(&BADGE)
1479            .extension_call("/deliveries/42/drop");
1480        assert_eq!(
1481            only.get("data-ui-ext-routes"),
1482            Some(&AttrValue::Text("=/deliveries/42/drop".into()))
1483        );
1484        // A relative address, the page itself, another site and a path with a space add nothing.
1485        for refused in [
1486            "relative",
1487            "#",
1488            "?x=1",
1489            "//other.example/geo/x",
1490            "https://other.example/geo/x",
1491            "/deliveries/42 /drop",
1492            "",
1493        ] {
1494            let element = el("div").extension(&MAP).extension_call(refused);
1495            assert_eq!(crate::render(&element.into()), plain, "{refused:?}");
1496        }
1497    }
1498
1499    #[test]
1500    fn extension_props_are_escaped_json() {
1501        #[derive(serde::Serialize)]
1502        struct Props {
1503            note: &'static str,
1504            city: &'static str,
1505        }
1506        let props = Props {
1507            note: "</div><script>alert(1)</script>",
1508            city: "Ludhiana",
1509        };
1510        let html = crate::render(&el("div").extension_with(&MAP, &props).into());
1511        assert!(
1512            html.contains(
1513                r#" data-ui-props="{&quot;note&quot;:&quot;&lt;/div&gt;&lt;script&gt;alert(1)&lt;/script&gt;&quot;,&quot;city&quot;:&quot;Ludhiana&quot;}""#
1514            ),
1515            "{html}"
1516        );
1517        assert!(!html.contains("<script"), "{html}");
1518        // Props that JSON can't write are `null`: a map keyed by pairs.
1519        let pairs = std::collections::BTreeMap::from([((1, 2), "x")]);
1520        let html = crate::render(&el("div").extension_with(&MAP, &pairs).into());
1521        assert!(html.contains(r#" data-ui-props="null""#), "{html}");
1522    }
1523
1524    #[test]
1525    fn the_extension_bits_are_two_modules_of_their_own() {
1526        assert_eq!(Uses::EXTENSIONS.0.count_ones(), 1);
1527        assert_eq!(Uses::EXTENSION_SHEETS.0.count_ones(), 1);
1528        assert_ne!(Uses::EXTENSIONS, Uses::EXTENSION_SHEETS);
1529        let both = Uses::EXTENSIONS
1530            .with(Uses::EXTENSION_SHEETS)
1531            .with(Uses::CORE);
1532        assert_eq!(
1533            both.extension_bits(),
1534            Uses::EXTENSIONS.with(Uses::EXTENSION_SHEETS)
1535        );
1536        assert_eq!(both.without_extensions(), Uses::CORE);
1537    }
1538}