plexus-ui-engine 0.2.3

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! UI-10: **HTML the page may hold** — `{@html expr}` draws the
//! expression's text as HTML, and `markdown(text)` makes HTML of
//! markdown; both go through [`sanitize`] first.
//!
//! The sanitizer is an allow-list: it parses the text into elements and
//! text, keeps a tag only when it is listed ([`ALLOWED_TAGS`]) and an
//! attribute only when it is listed for its tag ([`allowed_attr`]); a URL
//! attribute keeps only `http:`, `https:`, `#…` and `mailto:` values. A tag
//! not listed is dropped and its text kept — except `script`, `style`,
//! `iframe`, `object`, `embed`, `noscript`, `template`, `svg` and `math`,
//! dropped with everything inside. What it answers is a tree the engine
//! draws through the renderer: no HTML string reaches the page.

/// A sanitized node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HNode {
    Element { tag: String, attrs: Vec<(String, String)>, children: Vec<HNode> },
    Text(String),
}

/// The tags kept.
pub const ALLOWED_TAGS: &[&str] = &[
    "a", "abbr", "b", "blockquote", "br", "code", "dd", "del", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "kbd", "li",
    "mark", "ol", "p", "pre", "q", "s", "small", "span", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul",
];

/// Elements with no content and no end tag.
const VOID: &[&str] = &["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"];

/// Dropped with everything inside them.
const DROPPED_WHOLE: &[&str] = &["script", "style", "iframe", "object", "embed", "noscript", "template", "svg", "math", "textarea", "title", "head", "frameset", "frame", "noembed", "xmp", "plaintext"];

/// Whose content is raw text (no tags inside, up to the end tag).
const RAW_TEXT: &[&str] = &["script", "style", "textarea", "title", "xmp", "noembed", "plaintext"];

/// Attributes that hold a URL: kept only for `http:`, `https:`, `#…`, `mailto:`.
const URL_ATTRS: &[&str] = &["href", "src"];

/// Every `(tag, attribute)` kept; `*` is any allowed tag. Widening it is a
/// deliberate edit (html/tests.rs pins it).
pub const ALLOWED_ATTRS: &[(&str, &str)] = &[
    ("*", "title"),
    ("a", "href"),
    ("code", "class"),
    ("img", "alt"),
    ("img", "height"),
    ("img", "src"),
    ("img", "width"),
    ("ol", "start"),
    ("pre", "class"),
    ("td", "colspan"),
    ("td", "rowspan"),
    ("th", "colspan"),
    ("th", "rowspan"),
];

/// Whether `attr` is kept on `tag` ([`ALLOWED_ATTRS`]; on a house mark,
/// [`house_attr`]).
pub fn allowed_attr(tag: &str, attr: &str) -> bool {
    if house_tag(tag) {
        return house_attr(attr);
    }
    ALLOWED_TAGS.contains(&tag) && ALLOWED_ATTRS.iter().any(|(t, a)| (*t == "*" || *t == tag) && *a == attr)
}

/// EDITOR-8: **a house mark** — `m-<name>` (`m-summary`, `m-field`,
/// `m-decision`, …), letters, digits and `-` after the `m-`. A tenant's body
/// draws its marks as cards in CSS (the element is inert: no script defines
/// it here, and nothing on it loads or runs), so the tag is kept with the
/// plain-text attributes its card reads ([`house_attr`]) and nothing else.
pub fn house_tag(tag: &str) -> bool {
    tag.len() > 2 && tag.starts_with("m-") && tag[2..].bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
}

/// EDITOR-9: a custom element's name — letters, digits and `-`, with a `-`, beginning with a letter
/// (`volt-poll`, `x-new`); not a house mark's (those stay themselves).
pub fn custom_tag(tag: &str) -> bool {
    tag.contains('-') && tag.as_bytes().first().is_some_and(|c| c.is_ascii_lowercase()) && tag.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
}

/// The plain-text attributes a house mark keeps beside `data-*` (and `id`,
/// kept as `data-id`: an element's `id` names a global on `window`).
pub const HOUSE_ATTRS: &[&str] = &[
    "benefit", "by", "commits", "cost", "date", "description", "heading", "kicker", "kind", "label", "labels", "lang", "name", "path", "picked",
    "recommended", "ref", "size", "status", "ticket", "title", "tone", "value", "why",
];

