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