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