/// COMPS-4: where a house mark's or a custom tag's other attributes go — a
/// tag in a body names a component, its attributes its props: kept inert
/// under this prefix (`<x-counter start="3">` → `data-prop-start="3"`).
pub const PROP_PREFIX: &str = "data-prop-";

/// COMPS-4: an attribute kept as a prop ([`PROP_PREFIX`]) — letters, digits
/// and `-`, beginning with a letter; never a handler (`on…`), a style, a
/// URL (`href`, `src`) or a `data-*` (those are [`house_attr`]'s, the bound
/// mark's dropped).
pub fn prop_attr(attr: &str) -> bool {
    attr.as_bytes().first().is_some_and(u8::is_ascii_lowercase)
        && attr.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
        && !attr.starts_with("on")
        && !attr.starts_with("data-")
        && !matches!(attr, "style" | "href" | "src" | "id")
}

/// FRAME-29's bound mark: never planted by untrusted text, on any tag.
const BOUND_MARK: &[&str] = &["data-slot", "data-component", "data-version", "data-layout"];

/// Whether a house mark keeps `attr`: a `data-*` (letters, digits, `-`) but
/// the bound mark's four, or one of [`HOUSE_ATTRS`]. No handler, no style, no
/// URL.
pub fn house_attr(attr: &str) -> bool {
    let data = attr.len() > 5
        && attr.starts_with("data-")
        && attr[5..].bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
        && !BOUND_MARK.contains(&attr);
    data || HOUSE_ATTRS.contains(&attr)
}

fn url_ok(value: &str) -> bool {
    let v = value.trim().to_ascii_lowercase();
    v.starts_with("https://") || v.starts_with("http://") || v.starts_with("mailto:") || v.starts_with('#')
}

/// `&amp;`, `&lt;`, `&#39;`, `&#x27;`, … decoded; an unknown entity kept as written.
fn decode(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(i) = rest.find('&') {
        out.push_str(&rest[..i]);
        rest = &rest[i..];
        let end = rest[1..].find(|c: char| c == ';' || c == '&' || c.is_whitespace() || c == '<').map(|j| j + 1);
        let decoded = match end.filter(|e| rest.as_bytes().get(*e) == Some(&b';')) {
            Some(e) => {
                let name = &rest[1..e];
                let ch = match name {
                    "amp" => Some('&'),
                    "lt" => Some('<'),
                    "gt" => Some('>'),
                    "quot" => Some('"'),
                    "apos" => Some('\''),
                    "nbsp" => Some('\u{a0}'),
                    n if n.starts_with("#x") || n.starts_with("#X") => u32::from_str_radix(&n[2..], 16).ok().and_then(char::from_u32),
                    n if n.starts_with('#') => n[1..].parse::<u32>().ok().and_then(char::from_u32),
                    _ => None,
                };
                ch.map(|c| (c, e + 1))
            }
            None => None,
        };
        match decoded {
            Some((c, len)) => {
                out.push(c);
                rest = &rest[len..];
            }
            None => {
                out.push('&');
                rest = &rest[1..];
            }
        }
    }
    out.push_str(rest);
    out
}

/// An open element while parsing.
struct Open {
    /// The name its end tag says (EDITOR-9: a custom tag's own, kept as `m-el`).
    name: String,
    tag: String,
    attrs: Vec<(String, String)>,
    children: Vec<HNode>,
}

fn push_text(stack: &mut [Open], root: &mut Vec<HNode>, text: String) {
    if text.is_empty() {
        return;
    }
    let into = match stack.last_mut() {
        Some(o) => &mut o.children,
        None => root,
    };
    if let Some(HNode::Text(t)) = into.last_mut() {
        t.push_str(&text);
    } else {
        into.push(HNode::Text(text));
    }
}

fn close(stack: &mut Vec<Open>, root: &mut Vec<HNode>) {
    if let Some(o) = stack.pop() {
        let node = HNode::Element { tag: o.tag, attrs: o.attrs, children: o.children };
        match stack.last_mut() {
            Some(p) => p.children.push(node),
            None => root.push(node),
        }
    }
}

/// A tag's name at `s` (letters, digits, `-`), lower-cased.
fn tag_name(s: &str) -> Option<(String, usize)> {
    let b = s.as_bytes();
    if !b.first()?.is_ascii_alphabetic() {
        return None;
    }
    let n = b.iter().position(|c| !(c.is_ascii_alphanumeric() || *c == b'-' || *c == b':')).unwrap_or(b.len());
    Some((s[..n].to_ascii_lowercase(), n))
}

