@@ -1,8 +1,6 @@
11use std::collections::HashMap;
2−use std::hash::Hash;
32
43use crate::ast::*;
5−use crate::vocab::with_px;
64
75// ---------------------------------------------------------------------------
86// Style collector: deduplicates CSS and assigns class names
@@ -17,315 +15,47 @@ const BREAKPOINTS: &[(&str, &str)] = &[
1715 ("2xl", "1536px"),
1816];
1917
20−/// The prefix of every generated class (`hl-2k9xq0m`), which keeps them
21−/// out of the author's own class names.
22−pub const CLASS_PREFIX: &str = "hl-";
23−
24−/// How many base-36 digits a class's name has after `hl-`: 7, about 36
25−/// bits of its style's hash, so a site with 10,000 different styles has
26−/// odds of about 6 in 10,000 that two of them share a name, which
27−/// `htmlang build` reports (`class-collision`). Within one file, a style
28−/// whose name is taken takes more digits.
29−pub const CLASS_DIGITS: usize = 7;
30−
31−/// A stable hash of `text`: FNV-1a, then SplitMix64's finalizer, so every
32−/// digit of a name depends on all of the text. It is the same on every
33−/// platform and in every build, unlike `std`'s hasher.
34−pub fn stable_hash(text: &str) -> u64 {
35− let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
36− for byte in text.bytes() {
37− hash ^= u64::from(byte);
38− hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
39− }
40− hash = (hash ^ (hash >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
41− hash = (hash ^ (hash >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
42− hash ^ (hash >> 31)
43−}
44−
45−/// `digits` base-36 digits of `hash`: `2k9xq0m`. With 13, all of it.
46−pub fn hash_digits(hash: u64, digits: usize) -> String {
47− const DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
48− let mut n = hash;
49− (0..digits)
50− .map(|_| {
51− let digit = DIGITS[(n % 36) as usize] as char;
52− n /= 36;
53− digit
54− })
55− .collect()
56−}
57−
58−/// A class htmlang generated: its name, and the hash of the style it
59−/// stands for. One style has one name in every file, so a fragment's
60−/// classes mean the same in any page it goes into.
61−#[derive(Clone, Debug, PartialEq, Eq)]
62−pub struct Class {
63− pub name: String,
64− pub style: u64,
65−}
66−
67−/// When a style applies: the at-rule prefixes it is under (their ranks,
68−/// see [`crate::vocab::at_rule_rank`], sorted, so `dark:md:` and `md:dark:`
69−/// are one condition) and its selector prefixes, left to right as the
70−/// selector reads (`hover:children:` is `.a:hover > *`).
71−#[derive(Clone, Default, PartialEq, Eq, Hash, Debug)]
72−struct Condition {
73− at: Vec<usize>,
74− selector: Vec<String>,
75−}
76−
77−impl Condition {
78− /// The condition of an attribute's key, and the name after its
79− /// prefixes.
80− fn of(key: &str) -> (Condition, &str) {
81− let (prefixes, name) = crate::vocab::split_prefixes(key);
82− let mut condition = Condition::default();
83− for prefix in prefixes {
84− match crate::vocab::at_rule_rank(prefix) {
85− Some(rank) => condition.at.push(rank),
86− None => condition.selector.push(prefix.to_string()),
87− }
88− }
89− condition.at.sort_unstable();
90− condition.at.dedup();
91− (condition, name)
92− }
93−
94− /// Only the at-rule part: a direction under `hover:` is the one without
95− /// it.
96− fn at_only(at: &[usize]) -> Condition {
97− Condition {
98− at: at.to_vec(),
99− selector: Vec::new(),
100− }
101− }
102−
103− /// The styles go on the element's children (`children:`).
104− fn on_children(&self) -> bool {
105− self.selector.iter().any(|p| p == crate::vocab::CHILDREN)
106− }
107−
108− /// The styles go on the elements of one kind inside the element
109− /// (`@td:`): where the element prefix is in the selector chain.
110− fn inside(&self) -> Option<usize> {
111− self.selector
112− .iter()
113− .position(|p| crate::vocab::element_prefix(p).is_some())
114− }
115−
116− /// Whether this condition holds wherever `other` does: its at-rules
117− /// are implied by `other`'s, and it has no selector or `other`'s.
118− fn holds_at(&self, other: &Condition) -> bool {
119− (self.selector.is_empty() || self.selector == other.selector)
120− && self.at.iter().all(|&a| {
121− other
122− .at
123− .iter()
124− .any(|&b| crate::vocab::at_rule_implied(a, b))
125− })
126− }
127−
128− /// The order the rules of each condition are written in, which the
129− /// cascade follows: no prefix, then selectors, then each at-rule
130− /// block (see [`at_order`]), with its selectors inside it.
131− fn order(&self) -> (AtOrder, SelectorOrder) {
132− (at_order(&self.at), selector_order(&self.selector))
133− }
134−}
135−
136−/// Where a block of at-rules is written: after the rules without one; by
137−/// its last (innermost) prefix in the order of
138−/// [`crate::vocab::at_rule_prefixes`] (widths, media, container widths), so
139−/// `md:dark:` comes with `dark:`, after it; then by length.
140−type AtOrder = (bool, usize, usize, Vec<usize>);
141−
142−fn at_order(at: &[usize]) -> AtOrder {
143− (
144− !at.is_empty(),
145− at.last().copied().unwrap_or(0),
146− at.len(),
147− at.to_vec(),
148− )
149−}
150−
151−/// Selector chains in the order of [`crate::vocab::PSEUDOS`] (position,
152−/// then form state, then `hover:`, `focus:`, `active:`, `disabled:`), and
153−/// by their argument's text for the same pseudo-class; a chain before the
154−/// longer ones it starts. A chain through `children:` comes after the
155−/// others, ordered by what follows its last `children:` and then by what
156−/// comes before it: only that tail counts toward its specificity (see
157−/// [`selector`]), so `hover:children:` follows `children:` and wins over it
158−/// on hover.
159−type SelectorOrder = (bool, Vec<(usize, String)>, Vec<(usize, String)>);
160−
161−fn selector_order(selector: &[String]) -> SelectorOrder {
162− let table = crate::vocab::PSEUDOS;
163− let ranked = |chain: &[String]| -> Vec<(usize, String)> {
164− chain
165− .iter()
166− .map(|p| {
167− let name = crate::vocab::pseudo_name(p);
168− let rank = table
169− .iter()
170− .position(|(q, _)| *q == name)
171− .unwrap_or(table.len());
172− (rank, p.clone())
173− })
174− .collect()
175− };
176− match selector.iter().rposition(|p| p == crate::vocab::CHILDREN) {
177− None => (false, ranked(selector), Vec::new()),
178− Some(i) => (true, ranked(&selector[i + 1..]), ranked(&selector[..i])),
179− }
180−}
181−
182−/// The order of the chains through an element prefix (`@td:`, see
183−/// [`scoped_selector`]): by the prefixes before it, which select the root
184−/// of the scope and add nothing to the specificity, so `hover:@td:` comes
185−/// after `@td:` and wins on hover; then by the element; then by the
186−/// prefixes after it.
187−fn inside_order(chain: &[String]) -> (SelectorOrder, String, SelectorOrder) {
188− let at = chain
189− .iter()
190− .position(|p| crate::vocab::element_prefix(p).is_some())
191− .unwrap_or(chain.len());
192− (
193− selector_order(&chain[..at]),
194− chain.get(at).cloned().unwrap_or_default(),
195− selector_order(chain.get(at + 1..).unwrap_or_default()),
196− )
197−}
198−
199−/// The selector for `class` under a chain of selector prefixes, read left
200−/// to right. Everything before the last `children:` goes in `:where()`, so
201−/// a parent's `children:` styles have no specificity, and a child's own
202−/// attributes win over them: `children:hover:` is `:where(.a)>*:hover`,
203−/// `hover:children:` is `:where(.a:hover)>*`.
204−fn selector(class: &str, chain: &[String]) -> String {
205− let last_children = chain.iter().rposition(|p| p == crate::vocab::CHILDREN);
206− let mut out = format!(".{}", class);
207− for (i, prefix) in chain.iter().enumerate() {
208− if prefix == crate::vocab::CHILDREN {
209− if Some(i) == last_children {
210− out = format!(":where({})>*", out);
211− } else {
212− out.push_str(">*");
213− }
214− } else if let Some(pseudo) = crate::vocab::pseudo_selector(prefix) {
215− out.push_str(&pseudo);
216− }
18+/// Generate short CSS class names: a, b, ..., z, a0, a1, ..., z9, aa, ab, ...
19+fn short_class_name(idx: usize) -> String {
20+ if idx < 26 {
21+ return String::from((b'a' + idx as u8) as char);
21722 }
218− out
219−}
220−
221−/// The rule for the elements an element prefix picks out inside the
222−/// element with the class `class` (see [`Condition::inside`]): the scope's
223−/// root, from the selector prefixes before it (`hover:@td:` is inside a
224−/// hovered element), and the selector for the elements, from those after
225−/// it (`@td:hover:` is a hovered cell). `:scope td` leaves out the root
226−/// itself, so `@ul [@ul:...]` styles the lists inside, not its own. `None`
227−/// when the name has no tag of its own (the parser reports it).
228−fn scoped_selector(class: &str, chain: &[String], at: usize) -> Option<(String, String)> {
229− let name = crate::vocab::element_prefix(&chain[at])?;
230− let tag = ElementKind::from_name(name)?.own_tag()?;
231− let root = selector(class, &chain[..at]);
232− let mut target = format!(":scope {}", tag);
233− for prefix in &chain[at + 1..] {
234− if let Some(pseudo) = crate::vocab::pseudo_selector(prefix) {
235− target.push_str(&pseudo);
236− }
237− }
238− Some((root, target))
239−}
240−
241−/// The `@media` or `@container` rule an at-rule prefix stands for, as
242−/// written in readable and in compact output.
243−fn at_rule(rank: usize, dev: bool) -> String {
244− let prefix = crate::vocab::at_rule_prefixes()
245− .nth(rank)
246− .unwrap_or_default();
247− let name = prefix.trim_end_matches(':');
248− let width = |name: &str| {
249− BREAKPOINTS
250− .iter()
251− .find(|(n, _)| *n == name)
252− .map_or("0", |(_, w)| *w)
253− };
254− let (kind, feature, value) = if let Some(size) = name.strip_prefix("cq-") {
255− ("@container", "min-width", width(size))
256− } else {
257− match name {
258− "print" => {
259− return "@media print".to_string();
260− }
261− "dark" => ("@media", "prefers-color-scheme", "dark"),
262− "motion-safe" => ("@media", "prefers-reduced-motion", "no-preference"),
263− "motion-reduce" => ("@media", "prefers-reduced-motion", "reduce"),
264− "landscape" | "portrait" => ("@media", "orientation", name),
265− _ => ("@media", "min-width", width(name)),
266− }
267− };
268− if dev {
269− format!("{} ({}: {})", kind, feature, value)
270− } else {
271− format!("{}({}:{})", kind, feature, value)
23+ let mut n = idx - 26;
24+ let mut name = String::new();
25+ // First char is always a letter
26+ name.push((b'a' + (n % 26) as u8) as char);
27+ n /= 26;
28+ loop {
29+ name.push((b'a' + (n % 36).min(25) as u8) as char);
30+ if n < 36 { break; }
31+ n /= 36;
27232 }
273−}
274−
275−/// A style as text, for its hash: the defaults of its element's kind, its
276−/// rules (the at-rules' ranks, the selector prefixes and the declarations
277−/// of each) and the rules keyed on it, each part ended by a character CSS
278−/// doesn't have.
279−fn style_text(defaults: &str, rules: &[(Condition, String)], distinct: &str) -> String {
280− let mut text = format!("{defaults}\u{1}");
281− for (condition, body) in rules {
282− for rank in &condition.at {
283− text.push_str(&format!("{rank}\u{2}"));
284− }
285− text.push('\u{3}');
286− for prefix in &condition.selector {
287− text.push_str(prefix);
288− text.push('\u{2}');
289− }
290− text.push('\u{3}');
291− text.push_str(body);
292− text.push('\u{1}');
293− }
294− text.push_str(distinct);
295− text
33+ // Reverse so it reads naturally
34+ name.chars().rev().collect()
29635}
29736
29837struct StyleEntry {
29938 class_name: String,
300− /// The hash of the style, which names the class
301− style: u64,
302− /// The defaults of the element's kind (its layout, a heading's
303− /// `margin:0`, ...), less what its own attributes set. They are written
304− /// as `:where(.hl-a)` in the layer `hl-kind`, so an element prefix
305− /// around it (`@h2:`), its parent's `children:` styles and its own
306− /// attributes, all in later layers, win over them.
307− defaults: String,
308− /// The element's rules: under each condition, its declarations, in the
309− /// order they are written
310− rules: Vec<(Condition, String)>,
311− /// What else tells two elements with the same CSS apart: the rules
312− /// keyed on this class (see [`StyleCollector::keyed`]). Not written.
313− distinct: String,
39+ base: String,
40+ /// (CSS selector suffix, css_rules) — e.g. (":hover", "color:red;")
41+ pseudo: Vec<(String, String)>,
42+ /// Responsive overrides: (breakpoint_prefix, css)
43+ responsive: Vec<(String, String)>,
44+ /// Dark mode overrides
45+ dark: String,
46+ /// Print overrides
47+ print: String,
48+ motion_safe: String,
49+ motion_reduce: String,
50+ landscape: String,
51+ portrait: String,
52+ /// Container query overrides: (breakpoint_prefix, css)
53+ container: Vec<(String, String)>,
31454}
31555
31656struct StyleCollector {
31757 entries: Vec<StyleEntry>,
318− /// Maps a style's hash to its entries (more than one only when two
319− /// styles hash alike, which the full comparison tells apart).
320− index: HashMap<u64, Vec<usize>>,
321− /// The names given, which a style whose name is taken doesn't get
322− names: std::collections::HashSet<String>,
323− /// Rules for an element's children, keyed on its class and written in
324− /// the block of an at-rule condition: `(at-rules, selector, body)`, e.g.
325− /// `([md], ":where(.a)>.b", "flex:1;")` (see [`Flow`]).
326− keyed: Vec<(Vec<usize>, String, String)>,
327− /// The keyed rules already added
328− keyed_seen: std::collections::HashSet<(Vec<usize>, String, String)>,
58+ index: HashMap<String, usize>,
32959}
33060
33161impl StyleCollector {
@@ -333,328 +63,295 @@ impl StyleCollector {
33363 StyleCollector {
33464 entries: Vec::new(),
33565 index: HashMap::new(),
336− names: std::collections::HashSet::new(),
337− keyed: Vec::new(),
338− keyed_seen: std::collections::HashSet::new(),
339− }
340− }
341−
342− /// Add a rule for `selector` under the at-rules `at`, once.
343− fn add_keyed(&mut self, at: Vec<usize>, selector: String, body: String) {
344− let rule = (at, selector, body);
345− if self.keyed_seen.insert(rule.clone()) {
346− self.keyed.push(rule);
34766 }
34867 }
34968
35069 /// Returns a class name for this style combination, or None if all empty.
35170 fn get_class(
35271 &mut self,
353− defaults: String,
354− mut rules: Vec<(Condition, String)>,
355− distinct: String,
72+ base: String,
73+ pseudo: Vec<(String, String)>,
74+ responsive: Vec<(String, String)>,
75+ dark: String,
76+ print: String,
77+ motion_safe: String,
78+ motion_reduce: String,
79+ landscape: String,
80+ portrait: String,
81+ container: Vec<(String, String)>,
35682 ) -> Option<String> {
357− rules.retain(|(_, body)| !body.is_empty());
358− if defaults.is_empty() && rules.is_empty() {
83+ if base.is_empty()
84+ && pseudo.is_empty()
85+ && responsive.is_empty()
86+ && dark.is_empty()
87+ && print.is_empty()
88+ && motion_safe.is_empty()
89+ && motion_reduce.is_empty()
90+ && landscape.is_empty()
91+ && portrait.is_empty()
92+ && container.is_empty()
93+ {
35994 return None;
36095 }
361− rules.sort_by_cached_key(|(condition, _)| condition.order());
362− let style = stable_hash(&style_text(&defaults, &rules, &distinct));
363−
364− if let Some(indices) = self.index.get(&style) {
365− for &idx in indices {
366− let e = &self.entries[idx];
367− if e.defaults == defaults && e.rules == rules && e.distinct == distinct {
368− return Some(e.class_name.clone());
369− }
370− }
96+ let pseudo_key: String = pseudo
97+ .iter()
98+ .map(|(sel, css)| format!("{}={}", sel, css))
99+ .collect::<Vec<_>>()
100+ .join("|");
101+ let resp_key: String = responsive
102+ .iter()
103+ .map(|(bp, css)| format!("{}={}", bp, css))
104+ .collect::<Vec<_>>()
105+ .join("|");
106+ let cq_key: String = container
107+ .iter()
108+ .map(|(bp, css)| format!("{}={}", bp, css))
109+ .collect::<Vec<_>>()
110+ .join("|");
111+ let key = format!("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", base, pseudo_key, resp_key, dark, print, motion_safe, motion_reduce, landscape, portrait, cq_key);
112+ if let Some(&idx) = self.index.get(&key) {
113+ return Some(self.entries[idx].class_name.clone());
371114 }
372− // The name is the hash's first digits, and more of them when
373− // another style of this file has those; after all 13, the entry's
374− // number tells the two apart
375115 let idx = self.entries.len();
376− let name = (CLASS_DIGITS..=13)
377− .map(|digits| format!("{}{}", CLASS_PREFIX, hash_digits(style, digits)))
378− .find(|name| !self.names.contains(name))
379− .unwrap_or_else(|| format!("{}{}{}", CLASS_PREFIX, hash_digits(style, 13), idx));
380− self.names.insert(name.clone());
116+ let name = short_class_name(idx);
381117 self.entries.push(StyleEntry {
382118 class_name: name.clone(),
383− style,
384− defaults,
385− rules,
386− distinct,
119+ base,
120+ pseudo,
121+ responsive,
122+ dark,
123+ print,
124+ motion_safe,
125+ motion_reduce,
126+ landscape,
127+ portrait,
128+ container,
387129 });
388− self.index.entry(style).or_default().push(idx);
130+ self.index.insert(key, idx);
389131 Some(name)
390132 }
391133
392− /// The classes given, in the order they were
393− fn classes(&self) -> impl Iterator<Item = Class> + '_ {
394− self.entries.iter().map(|e| Class {
395− name: e.class_name.clone(),
396− style: e.style,
397− })
398− }
399−
400− /// All generated rules, in three layers (see [`LAYERS`]): the element
401− /// kinds' defaults in `hl-kind` (`:where(.hl-a)`), the rules for the
402− /// elements an element prefix picks out inside an element (`@td:`), and
403− /// a function's scoped `@style`, in `hl-inside`, and the elements' own
404− /// rules in `htmlang`. They are written in a fixed order, so which rule
405− /// wins never depends on where in the page an element is: the rules
406− /// without a prefix, then those under selector prefixes, then each block
407− /// of at-rules (see [`at_order`]), in which the rules keyed on a parent
408− /// come first, then the element's own, then its selectors (see
409− /// [`selector_order`]).
410− fn to_css_formatted(&self, dev: bool, scoped: &[String]) -> String {
411− // The defaults: `:where(.hl-a,.hl-b){...}`
412− let mut kind = String::new();
413− let mut defaults: Vec<(&str, Vec<&str>)> = Vec::new();
414− for e in self.entries.iter().filter(|e| !e.defaults.is_empty()) {
415− match defaults.iter_mut().find(|(body, _)| *body == e.defaults) {
416− Some((_, classes)) => classes.push(&e.class_name),
417− None => defaults.push((&e.defaults, vec![&e.class_name])),
418− }
419− }
420− for (body, classes) in defaults {
421− let classes: Vec<String> = classes.iter().map(|c| format!(".{}", c)).collect();
422− let selector = format!(":where({})", classes.join(","));
134+ fn to_css_formatted(&self, dev: bool, use_layer: bool) -> String {
135+ let mut css = String::new();
136+ let (sp, nl) = if dev { (" ", "\n") } else { ("", "") };
137+
138+ // Wrap in @layer for specificity management
139+ if use_layer {
423140 if dev {
424− kind.push_str(&format!(" {} {{{}}}\n", selector, body));
141+ css.push_str("@layer htmlang {\n");
425142 } else {
426− kind.push_str(&format!("{}{{{}}}", selector, body));
143+ css.push_str("@layer htmlang{");
144+ }
145+ }
146+
147+ // Non-responsive rules
148+ for e in &self.entries {
149+ if !e.base.is_empty() {
150+ if use_layer && dev {
151+ css.push_str(&format!(" .{}{sp}{{{}}}{nl}", e.class_name, e.base));
152+ } else {
153+ css.push_str(&format!(".{}{sp}{{{}}}{nl}", e.class_name, e.base));
154+ }
155+ }
156+ for (selector, pseudo_css) in &e.pseudo {
157+ if !pseudo_css.is_empty() {
158+ if use_layer && dev {
159+ css.push_str(&format!(" .{}{}{sp}{{{}}}{nl}", e.class_name, selector, pseudo_css));
160+ } else {
161+ css.push_str(&format!(".{}{}{sp}{{{}}}{nl}", e.class_name, selector, pseudo_css));
162+ }
163+ }
164+ }
165+ }
166+
167+ // Responsive rules grouped by breakpoint
168+ for &(bp_name, bp_width) in BREAKPOINTS {
169+ let mut bp_css = String::new();
170+ for e in &self.entries {
171+ for (bp, rule_css) in &e.responsive {
172+ if bp == bp_name && !rule_css.is_empty() {
173+ if dev {
174+ bp_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, rule_css));
175+ } else {
176+ bp_css.push_str(&format!(".{}{{{}}}", e.class_name, rule_css));
177+ }
178+ }
179+ }
180+ }
181+ if !bp_css.is_empty() {
182+ if dev {
183+ css.push_str(&format!(
184+ "@media (min-width: {}) {{\n{}}}\n",
185+ bp_width, bp_css
186+ ));
187+ } else {
188+ css.push_str(&format!(
189+ "@media(min-width:{}){{{}}}",
190+ bp_width, bp_css
191+ ));
192+ }
427193 }
428194 }
429195
430− let mut inside = self.blocks(true, dev);
431− // A function's scoped `@style`, nested under its class
432− for block in scoped {
196+ // Dark mode rules
197+ let mut dark_css = String::new();
198+ for e in &self.entries {
199+ if !e.dark.is_empty() {
200+ if dev {
201+ dark_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.dark));
202+ } else {
203+ dark_css.push_str(&format!(".{}{{{}}}", e.class_name, e.dark));
204+ }
205+ }
206+ }
207+ if !dark_css.is_empty() {
433208 if dev {
434− inside.push_str(block);
435− inside.push('\n');
209+ css.push_str(&format!("@media (prefers-color-scheme: dark) {{\n{}}}\n", dark_css));
436210 } else {
437− inside.push_str(&compact_css(block));
211+ css.push_str(&format!("@media(prefers-color-scheme:dark){{{}}}", dark_css));
438212 }
439213 }
440214
441− let mut css = String::new();
442− for (name, rules) in [
443− ("hl-kind", kind),
444− ("hl-inside", inside),
445− ("htmlang", self.blocks(false, dev)),
446− ] {
447− if rules.is_empty() {
448− continue;
215+ // Print rules
216+ let mut print_css = String::new();
217+ for e in &self.entries {
218+ if !e.print.is_empty() {
219+ if dev {
220+ print_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.print));
221+ } else {
222+ print_css.push_str(&format!(".{}{{{}}}", e.class_name, e.print));
223+ }
449224 }
225+ }
226+ if !print_css.is_empty() {
450227 if dev {
451− css.push_str(&format!("@layer {} {{\n{}}}\n", name, rules));
228+ css.push_str(&format!("@media print {{\n{}}}\n", print_css));
452229 } else {
453− css.push_str(&format!("@layer {}{{{}}}", name, rules));
230+ css.push_str(&format!("@media print{{{}}}", print_css));
454231 }
455232 }
456− css
457− }
458233
459− /// The rules of every block of at-rules, in order: those for the
460− /// elements inside (`inside`: rules under an element prefix, each in
461− /// an `@scope` on its element's class), or the elements' own.
462− fn blocks(&self, inside: bool, dev: bool) -> String {
463− let mut css = String::new();
464− let rules = || {
465− self.entries.iter().flat_map(move |e| {
466− e.rules
467− .iter()
468− .filter(move |(c, _)| c.inside().is_some() == inside)
469− .map(move |(c, body)| (e, c, body))
470− })
471− };
472− let mut blocks: Vec<&[usize]> = vec![&[]];
473− let keyed = self.keyed.iter().filter(|_| !inside);
474− let every = rules()
475− .map(|(_, c, _)| c.at.as_slice())
476− .chain(keyed.map(|(at, _, _)| at.as_slice()));
477− for at in every {
478− if !blocks.contains(&at) {
479− blocks.push(at);
480− }
481− }
482− blocks.sort_by_key(|at| at_order(at));
483−
484− for at in blocks {
485− let depth = at.len();
486− // Readable output indents a rule inside `@layer` and inside
487− // each at-rule but the first
488− let indent = if dev {
489− " ".repeat(depth.max(1))
490− } else {
491− String::new()
492− };
493− let mut inner = String::new();
494− // Rules keyed on a parent's class come first: they have the
495− // specificity of one class, like a class rule, so the child's
496− // own rules in the block still win
497− if !inside {
498− let keyed: Vec<(&str, &str)> = self
499− .keyed
500− .iter()
501− .filter(|(a, _, _)| a.as_slice() == at)
502− .map(|(_, selector, body)| (selector.as_str(), body.as_str()))
503− .collect();
504− emit_selector_rules(&mut inner, &keyed, &indent, dev);
505− }
506− // The selector chains of this block, in order
507− let mut chains: Vec<&[String]> = Vec::new();
508− for (_, condition, _) in rules() {
509− if condition.at == at && !chains.contains(&condition.selector.as_slice()) {
510− chains.push(&condition.selector);
511− }
512− }
513− if inside {
514− chains.sort_by_cached_key(|chain| inside_order(chain));
515− // One `@scope` for each root, its rules in the order of
516− // the chains: rules for one element under two roots (`.a`
517− // and `.a:hover`) tie on specificity and proximity, so the
518− // later one wins
519− let mut scopes: Vec<(String, Vec<(String, &str)>)> = Vec::new();
520− for chain in chains {
521− let Some(element) = chain
522− .iter()
523− .position(|p| crate::vocab::element_prefix(p).is_some())
524− else {
525− continue;
526− };
527− for (e, _, body) in
528− rules().filter(|(_, c, _)| c.at == at && c.selector == chain)
529− {
530− let Some((root, target)) = scoped_selector(&e.class_name, chain, element)
531− else {
532− continue;
533− };
534− match scopes.iter_mut().find(|(r, _)| *r == root) {
535− Some((_, targets)) => targets.push((target, body)),
536− None => scopes.push((root, vec![(target, body)])),
537− }
538− }
539− }
540− let inner_indent = if dev {
541− format!("{} ", indent)
234+ // Motion safe rules
235+ let mut motion_safe_css = String::new();
236+ for e in &self.entries {
237+ if !e.motion_safe.is_empty() {
238+ if dev {
239+ motion_safe_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.motion_safe));
542240 } else {
543− String::new()
544− };
545− for (root, targets) in scopes {
546− let targets: Vec<(&str, &str)> =
547− targets.iter().map(|(t, b)| (t.as_str(), *b)).collect();
548− inner.push_str(&indent);
549− inner.push_str(&format!("@scope ({})", root));
550− inner.push_str(if dev { " {\n" } else { "{" });
551− emit_selector_rules(&mut inner, &targets, &inner_indent, dev);
552− inner.push_str(&indent);
553− inner.push_str(if dev { "}\n" } else { "}" });
241+ motion_safe_css.push_str(&format!(".{}{{{}}}", e.class_name, e.motion_safe));
554242 }
243+ }
244+ }
245+ if !motion_safe_css.is_empty() {
246+ if dev {
247+ css.push_str(&format!("@media (prefers-reduced-motion: no-preference) {{\n{}}}\n", motion_safe_css));
555248 } else {
556− chains.sort_by_cached_key(|chain| selector_order(chain));
557− for chain in chains {
558− let pairs: Vec<(String, &str)> = rules()
559− .filter(|(_, c, _)| c.at == at && c.selector == chain)
560− .map(|(e, _, body)| (selector(&e.class_name, chain), body.as_str()))
561− .collect();
562− emit_grouped_rules(&mut inner, &pairs, &indent, dev);
249+ css.push_str(&format!("@media(prefers-reduced-motion:no-preference){{{}}}", motion_safe_css));
250+ }
251+ }
252+
253+ // Motion reduce rules
254+ let mut motion_reduce_css = String::new();
255+ for e in &self.entries {
256+ if !e.motion_reduce.is_empty() {
257+ if dev {
258+ motion_reduce_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.motion_reduce));
259+ } else {
260+ motion_reduce_css.push_str(&format!(".{}{{{}}}", e.class_name, e.motion_reduce));
563261 }
564262 }
565− if inner.is_empty() {
566− continue;
263+ }
264+ if !motion_reduce_css.is_empty() {
265+ if dev {
266+ css.push_str(&format!("@media (prefers-reduced-motion: reduce) {{\n{}}}\n", motion_reduce_css));
267+ } else {
268+ css.push_str(&format!("@media(prefers-reduced-motion:reduce){{{}}}", motion_reduce_css));
567269 }
568− // Each at-rule wraps the next, outermost first
569− for (level, &rank) in at.iter().enumerate().rev() {
570− let pad = if dev {
571− " ".repeat(level)
572− } else {
573− String::new()
574− };
575− inner = if dev {
576− format!("{pad}{} {{\n{inner}{pad}}}\n", at_rule(rank, true))
270+ }
271+
272+ // Landscape rules
273+ let mut landscape_css = String::new();
274+ for e in &self.entries {
275+ if !e.landscape.is_empty() {
276+ if dev {
277+ landscape_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.landscape));
577278 } else {
578− format!("{}{{{inner}}}", at_rule(rank, false))
579− };
279+ landscape_css.push_str(&format!(".{}{{{}}}", e.class_name, e.landscape));
280+ }
281+ }
282+ }
283+ if !landscape_css.is_empty() {
284+ if dev {
285+ css.push_str(&format!("@media (orientation: landscape) {{\n{}}}\n", landscape_css));
286+ } else {
287+ css.push_str(&format!("@media(orientation:landscape){{{}}}", landscape_css));
580288 }
581− css.push_str(&inner);
582289 }
583− css
584− }
585−}
586290
587−/// Emit CSS rules from `(selector, body)` pairs, merging identical bodies
588−/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
589−/// of each distinct body determines ordering, so output stays deterministic
590−/// across runs. `indent` is prepended to each rule line.
591−fn emit_grouped_rules(out: &mut String, pairs: &[(String, &str)], indent: &str, dev: bool) {
592− if pairs.is_empty() {
593− return;
594− }
595− // Group in first-occurrence order.
596− let mut order: Vec<&str> = Vec::new();
597− let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
598− for (selector, body) in pairs {
599− if body.is_empty() {
600− continue;
291+ // Portrait rules
292+ let mut portrait_css = String::new();
293+ for e in &self.entries {
294+ if !e.portrait.is_empty() {
295+ if dev {
296+ portrait_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.portrait));
297+ } else {
298+ portrait_css.push_str(&format!(".{}{{{}}}", e.class_name, e.portrait));
299+ }
300+ }
601301 }
602− if !groups.contains_key(body) {
603− order.push(body);
302+ if !portrait_css.is_empty() {
303+ if dev {
304+ css.push_str(&format!("@media (orientation: portrait) {{\n{}}}\n", portrait_css));
305+ } else {
306+ css.push_str(&format!("@media(orientation:portrait){{{}}}", portrait_css));
307+ }
604308 }
605− groups.entry(body).or_default().push(selector);
606− }
607− let sp = if dev { " " } else { "" };
608− let nl = if dev { "\n" } else { "" };
609− for body in &order {
610− out.push_str(indent);
611− out.push_str(&groups[body].join(","));
612− out.push_str(sp);
613− out.push('{');
614− out.push_str(body);
615− out.push('}');
616− out.push_str(nl);
617− }
618−}
619309
620−/// Emit `(selector, body)` rules in their order, merging a run of rules
621−/// with the same body into one rule with a selector list (the order
622−/// matters: two rules may apply to one element).
623−fn emit_selector_rules(out: &mut String, rules: &[(&str, &str)], indent: &str, dev: bool) {
624− let mut i = 0;
625− while i < rules.len() {
626− let body = rules[i].1;
627− let run = rules[i..].iter().take_while(|(_, b)| *b == body).count();
628− if !body.is_empty() {
629− let selectors: Vec<&str> = rules[i..i + run].iter().map(|(s, _)| *s).collect();
630− out.push_str(indent);
631− out.push_str(&selectors.join(","));
632− if dev {
633− out.push(' ');
310+ // Container query rules grouped by breakpoint
311+ for &(bp_name, bp_width) in BREAKPOINTS {
312+ let mut cq_css = String::new();
313+ for e in &self.entries {
314+ for (bp, rule_css) in &e.container {
315+ if bp == bp_name && !rule_css.is_empty() {
316+ if dev {
317+ cq_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, rule_css));
318+ } else {
319+ cq_css.push_str(&format!(".{}{{{}}}", e.class_name, rule_css));
320+ }
321+ }
322+ }
634323 }
635− out.push('{');
636− out.push_str(body);
637− out.push('}');
324+ if !cq_css.is_empty() {
325+ if dev {
326+ css.push_str(&format!(
327+ "@container (min-width: {}) {{\n{}}}\n",
328+ bp_width, cq_css
329+ ));
330+ } else {
331+ css.push_str(&format!(
332+ "@container(min-width:{}){{{}}}",
333+ bp_width, cq_css
334+ ));
335+ }
336+ }
337+ }
338+
339+ // Close @layer
340+ if use_layer {
638341 if dev {
639− out.push('\n');
342+ css.push_str("}\n");
343+ } else {
344+ css.push('}');
640345 }
641346 }
642− i += run;
347+
348+ css
643349 }
644350}
645351
646352struct GenContext {
647353 dev: bool,
648354 depth: usize,
649− has_interactive: bool,
650− /// Writing inside a text element, at any depth: htmlang's own `<div>`s
651− /// are `<span>`s there, which text can hold.
652− in_text: bool,
653− /// How the element whose children are being written lays them out
654− flow: Flow,
655− /// Writing the children of a `@picture`, where `@source`'s leading
656− /// argument is its `srcset`
657− in_picture: bool,
658355}
659356
660357impl GenContext {
@@ -680,26 +377,23 @@ pub struct CodegenOptions {
680377 pub dev: bool,
681378 pub partial: bool,
682379 pub minify: bool,
380+ pub compat: bool,
683381}
684382
685383/// Generate HTML from a parsed document using the given options.
686384pub fn generate_with(doc: &Document, opts: &CodegenOptions) -> String {
687− generate_with_classes(doc, opts).0
688−}
689−
690−/// [`generate_with`], and the classes the document's styles were given,
691−/// for a check across files that no name stands for two styles.
692−pub fn generate_with_classes(doc: &Document, opts: &CodegenOptions) -> (String, Vec<Class>) {
693− let mut classes = Vec::new();
694385 let mut html = if opts.partial {
695− generate_partial_inner(doc, opts.dev, &mut classes)
386+ generate_partial_inner(doc, opts.dev)
696387 } else {
697− generate_full_inner(doc, opts.dev, &mut classes)
388+ generate_full_inner(doc, opts.dev)
698389 };
699390 if opts.minify {
700391 html = minify_html(&html);
701392 }
702− (html, classes)
393+ if opts.compat {
394+ html = add_vendor_prefixes(&html);
395+ }
396+ html
703397}
704398
705399pub fn generate(doc: &Document) -> String {
@@ -707,44 +401,31 @@ pub fn generate(doc: &Document) -> String {
707401}
708402
709403pub fn generate_dev(doc: &Document) -> String {
710− generate_with(
711− doc,
712− &CodegenOptions {
713− dev: true,
714− ..Default::default()
715− },
716− )
404+ generate_with(doc, &CodegenOptions { dev: true, ..Default::default() })
717405}
718406
719407pub fn generate_partial(doc: &Document) -> String {
720− generate_with(
721− doc,
722− &CodegenOptions {
723− partial: true,
724− ..Default::default()
725− },
726− )
408+ generate_with(doc, &CodegenOptions { partial: true, ..Default::default() })
727409}
728410
729411pub fn generate_partial_dev(doc: &Document) -> String {
730− generate_with(
731− doc,
732− &CodegenOptions {
733− dev: true,
734− partial: true,
735− ..Default::default()
736− },
737− )
412+ generate_with(doc, &CodegenOptions { dev: true, partial: true, ..Default::default() })
738413}
739414
740415pub fn generate_minified(doc: &Document) -> String {
741− generate_with(
742− doc,
743− &CodegenOptions {
744− minify: true,
745− ..Default::default()
746− },
747− )
416+ generate_with(doc, &CodegenOptions { minify: true, ..Default::default() })
417+}
418+
419+pub fn generate_compat(doc: &Document) -> String {
420+ generate_with(doc, &CodegenOptions { compat: true, ..Default::default() })
421+}
422+
423+pub fn generate_dev_compat(doc: &Document) -> String {
424+ generate_with(doc, &CodegenOptions { dev: true, compat: true, ..Default::default() })
425+}
426+
427+pub fn generate_minified_compat(doc: &Document) -> String {
428+ generate_with(doc, &CodegenOptions { minify: true, compat: true, ..Default::default() })
748429}
749430
750431fn minify_html(html: &str) -> String {
@@ -761,9 +442,9 @@ fn minify_html(html: &str) -> String {
761442 if i + 4 < chars.len() && chars[i] == '<' {
762443 let rest: String = chars[i..].iter().take(10).collect();
763444 let rest_lower = rest.to_lowercase();
764− if rest_lower.starts_with("<pre") || rest_lower.starts_with("<textarea") {
445+ if rest_lower.starts_with("<pre") {
765446 in_pre = true;
766− } else if rest_lower.starts_with("</pre") || rest_lower.starts_with("</textarea") {
447+ } else if rest_lower.starts_with("</pre") {
767448 in_pre = false;
768449 } else if rest_lower.starts_with("<script") {
769450 in_script = true;
@@ -777,18 +458,13 @@ fn minify_html(html: &str) -> String {
777458 }
778459
779460 // Strip HTML comments (<!-- ... -->)
780− if !in_script
781− && !in_style
782− && i + 3 < chars.len()
783− && chars[i] == '<'
784− && chars[i + 1] == '!'
785− && chars[i + 2] == '-'
786− && chars[i + 3] == '-'
461+ if !in_script && !in_style && i + 3 < chars.len()
462+ && chars[i] == '<' && chars[i+1] == '!' && chars[i+2] == '-' && chars[i+3] == '-'
787463 {
788464 // Skip to -->
789465 let mut j = i + 4;
790466 while j + 2 < chars.len() {
791− if chars[j] == '-' && chars[j + 1] == '-' && chars[j + 2] == '>' {
467+ if chars[j] == '-' && chars[j+1] == '-' && chars[j+2] == '>' {
792468 j += 3;
793469 break;
794470 }
@@ -805,11 +481,10 @@ fn minify_html(html: &str) -> String {
805481 continue;
806482 }
807483
808− // Collapse whitespace runs to a single space. Spaces are never
809− // dropped entirely: next to inline elements they are significant
810− // ("Built with <span>" must keep its space).
484+ // Collapse whitespace between tags
811485 if chars[i].is_whitespace() {
812486 if !prev_was_space {
487+ // Only emit a space if we're between content (not between tags)
813488 result.push(' ');
814489 prev_was_space = true;
815490 }
@@ -817,6 +492,14 @@ fn minify_html(html: &str) -> String {
817492 continue;
818493 }
819494
495+ // Trim space before closing tags
496+ if chars[i] == '<' && prev_was_space {
497+ // Remove trailing space before tag
498+ if result.ends_with(' ') {
499+ result.pop();
500+ }
501+ }
502+
820503 prev_was_space = false;
821504 result.push(chars[i]);
822505 i += 1;
@@ -825,172 +508,186 @@ fn minify_html(html: &str) -> String {
825508 result
826509}
827510
828−fn generate_full_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
829− // Without `@page` the output is a fragment
830− let Some(page) = &doc.page else {
831− return generate_partial_inner(doc, dev, classes);
832− };
833− let mut styles = StyleCollector::new();
834− let mut ctx = GenContext {
835− dev,
836− depth: 0,
837− has_interactive: false,
838− in_text: false,
839− flow: Flow::default(),
840− in_picture: false,
841− };
842−
843− // The page is the root element: `<body>` is a column (the reset makes
844− // it one, filling the viewport), `@page`'s styles are its class, and
845− // the page's top-level elements are its children
846− let root = Element {
847− kind: ElementKind::El,
848− attrs: page.styles.clone(),
849− argument: None,
850− children: Vec::new(),
851− line_num: 0,
852− function: None,
853− };
854− let mut own = Flow::of(&root);
855− let top = Flow::default();
856− let site = Site {
857− kind: &root.kind,
858− parent: &top,
859− has_overlay_children: holds_overlays(&doc.nodes),
860− inline: false,
861− root: true,
862− };
863− let body_class = element_class(&root, &site, &mut styles);
864− own.class = body_class.clone();
865− ctx.flow = own;
511+/// Add vendor prefixes to CSS within <style> tags for broader browser compatibility.
512+fn add_vendor_prefixes(html: &str) -> String {
513+ // Find CSS within <style>...</style> and add vendor prefixes
514+ let mut result = String::with_capacity(html.len() + 512);
515+ let mut rest = html;
516+ while let Some(start) = rest.find("<style>") {
517+ let after_tag = start + 7;
518+ result.push_str(&rest[..after_tag]);
519+ rest = &rest[after_tag..];
520+ if let Some(end) = rest.find("</style>") {
521+ let css = &rest[..end];
522+ result.push_str(&prefix_css(css));
523+ result.push_str("</style>");
524+ rest = &rest[end + 8..];
525+ } else {
526+ break;
527+ }
528+ }
529+ result.push_str(rest);
530+ result
531+}
866532
867− let mut body = String::new();
868− generate_children(
869− &doc.nodes,
870− Some(Layout::Column),
871− &mut body,
872− &mut styles,
873− &mut ctx,
874− );
875−
876− let element_css = build_element_css(doc, &styles, dev);
877− let nl = if dev { "\n" } else { "" };
878−
879− let mut meta_html = String::new();
880− // A `@meta viewport` of the page's own replaces the usual one
881− if !doc.meta_tags.iter().any(|(name, _)| name == "viewport") {
882− meta_html.push_str(&format!(
883− "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">{}",
884− nl
885− ));
886− }
887− meta_html.push_str(&format!(
888− "<title>{}</title>{}",
889− html_escape(&page.title),
890− nl
891− ));
892− for (name, content) in &doc.meta_tags {
893− meta_html.push_str(&format!(
894− "<meta name=\"{}\" content=\"{}\">{}",
895− html_escape(name),
896− html_escape(content),
897− nl
898− ));
899− }
900− for (property, content) in &doc.og_tags {
901− meta_html.push_str(&format!(
902− "<meta property=\"og:{}\" content=\"{}\">{}",
903− html_escape(property),
904− html_escape(content),
905− nl
906− ));
907− }
908− if let Some(path) = &page.favicon {
909− meta_html.push_str(&format!(
910− "<link rel=\"icon\" href=\"{}\">{}",
911− html_escape(path),
912− nl
913− ));
914− }
915− for block in &doc.head_blocks {
916− meta_html.push_str(block);
917− meta_html.push_str(nl);
918− }
919−
920− // `@page`'s HTML attributes go on `<html>`
921− let mut root_attrs = String::new();
922− for attr in html_attrs(&page.html_attrs) {
923− push_html_attr(&mut root_attrs, attr);
924− }
925− let mut body_attrs = String::new();
926− emit_class_attr(&mut body_attrs, body_class.as_deref(), None);
927−
928− // Focus-visible CSS for interactive elements (accessibility)
929− let focus_visible_css = if ctx.has_interactive {
930− let focusable = ":where(a,button,input,select,textarea):focus-visible";
931− if dev {
932− format!(
933− "{}{} {{ outline: 2px solid currentColor; outline-offset: 2px; }}\n",
934− OWN_ELEMENTS, focusable
935− )
533+fn prefix_css(css: &str) -> String {
534+ let mut out = String::with_capacity(css.len() + 256);
535+ let mut i = 0;
536+ let bytes = css.as_bytes();
537+ while i < bytes.len() {
538+ // Find property declarations
539+ if let Some(pos) = css[i..].find('{') {
540+ let brace = i + pos;
541+ out.push_str(&css[i..=brace]);
542+ i = brace + 1;
543+ // Process declarations within this block
544+ if let Some(close) = css[i..].find('}') {
545+ let block = &css[i..i + close];
546+ out.push_str(&prefix_declarations(block));
547+ out.push('}');
548+ i = i + close + 1;
549+ }
936550 } else {
937− format!(
938− "{}{}{{outline:2px solid currentColor;outline-offset:2px}}",
939− OWN_ELEMENTS, focusable
940− )
551+ out.push_str(&css[i..]);
552+ break;
941553 }
942− } else {
943− String::new()
944− };
945− let reset_css = reset_css(dev, true, &focus_visible_css);
946− classes.extend(styles.classes());
554+ }
555+ out
556+}
947557
948− format!(
949− "<!DOCTYPE html>{nl}<html{root_attrs}>{nl}<head>{nl}<meta charset=\"utf-8\">{nl}\
950− {meta_html}<style>{nl}{reset_css}{element_css}</style>{nl}</head>{nl}\
951− <body{body_attrs}>{nl}{body}</body>{nl}</html>{nl}",
952− )
558+fn prefix_declarations(block: &str) -> String {
559+ let mut out = String::with_capacity(block.len() + 128);
560+ for decl in block.split(';') {
561+ let decl = decl.trim();
562+ if decl.is_empty() {
563+ continue;
564+ }
565+ if let Some((prop, val)) = decl.split_once(':') {
566+ let prop = prop.trim();
567+ let val = val.trim();
568+ match prop {
569+ "backdrop-filter" => {
570+ out.push_str(&format!("-webkit-backdrop-filter:{};", val));
571+ out.push_str(&format!("backdrop-filter:{};", val));
572+ }
573+ "user-select" => {
574+ out.push_str(&format!("-webkit-user-select:{};", val));
575+ out.push_str(&format!("-moz-user-select:{};", val));
576+ out.push_str(&format!("user-select:{};", val));
577+ }
578+ "appearance" => {
579+ out.push_str(&format!("-webkit-appearance:{};", val));
580+ out.push_str(&format!("-moz-appearance:{};", val));
581+ out.push_str(&format!("appearance:{};", val));
582+ }
583+ "background-clip" if val.contains("text") => {
584+ out.push_str(&format!("-webkit-background-clip:{};", val));
585+ out.push_str(&format!("background-clip:{};", val));
586+ }
587+ "hyphens" => {
588+ out.push_str(&format!("-webkit-hyphens:{};", val));
589+ out.push_str(&format!("-ms-hyphens:{};", val));
590+ out.push_str(&format!("hyphens:{};", val));
591+ }
592+ "text-size-adjust" => {
593+ out.push_str(&format!("-webkit-text-size-adjust:{};", val));
594+ out.push_str(&format!("-ms-text-size-adjust:{};", val));
595+ out.push_str(&format!("text-size-adjust:{};", val));
596+ }
597+ "mask-image" | "mask-size" | "mask-repeat" | "mask-position" => {
598+ out.push_str(&format!("-webkit-{}:{};", prop, val));
599+ out.push_str(&format!("{}:{};", prop, val));
600+ }
601+ _ => {
602+ out.push_str(decl);
603+ out.push(';');
604+ }
605+ }
606+ } else {
607+ out.push_str(decl);
608+ out.push(';');
609+ }
610+ }
611+ out
953612}
954613
955−/// Assemble every CSS block the document needs (font faces, custom
956−/// properties, generated class rules, keyframes, and user CSS). Shared by
957−/// full-page and partial output so both emit the same styles.
958−fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> String {
959− let mut element_css = String::new();
614+fn generate_full_inner(doc: &Document, dev: bool) -> String {
615+ let mut styles = StyleCollector::new();
616+ let mut ctx = GenContext { dev, depth: 0 };
617+ let mut body = String::new();
960618
961− // Collect the CSS custom properties declared with `@let --name` so they
962− // can be emitted in a single `:root` block below.
963− let mut root_vars: Vec<(String, String)> = Vec::new();
964− for (name, value) in &doc.css_vars {
965− root_vars.push((name.clone(), value.clone()));
619+ for node in &doc.nodes {
620+ generate_node(node, None, &mut body, &mut styles, &mut ctx);
966621 }
967622
968− // Generated rules always go in htmlang's layers, so unlayered user CSS
969− // (`@style`, `@raw`) overrides them regardless of specificity.
970− let styles_css = styles.to_css_formatted(dev, &doc.scoped_css);
623+ let mut element_css = String::new();
971624
972− // Emit the :root block first so the cascade picks up the custom
973− // properties before the class rules consume them.
974− if !root_vars.is_empty() {
625+ // CSS custom properties (includes @theme runtime tokens)
626+ let has_theme_tokens = !doc.theme_tokens.is_empty();
627+ if !doc.css_vars.is_empty() || has_theme_tokens {
975628 if dev {
976629 element_css.push_str(":root {\n");
977− for (name, value) in &root_vars {
630+ for (name, value) in &doc.css_vars {
978631 element_css.push_str(&format!(" {}: {};\n", name, value));
979632 }
633+ // @theme tokens as runtime CSS custom properties
634+ for (name, value) in &doc.theme_tokens {
635+ let css_name = format!("--{}", name);
636+ // Only emit if not already in css_vars
637+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
638+ element_css.push_str(&format!(" {}: {};\n", css_name, value));
639+ }
640+ }
980641 element_css.push_str("}\n");
981642 } else {
982643 element_css.push_str(":root{");
983− for (name, value) in &root_vars {
644+ for (name, value) in &doc.css_vars {
984645 element_css.push_str(name);
985646 element_css.push(':');
986647 element_css.push_str(value);
987648 element_css.push(';');
988649 }
650+ for (name, value) in &doc.theme_tokens {
651+ let css_name = format!("--{}", name);
652+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
653+ element_css.push_str(&css_name);
654+ element_css.push(':');
655+ element_css.push_str(value);
656+ element_css.push(';');
657+ }
658+ }
989659 element_css.push('}');
990660 }
991661 }
992662
993− element_css.push_str(&styles_css);
663+ let has_custom_css = !doc.custom_css.is_empty();
664+ element_css.push_str(&styles.to_css_formatted(dev, !has_custom_css));
665+
666+ // @keyframes
667+ for (name, kf_body) in &doc.keyframes {
668+ if dev {
669+ element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
670+ } else {
671+ element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
672+ }
673+ }
674+
675+ // Auto-inject skeleton keyframe if skeleton attribute is used
676+ let skeleton_used = element_css.contains("hl-skeleton");
677+ if skeleton_used {
678+ if dev {
679+ element_css.push_str("@keyframes hl-skeleton {\n 0% { background-position: 200% 0; }\n 100% { background-position: -200% 0; }\n}\n");
680+ } else {
681+ element_css.push_str("@keyframes hl-skeleton{0%{background-position:200% 0}100%{background-position:-200% 0}}");
682+ }
683+ }
684+
685+ // Also inject carousel webkit scrollbar hiding
686+ let carousel_used = element_css.contains("scroll-snap-type:x mandatory");
687+ if carousel_used && !element_css.contains("::-webkit-scrollbar") {
688+ // The carousel class already has scrollbar-width:none, but webkit needs pseudo-element
689+ // We add a global rule for carousel-style elements
690+ }
994691
995692 // @style blocks (custom CSS)
996693 for block in &doc.custom_css {
@@ -998,115 +695,408 @@ fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> Stri
998695 element_css.push_str(block);
999696 element_css.push('\n');
1000697 } else {
1001− element_css.push_str(&compact_css(block));
698+ // Minify: collapse whitespace
699+ let minified: String = block
700+ .lines()
701+ .map(|l| l.trim())
702+ .collect::<Vec<_>>()
703+ .join("");
704+ element_css.push_str(&minified);
1002705 }
1003706 }
1004707
1005− element_css
1006−}
1007−
1008−/// An `@style` body on one line: each line trimmed, and the lines joined with
1009−/// a space, so a value that goes on over two lines (`margin: 0` then `auto;`)
1010−/// keeps its words apart.
1011−fn compact_css(block: &str) -> String {
1012− block
1013− .lines()
1014− .map(str::trim)
1015− .filter(|l| !l.is_empty())
1016− .collect::<Vec<_>>()
1017− .join(" ")
1018−}
1019−
1020−/// htmlang's own elements: those with a generated class, or the class of a
1021−/// function's scoped `@style`. The reset's rules for elements are kept to
1022−/// them, so `@raw` and `@markdown` content, and the page a fragment is put
1023−/// into, keep their own.
1024−const OWN_ELEMENTS: &str = ":where([class^=\"hl-\"],[class*=\" hl-\"])";
1025−
1026−/// htmlang's cascade layers, from the one that loses to the one that wins:
1027−/// the reset; the defaults of each element's kind (a heading's `margin:0`,
1028−/// a column's `display:flex`); the styles an element gets from an
1029−/// element prefix on an element around it (`@td:padding 8`) and from a
1030−/// function's scoped `@style`; and the element's own styles. So a
1031−/// scope's styles win over the defaults, and what an element says about
1032−/// itself wins over both. CSS outside any layer (`@style`, `@raw`) wins
1033−/// over all of them.
1034−const LAYERS: [&str; 4] = ["hl-reset", "hl-kind", "hl-inside", "htmlang"];
1035−
1036−/// Built-in reset rules, in a layer before `htmlang`: unlayered CSS beats
1037−/// every layer, so an unlayered rule here would override the generated
1038−/// ones. A page resets `box-sizing` everywhere and makes `<body>` a column
1039−/// that fills the window; a fragment, which goes into a page it doesn't
1040−/// own, touches only htmlang's own elements. In both, an element htmlang
1041−/// lays out stays hidden while it is `hidden`, a closed `<dialog>` or a
1042−/// popover that isn't showing: its generated `display` would otherwise
1043−/// beat the browser's `display: none`.
1044−fn reset_css(dev: bool, page: bool, focus_visible_css: &str) -> String {
1045− let own = OWN_ELEMENTS;
1046− let mut rules = Vec::new();
1047− if page {
1048− rules.push(if dev {
1049− "*, *::before, *::after { box-sizing: border-box; }".to_string()
1050− } else {
1051− "*,*::before,*::after{box-sizing:border-box}".to_string()
1052− });
1053− rules.push(if dev {
1054− "body { margin: 0; font-family: system-ui, -apple-system, sans-serif; display: flex; flex-direction: column; min-height: 100dvh; }".to_string()
1055− } else {
1056− "body{margin:0;font-family:system-ui,-apple-system,sans-serif;display:flex;flex-direction:column;min-height:100dvh}".to_string()
1057− });
1058− } else {
1059− rules.push(if dev {
1060− format!("{own}, {own}::before, {own}::after {{ box-sizing: border-box; }}")
708+ // @scope blocks
709+ for block in &doc.scope_blocks {
710+ if dev {
711+ element_css.push_str(block);
712+ element_css.push('\n');
1061713 } else {
1062− format!("{own},{own}::before,{own}::after{{box-sizing:border-box}}")
1063− });
714+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
715+ element_css.push_str(&minified);
716+ }
1064717 }
1065− let hidden = "[hidden]:not([hidden=\"until-found\"]),dialog:not([open]):not(:popover-open),\
1066− [popover]:not(:popover-open):not(dialog[open])";
1067− rules.push(if dev {
1068− format!("{own}:where({hidden}) {{ display: none !important; }}")
1069− } else {
1070− format!("{own}:where({hidden}){{display:none!important}}")
1071− });
1072− let mut rules = rules.join(if dev { "\n" } else { "" });
1073− if dev {
1074− rules.push('\n');
1075− }
1076− rules.push_str(focus_visible_css);
1077− if dev {
1078− format!(
1079− "@layer {};\n@layer hl-reset {{\n{}}}\n",
1080− LAYERS.join(", "),
1081− rules
1082− )
1083− } else {
1084− format!("@layer {};@layer hl-reset{{{}}}", LAYERS.join(","), rules)
718+
719+ // @starting-style blocks
720+ if !doc.starting_style_blocks.is_empty() {
721+ if dev {
722+ element_css.push_str("@starting-style {\n");
723+ for block in &doc.starting_style_blocks {
724+ element_css.push_str(block);
725+ element_css.push('\n');
726+ }
727+ element_css.push_str("}\n");
728+ } else {
729+ element_css.push_str("@starting-style{");
730+ for block in &doc.starting_style_blocks {
731+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
732+ element_css.push_str(&minified);
733+ }
734+ element_css.push('}');
735+ }
1085736 }
1086−}
1087737
1088−/// Generate an HTML fragment: body + optional <style>, no <html>/<head>/<body> wrapper.
1089−fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
1090− let mut styles = StyleCollector::new();
1091− let mut ctx = GenContext {
1092− dev,
1093− depth: 0,
1094− has_interactive: false,
1095− in_text: false,
1096− flow: Flow::default(),
1097− in_picture: false,
738+ // Build meta tags string
739+ let meta_html = if doc.meta_tags.is_empty() {
740+ String::new()
741+ } else {
742+ let mut m = String::new();
743+ for (name, content) in &doc.meta_tags {
744+ if dev {
745+ m.push_str(&format!(
746+ "<meta name=\"{}\" content=\"{}\">\n",
747+ html_escape(name),
748+ html_escape(content)
749+ ));
750+ } else {
751+ m.push_str(&format!(
752+ "<meta name=\"{}\" content=\"{}\">",
753+ html_escape(name),
754+ html_escape(content)
755+ ));
756+ }
757+ }
758+ m
759+ };
760+
761+ // Build OG meta tags
762+ let og_html = if doc.og_tags.is_empty() {
763+ String::new()
764+ } else {
765+ let mut o = String::new();
766+ for (property, content) in &doc.og_tags {
767+ if dev {
768+ o.push_str(&format!(
769+ "<meta property=\"og:{}\" content=\"{}\">\n",
770+ html_escape(property),
771+ html_escape(content)
772+ ));
773+ } else {
774+ o.push_str(&format!(
775+ "<meta property=\"og:{}\" content=\"{}\">",
776+ html_escape(property),
777+ html_escape(content)
778+ ));
779+ }
780+ }
781+ o
782+ };
783+
784+ // Build head blocks string
785+ let head_html = if doc.head_blocks.is_empty() {
786+ String::new()
787+ } else {
788+ let mut h = String::new();
789+ for block in &doc.head_blocks {
790+ h.push_str(block);
791+ if dev {
792+ h.push('\n');
793+ }
794+ }
795+ h
796+ };
797+
798+ let lang_attr = match &doc.lang {
799+ Some(lang) => format!(" lang=\"{}\"", html_escape(lang)),
800+ None => String::new(),
801+ };
802+
803+ let favicon_html = match &doc.favicon {
804+ Some(path) => {
805+ // Try to read and inline the favicon
806+ if let Ok(data) = std::fs::read(path) {
807+ let mime = if path.ends_with(".ico") {
808+ "image/x-icon"
809+ } else if path.ends_with(".png") {
810+ "image/png"
811+ } else if path.ends_with(".svg") {
812+ "image/svg+xml"
813+ } else {
814+ "image/x-icon"
815+ };
816+ let b64 = base64_encode(&data);
817+ if dev {
818+ format!("<link rel=\"icon\" href=\"data:{};base64,{}\">\n", mime, b64)
819+ } else {
820+ format!("<link rel=\"icon\" href=\"data:{};base64,{}\">", mime, b64)
821+ }
822+ } else {
823+ // Fall back to href
824+ if dev {
825+ format!("<link rel=\"icon\" href=\"{}\">\n", html_escape(path))
826+ } else {
827+ format!("<link rel=\"icon\" href=\"{}\">", html_escape(path))
828+ }
829+ }
830+ }
831+ None => String::new(),
832+ };
833+
834+ // Canonical URL
835+ let canonical_html = match &doc.canonical {
836+ Some(url) => {
837+ if dev {
838+ format!("<link rel=\"canonical\" href=\"{}\">\n", html_escape(url))
839+ } else {
840+ format!("<link rel=\"canonical\" href=\"{}\">", html_escape(url))
841+ }
842+ }
843+ None => String::new(),
844+ };
845+
846+ // Base URL
847+ let base_html = match &doc.base_url {
848+ Some(url) => {
849+ if dev {
850+ format!("<base href=\"{}\">\n", html_escape(url))
851+ } else {
852+ format!("<base href=\"{}\">", html_escape(url))
853+ }
854+ }
855+ None => String::new(),
856+ };
857+
858+ // @font-face CSS
859+ for (name, url) in &doc.font_faces {
860+ let format_hint = if url.ends_with(".woff2") {
861+ " format('woff2')"
862+ } else if url.ends_with(".woff") {
863+ " format('woff')"
864+ } else if url.ends_with(".ttf") {
865+ " format('truetype')"
866+ } else if url.ends_with(".otf") {
867+ " format('opentype')"
868+ } else {
869+ ""
870+ };
871+ if dev {
872+ element_css.insert_str(0, &format!(
873+ "@font-face {{\n font-family: '{}';\n src: url('{}'){};\n font-display: swap;\n}}\n",
874+ name, url, format_hint
875+ ));
876+ } else {
877+ element_css.insert_str(0, &format!(
878+ "@font-face{{font-family:'{}';src:url('{}'){};font-display:swap}}",
879+ name, url, format_hint
880+ ));
881+ }
882+ }
883+
884+ // JSON-LD blocks
885+ let json_ld_html: String = doc.json_ld_blocks.iter().map(|block| {
886+ if dev {
887+ format!("<script type=\"application/ld+json\">\n{}\n</script>\n", block)
888+ } else {
889+ format!("<script type=\"application/ld+json\">{}</script>", block)
890+ }
891+ }).collect();
892+
893+ // Manifest link
894+ let manifest_html = if let Some(ref manifest) = doc.manifest {
895+ let mut json = String::from("{");
896+ json.push_str(&format!("\"name\":\"{}\",", manifest.name));
897+ if let Some(ref short) = manifest.short_name {
898+ json.push_str(&format!("\"short_name\":\"{}\",", short));
899+ }
900+ json.push_str(&format!("\"start_url\":\"{}\",", manifest.start_url));
901+ json.push_str(&format!("\"display\":\"{}\"", manifest.display));
902+ if let Some(ref bg) = manifest.background_color {
903+ json.push_str(&format!(",\"background_color\":\"{}\"", bg));
904+ }
905+ if let Some(ref tc) = manifest.theme_color {
906+ json.push_str(&format!(",\"theme_color\":\"{}\"", tc));
907+ }
908+ if let Some(ref desc) = manifest.description {
909+ json.push_str(&format!(",\"description\":\"{}\"", desc));
910+ }
911+ if !manifest.icons.is_empty() {
912+ json.push_str(",\"icons\":[");
913+ for (i, (src, sizes)) in manifest.icons.iter().enumerate() {
914+ if i > 0 { json.push(','); }
915+ json.push_str(&format!("{{\"src\":\"{}\",\"sizes\":\"{}\",\"type\":\"image/png\"}}", src, sizes));
916+ }
917+ json.push(']');
918+ }
919+ json.push('}');
920+
921+ // Inline the manifest as a data URI
922+ let encoded = base64_encode(json.as_bytes());
923+ if dev {
924+ format!("<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">\n", encoded)
925+ } else {
926+ format!("<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">", encoded)
927+ }
928+ } else {
929+ String::new()
1098930 };
931+
932+ // Preload hints (auto-detect fonts from @font-face)
933+ let mut preload_html = String::new();
934+ for (_, url) in &doc.font_faces {
935+ if dev {
936+ preload_html.push_str(&format!(
937+ "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>\n", url
938+ ));
939+ } else {
940+ preload_html.push_str(&format!(
941+ "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>", url
942+ ));
943+ }
944+ }
945+ // Explicit preload hints from the document
946+ for hint in &doc.preload_hints {
947+ if dev {
948+ preload_html.push_str(&format!(
949+ "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>\n",
950+ html_escape(&hint.href), hint.as_type,
951+ if hint.crossorigin { " crossorigin" } else { "" }
952+ ));
953+ } else {
954+ preload_html.push_str(&format!(
955+ "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>",
956+ html_escape(&hint.href), hint.as_type,
957+ if hint.crossorigin { " crossorigin" } else { "" }
958+ ));
959+ }
960+ }
961+
962+ match &doc.page_title {
963+ Some(title) => {
964+ if dev {
965+ format!(
966+ "\
967+<!DOCTYPE html>
968+<html{lang_attr}>
969+<head>
970+<meta charset=\"utf-8\">
971+<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
972+<title>{title}</title>
973+{base_html}{canonical_html}{manifest_html}{preload_html}{meta_html}{og_html}{favicon_html}{json_ld_html}{head_html}\
974+<style>
975+*, *::before, *::after {{ box-sizing: border-box; }}
976+body {{ margin: 0; font-family: system-ui, -apple-system, sans-serif; }}
977+img {{ display: block; }}
978+{element_css}\
979+</style>
980+</head>
981+<body>
982+{body}\
983+</body>
984+</html>
985+",
986+ title = html_escape(title),
987+ lang_attr = lang_attr,
988+ base_html = base_html,
989+ canonical_html = canonical_html,
990+ manifest_html = manifest_html,
991+ preload_html = preload_html,
992+ meta_html = meta_html,
993+ favicon_html = favicon_html,
994+ json_ld_html = json_ld_html,
995+ head_html = head_html,
996+ og_html = og_html,
997+ element_css = element_css,
998+ body = body,
999+ )
1000+ } else {
1001+ format!(
1002+ "<!DOCTYPE html><html{lang_attr}><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>{title}</title>{base_html}{canonical_html}{manifest_html}{preload_html}{meta_html}{og_html}{favicon_html}{json_ld_html}{head_html}<style>*,*::before,*::after{{box-sizing:border-box}}body{{margin:0;font-family:system-ui,-apple-system,sans-serif}}img{{display:block}}{element_css}</style></head><body>{body}</body></html>",
1003+ title = html_escape(title),
1004+ lang_attr = lang_attr,
1005+ base_html = base_html,
1006+ canonical_html = canonical_html,
1007+ manifest_html = manifest_html,
1008+ preload_html = preload_html,
1009+ meta_html = meta_html,
1010+ og_html = og_html,
1011+ favicon_html = favicon_html,
1012+ json_ld_html = json_ld_html,
1013+ head_html = head_html,
1014+ element_css = element_css,
1015+ body = body,
1016+ )
1017+ }
1018+ }
1019+ None => {
1020+ if element_css.is_empty() {
1021+ body
1022+ } else {
1023+ if dev {
1024+ format!("<style>\n{}</style>\n{}", element_css, body)
1025+ } else {
1026+ format!("<style>{}</style>{}", element_css, body)
1027+ }
1028+ }
1029+ }
1030+ }
1031+}
1032+
1033+/// Generate an HTML fragment: body + optional <style>, no <html>/<head>/<body> wrapper.
1034+fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1035+ let mut styles = StyleCollector::new();
1036+ let mut ctx = GenContext { dev, depth: 0 };
10991037 let mut body = String::new();
11001038
1101− generate_children(&doc.nodes, None, &mut body, &mut styles, &mut ctx);
1039+ for node in &doc.nodes {
1040+ generate_node(node, None, &mut body, &mut styles, &mut ctx);
1041+ }
1042+
1043+ let has_custom_css = !doc.custom_css.is_empty();
1044+ let mut element_css = String::new();
1045+
1046+ // CSS custom properties
1047+ if !doc.css_vars.is_empty() || !doc.theme_tokens.is_empty() {
1048+ if dev {
1049+ element_css.push_str(":root {\n");
1050+ for (name, value) in &doc.css_vars {
1051+ element_css.push_str(&format!(" {}: {};\n", name, value));
1052+ }
1053+ for (name, value) in &doc.theme_tokens {
1054+ let css_name = format!("--{}", name);
1055+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
1056+ element_css.push_str(&format!(" {}: {};\n", css_name, value));
1057+ }
1058+ }
1059+ element_css.push_str("}\n");
1060+ } else {
1061+ element_css.push_str(":root{");
1062+ for (name, value) in &doc.css_vars {
1063+ element_css.push_str(name);
1064+ element_css.push(':');
1065+ element_css.push_str(value);
1066+ element_css.push(';');
1067+ }
1068+ for (name, value) in &doc.theme_tokens {
1069+ let css_name = format!("--{}", name);
1070+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
1071+ element_css.push_str(&css_name);
1072+ element_css.push(':');
1073+ element_css.push_str(value);
1074+ element_css.push(';');
1075+ }
1076+ }
1077+ element_css.push('}');
1078+ }
1079+ }
1080+
1081+ element_css.push_str(&styles.to_css_formatted(dev, !has_custom_css));
11021082
1103− let mut element_css = build_element_css(doc, &styles, dev);
1104− // htmlang's own elements get the reset's rules for elements (which
1105− // also puts htmlang's layers in order)
1106− if !styles.entries.is_empty() || !doc.scoped_css.is_empty() {
1107− element_css.insert_str(0, &reset_css(dev, false, ""));
1083+ for (name, kf_body) in &doc.keyframes {
1084+ if dev {
1085+ element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1086+ } else {
1087+ element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1088+ }
1089+ }
1090+
1091+ for block in &doc.custom_css {
1092+ if dev {
1093+ element_css.push_str(block);
1094+ element_css.push('\n');
1095+ } else {
1096+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1097+ element_css.push_str(&minified);
1098+ }
11081099 }
1109− classes.extend(styles.classes());
11101100
11111101 if element_css.is_empty() {
11121102 body
@@ -1121,20 +1111,29 @@ fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -
11211111// Node generation
11221112// ---------------------------------------------------------------------------
11231113
1124−/// Write `node`, which is inside an element with the layout `parent`
1125−/// (`None` at the top of the page).
11261114fn generate_node(
11271115 node: &Node,
1128− parent: Option<Layout>,
1116+ parent_kind: Option<&ElementKind>,
11291117 out: &mut String,
11301118 styles: &mut StyleCollector,
11311119 ctx: &mut GenContext,
11321120) {
11331121 match node {
1134− Node::Element(elem) => generate_element(elem, parent, out, styles, ctx),
1122+ Node::Element(elem) => generate_element(elem, parent_kind, out, styles, ctx),
11351123 Node::Text(segments) => {
1136− // In a row, column or grid each line of text is a child
1137− let needs_wrap = parent.is_some_and(Layout::is_container);
1124+ let needs_wrap = matches!(
1125+ parent_kind,
1126+ Some(ElementKind::Row) | Some(ElementKind::Column) | Some(ElementKind::El)
1127+ | Some(ElementKind::Nav) | Some(ElementKind::Header) | Some(ElementKind::Footer)
1128+ | Some(ElementKind::Main) | Some(ElementKind::Section) | Some(ElementKind::Article)
1129+ | Some(ElementKind::Aside) | Some(ElementKind::ListItem)
1130+ | Some(ElementKind::Form) | Some(ElementKind::Details) | Some(ElementKind::Figure)
1131+ | Some(ElementKind::Blockquote)
1132+ | Some(ElementKind::Dialog) | Some(ElementKind::DefinitionList)
1133+ | Some(ElementKind::DefinitionDescription) | Some(ElementKind::Fieldset)
1134+ | Some(ElementKind::Datalist) | Some(ElementKind::Grid) | Some(ElementKind::Stack)
1135+ | Some(ElementKind::Noscript) | Some(ElementKind::Address) | Some(ElementKind::Search)
1136+ );
11381137 if needs_wrap {
11391138 out.push_str(&ctx.indent());
11401139 out.push_str("<span>");
@@ -1153,197 +1152,111 @@ fn generate_node(
11531152 }
11541153}
11551154
1156−/// What goes between two things written one after the other in an element
1157−/// with this layout (`None`: the top of the page): text flows, so its lines
1158−/// and children are joined with a space; in HTML's own layout, and at the
1159−/// top of the page, two lines of text are separated by a line break (a
1160−/// space, except where whitespace is kept, as in `@pre`).
1161−fn separator(layout: Option<Layout>, previous_is_text: bool, next: &Node) -> Option<char> {
1162− match layout {
1163− Some(Layout::Text) => Some(' '),
1164− Some(Layout::Native) | None if previous_is_text && matches!(next, Node::Text(_)) => {
1165− Some('\n')
1166− }
1167− _ => None,
1168− }
1169−}
1155+/// HTML attributes that are passed through to the HTML tag rather than converted to CSS.
1156+const HTML_PASSTHROUGH_ATTRS: &[&str] = &[
1157+ "type", "placeholder", "name", "value", "disabled", "required", "checked",
1158+ "for", "action", "method", "autocomplete",
1159+ "min", "max", "step", "pattern", "maxlength", "rows", "cols", "multiple",
1160+ "alt", "role", "tabindex", "title", "autofocus",
1161+ // Media
1162+ "controls", "autoplay", "loop", "muted", "poster", "preload",
1163+ // Image optimization
1164+ "loading", "decoding",
1165+ // Media src (explicit attribute form)
1166+ "src",
1167+ // New element attributes
1168+ "datetime", "media", "sizes", "srcset", "list",
1169+ // Details
1170+ "open",
1171+ // Form
1172+ "novalidate",
1173+ // Progress/Meter
1174+ "low", "high", "optimum",
1175+ // Table
1176+ "colspan", "rowspan", "scope",
1177+ // Popover API
1178+ "popover", "popovertarget", "popovertargetaction",
1179+ // Modern form/input hints
1180+ "inputmode", "enterkeyhint",
1181+ // Performance hints
1182+ "fetchpriority", "blocking",
1183+ // Global attrs
1184+ "translate", "spellcheck",
1185+];
11701186
1171−/// Write the children of an element (or of a `@fragment`, which has no
1172−/// element of its own) laid out as `layout` (`None`: the top of the page).
1173−/// The first line of an element's text is its first child.
1174−fn generate_children(
1175− children: &[Node],
1176− layout: Option<Layout>,
1177− out: &mut String,
1178− styles: &mut StyleCollector,
1179− ctx: &mut GenContext,
1180−) {
1181− generate_run(children, layout, &mut None, out, styles, ctx);
1182−}
1187+/// Boolean HTML attributes (rendered without a value, e.g., `<input disabled>`).
1188+const BOOLEAN_HTML_ATTRS: &[&str] = &[
1189+ "disabled", "required", "checked", "multiple",
1190+ "controls", "autoplay", "loop", "muted",
1191+ "open", "novalidate", "autofocus",
1192+ "defer", "async", "nomodule",
1193+ // Popover
1194+ "popover",
1195+];
11831196
1184−/// [`generate_children`], with `previous` saying whether what was written
1185−/// last was a line of text (`None`: nothing yet). A `@fragment`'s children
1186−/// are written as if they stood in its place, so its lines are separated
1187−/// from the lines around it like any other lines.
1188−fn generate_run(
1189− children: &[Node],
1190− layout: Option<Layout>,
1191− previous: &mut Option<bool>,
1192− out: &mut String,
1193− styles: &mut StyleCollector,
1194− ctx: &mut GenContext,
1195−) {
1196− for child in children {
1197− if let Node::Element(elem) = child
1198− && elem.kind == ElementKind::Fragment
1199− {
1200− generate_run(&elem.children, layout, previous, out, styles, ctx);
1201− continue;
1202− }
1203− let start = out.len();
1204− if let Some(previous_is_text) = *previous
1205− && let Some(sep) = separator(layout, previous_is_text, child)
1206− {
1207− out.push(sep);
1208− }
1209− let body = out.len();
1210− generate_node(child, layout, out, styles, ctx);
1211− // A child that writes nothing (an empty `@fragment`) takes no
1212− // separator either, so text never gets two spaces in a row
1213− if out.len() == body {
1214− out.truncate(start);
1197+fn emit_html_passthrough_attrs(out: &mut String, attrs: &[Attribute]) {
1198+ for attr in attrs {
1199+ let key = attr.key.as_str();
1200+ let is_passthrough = HTML_PASSTHROUGH_ATTRS.contains(&key)
1201+ || key.starts_with("aria-")
1202+ || key.starts_with("data-");
1203+ if !is_passthrough {
12151204 continue;
12161205 }
1217− *previous = Some(matches!(child, Node::Text(_)));
1218− }
1219−}
1220−
1221−/// Emit the element's leading argument as its attribute (`@iframe URL` →
1222−/// `src="URL"`, `@form /submit` → `action="/submit"`, `@link /a` →
1223−/// `href="/a"`), first, before the class. `@image [inline] photo.png` puts
1224−/// the file itself into the page.
1225−fn emit_argument_attr(out: &mut String, elem: &Element, in_picture: bool) {
1226− let (Some(attr), Some(value)) = (elem.kind.leading_attribute(in_picture), &elem.argument)
1227− else {
1228− return;
1229− };
1230− // `@image [inline]`'s file is already a `data:` URI (see the parser)
1231− let value = html_escape(value);
1232− out.push(' ');
1233− out.push_str(attr);
1234− out.push_str("=\"");
1235− out.push_str(&value);
1236− out.push('"');
1237−}
1238−
1239−/// A file's bytes as a `data:` URI, its type from its extension.
1240−pub(crate) fn data_uri(path: &str, data: &[u8]) -> String {
1241− let mime = match path
1242− .rsplit('.')
1243− .next()
1244− .map(str::to_ascii_lowercase)
1245− .as_deref()
1246− {
1247− Some("png") => "image/png",
1248− Some("jpg" | "jpeg") => "image/jpeg",
1249− Some("gif") => "image/gif",
1250− Some("webp") => "image/webp",
1251− Some("avif") => "image/avif",
1252− Some("svg") => "image/svg+xml",
1253− Some("ico") => "image/x-icon",
1254− _ => "application/octet-stream",
1255− };
1256− format!("data:{};base64,{}", mime, base64_encode(data))
1257−}
1258−
1259−/// Emit HTML attributes: `key=value` ones (except `id` / `class`, which
1260−/// are emitted with the generated class) and flags like `required`.
1261−fn emit_html_attrs(out: &mut String, attrs: &[Attribute]) {
1262− for attr in html_attrs(attrs) {
1263− let key = attr.key.as_str();
1264− if key != "id" && key != "class" {
1265− push_html_attr(out, attr);
1206+ if BOOLEAN_HTML_ATTRS.contains(&key) && attr.value.is_none() {
1207+ out.push(' ');
1208+ out.push_str(key);
1209+ } else if let Some(val) = &attr.value {
1210+ out.push(' ');
1211+ out.push_str(key);
1212+ out.push_str("=\"");
1213+ out.push_str(&html_escape(val));
1214+ out.push('"');
12661215 }
12671216 }
12681217}
12691218
1270−/// The HTML attributes of `attrs`, `key=value` ones and flags, each name
1271−/// once: the later one wins, as a style does. (Of two attributes with one
1272−/// name, the browser keeps the first, so a bundle's attribute or a
1273−/// function's own would win over one written after it.)
1274−fn html_attrs(attrs: &[Attribute]) -> impl Iterator<Item = &Attribute> {
1275− let is_html =
1276− |a: &Attribute| a.html || (a.value.is_none() && crate::vocab::is_html_flag(&a.key));
1277− attrs.iter().enumerate().filter_map(move |(i, attr)| {
1278− let later = attrs[i + 1..]
1279− .iter()
1280− .any(|other| is_html(other) && other.key == attr.key);
1281− (is_html(attr) && !later).then_some(attr)
1282− })
1283−}
1284−
1285−/// ` key="value"`, or ` key` for a flag.
1286−fn push_html_attr(out: &mut String, attr: &Attribute) {
1287− out.push(' ');
1288− out.push_str(&attr.key);
1289− if attr.html {
1290− out.push_str("=\"");
1291− // Quoted text has already lost its quotes (see parser.rs)
1292− out.push_str(&html_escape(attr.value.as_deref().unwrap_or("")));
1293− out.push('"');
1294− }
1295−}
1296−
1297−// True if any direct child is `@in-front` or `@behind`. Such children render
1298−// as absolutely positioned overlays, so the parent automatically becomes a
1299−// positioning context (position:relative + isolation:isolate).
1300−fn has_overlay_children(elem: &Element) -> bool {
1301− holds_overlays(&elem.children)
1302−}
1303−
1304−fn holds_overlays(children: &[Node]) -> bool {
1305− children.iter().any(|child| {
1306− matches!(
1307− child,
1308− Node::Element(e) if e.kind.is_tag("in-front") || e.kind.is_tag("behind")
1309− )
1310− })
1311−}
1312−
13131219fn generate_element(
13141220 elem: &Element,
1315− parent: Option<Layout>,
1221+ parent_kind: Option<&ElementKind>,
13161222 out: &mut String,
13171223 styles: &mut StyleCollector,
13181224 ctx: &mut GenContext,
13191225) {
13201226 // Self-closing elements
1321− if elem.kind.layout() == Layout::Void {
1322− generate_self_closing(elem, parent, out, styles, ctx);
1227+ if matches!(elem.kind, ElementKind::Image | ElementKind::Input | ElementKind::HorizontalRule | ElementKind::Source | ElementKind::Spacer) {
1228+ generate_self_closing(elem, parent_kind, out, styles, ctx);
13231229 return;
13241230 }
1325− // A verbatim element (@script) writes its body as it is, with no HTML
1326− // escaping; it isn't shown, so it has no class (its styles are an error)
1327− if elem.kind.is_verbatim() {
1328− let tag = elem.kind.spec().map_or("script", |spec| spec.html);
1231+ // @script renders as <script> with raw body content (no HTML escaping)
1232+ if elem.kind == ElementKind::Script {
13291233 out.push_str(&ctx.indent());
1330− out.push('<');
1331− out.push_str(tag);
1332− emit_argument_attr(out, elem, false);
1333− let (id, class) = extract_id_class(&elem.attrs);
1334− for (key, value) in [("id", id), ("class", class)] {
1335− if let Some(value) = value {
1336− out.push_str(&format!(" {}=\"{}\"", key, html_escape(&value)));
1234+ out.push_str("<script");
1235+ // Pass through src, type, defer, async, etc.
1236+ for attr in &elem.attrs {
1237+ let key = attr.key.as_str();
1238+ if matches!(key, "src" | "type" | "defer" | "async" | "crossorigin" | "integrity" | "nomodule" | "id") {
1239+ if let Some(val) = &attr.value {
1240+ out.push(' ');
1241+ out.push_str(key);
1242+ out.push_str("=\"");
1243+ out.push_str(&html_escape(val));
1244+ out.push('"');
1245+ } else {
1246+ out.push(' ');
1247+ out.push_str(key);
1248+ }
13371249 }
13381250 }
1339− emit_html_attrs(out, &elem.attrs);
13401251 out.push('>');
1252+ // Children are raw JS code, not HTML
13411253 for child in &elem.children {
13421254 match child {
13431255 Node::Text(segments) => {
13441256 for seg in segments {
1345− if let TextSegment::Plain(text) = seg {
1346− out.push_str(text)
1257+ match seg {
1258+ TextSegment::Plain(text) => out.push_str(text),
1259+ _ => {}
13471260 }
13481261 }
13491262 }
@@ -1351,10 +1264,46 @@ fn generate_element(
13511264 _ => {}
13521265 }
13531266 }
1354− out.push_str("</");
1355− out.push_str(tag);
1267+ out.push_str("</script>");
1268+ out.push_str(ctx.nl());
1269+ return;
1270+ }
1271+ // @breadcrumb generates semantic <nav aria-label="breadcrumb"><ol>...</ol></nav>
1272+ if elem.kind == ElementKind::Breadcrumb {
1273+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
1274+ let (id, user_class) = extract_id_class(&elem.attrs);
1275+ out.push_str(&ctx.indent());
1276+ out.push_str("<nav aria-label=\"breadcrumb\"");
1277+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1278+ if let Some(id) = id {
1279+ out.push_str(" id=\"");
1280+ out.push_str(&html_escape(&id));
1281+ out.push('"');
1282+ }
13561283 out.push('>');
13571284 out.push_str(ctx.nl());
1285+ ctx.depth += 1;
1286+ out.push_str(&ctx.indent());
1287+ out.push_str("<ol>");
1288+ out.push_str(ctx.nl());
1289+ ctx.depth += 1;
1290+ for child in &elem.children {
1291+ out.push_str(&ctx.indent());
1292+ out.push_str("<li>");
1293+ let mut buf = String::new();
1294+ generate_node(child, Some(&elem.kind), &mut buf, styles, ctx);
1295+ out.push_str(buf.trim());
1296+ out.push_str("</li>");
1297+ out.push_str(ctx.nl());
1298+ }
1299+ ctx.depth -= 1;
1300+ out.push_str(&ctx.indent());
1301+ out.push_str("</ol>");
1302+ out.push_str(ctx.nl());
1303+ ctx.depth -= 1;
1304+ out.push_str(&ctx.indent());
1305+ out.push_str("</nav>");
1306+ out.push_str(ctx.nl());
13581307 return;
13591308 }
13601309 if elem.kind == ElementKind::Children {
@@ -1364,54 +1313,243 @@ fn generate_element(
13641313 return;
13651314 }
13661315 if elem.kind == ElementKind::Fragment {
1367− // Render children without a wrapper element, as if they were
1368− // written where the fragment is
1369− generate_children(&elem.children, parent, out, styles, ctx);
1316+ // Render children without a wrapper element
1317+ for child in &elem.children {
1318+ generate_node(child, parent_kind, out, styles, ctx);
1319+ }
13701320 return;
13711321 }
13721322
1373− let mut own = Flow::of(elem);
13741323 let tag = match &elem.kind {
1375− ElementKind::Row | ElementKind::El => "div",
1324+ ElementKind::Row | ElementKind::Column | ElementKind::El
1325+ | ElementKind::Grid | ElementKind::Stack => "div",
13761326 ElementKind::Text => "span",
13771327 ElementKind::Paragraph => "p",
13781328 ElementKind::Link => "a",
1379− ElementKind::Tag(spec) => spec.html,
1380− _ => "",
1329+ ElementKind::Button => "button",
1330+ ElementKind::Select => "select",
1331+ ElementKind::Textarea => "textarea",
1332+ ElementKind::Option => "option",
1333+ ElementKind::Label => "label",
1334+ // Semantic elements
1335+ ElementKind::Nav => "nav",
1336+ ElementKind::Header => "header",
1337+ ElementKind::Footer => "footer",
1338+ ElementKind::Main => "main",
1339+ ElementKind::Section => "section",
1340+ ElementKind::Article => "article",
1341+ ElementKind::Aside => "aside",
1342+ // List
1343+ ElementKind::List => {
1344+ if elem.attrs.iter().any(|a| a.key == "ordered") { "ol" } else { "ul" }
1345+ }
1346+ ElementKind::ListItem => "li",
1347+ // Table
1348+ ElementKind::Table => "table",
1349+ ElementKind::TableHead => "thead",
1350+ ElementKind::TableBody => "tbody",
1351+ ElementKind::TableRow => "tr",
1352+ ElementKind::TableCell => "td",
1353+ ElementKind::TableHeaderCell => "th",
1354+ // Media
1355+ ElementKind::Video => "video",
1356+ ElementKind::Audio => "audio",
1357+ // Additional semantic elements
1358+ ElementKind::Form => "form",
1359+ ElementKind::Details => "details",
1360+ ElementKind::Summary => "summary",
1361+ ElementKind::Blockquote => "blockquote",
1362+ ElementKind::Cite => "cite",
1363+ ElementKind::Code => "code",
1364+ ElementKind::Pre => "pre",
1365+ ElementKind::Figure => "figure",
1366+ ElementKind::FigCaption => "figcaption",
1367+ ElementKind::Progress => "progress",
1368+ ElementKind::Meter => "meter",
1369+ // New elements
1370+ ElementKind::Dialog => "dialog",
1371+ ElementKind::DefinitionList => "dl",
1372+ ElementKind::DefinitionTerm => "dt",
1373+ ElementKind::DefinitionDescription => "dd",
1374+ ElementKind::Fieldset => "fieldset",
1375+ ElementKind::Legend => "legend",
1376+ ElementKind::Picture => "picture",
1377+ ElementKind::Time => "time",
1378+ ElementKind::Mark => "mark",
1379+ ElementKind::Kbd => "kbd",
1380+ ElementKind::Abbr => "abbr",
1381+ ElementKind::Datalist => "datalist",
1382+ ElementKind::Iframe => "iframe",
1383+ ElementKind::Output => "output",
1384+ ElementKind::Canvas => "canvas",
1385+ ElementKind::Badge => "span",
1386+ ElementKind::Tooltip => "span",
1387+ ElementKind::Avatar => "div",
1388+ ElementKind::Carousel => "div",
1389+ ElementKind::Chip => "span",
1390+ ElementKind::Tag => "span",
1391+ ElementKind::Noscript => "noscript",
1392+ ElementKind::Address => "address",
1393+ ElementKind::Search => "search",
1394+ ElementKind::Image | ElementKind::Input | ElementKind::HorizontalRule
1395+ | ElementKind::Children | ElementKind::Slot(_) | ElementKind::Fragment
1396+ | ElementKind::Source | ElementKind::Spacer
1397+ | ElementKind::Script | ElementKind::Breadcrumb => unreachable!(),
13811398 };
1382− // Inside text, htmlang's own `<div>` is a `<span>`, which text can
1383− // hold (directly in text, a row, column or grid is also laid out
1384− // inline: see `Site::inline`)
1385− let in_text = ctx.in_text || parent == Some(Layout::Text);
1386− let tag = if in_text && tag == "div" { "span" } else { tag };
1387− let kind_label = elem.kind.name();
13881399
1389− // Track interactive elements for focus-visible CSS
1390− if elem.kind == ElementKind::Link
1391− || matches!(kind_label, "button" | "input" | "select" | "textarea")
1392− {
1393− ctx.has_interactive = true;
1394− }
1400+ let kind_label = match elem.kind {
1401+ ElementKind::Row => "row",
1402+ ElementKind::Column => "column",
1403+ ElementKind::El => "el",
1404+ ElementKind::Text => "text",
1405+ ElementKind::Paragraph => "paragraph",
1406+ ElementKind::Link => "link",
1407+ ElementKind::Button => "button",
1408+ ElementKind::Select => "select",
1409+ ElementKind::Textarea => "textarea",
1410+ ElementKind::Option => "option",
1411+ ElementKind::Label => "label",
1412+ ElementKind::Nav => "nav",
1413+ ElementKind::Header => "header",
1414+ ElementKind::Footer => "footer",
1415+ ElementKind::Main => "main",
1416+ ElementKind::Section => "section",
1417+ ElementKind::Article => "article",
1418+ ElementKind::Aside => "aside",
1419+ ElementKind::List => "list",
1420+ ElementKind::ListItem => "item",
1421+ ElementKind::Table => "table",
1422+ ElementKind::TableHead => "thead",
1423+ ElementKind::TableBody => "tbody",
1424+ ElementKind::TableRow => "tr",
1425+ ElementKind::TableCell => "td",
1426+ ElementKind::TableHeaderCell => "th",
1427+ ElementKind::Video => "video",
1428+ ElementKind::Audio => "audio",
1429+ ElementKind::Form => "form",
1430+ ElementKind::Details => "details",
1431+ ElementKind::Summary => "summary",
1432+ ElementKind::Blockquote => "blockquote",
1433+ ElementKind::Cite => "cite",
1434+ ElementKind::Code => "code",
1435+ ElementKind::Pre => "pre",
1436+ ElementKind::Figure => "figure",
1437+ ElementKind::FigCaption => "figcaption",
1438+ ElementKind::Fragment => "fragment",
1439+ ElementKind::Dialog => "dialog",
1440+ ElementKind::DefinitionList => "dl",
1441+ ElementKind::DefinitionTerm => "dt",
1442+ ElementKind::DefinitionDescription => "dd",
1443+ ElementKind::Fieldset => "fieldset",
1444+ ElementKind::Legend => "legend",
1445+ ElementKind::Picture => "picture",
1446+ ElementKind::Time => "time",
1447+ ElementKind::Mark => "mark",
1448+ ElementKind::Kbd => "kbd",
1449+ ElementKind::Abbr => "abbr",
1450+ ElementKind::Datalist => "datalist",
1451+ ElementKind::Iframe => "iframe",
1452+ ElementKind::Output => "output",
1453+ ElementKind::Canvas => "canvas",
1454+ ElementKind::Grid => "grid",
1455+ ElementKind::Stack => "stack",
1456+ ElementKind::Badge => "badge",
1457+ ElementKind::Tooltip => "tooltip",
1458+ ElementKind::Avatar => "avatar",
1459+ ElementKind::Carousel => "carousel",
1460+ ElementKind::Chip => "chip",
1461+ ElementKind::Tag => "tag",
1462+ ElementKind::Noscript => "noscript",
1463+ ElementKind::Address => "address",
1464+ ElementKind::Search => "search",
1465+ _ => "",
1466+ };
13951467
13961468 // Compute CSS for each state and get a class name
1397− let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
1398− own.class = gen_class.clone();
1469+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
13991470 let (id, user_class) = extract_id_class(&elem.attrs);
14001471
14011472 if ctx.dev && elem.line_num > 0 {
14021473 out.push_str(&ctx.indent());
1403− out.push_str(&format!(
1404− "<!-- @{} line {} -->\n",
1405− kind_label, elem.line_num
1406− ));
1474+ out.push_str(&format!("<!-- @{} line {} -->\n", kind_label, elem.line_num));
14071475 }
14081476 out.push_str(&ctx.indent());
14091477 out.push('<');
14101478 out.push_str(tag);
14111479
1412− emit_argument_attr(out, elem, ctx.in_picture);
1480+ if elem.kind == ElementKind::Link {
1481+ if let Some(url) = &elem.argument {
1482+ out.push_str(" href=\"");
1483+ out.push_str(&html_escape(url));
1484+ out.push('"');
1485+ }
1486+ }
1487+
1488+ // Video/Audio src
1489+ if matches!(elem.kind, ElementKind::Video | ElementKind::Audio) {
1490+ if let Some(src) = &elem.argument {
1491+ out.push_str(" src=\"");
1492+ out.push_str(&html_escape(src));
1493+ out.push('"');
1494+ }
1495+ }
14131496
1414− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1497+ // Form action
1498+ if elem.kind == ElementKind::Form {
1499+ if let Some(action) = &elem.argument {
1500+ out.push_str(" action=\"");
1501+ out.push_str(&html_escape(action));
1502+ out.push('"');
1503+ }
1504+ }
1505+
1506+ // Iframe src
1507+ if elem.kind == ElementKind::Iframe {
1508+ if let Some(src) = &elem.argument {
1509+ out.push_str(" src=\"");
1510+ out.push_str(&html_escape(src));
1511+ out.push('"');
1512+ }
1513+ }
1514+
1515+ // Tooltip title
1516+ if elem.kind == ElementKind::Tooltip {
1517+ if let Some(text) = &elem.argument {
1518+ out.push_str(" title=\"");
1519+ out.push_str(&html_escape(text));
1520+ out.push('"');
1521+ }
1522+ }
1523+
1524+ // Time datetime
1525+ if elem.kind == ElementKind::Time {
1526+ if let Some(dt) = elem.attrs.iter().find(|a| a.key == "datetime") {
1527+ if let Some(val) = &dt.value {
1528+ out.push_str(" datetime=\"");
1529+ out.push_str(&html_escape(val));
1530+ out.push('"');
1531+ }
1532+ }
1533+ }
1534+
1535+ // Critical CSS: inline styles directly instead of using a class
1536+ let is_critical = elem.attrs.iter().any(|a| a.key == "critical");
1537+ if is_critical {
1538+ let inline_css = attrs_to_css(&elem.attrs, "", &elem.kind, parent_kind);
1539+ if !inline_css.is_empty() {
1540+ out.push_str(" style=\"");
1541+ out.push_str(&html_escape(&inline_css));
1542+ out.push('"');
1543+ }
1544+ // Still use class for non-base styles (pseudo, responsive, etc.)
1545+ if gen_class.as_deref().map_or(false, |c| !c.is_empty()) {
1546+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1547+ } else if let Some(ref uc) = user_class {
1548+ emit_class_attr(out, None, Some(uc));
1549+ }
1550+ } else {
1551+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1552+ }
14151553
14161554 if let Some(id) = id {
14171555 out.push_str(" id=\"");
@@ -1419,38 +1557,60 @@ fn generate_element(
14191557 out.push('"');
14201558 }
14211559
1422− emit_html_attrs(out, &elem.attrs);
1560+ emit_html_passthrough_attrs(out, &elem.attrs);
14231561
14241562 // Source map attributes in dev mode
14251563 if ctx.dev && elem.line_num > 0 {
1426− out.push_str(&format!(
1427− " data-hl-line=\"{}\" data-hl-el=\"{}\"",
1428− elem.line_num, kind_label
1429− ));
1564+ out.push_str(&format!(" data-hl-line=\"{}\" data-hl-el=\"{}\"", elem.line_num, kind_label));
14301565 }
14311566
14321567 out.push('>');
1433− // In `<pre>` and `<textarea>` every space and line break shows, so
1434− // readable (dev) output adds none there: a code sample's lines stay
1435− // exactly as written
1436− let outer_dev = ctx.dev;
1437− ctx.dev &= !matches!(tag, "pre" | "textarea");
14381568 out.push_str(ctx.nl());
14391569
1440− let layout = elem.kind.layout();
1570+ // Inline text argument
1571+ if matches!(
1572+ elem.kind,
1573+ ElementKind::Text
1574+ | ElementKind::Button
1575+ | ElementKind::Label
1576+ | ElementKind::Option
1577+ | ElementKind::Textarea
1578+ | ElementKind::ListItem
1579+ | ElementKind::TableCell
1580+ | ElementKind::TableHeaderCell
1581+ | ElementKind::Summary
1582+ | ElementKind::Cite
1583+ | ElementKind::Code
1584+ | ElementKind::FigCaption
1585+ | ElementKind::Legend
1586+ | ElementKind::DefinitionTerm
1587+ | ElementKind::Mark
1588+ | ElementKind::Kbd
1589+ | ElementKind::Abbr
1590+ | ElementKind::Time
1591+ | ElementKind::DefinitionDescription
1592+ | ElementKind::Badge
1593+ | ElementKind::Tooltip
1594+ | ElementKind::Chip
1595+ | ElementKind::Tag
1596+ ) {
1597+ if let Some(text) = &elem.argument {
1598+ out.push_str(&html_escape(text));
1599+ }
1600+ }
1601+
1602+ // Children
14411603 ctx.depth += 1;
1442− let outer_in_text = ctx.in_text;
1443− ctx.in_text = in_text || layout == Layout::Text;
1444− let outer_flow = std::mem::replace(&mut ctx.flow, own);
1445− let outer_picture = std::mem::replace(&mut ctx.in_picture, elem.kind.is_tag("picture"));
1446− generate_children(&elem.children, Some(layout), out, styles, ctx);
1447− ctx.in_picture = outer_picture;
1448− ctx.flow = outer_flow;
1449− ctx.in_text = outer_in_text;
1604+ let is_paragraph = elem.kind == ElementKind::Paragraph;
1605+ for (i, child) in elem.children.iter().enumerate() {
1606+ generate_node(child, Some(&elem.kind), out, styles, ctx);
1607+ if is_paragraph && i < elem.children.len() - 1 {
1608+ out.push(' ');
1609+ }
1610+ }
14501611 ctx.depth -= 1;
14511612
14521613 out.push_str(&ctx.indent());
1453− ctx.dev = outer_dev;
14541614 out.push_str("</");
14551615 out.push_str(tag);
14561616 out.push('>');
@@ -1459,31 +1619,60 @@ fn generate_element(
14591619
14601620fn generate_self_closing(
14611621 elem: &Element,
1462− parent: Option<Layout>,
1622+ parent_kind: Option<&ElementKind>,
14631623 out: &mut String,
14641624 styles: &mut StyleCollector,
1465− ctx: &mut GenContext,
1625+ ctx: &GenContext,
14661626) {
1467− let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
1627+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
14681628 let (id, user_class) = extract_id_class(&elem.attrs);
14691629
1470− let (tag, kind_label) = match &elem.kind {
1630+ let (tag, kind_label) = match elem.kind {
14711631 ElementKind::Image => ("img", "image"),
1472− ElementKind::Tag(spec) => (spec.html, spec.name),
1473− _ => unreachable!("not a void element: {:?}", elem.kind),
1632+ ElementKind::Input => ("input", "input"),
1633+ ElementKind::HorizontalRule => ("hr", "hr"),
1634+ ElementKind::Source => ("source", "source"),
1635+ ElementKind::Spacer => ("div", "spacer"),
1636+ _ => unreachable!(),
14741637 };
14751638
14761639 if ctx.dev && elem.line_num > 0 {
14771640 out.push_str(&ctx.indent());
1478− out.push_str(&format!(
1479− "<!-- @{} line {} -->\n",
1480− kind_label, elem.line_num
1481− ));
1641+ out.push_str(&format!("<!-- @{} line {} -->\n", kind_label, elem.line_num));
14821642 }
14831643 out.push_str(&ctx.indent());
14841644 out.push('<');
14851645 out.push_str(tag);
1486− emit_argument_attr(out, elem, ctx.in_picture);
1646+
1647+ // Image src (with optional non-SVG base64 inlining)
1648+ if elem.kind == ElementKind::Image {
1649+ let src = elem.argument.as_deref().unwrap_or("");
1650+ let is_inline = elem.attrs.iter().any(|a| a.key == "inline");
1651+ if is_inline && !src.is_empty() && !src.ends_with(".svg") {
1652+ let mime = if src.ends_with(".png") { "image/png" }
1653+ else if src.ends_with(".jpg") || src.ends_with(".jpeg") { "image/jpeg" }
1654+ else if src.ends_with(".gif") { "image/gif" }
1655+ else if src.ends_with(".webp") { "image/webp" }
1656+ else if src.ends_with(".avif") { "image/avif" }
1657+ else { "application/octet-stream" };
1658+ if let Ok(data) = std::fs::read(src) {
1659+ let b64 = base64_encode(&data);
1660+ out.push_str(" src=\"data:");
1661+ out.push_str(mime);
1662+ out.push_str(";base64,");
1663+ out.push_str(&b64);
1664+ out.push('"');
1665+ } else {
1666+ out.push_str(" src=\"");
1667+ out.push_str(&html_escape(src));
1668+ out.push('"');
1669+ }
1670+ } else {
1671+ out.push_str(" src=\"");
1672+ out.push_str(&html_escape(src));
1673+ out.push('"');
1674+ }
1675+ }
14871676
14881677 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
14891678
@@ -1493,23 +1682,91 @@ fn generate_self_closing(
14931682 out.push('"');
14941683 }
14951684
1496− emit_html_attrs(out, &elem.attrs);
1685+ emit_html_passthrough_attrs(out, &elem.attrs);
14971686
14981687 // Source map attributes in dev mode (self-closing)
14991688 if ctx.dev && elem.line_num > 0 {
1500− out.push_str(&format!(
1501− " data-hl-line=\"{}\" data-hl-el=\"{}\"",
1502− elem.line_num, kind_label
1503− ));
1504− }
1505−
1506− out.push('>');
1507− out.push_str(ctx.nl());
1508−}
1689+ out.push_str(&format!(" data-hl-line=\"{}\" data-hl-el=\"{}\"", elem.line_num, kind_label));
1690+ }
1691+
1692+ // Image optimization: auto-add loading="lazy" and decoding="async"
1693+ if elem.kind == ElementKind::Image {
1694+ // SVG inlining: @image [inline] logo.svg
1695+ if elem.attrs.iter().any(|a| a.key == "inline") {
1696+ if let Some(src) = &elem.argument {
1697+ if src.ends_with(".svg") {
1698+ if let Ok(svg_content) = std::fs::read_to_string(src) {
1699+ // Close the tag we opened, then emit inline SVG instead
1700+ out.truncate(out.rfind('<').unwrap_or(0));
1701+ out.push_str(&ctx.indent());
1702+ out.push_str(svg_content.trim());
1703+ out.push_str(ctx.nl());
1704+ return;
1705+ }
1706+ }
1707+ }
1708+ }
1709+ // Responsive srcset: @image photo.jpg [responsive 400 800 1200]
1710+ let responsive_attr = elem.attrs.iter().find(|a| a.key == "responsive");
1711+ if let Some(resp) = responsive_attr {
1712+ if let Some(ref sizes_str) = resp.value {
1713+ let widths: Vec<&str> = sizes_str.split_whitespace().collect();
1714+ if !widths.is_empty() {
1715+ let src = elem.argument.as_deref().unwrap_or("");
1716+ if !src.is_empty() {
1717+ // Generate srcset with width descriptors
1718+ // Convention: file-{width}.ext (e.g., photo-400.jpg)
1719+ let dot_pos = src.rfind('.').unwrap_or(src.len());
1720+ let base = &src[..dot_pos];
1721+ let ext = &src[dot_pos..];
1722+ let mut srcset_parts = Vec::new();
1723+ for w in &widths {
1724+ srcset_parts.push(format!("{}-{}{} {}w", base, w, ext, w));
1725+ }
1726+ out.push_str(" srcset=\"");
1727+ out.push_str(&srcset_parts.join(", "));
1728+ out.push('"');
1729+ // Generate sizes attribute
1730+ let max_width = widths.last().unwrap_or(&"100vw");
1731+ out.push_str(&format!(" sizes=\"(max-width: {}px) 100vw, {}px\"", max_width, max_width));
1732+ }
1733+ }
1734+ }
1735+ }
15091736
1510−fn generate_text_segments(
1511− segments: &[TextSegment],
1512− out: &mut String,
1737+ // Auto image dimensions: read local image file to inject width/height
1738+ let has_width = elem.attrs.iter().any(|a| a.key == "width");
1739+ let has_height = elem.attrs.iter().any(|a| a.key == "height");
1740+ if !has_width || !has_height {
1741+ if let Some(ref src) = elem.argument {
1742+ if !src.starts_with("http://") && !src.starts_with("https://") && !src.starts_with("data:") {
1743+ if let Some((w, h)) = read_image_dimensions(src) {
1744+ if !has_width {
1745+ out.push_str(&format!(" width=\"{}\"", w));
1746+ }
1747+ if !has_height {
1748+ out.push_str(&format!(" height=\"{}\"", h));
1749+ }
1750+ }
1751+ }
1752+ }
1753+ }
1754+
1755+ if !elem.attrs.iter().any(|a| a.key == "loading") {
1756+ out.push_str(" loading=\"lazy\"");
1757+ }
1758+ if !elem.attrs.iter().any(|a| a.key == "decoding") {
1759+ out.push_str(" decoding=\"async\"");
1760+ }
1761+ }
1762+
1763+ out.push('>');
1764+ out.push_str(ctx.nl());
1765+}
1766+
1767+fn generate_text_segments(
1768+ segments: &[TextSegment],
1769+ out: &mut String,
15131770 styles: &mut StyleCollector,
15141771 ctx: &mut GenContext,
15151772) {
@@ -1518,10 +1775,7 @@ fn generate_text_segments(
15181775 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
15191776 TextSegment::Inline(elem) => {
15201777 let mut buf = String::new();
1521− // An element inside a line of text is in text
1522− let outer_flow = std::mem::take(&mut ctx.flow);
1523− generate_element(elem, Some(Layout::Text), &mut buf, styles, ctx);
1524− ctx.flow = outer_flow;
1778+ generate_element(elem, None, &mut buf, styles, ctx);
15251779 out.push_str(buf.trim_end());
15261780 }
15271781 }
@@ -1534,183 +1788,97 @@ fn generate_text_segments(
15341788
15351789fn compute_class(
15361790 attrs: &[Attribute],
1537− site: &Site,
1791+ kind: &ElementKind,
1792+ parent_kind: Option<&ElementKind>,
15381793 styles: &mut StyleCollector,
1539− distinct: String,
15401794) -> Option<String> {
1541− // Every condition an attribute is under, and none
1542− let mut conditions = vec![Condition::default()];
1543− for attr in attrs.iter().filter(|a| !a.html) {
1544− let (condition, _) = Condition::of(&attr.key);
1545− if !conditions.contains(&condition) {
1546− conditions.push(condition);
1547− }
1548− }
1549− // Dedupe: if a property is declared twice within a single rule, keep only
1550− // the last occurrence.
1551− let rules: Vec<(Condition, String)> = conditions
1552− .into_iter()
1553− .map(|condition| {
1554− let css = dedupe_declarations(&attrs_to_css(attrs, &condition, site));
1555− (condition, css)
1556− })
1557− .collect();
1558− // The kind's defaults, less what the element sets itself (a user
1559− // `[list-style disc]` wins over the default `list-style:none` anyway,
1560− // so there is no need to ship both)
1561− let own = rules
1562− .iter()
1563− .find(|(condition, _)| *condition == Condition::default())
1564− .map_or("", |(_, css)| css.as_str());
1565− let own: Vec<&str> = declarations(own).map(|(name, _)| name).collect();
1566− let defaults: String = declarations(&dedupe_declarations(&default_css(site)))
1567− .filter(|(name, _)| !own.contains(name))
1568− .map(|(_, declaration)| declaration)
1569− .collect();
1570− styles.get_class(defaults, rules, distinct)
1571−}
1795+ let base = attrs_to_css(attrs, "", kind, parent_kind);
15721796
1573−/// The defaults of an element's kind where it is: an overlay's positioning
1574−/// context, its layout, and its kind's own CSS (a heading's `margin:0`).
1575−fn default_css(site: &Site) -> String {
1576− let mut css = String::new();
1577− // Elements with @in-front / @behind children become positioning
1578− // contexts
1579− if site.has_overlay_children {
1580− css.push_str("position:relative;isolation:isolate;");
1797+ // Collect pseudo-state overrides
1798+ let mut pseudo = Vec::new();
1799+ for &(prefix, selector) in PSEUDO_PREFIXES {
1800+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
1801+ if !css.is_empty() {
1802+ pseudo.push((selector.to_string(), css));
1803+ }
15811804 }
1582− if !site.root {
1583− css.push_str(layout_css(site.kind.layout(), site.inline));
1805+
1806+ // Auto-add ::-webkit-scrollbar pseudo for no-scrollbar attribute
1807+ if attrs.iter().any(|a| a.key == "no-scrollbar") {
1808+ pseudo.push(("::-webkit-scrollbar".to_string(), "display:none;".to_string()));
15841809 }
1585− css.push_str(site.kind.css());
1586− css
1587−}
15881810
1589−/// The declarations of a rule body, as (property, `property:value;`), for
1590−/// bodies htmlang wrote: every declaration ends in `;`, and a `;` inside
1591−/// quotes or parentheses doesn't end one.
1592−fn declarations(css: &str) -> impl Iterator<Item = (&str, &str)> {
1593− let mut rest = css;
1594− std::iter::from_fn(move || {
1595− if rest.is_empty() {
1596− return None;
1597− }
1598− let (mut depth, mut quote, mut escaped) = (0i32, None, false);
1599− let mut end = rest.len();
1600− for (i, c) in rest.char_indices() {
1601− match c {
1602− _ if escaped => escaped = false,
1603− '\\' => escaped = true,
1604− c if Some(c) == quote => quote = None,
1605− _ if quote.is_some() => {}
1606− '"' | '\'' => quote = Some(c),
1607− '(' => depth += 1,
1608− ')' => depth -= 1,
1609− ';' if depth == 0 => {
1610− end = i + 1;
1611− break;
1811+ // Collect nth:EXPR: dynamic pseudo selectors
1812+ let mut nth_prefixes: Vec<String> = Vec::new();
1813+ for attr in attrs {
1814+ if attr.key.starts_with("nth:") {
1815+ let rest = &attr.key[4..];
1816+ if let Some(colon_pos) = rest.find(':') {
1817+ let prefix = format!("nth:{}:", &rest[..colon_pos]);
1818+ if !nth_prefixes.contains(&prefix) {
1819+ nth_prefixes.push(prefix);
16121820 }
1613− _ => {}
16141821 }
16151822 }
1616− let (declaration, after) = rest.split_at(end);
1617− rest = after;
1618− let name = declaration.split(':').next().unwrap_or("").trim();
1619− Some((name, declaration))
1620− })
1621−}
1823+ }
1824+ for prefix in &nth_prefixes {
1825+ let expr = &prefix[4..prefix.len() - 1];
1826+ let selector = format!(":nth-child({})", expr);
1827+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
1828+ if !css.is_empty() {
1829+ pseudo.push((selector, css));
1830+ }
1831+ }
16221832
1623−/// Dedupe CSS declarations within a single rule body: for any property
1624−/// declared more than once, keep only the last occurrence. Unparseable
1625−/// segments (no `:`) are preserved as-is. Semicolons inside parentheses or
1626−/// quoted strings are treated as part of a value, not as declaration
1627−/// separators.
1628−fn dedupe_declarations(css: &str) -> String {
1629− if css.is_empty() {
1630− return String::new();
1631− }
1632− // Quick path: no chance of duplicates if there's fewer than 2 declarations.
1633− if css.matches(';').count() < 2 {
1634− return css.to_string();
1635− }
1636−
1637− // Split into (property_name_opt, full_decl_with_semi) preserving whatever
1638− // terminator the input used. We split on `;` at depth 0 (ignoring parens).
1639− let mut decls: Vec<(Option<String>, String)> = Vec::new();
1640− let mut current = String::new();
1641− let mut depth: i32 = 0;
1642− // A quoted string's `;` (`content "a;b"`) is text; a backslash escapes
1643− // the character after it
1644− let mut quote: Option<char> = None;
1645− let mut escaped = false;
1646− for ch in css.chars() {
1647− if escaped {
1648− escaped = false;
1649− current.push(ch);
1650− } else if ch == '\\' {
1651− escaped = true;
1652− current.push(ch);
1653− } else if let Some(q) = quote {
1654− if ch == q {
1655− quote = None;
1656− }
1657− current.push(ch);
1658− } else if ch == '"' || ch == '\'' {
1659− quote = Some(ch);
1660− current.push(ch);
1661− } else if ch == '(' {
1662− depth += 1;
1663− current.push(ch);
1664− } else if ch == ')' {
1665− depth -= 1;
1666− current.push(ch);
1667− } else if ch == ';' && depth == 0 {
1668− current.push(';');
1669− let trimmed = current.trim();
1670− if !trimmed.is_empty() && trimmed != ";" {
1671− let prop = trimmed
1672− .trim_end_matches(';')
1673− .split_once(':')
1674− .map(|(p, _)| p.trim().to_ascii_lowercase());
1675− decls.push((prop, std::mem::take(&mut current)));
1676− } else {
1677− current.clear();
1833+ // Collect has(...): dynamic pseudo selectors
1834+ let mut has_prefixes: Vec<String> = Vec::new();
1835+ for attr in attrs {
1836+ if attr.key.starts_with("has(") {
1837+ if let Some(close) = attr.key.find("):") {
1838+ let prefix = format!("{}:", &attr.key[..close + 1]);
1839+ if !has_prefixes.contains(&prefix) {
1840+ has_prefixes.push(prefix);
1841+ }
16781842 }
1679− } else {
1680− current.push(ch);
16811843 }
16821844 }
1683− if !current.trim().is_empty() {
1684− let prop = current
1685− .split_once(':')
1686− .map(|(p, _)| p.trim().to_ascii_lowercase());
1687− decls.push((prop, std::mem::take(&mut current)));
1688− }
1689−
1690− if decls.len() < 2 {
1691− return css.to_string();
1845+ for prefix in &has_prefixes {
1846+ let inner = &prefix[4..prefix.len() - 2]; // extract selector from has(selector):
1847+ let selector = format!(":has({})", inner);
1848+ let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1849+ if !css.is_empty() {
1850+ pseudo.push((selector, css));
1851+ }
16921852 }
16931853
1694− // Find index of last occurrence of each property.
1695− use std::collections::HashMap;
1696− let mut last: HashMap<String, usize> = HashMap::new();
1697− for (i, (prop, _)) in decls.iter().enumerate() {
1698− if let Some(p) = prop {
1699− last.insert(p.clone(), i);
1854+ // Collect responsive overrides
1855+ let mut responsive = Vec::new();
1856+ for &(bp_name, _) in BREAKPOINTS {
1857+ let prefix = format!("{}:", bp_name);
1858+ let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1859+ if !css.is_empty() {
1860+ responsive.push((bp_name.to_string(), css));
17001861 }
17011862 }
17021863
1703− let mut out = String::with_capacity(css.len());
1704− for (i, (prop, raw)) in decls.iter().enumerate() {
1705− let keep = match prop {
1706− Some(p) => last.get(p) == Some(&i),
1707− None => true,
1708− };
1709− if keep {
1710− out.push_str(raw);
1864+ // Collect container query overrides
1865+ let mut container = Vec::new();
1866+ for &(bp_name, _) in BREAKPOINTS {
1867+ let prefix = format!("cq-{}:", bp_name);
1868+ let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1869+ if !css.is_empty() {
1870+ container.push((bp_name.to_string(), css));
17111871 }
17121872 }
1713− out
1873+
1874+ let dark = attrs_to_css(attrs, "dark:", kind, parent_kind);
1875+ let print = attrs_to_css(attrs, "print:", kind, parent_kind);
1876+ let motion_safe = attrs_to_css(attrs, "motion-safe:", kind, parent_kind);
1877+ let motion_reduce = attrs_to_css(attrs, "motion-reduce:", kind, parent_kind);
1878+ let landscape = attrs_to_css(attrs, "landscape:", kind, parent_kind);
1879+ let portrait = attrs_to_css(attrs, "portrait:", kind, parent_kind);
1880+
1881+ styles.get_class(base, pseudo, responsive, dark, print, motion_safe, motion_reduce, landscape, portrait, container)
17141882}
17151883
17161884fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option<&str>) {
@@ -1740,553 +1908,933 @@ fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option
17401908// Attribute → CSS mapping
17411909// ---------------------------------------------------------------------------
17421910
1743−/// Where an element is written, which its CSS depends on.
1744−struct Site<'a> {
1745− kind: &'a ElementKind,
1746− /// How its parent lays out its children: its `width fill`, `height
1747− /// fill` and `shrink` compile against it.
1748− parent: &'a Flow,
1749− /// It has `@in-front` / `@behind` children.
1750− has_overlay_children: bool,
1751− /// A row, column or grid inside text, laid out inline.
1752− inline: bool,
1753− /// The page's `<body>`, which the reset already makes a column.
1754− root: bool,
1911+/// (htmlang prefix, CSS selector suffix)
1912+const PSEUDO_PREFIXES: &[(&str, &str)] = &[
1913+ ("hover:", ":hover"),
1914+ ("active:", ":active"),
1915+ ("focus:", ":focus"),
1916+ ("focus-visible:", ":focus-visible"),
1917+ ("focus-within:", ":focus-within"),
1918+ ("disabled:", ":disabled"),
1919+ ("checked:", ":checked"),
1920+ ("placeholder:", "::placeholder"),
1921+ ("first:", ":first-child"),
1922+ ("last:", ":last-child"),
1923+ ("odd:", ":nth-child(odd)"),
1924+ ("even:", ":nth-child(even)"),
1925+ ("before:", "::before"),
1926+ ("after:", "::after"),
1927+ ("selection:", "::selection"),
1928+ ("visited:", ":visited"),
1929+ ("empty:", ":empty"),
1930+ ("target:", ":target"),
1931+ ("valid:", ":valid"),
1932+ ("invalid:", ":invalid"),
1933+];
1934+const RESPONSIVE_PREFIXES: &[&str] = &["sm:", "md:", "lg:", "xl:", "2xl:"];
1935+const MEDIA_PREFIXES: &[&str] = &["dark:", "print:", "motion-safe:", "motion-reduce:", "landscape:", "portrait:"];
1936+const CONTAINER_QUERY_PREFIXES: &[&str] = &["cq-sm:", "cq-md:", "cq-lg:", "cq-xl:", "cq-2xl:"];
1937+
1938+fn is_prefixed_attr(key: &str) -> bool {
1939+ PSEUDO_PREFIXES.iter().any(|&(p, _)| key.starts_with(p))
1940+ || RESPONSIVE_PREFIXES.iter().any(|p| key.starts_with(p))
1941+ || MEDIA_PREFIXES.iter().any(|p| key.starts_with(p))
1942+ || CONTAINER_QUERY_PREFIXES.iter().any(|p| key.starts_with(p))
1943+ || key.starts_with("nth:")
1944+ || key.starts_with("has(")
17551945}
17561946
1757−impl Site<'_> {
1758− /// Where an element in a parent with the layout `layout` and the flow
1759− /// `parent` is.
1760− fn new<'a>(elem: &'a Element, layout: Option<Layout>, parent: &'a Flow) -> Site<'a> {
1761− Site {
1762− kind: &elem.kind,
1763− parent,
1764− has_overlay_children: has_overlay_children(elem),
1765− inline: layout == Some(Layout::Text) && elem.kind.layout().is_container(),
1766− root: false,
1947+fn attrs_to_css(
1948+ attrs: &[Attribute],
1949+ state_prefix: &str,
1950+ kind: &ElementKind,
1951+ parent_kind: Option<&ElementKind>,
1952+) -> String {
1953+ let mut css = String::new();
1954+
1955+ // Base element styles only for the default (non-state) pass
1956+ if state_prefix.is_empty() {
1957+ match kind {
1958+ ElementKind::Row => css.push_str("display:flex;flex-direction:row;"),
1959+ ElementKind::Column => css.push_str("display:flex;flex-direction:column;"),
1960+ ElementKind::El => css.push_str("display:flex;flex-direction:column;"),
1961+ ElementKind::Paragraph => css.push_str("margin:0;"),
1962+ // Semantic elements get flex column layout like @el
1963+ ElementKind::Nav | ElementKind::Header | ElementKind::Footer
1964+ | ElementKind::Main | ElementKind::Section | ElementKind::Article
1965+ | ElementKind::Aside => css.push_str("display:flex;flex-direction:column;"),
1966+ // Lists: reset browser defaults
1967+ ElementKind::List => css.push_str("margin:0;padding-left:0;list-style:none;"),
1968+ ElementKind::ListItem => css.push_str("display:flex;flex-direction:column;"),
1969+ // Form: flex column like @el
1970+ ElementKind::Form => css.push_str("display:flex;flex-direction:column;"),
1971+ // Details: flex column
1972+ ElementKind::Details => css.push_str("display:flex;flex-direction:column;"),
1973+ // Figure: flex column
1974+ ElementKind::Figure => css.push_str("display:flex;flex-direction:column;margin:0;"),
1975+ // Blockquote: flex column, reset browser margin
1976+ ElementKind::Blockquote => css.push_str("display:flex;flex-direction:column;margin:0;"),
1977+ // Pre: preserve whitespace
1978+ ElementKind::Pre => css.push_str("margin:0;white-space:pre;font-family:ui-monospace,monospace;"),
1979+ // Code: monospace font
1980+ ElementKind::Code => css.push_str("font-family:ui-monospace,monospace;"),
1981+ // New elements
1982+ ElementKind::Dialog => css.push_str("display:flex;flex-direction:column;"),
1983+ ElementKind::DefinitionList => css.push_str("margin:0;"),
1984+ ElementKind::DefinitionDescription => css.push_str("margin:0;display:flex;flex-direction:column;"),
1985+ ElementKind::Fieldset => css.push_str("display:flex;flex-direction:column;border:1px solid currentColor;padding:0.5em;margin:0;"),
1986+ ElementKind::Kbd => css.push_str("font-family:ui-monospace,monospace;"),
1987+ ElementKind::Grid => css.push_str("display:grid;"),
1988+ ElementKind::Stack => css.push_str("position:relative;"),
1989+ ElementKind::Badge => css.push_str("display:inline-flex;align-items:center;justify-content:center;padding:2px 8px;border-radius:9999px;font-size:0.75rem;font-weight:600;line-height:1;"),
1990+ ElementKind::Tooltip => css.push_str("position:relative;cursor:help;"),
1991+ ElementKind::Spacer => css.push_str("flex:1;"),
1992+ ElementKind::Avatar => css.push_str("display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;overflow:hidden;flex-shrink:0;"),
1993+ ElementKind::Carousel => css.push_str("display:flex;flex-direction:row;overflow-x:auto;scroll-snap-type:x mandatory;-webkit-overflow-scrolling:touch;scrollbar-width:none;"),
1994+ ElementKind::Chip => css.push_str("display:inline-flex;align-items:center;gap:4px;padding:4px 12px;border-radius:9999px;font-size:0.875rem;border:1px solid currentColor;"),
1995+ ElementKind::Tag => css.push_str("display:inline-flex;align-items:center;padding:2px 8px;border-radius:4px;font-size:0.75rem;font-weight:600;"),
1996+ _ => {}
1997+ }
1998+ // Children of @carousel get scroll-snap-align and flex-shrink
1999+ if matches!(parent_kind, Some(ElementKind::Carousel)) {
2000+ css.push_str("scroll-snap-align:start;flex-shrink:0;");
17672001 }
17682002 }
1769−}
17702003
1771−// ---------------------------------------------------------------------------
1772−// Direction: what a child's `fill` and `shrink` compile against
1773−// ---------------------------------------------------------------------------
2004+ for attr in attrs {
2005+ // Determine the effective key for this pass
2006+ let effective_key = if state_prefix.is_empty() {
2007+ if is_prefixed_attr(&attr.key) {
2008+ continue;
2009+ }
2010+ attr.key.as_str()
2011+ } else {
2012+ match attr.key.strip_prefix(state_prefix) {
2013+ Some(k) => k,
2014+ None => continue,
2015+ }
2016+ };
17742017
1775−/// The way a flex row or column lays out its children.
1776−#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1777−enum Axis {
1778− Row,
1779− Column,
1780−}
2018+ let val = attr.value.as_deref();
17812019
1782−impl Axis {
1783− /// The direction a `flex-direction` or `flex-flow` value sets, if it
1784− /// names one (not `var(--dir)`, which only the browser knows).
1785− fn of_value(value: &str) -> Option<Axis> {
1786− value.split_whitespace().find_map(|word| match word {
1787− "row" | "row-reverse" => Some(Axis::Row),
1788− "column" | "column-reverse" => Some(Axis::Column),
1789− _ => None,
1790− })
1791− }
1792−}
2020+ match effective_key {
2021+ // Layout
2022+ "spacing" | "gap" => {
2023+ if let Some(v) = val {
2024+ push_css(&mut css, "gap", &css_px(v));
2025+ }
2026+ }
2027+ "padding" => {
2028+ if let Some(v) = val {
2029+ push_css(&mut css, "padding", &css_px_multi(v));
2030+ }
2031+ }
2032+ "padding-x" => {
2033+ if let Some(v) = val {
2034+ push_css(&mut css, "padding-left", &css_px(v));
2035+ push_css(&mut css, "padding-right", &css_px(v));
2036+ }
2037+ }
2038+ "padding-y" => {
2039+ if let Some(v) = val {
2040+ push_css(&mut css, "padding-top", &css_px(v));
2041+ push_css(&mut css, "padding-bottom", &css_px(v));
2042+ }
2043+ }
17932044
1794−/// How an element lays out its children, as its CSS sets it: the
1795−/// direction its children's `width`/`height` `fill` and `shrink` compile
1796−/// against. That is the direction of `@row` or of a column, or the one its
1797−/// own `flex-direction` (or `flex-flow`) sets, with or without media or
1798−/// container prefixes. Like elm-ui's `.r > .wf`, the rules for a direction
1799−/// set under a prefix are keyed on the element's class: `@media (...) {
1800−/// :where(.a)>.b {...} }`.
1801−#[derive(Clone, Default)]
1802−struct Flow {
1803− /// Without a prefix; `None` when the element isn't a flex row or column
1804− /// (a grid, text, HTML's own layout, the top of the page)
1805− base: Option<Axis>,
1806− /// The direction under each chain of at-rule prefixes that sets one, in
1807− /// the order their blocks are written
1808− changes: Vec<(Vec<usize>, Axis)>,
1809− /// The element's generated class, which the rules for the changes are
1810− /// keyed on
1811− class: Option<String>,
1812−}
2045+ // Sizing
2046+ "width" => {
2047+ if let Some(v) = val {
2048+ match v {
2049+ "fill" => match parent_kind {
2050+ Some(ElementKind::Row) => {
2051+ push_css(&mut css, "flex", "1");
2052+ push_css(&mut css, "min-width", "0");
2053+ }
2054+ _ => push_css(&mut css, "width", "100%"),
2055+ },
2056+ "shrink" => push_css(&mut css, "flex-shrink", "0"),
2057+ _ => push_css(&mut css, "width", &css_px(v)),
2058+ }
2059+ }
2060+ }
2061+ "height" => {
2062+ if let Some(v) = val {
2063+ match v {
2064+ "fill" => match parent_kind {
2065+ Some(ElementKind::Column) => {
2066+ push_css(&mut css, "flex", "1");
2067+ push_css(&mut css, "min-height", "0");
2068+ }
2069+ _ => push_css(&mut css, "height", "100%"),
2070+ },
2071+ "shrink" => push_css(&mut css, "flex-shrink", "0"),
2072+ _ => push_css(&mut css, "height", &css_px(v)),
2073+ }
2074+ }
2075+ }
2076+ "min-width" => {
2077+ if let Some(v) = val {
2078+ push_css(&mut css, "min-width", &css_px(v));
2079+ }
2080+ }
2081+ "max-width" => {
2082+ if let Some(v) = val {
2083+ push_css(&mut css, "max-width", &css_px(v));
2084+ }
2085+ }
2086+ "min-height" => {
2087+ if let Some(v) = val {
2088+ push_css(&mut css, "min-height", &css_px(v));
2089+ }
2090+ }
2091+ "max-height" => {
2092+ if let Some(v) = val {
2093+ push_css(&mut css, "max-height", &css_px(v));
2094+ }
2095+ }
18132096
1814−impl Flow {
1815− fn of(elem: &Element) -> Flow {
1816− let mut base = match elem.kind.layout() {
1817− Layout::Row => Axis::Row,
1818− Layout::Column => Axis::Column,
1819− _ => return Flow::default(),
1820− };
1821− let mut changes: Vec<(Vec<usize>, Axis)> = Vec::new();
1822− for attr in elem.attrs.iter().filter(|a| !a.html) {
1823− let (condition, name) = Condition::of(&attr.key);
1824− if !matches!(name, "flex-direction" | "flex-flow") || !condition.selector.is_empty() {
1825− continue;
2097+ // Alignment
2098+ "center-x" => match parent_kind {
2099+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2100+ push_css(&mut css, "align-self", "center");
2101+ }
2102+ _ => {
2103+ push_css(&mut css, "margin-left", "auto");
2104+ push_css(&mut css, "margin-right", "auto");
2105+ }
2106+ },
2107+ "center-y" => match parent_kind {
2108+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "center"),
2109+ _ => {
2110+ push_css(&mut css, "margin-top", "auto");
2111+ push_css(&mut css, "margin-bottom", "auto");
2112+ }
2113+ },
2114+ "align-left" => match parent_kind {
2115+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2116+ push_css(&mut css, "align-self", "flex-start");
2117+ }
2118+ _ => push_css(&mut css, "margin-right", "auto"),
2119+ },
2120+ "align-right" => match parent_kind {
2121+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2122+ push_css(&mut css, "align-self", "flex-end");
2123+ }
2124+ _ => push_css(&mut css, "margin-left", "auto"),
2125+ },
2126+ "align-top" => match parent_kind {
2127+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-start"),
2128+ _ => push_css(&mut css, "margin-bottom", "auto"),
2129+ },
2130+ "align-bottom" => match parent_kind {
2131+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-end"),
2132+ _ => push_css(&mut css, "margin-top", "auto"),
2133+ },
2134+
2135+ // Style
2136+ "background" => {
2137+ if let Some(v) = val {
2138+ push_css(&mut css, "background", v);
2139+ }
18262140 }
1827− let Some(axis) = attr.value.as_deref().and_then(Axis::of_value) else {
1828− continue;
1829− };
1830− if condition.at.is_empty() {
1831− base = axis;
1832− } else {
1833− // The later one wins, as in the CSS
1834− changes.retain(|(at, _)| *at != condition.at);
1835− changes.push((condition.at, axis));
2141+ "color" => {
2142+ if let Some(v) = val {
2143+ push_css(&mut css, "color", v);
2144+ }
2145+ }
2146+ "border" => {
2147+ if let Some(v) = val {
2148+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2149+ if parts.len() == 2 {
2150+ push_css(
2151+ &mut css,
2152+ "border",
2153+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2154+ );
2155+ } else {
2156+ push_css(
2157+ &mut css,
2158+ "border",
2159+ &format!("{} solid currentColor", css_px(parts[0])),
2160+ );
2161+ }
2162+ }
2163+ }
2164+ "border-top" | "border-bottom" | "border-left" | "border-right" => {
2165+ if let Some(v) = val {
2166+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2167+ if parts.len() == 2 {
2168+ push_css(
2169+ &mut css,
2170+ effective_key,
2171+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2172+ );
2173+ } else {
2174+ push_css(
2175+ &mut css,
2176+ effective_key,
2177+ &format!("{} solid currentColor", css_px(parts[0])),
2178+ );
2179+ }
2180+ }
2181+ }
2182+ "rounded" => {
2183+ if let Some(v) = val {
2184+ push_css(&mut css, "border-radius", &css_px(v));
2185+ }
2186+ }
2187+ "bold" => push_css(&mut css, "font-weight", "bold"),
2188+ "italic" => push_css(&mut css, "font-style", "italic"),
2189+ "underline" => push_css(&mut css, "text-decoration", "underline"),
2190+ "size" => {
2191+ if let Some(v) = val {
2192+ push_css(&mut css, "font-size", &css_px(v));
2193+ }
2194+ }
2195+ "font" => {
2196+ if let Some(v) = val {
2197+ push_css(&mut css, "font-family", v);
2198+ }
2199+ }
2200+ "transition" => {
2201+ if let Some(v) = val {
2202+ push_css(&mut css, "transition", v);
2203+ }
2204+ }
2205+ "cursor" => {
2206+ if let Some(v) = val {
2207+ push_css(&mut css, "cursor", v);
2208+ }
2209+ }
2210+ "opacity" => {
2211+ if let Some(v) = val {
2212+ push_css(&mut css, "opacity", v);
2213+ }
18362214 }
1837− }
1838− changes.sort_by_key(|(at, _)| at_order(at));
1839− Flow {
1840− base: Some(base),
1841− changes,
1842− class: None,
1843− }
1844− }
18452215
1846− /// The direction under the at-rules `at`: the latest one set among
1847− /// the conditions that hold there (`md:` holds at `lg:`), else the one
1848− /// without a prefix.
1849− fn at(&self, at: &[usize]) -> Option<Axis> {
1850− let base = self.base?;
1851− let here = Condition::at_only(at);
1852− let changed = self
1853− .changes
1854− .iter()
1855− .rev()
1856− .find(|(chain, _)| Condition::at_only(chain).holds_at(&here))
1857− .map(|&(_, axis)| axis);
1858− Some(changed.unwrap_or(base))
1859− }
1860−}
2216+ // Typography
2217+ "text-align" => {
2218+ if let Some(v) = val {
2219+ push_css(&mut css, "text-align", v);
2220+ }
2221+ }
2222+ "line-height" => {
2223+ if let Some(v) = val {
2224+ push_css(&mut css, "line-height", v);
2225+ }
2226+ }
2227+ "letter-spacing" => {
2228+ if let Some(v) = val {
2229+ push_css(&mut css, "letter-spacing", &css_px(v));
2230+ }
2231+ }
2232+ "text-transform" => {
2233+ if let Some(v) = val {
2234+ push_css(&mut css, "text-transform", v);
2235+ }
2236+ }
2237+ "white-space" => {
2238+ if let Some(v) = val {
2239+ push_css(&mut css, "white-space", v);
2240+ }
2241+ }
18612242
1862−/// `width` or `height`.
1863−#[derive(Clone, Copy, PartialEq, Eq)]
1864−enum Dim {
1865− Width,
1866− Height,
1867−}
2243+ // Overflow & positioning
2244+ "overflow" => {
2245+ if let Some(v) = val {
2246+ push_css(&mut css, "overflow", v);
2247+ }
2248+ }
2249+ "position" => {
2250+ if let Some(v) = val {
2251+ push_css(&mut css, "position", v);
2252+ }
2253+ }
2254+ "top" => {
2255+ if let Some(v) = val {
2256+ push_css(&mut css, "top", &css_px(v));
2257+ }
2258+ }
2259+ "right" => {
2260+ if let Some(v) = val {
2261+ push_css(&mut css, "right", &css_px(v));
2262+ }
2263+ }
2264+ "bottom" => {
2265+ if let Some(v) = val {
2266+ push_css(&mut css, "bottom", &css_px(v));
2267+ }
2268+ }
2269+ "left" => {
2270+ if let Some(v) = val {
2271+ push_css(&mut css, "left", &css_px(v));
2272+ }
2273+ }
2274+ "z-index" => {
2275+ if let Some(v) = val {
2276+ push_css(&mut css, "z-index", v);
2277+ }
2278+ }
18682279
1869−/// What a `width` or `height` says.
1870−#[derive(Clone, Copy, PartialEq, Eq)]
1871−enum Size {
1872− Fill,
1873− Shrink,
1874− /// A size of its own (`width 300`)
1875− Set,
1876−}
2280+ // Display & visibility
2281+ "display" => {
2282+ if let Some(v) = val {
2283+ push_css(&mut css, "display", v);
2284+ }
2285+ }
2286+ "visibility" => {
2287+ if let Some(v) = val {
2288+ push_css(&mut css, "visibility", v);
2289+ }
2290+ }
2291+ "hidden" => push_css(&mut css, "display", "none"),
18772292
1878−impl Size {
1879− fn of(value: &str) -> Size {
1880− match value.trim() {
1881− "fill" => Size::Fill,
1882− "shrink" => Size::Shrink,
1883− _ => Size::Set,
1884− }
1885− }
1886−}
2293+ // Transform & filters
2294+ "transform" => {
2295+ if let Some(v) = val {
2296+ push_css(&mut css, "transform", v);
2297+ }
2298+ }
2299+ "backdrop-filter" => {
2300+ if let Some(v) = val {
2301+ push_css(&mut css, "backdrop-filter", v);
2302+ }
2303+ }
18872304
1888−/// The declarations `fill` and `shrink` make in a parent laid out along
1889−/// `axis` (`None`: not a flex row or column). Along the parent's direction,
1890−/// `fill` takes the remaining space and `shrink` keeps the content's size;
1891−/// across it (or outside flex), `fill` is the full size and `shrink` fits
1892−/// the content.
1893−fn sizing(dim: Dim, size: Size, axis: Option<Axis>) -> &'static [(&'static str, &'static str)] {
1894− match (dim, size, axis) {
1895− (_, Size::Set, _) => &[],
1896− (Dim::Width, Size::Fill, Some(Axis::Row)) => &[("flex", "1"), ("min-width", "0")],
1897− (Dim::Width, Size::Fill, _) => &[("width", "100%")],
1898− (Dim::Width, Size::Shrink, Some(Axis::Row)) => &[("flex-shrink", "0")],
1899− (Dim::Width, Size::Shrink, _) => &[("width", "fit-content")],
1900− (Dim::Height, Size::Fill, Some(Axis::Column)) => &[("flex", "1"), ("min-height", "0")],
1901− (Dim::Height, Size::Fill, _) => &[("height", "100%")],
1902− (Dim::Height, Size::Shrink, Some(Axis::Column)) => &[("flex-shrink", "0")],
1903− (Dim::Height, Size::Shrink, _) => &[("height", "fit-content")],
1904− }
1905−}
2305+ // Effects
2306+ "shadow" => {
2307+ if let Some(v) = val {
2308+ push_css(&mut css, "box-shadow", v);
2309+ }
2310+ }
19062311
1907−/// Every property `fill` and `shrink` of `dim` can set, with its initial
1908−/// value (`flex` covers `flex-shrink`).
1909−fn sizing_properties(dim: Dim) -> [(&'static str, &'static str); 3] {
1910− match dim {
1911− Dim::Width => [
1912− ("flex", "0 1 auto"),
1913− ("min-width", "auto"),
1914− ("width", "auto"),
1915− ],
1916− Dim::Height => [
1917− ("flex", "0 1 auto"),
1918− ("min-height", "auto"),
1919− ("height", "auto"),
1920− ],
1921− }
1922−}
2312+ // Flow
2313+ "wrap" => push_css(&mut css, "flex-wrap", "wrap"),
2314+ "gap-x" => {
2315+ if let Some(v) = val {
2316+ push_css(&mut css, "column-gap", &css_px(v));
2317+ }
2318+ }
2319+ "gap-y" => {
2320+ if let Some(v) = val {
2321+ push_css(&mut css, "row-gap", &css_px(v));
2322+ }
2323+ }
2324+
2325+ // Grid
2326+ "grid" => {
2327+ push_css(&mut css, "display", "grid");
2328+ }
2329+ "grid-cols" => {
2330+ if let Some(v) = val {
2331+ if let Ok(n) = v.parse::<u32>() {
2332+ push_css(&mut css, "grid-template-columns", &format!("repeat({},1fr)", n));
2333+ } else {
2334+ push_css(&mut css, "grid-template-columns", v);
2335+ }
2336+ }
2337+ }
2338+ "grid-rows" => {
2339+ if let Some(v) = val {
2340+ if let Ok(n) = v.parse::<u32>() {
2341+ push_css(&mut css, "grid-template-rows", &format!("repeat({},1fr)", n));
2342+ } else {
2343+ push_css(&mut css, "grid-template-rows", v);
2344+ }
2345+ }
2346+ }
2347+ "col-span" => {
2348+ if let Some(v) = val {
2349+ push_css(&mut css, "grid-column", &format!("span {}", v));
2350+ }
2351+ }
2352+ "row-span" => {
2353+ if let Some(v) = val {
2354+ push_css(&mut css, "grid-row", &format!("span {}", v));
2355+ }
2356+ }
2357+
2358+ // Animation
2359+ "animation" => {
2360+ if let Some(v) = val {
2361+ push_css(&mut css, "animation", v);
2362+ }
2363+ }
2364+
2365+ // Aspect ratio
2366+ "aspect-ratio" => {
2367+ if let Some(v) = val {
2368+ push_css(&mut css, "aspect-ratio", v);
2369+ }
2370+ }
2371+
2372+ // Outline (like border but doesn't affect layout)
2373+ "outline" => {
2374+ if let Some(v) = val {
2375+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2376+ if parts.len() == 2 {
2377+ push_css(
2378+ &mut css,
2379+ "outline",
2380+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2381+ );
2382+ } else {
2383+ push_css(
2384+ &mut css,
2385+ "outline",
2386+ &format!("{} solid currentColor", css_px(parts[0])),
2387+ );
2388+ }
2389+ }
2390+ }
2391+
2392+ // Logical properties (i18n-aware)
2393+ "padding-inline" => {
2394+ if let Some(v) = val {
2395+ push_css(&mut css, "padding-inline", &css_px_multi(v));
2396+ }
2397+ }
2398+ "padding-block" => {
2399+ if let Some(v) = val {
2400+ push_css(&mut css, "padding-block", &css_px_multi(v));
2401+ }
2402+ }
2403+ "margin-inline" => {
2404+ if let Some(v) = val {
2405+ push_css(&mut css, "margin-inline", &css_px_multi(v));
2406+ }
2407+ }
2408+ "margin-block" => {
2409+ if let Some(v) = val {
2410+ push_css(&mut css, "margin-block", &css_px_multi(v));
2411+ }
2412+ }
2413+
2414+ // Logical property start/end variants
2415+ "padding-inline-start" | "padding-inline-end" |
2416+ "padding-block-start" | "padding-block-end" |
2417+ "margin-inline-start" | "margin-inline-end" |
2418+ "margin-block-start" | "margin-block-end" => {
2419+ if let Some(v) = val {
2420+ push_css(&mut css, effective_key, &css_px(v));
2421+ }
2422+ }
2423+
2424+ // Logical inset
2425+ "inset-inline" | "inset-block" => {
2426+ if let Some(v) = val {
2427+ push_css(&mut css, effective_key, &css_px_multi(v));
2428+ }
2429+ }
2430+ "inset-inline-start" | "inset-inline-end" |
2431+ "inset-block-start" | "inset-block-end" => {
2432+ if let Some(v) = val {
2433+ push_css(&mut css, effective_key, &css_px(v));
2434+ }
2435+ }
2436+
2437+ // Logical border
2438+ "border-inline" | "border-block" |
2439+ "border-inline-start" | "border-inline-end" |
2440+ "border-block-start" | "border-block-end" => {
2441+ if let Some(v) = val {
2442+ push_css(&mut css, effective_key, v);
2443+ }
2444+ }
2445+
2446+ // Logical border-radius
2447+ "border-start-start-radius" | "border-start-end-radius" |
2448+ "border-end-start-radius" | "border-end-end-radius" => {
2449+ if let Some(v) = val {
2450+ push_css(&mut css, effective_key, &css_px(v));
2451+ }
2452+ }
2453+
2454+ // Logical scroll margins & padding
2455+ "scroll-margin-inline" | "scroll-margin-block" |
2456+ "scroll-padding-inline" | "scroll-padding-block" => {
2457+ if let Some(v) = val {
2458+ push_css(&mut css, effective_key, &css_px_multi(v));
2459+ }
2460+ }
2461+
2462+ // Logical sizing
2463+ "inline-size" | "block-size" |
2464+ "min-inline-size" | "max-inline-size" |
2465+ "min-block-size" | "max-block-size" => {
2466+ if let Some(v) = val {
2467+ push_css(&mut css, effective_key, &css_px(v));
2468+ }
2469+ }
2470+
2471+ // Scroll snap
2472+ "scroll-snap-type" => {
2473+ if let Some(v) = val {
2474+ push_css(&mut css, "scroll-snap-type", v);
2475+ }
2476+ }
2477+ "scroll-snap-align" => {
2478+ if let Some(v) = val {
2479+ push_css(&mut css, "scroll-snap-align", v);
2480+ }
2481+ }
2482+
2483+ // Margin
2484+ "margin" => {
2485+ if let Some(v) = val {
2486+ push_css(&mut css, "margin", &css_px_multi(v));
2487+ }
2488+ }
2489+ "margin-x" => {
2490+ if let Some(v) = val {
2491+ push_css(&mut css, "margin-left", &css_px(v));
2492+ push_css(&mut css, "margin-right", &css_px(v));
2493+ }
2494+ }
2495+ "margin-y" => {
2496+ if let Some(v) = val {
2497+ push_css(&mut css, "margin-top", &css_px(v));
2498+ push_css(&mut css, "margin-bottom", &css_px(v));
2499+ }
2500+ }
2501+
2502+ // Filter
2503+ "filter" => {
2504+ if let Some(v) = val {
2505+ push_css(&mut css, "filter", v);
2506+ }
2507+ }
2508+
2509+ // Object fit/position (for images)
2510+ "object-fit" => {
2511+ if let Some(v) = val {
2512+ push_css(&mut css, "object-fit", v);
2513+ }
2514+ }
2515+ "object-position" => {
2516+ if let Some(v) = val {
2517+ push_css(&mut css, "object-position", v);
2518+ }
2519+ }
2520+
2521+ // Text shadow
2522+ "text-shadow" => {
2523+ if let Some(v) = val {
2524+ push_css(&mut css, "text-shadow", v);
2525+ }
2526+ }
2527+
2528+ // Text overflow
2529+ "text-overflow" => {
2530+ if let Some(v) = val {
2531+ push_css(&mut css, "text-overflow", v);
2532+ }
2533+ }
2534+
2535+ // Interaction
2536+ "pointer-events" => {
2537+ if let Some(v) = val {
2538+ push_css(&mut css, "pointer-events", v);
2539+ }
2540+ }
2541+ "user-select" => {
2542+ if let Some(v) = val {
2543+ push_css(&mut css, "user-select", v);
2544+ }
2545+ }
2546+
2547+ // Flexbox/grid alignment
2548+ "justify-content" => {
2549+ if let Some(v) = val {
2550+ push_css(&mut css, "justify-content", v);
2551+ }
2552+ }
2553+ "align-items" => {
2554+ if let Some(v) = val {
2555+ push_css(&mut css, "align-items", v);
2556+ }
2557+ }
19232558
1924−/// What an element's attributes under some prefixes say about its size.
1925−#[derive(Default)]
1926−struct Sizes {
1927− /// The last `width` and `height`
1928− width: Option<Size>,
1929− height: Option<Size>,
1930− /// A `fill` or `shrink` for the width / height is among them (a later
1931− /// size may replace it)
1932− width_word: bool,
1933− height_word: bool,
1934− /// It writes `flex`, one of its longhands (`flex-grow`, `flex-shrink`,
1935− /// `flex-basis`), `min-width` or `min-height` itself
1936− flex: bool,
1937− flex_grow: bool,
1938− flex_shrink: bool,
1939− flex_basis: bool,
1940− min_width: bool,
1941− min_height: bool,
1942−}
2559+ // Flex item order
2560+ "order" => {
2561+ if let Some(v) = val {
2562+ push_css(&mut css, "order", v);
2563+ }
2564+ }
19432565
1944−impl Sizes {
1945− /// Read the attributes under the conditions that hold wherever `at`
1946− /// does, a later condition over an earlier one.
1947− fn of(attrs: &[Attribute], at: &Condition) -> Sizes {
1948− let mut sizes = Sizes::default();
1949− let mut read: Vec<(Condition, &str, &str)> = Vec::new();
1950− for attr in attrs.iter().filter(|a| !a.html) {
1951− let (condition, name) = Condition::of(&attr.key);
1952− let Some(value) = attr.value.as_deref().filter(|v| !v.trim().is_empty()) else {
1953− continue;
1954− };
1955− if condition.holds_at(at) {
1956− read.push((condition, name, value));
1957− }
1958− }
1959− read.sort_by_cached_key(|(condition, _, _)| condition.order());
1960− for (_, name, value) in read {
1961− match name {
1962− "width" => {
1963− let size = Size::of(value);
1964− sizes.width = Some(size);
1965− sizes.width_word |= size != Size::Set;
1966− }
1967− "height" => {
1968− let size = Size::of(value);
1969− sizes.height = Some(size);
1970− sizes.height_word |= size != Size::Set;
1971− }
1972− "flex" => sizes.flex = true,
1973− "flex-grow" => sizes.flex_grow = true,
1974− "flex-shrink" => sizes.flex_shrink = true,
1975− "flex-basis" => sizes.flex_basis = true,
1976− "min-width" => sizes.min_width = true,
1977− "min-height" => sizes.min_height = true,
1978− _ => {}
2566+ // Background extras
2567+ "background-size" => {
2568+ if let Some(v) = val {
2569+ push_css(&mut css, "background-size", v);
2570+ }
19792571 }
1980− }
1981− sizes
1982− }
1983−
1984− /// The element writes `property` itself: a layout word leaves it alone.
1985− fn writes(&self, property: &str) -> bool {
1986− match property {
1987− "flex" => self.flex,
1988− "flex-grow" => self.flex || self.flex_grow,
1989− "flex-shrink" => self.flex || self.flex_shrink,
1990− "flex-basis" => self.flex || self.flex_basis,
1991− "min-width" => self.min_width,
1992− "min-height" => self.min_height,
1993− "width" => self.width == Some(Size::Set),
1994− "height" => self.height == Some(Size::Set),
1995− _ => false,
1996− }
1997− }
1998−
1999− /// Write a layout word's `property: value`, unless the element writes
2000− /// the property itself. When it writes some of `flex`'s longhands, a
2001− /// `flex` is written as the others (`flex-shrink 0, width fill` still
2002− /// grows).
2003− fn push(&self, css: &mut String, property: &str, value: &str) {
2004− if property == "flex" && !self.flex {
2005− let longhands = match value {
2006− "1" => [
2007− ("flex-grow", "1"),
2008− ("flex-shrink", "1"),
2009− ("flex-basis", "0%"),
2010− ],
2011− // The reset, `0 1 auto`
2012− _ => [
2013− ("flex-grow", "0"),
2014− ("flex-shrink", "1"),
2015− ("flex-basis", "auto"),
2016− ],
2017− };
2018− if longhands.iter().any(|&(p, _)| self.writes(p)) {
2019− for (longhand, value) in longhands {
2020− if !self.writes(longhand) {
2021− push_css(css, longhand, value);
2022− }
2572+ "background-position" => {
2573+ if let Some(v) = val {
2574+ push_css(&mut css, "background-position", v);
2575+ }
2576+ }
2577+ "background-repeat" => {
2578+ if let Some(v) = val {
2579+ push_css(&mut css, "background-repeat", v);
20232580 }
2024− return;
20252581 }
2026− }
2027− if !self.writes(property) {
2028− push_css(css, property, value);
2029− }
2030− }
2031−}
20322582
2033−/// The rule that gives an element's `fill` and `shrink`, as its attributes
2034−/// under the at-rules `at` set them, their meaning in a parent laid out
2035−/// along `axis`. Every other property a layout word could have set is put
2036−/// back to its initial value, so the rule is right whichever earlier rule
2037−/// it overrides. Properties the element writes itself are left alone.
2038−fn sizing_rule(attrs: &[Attribute], at: &[usize], axis: Axis) -> String {
2039− let sizes = Sizes::of(attrs, &Condition::at_only(at));
2040− let mut sets: Vec<(&str, &str)> = Vec::new();
2041− let mut resets: Vec<(&str, &str)> = Vec::new();
2042− for (dim, size, word) in [
2043− (Dim::Width, sizes.width, sizes.width_word),
2044− (Dim::Height, sizes.height, sizes.height_word),
2045− ] {
2046− if !word {
2047− continue;
2048− }
2049− if let Some(size) = size {
2050− sets.extend_from_slice(sizing(dim, size, Some(axis)));
2051− }
2052− resets.extend_from_slice(&sizing_properties(dim));
2053− }
2054− let mut css = String::new();
2055− let mut written: Vec<&str> = Vec::new();
2056− for &(property, value) in &resets {
2057− if sets.iter().any(|&(p, _)| p == property) || written.contains(&property) {
2058− continue;
2059− }
2060− written.push(property);
2061− sizes.push(&mut css, property, value);
2062− }
2063− for &(property, value) in &sets {
2064− sizes.push(&mut css, property, value);
2065− }
2066− css
2067−}
2583+ // Text wrapping
2584+ "word-break" => {
2585+ if let Some(v) = val {
2586+ push_css(&mut css, "word-break", v);
2587+ }
2588+ }
2589+ "overflow-wrap" => {
2590+ if let Some(v) = val {
2591+ push_css(&mut css, "overflow-wrap", v);
2592+ }
2593+ }
20682594
2069−/// The rules an element's `fill` and `shrink` need under each chain of
2070−/// at-rules where the direction of `flow` (its parent's) changes: `(at,
2071−/// body)`.
2072−fn sizing_changes(attrs: &[Attribute], flow: &Flow) -> Vec<(Vec<usize>, String)> {
2073− flow.changes
2074− .iter()
2075− .map(|(at, axis)| (at.clone(), sizing_rule(attrs, at, *axis)))
2076− .filter(|(_, body)| !body.is_empty())
2077− .collect()
2078−}
2595+ // Container queries
2596+ "container" => {
2597+ push_css(&mut css, "container-type", "inline-size");
2598+ }
2599+ "container-name" => {
2600+ if let Some(v) = val {
2601+ push_css(&mut css, "container-name", v);
2602+ }
2603+ }
2604+ "container-type" => {
2605+ if let Some(v) = val {
2606+ push_css(&mut css, "container-type", v);
2607+ }
2608+ }
20792609
2080−/// An element's generated class, with the rules keyed on its parent's
2081−/// class that its `fill` and `shrink` need where the parent's direction
2082−/// changes under a prefix (see [`Flow`]): `:where(.a)>.b`, one class of
2083−/// specificity like any class rule.
2084−fn element_class(elem: &Element, site: &Site, styles: &mut StyleCollector) -> Option<String> {
2085− let as_child = match site.parent.class {
2086− Some(_) => sizing_changes(&elem.attrs, site.parent),
2087− None => Vec::new(),
2088− };
2089− // Two elements with the same CSS but different rules keyed on them
2090− // need two classes
2091− let mut distinct = String::new();
2092− for (at, body) in &as_child {
2093− distinct.push_str(&format!("<{:?}{}", at, body));
2094− }
2095− let class = compute_class(&elem.attrs, site, styles, distinct)?;
2096− if let Some(parent) = &site.parent.class {
2097− for (at, body) in as_child {
2098− styles.add_keyed(at, format!(":where(.{})>.{}", parent, class), body);
2099− }
2100− }
2101− Some(class)
2102−}
2610+ // Overflow axis
2611+ "overflow-x" => {
2612+ if let Some(v) = val {
2613+ push_css(&mut css, "overflow-x", v);
2614+ }
2615+ }
2616+ "overflow-y" => {
2617+ if let Some(v) = val {
2618+ push_css(&mut css, "overflow-y", v);
2619+ }
2620+ }
21032621
2104−/// The `display` of a layout (nothing for text, native and void elements,
2105−/// which keep HTML's own).
2106−fn layout_css(layout: Layout, inline: bool) -> &'static str {
2107− match (layout, inline) {
2108− (Layout::Column, false) => "display:flex;flex-direction:column;",
2109− (Layout::Column, true) => "display:inline-flex;flex-direction:column;",
2110− (Layout::Row, false) => "display:flex;flex-direction:row;",
2111− (Layout::Row, true) => "display:inline-flex;flex-direction:row;",
2112− (Layout::Grid, false) => "display:grid;",
2113− (Layout::Grid, true) => "display:inline-grid;",
2114− _ => "",
2115− }
2116−}
2622+ // Inset (shorthand for top/right/bottom/left)
2623+ "inset" => {
2624+ if let Some(v) = val {
2625+ push_css(&mut css, "inset", &css_px(v));
2626+ }
2627+ }
21172628
2118−/// The declarations of the attributes under `condition` (the defaults of
2119−/// the element's kind are [`default_css`]'s).
2120−fn attrs_to_css(attrs: &[Attribute], condition: &Condition, site: &Site) -> String {
2121− let mut css = String::new();
2122− // The auto margins of `center-x`, `align-left`, ..., written at the end
2123− let mut aligned = String::new();
2124− let kind = site.kind;
2125− // Under `children:` the styles go on the children, whose parent is this
2126− // element: htmlang's words that place an element in its parent are an
2127− // error there (the parser reports them), and left out
2128− let on_children = condition.on_children();
2129− let inside = condition.inside().is_some();
2130− // The direction `fill` and `shrink` compile against
2131− let axis = site.parent.at(&condition.at);
2132−
2133− // htmlang's words for laying out children (`spacing`, `wrap`,
2134− // `grid-cols`) mean nothing on an element that doesn't lay out its
2135− // children, which the parser reports; they are left out. Under
2136− // `children:` they go on the children, whose layout isn't known here.
2137− let lays_out_children = kind.layout().is_container() || on_children;
2138− fn under<'k>(key: &'k str, condition: &Condition) -> Option<&'k str> {
2139− let (c, name) = Condition::of(key);
2140− (c == *condition).then_some(name)
2141− }
2142−
2143− for (index, attr) in attrs.iter().enumerate() {
2144− if attr.html {
2145− continue;
2146− }
2147− let Some(effective_key) = under(&attr.key, condition) else {
2148− continue;
2149− };
2150− if on_children && crate::vocab::places_in_parent(effective_key, attr.value.as_deref()) {
2151− continue;
2152− }
2153− // Under an element prefix (`@td:`) the styles go on elements whose
2154− // layout and parent aren't known here: htmlang's own words are an
2155− // error there (the parser reports them), and left out
2156− if inside && crate::vocab::is_htmlang_word(effective_key, attr.value.as_deref()) {
2157− continue;
2158− }
2629+ // Accent & caret colors
2630+ "accent-color" => {
2631+ if let Some(v) = val {
2632+ push_css(&mut css, "accent-color", v);
2633+ }
2634+ }
2635+ "caret-color" => {
2636+ if let Some(v) = val {
2637+ push_css(&mut css, "caret-color", v);
2638+ }
2639+ }
21592640
2160− let val = attr.value.as_deref();
2161− // A style whose value came out empty (a field a record doesn't
2162− // have, `${if()}` without its other branch) is left out
2163− if val.is_some_and(|v| v.trim().is_empty()) {
2164− continue;
2165− }
2641+ // Color scheme & appearance
2642+ "color-scheme" => {
2643+ if let Some(v) = val {
2644+ push_css(&mut css, "color-scheme", v);
2645+ }
2646+ }
2647+ "appearance" => {
2648+ if let Some(v) = val {
2649+ push_css(&mut css, "appearance", v);
2650+ }
2651+ }
21662652
2167− match effective_key {
2168− // htmlang's own words: they lay out children or place the
2169− // element in its parent, and mean more than one CSS property
2170− "spacing" if !lays_out_children => {}
2171− "spacing" => {
2653+ // List style
2654+ "list-style" => {
21722655 if let Some(v) = val {
2173− push_css(&mut css, "gap", &with_px("gap", v));
2656+ push_css(&mut css, "list-style", v);
21742657 }
21752658 }
21762659
2177− // Sizing: `fill` and `shrink` compile against the parent's
2178− // direction. Only the last `width` (`height`) counts, as for
2179− // any style written twice.
2180− "width" | "height" if val.is_some_and(|v| Size::of(v) != Size::Set) => {
2181− let later = attrs[index + 1..].iter().any(|a| {
2182− !a.html
2183− && under(&a.key, condition) == Some(effective_key)
2184− && a.value.as_deref().is_some_and(|v| !v.trim().is_empty())
2185− });
2186− if later {
2187− continue;
2660+ // Table
2661+ "border-collapse" => {
2662+ if let Some(v) = val {
2663+ push_css(&mut css, "border-collapse", v);
21882664 }
2189− let dim = if effective_key == "width" {
2190− Dim::Width
2191− } else {
2192− Dim::Height
2193− };
2194− let size = Size::of(val.unwrap_or_default());
2195− // What the element writes itself, which a layout word
2196− // leaves alone
2197− let sizes = Sizes::of(attrs, condition);
2198− for &(property, value) in sizing(dim, size, axis) {
2199− sizes.push(&mut css, property, value);
2200− }
2201− }
2202−
2203− // A size of its own under a prefix, where a `fill` or
2204− // `shrink` that sets `flex` (along a flex parent's direction)
2205− // holds too: the word's `flex` and minimum are put back, so the
2206− // size is the one the element gets (`width fill, lg:width 200`
2207− // in a row)
2208− "width" | "height"
2209− if *condition != Condition::default()
2210− && attrs.iter().any(|a| {
2211− let (c, name) = Condition::of(&a.key);
2212− let along = match site.parent.at(&c.at) {
2213− Some(Axis::Row) => name == "width",
2214− Some(Axis::Column) => name == "height",
2215− None => false,
2216− };
2217− !a.html
2218− && name == effective_key
2219− && along
2220− && c != *condition
2221− && c.holds_at(condition)
2222− && a.value
2223− .as_deref()
2224− .is_some_and(|v| !v.trim().is_empty() && Size::of(v) != Size::Set)
2225− }) =>
2226− {
2227− let dim = if effective_key == "width" {
2228− Dim::Width
2229− } else {
2230− Dim::Height
2231− };
2232− let sizes = Sizes::of(attrs, condition);
2233− for (property, value) in sizing_properties(dim) {
2234− if property != effective_key {
2235− sizes.push(&mut css, property, value);
2236− }
2665+ }
2666+ "border-spacing" => {
2667+ if let Some(v) = val {
2668+ push_css(&mut css, "border-spacing", &css_px(v));
2669+ }
2670+ }
2671+
2672+ // Text decoration
2673+ "text-decoration" => {
2674+ if let Some(v) = val {
2675+ push_css(&mut css, "text-decoration", v);
2676+ }
2677+ }
2678+ "text-decoration-color" => {
2679+ if let Some(v) = val {
2680+ push_css(&mut css, "text-decoration-color", v);
2681+ }
2682+ }
2683+ "text-decoration-thickness" => {
2684+ if let Some(v) = val {
2685+ push_css(&mut css, "text-decoration-thickness", &css_px(v));
2686+ }
2687+ }
2688+ "text-decoration-style" => {
2689+ if let Some(v) = val {
2690+ push_css(&mut css, "text-decoration-style", v);
2691+ }
2692+ }
2693+ "text-underline-offset" => {
2694+ if let Some(v) = val {
2695+ push_css(&mut css, "text-underline-offset", &css_px(v));
2696+ }
2697+ }
2698+
2699+ // Multi-column
2700+ "column-width" => {
2701+ if let Some(v) = val {
2702+ push_css(&mut css, "column-width", &css_px(v));
22372703 }
2704+ }
2705+ "column-rule" => {
22382706 if let Some(v) = val {
2239− push_css(&mut css, effective_key, &with_px(effective_key, v));
2707+ push_css(&mut css, "column-rule", v);
22402708 }
22412709 }
22422710
2243− // Alignment: auto margins, which work along either direction.
2244− // They are written last, so a `margin` on the same element
2245− // keeps its other sides (`center-x, margin 20`)
2246− "center-x" => {
2247− push_css(&mut aligned, "margin-left", "auto");
2248− push_css(&mut aligned, "margin-right", "auto");
2711+ // Place items/self
2712+ "place-items" => {
2713+ if let Some(v) = val {
2714+ push_css(&mut css, "place-items", v);
2715+ }
22492716 }
2250− "center-y" => {
2251− push_css(&mut aligned, "margin-top", "auto");
2252− push_css(&mut aligned, "margin-bottom", "auto");
2717+ "place-self" => {
2718+ if let Some(v) = val {
2719+ push_css(&mut css, "place-self", v);
2720+ }
22532721 }
2254− "align-left" => push_css(&mut aligned, "margin-right", "auto"),
2255− "align-right" => push_css(&mut aligned, "margin-left", "auto"),
2256− "align-top" => push_css(&mut aligned, "margin-bottom", "auto"),
2257− "align-bottom" => push_css(&mut aligned, "margin-top", "auto"),
22582722
2259− "wrap" if lays_out_children => push_css(&mut css, "flex-wrap", "wrap"),
2260− "wrap" => {}
2723+ // Scroll behavior
2724+ "scroll-behavior" => {
2725+ if let Some(v) = val {
2726+ push_css(&mut css, "scroll-behavior", v);
2727+ }
2728+ }
22612729
2262− // Grid
2263− "grid-cols" | "grid-rows" if !lays_out_children => {}
2264− "grid-cols" | "grid-rows" => {
2730+ // Resize
2731+ "resize" => {
22652732 if let Some(v) = val {
2266− let property = if effective_key == "grid-cols" {
2267− "grid-template-columns"
2268− } else {
2269− "grid-template-rows"
2270− };
2271− match v.parse::<u32>() {
2272− Ok(n) => push_css(&mut css, property, &format!("repeat({},1fr)", n)),
2273− Err(_) => push_css(&mut css, property, &with_px(property, v)),
2274− }
2733+ push_css(&mut css, "resize", v);
22752734 }
22762735 }
2277− "col-span" | "row-span" => {
2736+
2737+ // New CSS properties
2738+ "clip-path" => {
2739+ if let Some(v) = val { push_css(&mut css, "clip-path", v); }
2740+ }
2741+ "mix-blend-mode" => {
2742+ if let Some(v) = val { push_css(&mut css, "mix-blend-mode", v); }
2743+ }
2744+ "background-blend-mode" => {
2745+ if let Some(v) = val { push_css(&mut css, "background-blend-mode", v); }
2746+ }
2747+ "writing-mode" => {
2748+ if let Some(v) = val { push_css(&mut css, "writing-mode", v); }
2749+ }
2750+ "column-count" => {
2751+ if let Some(v) = val { push_css(&mut css, "column-count", v); }
2752+ }
2753+ "column-gap" => {
2754+ if let Some(v) = val { push_css(&mut css, "column-gap", &css_px(v)); }
2755+ }
2756+ "text-indent" => {
2757+ if let Some(v) = val { push_css(&mut css, "text-indent", &css_px(v)); }
2758+ }
2759+ "hyphens" => {
2760+ if let Some(v) = val { push_css(&mut css, "hyphens", v); }
2761+ }
2762+ "flex-grow" => {
2763+ if let Some(v) = val { push_css(&mut css, "flex-grow", v); }
2764+ }
2765+ "flex-shrink" => {
2766+ if let Some(v) = val { push_css(&mut css, "flex-shrink", v); }
2767+ }
2768+ "flex-basis" => {
2769+ if let Some(v) = val { push_css(&mut css, "flex-basis", &css_px(v)); }
2770+ }
2771+ "isolation" => {
2772+ if let Some(v) = val { push_css(&mut css, "isolation", v); }
2773+ }
2774+ "place-content" => {
2775+ if let Some(v) = val { push_css(&mut css, "place-content", v); }
2776+ }
2777+ "background-image" => {
2778+ if let Some(v) = val { push_css(&mut css, "background-image", v); }
2779+ }
2780+ "font-weight" => {
2781+ if let Some(v) = val { push_css(&mut css, "font-weight", v); }
2782+ }
2783+ "font-style" => {
2784+ if let Some(v) = val { push_css(&mut css, "font-style", v); }
2785+ }
2786+ "text-wrap" => {
2787+ if let Some(v) = val { push_css(&mut css, "text-wrap", v); }
2788+ }
2789+ "will-change" => {
2790+ if let Some(v) = val { push_css(&mut css, "will-change", v); }
2791+ }
2792+ "touch-action" => {
2793+ if let Some(v) = val { push_css(&mut css, "touch-action", v); }
2794+ }
2795+ "vertical-align" => {
2796+ if let Some(v) = val { push_css(&mut css, "vertical-align", v); }
2797+ }
2798+ "contain" => {
2799+ if let Some(v) = val { push_css(&mut css, "contain", v); }
2800+ }
2801+ "scroll-margin" => {
2802+ if let Some(v) = val { push_css(&mut css, "scroll-margin", &css_px(v)); }
2803+ }
2804+ "scroll-margin-top" | "scroll-margin-bottom" | "scroll-margin-left" | "scroll-margin-right" => {
2805+ if let Some(v) = val { push_css(&mut css, effective_key, &css_px(v)); }
2806+ }
2807+ "scroll-padding" => {
2808+ if let Some(v) = val { push_css(&mut css, "scroll-padding", &css_px(v)); }
2809+ }
2810+ "scroll-padding-top" | "scroll-padding-bottom" | "scroll-padding-left" | "scroll-padding-right" => {
2811+ if let Some(v) = val { push_css(&mut css, effective_key, &css_px(v)); }
2812+ }
2813+ "content-visibility" => {
2814+ if let Some(v) = val { push_css(&mut css, "content-visibility", v); }
2815+ }
2816+ "direction" => {
2817+ if let Some(v) = val { push_css(&mut css, "direction", v); }
2818+ }
2819+
2820+ "content" => {
22782821 if let Some(v) = val {
2279− let property = if effective_key == "col-span" {
2280− "grid-column"
2822+ // Wrap in quotes if not already quoted and not a CSS keyword
2823+ if v.starts_with('"') || v.starts_with('\'') || v == "none" || v == "normal" || v.starts_with("attr(") || v.starts_with("counter(") {
2824+ push_css(&mut css, "content", v);
22812825 } else {
2282− "grid-row"
2283− };
2284− push_css(&mut css, property, &format!("span {}", v));
2826+ push_css(&mut css, "content", &format!("\"{}\"", v));
2827+ }
22852828 }
22862829 }
22872830
2288− // CSS's `line-clamp` has no support yet without its
2289− // `-webkit-` fallback, which needs a box to clamp
2831+ // --- CSS Shorthands ---
2832+
2833+ "truncate" => {
2834+ push_css(&mut css, "overflow", "hidden");
2835+ push_css(&mut css, "text-overflow", "ellipsis");
2836+ push_css(&mut css, "white-space", "nowrap");
2837+ }
22902838 "line-clamp" => {
22912839 if let Some(v) = val {
22922840 push_css(&mut css, "display", "-webkit-box");
@@ -2295,23 +2843,128 @@ fn attrs_to_css(attrs: &[Attribute], condition: &Condition, site: &Site) -> Stri
22952843 push_css(&mut css, "overflow", "hidden");
22962844 }
22972845 }
2298−
2299− // Every other name is a CSS property (standard, custom,
2300− // vendor-prefixed, or one htmlang doesn't know, which the
2301− // parser warned about), written under its own name with the
2302− // value as written, except for `px` after a bare number where
2303− // the property takes a length
2304− key if crate::vocab::is_property_name(key) => {
2846+ "blur" => {
23052847 if let Some(v) = val {
2306− push_css(&mut css, key, &with_px(key, v));
2848+ push_css(&mut css, "filter", &format!("blur({})", css_px(v)));
23072849 }
23082850 }
2851+ "backdrop-blur" => {
2852+ if let Some(v) = val {
2853+ push_css(&mut css, "backdrop-filter", &format!("blur({})", css_px(v)));
2854+ }
2855+ }
2856+ "no-scrollbar" => {
2857+ push_css(&mut css, "scrollbar-width", "none");
2858+ push_css(&mut css, "-ms-overflow-style", "none");
2859+ }
2860+ "skeleton" => {
2861+ push_css(&mut css, "background", "linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%)");
2862+ push_css(&mut css, "background-size", "200% 100%");
2863+ push_css(&mut css, "animation", "hl-skeleton 1.5s ease-in-out infinite");
2864+ }
2865+ "gradient" => {
2866+ if let Some(v) = val {
2867+ // Parse: "from to [angle]" or "color1 color2 [angle]"
2868+ let parts: Vec<&str> = v.split_whitespace().collect();
2869+ let bg = if parts.len() >= 3 && (parts[2].ends_with("deg") || parts[2].ends_with("turn") || parts[2].ends_with("rad")) {
2870+ format!("linear-gradient({},{},{})", parts[2], parts[0], parts[1])
2871+ } else if parts.len() >= 2 {
2872+ format!("linear-gradient({},{})", parts[0], parts[1])
2873+ } else {
2874+ format!("linear-gradient({},transparent)", parts[0])
2875+ };
2876+ push_css(&mut css, "background", &bg);
2877+ }
2878+ }
2879+
2880+ // Grid areas
2881+ "grid-template-areas" => {
2882+ if let Some(v) = val { push_css(&mut css, "grid-template-areas", v); }
2883+ }
2884+ "grid-area" => {
2885+ if let Some(v) = val { push_css(&mut css, "grid-area", v); }
2886+ }
2887+
2888+ // View transitions
2889+ "view-transition-name" => {
2890+ if let Some(v) = val { push_css(&mut css, "view-transition-name", v); }
2891+ }
2892+
2893+ // Animate shorthand (alias for animation)
2894+ "animate" => {
2895+ if let Some(v) = val { push_css(&mut css, "animation", v); }
2896+ }
2897+
2898+ // CSS subgrid
2899+ "grid-template-columns" => {
2900+ if let Some(v) = val { push_css(&mut css, "grid-template-columns", v); }
2901+ }
2902+ "grid-template-rows" => {
2903+ if let Some(v) = val { push_css(&mut css, "grid-template-rows", v); }
2904+ }
2905+
2906+ // Scroll-driven animations
2907+ "animation-timeline" => {
2908+ if let Some(v) = val { push_css(&mut css, "animation-timeline", v); }
2909+ }
2910+ "animation-range" => {
2911+ if let Some(v) = val { push_css(&mut css, "animation-range", v); }
2912+ }
2913+ "view-timeline-name" => {
2914+ if let Some(v) = val { push_css(&mut css, "view-timeline-name", v); }
2915+ }
2916+ "view-timeline-axis" => {
2917+ if let Some(v) = val { push_css(&mut css, "view-timeline-axis", v); }
2918+ }
2919+ "scroll-timeline-name" => {
2920+ if let Some(v) = val { push_css(&mut css, "scroll-timeline-name", v); }
2921+ }
2922+ "scroll-timeline-axis" => {
2923+ if let Some(v) = val { push_css(&mut css, "scroll-timeline-axis", v); }
2924+ }
2925+
2926+ // Anchor positioning
2927+ "anchor-name" => {
2928+ if let Some(v) = val { push_css(&mut css, "anchor-name", v); }
2929+ }
2930+ "position-anchor" => {
2931+ if let Some(v) = val { push_css(&mut css, "position-anchor", v); }
2932+ }
2933+ "position-area" => {
2934+ if let Some(v) = val { push_css(&mut css, "position-area", v); }
2935+ }
2936+ "inset-area" => {
2937+ // Legacy alias for position-area
2938+ if let Some(v) = val { push_css(&mut css, "position-area", v); }
2939+ }
2940+
2941+ // initial-letter (drop caps)
2942+ "initial-letter" => {
2943+ if let Some(v) = val { push_css(&mut css, "initial-letter", v); }
2944+ }
2945+
2946+ // Critical CSS hint — not CSS, handled elsewhere
2947+ "critical" => {}
2948+
2949+ // Identity and HTML passthrough — not CSS
2950+ "id" | "class" => {}
2951+ "type" | "placeholder" | "name" | "value" | "disabled" | "required"
2952+ | "checked" | "for" | "action" | "method" | "autocomplete" | "min"
2953+ | "max" | "step" | "pattern" | "maxlength" | "rows" | "cols"
2954+ | "multiple" | "alt" | "role" | "tabindex" | "title"
2955+ | "controls" | "autoplay" | "loop" | "muted" | "poster" | "preload"
2956+ | "loading" | "decoding" | "ordered" | "src"
2957+ | "open" | "novalidate" | "low" | "high" | "optimum"
2958+ | "colspan" | "rowspan" | "scope" | "inline" | "responsive"
2959+ | "datetime" | "media" | "sizes" | "srcset" | "cite" | "list"
2960+ | "sandbox" | "allow" | "allowfullscreen" | "referrerpolicy"
2961+ | "formaction" | "formmethod" | "formtarget" | "target"
2962+ | "autofocus" => {}
23092963
23102964 _ => {}
23112965 }
23122966 }
23132967
2314− css.push_str(&aligned);
23152968 css
23162969}
23172970
@@ -2322,10 +2975,41 @@ fn push_css(css: &mut String, prop: &str, value: &str) {
23222975 css.push(';');
23232976}
23242977
2978+/// Known CSS units — if a value ends with one, skip appending `px`.
2979+const CSS_UNITS: &[&str] = &[
2980+ "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh",
2981+ "ch", "ex", "cm", "mm", "in", "pt", "pc", "fr",
2982+];
2983+
2984+/// Format a numeric value: if it already has a CSS unit, pass through as-is;
2985+/// otherwise append `px`.
2986+fn css_px(value: &str) -> String {
2987+ let v = value.trim();
2988+ if v == "0" {
2989+ return "0".to_string();
2990+ }
2991+ if CSS_UNITS.iter().any(|u| v.ends_with(u)) {
2992+ return v.to_string();
2993+ }
2994+ if v.starts_with("var(") || v.starts_with("calc(") || v.starts_with("clamp(") || v.starts_with("min(") || v.starts_with("max(") {
2995+ return v.to_string();
2996+ }
2997+ format!("{}px", v)
2998+}
2999+
3000+/// Format multiple space-separated values, each getting px if needed.
3001+fn css_px_multi(value: &str) -> String {
3002+ value
3003+ .split_whitespace()
3004+ .map(|p| css_px(p))
3005+ .collect::<Vec<_>>()
3006+ .join(" ")
3007+}
3008+
23253009fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
23263010 let mut id = None;
23273011 let mut class = None;
2328− for attr in attrs.iter().filter(|a| a.html) {
3012+ for attr in attrs {
23293013 match attr.key.as_str() {
23303014 "id" => id = attr.value.clone(),
23313015 "class" => class = attr.value.clone(),
@@ -2335,6 +3019,149 @@ fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
23353019 (id, class)
23363020}
23373021
3022+/// Read image dimensions from a local file by parsing the header bytes.
3023+/// Supports PNG, JPEG, GIF, WebP, AVIF, and SVG.
3024+fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
3025+ // SVG: parse as text for viewBox/width/height attributes
3026+ if path.ends_with(".svg") || path.ends_with(".SVG") {
3027+ let text = std::fs::read_to_string(path).ok()?;
3028+ return read_svg_dimensions(&text);
3029+ }
3030+
3031+ let data = std::fs::read(path).ok()?;
3032+ if data.len() < 12 {
3033+ return None;
3034+ }
3035+
3036+ // PNG: 8-byte signature, then IHDR chunk with width/height at bytes 16-23
3037+ if data.len() >= 24 && data.starts_with(b"\x89PNG\r\n\x1a\n") {
3038+ let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
3039+ let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
3040+ return Some((w, h));
3041+ }
3042+
3043+ // GIF: "GIF87a" or "GIF89a", width/height at bytes 6-9 (little-endian)
3044+ if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
3045+ let w = u16::from_le_bytes([data[6], data[7]]) as u32;
3046+ let h = u16::from_le_bytes([data[8], data[9]]) as u32;
3047+ return Some((w, h));
3048+ }
3049+
3050+ // JPEG: scan for SOF0/SOF2 marker (0xFF 0xC0 or 0xFF 0xC2)
3051+ if data.starts_with(b"\xff\xd8") {
3052+ let mut i = 2;
3053+ while i + 9 < data.len() {
3054+ if data[i] != 0xFF {
3055+ i += 1;
3056+ continue;
3057+ }
3058+ let marker = data[i + 1];
3059+ if marker == 0xC0 || marker == 0xC2 {
3060+ let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
3061+ let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
3062+ return Some((w, h));
3063+ }
3064+ if i + 3 < data.len() {
3065+ let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
3066+ i += 2 + len;
3067+ } else {
3068+ break;
3069+ }
3070+ }
3071+ }
3072+
3073+ // WebP: "RIFF" ... "WEBP", VP8 header at byte 20
3074+ if data.len() >= 30 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
3075+ if &data[12..16] == b"VP8 " && data.len() >= 30 {
3076+ let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
3077+ let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
3078+ return Some((w, h));
3079+ }
3080+ if &data[12..16] == b"VP8L" && data.len() >= 25 && data[21] == 0x2F {
3081+ let bits = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
3082+ let w = (bits & 0x3FFF) + 1;
3083+ let h = ((bits >> 14) & 0x3FFF) + 1;
3084+ return Some((w, h));
3085+ }
3086+ }
3087+
3088+ // AVIF: ISOBMFF container with "ftyp" box containing "avif"/"avis" brand,
3089+ // then "ispe" box with width/height
3090+ if data.len() >= 12 && &data[4..8] == b"ftyp" {
3091+ let brand = &data[8..12];
3092+ if brand == b"avif" || brand == b"avis" || brand == b"mif1" {
3093+ return read_avif_dimensions(&data);
3094+ }
3095+ }
3096+
3097+ None
3098+}
3099+
3100+/// Parse SVG viewBox or width/height attributes to get dimensions.
3101+fn read_svg_dimensions(text: &str) -> Option<(u32, u32)> {
3102+ // Try viewBox first: viewBox="minX minY width height"
3103+ if let Some(vb_start) = text.find("viewBox=\"") {
3104+ let rest = &text[vb_start + 9..];
3105+ if let Some(end) = rest.find('"') {
3106+ let parts: Vec<&str> = rest[..end].split_whitespace().collect();
3107+ if parts.len() == 4 {
3108+ if let (Ok(w), Ok(h)) = (parts[2].parse::<f64>(), parts[3].parse::<f64>()) {
3109+ if w > 0.0 && h > 0.0 {
3110+ return Some((w.round() as u32, h.round() as u32));
3111+ }
3112+ }
3113+ }
3114+ }
3115+ }
3116+ // Fall back to width/height attributes on <svg>
3117+ let svg_tag = text.find("<svg")?;
3118+ let tag_end = text[svg_tag..].find('>')? + svg_tag;
3119+ let tag = &text[svg_tag..tag_end];
3120+ let w = extract_svg_attr(tag, "width")?;
3121+ let h = extract_svg_attr(tag, "height")?;
3122+ Some((w, h))
3123+}
3124+
3125+fn extract_svg_attr(tag: &str, attr: &str) -> Option<u32> {
3126+ let needle = format!("{}=\"", attr);
3127+ let start = tag.find(&needle)? + needle.len();
3128+ let rest = &tag[start..];
3129+ let end = rest.find('"')?;
3130+ let val = rest[..end].trim_end_matches("px");
3131+ val.parse::<f64>().ok().map(|v| v.round() as u32)
3132+}
3133+
3134+/// Parse AVIF (ISOBMFF) container to find ispe box with image dimensions.
3135+fn read_avif_dimensions(data: &[u8]) -> Option<(u32, u32)> {
3136+ // Walk ISOBMFF boxes looking for "ispe" (image spatial extents)
3137+ let mut i = 0;
3138+ while i + 8 <= data.len() {
3139+ let box_size = u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as usize;
3140+ let box_type = &data[i + 4..i + 8];
3141+ if box_size < 8 {
3142+ break;
3143+ }
3144+ let box_end = (i + box_size).min(data.len());
3145+ // ispe box: 4 bytes version/flags + 4 bytes width + 4 bytes height
3146+ if box_type == b"ispe" && box_end >= i + 20 {
3147+ let w = u32::from_be_bytes([data[i + 12], data[i + 13], data[i + 14], data[i + 15]]);
3148+ let h = u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
3149+ return Some((w, h));
3150+ }
3151+ // Recurse into container boxes (meta, iprp, ipco)
3152+ if matches!(box_type, b"meta" | b"iprp" | b"ipco" | b"moov" | b"trak" | b"mdia") {
3153+ let header_size = if box_type == b"meta" { 12 } else { 8 };
3154+ if i + header_size < box_end {
3155+ if let Some(dims) = read_avif_dimensions(&data[i + header_size..box_end]) {
3156+ return Some(dims);
3157+ }
3158+ }
3159+ }
3160+ i = box_end;
3161+ }
3162+ None
3163+}
3164+
23383165fn html_escape(s: &str) -> String {
23393166 s.replace('&', "&")
23403167 .replace('<', "<")
@@ -2373,24 +3200,10 @@ fn base64_encode(data: &[u8]) -> String {
23733200/// Generate a standard v3 source map with VLQ-encoded mappings.
23743201/// Compatible with browser devtools and source map tooling.
23753202pub fn generate_source_map(doc: &Document, source_file: &str) -> String {
2376− source_map_for_html(&generate_dev(doc), source_file)
2377−}
2378−
2379−/// Build a source map for dev-mode HTML by reading the `data-hl-line`
2380−/// markers each element carries, so generated line numbers are exact.
2381−pub fn source_map_for_html(html: &str, source_file: &str) -> String {
23823203 let mut mappings: Vec<(usize, usize)> = Vec::new(); // (html_line, hl_line)
2383− for (idx, line) in html.lines().enumerate() {
2384− if let Some(pos) = line.find("data-hl-line=\"") {
2385− let digits: String = line[pos + "data-hl-line=\"".len()..]
2386− .chars()
2387− .take_while(|c| c.is_ascii_digit())
2388− .collect();
2389− if let Ok(hl_line) = digits.parse::<usize>() {
2390− mappings.push((idx + 1, hl_line));
2391− }
2392− }
2393− }
3204+ collect_source_lines(&doc.nodes, &mut mappings);
3205+ mappings.sort_by_key(|m| m.0);
3206+ mappings.dedup_by_key(|m| m.0);
23943207
23953208 // Build VLQ-encoded mappings string.
23963209 // Each generated line is separated by ';'. Each segment within a line is
@@ -2408,19 +3221,16 @@ pub fn source_map_for_html(html: &str, source_file: &str) -> String {
24083221 if mapping_idx < mappings.len() && mappings[mapping_idx].0 == gen_line {
24093222 let source_line = mappings[mapping_idx].1 as i64 - 1; // 0-based
24103223 // Segment: gen_col=0, source_idx=0, source_line=delta, source_col=0
2411− vlq_encode(0, &mut vlq); // generated column (always 0)
2412− vlq_encode(0, &mut vlq); // source file index (always 0)
3224+ vlq_encode(0, &mut vlq); // generated column (always 0)
3225+ vlq_encode(0, &mut vlq); // source file index (always 0)
24133226 vlq_encode(source_line - prev_source_line, &mut vlq); // source line delta
2414− vlq_encode(0, &mut vlq); // source column (always 0)
3227+ vlq_encode(0, &mut vlq); // source column (always 0)
24153228 prev_source_line = source_line;
24163229 mapping_idx += 1;
24173230 }
24183231 }
24193232
2420− let escaped_file = source_file
2421− .replace(".hl", ".html")
2422− .replace('\\', "\\\\")
2423− .replace('"', "\\\"");
3233+ let escaped_file = source_file.replace(".hl", ".html").replace('\\', "\\\\").replace('"', "\\\"");
24243234 let escaped_source = source_file.replace('\\', "\\\\").replace('"', "\\\"");
24253235
24263236 format!(
@@ -2450,30 +3260,13 @@ fn vlq_encode(value: i64, out: &mut String) {
24503260 }
24513261}
24523262
2453−#[cfg(test)]
2454−mod tests {
2455− use super::*;
2456−
2457− #[test]
2458− fn a_name_is_a_stable_hash_of_the_style() {
2459− // The same in every build and on every platform
2460− assert_eq!(stable_hash(""), 0xf52a_15e9_a9b5_e89b);
2461− assert_eq!(hash_digits(35, 3), "z00");
2462− assert_eq!(hash_digits(u64::MAX, 13), "fsgs46211e5w3");
2463− }
2464−
2465− #[test]
2466− fn a_name_taken_in_the_file_takes_more_digits() {
2467− // These two styles' hashes end in the same 7 digits
2468− let mut styles = StyleCollector::new();
2469− let first = styles.get_class("width:129555px;".into(), Vec::new(), String::new());
2470− let second = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
2471− let (first, second) = (first.unwrap(), second.unwrap());
2472− assert_eq!(first.len(), 3 + CLASS_DIGITS, "{first}");
2473− assert_eq!(second.len(), 3 + CLASS_DIGITS + 1, "{second}");
2474− assert!(second.starts_with(&first), "{first} {second}");
2475− // The same style gets the name it got before
2476− let again = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
2477− assert_eq!(again.as_deref(), Some(second.as_str()));
3263+fn collect_source_lines(nodes: &[Node], mappings: &mut Vec<(usize, usize)>) {
3264+ for node in nodes {
3265+ if let Node::Element(elem) = node {
3266+ if elem.line_num > 0 {
3267+ mappings.push((mappings.len() + 1, elem.line_num));
3268+ }
3269+ collect_source_lines(&elem.children, mappings);
3270+ }
24783271 }
24793272}