Skip to main content

glory_html/
lib.rs

1//! Common HTML lowering. No UI/core runtime, DOM, HTTP or window dependencies.
2pub mod display;
3mod graphic;
4mod mapping;
5mod patch;
6mod plan;
7#[cfg(test)]
8mod rich_tests;
9/// Experimental sparse HTML display declarations, independent of semantic nodes.
10pub mod template;
11pub mod view;
12pub use plan::PlanShape;
13#[cfg(test)]
14mod anchor_tests;
15#[cfg(test)]
16mod choice_tests;
17#[cfg(test)]
18mod collapse_tests;
19#[cfg(test)]
20mod context_menu_tests;
21#[cfg(test)]
22mod drag_capture_tests;
23#[cfg(test)]
24mod environment_tests;
25#[cfg(test)]
26mod focus_scope_tests;
27#[cfg(test)]
28mod menubar_tests;
29#[cfg(test)]
30mod patch_tests;
31#[cfg(test)]
32mod placeholder_tests;
33#[cfg(test)]
34mod presence_tests;
35mod semantics;
36#[cfg(test)]
37mod semantics_tests;
38
39#[cfg(test)]
40mod role_tests;
41mod serialize;
42#[cfg(feature = "css")]
43mod sheets;
44mod styles;
45#[cfg(test)]
46mod tags_tests;
47#[cfg(test)]
48mod translation_tests;
49#[cfg(feature = "css")]
50pub use glory_style::Sheet;
51#[cfg(feature = "css")]
52pub use sheets::sheet;
53
54use glory_render::memory::{Memory, Subtree};
55use glory_render::{Error, Mutation, NodeId, Receipt, Render, RuntimeId};
56use std::collections::{BTreeMap, HashMap};
57
58pub use mapping::{preflight, shape, shape_in};
59pub use serialize::{escape, rich_document, select_options, serialize};
60pub use styles::style;
61pub const FORMAT_VERSION: u32 = 19;
62/// Namespace is determined solely by the mapper's finite element vocabulary.
63pub fn element_namespace(tag: &str) -> &'static str {
64    if matches!(tag, "svg" | "path") {
65        "http://www.w3.org/2000/svg"
66    } else {
67        "http://www.w3.org/1999/xhtml"
68    }
69}
70
71pub const BASE_CSS: &str = concat!(
72    "[data-gly-kind=graphic]>path:not([data-gly-path-transition]){transition:none}",
73    "[data-gly-path-transition]{transition-property:d;transition-timing-function:linear}",
74    "@media(prefers-reduced-motion:reduce){[data-gly-path-transition]{transition:none!important}}",
75    "@keyframes gly-rotate{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}",
76    "[data-gly-rotate]{animation-name:gly-rotate;animation-timing-function:linear;animation-iteration-count:infinite;transform-box:view-box;transform-origin:50% 50%}",
77    "@media(prefers-reduced-motion:reduce){[data-gly-rotate]{animation-name:none;transform:none}}",
78    "@keyframes gly-pulse{0%,100%{opacity:.25}50%{opacity:1}}",
79    "[data-gly-pulse]{animation-name:gly-pulse;animation-timing-function:linear;animation-iteration-count:infinite}",
80    "@media(prefers-reduced-motion:reduce){[data-gly-pulse]{animation-name:none;opacity:1}}",
81    "[data-gly-swipe-axis=horizontal]{touch-action:pan-y pinch-zoom;user-select:none}[data-gly-swipe-axis=vertical]{touch-action:pan-x pinch-zoom;user-select:none}",
82    "[data-gly-splitter],[data-gly-slider],[data-gly-sheet-grip],[data-gly-drag-capture]{touch-action:none}",
83    "[data-gly-splitter]{user-select:none}",
84    "[data-gly-sheet][data-gly-layer=left],[data-gly-sheet][data-gly-layer=right]{width:var(--gly-sheet-extent,100vw)!important;min-width:0!important;max-width:100vw!important}",
85    "[data-gly-sheet][data-gly-layer=top],[data-gly-sheet][data-gly-layer=bottom]{height:var(--gly-sheet-extent,100dvh)!important;min-height:0!important;max-height:100dvh!important}",
86    "[data-gly-sheet][data-gly-layer=left]{left:var(--gly-sheet-x,0px);top:var(--gly-sheet-y,0px);height:var(--gly-sheet-height,100dvh)!important}",
87    "[data-gly-sheet][data-gly-layer=right]{left:calc(var(--gly-sheet-x,0px) + var(--gly-sheet-width,100vw) - var(--gly-sheet-extent,100vw));right:auto;top:var(--gly-sheet-y,0px);height:var(--gly-sheet-height,100dvh)!important}",
88    "[data-gly-sheet][data-gly-layer=top]{left:var(--gly-sheet-x,0px);top:var(--gly-sheet-y,0px);width:var(--gly-sheet-width,100vw)!important}",
89    "[data-gly-sheet][data-gly-layer=bottom]{left:var(--gly-sheet-x,0px);top:calc(var(--gly-sheet-y,0px) + var(--gly-sheet-height,100dvh) - var(--gly-sheet-extent,100dvh));bottom:auto;width:var(--gly-sheet-width,100vw)!important}",
90    "[data-gly-sheet]{transition:width var(--gly-sheet-settle,0ms) ease-out,height var(--gly-sheet-settle,0ms) ease-out,left var(--gly-sheet-settle,0ms) ease-out,top var(--gly-sheet-settle,0ms) ease-out}",
91    "@media(prefers-reduced-motion:reduce){[data-gly-sheet]{transition:none}}",
92    "[data-gly-sheet-grip]{position:absolute;z-index:1}",
93    "[data-gly-sheet][data-gly-layer=bottom]>[data-gly-sheet-grip]{left:0;right:0;top:0;height:24px}",
94    "[data-gly-sheet][data-gly-layer=top]>[data-gly-sheet-grip]{left:0;right:0;bottom:0;height:24px}",
95    "[data-gly-sheet][data-gly-layer=left]>[data-gly-sheet-grip]{right:0;top:0;bottom:0;width:24px}",
96    "[data-gly-sheet][data-gly-layer=right]>[data-gly-sheet-grip]{left:0;top:0;bottom:0;width:24px}",
97    "[data-gly-sheet][data-gly-layer=left]>[data-gly-sheet-grip]>*,[data-gly-sheet][data-gly-layer=right]>[data-gly-sheet-grip]>*{width:4px!important;height:48px!important}",
98    "[data-gly-layer]:not(:popover-open){display:none!important}",
99    "[data-gly-layer]{position:fixed;inset:auto;margin:0;max-width:calc(100vw - 24px);max-height:calc(100dvh - 24px);overflow:auto;overscroll-behavior:contain}",
100    "[data-gly-anchor-match-width]{width:var(--gly-anchor-width)!important}",
101    "[data-gly-anchor-arrow]{overflow:visible}",
102    "[data-gly-anchor-arrow]::before{content:\"\";position:absolute;z-index:-1;width:var(--gly-anchor-arrow-size);height:var(--gly-anchor-arrow-size);border-radius:var(--gly-anchor-arrow-radius);background:inherit;border:inherit;transform:rotate(45deg);box-sizing:border-box}",
103    "[data-gly-anchor-arrow][data-gly-anchor-resolved=bottom]::before{left:calc(var(--gly-anchor-arrow-cross) - var(--gly-anchor-arrow-size)/2);top:calc(var(--gly-anchor-arrow-size)/-2)}",
104    "[data-gly-anchor-arrow][data-gly-anchor-resolved=top]::before{left:calc(var(--gly-anchor-arrow-cross) - var(--gly-anchor-arrow-size)/2);bottom:calc(var(--gly-anchor-arrow-size)/-2)}",
105    "[data-gly-anchor-arrow][data-gly-anchor-resolved=right]::before{top:calc(var(--gly-anchor-arrow-cross) - var(--gly-anchor-arrow-size)/2);left:calc(var(--gly-anchor-arrow-size)/-2)}",
106    "[data-gly-anchor-arrow][data-gly-anchor-resolved=left]::before{top:calc(var(--gly-anchor-arrow-cross) - var(--gly-anchor-arrow-size)/2);right:calc(var(--gly-anchor-arrow-size)/-2)}",
107    "[data-gly-drag-preview]{position:fixed;top:0;left:0;z-index:2147483647;pointer-events:none;user-select:none;",
108    "max-width:min(220px,calc(100vw - 16px));padding:6px 12px;border-radius:8px;",
109    "border:1px solid var(--gly-drag-preview-line,GrayText);background:var(--gly-drag-preview-bg,Canvas);",
110    "color:var(--gly-drag-preview-text,CanvasText);box-shadow:0 6px 18px #0004;",
111    "text-overflow:ellipsis;white-space:nowrap;overflow:hidden}",
112    "[data-gly-layer=center]{top:50%;left:50%;transform:translate(-50%,-50%)}",
113    "[data-gly-layer=left]{left:0;top:0;height:100dvh;max-height:100dvh}",
114    "[data-gly-layer=right]{right:0;top:0;height:100dvh;max-height:100dvh}",
115    "[data-gly-layer=top]{left:0;top:0;width:100vw;max-width:100vw}",
116    "[data-gly-layer=bottom]{left:0;bottom:0;width:100vw;max-width:100vw}",
117    "[data-gly-layer=anchor],[data-gly-layer=context-point],[data-gly-layer=viewport]{left:var(--gly-layer-x,12px);top:var(--gly-layer-y,12px)}",
118    "[data-gly-layer][aria-modal=true]::backdrop{background:rgba(0,0,0,.35)}",
119    "[data-gly-hidden]:not([data-gly-collapse]):not([data-gly-presence]){display:none!important}",
120    "[data-gly-presence]{--gly-presence-transform:translate(attr(data-gly-presence-x type(<length>),0px),attr(data-gly-presence-y type(<length>),0px)) scale(attr(data-gly-presence-scale-x type(<number>),1),attr(data-gly-presence-scale-y type(<number>),1)) rotate(attr(data-gly-presence-rotate type(<angle>),0deg)) skew(attr(data-gly-presence-skew-x type(<angle>),0deg),attr(data-gly-presence-skew-y type(<angle>),0deg));opacity:1;transform:none;transform-origin:attr(data-gly-presence-origin-x type(<percentage>),50%) attr(data-gly-presence-origin-y type(<percentage>),50%);transition:opacity attr(data-gly-presence-duration type(<time>),0ms) ease attr(data-gly-presence-delay type(<time>),0ms),transform attr(data-gly-presence-duration type(<time>),0ms) ease attr(data-gly-presence-delay type(<time>),0ms),display attr(data-gly-presence-duration type(<time>),0ms) allow-discrete attr(data-gly-presence-delay type(<time>),0ms)}",
121    "[data-gly-presence-timing=linear]{transition-timing-function:linear}[data-gly-presence-timing=ease-in]{transition-timing-function:ease-in}[data-gly-presence-timing=ease-out]{transition-timing-function:ease-out}[data-gly-presence-timing=ease-in-out]{transition-timing-function:ease-in-out}",
122    "[data-gly-presence=closed]{display:none;opacity:attr(data-gly-presence-opacity type(<number>),0);transform:var(--gly-presence-transform);pointer-events:none}",
123    "@starting-style{[data-gly-presence=open][data-gly-presence-appear],[data-gly-presence=open]:not([data-gly-presence-revision=\"0\"]){opacity:attr(data-gly-presence-opacity type(<number>),0);transform:var(--gly-presence-transform)}}",
124    "[data-gly-presence-settled],[data-gly-presence-duration=\"0ms\"],[data-gly-presence-effect=none],[data-gly-app][data-gly-presence-static] [data-gly-presence]{transition:none!important}",
125    "@media(prefers-reduced-motion:reduce){[data-gly-presence]{transition:none!important}}",
126    "[data-gly-collapse]{interpolate-size:allow-keywords;overflow:hidden!important;transition:height attr(data-gly-collapse-duration type(<time>),0ms) linear}",
127    "[data-gly-collapse=open]{height:auto!important}",
128    "[data-gly-collapse=closed]{height:0!important}",
129    "[data-gly-collapse-duration=\"0ms\"]{transition:none}",
130    "@media(prefers-reduced-motion:reduce){[data-gly-collapse]{transition:none!important}}",
131    "[data-gly-app][data-gly-collapse-static] [data-gly-collapse]{transition:none!important}",
132    "[data-gly-kind]{box-sizing:border-box}[data-gly-kind=text]{margin:0;font:inherit}",
133    "[data-gly-kind=select],[data-gly-kind=button],[data-gly-kind=file],[data-gly-kind=input],[data-gly-kind=check] input{font:inherit}",
134    "[data-gly-virtual=surface]:not([data-gly-live]){height:auto!important;overflow:visible!important}",
135    "[data-gly-virtual=row]:not([data-gly-live]){display:flow-root!important;position:relative!important;top:auto!important;left:auto!important}",
136);
137
138/// HTML parsing canonicalizes CR/CRLF and NUL. DOM creation must do so too.
139pub fn normalize(value: &str) -> String {
140    glory_render::normalize_text(value, true).into_owned()
141}
142
143/// Escape already serialized JSON for an HTML script raw-text body. HTML
144/// entity escaping is wrong here: script text does not decode &quot;/&lt;.
145pub fn escape_script_data(json: &str) -> String {
146    let mut escaped = String::with_capacity(json.len());
147    for ch in json.chars() {
148        match ch {
149            '<' => escaped.push_str("\\u003c"),
150            '>' => escaped.push_str("\\u003e"),
151            '&' => escaped.push_str("\\u0026"),
152            '\u{2028}' => escaped.push_str("\\u2028"),
153            '\u{2029}' => escaped.push_str("\\u2029"),
154            _ => escaped.push(ch),
155        }
156    }
157    escaped
158}
159
160#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
161pub enum Part {
162    Main,
163    Control,
164    Content,
165    Picker,
166}
167impl Part {
168    pub fn name(self) -> &'static str {
169        match self {
170            Self::Main => "main",
171            Self::Control => "control",
172            Self::Content => "content",
173            Self::Picker => "picker",
174        }
175    }
176}
177#[derive(Clone, Debug, PartialEq, Eq)]
178pub enum Property {
179    Text(String),
180    Bool(bool),
181    SelectedKeys(Vec<String>),
182    RichDocument(std::rc::Rc<glory_render::RichDocument>),
183}
184#[derive(Clone, Debug, PartialEq, Eq)]
185pub enum Kind {
186    Element {
187        tag: &'static str,
188        attributes: BTreeMap<&'static str, String>,
189        properties: BTreeMap<&'static str, Property>,
190    },
191    Text(String),
192}
193#[derive(Clone, Debug, PartialEq, Eq)]
194pub struct Piece {
195    pub part: Part,
196    pub parent: Option<Part>,
197    pub kind: Kind,
198}
199#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
200pub enum EditKind {
201    #[default]
202    None,
203    Text,
204    Check,
205    Select,
206    Rich,
207}
208#[derive(Clone, Debug, PartialEq, Eq)]
209pub struct SelectOptions {
210    pub entries: std::rc::Rc<Vec<glory_render::SelectEntry>>,
211    /// Single controls always own one private, disabled empty-selection option.
212    pub placeholder: Option<String>,
213}
214#[derive(Clone, Debug, Default, PartialEq, Eq)]
215pub struct Shape {
216    pub display: Option<display::Placement>,
217    /// Empty pieces describe a comment-delimited Group, not an element.
218    pub pieces: Vec<Piece>,
219    pub select_options: Option<SelectOptions>,
220    pub children: Option<Part>,
221    pub control: Option<Part>,
222    pub edit: EditKind,
223    pub revision: u64,
224    pub prevent_activate_default: bool,
225}
226impl Shape {
227    /// The physical range root may differ from the semantic main/control node.
228    /// Groups have comment boundaries and therefore no physical root part.
229    pub fn root_part(&self) -> Result<Part, Error> {
230        let mut seen = std::collections::BTreeSet::new();
231        let mut root = None;
232        for piece in &self.pieces {
233            if !seen.insert(piece.part) {
234                return Err(Error::InvalidProps("duplicate HTML part"));
235            }
236            match piece.parent {
237                Some(parent) if parent == piece.part || !seen.contains(&parent) => {
238                    return Err(Error::InvalidProps("HTML part parent order"));
239                }
240                None if root.replace(piece.part).is_some() => {
241                    return Err(Error::InvalidProps("multiple HTML part roots"));
242                }
243                _ => {}
244            }
245        }
246        if !seen.contains(&Part::Main)
247            || self.control.is_some_and(|part| !seen.contains(&part))
248            || self.children.is_some_and(|part| !seen.contains(&part))
249        {
250            return Err(Error::InvalidProps("missing HTML part"));
251        }
252        root.ok_or(Error::Unsupported("Group has no physical root part"))
253    }
254}
255#[derive(Clone, Debug, PartialEq, Eq)]
256pub enum Edit {
257    Revision(u64),
258    Attribute {
259        part: Part,
260        name: &'static str,
261        value: Option<String>,
262    },
263    Property {
264        part: Part,
265        name: &'static str,
266        value: Property,
267    },
268    Text {
269        part: Part,
270        value: String,
271    },
272}
273#[derive(Clone, Debug, PartialEq)]
274pub enum Op {
275    Create {
276        id: NodeId,
277        key: u64,
278        shape: Shape,
279    },
280    Patch {
281        id: NodeId,
282        edits: Vec<Edit>,
283    },
284    Place {
285        id: NodeId,
286        parent: Option<NodeId>,
287        before: Option<NodeId>,
288    },
289    Suspend {
290        id: NodeId,
291    },
292    Dispose {
293        id: NodeId,
294        subtree: Vec<NodeId>,
295    },
296}
297pub trait Sink {
298    fn apply(&mut self, op: Op) -> Result<(), Error>;
299    /// Opt in to updating an existing inline flex-grow declaration alone.
300    fn supports_flex_grow_patch(&self) -> bool {
301        false
302    }
303    fn set_flex_grow(&mut self, _id: NodeId, _value: f64) -> Result<(), Error> {
304        Err(Error::Unsupported("incremental flex-grow"))
305    }
306    /// A detached semantic construction unit. Hosts without subtree cloning
307    /// expand it into their existing finite operations; stream v3 stays intact.
308    fn create_plan(
309        &mut self,
310        plan: &glory_render::Plan,
311        ids: &[NodeId],
312        keys: &[u64],
313        shape: &PlanShape,
314    ) -> Result<(), Error> {
315        shape.validate_instance(plan, ids, keys)?;
316        for (index, node) in shape.shapes.iter().enumerate() {
317            self.apply(Op::Create {
318                id: ids[index],
319                key: keys[index],
320                shape: node.clone(),
321            })?;
322            if let Some(parent) = shape.parents[index] {
323                self.apply(Op::Place {
324                    id: ids[index],
325                    parent: Some(ids[parent]),
326                    before: None,
327                })?;
328            }
329        }
330        Ok(())
331    }
332}
333
334#[derive(Clone, Copy, Debug, PartialEq, Eq)]
335pub enum TextTag {
336    Span,
337    Code,
338    Kbd,
339    Mark,
340    P,
341    H1,
342    H2,
343    H3,
344    H4,
345    H5,
346    H6,
347}
348#[derive(Clone, Debug, Default)]
349pub struct HtmlTextOptions {
350    pub tag: Option<TextTag>,
351}
352impl HtmlTextOptions {
353    pub fn tag(mut self, tag: TextTag) -> Self {
354        self.tag = Some(tag);
355        self
356    }
357}
358#[derive(Clone, Debug, Default)]
359pub struct HtmlEventOptions {
360    pub prevent_default: bool,
361}
362impl HtmlEventOptions {
363    pub fn prevent_default(mut self, value: bool) -> Self {
364        self.prevent_default = value;
365        self
366    }
367}
368
369pub struct Mapper {
370    tree: Memory,
371    keys: HashMap<NodeId, u64>,
372    next_key: u64,
373    receipt: Receipt,
374    plans: plan::Plans,
375}
376mod submission;
377pub use submission::{PreparedOp, Submission};
378impl Mapper {
379    pub fn new(runtime: RuntimeId) -> Self {
380        Self {
381            tree: Memory::new(runtime),
382            keys: HashMap::new(),
383            next_key: 0,
384            receipt: Receipt::default(),
385            plans: plan::Plans::default(),
386        }
387    }
388    pub fn tree(&self) -> &Memory {
389        &self.tree
390    }
391    /// Admit a host action identity without exposing mutable descriptors.
392    pub fn admit_file_action(&mut self, action: glory_render::Action) -> Result<(), Error> {
393        self.tree.admit_file_action(action)
394    }
395    pub fn finish_files(
396        &mut self,
397        node: NodeId,
398        document: glory_render::FileDocumentId,
399        event: &glory_render::FileEvent,
400    ) -> Result<bool, Error> {
401        self.tree.finish_files(node, document, event)
402    }
403    pub fn admit_clipboard(&mut self, action: glory_render::Action) -> Result<(), Error> {
404        self.tree.admit_clipboard(action)
405    }
406    pub fn finish_clipboard(
407        &mut self,
408        node: NodeId,
409        request: u64,
410        revision: u64,
411    ) -> Result<bool, Error> {
412        self.tree.finish_clipboard(node, request, revision)
413    }
414    pub fn key(&self, id: NodeId) -> Option<u64> {
415        self.keys.get(&id).copied()
416    }
417    /// Last successful prefix, including when a later mutation failed.
418    pub fn receipt(&self) -> Receipt {
419        self.receipt
420    }
421    pub fn html(&self) -> Result<String, Error> {
422        serialize(&self.tree, |id| self.key(id))
423    }
424    /// Final snapshot keys follow the logical tree, independent of asynchronous
425    /// completion/creation order. Hidden/unplaced nodes get unique trailing
426    /// keys; only visible tree keys participate in HTML adoption. A streaming
427    /// consumer uses the returned pairs to relabel metadata without remounting.
428    pub fn canonicalize(&mut self) -> Result<Vec<(u64, u64)>, Error> {
429        let mut order = Vec::with_capacity(self.keys.len());
430        let mut seen = std::collections::HashSet::new();
431        let mut pending: Vec<_> = self.tree.roots().iter().rev().copied().collect();
432        while let Some(id) = pending.pop() {
433            if self.tree.node(id)?.suspended {
434                continue;
435            }
436            if !seen.insert(id) {
437                continue;
438            }
439            order.push(id);
440            pending.extend(self.tree.node(id)?.children.iter().rev().copied());
441        }
442        let mut trailing: Vec<_> = self
443            .keys
444            .iter()
445            .filter(|(id, _)| !seen.contains(id))
446            .map(|(id, key)| (*key, *id))
447            .collect();
448        trailing.sort_by_key(|(key, _)| *key);
449        order.extend(trailing.into_iter().map(|(_, id)| id));
450        let mut pairs = Vec::with_capacity(order.len());
451        for (index, id) in order.into_iter().enumerate() {
452            let key = u64::try_from(index)
453                .map_err(|_| Error::InvalidProps("HTML key space exhausted"))?;
454            let old = self.keys.insert(id, key).expect("live HTML key");
455            pairs.push((old, key));
456        }
457        self.next_key = u64::try_from(self.keys.len())
458            .map_err(|_| Error::InvalidProps("HTML key space exhausted"))?;
459        Ok(pairs)
460    }
461    pub fn apply(
462        &mut self,
463        mutations: &[Mutation],
464        sink: &mut impl Sink,
465    ) -> Result<Receipt, Error> {
466        let mut receipt = self.receipt;
467        for mutation in mutations {
468            let op = match mutation {
469                Mutation::CreatePlan { plan, ids } => {
470                    preflight_place(&self.tree, Subtree::Plan(plan), None)?;
471                    let shape = self.plans.shape(plan)?;
472                    let end = self
473                        .next_key
474                        .checked_add(ids.len() as u64)
475                        .ok_or(Error::InvalidProps("HTML key space exhausted"))?;
476                    receipt = self.tree.apply(std::slice::from_ref(mutation))?;
477                    let keys: Vec<_> = (self.next_key..end).collect();
478                    for (id, key) in ids.iter().zip(&keys) {
479                        self.keys.insert(*id, *key);
480                    }
481                    self.next_key = end;
482                    sink.create_plan(plan, ids, &keys, &shape)?;
483                    self.receipt = receipt;
484                    continue;
485                }
486                Mutation::Create { id, node } => {
487                    let shape = shape(node.view())?;
488                    let key = self.next_key;
489                    self.next_key = self
490                        .next_key
491                        .checked_add(1)
492                        .ok_or(Error::InvalidProps("HTML key space exhausted"))?;
493                    receipt = self.tree.apply(std::slice::from_ref(mutation))?;
494                    self.keys.insert(*id, key);
495                    Op::Create {
496                        id: *id,
497                        key,
498                        shape,
499                    }
500                }
501                Mutation::Patch { id, patch } => {
502                    let descriptor = self.tree.node(*id)?.descriptor.view();
503                    preflight(descriptor, Some(patch))?;
504                    let prepared = self.tree.prepare_patch(*id, patch)?;
505                    if sink.supports_flex_grow_patch()
506                        && let Some(grow) =
507                            patch::flex_grow(prepared.descriptor(), prepared.previous())
508                    {
509                        receipt = prepared.commit();
510                        sink.set_flex_grow(*id, grow)?;
511                        self.receipt = receipt;
512                        continue;
513                    }
514                    let edits = patch::lower(prepared.descriptor(), prepared.previous());
515                    receipt = prepared.commit();
516                    Op::Patch { id: *id, edits }
517                }
518                Mutation::Place { id, parent, before }
519                | Mutation::Resume { id, parent, before } => {
520                    self.tree.validate_placement(
521                        *id,
522                        *parent,
523                        *before,
524                        matches!(mutation, Mutation::Resume { .. }),
525                    )?;
526                    preflight_place(&self.tree, Subtree::Existing(*id), *parent)?;
527                    receipt = self.tree.apply(std::slice::from_ref(mutation))?;
528                    let siblings = if let Some(parent) = parent {
529                        &self.tree.node(*parent)?.children
530                    } else {
531                        self.tree.roots()
532                    };
533                    let before = before
534                        .and_then(|before| siblings.iter().position(|id| *id == before))
535                        .and_then(|index| {
536                            siblings[index..]
537                                .iter()
538                                .copied()
539                                .find(|id| !self.tree.node(*id).expect("sibling").suspended)
540                        });
541                    Op::Place {
542                        id: *id,
543                        parent: *parent,
544                        before,
545                    }
546                }
547                Mutation::Suspend { id } => {
548                    receipt = self.tree.apply(std::slice::from_ref(mutation))?;
549                    Op::Suspend { id: *id }
550                }
551                Mutation::Dispose { id } => {
552                    let (accepted, subtree) = self.tree.dispose(*id)?;
553                    receipt = accepted;
554                    for id in &subtree {
555                        self.keys.remove(id);
556                    }
557                    Op::Dispose { id: *id, subtree }
558                }
559            };
560            sink.apply(op)?;
561            self.receipt = receipt;
562        }
563        Ok(receipt)
564    }
565}
566
567/// HTML ancestor checks over the supplied staged semantic tree, never a host
568/// lookup. New children need no subtree allocation; ordinary list moves only
569/// walk ancestors. A button destination additionally examines live descendants.
570pub fn preflight_place(
571    tree: &Memory,
572    child: Subtree<'_>,
573    parent: Option<NodeId>,
574) -> Result<(), Error> {
575    let descriptor = match child {
576        Subtree::New(descriptor) => Some(descriptor),
577        Subtree::Existing(id) => Some(tree.node(id)?.descriptor.view()),
578        _ => None,
579    };
580    if let Some(parent) = parent
581        && let Some(display::Placement::Root(frame)) = tree
582            .node(parent)?
583            .descriptor
584            .view()
585            .options
586            .get::<display::Placement>()
587        && !matches!(descriptor.and_then(|d|d.options.get::<display::Placement>()),Some(display::Placement::Outlet{frame:child_frame,slot}) if std::rc::Rc::ptr_eq(frame,child_frame)&&frame.compiled().slots.get(*slot as usize).is_some_and(|slot|matches!(slot.kind,template::Kind::Children|template::Kind::Range)))
588    {
589        return Err(Error::InvalidPlacement(
590            "display root children require their declared outlet",
591        ));
592    }
593    if let Subtree::Plan(plan) = child
594        && plan.nodes().iter().any(|node| {
595            node.descriptor
596                .view()
597                .options
598                .get::<display::Placement>()
599                .is_some()
600        })
601    {
602        return Err(Error::InvalidProps(
603            "display instance state cannot be shared in a static Plan",
604        ));
605    }
606    let mut cursor = parent;
607    let mut raw_context = None;
608    while let Some(id) = cursor {
609        let node = tree.node(id)?;
610        let descriptor = node.descriptor.view();
611        if let Some(display::Placement::Outlet { frame, slot }) =
612            descriptor.options.get::<display::Placement>()
613        {
614            raw_context = frame.context(*slot);
615            break;
616        }
617        if let Some(tag) = mapping::physical_tag(descriptor)? {
618            if let Some(display::Placement::Root(frame)) = match child {
619                Subtree::New(descriptor) => descriptor.options.get::<display::Placement>(),
620                Subtree::Existing(id) => tree
621                    .node(id)?
622                    .descriptor
623                    .view()
624                    .options
625                    .get::<display::Placement>(),
626                _ => None,
627            } && !frame.accepts(tag)
628            {
629                return Err(Error::InvalidPlacement(
630                    "display template physical parent context",
631                ));
632            }
633            break;
634        }
635        cursor = node.parent;
636    }
637    if let Some(context) = raw_context {
638        let check = |descriptor: glory_render::DescriptorView<'_>| -> Result<(), Error> {
639            if let Some(display::Placement::Root(frame)) =
640                descriptor.options.get::<display::Placement>()
641            {
642                if !frame.accepts(context) {
643                    return Err(Error::InvalidPlacement(
644                        "display template root content context",
645                    ));
646                }
647            } else if let Some(tag) = mapping::physical_tag(descriptor)? {
648                let accepted = match context {
649                    "table" => matches!(tag, "tbody" | "thead" | "tfoot" | "caption" | "colgroup"),
650                    "tbody" => tag == "tr",
651                    "tr" => matches!(tag, "td" | "th"),
652                    _ => !matches!(tag, "tbody" | "thead" | "tfoot" | "tr" | "td" | "th"),
653                };
654                if !accepted {
655                    return Err(Error::InvalidPlacement("widget root content context"));
656                }
657            }
658            Ok(())
659        };
660        match child {
661            Subtree::New(descriptor) => check(descriptor)?,
662            Subtree::Existing(id) => {
663                let mut pending = vec![id];
664                while let Some(id) = pending.pop() {
665                    let node = tree.node(id)?;
666                    let descriptor = node.descriptor.view();
667                    check(descriptor)?;
668                    if mapping::physical_tag(descriptor)?.is_none()
669                        && descriptor.options.get::<display::Placement>().is_none()
670                    {
671                        pending.extend(node.children.iter().copied());
672                    }
673                }
674            }
675            Subtree::Plan(plan) => {
676                for node in plan.nodes().iter().filter(|node| node.parent.is_none()) {
677                    check(node.descriptor.view())?;
678                }
679            }
680        }
681    }
682    if let Subtree::Existing(id) = child {
683        tree.node(id)?;
684    }
685    let mut cursor = parent;
686    let mut button = false;
687    while let Some(ancestor) = cursor {
688        if matches!(child, Subtree::Existing(id) if ancestor == id) {
689            return Err(Error::InvalidPlacement("tree cycle"));
690        }
691        let node = tree.node(ancestor)?;
692        button |= matches!(
693            node.descriptor.view().props,
694            glory_render::Props::Button(_)
695                | glory_render::Props::File(_)
696                | glory_render::Props::Link(_)
697        );
698        cursor = node.parent;
699    }
700    // Semantic Inline text may explicitly map to <p>. That extension must
701    // not bypass the button's phrasing-only content model, including when
702    // a previously built Group is moved into a button. Ordinary list moves
703    // do not scan their subtree.
704    if button || matches!(child, Subtree::Plan(_)) {
705        let check = |descriptor: glory_render::DescriptorView<'_>| {
706            if let Some(display::Placement::Root(frame)) =
707                descriptor.options.get::<display::Placement>()
708                && !frame.phrasing()
709            {
710                return Err(Error::InvalidProps(
711                    "interactive widget display content must be text or spans without dynamic outlets",
712                ));
713            }
714            if matches!(descriptor.props, glory_render::Props::Text(_))
715                && descriptor
716                    .options
717                    .get::<HtmlTextOptions>()
718                    .is_some_and(|options| options.tag == Some(TextTag::P))
719            {
720                return Err(Error::InvalidProps(
721                    "button text cannot map to an HTML paragraph",
722                ));
723            }
724            Ok(())
725        };
726        match child {
727            Subtree::Plan(plan) => {
728                for (index, node) in plan.nodes().iter().enumerate() {
729                    let mut ancestor = plan.nodes()[index].parent;
730                    let mut in_button = button;
731                    while let Some(parent) = ancestor {
732                        in_button |= matches!(
733                            plan.nodes()[parent].descriptor.view().props,
734                            glory_render::Props::Button(_) | glory_render::Props::File(_)
735                        );
736                        ancestor = plan.nodes()[parent].parent;
737                    }
738                    if in_button {
739                        check(node.descriptor.view())?;
740                    }
741                }
742            }
743            Subtree::New(descriptor) => check(descriptor)?,
744            Subtree::Existing(id) => {
745                let mut pending = vec![id];
746                while let Some(id) = pending.pop() {
747                    let node = tree.node(id)?;
748                    check(node.descriptor.view())?;
749                    pending.extend(node.children.iter().copied());
750                }
751            }
752        }
753    }
754    Ok(())
755}
756
757#[cfg(test)]
758fn difference(
759    old: &Shape,
760    new: &Shape,
761    checked_write: bool,
762    mode_write: bool,
763    select_write: bool,
764) -> Result<Vec<Edit>, Error> {
765    if old.pieces.len() != new.pieces.len()
766        || old.control != new.control
767        || old.edit != new.edit
768        || old.prevent_activate_default != new.prevent_activate_default
769        || old.select_options != new.select_options
770    {
771        return Err(Error::InvalidProps(
772            "HTML structure changes require remount",
773        ));
774    }
775    let mut edits = Vec::new();
776    let revision = old.revision != new.revision;
777    if revision {
778        edits.push(Edit::Revision(new.revision));
779    }
780    for (old, new) in old.pieces.iter().zip(&new.pieces) {
781        if old.part != new.part || old.parent != new.parent {
782            return Err(Error::InvalidProps(
783                "HTML structure changes require remount",
784            ));
785        }
786        match (&old.kind, &new.kind) {
787            (Kind::Text(old), Kind::Text(new_value)) => {
788                if old != new_value {
789                    edits.push(Edit::Text {
790                        part: new.part,
791                        value: new_value.clone(),
792                    });
793                }
794            }
795            (
796                Kind::Element {
797                    tag: a,
798                    attributes: old,
799                    properties: old_props,
800                },
801                Kind::Element {
802                    tag: b,
803                    attributes: attrs,
804                    properties,
805                },
806            ) if a == b => {
807                for (name, value) in attrs {
808                    if old.get(name) != Some(value) || revision && *name == "src" && *a == "img" {
809                        edits.push(Edit::Attribute {
810                            part: new.part,
811                            name,
812                            value: Some(value.clone()),
813                        });
814                    }
815                }
816                for name in old.keys() {
817                    if !attrs.contains_key(name) {
818                        edits.push(Edit::Attribute {
819                            part: new.part,
820                            name,
821                            value: None,
822                        });
823                    }
824                }
825                for (name, value) in properties {
826                    if old_props.get(name) != Some(value)
827                        || revision && matches!(*name, "value" | "richDocument")
828                        || select_write && *name == "selectedKeys"
829                        || checked_write && *name == "checked"
830                        || *name == "checked" && old.get("type") != attrs.get("type")
831                        || mode_write && *name == "indeterminate"
832                    {
833                        edits.push(Edit::Property {
834                            part: new.part,
835                            name,
836                            value: value.clone(),
837                        });
838                    }
839                }
840            }
841            _ => return Err(Error::InvalidProps("HTML tag changes require remount")),
842        }
843    }
844    Ok(edits)
845}
846
847#[cfg(test)]
848mod clipboard_tests;
849#[cfg(test)]
850mod table_tests;
851#[cfg(test)]
852mod tree_tests;
853
854#[cfg(test)]
855mod file_shape_tests {
856    use super::*;
857    use glory_render::{Descriptor, FileConfig, FileFilter, FileProps, Mutation, NodeIds, Props};
858
859    #[test]
860    fn file_range_root_keeps_real_button_and_hidden_picker_siblings() {
861        let runtime = RuntimeId::new();
862        let id = NodeIds::new(runtime).allocate();
863        let node = Descriptor::new(Props::File(FileProps {
864            label: "Select <file>".into(),
865            configuration: FileConfig {
866                multiple: true,
867                max_files: 2,
868                filters: vec![FileFilter::Mime("image/png".into())],
869                ..Default::default()
870            },
871            ..Default::default()
872        }));
873        let shape = shape(&node).unwrap();
874        assert_eq!(shape.root_part().unwrap(), Part::Control);
875        assert_eq!(shape.control, Some(Part::Main));
876        assert_eq!(shape.children, None);
877        for part in [Part::Main, Part::Picker] {
878            assert_eq!(
879                shape.pieces.iter().find(|p| p.part == part).unwrap().parent,
880                Some(Part::Control)
881            );
882        }
883        let mut tree = Memory::new(runtime);
884        tree.apply(&[
885            Mutation::Create {
886                id,
887                node: Box::new(node),
888            },
889            Mutation::Place {
890                id,
891                parent: None,
892                before: None,
893            },
894        ])
895        .unwrap();
896        let html = serialize(&tree, |_| Some(1)).unwrap();
897        assert!(html.starts_with("<span data-gly-key=\"1\" data-gly-part=\"control\""));
898        assert!(html.contains("<button "));
899        assert!(html.contains("Select &lt;file&gt;</button><input "));
900        assert!(html.contains("accept=\"image/png\""));
901        assert!(html.contains("type=\"file\""));
902        assert!(html.ends_with("></span>"));
903        assert!(!html.contains("value="));
904    }
905
906    #[test]
907    fn physical_root_validation_rejects_missing_duplicate_and_disconnected_parts() {
908        let mut shape = shape(&Descriptor::new(Props::File(FileProps::default()))).unwrap();
909        let original = shape.clone();
910        shape.pieces[1].parent = None;
911        assert!(shape.root_part().is_err());
912        shape = original.clone();
913        shape.pieces[1].part = Part::Picker;
914        assert!(shape.root_part().is_err());
915        shape = original.clone();
916        shape.pieces[0].parent = Some(Part::Main);
917        assert!(shape.root_part().is_err());
918        shape = original;
919        shape.pieces.retain(|p| p.part != Part::Main);
920        assert!(shape.root_part().is_err());
921        assert!(Shape::default().root_part().is_err());
922    }
923}
924
925#[cfg(test)]
926mod swipe_tests;