Skip to main content

glory_html/
mapping.rs

1use crate::*;
2use glory_render::{Change, Error, FocusMode, Patch, Props, Purpose, Role, TextKind};
3use std::collections::BTreeMap;
4
5fn normalize_in_place(value: &mut String) {
6    if let std::borrow::Cow::Owned(normalized) = glory_render::normalize_text(value, true) {
7        *value = normalized;
8    }
9}
10
11fn element(part: Part, parent: Option<Part>, tag: &'static str) -> Piece {
12    Piece {
13        part,
14        parent,
15        kind: Kind::Element {
16            tag,
17            attributes: BTreeMap::new(),
18            properties: BTreeMap::new(),
19        },
20    }
21}
22fn attrs(shape: &mut Shape, part: Part) -> &mut BTreeMap<&'static str, String> {
23    let Kind::Element { attributes, .. } = &mut shape
24        .pieces
25        .iter_mut()
26        .find(|piece| piece.part == part)
27        .expect("element part")
28        .kind
29    else {
30        unreachable!()
31    };
32    attributes
33}
34fn props(shape: &mut Shape, part: Part) -> &mut BTreeMap<&'static str, Property> {
35    let Kind::Element { properties, .. } = &mut shape
36        .pieces
37        .iter_mut()
38        .find(|piece| piece.part == part)
39        .expect("element part")
40        .kind
41    else {
42        unreachable!()
43    };
44    properties
45}
46fn text(shape: &mut Shape, value: &str) {
47    shape.pieces.push(Piece {
48        part: Part::Content,
49        parent: Some(Part::Main),
50        kind: Kind::Text(value.to_owned()),
51    });
52}
53fn enabled(shape: &mut Shape, part: Part, enabled: bool) {
54    attrs(shape, Part::Main).insert(
55        if enabled {
56            "data-gly-enabled"
57        } else {
58            "data-gly-disabled"
59        },
60        String::new(),
61    );
62    props(shape, part).insert("disabled", Property::Bool(!enabled));
63    if !enabled {
64        attrs(shape, part).insert("disabled", String::new());
65    }
66}
67fn changed<T: Copy + Default>(old: T, change: &Change<T>) -> T {
68    match change {
69        Change::Keep => old,
70        Change::Set(value) => *value,
71        Change::Clear => T::default(),
72    }
73}
74fn view_tag(
75    role: Option<Role>,
76    part: Option<glory_render::FieldPart>,
77    document: Option<glory_render::DocumentPart>,
78) -> &'static str {
79    if let Some(document) = document {
80        return match document {
81            glory_render::DocumentPart::Blockquote => "blockquote",
82            glory_render::DocumentPart::OrderedList => "ol",
83            glory_render::DocumentPart::UnorderedList => "ul",
84            glory_render::DocumentPart::ListItem => "li",
85            glory_render::DocumentPart::DescriptionList => "dl",
86            glory_render::DocumentPart::Term => "dt",
87            glory_render::DocumentPart::Definition => "dd",
88            glory_render::DocumentPart::Table => "table",
89            glory_render::DocumentPart::TableCaption => "caption",
90            glory_render::DocumentPart::TableHead => "thead",
91            glory_render::DocumentPart::TableBody => "tbody",
92            glory_render::DocumentPart::TableFoot => "tfoot",
93            glory_render::DocumentPart::TableRow => "tr",
94            glory_render::DocumentPart::ColumnHeader | glory_render::DocumentPart::RowHeader => {
95                "th"
96            }
97            glory_render::DocumentPart::TableCell => "td",
98        };
99    }
100    if let Some(part) = part {
101        return match part {
102            glory_render::FieldPart::Form => "form",
103            glory_render::FieldPart::Label => "label",
104            glory_render::FieldPart::Fieldset => "fieldset",
105            glory_render::FieldPart::Legend => "legend",
106        };
107    }
108    match role {
109        Some(Role::Main) => "main",
110        Some(Role::Banner) => "header",
111        Some(Role::ContentInfo) => "footer",
112        Some(Role::Navigation) => "nav",
113        Some(Role::Section) => "section",
114        _ => "div",
115    }
116}
117pub(crate) fn role_name(role: Role) -> &'static str {
118    match role {
119        Role::ProgressBar => "progressbar",
120        Role::Slider => "slider",
121        Role::SpinButton => "spinbutton",
122        Role::Separator => "separator",
123        Role::Group => "group",
124        Role::Main => "main",
125        Role::Banner => "banner",
126        Role::ContentInfo => "contentinfo",
127        Role::Navigation => "navigation",
128        Role::Section => "region",
129        Role::List => "list",
130        Role::ListItem => "listitem",
131        Role::Status => "status",
132        Role::Alert => "alert",
133        Role::Table => "table",
134        Role::Grid => "grid",
135        Role::GridCell => "gridcell",
136        Role::Tree => "tree",
137        Role::TreeItem => "treeitem",
138        Role::Row => "row",
139        Role::ColumnHeader => "columnheader",
140        Role::Cell => "cell",
141        Role::Dialog => "dialog",
142        Role::AlertDialog => "alertdialog",
143        Role::Tooltip => "tooltip",
144        Role::TabList => "tablist",
145        Role::TabPanel => "tabpanel",
146        Role::RadioGroup => "radiogroup",
147        Role::Toolbar => "toolbar",
148        Role::Menu => "menu",
149        Role::Menubar => "menubar",
150        Role::Listbox => "listbox",
151        Role::Heading(_) => "heading",
152    }
153}
154pub(crate) fn input_type(purpose: Purpose) -> &'static str {
155    match purpose {
156        Purpose::Password => "password",
157        Purpose::Search => "search",
158        Purpose::Tel => "tel",
159        Purpose::Text | Purpose::Number | Purpose::Email | Purpose::Url => "text",
160    }
161}
162pub(crate) fn input_mode(purpose: Purpose) -> Option<&'static str> {
163    match purpose {
164        Purpose::Number => Some("decimal"),
165        Purpose::Email => Some("email"),
166        Purpose::Url => Some("url"),
167        _ => None,
168    }
169}
170fn text_tag(kind: TextKind, options: Option<&HtmlTextOptions>) -> Result<&'static str, Error> {
171    let default = match kind {
172        TextKind::Inline => TextTag::Span,
173        TextKind::Code => TextTag::Code,
174        TextKind::Kbd => TextTag::Kbd,
175        TextKind::Mark => TextTag::Mark,
176        TextKind::Paragraph => TextTag::P,
177        TextKind::Heading(level @ 1..=6) => [
178            TextTag::H1,
179            TextTag::H2,
180            TextTag::H3,
181            TextTag::H4,
182            TextTag::H5,
183            TextTag::H6,
184        ][level as usize - 1],
185        TextKind::Heading(_) => {
186            return Err(Error::InvalidProps("heading level must be 1..=6"));
187        }
188    };
189    let selected = options.and_then(|options| options.tag).unwrap_or(default);
190    if (kind != TextKind::Inline && selected != default)
191        || matches!(kind, TextKind::Inline) && !matches!(selected, TextTag::Span | TextTag::P)
192    {
193        return Err(Error::InvalidProps(
194            "HTML text tag conflicts with semantic kind",
195        ));
196    }
197    Ok(match selected {
198        TextTag::Span => "span",
199        TextTag::Code => "code",
200        TextTag::Kbd => "kbd",
201        TextTag::Mark => "mark",
202        TextTag::P => "p",
203        TextTag::H1 => "h1",
204        TextTag::H2 => "h2",
205        TextTag::H3 => "h3",
206        TextTag::H4 => "h4",
207        TextTag::H5 => "h5",
208        TextTag::H6 => "h6",
209    })
210}
211
212/// Check descriptor-local HTML constraints without shaping text, allocating
213/// styles, reading a host tree or cloning a node's potentially large value.
214/// Creation checks mapping options; patches preserve the existing HTML tag.
215pub fn preflight<'a>(
216    node: impl Into<glory_render::DescriptorView<'a>>,
217    patch: Option<&Patch>,
218) -> Result<(), Error> {
219    let node = node.into();
220    let tags = match (&node.props, patch) {
221        (Props::Text(text), None) => {
222            text_tag(text.kind, node.options.get::<HtmlTextOptions>())?;
223            return Ok(());
224        }
225        (Props::Text(text), Some(Patch::TextKind(change))) => {
226            let options = node.options.get::<HtmlTextOptions>();
227            Some((
228                text_tag(text.kind, options)?,
229                text_tag(changed(text.kind, change), options)?,
230            ))
231        }
232        (Props::View, Some(Patch::Role(change))) => Some((
233            view_tag(node.role, node.field_part(), node.document_part()),
234            view_tag(
235                changed(node.role, change),
236                node.field_part(),
237                node.document_part(),
238            ),
239        )),
240        (Props::View, Some(Patch::Semantics(change))) => {
241            let document = match change {
242                Change::Keep => node.document_part(),
243                Change::Clear => None,
244                Change::Set(value) => value.as_ref().and_then(|s| s.document_part),
245            };
246            let part = match change {
247                Change::Keep => node.field_part(),
248                Change::Clear => None,
249                Change::Set(value) => value.as_ref().and_then(|s| s.field_part),
250            };
251            Some((
252                view_tag(node.role, node.field_part(), node.document_part()),
253                view_tag(node.role, part, document),
254            ))
255        }
256        (Props::Input(input), Some(Patch::Multiline(change)))
257            if input.multiline != changed(input.multiline, change) =>
258        {
259            return Err(Error::InvalidProps("HTML tag changes require remount"));
260        }
261        _ => None,
262    };
263    if tags.is_some_and(|(old, next)| old != next) {
264        return Err(Error::InvalidProps("HTML tag changes require remount"));
265    }
266    Ok(())
267}
268
269pub fn shape<'a>(descriptor: impl Into<glory_render::DescriptorView<'a>>) -> Result<Shape, Error> {
270    shape_view(descriptor.into())
271}
272pub(crate) fn physical_tag(
273    node: glory_render::DescriptorView<'_>,
274) -> Result<Option<&'static str>, Error> {
275    Ok(Some(match node.props {
276        Props::Group => return Ok(None),
277        Props::View => view_tag(node.role, node.field_part(), node.document_part()),
278        Props::Text(text) => text_tag(text.kind, node.options.get::<HtmlTextOptions>())?,
279        Props::Button(_) | Props::File(_) => "button",
280        Props::Input(input) => {
281            if input.multiline {
282                "textarea"
283            } else {
284                "input"
285            }
286        }
287        Props::Select(_) => "select",
288        Props::RichEditor(_) => "div",
289        Props::Check(_) => "label",
290        Props::Image(_) => "img",
291        Props::Graphic(_) => "svg",
292        Props::Link(_) => "a",
293    }))
294}
295
296// Keep the finite lowering shared by owned, live and declared descriptors.
297// The public conversion boundary must not monomorphize this complete mapper.
298fn shape_view(descriptor: glory_render::DescriptorView<'_>) -> Result<Shape, Error> {
299    descriptor.validate()?;
300    if matches!(descriptor.props, Props::Group) {
301        return Ok(Shape {
302            display: descriptor
303                .options
304                .get::<crate::display::Placement>()
305                .cloned(),
306            ..Shape::default()
307        });
308    }
309    let tag = match &descriptor.props {
310        Props::View => view_tag(
311            descriptor.role,
312            descriptor.field_part(),
313            descriptor.document_part(),
314        ),
315        Props::Text(text) => text_tag(text.kind, descriptor.options.get::<HtmlTextOptions>())?,
316        Props::Button(_) => "button",
317        Props::Input(input) if input.multiline => "textarea",
318        Props::Input(_) => "input",
319        Props::RichEditor(_) => "div",
320        Props::File(_) => "button",
321        Props::Select(_) => "select",
322        Props::Check(_) => "label",
323        Props::Image(_) => "img",
324        Props::Graphic(_) => "svg",
325        Props::Link(_) => "a",
326        Props::Group => unreachable!(),
327    };
328    let mut shape = Shape {
329        pieces: vec![element(Part::Main, None, tag)],
330        control: Some(Part::Main),
331        children: descriptor.props.accepts_children().then_some(Part::Main),
332        prevent_activate_default: descriptor
333            .options
334            .get::<HtmlEventOptions>()
335            .is_some_and(|options| options.prevent_default),
336        ..Shape::default()
337    };
338    let kind = match &descriptor.props {
339        Props::RichEditor(value) => {
340            attrs(&mut shape, Part::Main)
341                .insert("data-gly-rich-focus", rich_focus(descriptor.focus).into());
342            attrs(&mut shape, Part::Main).insert(
343                if value.enabled {
344                    "data-gly-enabled"
345                } else {
346                    "data-gly-disabled"
347                },
348                String::new(),
349            );
350            shape.edit = EditKind::Rich;
351            shape.revision = value.revision;
352            props(&mut shape, Part::Main).insert(
353                "richDocument",
354                Property::RichDocument(value.document.clone()),
355            );
356            attrs(&mut shape, Part::Main).insert("role", "textbox".into());
357            attrs(&mut shape, Part::Main).insert("aria-multiline", "true".into());
358            attrs(&mut shape, Part::Main).insert(
359                "contenteditable",
360                if value.enabled && !descriptor.semantics.as_ref().is_some_and(|s| s.readonly) {
361                    "true"
362                } else {
363                    "false"
364                }
365                .into(),
366            );
367            if !value.enabled {
368                attrs(&mut shape, Part::Main).insert("aria-disabled", "true".into());
369            }
370            "rich-editor"
371        }
372        Props::File(value) => {
373            shape.revision = value.revision;
374            shape.pieces[0].parent = Some(Part::Control);
375            shape.pieces.insert(0, element(Part::Control, None, "span"));
376            attrs(&mut shape, Part::Control).insert("style", "display:contents;".into());
377            attrs(&mut shape, Part::Main).insert("type", "button".into());
378            text(&mut shape, &value.label);
379            shape
380                .pieces
381                .push(element(Part::Picker, Some(Part::Control), "input"));
382            attrs(&mut shape, Part::Picker).insert("type", "file".into());
383            attrs(&mut shape, Part::Picker).insert("hidden", String::new());
384            attrs(&mut shape, Part::Picker).insert("tabindex", "-1".into());
385            attrs(&mut shape, Part::Picker).insert("aria-hidden", "true".into());
386            attrs(&mut shape, Part::Picker).extend(file_attributes(&value.configuration));
387            if value.configuration.drop {
388                attrs(&mut shape, Part::Main).insert("data-gly-file-drop", String::new());
389            }
390            enabled(&mut shape, Part::Main, value.enabled);
391            props(&mut shape, Part::Picker).insert("disabled", Property::Bool(!value.enabled));
392            if !value.enabled {
393                attrs(&mut shape, Part::Picker).insert("disabled", String::new());
394            }
395            "file"
396        }
397        Props::View => "view",
398        Props::Text(value) => {
399            text(&mut shape, &value.content);
400            if !value.selectable {
401                attrs(&mut shape, Part::Main).insert("style", "user-select:none;".into());
402            }
403            "text"
404        }
405        Props::Button(value) => {
406            attrs(&mut shape, Part::Main).insert("type", "button".into());
407            text(&mut shape, &value.label);
408            enabled(&mut shape, Part::Main, value.enabled);
409            "button"
410        }
411        Props::Input(value) => {
412            shape.edit = EditKind::Text;
413            shape.revision = value.revision;
414            props(&mut shape, Part::Main).insert("value", Property::Text(value.value.clone()));
415            if !value.multiline {
416                attrs(&mut shape, Part::Main).insert("type", input_type(value.purpose).into());
417                attrs(&mut shape, Part::Main).insert("value", value.value.clone());
418                if let Some(mode) = input_mode(value.purpose) {
419                    attrs(&mut shape, Part::Main).insert("inputmode", mode.into());
420                }
421            }
422            enabled(&mut shape, Part::Main, value.enabled);
423            "input"
424        }
425        Props::Select(value) => {
426            shape.edit = EditKind::Select;
427            shape.revision = value.selection.revision;
428            shape.select_options = Some(crate::SelectOptions {
429                entries: value.entries.clone(),
430                placeholder: (!value.multiple).then(|| value.placeholder.clone()),
431            });
432            props(&mut shape, Part::Main).insert(
433                "selectedKeys",
434                Property::SelectedKeys(
435                    value
436                        .selection
437                        .keys
438                        .iter()
439                        .map(|key| key.as_str().to_owned())
440                        .collect(),
441                ),
442            );
443            if value.multiple {
444                attrs(&mut shape, Part::Main).insert("multiple", String::new());
445            }
446            if let Some(rows) = value.rows {
447                attrs(&mut shape, Part::Main).insert("size", rows.to_string());
448            }
449            enabled(&mut shape, Part::Main, value.enabled);
450            "select"
451        }
452        Props::Check(value) => {
453            shape.control = Some(Part::Control);
454            shape.edit = EditKind::Check;
455            shape
456                .pieces
457                .push(element(Part::Control, Some(Part::Main), "input"));
458            attrs(&mut shape, Part::Control).insert("type", check_type(value.mode).into());
459            if value.checked {
460                attrs(&mut shape, Part::Control).insert("checked", String::new());
461                attrs(&mut shape, Part::Main).insert("data-gly-checked", String::new());
462            }
463            props(&mut shape, Part::Control).insert("checked", Property::Bool(value.checked));
464            props(&mut shape, Part::Control).insert(
465                "indeterminate",
466                Property::Bool(value.mode == glory_render::CheckMode::Mixed),
467            );
468            if value.mode == glory_render::CheckMode::Mixed {
469                attrs(&mut shape, Part::Control).insert("data-gly-indeterminate", String::new());
470                attrs(&mut shape, Part::Main).insert("data-gly-mixed", String::new());
471            }
472            if value.mode == glory_render::CheckMode::Switch {
473                attrs(&mut shape, Part::Control).insert("role", "switch".into());
474            }
475            attrs(&mut shape, Part::Control)
476                .insert("aria-checked", check_aria(value.mode, value.checked).into());
477            enabled(&mut shape, Part::Control, value.enabled);
478            text(&mut shape, &value.label);
479            "check"
480        }
481        Props::Image(value) => {
482            shape.revision = value.revision;
483            if !value.source.is_empty() {
484                attrs(&mut shape, Part::Main).insert("src", value.source.clone());
485            }
486            attrs(&mut shape, Part::Main)
487                .insert("alt", value.alternative.clone().unwrap_or_default());
488            if value.alternative.is_none() {
489                attrs(&mut shape, Part::Main).insert("aria-hidden", "true".into());
490            }
491            if !value.responsive.candidates.is_empty() {
492                attrs(&mut shape, Part::Main).insert(
493                    "srcset",
494                    value
495                        .responsive
496                        .candidates
497                        .iter()
498                        .map(|candidate| format!("{} {}w", candidate.source, candidate.width))
499                        .collect::<Vec<_>>()
500                        .join(", "),
501                );
502                attrs(&mut shape, Part::Main).insert(
503                    "sizes",
504                    value
505                        .responsive
506                        .sizes
507                        .iter()
508                        .map(|hint| {
509                            let slot = match hint.slot {
510                                glory_render::ImageSlotSize::Pixels(value) => format!("{value}px"),
511                                glory_render::ImageSlotSize::ViewportWidth(value) => {
512                                    format!("{value}vw")
513                                }
514                            };
515                            hint.max_viewport_width.map_or(slot.clone(), |width| {
516                                format!("(max-width: {width}px) {slot}")
517                            })
518                        })
519                        .collect::<Vec<_>>()
520                        .join(", "),
521                );
522            }
523            match value.loading {
524                glory_render::ImageLoading::Auto => {}
525                glory_render::ImageLoading::Eager => {
526                    attrs(&mut shape, Part::Main).insert("loading", "eager".into());
527                }
528                glory_render::ImageLoading::Lazy => {
529                    attrs(&mut shape, Part::Main).insert("loading", "lazy".into());
530                }
531            }
532            "image"
533        }
534        Props::Graphic(value) => {
535            attrs(&mut shape, Part::Main)
536                .extend(crate::graphic::main(value, descriptor.name.as_deref()));
537            shape
538                .pieces
539                .push(element(Part::Content, Some(Part::Main), "path"));
540            attrs(&mut shape, Part::Content).extend(crate::graphic::content(value));
541            "graphic"
542        }
543        Props::Link(value) => {
544            attrs(&mut shape, Part::Main).insert("href", value.target.clone());
545            text(&mut shape, &value.label);
546            "link"
547        }
548        Props::Group => unreachable!(),
549    };
550    attrs(&mut shape, Part::Main).insert("data-gly-kind", kind.into());
551    if let Some(part) = descriptor.options.get::<glory_render::VirtualPart>() {
552        attrs(&mut shape, Part::Main).insert(
553            "data-gly-virtual",
554            match part {
555                glory_render::VirtualPart::Root => "root",
556                glory_render::VirtualPart::Surface => "surface",
557                glory_render::VirtualPart::Row => "row",
558            }
559            .into(),
560        );
561    }
562    if !descriptor.classes.is_empty() {
563        attrs(&mut shape, Part::Main).insert("class", descriptor.classes.join(" "));
564    }
565    let mut css = style(descriptor.style);
566    css.push_str(&crate::semantics::translation_style(
567        descriptor.semantics.as_deref().and_then(|s| s.translation),
568    ));
569    if !css.is_empty() {
570        attrs(&mut shape, Part::Main)
571            .entry("style")
572            .or_default()
573            .push_str(&css);
574    }
575    let control = shape.control.expect("element control");
576    if let Some(name) = &descriptor.name {
577        attrs(&mut shape, control).insert("aria-label", name.clone());
578    }
579    // Semantic role and heading metadata are lowered once, by the same path
580    // used for patches. Intrinsic control roles were set above.
581    attrs(&mut shape, control).extend(crate::semantics::attributes(
582        descriptor.semantics.as_deref(),
583        descriptor.effective_role(),
584    ));
585    match descriptor.focus {
586        FocusMode::Auto => {}
587        FocusMode::Programmatic => {
588            attrs(&mut shape, control).insert("tabindex", "-1".into());
589        }
590        FocusMode::TabStop => {
591            attrs(&mut shape, control).insert("tabindex", "0".into());
592        }
593    }
594    if matches!(descriptor.props,Props::RichEditor(value) if !value.enabled) {
595        attrs(&mut shape, control).insert("tabindex", "-1".into());
596    }
597    if let Some(item) = descriptor.item {
598        attrs(&mut shape, Part::Main).insert("aria-posinset", (item.index + 1).to_string());
599        attrs(&mut shape, Part::Main).insert(
600            "aria-setsize",
601            item.count
602                .map_or_else(|| "-1".into(), |count| count.to_string()),
603        );
604    }
605    for piece in &mut shape.pieces {
606        match &mut piece.kind {
607            Kind::Text(value) => normalize_in_place(value),
608            Kind::Element {
609                attributes,
610                properties,
611                ..
612            } => {
613                for value in attributes.values_mut() {
614                    normalize_in_place(value);
615                }
616                for value in properties.values_mut() {
617                    if let Property::Text(value) = value {
618                        normalize_in_place(value);
619                    }
620                }
621            }
622        }
623    }
624    shape.root_part()?;
625    Ok(shape)
626}
627pub(crate) fn rich_focus(focus: FocusMode) -> &'static str {
628    match focus {
629        FocusMode::Auto => "auto",
630        FocusMode::TabStop => "tab",
631        FocusMode::Programmatic => "programmatic",
632    }
633}
634pub(crate) fn rich_tabindex(focus: FocusMode, enabled: bool) -> Option<&'static str> {
635    if !enabled {
636        return Some("-1");
637    }
638    match focus {
639        FocusMode::Auto => None,
640        FocusMode::TabStop => Some("0"),
641        FocusMode::Programmatic => Some("-1"),
642    }
643}
644/// Resolve only rich editors' inherited disabled policy from the supplied
645/// semantic tree. Ordinary shapes remain descriptor-local. Intrinsic HTML
646/// controls already inherit fieldset behavior in their native host.
647pub fn shape_in(tree: &Memory, id: NodeId) -> Result<Shape, Error> {
648    let descriptor = tree.node(id)?.descriptor.view();
649    let mut shape = shape(descriptor)?;
650    if matches!(descriptor.props,Props::RichEditor(value) if value.enabled) && !tree.enabled(id) {
651        let attrs = attrs(&mut shape, Part::Main);
652        attrs.insert("data-gly-rich-ancestor-disabled", String::new());
653        attrs.insert("contenteditable", "false".into());
654        attrs.insert("aria-disabled", "true".into());
655        attrs.insert("tabindex", "-1".into());
656    }
657    Ok(shape)
658}
659
660pub(crate) fn file_attributes(config: &glory_render::FileConfig) -> BTreeMap<&'static str, String> {
661    let mut attrs = BTreeMap::new();
662    if config.multiple {
663        attrs.insert("multiple", String::new());
664    }
665    if !config.filters.is_empty() {
666        attrs.insert(
667            "accept",
668            config
669                .filters
670                .iter()
671                .map(|f| f.text())
672                .collect::<Vec<_>>()
673                .join(","),
674        );
675    }
676    attrs
677}
678
679/// Shared with field lowering: explicit false remains observable to AT.
680pub(crate) fn check_aria(mode: glory_render::CheckMode, checked: bool) -> &'static str {
681    if mode == glory_render::CheckMode::Mixed {
682        "mixed"
683    } else if checked {
684        "true"
685    } else {
686        "false"
687    }
688}
689
690pub(crate) fn check_type(mode: glory_render::CheckMode) -> &'static str {
691    if mode == glory_render::CheckMode::Radio {
692        "radio"
693    } else {
694        "checkbox"
695    }
696}
697
698#[cfg(test)]
699mod normalization_tests {
700    use super::normalize_in_place;
701
702    #[test]
703    fn canonical_allocations_are_kept_and_html_parser_aliases_are_repaired() {
704        for original in ["row 123", "Unicode 🙂 末尾", "a\nb", ""] {
705            let mut value = original.to_owned();
706            let allocation = value.as_ptr();
707            let capacity = value.capacity();
708            normalize_in_place(&mut value);
709            assert_eq!(value, original);
710            assert_eq!(value.as_ptr(), allocation);
711            assert_eq!(value.capacity(), capacity);
712        }
713        for (original, expected) in [("a\r\nb\rc\0🙂", "a\nb\nc�🙂"), ("\0\r", "�\n")] {
714            let mut value = original.to_owned();
715            normalize_in_place(&mut value);
716            assert_eq!(value, expected);
717        }
718    }
719}