/// The attributes of a start tag from `s` (after its name) to its `>`:
/// the attributes, whether it closed itself, and how far it went.
fn attributes(s: &str) -> (Vec<(String, String)>, bool, usize) {
    let b = s.as_bytes();
    let mut i = 0;
    let mut attrs = Vec::new();
    loop {
        while i < b.len() && (b[i].is_ascii_whitespace() || b[i] == b'/') {
            if b[i] == b'/' && b.get(i + 1) == Some(&b'>') {
                return (attrs, true, i + 2);
            }
            i += 1;
        }
        if i >= b.len() {
            return (attrs, false, i);
        }
        if b[i] == b'>' {
            return (attrs, false, i + 1);
        }
        let start = i;
        while i < b.len() && !(b[i].is_ascii_whitespace() || b[i] == b'=' || b[i] == b'>' || b[i] == b'/') {
            i += 1;
        }
        let name = s[start..i].to_ascii_lowercase();
        while i < b.len() && b[i].is_ascii_whitespace() {
            i += 1;
        }
        let mut value = String::new();
        if b.get(i) == Some(&b'=') {
            i += 1;
            while i < b.len() && b[i].is_ascii_whitespace() {
                i += 1;
            }
            match b.get(i) {
                Some(&q) if q == b'"' || q == b'\'' => {
                    let end = s[i + 1..].find(q as char).map(|e| i + 1 + e).unwrap_or(b.len());
                    value = decode(&s[i + 1..end]);
                    i = (end + 1).min(b.len());
                }
                _ => {
                    let vs = i;
                    while i < b.len() && !(b[i].is_ascii_whitespace() || b[i] == b'>') {
                        i += 1;
                    }
                    value = decode(&s[vs..i]);
                }
            }
        }
        if !name.is_empty() {
            attrs.push((name, value));
        }
    }
}

/// Where the end tag `</tag` closing a dropped element is, counting the
/// same tag opened inside it (raw text: the first end tag); none: the end.
fn skip_to_end(s: &str, tag: &str) -> usize {
    let lower = s.to_ascii_lowercase();
    let (open, close) = (format!("<{tag}"), format!("</{tag}"));
    let raw = RAW_TEXT.contains(&tag);
    // `<svg` names svg only when the name ends there (`<svgx` does not).
    let find = |from: usize, pat: &str| -> Option<usize> {
        let mut at = from;
        while let Some(j) = lower[at..].find(pat) {
            let k = at + j;
            match lower.as_bytes().get(k + pat.len()) {
                Some(c) if c.is_ascii_alphanumeric() || *c == b'-' || *c == b':' => at = k + pat.len(),
                _ => return Some(k),
            }
        }
        None
    };
    let mut depth = 1;
    let mut i = 0;
    loop {
        let next_close = find(i, &close);
        let next_open = if raw { None } else { find(i, &open) };
        match (next_open, next_close) {
            (Some(o), Some(c)) if o < c => {
                depth += 1;
                i = o + open.len();
            }
            (_, Some(c)) => {
                depth -= 1;
                let gt = lower[c..].find('>').map(|g| c + g + 1).unwrap_or(s.len());
                if depth == 0 {
                    return gt;
                }
                i = gt;
            }
            (_, None) => return s.len(),
        }
    }
}

