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