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