/// `html`, parsed and kept to the allow-list.
pub fn sanitize(html: &str) -> Vec<HNode> {
    let mut root = Vec::new();
    let mut stack: Vec<Open> = Vec::new();
    let mut text = String::new();
    let mut i = 0;
    let s = html;
    while i < s.len() {
        let rest = &s[i..];
        let Some(lt) = rest.find('<') else {
            text.push_str(rest);
            break;
        };
        text.push_str(&rest[..lt]);
        i += lt;
        let rest = &s[i..];
        if rest.starts_with("<!--") {
            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
            i += rest.find("-->").map(|e| e + 3).unwrap_or(rest.len());
            continue;
        }
        if rest.starts_with("<!") || rest.starts_with("<?") {
            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
            i += rest.find('>').map(|e| e + 1).unwrap_or(rest.len());
            continue;
        }
        if let Some((name, n)) = rest.strip_prefix("</").and_then(tag_name) {
            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
            i += 2 + n + rest[2 + n..].find('>').map(|e| e + 1).unwrap_or(rest.len() - 2 - n);
            if let Some(at) = stack.iter().rposition(|o| o.name == name) {
                while stack.len() > at {
                    close(&mut stack, &mut root);
                }
            }
            continue;
        }
        let Some((name, n)) = tag_name(&rest[1..]) else {
            text.push('<');
            i += 1;
            continue;
        };
        push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
        let (attrs, self_closed, used) = attributes(&rest[1 + n..]);
        i += 1 + n + used;
        if DROPPED_WHOLE.contains(&name.as_str()) {
            if !VOID.contains(&name.as_str()) && !self_closed {
                i += skip_to_end(&s[i..], &name);
            }
            continue;
        }
        // EDITOR-9: any other custom element's tag (a `-` in its name: `volt-poll`) is kept inert as
        // `m-el`, its own name as `data-tag` — a name a page may define is never planted, and the
        // body's words inside it still draw, in a neutral box the tenant styles.
        let custom = !house_tag(&name) && !ALLOWED_TAGS.contains(&name.as_str()) && custom_tag(&name);
        let (name, tag) = if custom { (name.clone(), "m-el".to_string()) } else { (name.clone(), name) };
        let house = house_tag(&tag);
        if !ALLOWED_TAGS.contains(&tag.as_str()) && !house {
            continue;
        }
        let attrs: Vec<(String, String)> = if house {
            // EDITOR-8: `id` as `data-id` (unless the mark says one itself), then the house's list.
            let named = attrs.iter().any(|(a, _)| a == "data-id");
            let mut kept: Vec<(String, String)> = Vec::new();
            if custom {
                kept.push(("data-tag".to_string(), name.clone()));
            }
            for (a, v) in attrs {
                let a = if a == "id" && !named { "data-id".to_string() } else { a };
                if house_attr(&a) && !kept.iter().any(|(k, _)| *k == a) && !(custom && a == "data-tag") {
                    kept.push((a, v));
                } else if prop_attr(&a) {
                    // COMPS-4: any other plain attribute is a prop of the component the tag may
                    // name, kept inert as `data-prop-<name>`.
                    let named = format!("{PROP_PREFIX}{a}");
                    if !kept.iter().any(|(k, _)| *k == named) {
                        kept.push((named, v));
                    }
                }
            }
            kept
        } else {
            attrs.into_iter().filter(|(a, v)| allowed_attr(&name, a) && (!URL_ATTRS.contains(&a.as_str()) || url_ok(v))).collect()
        };
        if VOID.contains(&tag.as_str()) || self_closed {
            let node = HNode::Element { tag, attrs, children: Vec::new() };
            match stack.last_mut() {
                Some(p) => p.children.push(node),
                None => root.push(node),
            }
        } else {
            stack.push(Open { name, tag, attrs, children: Vec::new() });
        }
    }
    push_text(&mut stack, &mut root, decode(&text));
    while !stack.is_empty() {
        close(&mut stack, &mut root);
    }
    root
}

fn escape(text: &str, attr: bool) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' if attr => out.push_str("&quot;"),
            c => out.push(c),
        }
    }
    out
}

/// The nodes as HTML text (escaped), for the tests and the console.
pub fn to_html(nodes: &[HNode]) -> String {
    let mut out = String::new();
    for n in nodes {
        match n {
            HNode::Text(t) => out.push_str(&escape(t, false)),
            HNode::Element { tag, attrs, children } => {
                out.push('<');
                out.push_str(tag);
                for (k, v) in attrs {
                    out.push_str(&format!(" {k}=\"{}\"", escape(v, true)));
                }
                out.push('>');
                if !VOID.contains(&tag.as_str()) {
                    out.push_str(&to_html(children));
                    out.push_str(&format!("</{tag}>"));
                }
            }
        }
    }
    out
}

/// Markdown as HTML (CommonMark with tables and strikethrough); raw HTML in
/// it passes through, to be sanitized where it is drawn.
pub fn markdown(text: &str) -> String {
    use pulldown_cmark::{html, Options, Parser};
    let mut out = String::new();
    html::push_html(&mut out, Parser::new_ext(text, Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH));
    out
}

#[cfg(test)]
mod tests;