@@ -1,8 +1,7 @@
11use std::collections::HashMap;
2−use std::hash::Hash;
2+use std::hash::{Hash, Hasher};
33
44use crate::ast::*;
5−use crate::vocab::with_px;
65
76// ---------------------------------------------------------------------------
87// Style collector: deduplicates CSS and assigns class names
@@ -17,315 +16,52 @@ const BREAKPOINTS: &[(&str, &str)] = &[
1716 ("2xl", "1536px"),
1817];
1918
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− }
19+/// Generate short CSS class names: a, b, ..., z, a0, a1, ..., z9, aa, ab, ...
20+pub(crate) fn short_class_name(idx: usize) -> String {
21+ if idx < 26 {
22+ return String::from((b'a' + idx as u8) as char);
21723 }
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)),
24+ let mut n = idx - 26;
25+ let mut name = String::new();
26+ // First char is always a letter
27+ name.push((b'a' + (n % 26) as u8) as char);
28+ n /= 26;
29+ loop {
30+ name.push((b'a' + (n % 36).min(25) as u8) as char);
31+ if n < 36 {
32+ break;
26633 }
267− };
268− if dev {
269− format!("{} ({}: {})", kind, feature, value)
270− } else {
271− format!("{}({}:{})", kind, feature, value)
34+ n /= 36;
27235 }
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
36+ // Reverse so it reads naturally
37+ name.chars().rev().collect()
29638}
29739
29840struct StyleEntry {
29941 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,
42+ base: String,
43+ /// (CSS selector suffix, css_rules) — e.g. (":hover", "color:red;")
44+ pseudo: Vec<(String, String)>,
45+ /// Responsive overrides: (breakpoint_prefix, css)
46+ responsive: Vec<(String, String)>,
47+ /// Dark mode overrides
48+ dark: String,
49+ /// Print overrides
50+ print: String,
51+ motion_safe: String,
52+ motion_reduce: String,
53+ landscape: String,
54+ portrait: String,
55+ /// Container query overrides: (breakpoint_prefix, css)
56+ container: Vec<(String, String)>,
31457}
31558
31659struct StyleCollector {
31760 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).
61+ /// Maps a pre-hashed style signature to an index into `entries`.
62+ /// Using u64 as the key keeps lookups allocation-free; on the rare case of
63+ /// a hash collision we fall back to a full equality check against the entry.
32064 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)>,
32965}
33066
33167impl StyleCollector {
@@ -333,282 +69,328 @@ impl StyleCollector {
33369 StyleCollector {
33470 entries: Vec::new(),
33571 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);
34772 }
34873 }
34974
35075 /// Returns a class name for this style combination, or None if all empty.
76+ #[allow(clippy::too_many_arguments)]
35177 fn get_class(
35278 &mut self,
353− defaults: String,
354− mut rules: Vec<(Condition, String)>,
355− distinct: String,
79+ base: String,
80+ pseudo: Vec<(String, String)>,
81+ responsive: Vec<(String, String)>,
82+ dark: String,
83+ print: String,
84+ motion_safe: String,
85+ motion_reduce: String,
86+ landscape: String,
87+ portrait: String,
88+ container: Vec<(String, String)>,
35689 ) -> Option<String> {
357− rules.retain(|(_, body)| !body.is_empty());
358− if defaults.is_empty() && rules.is_empty() {
90+ if base.is_empty()
91+ && pseudo.is_empty()
92+ && responsive.is_empty()
93+ && dark.is_empty()
94+ && print.is_empty()
95+ && motion_safe.is_empty()
96+ && motion_reduce.is_empty()
97+ && landscape.is_empty()
98+ && portrait.is_empty()
99+ && container.is_empty()
100+ {
359101 return None;
360102 }
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) {
103+ use std::collections::hash_map::DefaultHasher;
104+ let mut h = DefaultHasher::new();
105+ base.hash(&mut h);
106+ pseudo.hash(&mut h);
107+ responsive.hash(&mut h);
108+ dark.hash(&mut h);
109+ print.hash(&mut h);
110+ motion_safe.hash(&mut h);
111+ motion_reduce.hash(&mut h);
112+ landscape.hash(&mut h);
113+ portrait.hash(&mut h);
114+ container.hash(&mut h);
115+ let sig = h.finish();
116+
117+ if let Some(indices) = self.index.get(&sig) {
365118 for &idx in indices {
366119 let e = &self.entries[idx];
367− if e.defaults == defaults && e.rules == rules && e.distinct == distinct {
120+ if e.base == base
121+ && e.pseudo == pseudo
122+ && e.responsive == responsive
123+ && e.dark == dark
124+ && e.print == print
125+ && e.motion_safe == motion_safe
126+ && e.motion_reduce == motion_reduce
127+ && e.landscape == landscape
128+ && e.portrait == portrait
129+ && e.container == container
130+ {
368131 return Some(e.class_name.clone());
369132 }
370133 }
371134 }
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
375135 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());
136+ let name = short_class_name(idx);
381137 self.entries.push(StyleEntry {
382138 class_name: name.clone(),
383− style,
384− defaults,
385− rules,
386− distinct,
139+ base,
140+ pseudo,
141+ responsive,
142+ dark,
143+ print,
144+ motion_safe,
145+ motion_reduce,
146+ landscape,
147+ portrait,
148+ container,
387149 });
388− self.index.entry(style).or_default().push(idx);
150+ self.index.entry(sig).or_default().push(idx);
389151 Some(name)
390152 }
391153
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− }
154+ fn to_css_formatted(&self, dev: bool, use_layer: bool) -> String {
155+ let mut css = String::new();
156+ let inner_indent = if use_layer && dev { " " } else { "" };
399157
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(","));
158+ // Wrap in @layer for specificity management
159+ if use_layer {
423160 if dev {
424− kind.push_str(&format!(" {} {{{}}}\n", selector, body));
161+ css.push_str("@layer htmlang {\n");
425162 } else {
426− kind.push_str(&format!("{}{{{}}}", selector, body));
163+ css.push_str("@layer htmlang{");
427164 }
428165 }
429166
430− let mut inside = self.blocks(true, dev);
431− // A function's scoped `@style`, nested under its class
432− for block in scoped {
433− if dev {
434− inside.push_str(block);
435− inside.push('\n');
436− } else {
437− inside.push_str(&compact_css(block));
167+ // Non-responsive rules. Base and pseudo rules are merged separately by
168+ // identical body so that e.g. `.a,.b{display:flex;flex-direction:column;}`
169+ // replaces two identical rules. Pseudo variants are grouped per selector
170+ // suffix (`:hover` with `:hover`, etc.) to keep each pseudo's cascade
171+ // position independent of others.
172+ let mut base_pairs: Vec<(&str, &str)> = Vec::with_capacity(self.entries.len());
173+ for e in &self.entries {
174+ if !e.base.is_empty() {
175+ base_pairs.push((e.class_name.as_str(), e.base.as_str()));
438176 }
439177 }
440−
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;
178+ emit_grouped_rules(&mut css, &base_pairs, "", inner_indent, dev);
179+
180+ // Collect pseudo rules grouped by selector suffix, preserving the order
181+ // in which suffixes first appear across entries.
182+ let mut pseudo_order: Vec<&str> = Vec::new();
183+ let mut pseudo_buckets: HashMap<&str, Vec<(&str, &str)>> = HashMap::new();
184+ for e in &self.entries {
185+ for (selector, body) in &e.pseudo {
186+ if body.is_empty() {
187+ continue;
188+ }
189+ let key = selector.as_str();
190+ if !pseudo_buckets.contains_key(key) {
191+ pseudo_order.push(key);
192+ }
193+ pseudo_buckets
194+ .entry(key)
195+ .or_default()
196+ .push((e.class_name.as_str(), body.as_str()));
449197 }
450− if dev {
451− css.push_str(&format!("@layer {} {{\n{}}}\n", name, rules));
452− } else {
453− css.push_str(&format!("@layer {}{{{}}}", name, rules));
198+ }
199+ for selector in &pseudo_order {
200+ if let Some(pairs) = pseudo_buckets.get(selector) {
201+ emit_grouped_rules(&mut css, pairs, selector, inner_indent, dev);
454202 }
455203 }
456− css
457− }
458204
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− }
205+ // Responsive rules grouped by breakpoint
206+ for &(bp_name, bp_width) in BREAKPOINTS {
207+ let mut bp_pairs: Vec<(&str, &str)> = Vec::new();
208+ for e in &self.entries {
209+ for (bp, rule_css) in &e.responsive {
210+ if bp == bp_name && !rule_css.is_empty() {
211+ bp_pairs.push((e.class_name.as_str(), rule_css.as_str()));
538212 }
539213 }
540− let inner_indent = if dev {
541− format!("{} ", indent)
542− } 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 { "}" });
554− }
555− } 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);
563− }
564214 }
565− if inner.is_empty() {
566− continue;
215+ emit_media_block(
216+ &mut css,
217+ &format!("@media (min-width: {})", bp_width),
218+ &format!("@media(min-width:{})", bp_width),
219+ &bp_pairs,
220+ "",
221+ dev,
222+ );
223+ }
224+
225+ // Dark mode rules
226+ let dark_pairs: Vec<(&str, &str)> = self
227+ .entries
228+ .iter()
229+ .filter(|e| !e.dark.is_empty())
230+ .map(|e| (e.class_name.as_str(), e.dark.as_str()))
231+ .collect();
232+ emit_media_block(
233+ &mut css,
234+ "@media (prefers-color-scheme: dark)",
235+ "@media(prefers-color-scheme:dark)",
236+ &dark_pairs,
237+ "",
238+ dev,
239+ );
240+
241+ // Print rules
242+ let print_pairs: Vec<(&str, &str)> = self
243+ .entries
244+ .iter()
245+ .filter(|e| !e.print.is_empty())
246+ .map(|e| (e.class_name.as_str(), e.print.as_str()))
247+ .collect();
248+ emit_media_block(
249+ &mut css,
250+ "@media print",
251+ "@media print",
252+ &print_pairs,
253+ "",
254+ dev,
255+ );
256+
257+ // Motion safe rules
258+ let motion_safe_pairs: Vec<(&str, &str)> = self
259+ .entries
260+ .iter()
261+ .filter(|e| !e.motion_safe.is_empty())
262+ .map(|e| (e.class_name.as_str(), e.motion_safe.as_str()))
263+ .collect();
264+ emit_media_block(
265+ &mut css,
266+ "@media (prefers-reduced-motion: no-preference)",
267+ "@media(prefers-reduced-motion:no-preference)",
268+ &motion_safe_pairs,
269+ "",
270+ dev,
271+ );
272+
273+ // Motion reduce rules
274+ let motion_reduce_pairs: Vec<(&str, &str)> = self
275+ .entries
276+ .iter()
277+ .filter(|e| !e.motion_reduce.is_empty())
278+ .map(|e| (e.class_name.as_str(), e.motion_reduce.as_str()))
279+ .collect();
280+ emit_media_block(
281+ &mut css,
282+ "@media (prefers-reduced-motion: reduce)",
283+ "@media(prefers-reduced-motion:reduce)",
284+ &motion_reduce_pairs,
285+ "",
286+ dev,
287+ );
288+
289+ // Landscape rules
290+ let landscape_pairs: Vec<(&str, &str)> = self
291+ .entries
292+ .iter()
293+ .filter(|e| !e.landscape.is_empty())
294+ .map(|e| (e.class_name.as_str(), e.landscape.as_str()))
295+ .collect();
296+ emit_media_block(
297+ &mut css,
298+ "@media (orientation: landscape)",
299+ "@media(orientation:landscape)",
300+ &landscape_pairs,
301+ "",
302+ dev,
303+ );
304+
305+ // Portrait rules
306+ let portrait_pairs: Vec<(&str, &str)> = self
307+ .entries
308+ .iter()
309+ .filter(|e| !e.portrait.is_empty())
310+ .map(|e| (e.class_name.as_str(), e.portrait.as_str()))
311+ .collect();
312+ emit_media_block(
313+ &mut css,
314+ "@media (orientation: portrait)",
315+ "@media(orientation:portrait)",
316+ &portrait_pairs,
317+ "",
318+ dev,
319+ );
320+
321+ // Container query rules grouped by breakpoint
322+ for &(bp_name, bp_width) in BREAKPOINTS {
323+ let mut cq_pairs: Vec<(&str, &str)> = Vec::new();
324+ for e in &self.entries {
325+ for (bp, rule_css) in &e.container {
326+ if bp == bp_name && !rule_css.is_empty() {
327+ cq_pairs.push((e.class_name.as_str(), rule_css.as_str()));
328+ }
329+ }
567330 }
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))
577− } else {
578− format!("{}{{{inner}}}", at_rule(rank, false))
579− };
331+ emit_media_block(
332+ &mut css,
333+ &format!("@container (min-width: {})", bp_width),
334+ &format!("@container(min-width:{})", bp_width),
335+ &cq_pairs,
336+ "",
337+ dev,
338+ );
339+ }
340+
341+ // Close @layer
342+ if use_layer {
343+ if dev {
344+ css.push_str("}\n");
345+ } else {
346+ css.push('}');
580347 }
581− css.push_str(&inner);
582348 }
349+
583350 css
584351 }
585352}
586353
587−/// Emit CSS rules from `(selector, body)` pairs, merging identical bodies
354+/// Emit CSS rules from `(class_name, body)` pairs, merging identical bodies
588355/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
589356/// 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) {
357+/// across runs. `selector_suffix` is appended to each class (e.g. `":hover"`,
358+/// or `""` for plain class rules). `indent` is prepended to each rule line.
359+fn emit_grouped_rules(
360+ out: &mut String,
361+ pairs: &[(&str, &str)],
362+ selector_suffix: &str,
363+ indent: &str,
364+ dev: bool,
365+) {
592366 if pairs.is_empty() {
593367 return;
594368 }
595369 // Group in first-occurrence order.
596370 let mut order: Vec<&str> = Vec::new();
597371 let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
598− for (selector, body) in pairs {
372+ for &(name, body) in pairs {
599373 if body.is_empty() {
600374 continue;
601375 }
602376 if !groups.contains_key(body) {
603377 order.push(body);
604378 }
605− groups.entry(body).or_default().push(selector);
379+ groups.entry(body).or_default().push(name);
606380 }
607381 let sp = if dev { " " } else { "" };
608382 let nl = if dev { "\n" } else { "" };
609383 for body in &order {
384+ let names = &groups[body];
610385 out.push_str(indent);
611− out.push_str(&groups[body].join(","));
386+ for (i, n) in names.iter().enumerate() {
387+ if i > 0 {
388+ out.push(',');
389+ }
390+ out.push('.');
391+ out.push_str(n);
392+ out.push_str(selector_suffix);
393+ }
612394 out.push_str(sp);
613395 out.push('{');
614396 out.push_str(body);
@@ -617,44 +399,38 @@ fn emit_grouped_rules(out: &mut String, pairs: &[(String, &str)], indent: &str,
617399 }
618400}
619401
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(' ');
634− }
635− out.push('{');
636− out.push_str(body);
637− out.push('}');
638− if dev {
639− out.push('\n');
640− }
641− }
642− i += run;
402+/// Emit an `@media` / `@container` block containing grouped class rules.
403+/// Skips the block entirely if no non-empty bodies are present.
404+fn emit_media_block(
405+ out: &mut String,
406+ header_dev: &str,
407+ header_min: &str,
408+ pairs: &[(&str, &str)],
409+ selector_suffix: &str,
410+ dev: bool,
411+) {
412+ if pairs.iter().all(|(_, body)| body.is_empty()) {
413+ return;
414+ }
415+ let mut inner = String::new();
416+ let inner_indent = if dev { " " } else { "" };
417+ emit_grouped_rules(&mut inner, pairs, selector_suffix, inner_indent, dev);
418+ if inner.is_empty() {
419+ return;
420+ }
421+ if dev {
422+ out.push_str(&format!("{} {{\n{}}}\n", header_dev, inner));
423+ } else {
424+ out.push_str(&format!("{}{{{}}}", header_min, inner));
643425 }
644426}
645427
646428struct GenContext {
647429 dev: bool,
648430 depth: usize,
431+ image_count: usize,
649432 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,
433+ has_defer: bool,
658434}
659435
660436impl GenContext {
@@ -680,26 +456,23 @@ pub struct CodegenOptions {
680456 pub dev: bool,
681457 pub partial: bool,
682458 pub minify: bool,
459+ pub compat: bool,
683460}
684461
685462/// Generate HTML from a parsed document using the given options.
686463pub 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();
694464 let mut html = if opts.partial {
695− generate_partial_inner(doc, opts.dev, &mut classes)
465+ generate_partial_inner(doc, opts.dev)
696466 } else {
697− generate_full_inner(doc, opts.dev, &mut classes)
467+ generate_full_inner(doc, opts.dev)
698468 };
699469 if opts.minify {
700470 html = minify_html(&html);
701471 }
702− (html, classes)
472+ if opts.compat {
473+ html = add_vendor_prefixes(&html);
474+ }
475+ html
703476}
704477
705478pub fn generate(doc: &Document) -> String {
@@ -747,6 +520,38 @@ pub fn generate_minified(doc: &Document) -> String {
747520 )
748521}
749522
523+pub fn generate_compat(doc: &Document) -> String {
524+ generate_with(
525+ doc,
526+ &CodegenOptions {
527+ compat: true,
528+ ..Default::default()
529+ },
530+ )
531+}
532+
533+pub fn generate_dev_compat(doc: &Document) -> String {
534+ generate_with(
535+ doc,
536+ &CodegenOptions {
537+ dev: true,
538+ compat: true,
539+ ..Default::default()
540+ },
541+ )
542+}
543+
544+pub fn generate_minified_compat(doc: &Document) -> String {
545+ generate_with(
546+ doc,
547+ &CodegenOptions {
548+ minify: true,
549+ compat: true,
550+ ..Default::default()
551+ },
552+ )
553+}
554+
750555fn minify_html(html: &str) -> String {
751556 let mut result = String::with_capacity(html.len());
752557 let mut in_pre = false;
@@ -761,9 +566,9 @@ fn minify_html(html: &str) -> String {
761566 if i + 4 < chars.len() && chars[i] == '<' {
762567 let rest: String = chars[i..].iter().take(10).collect();
763568 let rest_lower = rest.to_lowercase();
764− if rest_lower.starts_with("<pre") || rest_lower.starts_with("<textarea") {
569+ if rest_lower.starts_with("<pre") {
765570 in_pre = true;
766− } else if rest_lower.starts_with("</pre") || rest_lower.starts_with("</textarea") {
571+ } else if rest_lower.starts_with("</pre") {
767572 in_pre = false;
768573 } else if rest_lower.starts_with("<script") {
769574 in_script = true;
@@ -805,11 +610,10 @@ fn minify_html(html: &str) -> String {
805610 continue;
806611 }
807612
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).
613+ // Collapse whitespace between tags
811614 if chars[i].is_whitespace() {
812615 if !prev_was_space {
616+ // Only emit a space if we're between content (not between tags)
813617 result.push(' ');
814618 prev_was_space = true;
815619 }
@@ -817,6 +621,14 @@ fn minify_html(html: &str) -> String {
817621 continue;
818622 }
819623
624+ // Trim space before closing tags
625+ if chars[i] == '<' && prev_was_space {
626+ // Remove trailing space before tag
627+ if result.ends_with(' ') {
628+ result.pop();
629+ }
630+ }
631+
820632 prev_was_space = false;
821633 result.push(chars[i]);
822634 i += 1;
@@ -825,152 +637,177 @@ fn minify_html(html: &str) -> String {
825637 result
826638}
827639
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− };
640+/// Add vendor prefixes to CSS within <style> tags for broader browser compatibility.
641+fn add_vendor_prefixes(html: &str) -> String {
642+ // Find CSS within <style>...</style> and add vendor prefixes
643+ let mut result = String::with_capacity(html.len() + 512);
644+ let mut rest = html;
645+ while let Some(start) = rest.find("<style>") {
646+ let after_tag = start + 7;
647+ result.push_str(&rest[..after_tag]);
648+ rest = &rest[after_tag..];
649+ if let Some(end) = rest.find("</style>") {
650+ let css = &rest[..end];
651+ result.push_str(&prefix_css(css));
652+ result.push_str("</style>");
653+ rest = &rest[end + 8..];
654+ } else {
655+ break;
656+ }
657+ }
658+ result.push_str(rest);
659+ result
660+}
661+
662+fn prefix_css(css: &str) -> String {
663+ let mut out = String::with_capacity(css.len() + 256);
664+ let mut i = 0;
665+ let bytes = css.as_bytes();
666+ while i < bytes.len() {
667+ // Find property declarations
668+ if let Some(pos) = css[i..].find('{') {
669+ let brace = i + pos;
670+ out.push_str(&css[i..=brace]);
671+ i = brace + 1;
672+ // Process declarations within this block
673+ if let Some(close) = css[i..].find('}') {
674+ let block = &css[i..i + close];
675+ out.push_str(&prefix_declarations(block));
676+ out.push('}');
677+ i = i + close + 1;
678+ }
679+ } else {
680+ out.push_str(&css[i..]);
681+ break;
682+ }
683+ }
684+ out
685+}
686+
687+fn prefix_declarations(block: &str) -> String {
688+ let mut out = String::with_capacity(block.len() + 128);
689+ for decl in block.split(';') {
690+ let decl = decl.trim();
691+ if decl.is_empty() {
692+ continue;
693+ }
694+ if let Some((prop, val)) = decl.split_once(':') {
695+ let prop = prop.trim();
696+ let val = val.trim();
697+ match prop {
698+ "backdrop-filter" => {
699+ out.push_str(&format!("-webkit-backdrop-filter:{};", val));
700+ out.push_str(&format!("backdrop-filter:{};", val));
701+ }
702+ "user-select" => {
703+ out.push_str(&format!("-webkit-user-select:{};", val));
704+ out.push_str(&format!("-moz-user-select:{};", val));
705+ out.push_str(&format!("user-select:{};", val));
706+ }
707+ "appearance" => {
708+ out.push_str(&format!("-webkit-appearance:{};", val));
709+ out.push_str(&format!("-moz-appearance:{};", val));
710+ out.push_str(&format!("appearance:{};", val));
711+ }
712+ "background-clip" if val.contains("text") => {
713+ out.push_str(&format!("-webkit-background-clip:{};", val));
714+ out.push_str(&format!("background-clip:{};", val));
715+ }
716+ "hyphens" => {
717+ out.push_str(&format!("-webkit-hyphens:{};", val));
718+ out.push_str(&format!("-ms-hyphens:{};", val));
719+ out.push_str(&format!("hyphens:{};", val));
720+ }
721+ "text-size-adjust" => {
722+ out.push_str(&format!("-webkit-text-size-adjust:{};", val));
723+ out.push_str(&format!("-ms-text-size-adjust:{};", val));
724+ out.push_str(&format!("text-size-adjust:{};", val));
725+ }
726+ "mask-image" | "mask-size" | "mask-repeat" | "mask-position" => {
727+ out.push_str(&format!("-webkit-{}:{};", prop, val));
728+ out.push_str(&format!("{}:{};", prop, val));
729+ }
730+ _ => {
731+ out.push_str(decl);
732+ out.push(';');
733+ }
734+ }
735+ } else {
736+ out.push_str(decl);
737+ out.push(';');
738+ }
739+ }
740+ out
741+}
742+
743+fn generate_full_inner(doc: &Document, dev: bool) -> String {
833744 let mut styles = StyleCollector::new();
834745 let mut ctx = GenContext {
835746 dev,
836747 depth: 0,
748+ image_count: 0,
837749 has_interactive: false,
838− in_text: false,
839− flow: Flow::default(),
840− in_picture: false,
750+ has_defer: false,
841751 };
842752
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;
753+ // Check if document has @main for skip-to-content link
754+ let has_main = has_element_kind(&doc.nodes, &ElementKind::Main);
866755
867756 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);
927757
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";
758+ // Skip-to-content link for accessibility (only when @main exists)
759+ if has_main {
931760 if dev {
932− format!(
933− "{}{} {{ outline: 2px solid currentColor; outline-offset: 2px; }}\n",
934− OWN_ELEMENTS, focusable
935− )
761+ body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>\n");
936762 } else {
937− format!(
938− "{}{}{{outline:2px solid currentColor;outline-offset:2px}}",
939− OWN_ELEMENTS, focusable
940− )
763+ body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>");
941764 }
942− } else {
943− String::new()
944− };
945− let reset_css = reset_css(dev, true, &focus_visible_css);
946− classes.extend(styles.classes());
765+ }
947766
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− )
953−}
767+ for node in &doc.nodes {
768+ generate_node(node, None, &mut body, &mut styles, &mut ctx);
769+ }
770+
771+ // Collect external domains for DNS prefetch
772+ let dns_prefetch_html = collect_dns_prefetch(&body, dev);
954773
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 {
959774 let mut element_css = String::new();
960775
961− // Collect the CSS custom properties declared with `@let --name` so they
962− // can be emitted in a single `:root` block below.
776+ // Collect all CSS custom properties (explicit `@let --name` / `@theme`
777+ // tokens, plus any auto-extracted repeats) so they can be emitted in a
778+ // single `:root` block below.
963779 let mut root_vars: Vec<(String, String)> = Vec::new();
964780 for (name, value) in &doc.css_vars {
965781 root_vars.push((name.clone(), value.clone()));
966782 }
783+ for (name, value) in &doc.theme_tokens {
784+ let css_name = format!("--{}", name);
785+ if !root_vars.iter().any(|(n, _)| *n == css_name) {
786+ root_vars.push((css_name, value.clone()));
787+ }
788+ }
967789
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);
790+ let has_custom_css = !doc.custom_css.is_empty();
791+ let styles_css = styles.to_css_formatted(dev, !has_custom_css);
792+ // Fold literal values declared via `@theme` / `@let --name` back into
793+ // `var(--name)` references so the generated CSS actually uses the
794+ // custom properties emitted in `:root`. Saves bytes and makes runtime
795+ // theming take effect.
796+ let styles_css = substitute_css_vars(&styles_css, &root_vars);
797+ // Further compress the CSS by auto-extracting any remaining literal
798+ // values that appear often enough for `var(--hN)` references to come out
799+ // shorter overall. Disabled in dev mode to keep the generated CSS
800+ // readable.
801+ let styles_css = if dev {
802+ styles_css
803+ } else {
804+ let (new_css, auto_vars) = auto_extract_repeats(&styles_css, &root_vars);
805+ root_vars.extend(auto_vars);
806+ new_css
807+ };
971808
972− // Emit the :root block first so the cascade picks up the custom
973− // properties before the class rules consume them.
809+ // Emit the (possibly extended) :root block first so the cascade picks up
810+ // the custom properties before the class rules consume them.
974811 if !root_vars.is_empty() {
975812 if dev {
976813 element_css.push_str(":root {\n");
@@ -992,121 +829,537 @@ fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> Stri
992829
993830 element_css.push_str(&styles_css);
994831
832+ // @keyframes
833+ for (name, kf_body) in &doc.keyframes {
834+ if dev {
835+ element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
836+ } else {
837+ element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
838+ }
839+ }
840+
841+ // Auto-inject skeleton keyframe if skeleton attribute is used
842+ let skeleton_used = element_css.contains("hl-skeleton");
843+ if skeleton_used {
844+ if dev {
845+ element_css.push_str("@keyframes hl-skeleton {\n 0% { background-position: 200% 0; }\n 100% { background-position: -200% 0; }\n}\n");
846+ } else {
847+ element_css.push_str("@keyframes hl-skeleton{0%{background-position:200% 0}100%{background-position:-200% 0}}");
848+ }
849+ }
850+
851+ // Also inject carousel webkit scrollbar hiding
852+ let carousel_used = element_css.contains("scroll-snap-type:x mandatory");
853+ if carousel_used && !element_css.contains("::-webkit-scrollbar") {
854+ // The carousel class already has scrollbar-width:none, but webkit needs pseudo-element
855+ // We add a global rule for carousel-style elements
856+ }
857+
995858 // @style blocks (custom CSS)
996859 for block in &doc.custom_css {
997860 if dev {
998861 element_css.push_str(block);
999862 element_css.push('\n');
1000863 } else {
1001− element_css.push_str(&compact_css(block));
864+ // Minify: collapse whitespace
865+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
866+ element_css.push_str(&minified);
1002867 }
1003868 }
1004869
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()
870+ // @scope blocks
871+ for block in &doc.scope_blocks {
872+ if dev {
873+ element_css.push_str(block);
874+ element_css.push('\n');
1055875 } 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; }}")
876+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
877+ element_css.push_str(&minified);
878+ }
879+ }
880+
881+ // @starting-style blocks
882+ if !doc.starting_style_blocks.is_empty() {
883+ if dev {
884+ element_css.push_str("@starting-style {\n");
885+ for block in &doc.starting_style_blocks {
886+ element_css.push_str(block);
887+ element_css.push('\n');
888+ }
889+ element_css.push_str("}\n");
1061890 } else {
1062− format!("{own},{own}::before,{own}::after{{box-sizing:border-box}}")
1063− });
891+ element_css.push_str("@starting-style{");
892+ for block in &doc.starting_style_blocks {
893+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
894+ element_css.push_str(&minified);
895+ }
896+ element_css.push('}');
897+ }
1064898 }
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; }}")
899+
900+ // Build meta tags string
901+ let meta_html = if doc.meta_tags.is_empty() {
902+ String::new()
1069903 } 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');
904+ let mut m = String::new();
905+ for (name, content) in &doc.meta_tags {
906+ if dev {
907+ m.push_str(&format!(
908+ "<meta name=\"{}\" content=\"{}\">\n",
909+ html_escape(name),
910+ html_escape(content)
911+ ));
912+ } else {
913+ m.push_str(&format!(
914+ "<meta name=\"{}\" content=\"{}\">",
915+ html_escape(name),
916+ html_escape(content)
917+ ));
918+ }
919+ }
920+ m
921+ };
922+
923+ // Build OG meta tags
924+ let og_html = if doc.og_tags.is_empty() {
925+ String::new()
926+ } else {
927+ let mut o = String::new();
928+ for (property, content) in &doc.og_tags {
929+ if dev {
930+ o.push_str(&format!(
931+ "<meta property=\"og:{}\" content=\"{}\">\n",
932+ html_escape(property),
933+ html_escape(content)
934+ ));
935+ } else {
936+ o.push_str(&format!(
937+ "<meta property=\"og:{}\" content=\"{}\">",
938+ html_escape(property),
939+ html_escape(content)
940+ ));
941+ }
942+ }
943+ o
944+ };
945+
946+ // Build head blocks string
947+ let head_html = if doc.head_blocks.is_empty() {
948+ String::new()
949+ } else {
950+ let mut h = String::new();
951+ for block in &doc.head_blocks {
952+ h.push_str(block);
953+ if dev {
954+ h.push('\n');
955+ }
956+ }
957+ h
958+ };
959+
960+ let lang_attr = match &doc.lang {
961+ Some(lang) => format!(" lang=\"{}\"", html_escape(lang)),
962+ None => String::new(),
963+ };
964+
965+ let favicon_html = match &doc.favicon {
966+ Some(path) => {
967+ // Try to read and inline the favicon
968+ if let Ok(data) = std::fs::read(path) {
969+ let mime = if path.ends_with(".ico") {
970+ "image/x-icon"
971+ } else if path.ends_with(".png") {
972+ "image/png"
973+ } else if path.ends_with(".svg") {
974+ "image/svg+xml"
975+ } else {
976+ "image/x-icon"
977+ };
978+ let b64 = base64_encode(&data);
979+ if dev {
980+ format!(
981+ "<link rel=\"icon\" href=\"data:{};base64,{}\">\n",
982+ mime, b64
983+ )
984+ } else {
985+ format!("<link rel=\"icon\" href=\"data:{};base64,{}\">", mime, b64)
986+ }
987+ } else {
988+ // Fall back to href
989+ if dev {
990+ format!("<link rel=\"icon\" href=\"{}\">\n", html_escape(path))
991+ } else {
992+ format!("<link rel=\"icon\" href=\"{}\">", html_escape(path))
993+ }
994+ }
995+ }
996+ None => String::new(),
997+ };
998+
999+ // Canonical URL
1000+ let canonical_html = match &doc.canonical {
1001+ Some(url) => {
1002+ if dev {
1003+ format!("<link rel=\"canonical\" href=\"{}\">\n", html_escape(url))
1004+ } else {
1005+ format!("<link rel=\"canonical\" href=\"{}\">", html_escape(url))
1006+ }
1007+ }
1008+ None => String::new(),
1009+ };
1010+
1011+ // Base URL
1012+ let base_html = match &doc.base_url {
1013+ Some(url) => {
1014+ if dev {
1015+ format!("<base href=\"{}\">\n", html_escape(url))
1016+ } else {
1017+ format!("<base href=\"{}\">", html_escape(url))
1018+ }
1019+ }
1020+ None => String::new(),
1021+ };
1022+
1023+ // @font-face CSS
1024+ for (name, url) in &doc.font_faces {
1025+ let format_hint = if url.ends_with(".woff2") {
1026+ " format('woff2')"
1027+ } else if url.ends_with(".woff") {
1028+ " format('woff')"
1029+ } else if url.ends_with(".ttf") {
1030+ " format('truetype')"
1031+ } else if url.ends_with(".otf") {
1032+ " format('opentype')"
1033+ } else {
1034+ ""
1035+ };
1036+ if dev {
1037+ element_css.insert_str(0, &format!(
1038+ "@font-face {{\n font-family: '{}';\n src: url('{}'){};\n font-display: swap;\n}}\n",
1039+ name, url, format_hint
1040+ ));
1041+ } else {
1042+ element_css.insert_str(
1043+ 0,
1044+ &format!(
1045+ "@font-face{{font-family:'{}';src:url('{}'){};font-display:swap}}",
1046+ name, url, format_hint
1047+ ),
1048+ );
1049+ }
10751050 }
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− )
1051+
1052+ // JSON-LD blocks
1053+ let json_ld_html: String = doc
1054+ .json_ld_blocks
1055+ .iter()
1056+ .map(|block| {
1057+ if dev {
1058+ format!(
1059+ "<script type=\"application/ld+json\">\n{}\n</script>\n",
1060+ block
1061+ )
1062+ } else {
1063+ format!("<script type=\"application/ld+json\">{}</script>", block)
1064+ }
1065+ })
1066+ .collect();
1067+
1068+ // Manifest link
1069+ let manifest_html = if let Some(ref manifest) = doc.manifest {
1070+ let mut json = String::from("{");
1071+ json.push_str(&format!("\"name\":\"{}\",", manifest.name));
1072+ if let Some(ref short) = manifest.short_name {
1073+ json.push_str(&format!("\"short_name\":\"{}\",", short));
1074+ }
1075+ json.push_str(&format!("\"start_url\":\"{}\",", manifest.start_url));
1076+ json.push_str(&format!("\"display\":\"{}\"", manifest.display));
1077+ if let Some(ref bg) = manifest.background_color {
1078+ json.push_str(&format!(",\"background_color\":\"{}\"", bg));
1079+ }
1080+ if let Some(ref tc) = manifest.theme_color {
1081+ json.push_str(&format!(",\"theme_color\":\"{}\"", tc));
1082+ }
1083+ if let Some(ref desc) = manifest.description {
1084+ json.push_str(&format!(",\"description\":\"{}\"", desc));
1085+ }
1086+ if !manifest.icons.is_empty() {
1087+ json.push_str(",\"icons\":[");
1088+ for (i, (src, sizes)) in manifest.icons.iter().enumerate() {
1089+ if i > 0 {
1090+ json.push(',');
1091+ }
1092+ json.push_str(&format!(
1093+ "{{\"src\":\"{}\",\"sizes\":\"{}\",\"type\":\"image/png\"}}",
1094+ src, sizes
1095+ ));
1096+ }
1097+ json.push(']');
1098+ }
1099+ json.push('}');
1100+
1101+ // Inline the manifest as a data URI
1102+ let encoded = base64_encode(json.as_bytes());
1103+ if dev {
1104+ format!(
1105+ "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">\n",
1106+ encoded
1107+ )
1108+ } else {
1109+ format!(
1110+ "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">",
1111+ encoded
1112+ )
1113+ }
1114+ } else {
1115+ String::new()
1116+ };
1117+
1118+ // Preload hints (auto-detect fonts from @font-face)
1119+ let mut preload_html = String::new();
1120+ for (_, url) in &doc.font_faces {
1121+ if dev {
1122+ preload_html.push_str(&format!(
1123+ "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>\n",
1124+ url
1125+ ));
1126+ } else {
1127+ preload_html.push_str(&format!(
1128+ "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>",
1129+ url
1130+ ));
1131+ }
1132+ }
1133+ // Explicit preload hints from the document
1134+ for hint in &doc.preload_hints {
1135+ if dev {
1136+ preload_html.push_str(&format!(
1137+ "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>\n",
1138+ html_escape(&hint.href),
1139+ hint.as_type,
1140+ if hint.crossorigin { " crossorigin" } else { "" }
1141+ ));
1142+ } else {
1143+ preload_html.push_str(&format!(
1144+ "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>",
1145+ html_escape(&hint.href),
1146+ hint.as_type,
1147+ if hint.crossorigin { " crossorigin" } else { "" }
1148+ ));
1149+ }
1150+ }
1151+
1152+ // Auto theme-color meta from @theme primary token
1153+ let theme_color_html = doc
1154+ .theme_tokens
1155+ .iter()
1156+ .find(|(name, _)| name == "primary" || name == "theme-color")
1157+ .map(|(_, value)| {
1158+ if dev {
1159+ format!(
1160+ "<meta name=\"theme-color\" content=\"{}\">\n",
1161+ html_escape(value)
1162+ )
1163+ } else {
1164+ format!(
1165+ "<meta name=\"theme-color\" content=\"{}\">",
1166+ html_escape(value)
1167+ )
1168+ }
1169+ })
1170+ .unwrap_or_default();
1171+
1172+ // Focus-visible CSS for interactive elements (accessibility)
1173+ let focus_visible_css = if ctx.has_interactive {
1174+ if dev {
1175+ "a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }\n"
1176+ } else {
1177+ "a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid currentColor;outline-offset:2px}"
1178+ }
1179+ } else {
1180+ ""
1181+ };
1182+
1183+ // Skip-to-content CSS (visually hidden but accessible)
1184+ let skip_link_css = if has_main {
1185+ if dev {
1186+ ".hl-skip { position: absolute; left: -9999px; top: auto; width: 1px; height: 1px; overflow: hidden; z-index: 9999; padding: 8px 16px; background: #000; color: #fff; text-decoration: none; font-size: 14px; }\n.hl-skip:focus { left: 8px; top: 8px; width: auto; height: auto; overflow: visible; }\n"
1187+ } else {
1188+ ".hl-skip{position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden;z-index:9999;padding:8px 16px;background:#000;color:#fff;text-decoration:none;font-size:14px}.hl-skip:focus{left:8px;top:8px;width:auto;height:auto;overflow:visible}"
1189+ }
10831190 } else {
1084− format!("@layer {};@layer hl-reset{{{}}}", LAYERS.join(","), rules)
1191+ ""
1192+ };
1193+
1194+ // Noscript fallback: show deferred content if JS is disabled
1195+ let noscript_html = if ctx.has_defer {
1196+ if dev {
1197+ "<noscript><style>.hl-defer-placeholder { display: none; }</style></noscript>\n"
1198+ } else {
1199+ "<noscript><style>.hl-defer-placeholder{display:none}</style></noscript>"
1200+ }
1201+ } else {
1202+ ""
1203+ };
1204+
1205+ match &doc.page_title {
1206+ Some(title) => {
1207+ if dev {
1208+ format!(
1209+ "\
1210+<!DOCTYPE html>
1211+<html{lang_attr}>
1212+<head>
1213+<meta charset=\"utf-8\">
1214+<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
1215+<title>{title}</title>
1216+{theme_color_html}{base_html}{canonical_html}{manifest_html}{preload_html}{dns_prefetch_html}{meta_html}{og_html}{favicon_html}{json_ld_html}{head_html}\
1217+<style>
1218+*, *::before, *::after {{ box-sizing: border-box; }}
1219+body {{ margin: 0; font-family: system-ui, -apple-system, sans-serif; }}
1220+img {{ display: block; }}
1221+{focus_visible_css}{skip_link_css}{element_css}\
1222+</style>
1223+{noscript_html}\
1224+</head>
1225+<body>
1226+{body}\
1227+</body>
1228+</html>
1229+",
1230+ title = html_escape(title),
1231+ lang_attr = lang_attr,
1232+ theme_color_html = theme_color_html,
1233+ base_html = base_html,
1234+ canonical_html = canonical_html,
1235+ manifest_html = manifest_html,
1236+ preload_html = preload_html,
1237+ dns_prefetch_html = dns_prefetch_html,
1238+ meta_html = meta_html,
1239+ favicon_html = favicon_html,
1240+ json_ld_html = json_ld_html,
1241+ head_html = head_html,
1242+ og_html = og_html,
1243+ focus_visible_css = focus_visible_css,
1244+ skip_link_css = skip_link_css,
1245+ noscript_html = noscript_html,
1246+ element_css = element_css,
1247+ body = body,
1248+ )
1249+ } else {
1250+ format!(
1251+ "<!DOCTYPE html><html{lang_attr}><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>{title}</title>{theme_color_html}{base_html}{canonical_html}{manifest_html}{preload_html}{dns_prefetch_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}}{focus_visible_css}{skip_link_css}{element_css}</style>{noscript_html}</head><body>{body}</body></html>",
1252+ title = html_escape(title),
1253+ lang_attr = lang_attr,
1254+ theme_color_html = theme_color_html,
1255+ base_html = base_html,
1256+ canonical_html = canonical_html,
1257+ manifest_html = manifest_html,
1258+ preload_html = preload_html,
1259+ dns_prefetch_html = dns_prefetch_html,
1260+ meta_html = meta_html,
1261+ og_html = og_html,
1262+ favicon_html = favicon_html,
1263+ json_ld_html = json_ld_html,
1264+ head_html = head_html,
1265+ focus_visible_css = focus_visible_css,
1266+ skip_link_css = skip_link_css,
1267+ noscript_html = noscript_html,
1268+ element_css = element_css,
1269+ body = body,
1270+ )
1271+ }
1272+ }
1273+ None => {
1274+ if element_css.is_empty() {
1275+ body
1276+ } else if dev {
1277+ format!("<style>\n{}</style>\n{}", element_css, body)
1278+ } else {
1279+ format!("<style>{}</style>{}", element_css, body)
1280+ }
1281+ }
10851282 }
10861283}
10871284
10881285/// 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 {
1286+fn generate_partial_inner(doc: &Document, dev: bool) -> String {
10901287 let mut styles = StyleCollector::new();
10911288 let mut ctx = GenContext {
10921289 dev,
10931290 depth: 0,
1291+ image_count: 0,
10941292 has_interactive: false,
1095− in_text: false,
1096− flow: Flow::default(),
1097− in_picture: false,
1293+ has_defer: false,
10981294 };
10991295 let mut body = String::new();
11001296
1101− generate_children(&doc.nodes, None, &mut body, &mut styles, &mut ctx);
1297+ for node in &doc.nodes {
1298+ generate_node(node, None, &mut body, &mut styles, &mut ctx);
1299+ }
1300+
1301+ let has_custom_css = !doc.custom_css.is_empty();
1302+ let mut element_css = String::new();
1303+
1304+ let mut root_vars: Vec<(String, String)> = Vec::new();
1305+ for (name, value) in &doc.css_vars {
1306+ root_vars.push((name.clone(), value.clone()));
1307+ }
1308+ for (name, value) in &doc.theme_tokens {
1309+ let css_name = format!("--{}", name);
1310+ if !root_vars.iter().any(|(n, _)| *n == css_name) {
1311+ root_vars.push((css_name, value.clone()));
1312+ }
1313+ }
1314+
1315+ let styles_css = styles.to_css_formatted(dev, !has_custom_css);
1316+ let styles_css = substitute_css_vars(&styles_css, &root_vars);
1317+ let styles_css = if dev {
1318+ styles_css
1319+ } else {
1320+ let (new_css, auto_vars) = auto_extract_repeats(&styles_css, &root_vars);
1321+ root_vars.extend(auto_vars);
1322+ new_css
1323+ };
1324+
1325+ if !root_vars.is_empty() {
1326+ if dev {
1327+ element_css.push_str(":root {\n");
1328+ for (name, value) in &root_vars {
1329+ element_css.push_str(&format!(" {}: {};\n", name, value));
1330+ }
1331+ element_css.push_str("}\n");
1332+ } else {
1333+ element_css.push_str(":root{");
1334+ for (name, value) in &root_vars {
1335+ element_css.push_str(name);
1336+ element_css.push(':');
1337+ element_css.push_str(value);
1338+ element_css.push(';');
1339+ }
1340+ element_css.push('}');
1341+ }
1342+ }
1343+
1344+ element_css.push_str(&styles_css);
1345+
1346+ for (name, kf_body) in &doc.keyframes {
1347+ if dev {
1348+ element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1349+ } else {
1350+ element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1351+ }
1352+ }
11021353
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, ""));
1354+ for block in &doc.custom_css {
1355+ if dev {
1356+ element_css.push_str(block);
1357+ element_css.push('\n');
1358+ } else {
1359+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1360+ element_css.push_str(&minified);
1361+ }
11081362 }
1109− classes.extend(styles.classes());
11101363
11111364 if element_css.is_empty() {
11121365 body
@@ -1121,20 +1374,44 @@ fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -
11211374// Node generation
11221375// ---------------------------------------------------------------------------
11231376
1124−/// Write `node`, which is inside an element with the layout `parent`
1125−/// (`None` at the top of the page).
11261377fn generate_node(
11271378 node: &Node,
1128− parent: Option<Layout>,
1379+ parent_kind: Option<&ElementKind>,
11291380 out: &mut String,
11301381 styles: &mut StyleCollector,
11311382 ctx: &mut GenContext,
11321383) {
11331384 match node {
1134− Node::Element(elem) => generate_element(elem, parent, out, styles, ctx),
1385+ Node::Element(elem) => generate_element(elem, parent_kind, out, styles, ctx),
11351386 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);
1387+ let needs_wrap = matches!(
1388+ parent_kind,
1389+ Some(ElementKind::Row)
1390+ | Some(ElementKind::Column)
1391+ | Some(ElementKind::El)
1392+ | Some(ElementKind::Nav)
1393+ | Some(ElementKind::Header)
1394+ | Some(ElementKind::Footer)
1395+ | Some(ElementKind::Main)
1396+ | Some(ElementKind::Section)
1397+ | Some(ElementKind::Article)
1398+ | Some(ElementKind::Aside)
1399+ | Some(ElementKind::ListItem)
1400+ | Some(ElementKind::Form)
1401+ | Some(ElementKind::Details)
1402+ | Some(ElementKind::Figure)
1403+ | Some(ElementKind::Blockquote)
1404+ | Some(ElementKind::Dialog)
1405+ | Some(ElementKind::DefinitionList)
1406+ | Some(ElementKind::DefinitionDescription)
1407+ | Some(ElementKind::Fieldset)
1408+ | Some(ElementKind::Datalist)
1409+ | Some(ElementKind::Grid)
1410+ | Some(ElementKind::Stack)
1411+ | Some(ElementKind::Noscript)
1412+ | Some(ElementKind::Address)
1413+ | Some(ElementKind::Search)
1414+ );
11381415 if needs_wrap {
11391416 out.push_str(&ctx.indent());
11401417 out.push_str("<span>");
@@ -1153,191 +1430,195 @@ fn generate_node(
11531430 }
11541431}
11551432
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−}
1433+/// HTML attributes that are passed through to the HTML tag rather than converted to CSS.
1434+const HTML_PASSTHROUGH_ATTRS: &[&str] = &[
1435+ "type",
1436+ "placeholder",
1437+ "name",
1438+ "value",
1439+ "disabled",
1440+ "required",
1441+ "checked",
1442+ "for",
1443+ "action",
1444+ "method",
1445+ "autocomplete",
1446+ "min",
1447+ "max",
1448+ "step",
1449+ "pattern",
1450+ "maxlength",
1451+ "rows",
1452+ "cols",
1453+ "multiple",
1454+ "alt",
1455+ "role",
1456+ "tabindex",
1457+ "title",
1458+ "autofocus",
1459+ // Media
1460+ "controls",
1461+ "autoplay",
1462+ "loop",
1463+ "muted",
1464+ "poster",
1465+ "preload",
1466+ // Image optimization
1467+ "loading",
1468+ "decoding",
1469+ // Media src (explicit attribute form)
1470+ "src",
1471+ // New element attributes
1472+ "datetime",
1473+ "media",
1474+ "sizes",
1475+ "srcset",
1476+ "list",
1477+ // Details
1478+ "open",
1479+ // Form
1480+ "novalidate",
1481+ // Progress/Meter
1482+ "low",
1483+ "high",
1484+ "optimum",
1485+ // Table
1486+ "colspan",
1487+ "rowspan",
1488+ "scope",
1489+ // Popover API
1490+ "popover",
1491+ "popovertarget",
1492+ "popovertargetaction",
1493+ // Modern form/input hints
1494+ "inputmode",
1495+ "enterkeyhint",
1496+ // Performance hints
1497+ "fetchpriority",
1498+ "blocking",
1499+ // Global attrs
1500+ "translate",
1501+ "spellcheck",
1502+ // ARIA live regions
1503+ "aria-live",
1504+ "aria-atomic",
1505+ "aria-relevant",
1506+];
11701507
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−}
1508+/// Boolean HTML attributes (rendered without a value, e.g., `<input disabled>`).
1509+const BOOLEAN_HTML_ATTRS: &[&str] = &[
1510+ "disabled",
1511+ "required",
1512+ "checked",
1513+ "multiple",
1514+ "controls",
1515+ "autoplay",
1516+ "loop",
1517+ "muted",
1518+ "open",
1519+ "novalidate",
1520+ "autofocus",
1521+ "defer",
1522+ "async",
1523+ "nomodule",
1524+ // Popover
1525+ "popover",
1526+];
11831527
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);
1528+fn emit_html_passthrough_attrs(out: &mut String, attrs: &[Attribute]) {
1529+ for attr in attrs {
1530+ let key = attr.key.as_str();
1531+ let is_passthrough = HTML_PASSTHROUGH_ATTRS.contains(&key)
1532+ || key.starts_with("aria-")
1533+ || key.starts_with("data-");
1534+ if !is_passthrough {
12011535 continue;
12021536 }
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);
1215− continue;
1537+ if BOOLEAN_HTML_ATTRS.contains(&key) && attr.value.is_none() {
1538+ out.push(' ');
1539+ out.push_str(key);
1540+ } else if let Some(val) = &attr.value {
1541+ out.push(' ');
1542+ out.push_str(key);
1543+ out.push_str("=\"");
1544+ out.push_str(&html_escape(strip_string_quotes(val)));
1545+ out.push('"');
12161546 }
1217− *previous = Some(matches!(child, Node::Text(_)));
12181547 }
12191548}
12201549
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);
1266− }
1550+/// If the value is wrapped in a single pair of matching quotes (e.g.
1551+/// `"Avatar"`), return the inner content. Quotes act as source-level
1552+/// delimiters in the `.hl` syntax and shouldn't leak into HTML attribute
1553+/// values. Multi-quoted values like `"h h" "s m"` are left unchanged —
1554+/// those are real string tokens (used e.g. by CSS `grid-template-areas`).
1555+fn strip_string_quotes(val: &str) -> &str {
1556+ let bytes = val.as_bytes();
1557+ if bytes.len() < 2 {
1558+ return val;
12671559 }
1268−}
1269−
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('"');
1560+ let first = bytes[0];
1561+ let last = bytes[bytes.len() - 1];
1562+ if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
1563+ let inner = &val[1..val.len() - 1];
1564+ if !inner.as_bytes().contains(&first) {
1565+ return inner;
1566+ }
12941567 }
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− })
1568+ val
13111569}
13121570
13131571fn generate_element(
13141572 elem: &Element,
1315− parent: Option<Layout>,
1573+ parent_kind: Option<&ElementKind>,
13161574 out: &mut String,
13171575 styles: &mut StyleCollector,
13181576 ctx: &mut GenContext,
13191577) {
13201578 // Self-closing elements
1321− if elem.kind.layout() == Layout::Void {
1322− generate_self_closing(elem, parent, out, styles, ctx);
1579+ if matches!(
1580+ elem.kind,
1581+ ElementKind::Image
1582+ | ElementKind::Input
1583+ | ElementKind::HorizontalRule
1584+ | ElementKind::Source
1585+ | ElementKind::Spacer
1586+ ) {
1587+ generate_self_closing(elem, parent_kind, out, styles, ctx);
13231588 return;
13241589 }
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);
1590+ // @script renders as <script> with raw body content (no HTML escaping)
1591+ if elem.kind == ElementKind::Script {
13291592 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)));
1593+ out.push_str("<script");
1594+ // Pass through src, type, defer, async, etc.
1595+ for attr in &elem.attrs {
1596+ let key = attr.key.as_str();
1597+ if matches!(
1598+ key,
1599+ "src"
1600+ | "type"
1601+ | "defer"
1602+ | "async"
1603+ | "crossorigin"
1604+ | "integrity"
1605+ | "nomodule"
1606+ | "id"
1607+ ) {
1608+ if let Some(val) = &attr.value {
1609+ out.push(' ');
1610+ out.push_str(key);
1611+ out.push_str("=\"");
1612+ out.push_str(&html_escape(val));
1613+ out.push('"');
1614+ } else {
1615+ out.push(' ');
1616+ out.push_str(key);
1617+ }
13371618 }
13381619 }
1339− emit_html_attrs(out, &elem.attrs);
13401620 out.push('>');
1621+ // Children are raw JS code, not HTML
13411622 for child in &elem.children {
13421623 match child {
13431624 Node::Text(segments) => {
@@ -1351,10 +1632,46 @@ fn generate_element(
13511632 _ => {}
13521633 }
13531634 }
1354− out.push_str("</");
1355− out.push_str(tag);
1635+ out.push_str("</script>");
1636+ out.push_str(ctx.nl());
1637+ return;
1638+ }
1639+ // @breadcrumb generates semantic <nav aria-label="breadcrumb"><ol>...</ol></nav>
1640+ if elem.kind == ElementKind::Breadcrumb {
1641+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
1642+ let (id, user_class) = extract_id_class(&elem.attrs);
1643+ out.push_str(&ctx.indent());
1644+ out.push_str("<nav aria-label=\"breadcrumb\"");
1645+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1646+ if let Some(id) = id {
1647+ out.push_str(" id=\"");
1648+ out.push_str(&html_escape(&id));
1649+ out.push('"');
1650+ }
13561651 out.push('>');
13571652 out.push_str(ctx.nl());
1653+ ctx.depth += 1;
1654+ out.push_str(&ctx.indent());
1655+ out.push_str("<ol>");
1656+ out.push_str(ctx.nl());
1657+ ctx.depth += 1;
1658+ for child in &elem.children {
1659+ out.push_str(&ctx.indent());
1660+ out.push_str("<li>");
1661+ let mut buf = String::new();
1662+ generate_node(child, Some(&elem.kind), &mut buf, styles, ctx);
1663+ out.push_str(buf.trim());
1664+ out.push_str("</li>");
1665+ out.push_str(ctx.nl());
1666+ }
1667+ ctx.depth -= 1;
1668+ out.push_str(&ctx.indent());
1669+ out.push_str("</ol>");
1670+ out.push_str(ctx.nl());
1671+ ctx.depth -= 1;
1672+ out.push_str(&ctx.indent());
1673+ out.push_str("</nav>");
1674+ out.push_str(ctx.nl());
13581675 return;
13591676 }
13601677 if elem.kind == ElementKind::Children {
@@ -1364,38 +1681,185 @@ fn generate_element(
13641681 return;
13651682 }
13661683 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);
1684+ // Render children without a wrapper element
1685+ for child in &elem.children {
1686+ generate_node(child, parent_kind, out, styles, ctx);
1687+ }
13701688 return;
13711689 }
13721690
1373− let mut own = Flow::of(elem);
13741691 let tag = match &elem.kind {
1375− ElementKind::Row | ElementKind::El => "div",
1692+ ElementKind::Row
1693+ | ElementKind::Column
1694+ | ElementKind::El
1695+ | ElementKind::Grid
1696+ | ElementKind::Stack => "div",
13761697 ElementKind::Text => "span",
13771698 ElementKind::Paragraph => "p",
13781699 ElementKind::Link => "a",
1379− ElementKind::Tag(spec) => spec.html,
1700+ ElementKind::Button => "button",
1701+ ElementKind::Select => "select",
1702+ ElementKind::Textarea => "textarea",
1703+ ElementKind::Option => "option",
1704+ ElementKind::Label => "label",
1705+ // Semantic elements
1706+ ElementKind::Nav => "nav",
1707+ ElementKind::Header => "header",
1708+ ElementKind::Footer => "footer",
1709+ ElementKind::Main => "main",
1710+ ElementKind::Section => "section",
1711+ ElementKind::Article => "article",
1712+ ElementKind::Aside => "aside",
1713+ // List
1714+ ElementKind::List => {
1715+ if elem.attrs.iter().any(|a| a.key == "ordered") {
1716+ "ol"
1717+ } else {
1718+ "ul"
1719+ }
1720+ }
1721+ ElementKind::ListItem => "li",
1722+ // Table
1723+ ElementKind::Table => "table",
1724+ ElementKind::TableHead => "thead",
1725+ ElementKind::TableBody => "tbody",
1726+ ElementKind::TableRow => "tr",
1727+ ElementKind::TableCell => "td",
1728+ ElementKind::TableHeaderCell => "th",
1729+ // Media
1730+ ElementKind::Video => "video",
1731+ ElementKind::Audio => "audio",
1732+ // Additional semantic elements
1733+ ElementKind::Form => "form",
1734+ ElementKind::Details => "details",
1735+ ElementKind::Summary => "summary",
1736+ ElementKind::Blockquote => "blockquote",
1737+ ElementKind::Cite => "cite",
1738+ ElementKind::Code => "code",
1739+ ElementKind::Pre => "pre",
1740+ ElementKind::Figure => "figure",
1741+ ElementKind::FigCaption => "figcaption",
1742+ ElementKind::Progress => "progress",
1743+ ElementKind::Meter => "meter",
1744+ // New elements
1745+ ElementKind::Dialog => "dialog",
1746+ ElementKind::DefinitionList => "dl",
1747+ ElementKind::DefinitionTerm => "dt",
1748+ ElementKind::DefinitionDescription => "dd",
1749+ ElementKind::Fieldset => "fieldset",
1750+ ElementKind::Legend => "legend",
1751+ ElementKind::Picture => "picture",
1752+ ElementKind::Time => "time",
1753+ ElementKind::Mark => "mark",
1754+ ElementKind::Kbd => "kbd",
1755+ ElementKind::Abbr => "abbr",
1756+ ElementKind::Datalist => "datalist",
1757+ ElementKind::Iframe => "iframe",
1758+ ElementKind::Output => "output",
1759+ ElementKind::Canvas => "canvas",
1760+ ElementKind::Badge => "span",
1761+ ElementKind::Tooltip => "span",
1762+ ElementKind::Avatar => "div",
1763+ ElementKind::Carousel => "div",
1764+ ElementKind::Chip => "span",
1765+ ElementKind::Tag => "span",
1766+ ElementKind::Noscript => "noscript",
1767+ ElementKind::Address => "address",
1768+ ElementKind::Search => "search",
1769+ ElementKind::Image
1770+ | ElementKind::Input
1771+ | ElementKind::HorizontalRule
1772+ | ElementKind::Children
1773+ | ElementKind::Slot(_)
1774+ | ElementKind::Fragment
1775+ | ElementKind::Source
1776+ | ElementKind::Spacer
1777+ | ElementKind::Script
1778+ | ElementKind::Breadcrumb => unreachable!(),
1779+ };
1780+
1781+ let kind_label = match elem.kind {
1782+ ElementKind::Row => "row",
1783+ ElementKind::Column => "column",
1784+ ElementKind::El => "el",
1785+ ElementKind::Text => "text",
1786+ ElementKind::Paragraph => "paragraph",
1787+ ElementKind::Link => "link",
1788+ ElementKind::Button => "button",
1789+ ElementKind::Select => "select",
1790+ ElementKind::Textarea => "textarea",
1791+ ElementKind::Option => "option",
1792+ ElementKind::Label => "label",
1793+ ElementKind::Nav => "nav",
1794+ ElementKind::Header => "header",
1795+ ElementKind::Footer => "footer",
1796+ ElementKind::Main => "main",
1797+ ElementKind::Section => "section",
1798+ ElementKind::Article => "article",
1799+ ElementKind::Aside => "aside",
1800+ ElementKind::List => "list",
1801+ ElementKind::ListItem => "item",
1802+ ElementKind::Table => "table",
1803+ ElementKind::TableHead => "thead",
1804+ ElementKind::TableBody => "tbody",
1805+ ElementKind::TableRow => "tr",
1806+ ElementKind::TableCell => "td",
1807+ ElementKind::TableHeaderCell => "th",
1808+ ElementKind::Video => "video",
1809+ ElementKind::Audio => "audio",
1810+ ElementKind::Form => "form",
1811+ ElementKind::Details => "details",
1812+ ElementKind::Summary => "summary",
1813+ ElementKind::Blockquote => "blockquote",
1814+ ElementKind::Cite => "cite",
1815+ ElementKind::Code => "code",
1816+ ElementKind::Pre => "pre",
1817+ ElementKind::Figure => "figure",
1818+ ElementKind::FigCaption => "figcaption",
1819+ ElementKind::Fragment => "fragment",
1820+ ElementKind::Dialog => "dialog",
1821+ ElementKind::DefinitionList => "dl",
1822+ ElementKind::DefinitionTerm => "dt",
1823+ ElementKind::DefinitionDescription => "dd",
1824+ ElementKind::Fieldset => "fieldset",
1825+ ElementKind::Legend => "legend",
1826+ ElementKind::Picture => "picture",
1827+ ElementKind::Time => "time",
1828+ ElementKind::Mark => "mark",
1829+ ElementKind::Kbd => "kbd",
1830+ ElementKind::Abbr => "abbr",
1831+ ElementKind::Datalist => "datalist",
1832+ ElementKind::Iframe => "iframe",
1833+ ElementKind::Output => "output",
1834+ ElementKind::Canvas => "canvas",
1835+ ElementKind::Grid => "grid",
1836+ ElementKind::Stack => "stack",
1837+ ElementKind::Badge => "badge",
1838+ ElementKind::Tooltip => "tooltip",
1839+ ElementKind::Avatar => "avatar",
1840+ ElementKind::Carousel => "carousel",
1841+ ElementKind::Chip => "chip",
1842+ ElementKind::Tag => "tag",
1843+ ElementKind::Noscript => "noscript",
1844+ ElementKind::Address => "address",
1845+ ElementKind::Search => "search",
13801846 _ => "",
13811847 };
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();
13881848
13891849 // Track interactive elements for focus-visible CSS
1390− if elem.kind == ElementKind::Link
1391− || matches!(kind_label, "button" | "input" | "select" | "textarea")
1392− {
1850+ if matches!(
1851+ elem.kind,
1852+ ElementKind::Link
1853+ | ElementKind::Button
1854+ | ElementKind::Input
1855+ | ElementKind::Select
1856+ | ElementKind::Textarea
1857+ ) {
13931858 ctx.has_interactive = true;
13941859 }
13951860
13961861 // 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();
1862+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
13991863 let (id, user_class) = extract_id_class(&elem.attrs);
14001864
14011865 if ctx.dev && elem.line_num > 0 {
@@ -1409,17 +1873,93 @@ fn generate_element(
14091873 out.push('<');
14101874 out.push_str(tag);
14111875
1412− emit_argument_attr(out, elem, ctx.in_picture);
1413−
1414− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1415−
1416− if let Some(id) = id {
1417− out.push_str(" id=\"");
1418− out.push_str(&html_escape(&id));
1419− out.push('"');
1876+ // @main gets id="hl-main" for skip-to-content link (unless user set an id)
1877+ if elem.kind == ElementKind::Main && id.is_none() {
1878+ out.push_str(" id=\"hl-main\"");
14201879 }
14211880
1422− emit_html_attrs(out, &elem.attrs);
1881+ if elem.kind == ElementKind::Link
1882+ && let Some(url) = &elem.argument
1883+ {
1884+ out.push_str(" href=\"");
1885+ out.push_str(&html_escape(url));
1886+ out.push('"');
1887+ // Auto rel="noopener noreferrer" and target="_blank" for external links
1888+ let is_external = url.starts_with("http://") || url.starts_with("https://");
1889+ if is_external {
1890+ let has_rel = elem.attrs.iter().any(|a| a.key == "rel");
1891+ let has_target = elem.attrs.iter().any(|a| a.key == "target");
1892+ if !has_rel {
1893+ out.push_str(" rel=\"noopener noreferrer\"");
1894+ }
1895+ if !has_target {
1896+ out.push_str(" target=\"_blank\"");
1897+ }
1898+ }
1899+ }
1900+
1901+ // Video/Audio src
1902+ if matches!(elem.kind, ElementKind::Video | ElementKind::Audio)
1903+ && let Some(src) = &elem.argument
1904+ {
1905+ out.push_str(" src=\"");
1906+ out.push_str(&html_escape(src));
1907+ out.push('"');
1908+ }
1909+
1910+ // Form action
1911+ if elem.kind == ElementKind::Form
1912+ && let Some(action) = &elem.argument
1913+ {
1914+ out.push_str(" action=\"");
1915+ out.push_str(&html_escape(action));
1916+ out.push('"');
1917+ }
1918+
1919+ // Iframe src
1920+ if elem.kind == ElementKind::Iframe
1921+ && let Some(src) = &elem.argument
1922+ {
1923+ out.push_str(" src=\"");
1924+ out.push_str(&html_escape(src));
1925+ out.push('"');
1926+ }
1927+
1928+ // Tooltip title
1929+ if elem.kind == ElementKind::Tooltip
1930+ && let Some(text) = &elem.argument
1931+ {
1932+ out.push_str(" title=\"");
1933+ out.push_str(&html_escape(text));
1934+ out.push('"');
1935+ }
1936+
1937+ // Critical CSS: inline styles directly instead of using a class
1938+ let is_critical = elem.attrs.iter().any(|a| a.key == "critical");
1939+ if is_critical {
1940+ let inline_css = attrs_to_css(&elem.attrs, "", &elem.kind, parent_kind);
1941+ if !inline_css.is_empty() {
1942+ out.push_str(" style=\"");
1943+ out.push_str(&html_escape(&inline_css));
1944+ out.push('"');
1945+ }
1946+ // Still use class for non-base styles (pseudo, responsive, etc.)
1947+ if gen_class.as_deref().is_some_and(|c| !c.is_empty()) {
1948+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1949+ } else if let Some(ref uc) = user_class {
1950+ emit_class_attr(out, None, Some(uc));
1951+ }
1952+ } else {
1953+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1954+ }
1955+
1956+ if let Some(id) = id {
1957+ out.push_str(" id=\"");
1958+ out.push_str(&html_escape(&id));
1959+ out.push('"');
1960+ }
1961+
1962+ emit_html_passthrough_attrs(out, &elem.attrs);
14231963
14241964 // Source map attributes in dev mode
14251965 if ctx.dev && elem.line_num > 0 {
@@ -1430,27 +1970,51 @@ fn generate_element(
14301970 }
14311971
14321972 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");
14381973 out.push_str(ctx.nl());
14391974
1440− let layout = elem.kind.layout();
1975+ // Inline text argument
1976+ if matches!(
1977+ elem.kind,
1978+ ElementKind::Text
1979+ | ElementKind::Button
1980+ | ElementKind::Label
1981+ | ElementKind::Option
1982+ | ElementKind::Textarea
1983+ | ElementKind::ListItem
1984+ | ElementKind::TableCell
1985+ | ElementKind::TableHeaderCell
1986+ | ElementKind::Summary
1987+ | ElementKind::Cite
1988+ | ElementKind::Code
1989+ | ElementKind::FigCaption
1990+ | ElementKind::Legend
1991+ | ElementKind::DefinitionTerm
1992+ | ElementKind::Mark
1993+ | ElementKind::Kbd
1994+ | ElementKind::Abbr
1995+ | ElementKind::Time
1996+ | ElementKind::DefinitionDescription
1997+ | ElementKind::Badge
1998+ | ElementKind::Tooltip
1999+ | ElementKind::Chip
2000+ | ElementKind::Tag
2001+ ) && let Some(text) = &elem.argument
2002+ {
2003+ out.push_str(&html_escape(text));
2004+ }
2005+
2006+ // Children
14412007 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;
2008+ let is_paragraph = elem.kind == ElementKind::Paragraph;
2009+ for (i, child) in elem.children.iter().enumerate() {
2010+ generate_node(child, Some(&elem.kind), out, styles, ctx);
2011+ if is_paragraph && i < elem.children.len() - 1 {
2012+ out.push(' ');
2013+ }
2014+ }
14502015 ctx.depth -= 1;
14512016
14522017 out.push_str(&ctx.indent());
1453− ctx.dev = outer_dev;
14542018 out.push_str("</");
14552019 out.push_str(tag);
14562020 out.push('>');
@@ -1459,18 +2023,21 @@ fn generate_element(
14592023
14602024fn generate_self_closing(
14612025 elem: &Element,
1462− parent: Option<Layout>,
2026+ parent_kind: Option<&ElementKind>,
14632027 out: &mut String,
14642028 styles: &mut StyleCollector,
14652029 ctx: &mut GenContext,
14662030) {
1467− let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
2031+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
14682032 let (id, user_class) = extract_id_class(&elem.attrs);
14692033
1470− let (tag, kind_label) = match &elem.kind {
2034+ let (tag, kind_label) = match elem.kind {
14712035 ElementKind::Image => ("img", "image"),
1472− ElementKind::Tag(spec) => (spec.html, spec.name),
1473− _ => unreachable!("not a void element: {:?}", elem.kind),
2036+ ElementKind::Input => ("input", "input"),
2037+ ElementKind::HorizontalRule => ("hr", "hr"),
2038+ ElementKind::Source => ("source", "source"),
2039+ ElementKind::Spacer => ("div", "spacer"),
2040+ _ => unreachable!(),
14742041 };
14752042
14762043 if ctx.dev && elem.line_num > 0 {
@@ -1483,7 +2050,43 @@ fn generate_self_closing(
14832050 out.push_str(&ctx.indent());
14842051 out.push('<');
14852052 out.push_str(tag);
1486− emit_argument_attr(out, elem, ctx.in_picture);
2053+
2054+ // Image src (with optional non-SVG base64 inlining)
2055+ if elem.kind == ElementKind::Image {
2056+ let src = elem.argument.as_deref().unwrap_or("");
2057+ let is_inline = elem.attrs.iter().any(|a| a.key == "inline");
2058+ if is_inline && !src.is_empty() && !src.ends_with(".svg") {
2059+ let mime = if src.ends_with(".png") {
2060+ "image/png"
2061+ } else if src.ends_with(".jpg") || src.ends_with(".jpeg") {
2062+ "image/jpeg"
2063+ } else if src.ends_with(".gif") {
2064+ "image/gif"
2065+ } else if src.ends_with(".webp") {
2066+ "image/webp"
2067+ } else if src.ends_with(".avif") {
2068+ "image/avif"
2069+ } else {
2070+ "application/octet-stream"
2071+ };
2072+ if let Ok(data) = std::fs::read(src) {
2073+ let b64 = base64_encode(&data);
2074+ out.push_str(" src=\"data:");
2075+ out.push_str(mime);
2076+ out.push_str(";base64,");
2077+ out.push_str(&b64);
2078+ out.push('"');
2079+ } else {
2080+ out.push_str(" src=\"");
2081+ out.push_str(&html_escape(src));
2082+ out.push('"');
2083+ }
2084+ } else {
2085+ out.push_str(" src=\"");
2086+ out.push_str(&html_escape(src));
2087+ out.push('"');
2088+ }
2089+ }
14872090
14882091 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
14892092
@@ -1493,7 +2096,7 @@ fn generate_self_closing(
14932096 out.push('"');
14942097 }
14952098
1496− emit_html_attrs(out, &elem.attrs);
2099+ emit_html_passthrough_attrs(out, &elem.attrs);
14972100
14982101 // Source map attributes in dev mode (self-closing)
14992102 if ctx.dev && elem.line_num > 0 {
@@ -1503,6 +2106,93 @@ fn generate_self_closing(
15032106 ));
15042107 }
15052108
2109+ // Image optimization: auto-add loading="lazy" and decoding="async"
2110+ if elem.kind == ElementKind::Image {
2111+ // SVG inlining: @image [inline] logo.svg
2112+ if elem.attrs.iter().any(|a| a.key == "inline")
2113+ && let Some(src) = &elem.argument
2114+ && src.ends_with(".svg")
2115+ && let Ok(svg_content) = std::fs::read_to_string(src)
2116+ {
2117+ // Close the tag we opened, then emit inline SVG instead
2118+ out.truncate(out.rfind('<').unwrap_or(0));
2119+ out.push_str(&ctx.indent());
2120+ out.push_str(svg_content.trim());
2121+ out.push_str(ctx.nl());
2122+ return;
2123+ }
2124+ // Responsive srcset: @image photo.jpg [responsive 400 800 1200]
2125+ let responsive_attr = elem.attrs.iter().find(|a| a.key == "responsive");
2126+ if let Some(resp) = responsive_attr
2127+ && let Some(ref sizes_str) = resp.value
2128+ {
2129+ let widths: Vec<&str> = sizes_str.split_whitespace().collect();
2130+ if !widths.is_empty() {
2131+ let src = elem.argument.as_deref().unwrap_or("");
2132+ if !src.is_empty() {
2133+ // Generate srcset with width descriptors
2134+ // Convention: file-{width}.ext (e.g., photo-400.jpg)
2135+ let dot_pos = src.rfind('.').unwrap_or(src.len());
2136+ let base = &src[..dot_pos];
2137+ let ext = &src[dot_pos..];
2138+ let mut srcset_parts = Vec::new();
2139+ for w in &widths {
2140+ srcset_parts.push(format!("{}-{}{} {}w", base, w, ext, w));
2141+ }
2142+ out.push_str(" srcset=\"");
2143+ out.push_str(&srcset_parts.join(", "));
2144+ out.push('"');
2145+ // Generate sizes attribute
2146+ let max_width = widths.last().unwrap_or(&"100vw");
2147+ out.push_str(&format!(
2148+ " sizes=\"(max-width: {}px) 100vw, {}px\"",
2149+ max_width, max_width
2150+ ));
2151+ }
2152+ }
2153+ }
2154+
2155+ // Auto image dimensions: read local image file to inject width/height + aspect-ratio
2156+ let has_width = elem.attrs.iter().any(|a| a.key == "width");
2157+ let has_height = elem.attrs.iter().any(|a| a.key == "height");
2158+ if (!has_width || !has_height)
2159+ && let Some(ref src) = elem.argument
2160+ && !src.starts_with("http://")
2161+ && !src.starts_with("https://")
2162+ && !src.starts_with("data:")
2163+ && let Some((w, h)) = read_image_dimensions(src)
2164+ {
2165+ if !has_width {
2166+ out.push_str(&format!(" width=\"{}\"", w));
2167+ }
2168+ if !has_height {
2169+ out.push_str(&format!(" height=\"{}\"", h));
2170+ }
2171+ // Auto aspect-ratio to prevent CLS
2172+ if !elem.attrs.iter().any(|a| a.key == "aspect-ratio") {
2173+ out.push_str(&format!(" style=\"aspect-ratio:{}/{}\"", w, h));
2174+ }
2175+ }
2176+
2177+ // Smart image loading: first 3 images get fetchpriority="high" (above the fold),
2178+ // subsequent images get loading="lazy" + decoding="async"
2179+ ctx.image_count += 1;
2180+ if ctx.image_count <= 3 {
2181+ // Above-the-fold: eager loading with high priority
2182+ if !elem.attrs.iter().any(|a| a.key == "fetchpriority") {
2183+ out.push_str(" fetchpriority=\"high\"");
2184+ }
2185+ } else {
2186+ // Below-the-fold: lazy loading
2187+ if !elem.attrs.iter().any(|a| a.key == "loading") {
2188+ out.push_str(" loading=\"lazy\"");
2189+ }
2190+ if !elem.attrs.iter().any(|a| a.key == "decoding") {
2191+ out.push_str(" decoding=\"async\"");
2192+ }
2193+ }
2194+ }
2195+
15062196 out.push('>');
15072197 out.push_str(ctx.nl());
15082198}
@@ -1518,10 +2208,7 @@ fn generate_text_segments(
15182208 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
15192209 TextSegment::Inline(elem) => {
15202210 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;
2211+ generate_element(elem, None, &mut buf, styles, ctx);
15252212 out.push_str(buf.trim_end());
15262213 }
15272214 }
@@ -1534,97 +2221,141 @@ fn generate_text_segments(
15342221
15352222fn compute_class(
15362223 attrs: &[Attribute],
1537− site: &Site,
2224+ kind: &ElementKind,
2225+ parent_kind: Option<&ElementKind>,
15382226 styles: &mut StyleCollector,
1539− distinct: String,
15402227) -> 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);
2228+ let base = attrs_to_css(attrs, "", kind, parent_kind);
2229+
2230+ // Collect pseudo-state overrides
2231+ let mut pseudo = Vec::new();
2232+ for &(prefix, selector) in PSEUDO_PREFIXES {
2233+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2234+ if !css.is_empty() {
2235+ pseudo.push((selector.to_string(), css));
15472236 }
15482237 }
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−}
15722238
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;");
1581− }
1582− if !site.root {
1583− css.push_str(layout_css(site.kind.layout(), site.inline));
2239+ // Auto-add ::-webkit-scrollbar pseudo for no-scrollbar attribute
2240+ if attrs.iter().any(|a| a.key == "no-scrollbar") {
2241+ pseudo.push((
2242+ "::-webkit-scrollbar".to_string(),
2243+ "display:none;".to_string(),
2244+ ));
15842245 }
1585− css.push_str(site.kind.css());
1586− css
1587−}
15882246
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;
2247+ // Collect nth:EXPR: dynamic pseudo selectors
2248+ let mut nth_prefixes: Vec<String> = Vec::new();
2249+ for attr in attrs {
2250+ if attr.key.starts_with("nth:") {
2251+ let rest = &attr.key[4..];
2252+ if let Some(colon_pos) = rest.find(':') {
2253+ let prefix = format!("nth:{}:", &rest[..colon_pos]);
2254+ if !nth_prefixes.contains(&prefix) {
2255+ nth_prefixes.push(prefix);
16122256 }
1613− _ => {}
16142257 }
16152258 }
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− })
2259+ }
2260+ for prefix in &nth_prefixes {
2261+ let expr = &prefix[4..prefix.len() - 1];
2262+ let selector = format!(":nth-child({})", expr);
2263+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2264+ if !css.is_empty() {
2265+ pseudo.push((selector, css));
2266+ }
2267+ }
2268+
2269+ // Collect has(...): dynamic pseudo selectors
2270+ let mut has_prefixes: Vec<String> = Vec::new();
2271+ for attr in attrs {
2272+ if attr.key.starts_with("has(")
2273+ && let Some(close) = attr.key.find("):")
2274+ {
2275+ let prefix = format!("{}:", &attr.key[..close + 1]);
2276+ if !has_prefixes.contains(&prefix) {
2277+ has_prefixes.push(prefix);
2278+ }
2279+ }
2280+ }
2281+ for prefix in &has_prefixes {
2282+ let inner = &prefix[4..prefix.len() - 2]; // extract selector from has(selector):
2283+ let selector = format!(":has({})", inner);
2284+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2285+ if !css.is_empty() {
2286+ pseudo.push((selector, css));
2287+ }
2288+ }
2289+
2290+ // Collect responsive overrides
2291+ let mut responsive = Vec::new();
2292+ for &(bp_name, _) in BREAKPOINTS {
2293+ let prefix = format!("{}:", bp_name);
2294+ let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
2295+ if !css.is_empty() {
2296+ responsive.push((bp_name.to_string(), css));
2297+ }
2298+ }
2299+
2300+ // Collect container query overrides
2301+ let mut container = Vec::new();
2302+ for &(bp_name, _) in BREAKPOINTS {
2303+ let prefix = format!("cq-{}:", bp_name);
2304+ let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
2305+ if !css.is_empty() {
2306+ container.push((bp_name.to_string(), css));
2307+ }
2308+ }
2309+
2310+ let dark = attrs_to_css(attrs, "dark:", kind, parent_kind);
2311+ let print = attrs_to_css(attrs, "print:", kind, parent_kind);
2312+ let motion_safe = attrs_to_css(attrs, "motion-safe:", kind, parent_kind);
2313+ let motion_reduce = attrs_to_css(attrs, "motion-reduce:", kind, parent_kind);
2314+ let landscape = attrs_to_css(attrs, "landscape:", kind, parent_kind);
2315+ let portrait = attrs_to_css(attrs, "portrait:", kind, parent_kind);
2316+
2317+ // Dedupe: if a property is declared twice within a single rule, keep only
2318+ // the last occurrence (element-kind defaults are written before
2319+ // user attributes, so a user [list-style disc] correctly overrides the
2320+ // default list-style:none, and we don't need to ship both).
2321+ let base = dedupe_declarations(&base);
2322+ let pseudo: Vec<(String, String)> = pseudo
2323+ .into_iter()
2324+ .map(|(sel, css)| (sel, dedupe_declarations(&css)))
2325+ .collect();
2326+ let responsive: Vec<(String, String)> = responsive
2327+ .into_iter()
2328+ .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2329+ .collect();
2330+ let dark = dedupe_declarations(&dark);
2331+ let print = dedupe_declarations(&print);
2332+ let motion_safe = dedupe_declarations(&motion_safe);
2333+ let motion_reduce = dedupe_declarations(&motion_reduce);
2334+ let landscape = dedupe_declarations(&landscape);
2335+ let portrait = dedupe_declarations(&portrait);
2336+ let container: Vec<(String, String)> = container
2337+ .into_iter()
2338+ .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2339+ .collect();
2340+
2341+ styles.get_class(
2342+ base,
2343+ pseudo,
2344+ responsive,
2345+ dark,
2346+ print,
2347+ motion_safe,
2348+ motion_reduce,
2349+ landscape,
2350+ portrait,
2351+ container,
2352+ )
16212353}
16222354
16232355/// Dedupe CSS declarations within a single rule body: for any property
16242356/// 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.
2357+/// segments (no `:`) are preserved as-is. Semicolons inside parentheses are
2358+/// treated as part of a value, not as declaration separators.
16282359fn dedupe_declarations(css: &str) -> String {
16292360 if css.is_empty() {
16302361 return String::new();
@@ -1639,26 +2370,8 @@ fn dedupe_declarations(css: &str) -> String {
16392370 let mut decls: Vec<(Option<String>, String)> = Vec::new();
16402371 let mut current = String::new();
16412372 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;
16462373 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 == '(' {
2374+ if ch == '(' {
16622375 depth += 1;
16632376 current.push(ch);
16642377 } else if ch == ')' {
@@ -1700,639 +2413,1702 @@ fn dedupe_declarations(css: &str) -> String {
17002413 }
17012414 }
17022415
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);
1711− }
1712− }
1713− out
1714−}
2416+ let mut out = String::with_capacity(css.len());
2417+ for (i, (prop, raw)) in decls.iter().enumerate() {
2418+ let keep = match prop {
2419+ Some(p) => last.get(p) == Some(&i),
2420+ None => true,
2421+ };
2422+ if keep {
2423+ out.push_str(raw);
2424+ }
2425+ }
2426+ out
2427+}
2428+
2429+fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option<&str>) {
2430+ match (gen_class, user_class) {
2431+ (Some(g), Some(u)) => {
2432+ out.push_str(" class=\"");
2433+ out.push_str(g);
2434+ out.push(' ');
2435+ out.push_str(&html_escape(u));
2436+ out.push('"');
2437+ }
2438+ (Some(g), None) => {
2439+ out.push_str(" class=\"");
2440+ out.push_str(g);
2441+ out.push('"');
2442+ }
2443+ (None, Some(u)) => {
2444+ out.push_str(" class=\"");
2445+ out.push_str(&html_escape(u));
2446+ out.push('"');
2447+ }
2448+ (None, None) => {}
2449+ }
2450+}
2451+
2452+// ---------------------------------------------------------------------------
2453+// Attribute → CSS mapping
2454+// ---------------------------------------------------------------------------
2455+
2456+/// (htmlang prefix, CSS selector suffix)
2457+const PSEUDO_PREFIXES: &[(&str, &str)] = &[
2458+ ("hover:", ":hover"),
2459+ ("active:", ":active"),
2460+ ("focus:", ":focus"),
2461+ ("focus-visible:", ":focus-visible"),
2462+ ("focus-within:", ":focus-within"),
2463+ ("disabled:", ":disabled"),
2464+ ("checked:", ":checked"),
2465+ ("placeholder:", "::placeholder"),
2466+ ("first:", ":first-child"),
2467+ ("last:", ":last-child"),
2468+ ("odd:", ":nth-child(odd)"),
2469+ ("even:", ":nth-child(even)"),
2470+ ("before:", "::before"),
2471+ ("after:", "::after"),
2472+ ("selection:", "::selection"),
2473+ ("visited:", ":visited"),
2474+ ("empty:", ":empty"),
2475+ ("target:", ":target"),
2476+ ("valid:", ":valid"),
2477+ ("invalid:", ":invalid"),
2478+];
2479+const RESPONSIVE_PREFIXES: &[&str] = &["sm:", "md:", "lg:", "xl:", "2xl:"];
2480+const MEDIA_PREFIXES: &[&str] = &[
2481+ "dark:",
2482+ "print:",
2483+ "motion-safe:",
2484+ "motion-reduce:",
2485+ "landscape:",
2486+ "portrait:",
2487+];
2488+const CONTAINER_QUERY_PREFIXES: &[&str] = &["cq-sm:", "cq-md:", "cq-lg:", "cq-xl:", "cq-2xl:"];
2489+
2490+fn is_prefixed_attr(key: &str) -> bool {
2491+ PSEUDO_PREFIXES.iter().any(|&(p, _)| key.starts_with(p))
2492+ || RESPONSIVE_PREFIXES.iter().any(|p| key.starts_with(p))
2493+ || MEDIA_PREFIXES.iter().any(|p| key.starts_with(p))
2494+ || CONTAINER_QUERY_PREFIXES.iter().any(|p| key.starts_with(p))
2495+ || key.starts_with("nth:")
2496+ || key.starts_with("has(")
2497+}
2498+
2499+/// `display:flex;flex-direction:column;` — base layout for `@el` and every
2500+/// semantic wrapper that behaves like a column.
2501+const FLEX_COLUMN: &str = "display:flex;flex-direction:column;";
2502+
2503+/// Font stack shared by `@pre`, `@code`, `@kbd`.
2504+const MONOSPACE_STACK: &str = "font-family:ui-monospace,monospace;";
2505+
2506+/// Declarations common to `@badge` and `@tag`. They differ only in
2507+/// `border-radius` (and `@badge` additionally centers content / pins
2508+/// line-height:1), so keeping the shared base here avoids drift.
2509+const PILL_BASE: &str =
2510+ "display:inline-flex;align-items:center;padding:2px 8px;font-size:0.75rem;font-weight:600;";
2511+
2512+fn attrs_to_css(
2513+ attrs: &[Attribute],
2514+ state_prefix: &str,
2515+ kind: &ElementKind,
2516+ parent_kind: Option<&ElementKind>,
2517+) -> String {
2518+ let mut css = String::new();
2519+
2520+ // Base element styles only for the default (non-state) pass
2521+ if state_prefix.is_empty() {
2522+ match kind {
2523+ ElementKind::Row => css.push_str("display:flex;flex-direction:row;"),
2524+ ElementKind::Column
2525+ | ElementKind::El
2526+ // Semantic elements get flex column layout like @el
2527+ | ElementKind::Nav
2528+ | ElementKind::Header
2529+ | ElementKind::Footer
2530+ | ElementKind::Main
2531+ | ElementKind::Section
2532+ | ElementKind::Article
2533+ | ElementKind::Aside
2534+ | ElementKind::ListItem
2535+ | ElementKind::Form
2536+ | ElementKind::Details
2537+ | ElementKind::Dialog => css.push_str(FLEX_COLUMN),
2538+ ElementKind::Paragraph => css.push_str("margin:0;"),
2539+ // Lists: reset browser defaults
2540+ ElementKind::List => css.push_str("margin:0;padding-left:0;list-style:none;"),
2541+ // Figure / Blockquote: flex column with browser margin reset
2542+ ElementKind::Figure | ElementKind::Blockquote => {
2543+ css.push_str(FLEX_COLUMN);
2544+ css.push_str("margin:0;");
2545+ }
2546+ // Pre: preserve whitespace
2547+ ElementKind::Pre => {
2548+ css.push_str("margin:0;white-space:pre;");
2549+ css.push_str(MONOSPACE_STACK);
2550+ }
2551+ // Code / Kbd: monospace font
2552+ ElementKind::Code | ElementKind::Kbd => css.push_str(MONOSPACE_STACK),
2553+ ElementKind::DefinitionList => css.push_str("margin:0;"),
2554+ ElementKind::DefinitionDescription => {
2555+ css.push_str("margin:0;");
2556+ css.push_str(FLEX_COLUMN);
2557+ }
2558+ ElementKind::Fieldset => {
2559+ css.push_str(FLEX_COLUMN);
2560+ // Align padding to the px-based scale used by Badge/Tag/Chip
2561+ // rather than the old 0.5em (which depended on font-size).
2562+ css.push_str("border:1px solid currentColor;padding:8px;margin:0;");
2563+ }
2564+ ElementKind::Grid => css.push_str("display:grid;"),
2565+ ElementKind::Stack => css.push_str("position:relative;"),
2566+ ElementKind::Badge => {
2567+ css.push_str(PILL_BASE);
2568+ css.push_str("justify-content:center;border-radius:9999px;line-height:1;");
2569+ }
2570+ ElementKind::Tag => {
2571+ css.push_str(PILL_BASE);
2572+ css.push_str("border-radius:4px;");
2573+ }
2574+ ElementKind::Tooltip => css.push_str("position:relative;cursor:help;"),
2575+ ElementKind::Spacer => css.push_str("flex:1;"),
2576+ ElementKind::Avatar => css.push_str("display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;overflow:hidden;flex-shrink:0;"),
2577+ 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;"),
2578+ 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;"),
2579+ _ => {}
2580+ }
2581+ // Children of @carousel get scroll-snap-align and flex-shrink
2582+ if matches!(parent_kind, Some(ElementKind::Carousel)) {
2583+ css.push_str("scroll-snap-align:start;flex-shrink:0;");
2584+ }
2585+ }
2586+
2587+ for attr in attrs {
2588+ // Determine the effective key for this pass
2589+ let effective_key = if state_prefix.is_empty() {
2590+ if is_prefixed_attr(&attr.key) {
2591+ continue;
2592+ }
2593+ attr.key.as_str()
2594+ } else {
2595+ match attr.key.strip_prefix(state_prefix) {
2596+ Some(k) => k,
2597+ None => continue,
2598+ }
2599+ };
2600+
2601+ let val = attr.value.as_deref();
2602+
2603+ match effective_key {
2604+ // Layout
2605+ "spacing" | "gap" => {
2606+ if let Some(v) = val {
2607+ push_css(&mut css, "gap", &css_px(v));
2608+ }
2609+ }
2610+ "padding" => {
2611+ if let Some(v) = val {
2612+ push_css(&mut css, "padding", &css_px_multi(v));
2613+ }
2614+ }
2615+ "padding-x" => {
2616+ if let Some(v) = val {
2617+ // Logical property covers both inline sides in one
2618+ // declaration; for symmetric values this is visually
2619+ // identical to padding-left/right in LTR and RTL.
2620+ push_css(&mut css, "padding-inline", &css_px(v));
2621+ }
2622+ }
2623+ "padding-y" => {
2624+ if let Some(v) = val {
2625+ push_css(&mut css, "padding-block", &css_px(v));
2626+ }
2627+ }
2628+
2629+ // Sizing
2630+ "width" => {
2631+ if let Some(v) = val {
2632+ match v {
2633+ "fill" => match parent_kind {
2634+ Some(ElementKind::Row) => {
2635+ push_css(&mut css, "flex", "1");
2636+ push_css(&mut css, "min-width", "0");
2637+ }
2638+ _ => push_css(&mut css, "width", "100%"),
2639+ },
2640+ "shrink" => push_css(&mut css, "flex-shrink", "0"),
2641+ _ => push_css(&mut css, "width", &css_px(v)),
2642+ }
2643+ }
2644+ }
2645+ "height" => {
2646+ if let Some(v) = val {
2647+ match v {
2648+ "fill" => match parent_kind {
2649+ Some(ElementKind::Column) => {
2650+ push_css(&mut css, "flex", "1");
2651+ push_css(&mut css, "min-height", "0");
2652+ }
2653+ _ => push_css(&mut css, "height", "100%"),
2654+ },
2655+ "shrink" => push_css(&mut css, "flex-shrink", "0"),
2656+ _ => push_css(&mut css, "height", &css_px(v)),
2657+ }
2658+ }
2659+ }
2660+ "min-width" => {
2661+ if let Some(v) = val {
2662+ push_css(&mut css, "min-width", &css_px(v));
2663+ }
2664+ }
2665+ "max-width" => {
2666+ if let Some(v) = val {
2667+ push_css(&mut css, "max-width", &css_px(v));
2668+ }
2669+ }
2670+ "min-height" => {
2671+ if let Some(v) = val {
2672+ push_css(&mut css, "min-height", &css_px(v));
2673+ }
2674+ }
2675+ "max-height" => {
2676+ if let Some(v) = val {
2677+ push_css(&mut css, "max-height", &css_px(v));
2678+ }
2679+ }
2680+
2681+ // Alignment
2682+ "center-x" => match parent_kind {
2683+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2684+ push_css(&mut css, "align-self", "center");
2685+ }
2686+ _ => {
2687+ push_css(&mut css, "margin-left", "auto");
2688+ push_css(&mut css, "margin-right", "auto");
2689+ }
2690+ },
2691+ "center-y" => match parent_kind {
2692+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "center"),
2693+ _ => {
2694+ push_css(&mut css, "margin-top", "auto");
2695+ push_css(&mut css, "margin-bottom", "auto");
2696+ }
2697+ },
2698+ "align-left" => match parent_kind {
2699+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2700+ push_css(&mut css, "align-self", "flex-start");
2701+ }
2702+ _ => push_css(&mut css, "margin-right", "auto"),
2703+ },
2704+ "align-right" => match parent_kind {
2705+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2706+ push_css(&mut css, "align-self", "flex-end");
2707+ }
2708+ _ => push_css(&mut css, "margin-left", "auto"),
2709+ },
2710+ "align-top" => match parent_kind {
2711+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-start"),
2712+ _ => push_css(&mut css, "margin-bottom", "auto"),
2713+ },
2714+ "align-bottom" => match parent_kind {
2715+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-end"),
2716+ _ => push_css(&mut css, "margin-top", "auto"),
2717+ },
2718+
2719+ // Style
2720+ "background" => {
2721+ if let Some(v) = val {
2722+ push_css(&mut css, "background", v);
2723+ }
2724+ }
2725+ "color" => {
2726+ if let Some(v) = val {
2727+ push_css(&mut css, "color", v);
2728+ }
2729+ }
2730+ "border" => {
2731+ if let Some(v) = val {
2732+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2733+ if parts.len() == 2 {
2734+ push_css(
2735+ &mut css,
2736+ "border",
2737+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2738+ );
2739+ } else {
2740+ push_css(
2741+ &mut css,
2742+ "border",
2743+ &format!("{} solid currentColor", css_px(parts[0])),
2744+ );
2745+ }
2746+ }
2747+ }
2748+ "border-top" | "border-bottom" | "border-left" | "border-right" => {
2749+ if let Some(v) = val {
2750+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2751+ if parts.len() == 2 {
2752+ push_css(
2753+ &mut css,
2754+ effective_key,
2755+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2756+ );
2757+ } else {
2758+ push_css(
2759+ &mut css,
2760+ effective_key,
2761+ &format!("{} solid currentColor", css_px(parts[0])),
2762+ );
2763+ }
2764+ }
2765+ }
2766+ "rounded" => {
2767+ if let Some(v) = val {
2768+ push_css(&mut css, "border-radius", &css_px(v));
2769+ }
2770+ }
2771+ "bold" => push_css(&mut css, "font-weight", "bold"),
2772+ "italic" => push_css(&mut css, "font-style", "italic"),
2773+ "underline" => push_css(&mut css, "text-decoration", "underline"),
2774+ "size" => {
2775+ if let Some(v) = val {
2776+ push_css(&mut css, "font-size", &css_px(v));
2777+ }
2778+ }
2779+ "font" => {
2780+ if let Some(v) = val {
2781+ push_css(&mut css, "font-family", v);
2782+ }
2783+ }
2784+ "transition" => {
2785+ if let Some(v) = val {
2786+ push_css(&mut css, "transition", v);
2787+ }
2788+ }
2789+ "cursor" => {
2790+ if let Some(v) = val {
2791+ push_css(&mut css, "cursor", v);
2792+ }
2793+ }
2794+ "opacity" => {
2795+ if let Some(v) = val {
2796+ push_css(&mut css, "opacity", v);
2797+ }
2798+ }
2799+
2800+ // Typography
2801+ "text-align" => {
2802+ if let Some(v) = val {
2803+ push_css(&mut css, "text-align", v);
2804+ }
2805+ }
2806+ "line-height" => {
2807+ if let Some(v) = val {
2808+ push_css(&mut css, "line-height", &css_line_height(v));
2809+ }
2810+ }
2811+ "letter-spacing" => {
2812+ if let Some(v) = val {
2813+ push_css(&mut css, "letter-spacing", &css_px(v));
2814+ }
2815+ }
2816+ "text-transform" => {
2817+ if let Some(v) = val {
2818+ push_css(&mut css, "text-transform", v);
2819+ }
2820+ }
2821+ "white-space" => {
2822+ if let Some(v) = val {
2823+ push_css(&mut css, "white-space", v);
2824+ }
2825+ }
2826+
2827+ // Overflow & positioning
2828+ "overflow" => {
2829+ if let Some(v) = val {
2830+ push_css(&mut css, "overflow", v);
2831+ }
2832+ }
2833+ "position" => {
2834+ if let Some(v) = val {
2835+ push_css(&mut css, "position", v);
2836+ }
2837+ }
2838+ "top" => {
2839+ if let Some(v) = val {
2840+ push_css(&mut css, "top", &css_px(v));
2841+ }
2842+ }
2843+ "right" => {
2844+ if let Some(v) = val {
2845+ push_css(&mut css, "right", &css_px(v));
2846+ }
2847+ }
2848+ "bottom" => {
2849+ if let Some(v) = val {
2850+ push_css(&mut css, "bottom", &css_px(v));
2851+ }
2852+ }
2853+ "left" => {
2854+ if let Some(v) = val {
2855+ push_css(&mut css, "left", &css_px(v));
2856+ }
2857+ }
2858+ "z-index" => {
2859+ if let Some(v) = val {
2860+ push_css(&mut css, "z-index", v);
2861+ }
2862+ }
2863+
2864+ // Display & visibility
2865+ "display" => {
2866+ if let Some(v) = val {
2867+ push_css(&mut css, "display", v);
2868+ }
2869+ }
2870+ "visibility" => {
2871+ if let Some(v) = val {
2872+ push_css(&mut css, "visibility", v);
2873+ }
2874+ }
2875+ "hidden" => push_css(&mut css, "display", "none"),
2876+
2877+ // Transform & filters
2878+ "transform" => {
2879+ if let Some(v) = val {
2880+ push_css(&mut css, "transform", v);
2881+ }
2882+ }
2883+ "backdrop-filter" => {
2884+ if let Some(v) = val {
2885+ push_css(&mut css, "backdrop-filter", v);
2886+ }
2887+ }
2888+
2889+ // Effects
2890+ "shadow" => {
2891+ if let Some(v) = val {
2892+ push_css(&mut css, "box-shadow", v);
2893+ }
2894+ }
2895+
2896+ // Flow
2897+ "wrap" => push_css(&mut css, "flex-wrap", "wrap"),
2898+ "gap-x" => {
2899+ if let Some(v) = val {
2900+ push_css(&mut css, "column-gap", &css_px(v));
2901+ }
2902+ }
2903+ "gap-y" => {
2904+ if let Some(v) = val {
2905+ push_css(&mut css, "row-gap", &css_px(v));
2906+ }
2907+ }
2908+
2909+ // Grid
2910+ "grid" => {
2911+ push_css(&mut css, "display", "grid");
2912+ }
2913+ "grid-cols" => {
2914+ if let Some(v) = val {
2915+ if let Ok(n) = v.parse::<u32>() {
2916+ push_css(
2917+ &mut css,
2918+ "grid-template-columns",
2919+ &format!("repeat({},1fr)", n),
2920+ );
2921+ } else {
2922+ push_css(&mut css, "grid-template-columns", v);
2923+ }
2924+ }
2925+ }
2926+ "grid-rows" => {
2927+ if let Some(v) = val {
2928+ if let Ok(n) = v.parse::<u32>() {
2929+ push_css(
2930+ &mut css,
2931+ "grid-template-rows",
2932+ &format!("repeat({},1fr)", n),
2933+ );
2934+ } else {
2935+ push_css(&mut css, "grid-template-rows", v);
2936+ }
2937+ }
2938+ }
2939+ "col-span" => {
2940+ if let Some(v) = val {
2941+ push_css(&mut css, "grid-column", &format!("span {}", v));
2942+ }
2943+ }
2944+ "row-span" => {
2945+ if let Some(v) = val {
2946+ push_css(&mut css, "grid-row", &format!("span {}", v));
2947+ }
2948+ }
2949+
2950+ // Animation
2951+ "animation" => {
2952+ if let Some(v) = val {
2953+ push_css(&mut css, "animation", v);
2954+ }
2955+ }
2956+
2957+ // Aspect ratio
2958+ "aspect-ratio" => {
2959+ if let Some(v) = val {
2960+ push_css(&mut css, "aspect-ratio", v);
2961+ }
2962+ }
2963+
2964+ // CSS containment for rendering performance
2965+ "contain" => {
2966+ if let Some(v) = val {
2967+ push_css(&mut css, "contain", v);
2968+ } else {
2969+ push_css(&mut css, "contain", "layout style paint");
2970+ }
2971+ }
2972+ "content-visibility" => {
2973+ if let Some(v) = val {
2974+ push_css(&mut css, "content-visibility", v);
2975+ } else {
2976+ push_css(&mut css, "content-visibility", "auto");
2977+ }
2978+ }
2979+
2980+ // Outline (like border but doesn't affect layout)
2981+ "outline" => {
2982+ if let Some(v) = val {
2983+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2984+ if parts.len() == 2 {
2985+ push_css(
2986+ &mut css,
2987+ "outline",
2988+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2989+ );
2990+ } else {
2991+ push_css(
2992+ &mut css,
2993+ "outline",
2994+ &format!("{} solid currentColor", css_px(parts[0])),
2995+ );
2996+ }
2997+ }
2998+ }
2999+
3000+ // Logical properties (i18n-aware)
3001+ "padding-inline" => {
3002+ if let Some(v) = val {
3003+ push_css(&mut css, "padding-inline", &css_px_multi(v));
3004+ }
3005+ }
3006+ "padding-block" => {
3007+ if let Some(v) = val {
3008+ push_css(&mut css, "padding-block", &css_px_multi(v));
3009+ }
3010+ }
3011+ "margin-inline" => {
3012+ if let Some(v) = val {
3013+ push_css(&mut css, "margin-inline", &css_px_multi(v));
3014+ }
3015+ }
3016+ "margin-block" => {
3017+ if let Some(v) = val {
3018+ push_css(&mut css, "margin-block", &css_px_multi(v));
3019+ }
3020+ }
3021+
3022+ // Logical property start/end variants
3023+ "padding-inline-start"
3024+ | "padding-inline-end"
3025+ | "padding-block-start"
3026+ | "padding-block-end"
3027+ | "margin-inline-start"
3028+ | "margin-inline-end"
3029+ | "margin-block-start"
3030+ | "margin-block-end" => {
3031+ if let Some(v) = val {
3032+ push_css(&mut css, effective_key, &css_px(v));
3033+ }
3034+ }
3035+
3036+ // Logical inset
3037+ "inset-inline" | "inset-block" => {
3038+ if let Some(v) = val {
3039+ push_css(&mut css, effective_key, &css_px_multi(v));
3040+ }
3041+ }
3042+ "inset-inline-start" | "inset-inline-end" | "inset-block-start" | "inset-block-end" => {
3043+ if let Some(v) = val {
3044+ push_css(&mut css, effective_key, &css_px(v));
3045+ }
3046+ }
3047+
3048+ // Logical border
3049+ "border-inline"
3050+ | "border-block"
3051+ | "border-inline-start"
3052+ | "border-inline-end"
3053+ | "border-block-start"
3054+ | "border-block-end" => {
3055+ if let Some(v) = val {
3056+ push_css(&mut css, effective_key, v);
3057+ }
3058+ }
3059+
3060+ // Logical border-radius
3061+ "border-start-start-radius"
3062+ | "border-start-end-radius"
3063+ | "border-end-start-radius"
3064+ | "border-end-end-radius" => {
3065+ if let Some(v) = val {
3066+ push_css(&mut css, effective_key, &css_px(v));
3067+ }
3068+ }
3069+
3070+ // Logical scroll margins & padding
3071+ "scroll-margin-inline"
3072+ | "scroll-margin-block"
3073+ | "scroll-padding-inline"
3074+ | "scroll-padding-block" => {
3075+ if let Some(v) = val {
3076+ push_css(&mut css, effective_key, &css_px_multi(v));
3077+ }
3078+ }
3079+
3080+ // Logical sizing
3081+ "inline-size" | "block-size" | "min-inline-size" | "max-inline-size"
3082+ | "min-block-size" | "max-block-size" => {
3083+ if let Some(v) = val {
3084+ push_css(&mut css, effective_key, &css_px(v));
3085+ }
3086+ }
3087+
3088+ // Scroll snap
3089+ "scroll-snap-type" => {
3090+ if let Some(v) = val {
3091+ push_css(&mut css, "scroll-snap-type", v);
3092+ }
3093+ }
3094+ "scroll-snap-align" => {
3095+ if let Some(v) = val {
3096+ push_css(&mut css, "scroll-snap-align", v);
3097+ }
3098+ }
3099+
3100+ // Margin
3101+ "margin" => {
3102+ if let Some(v) = val {
3103+ push_css(&mut css, "margin", &css_px_multi(v));
3104+ }
3105+ }
3106+ "margin-x" => {
3107+ if let Some(v) = val {
3108+ push_css(&mut css, "margin-inline", &css_px(v));
3109+ }
3110+ }
3111+ "margin-y" => {
3112+ if let Some(v) = val {
3113+ push_css(&mut css, "margin-block", &css_px(v));
3114+ }
3115+ }
3116+
3117+ // Filter
3118+ "filter" => {
3119+ if let Some(v) = val {
3120+ push_css(&mut css, "filter", v);
3121+ }
3122+ }
3123+
3124+ // Object fit/position (for images)
3125+ "object-fit" => {
3126+ if let Some(v) = val {
3127+ push_css(&mut css, "object-fit", v);
3128+ }
3129+ }
3130+ "object-position" => {
3131+ if let Some(v) = val {
3132+ push_css(&mut css, "object-position", v);
3133+ }
3134+ }
3135+
3136+ // Text shadow
3137+ "text-shadow" => {
3138+ if let Some(v) = val {
3139+ push_css(&mut css, "text-shadow", v);
3140+ }
3141+ }
3142+
3143+ // Text overflow
3144+ "text-overflow" => {
3145+ if let Some(v) = val {
3146+ push_css(&mut css, "text-overflow", v);
3147+ }
3148+ }
3149+
3150+ // Interaction
3151+ "pointer-events" => {
3152+ if let Some(v) = val {
3153+ push_css(&mut css, "pointer-events", v);
3154+ }
3155+ }
3156+ "user-select" => {
3157+ if let Some(v) = val {
3158+ push_css(&mut css, "user-select", v);
3159+ }
3160+ }
3161+
3162+ // Flexbox/grid alignment
3163+ "justify-content" => {
3164+ if let Some(v) = val {
3165+ push_css(&mut css, "justify-content", v);
3166+ }
3167+ }
3168+ "align-items" => {
3169+ if let Some(v) = val {
3170+ push_css(&mut css, "align-items", v);
3171+ }
3172+ }
3173+
3174+ // Flex item order
3175+ "order" => {
3176+ if let Some(v) = val {
3177+ push_css(&mut css, "order", v);
3178+ }
3179+ }
3180+
3181+ // Background extras
3182+ "background-size" => {
3183+ if let Some(v) = val {
3184+ push_css(&mut css, "background-size", v);
3185+ }
3186+ }
3187+ "background-position" => {
3188+ if let Some(v) = val {
3189+ push_css(&mut css, "background-position", v);
3190+ }
3191+ }
3192+ "background-repeat" => {
3193+ if let Some(v) = val {
3194+ push_css(&mut css, "background-repeat", v);
3195+ }
3196+ }
3197+
3198+ // Text wrapping
3199+ "word-break" => {
3200+ if let Some(v) = val {
3201+ push_css(&mut css, "word-break", v);
3202+ }
3203+ }
3204+ "overflow-wrap" => {
3205+ if let Some(v) = val {
3206+ push_css(&mut css, "overflow-wrap", v);
3207+ }
3208+ }
3209+
3210+ // Container queries
3211+ "container" => {
3212+ push_css(&mut css, "container-type", "inline-size");
3213+ }
3214+ "container-name" => {
3215+ if let Some(v) = val {
3216+ push_css(&mut css, "container-name", v);
3217+ }
3218+ }
3219+ "container-type" => {
3220+ if let Some(v) = val {
3221+ push_css(&mut css, "container-type", v);
3222+ }
3223+ }
3224+
3225+ // Overflow axis
3226+ "overflow-x" => {
3227+ if let Some(v) = val {
3228+ push_css(&mut css, "overflow-x", v);
3229+ }
3230+ }
3231+ "overflow-y" => {
3232+ if let Some(v) = val {
3233+ push_css(&mut css, "overflow-y", v);
3234+ }
3235+ }
3236+
3237+ // Inset (shorthand for top/right/bottom/left)
3238+ "inset" => {
3239+ if let Some(v) = val {
3240+ push_css(&mut css, "inset", &css_px(v));
3241+ }
3242+ }
3243+
3244+ // Accent & caret colors
3245+ "accent-color" => {
3246+ if let Some(v) = val {
3247+ push_css(&mut css, "accent-color", v);
3248+ }
3249+ }
3250+ "caret-color" => {
3251+ if let Some(v) = val {
3252+ push_css(&mut css, "caret-color", v);
3253+ }
3254+ }
3255+
3256+ // Color scheme & appearance
3257+ "color-scheme" => {
3258+ if let Some(v) = val {
3259+ push_css(&mut css, "color-scheme", v);
3260+ }
3261+ }
3262+ "appearance" => {
3263+ if let Some(v) = val {
3264+ push_css(&mut css, "appearance", v);
3265+ }
3266+ }
3267+
3268+ // List style
3269+ "list-style" => {
3270+ if let Some(v) = val {
3271+ push_css(&mut css, "list-style", v);
3272+ }
3273+ }
3274+
3275+ // Table
3276+ "border-collapse" => {
3277+ if let Some(v) = val {
3278+ push_css(&mut css, "border-collapse", v);
3279+ }
3280+ }
3281+ "border-spacing" => {
3282+ if let Some(v) = val {
3283+ push_css(&mut css, "border-spacing", &css_px(v));
3284+ }
3285+ }
3286+
3287+ // Text decoration
3288+ "text-decoration" => {
3289+ if let Some(v) = val {
3290+ push_css(&mut css, "text-decoration", v);
3291+ }
3292+ }
3293+ "text-decoration-color" => {
3294+ if let Some(v) = val {
3295+ push_css(&mut css, "text-decoration-color", v);
3296+ }
3297+ }
3298+ "text-decoration-thickness" => {
3299+ if let Some(v) = val {
3300+ push_css(&mut css, "text-decoration-thickness", &css_px(v));
3301+ }
3302+ }
3303+ "text-decoration-style" => {
3304+ if let Some(v) = val {
3305+ push_css(&mut css, "text-decoration-style", v);
3306+ }
3307+ }
3308+ "text-underline-offset" => {
3309+ if let Some(v) = val {
3310+ push_css(&mut css, "text-underline-offset", &css_px(v));
3311+ }
3312+ }
3313+
3314+ // Multi-column
3315+ "column-width" => {
3316+ if let Some(v) = val {
3317+ push_css(&mut css, "column-width", &css_px(v));
3318+ }
3319+ }
3320+ "column-rule" => {
3321+ if let Some(v) = val {
3322+ push_css(&mut css, "column-rule", v);
3323+ }
3324+ }
3325+
3326+ // Place items/self
3327+ "place-items" => {
3328+ if let Some(v) = val {
3329+ push_css(&mut css, "place-items", v);
3330+ }
3331+ }
3332+ "place-self" => {
3333+ if let Some(v) = val {
3334+ push_css(&mut css, "place-self", v);
3335+ }
3336+ }
3337+
3338+ // Scroll behavior
3339+ "scroll-behavior" => {
3340+ if let Some(v) = val {
3341+ push_css(&mut css, "scroll-behavior", v);
3342+ }
3343+ }
3344+
3345+ // Resize
3346+ "resize" => {
3347+ if let Some(v) = val {
3348+ push_css(&mut css, "resize", v);
3349+ }
3350+ }
3351+
3352+ // New CSS properties
3353+ "clip-path" => {
3354+ if let Some(v) = val {
3355+ push_css(&mut css, "clip-path", v);
3356+ }
3357+ }
3358+ "mix-blend-mode" => {
3359+ if let Some(v) = val {
3360+ push_css(&mut css, "mix-blend-mode", v);
3361+ }
3362+ }
3363+ "background-blend-mode" => {
3364+ if let Some(v) = val {
3365+ push_css(&mut css, "background-blend-mode", v);
3366+ }
3367+ }
3368+ "writing-mode" => {
3369+ if let Some(v) = val {
3370+ push_css(&mut css, "writing-mode", v);
3371+ }
3372+ }
3373+ "column-count" => {
3374+ if let Some(v) = val {
3375+ push_css(&mut css, "column-count", v);
3376+ }
3377+ }
3378+ "column-gap" => {
3379+ if let Some(v) = val {
3380+ push_css(&mut css, "column-gap", &css_px(v));
3381+ }
3382+ }
3383+ "text-indent" => {
3384+ if let Some(v) = val {
3385+ push_css(&mut css, "text-indent", &css_px(v));
3386+ }
3387+ }
3388+ "hyphens" => {
3389+ if let Some(v) = val {
3390+ push_css(&mut css, "hyphens", v);
3391+ }
3392+ }
3393+ "flex-grow" => {
3394+ if let Some(v) = val {
3395+ push_css(&mut css, "flex-grow", v);
3396+ }
3397+ }
3398+ "flex-shrink" => {
3399+ if let Some(v) = val {
3400+ push_css(&mut css, "flex-shrink", v);
3401+ }
3402+ }
3403+ "flex-basis" => {
3404+ if let Some(v) = val {
3405+ push_css(&mut css, "flex-basis", &css_px(v));
3406+ }
3407+ }
3408+ "isolation" => {
3409+ if let Some(v) = val {
3410+ push_css(&mut css, "isolation", v);
3411+ }
3412+ }
3413+ "place-content" => {
3414+ if let Some(v) = val {
3415+ push_css(&mut css, "place-content", v);
3416+ }
3417+ }
3418+ "background-image" => {
3419+ if let Some(v) = val {
3420+ push_css(&mut css, "background-image", v);
3421+ }
3422+ }
3423+ "font-weight" => {
3424+ if let Some(v) = val {
3425+ push_css(&mut css, "font-weight", v);
3426+ }
3427+ }
3428+ "font-style" => {
3429+ if let Some(v) = val {
3430+ push_css(&mut css, "font-style", v);
3431+ }
3432+ }
3433+ "text-wrap" => {
3434+ if let Some(v) = val {
3435+ push_css(&mut css, "text-wrap", v);
3436+ }
3437+ }
3438+ "will-change" => {
3439+ if let Some(v) = val {
3440+ push_css(&mut css, "will-change", v);
3441+ }
3442+ }
3443+ "touch-action" => {
3444+ if let Some(v) = val {
3445+ push_css(&mut css, "touch-action", v);
3446+ }
3447+ }
3448+ "vertical-align" => {
3449+ if let Some(v) = val {
3450+ push_css(&mut css, "vertical-align", v);
3451+ }
3452+ }
3453+ "scroll-margin" => {
3454+ if let Some(v) = val {
3455+ push_css(&mut css, "scroll-margin", &css_px(v));
3456+ }
3457+ }
3458+ "scroll-margin-top"
3459+ | "scroll-margin-bottom"
3460+ | "scroll-margin-left"
3461+ | "scroll-margin-right" => {
3462+ if let Some(v) = val {
3463+ push_css(&mut css, effective_key, &css_px(v));
3464+ }
3465+ }
3466+ "scroll-padding" => {
3467+ if let Some(v) = val {
3468+ push_css(&mut css, "scroll-padding", &css_px(v));
3469+ }
3470+ }
3471+ "scroll-padding-top"
3472+ | "scroll-padding-bottom"
3473+ | "scroll-padding-left"
3474+ | "scroll-padding-right" => {
3475+ if let Some(v) = val {
3476+ push_css(&mut css, effective_key, &css_px(v));
3477+ }
3478+ }
3479+ "direction" => {
3480+ if let Some(v) = val {
3481+ push_css(&mut css, "direction", v);
3482+ }
3483+ }
3484+
3485+ "content" => {
3486+ if let Some(v) = val {
3487+ // Wrap in quotes if not already quoted and not a CSS keyword
3488+ if v.starts_with('"')
3489+ || v.starts_with('\'')
3490+ || v == "none"
3491+ || v == "normal"
3492+ || v.starts_with("attr(")
3493+ || v.starts_with("counter(")
3494+ {
3495+ push_css(&mut css, "content", v);
3496+ } else {
3497+ push_css(&mut css, "content", &format!("\"{}\"", v));
3498+ }
3499+ }
3500+ }
3501+
3502+ // --- CSS Shorthands ---
3503+ "truncate" => {
3504+ push_css(&mut css, "overflow", "hidden");
3505+ push_css(&mut css, "text-overflow", "ellipsis");
3506+ push_css(&mut css, "white-space", "nowrap");
3507+ }
3508+ "line-clamp" => {
3509+ if let Some(v) = val {
3510+ push_css(&mut css, "display", "-webkit-box");
3511+ push_css(&mut css, "-webkit-line-clamp", v);
3512+ push_css(&mut css, "-webkit-box-orient", "vertical");
3513+ push_css(&mut css, "overflow", "hidden");
3514+ }
3515+ }
3516+ "blur" => {
3517+ if let Some(v) = val {
3518+ push_css(&mut css, "filter", &format!("blur({})", css_px(v)));
3519+ }
3520+ }
3521+ "backdrop-blur" => {
3522+ if let Some(v) = val {
3523+ push_css(&mut css, "backdrop-filter", &format!("blur({})", css_px(v)));
3524+ }
3525+ }
3526+ "no-scrollbar" => {
3527+ push_css(&mut css, "scrollbar-width", "none");
3528+ push_css(&mut css, "-ms-overflow-style", "none");
3529+ }
3530+ "skeleton" => {
3531+ push_css(
3532+ &mut css,
3533+ "background",
3534+ "linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%)",
3535+ );
3536+ push_css(&mut css, "background-size", "200% 100%");
3537+ push_css(
3538+ &mut css,
3539+ "animation",
3540+ "hl-skeleton 1.5s ease-in-out infinite",
3541+ );
3542+ }
3543+ "gradient" => {
3544+ if let Some(v) = val {
3545+ // Parse: "from to [angle]" or "color1 color2 [angle]"
3546+ let parts: Vec<&str> = v.split_whitespace().collect();
3547+ let bg = if parts.len() >= 3
3548+ && (parts[2].ends_with("deg")
3549+ || parts[2].ends_with("turn")
3550+ || parts[2].ends_with("rad"))
3551+ {
3552+ format!("linear-gradient({},{},{})", parts[2], parts[0], parts[1])
3553+ } else if parts.len() >= 2 {
3554+ format!("linear-gradient({},{})", parts[0], parts[1])
3555+ } else {
3556+ format!("linear-gradient({},transparent)", parts[0])
3557+ };
3558+ push_css(&mut css, "background", &bg);
3559+ }
3560+ }
3561+
3562+ // Grid areas
3563+ "grid-template-areas" => {
3564+ if let Some(v) = val {
3565+ push_css(&mut css, "grid-template-areas", v);
3566+ }
3567+ }
3568+ "grid-area" => {
3569+ if let Some(v) = val {
3570+ push_css(&mut css, "grid-area", v);
3571+ }
3572+ }
3573+
3574+ // View transitions
3575+ "view-transition-name" => {
3576+ if let Some(v) = val {
3577+ push_css(&mut css, "view-transition-name", v);
3578+ }
3579+ }
3580+
3581+ // Animate shorthand (alias for animation)
3582+ "animate" => {
3583+ if let Some(v) = val {
3584+ push_css(&mut css, "animation", v);
3585+ }
3586+ }
3587+
3588+ // CSS subgrid
3589+ "grid-template-columns" => {
3590+ if let Some(v) = val {
3591+ push_css(&mut css, "grid-template-columns", v);
3592+ }
3593+ }
3594+ "grid-template-rows" => {
3595+ if let Some(v) = val {
3596+ push_css(&mut css, "grid-template-rows", v);
3597+ }
3598+ }
3599+
3600+ // Scroll-driven animations
3601+ "animation-timeline" => {
3602+ if let Some(v) = val {
3603+ push_css(&mut css, "animation-timeline", v);
3604+ }
3605+ }
3606+ "animation-range" => {
3607+ if let Some(v) = val {
3608+ push_css(&mut css, "animation-range", v);
3609+ }
3610+ }
3611+ "view-timeline-name" => {
3612+ if let Some(v) = val {
3613+ push_css(&mut css, "view-timeline-name", v);
3614+ }
3615+ }
3616+ "view-timeline-axis" => {
3617+ if let Some(v) = val {
3618+ push_css(&mut css, "view-timeline-axis", v);
3619+ }
3620+ }
3621+ "scroll-timeline-name" => {
3622+ if let Some(v) = val {
3623+ push_css(&mut css, "scroll-timeline-name", v);
3624+ }
3625+ }
3626+ "scroll-timeline-axis" => {
3627+ if let Some(v) = val {
3628+ push_css(&mut css, "scroll-timeline-axis", v);
3629+ }
3630+ }
3631+
3632+ // Anchor positioning
3633+ "anchor-name" => {
3634+ if let Some(v) = val {
3635+ push_css(&mut css, "anchor-name", v);
3636+ }
3637+ }
3638+ "position-anchor" => {
3639+ if let Some(v) = val {
3640+ push_css(&mut css, "position-anchor", v);
3641+ }
3642+ }
3643+ "position-area" => {
3644+ if let Some(v) = val {
3645+ push_css(&mut css, "position-area", v);
3646+ }
3647+ }
3648+ "inset-area" => {
3649+ // Legacy alias for position-area
3650+ if let Some(v) = val {
3651+ push_css(&mut css, "position-area", v);
3652+ }
3653+ }
3654+
3655+ // initial-letter (drop caps)
3656+ "initial-letter" => {
3657+ if let Some(v) = val {
3658+ push_css(&mut css, "initial-letter", v);
3659+ }
3660+ }
3661+
3662+ // Critical CSS hint — not CSS, handled elsewhere
3663+ "critical" => {}
3664+
3665+ // Identity and HTML passthrough — not CSS
3666+ "id" | "class" => {}
3667+ "type" | "placeholder" | "name" | "value" | "disabled" | "required" | "checked"
3668+ | "for" | "action" | "method" | "autocomplete" | "min" | "max" | "step" | "pattern"
3669+ | "maxlength" | "rows" | "cols" | "multiple" | "alt" | "role" | "tabindex"
3670+ | "title" | "controls" | "autoplay" | "loop" | "muted" | "poster" | "preload"
3671+ | "loading" | "decoding" | "ordered" | "src" | "open" | "novalidate" | "low"
3672+ | "high" | "optimum" | "colspan" | "rowspan" | "scope" | "inline" | "responsive"
3673+ | "datetime" | "media" | "sizes" | "srcset" | "cite" | "list" | "sandbox" | "allow"
3674+ | "allowfullscreen" | "referrerpolicy" | "formaction" | "formmethod" | "formtarget"
3675+ | "target" | "autofocus" => {}
17153676
1716−fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option<&str>) {
1717− match (gen_class, user_class) {
1718− (Some(g), Some(u)) => {
1719− out.push_str(" class=\"");
1720− out.push_str(g);
1721− out.push(' ');
1722− out.push_str(&html_escape(u));
1723− out.push('"');
1724− }
1725− (Some(g), None) => {
1726− out.push_str(" class=\"");
1727− out.push_str(g);
1728− out.push('"');
1729− }
1730− (None, Some(u)) => {
1731− out.push_str(" class=\"");
1732− out.push_str(&html_escape(u));
1733− out.push('"');
3677+ _ => {}
17343678 }
1735− (None, None) => {}
17363679 }
1737−}
1738−
1739−// ---------------------------------------------------------------------------
1740−// Attribute → CSS mapping
1741−// ---------------------------------------------------------------------------
17423680
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,
3681+ css
17553682}
17563683
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,
1767− }
1768− }
3684+fn push_css(css: &mut String, prop: &str, value: &str) {
3685+ css.push_str(prop);
3686+ css.push(':');
3687+ css.push_str(value);
3688+ css.push(';');
17693689}
17703690
1771−// ---------------------------------------------------------------------------
1772−// Direction: what a child's `fill` and `shrink` compile against
1773−// ---------------------------------------------------------------------------
3691+/// Known CSS units — if a value ends with one, skip appending `px`.
3692+const CSS_UNITS: &[&str] = &[
3693+ "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh", "ch", "ex", "cm", "mm",
3694+ "in", "pt", "pc", "fr",
3695+];
17743696
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,
3697+/// Format a numeric value: if it already has a CSS unit, pass through as-is;
3698+/// otherwise append `px`.
3699+fn css_px(value: &str) -> String {
3700+ let v = value.trim();
3701+ if v == "0" {
3702+ return "0".to_string();
3703+ }
3704+ if CSS_UNITS.iter().any(|u| v.ends_with(u)) {
3705+ return v.to_string();
3706+ }
3707+ if v.starts_with("var(")
3708+ || v.starts_with("calc(")
3709+ || v.starts_with("clamp(")
3710+ || v.starts_with("min(")
3711+ || v.starts_with("max(")
3712+ {
3713+ return v.to_string();
3714+ }
3715+ format!("{}px", v)
17803716}
17813717
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− })
3718+/// Rewrite literal values that match a declared CSS custom property (from
3719+/// `@theme` or `@let --name value`) to `var(--name)` references. Matches are
3720+/// anchored to CSS value boundaries so e.g. `#3b82f6` inside a longer hex or
3721+/// inside an identifier is not replaced. The `:root` block is emitted before
3722+/// this call runs, so its declarations are not affected.
3723+fn substitute_css_vars(css: &str, vars: &[(String, String)]) -> String {
3724+ if css.is_empty() || vars.is_empty() {
3725+ return css.to_string();
3726+ }
3727+ // Prefer longer values first so that if two vars share a prefix, the
3728+ // longer (more specific) match wins.
3729+ let mut pairs: Vec<(&str, String)> = vars
3730+ .iter()
3731+ .filter(|(name, value)| name.starts_with("--") && !value.is_empty())
3732+ .map(|(name, value)| (value.as_str(), format!("var({})", name)))
3733+ .collect();
3734+ pairs.sort_by_key(|(v, _)| std::cmp::Reverse(v.len()));
3735+ if pairs.is_empty() {
3736+ return css.to_string();
17913737 }
1792−}
17933738
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−}
3739+ let is_boundary_before = |b: Option<u8>| match b {
3740+ None => true,
3741+ Some(c) => matches!(
3742+ c,
3743+ b':' | b' ' | b',' | b'(' | b';' | b'{' | b'\n' | b'\t'
3744+ ),
3745+ };
3746+ let is_boundary_after = |b: Option<u8>| match b {
3747+ None => true,
3748+ Some(c) => matches!(
3749+ c,
3750+ b';' | b'}' | b',' | b' ' | b')' | b'\n' | b'\t'
3751+ ),
3752+ };
18133753
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;
3754+ let bytes = css.as_bytes();
3755+ let mut out = String::with_capacity(css.len());
3756+ let mut i = 0;
3757+ let mut prev: Option<u8> = None;
3758+ while i < bytes.len() {
3759+ if is_boundary_before(prev) {
3760+ let mut matched = false;
3761+ for (val, repl) in &pairs {
3762+ let vb = val.as_bytes();
3763+ if i + vb.len() <= bytes.len() && &bytes[i..i + vb.len()] == vb {
3764+ let next = bytes.get(i + vb.len()).copied();
3765+ if is_boundary_after(next) {
3766+ out.push_str(repl);
3767+ prev = repl.as_bytes().last().copied();
3768+ i += vb.len();
3769+ matched = true;
3770+ break;
3771+ }
3772+ }
18263773 }
1827− let Some(axis) = attr.value.as_deref().and_then(Axis::of_value) else {
3774+ if matched {
18283775 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));
18363776 }
18373777 }
1838− changes.sort_by_key(|(at, _)| at_order(at));
1839− Flow {
1840− base: Some(base),
1841− changes,
1842− class: None,
1843− }
1844− }
1845−
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−}
1861−
1862−/// `width` or `height`.
1863−#[derive(Clone, Copy, PartialEq, Eq)]
1864−enum Dim {
1865− Width,
1866− Height,
1867−}
1868−
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−}
1877−
1878−impl Size {
1879− fn of(value: &str) -> Size {
1880− match value.trim() {
1881− "fill" => Size::Fill,
1882− "shrink" => Size::Shrink,
1883− _ => Size::Set,
3778+ // Advance by one UTF-8 code point.
3779+ let start = i;
3780+ i += 1;
3781+ while i < bytes.len() && (bytes[i] & 0xC0) == 0x80 {
3782+ i += 1;
18843783 }
3784+ out.push_str(&css[start..i]);
3785+ prev = bytes.get(i - 1).copied();
18853786 }
3787+ out
18863788}
18873789
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−}
1906−
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− ],
3790+/// Scan generated CSS for literal property values that repeat often enough
3791+/// that substituting them with an auto-named custom property would reduce
3792+/// total byte count. Returns the rewritten CSS and any new vars that should
3793+/// be appended to `:root`.
3794+///
3795+/// The algorithm only promotes a value if it strictly saves bytes after
3796+/// accounting for the `--xN:value;` declaration overhead plus the
3797+/// `var(--xN)` reference cost at each call site. Values that are already
3798+/// `var(...)` references or contain `var(` calls are skipped so we never
3799+/// nest references. Names avoid collisions with `existing_vars`.
3800+fn auto_extract_repeats(
3801+ css: &str,
3802+ existing_vars: &[(String, String)],
3803+) -> (String, Vec<(String, String)>) {
3804+ if css.is_empty() {
3805+ return (css.to_string(), Vec::new());
19213806 }
1922−}
1923−
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−}
1943−
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 {
3807+ // Count occurrences of each distinct property value (the text between
3808+ // `:` and the next `;` or `}` at the top level of a declaration block,
3809+ // ignoring balanced parentheses so that e.g. `rgba(...)` stays intact).
3810+ let bytes = css.as_bytes();
3811+ let mut counts: HashMap<String, usize> = HashMap::new();
3812+ let mut depth: i32 = 0;
3813+ let mut i = 0;
3814+ while i < bytes.len() {
3815+ match bytes[i] {
3816+ b'{' => {
3817+ depth += 1;
3818+ i += 1;
3819+ continue;
3820+ }
3821+ b'}' => {
3822+ if depth > 0 {
3823+ depth -= 1;
3824+ }
3825+ i += 1;
19533826 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− _ => {}
19793827 }
3828+ _ => {}
19803829 }
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);
3830+ if depth > 0 && bytes[i] == b':' {
3831+ // Skip past `:` then walk to the terminator.
3832+ let start = i + 1;
3833+ let mut end = start;
3834+ let mut pdepth = 0i32;
3835+ while end < bytes.len() {
3836+ match bytes[end] {
3837+ b'(' => pdepth += 1,
3838+ b')' => {
3839+ if pdepth > 0 {
3840+ pdepth -= 1;
3841+ }
20223842 }
3843+ b';' | b'}' if pdepth == 0 => break,
3844+ b'{' if pdepth == 0 => break,
3845+ _ => {}
20233846 }
2024− return;
3847+ end += 1;
3848+ }
3849+ let val = css[start..end].trim();
3850+ if !val.is_empty() && !val.starts_with("var(") && !val.contains("var(") {
3851+ *counts.entry(val.to_string()).or_default() += 1;
20253852 }
3853+ i = end;
3854+ continue;
20263855 }
2027− if !self.writes(property) {
2028− push_css(css, property, value);
3856+ i += 1;
3857+ }
3858+
3859+ // Decide which values are worth extracting. A value of length L appearing
3860+ // N times costs N*L bytes inline; promoting it costs (L + 6) for the
3861+ // `--hK:V;` declaration plus N * ref_len for the call sites. We estimate
3862+ // ref_len optimistically as `var(--h0)` (9 bytes) and fall back to 10 for
3863+ // two-digit indices, which only affects very large extraction counts.
3864+ let existing: std::collections::HashSet<&str> =
3865+ existing_vars.iter().map(|(n, _)| n.as_str()).collect();
3866+ let mut candidates: Vec<(String, usize)> = counts
3867+ .into_iter()
3868+ .filter(|(_, n)| *n >= 2)
3869+ .collect();
3870+ // Stable, deterministic ordering — longest values first, tiebreak by text.
3871+ candidates.sort_by(|a, b| {
3872+ b.0.len()
3873+ .cmp(&a.0.len())
3874+ .then_with(|| a.0.cmp(&b.0))
3875+ });
3876+
3877+ let mut extracted: Vec<(String, String)> = Vec::new();
3878+ let mut next_idx: usize = 0;
3879+ for (value, n) in candidates {
3880+ let l = value.len();
3881+ // Allocate the next unused `--hN` name.
3882+ let (name, ref_len) = loop {
3883+ let candidate = format!("--h{}", next_idx);
3884+ next_idx += 1;
3885+ let rl = candidate.len() + 6; // `var(` + name + `)`
3886+ if !existing.contains(candidate.as_str())
3887+ && !extracted.iter().any(|(n, _)| *n == candidate)
3888+ {
3889+ break (candidate, rl);
3890+ }
3891+ };
3892+ // Skip if promotion would not strictly reduce byte count.
3893+ // Before: n * l bytes. After: (l + name.len() + 2) for the :root
3894+ // declaration (`<name>:<value>;`) plus n * ref_len for the sites.
3895+ let decl_overhead = l + name.len() + 2;
3896+ let before = n * l;
3897+ let after = decl_overhead + n * ref_len;
3898+ if after < before {
3899+ extracted.push((name, value));
3900+ } else {
3901+ // Rewind the index so the next value can reuse this slot.
3902+ next_idx -= 1;
20293903 }
20303904 }
3905+
3906+ if extracted.is_empty() {
3907+ return (css.to_string(), Vec::new());
3908+ }
3909+ let new_css = substitute_css_vars(css, &extracted);
3910+ (new_css, extracted)
20313911}
20323912
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));
3913+/// Format a `line-height` value. CSS accepts either a unitless multiplier
3914+/// (e.g. `1.5`) or a length (e.g. `24px`). Plain integers in htmlang source
3915+/// are ambiguous: `[line-height 24]` was historically emitted as `24` (which
3916+/// CSS interprets as 24× font-size — almost never what anyone wants). Treat
3917+/// integers ≥ 2 as pixel lengths; anything with a decimal, an existing unit,
3918+/// or the value `0`/`1` passes through unchanged.
3919+fn css_line_height(value: &str) -> String {
3920+ let v = value.trim();
3921+ if v == "0" || v == "1" {
3922+ return v.to_string();
20533923 }
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);
3924+ if v.contains('.') {
3925+ return v.to_string();
20623926 }
2063− for &(property, value) in &sets {
2064− sizes.push(&mut css, property, value);
3927+ if CSS_UNITS.iter().any(|u| v.ends_with(u)) || v.ends_with("px") {
3928+ return v.to_string();
20653929 }
2066− css
3930+ if v.starts_with("var(")
3931+ || v.starts_with("calc(")
3932+ || v.starts_with("clamp(")
3933+ || v.starts_with("min(")
3934+ || v.starts_with("max(")
3935+ {
3936+ return v.to_string();
3937+ }
3938+ // Plain integer — treat as pixel length.
3939+ if v.chars().all(|c| c.is_ascii_digit()) {
3940+ return format!("{}px", v);
3941+ }
3942+ v.to_string()
20673943}
20683944
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()
3945+/// Format multiple space-separated values, each getting px if needed.
3946+fn css_px_multi(value: &str) -> String {
3947+ value
3948+ .split_whitespace()
3949+ .map(css_px)
3950+ .collect::<Vec<_>>()
3951+ .join(" ")
20783952}
20793953
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);
3954+fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
3955+ let mut id = None;
3956+ let mut class = None;
3957+ for attr in attrs {
3958+ match attr.key.as_str() {
3959+ "id" => id = attr.value.clone(),
3960+ "class" => class = attr.value.clone(),
3961+ _ => {}
20993962 }
21003963 }
2101− Some(class)
3964+ (id, class)
21023965}
21033966
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− _ => "",
3967+/// Read image dimensions from a local file by parsing the header bytes.
3968+/// Supports PNG, JPEG, GIF, WebP, AVIF, and SVG.
3969+fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
3970+ // SVG: parse as text for viewBox/width/height attributes
3971+ if path.ends_with(".svg") || path.ends_with(".SVG") {
3972+ let text = std::fs::read_to_string(path).ok()?;
3973+ return read_svg_dimensions(&text);
21153974 }
2116−}
21173975
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− }
3976+ let data = std::fs::read(path).ok()?;
3977+ if data.len() < 12 {
3978+ return None;
3979+ }
21593980
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− }
3981+ // PNG: 8-byte signature, then IHDR chunk with width/height at bytes 16-23
3982+ if data.len() >= 24 && data.starts_with(b"\x89PNG\r\n\x1a\n") {
3983+ let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
3984+ let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
3985+ return Some((w, h));
3986+ }
21663987
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" => {
2172− if let Some(v) = val {
2173− push_css(&mut css, "gap", &with_px("gap", v));
2174− }
2175− }
3988+ // GIF: "GIF87a" or "GIF89a", width/height at bytes 6-9 (little-endian)
3989+ if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
3990+ let w = u16::from_le_bytes([data[6], data[7]]) as u32;
3991+ let h = u16::from_le_bytes([data[8], data[9]]) as u32;
3992+ return Some((w, h));
3993+ }
21763994
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;
2188− }
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− }
2237− }
2238− if let Some(v) = val {
2239− push_css(&mut css, effective_key, &with_px(effective_key, v));
2240− }
3995+ // JPEG: scan for SOF0/SOF2 marker (0xFF 0xC0 or 0xFF 0xC2)
3996+ if data.starts_with(b"\xff\xd8") {
3997+ let mut i = 2;
3998+ while i + 9 < data.len() {
3999+ if data[i] != 0xFF {
4000+ i += 1;
4001+ continue;
22414002 }
2242−
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");
4003+ let marker = data[i + 1];
4004+ if marker == 0xC0 || marker == 0xC2 {
4005+ let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
4006+ let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
4007+ return Some((w, h));
22494008 }
2250− "center-y" => {
2251− push_css(&mut aligned, "margin-top", "auto");
2252− push_css(&mut aligned, "margin-bottom", "auto");
4009+ if i + 3 < data.len() {
4010+ let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
4011+ i += 2 + len;
4012+ } else {
4013+ break;
22534014 }
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"),
4015+ }
4016+ }
22584017
2259− "wrap" if lays_out_children => push_css(&mut css, "flex-wrap", "wrap"),
2260− "wrap" => {}
4018+ // WebP: "RIFF" ... "WEBP", VP8 header at byte 20
4019+ if data.len() >= 30 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
4020+ if &data[12..16] == b"VP8 " && data.len() >= 30 {
4021+ let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
4022+ let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
4023+ return Some((w, h));
4024+ }
4025+ if &data[12..16] == b"VP8L" && data.len() >= 25 && data[21] == 0x2F {
4026+ let bits = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
4027+ let w = (bits & 0x3FFF) + 1;
4028+ let h = ((bits >> 14) & 0x3FFF) + 1;
4029+ return Some((w, h));
4030+ }
4031+ }
22614032
2262− // Grid
2263− "grid-cols" | "grid-rows" if !lays_out_children => {}
2264− "grid-cols" | "grid-rows" => {
2265− 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− }
2275− }
2276− }
2277− "col-span" | "row-span" => {
2278− if let Some(v) = val {
2279− let property = if effective_key == "col-span" {
2280− "grid-column"
2281− } else {
2282− "grid-row"
2283− };
2284− push_css(&mut css, property, &format!("span {}", v));
2285− }
2286− }
4033+ // AVIF: ISOBMFF container with "ftyp" box containing "avif"/"avis" brand,
4034+ // then "ispe" box with width/height
4035+ if data.len() >= 12 && &data[4..8] == b"ftyp" {
4036+ let brand = &data[8..12];
4037+ if brand == b"avif" || brand == b"avis" || brand == b"mif1" {
4038+ return read_avif_dimensions(&data);
4039+ }
4040+ }
22874041
2288− // CSS's `line-clamp` has no support yet without its
2289− // `-webkit-` fallback, which needs a box to clamp
2290− "line-clamp" => {
2291− if let Some(v) = val {
2292− push_css(&mut css, "display", "-webkit-box");
2293− push_css(&mut css, "-webkit-line-clamp", v);
2294− push_css(&mut css, "-webkit-box-orient", "vertical");
2295− push_css(&mut css, "overflow", "hidden");
2296− }
2297− }
4042+ None
4043+}
22984044
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) => {
2305− if let Some(v) = val {
2306− push_css(&mut css, key, &with_px(key, v));
2307− }
4045+/// Parse SVG viewBox or width/height attributes to get dimensions.
4046+fn read_svg_dimensions(text: &str) -> Option<(u32, u32)> {
4047+ // Try viewBox first: viewBox="minX minY width height"
4048+ if let Some(vb_start) = text.find("viewBox=\"") {
4049+ let rest = &text[vb_start + 9..];
4050+ if let Some(end) = rest.find('"') {
4051+ let parts: Vec<&str> = rest[..end].split_whitespace().collect();
4052+ if parts.len() == 4
4053+ && let (Ok(w), Ok(h)) = (parts[2].parse::<f64>(), parts[3].parse::<f64>())
4054+ && w > 0.0
4055+ && h > 0.0
4056+ {
4057+ return Some((w.round() as u32, h.round() as u32));
23084058 }
2309−
2310− _ => {}
23114059 }
23124060 }
2313−
2314− css.push_str(&aligned);
2315− css
4061+ // Fall back to width/height attributes on <svg>
4062+ let svg_tag = text.find("<svg")?;
4063+ let tag_end = text[svg_tag..].find('>')? + svg_tag;
4064+ let tag = &text[svg_tag..tag_end];
4065+ let w = extract_svg_attr(tag, "width")?;
4066+ let h = extract_svg_attr(tag, "height")?;
4067+ Some((w, h))
23164068}
23174069
2318−fn push_css(css: &mut String, prop: &str, value: &str) {
2319− css.push_str(prop);
2320− css.push(':');
2321− css.push_str(value);
2322− css.push(';');
4070+fn extract_svg_attr(tag: &str, attr: &str) -> Option<u32> {
4071+ let needle = format!("{}=\"", attr);
4072+ let start = tag.find(&needle)? + needle.len();
4073+ let rest = &tag[start..];
4074+ let end = rest.find('"')?;
4075+ let val = rest[..end].trim_end_matches("px");
4076+ val.parse::<f64>().ok().map(|v| v.round() as u32)
23234077}
23244078
2325−fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
2326− let mut id = None;
2327− let mut class = None;
2328− for attr in attrs.iter().filter(|a| a.html) {
2329− match attr.key.as_str() {
2330− "id" => id = attr.value.clone(),
2331− "class" => class = attr.value.clone(),
2332− _ => {}
4079+/// Parse AVIF (ISOBMFF) container to find ispe box with image dimensions.
4080+fn read_avif_dimensions(data: &[u8]) -> Option<(u32, u32)> {
4081+ // Walk ISOBMFF boxes looking for "ispe" (image spatial extents)
4082+ let mut i = 0;
4083+ while i + 8 <= data.len() {
4084+ let box_size =
4085+ u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as usize;
4086+ let box_type = &data[i + 4..i + 8];
4087+ if box_size < 8 {
4088+ break;
4089+ }
4090+ let box_end = (i + box_size).min(data.len());
4091+ // ispe box: 4 bytes version/flags + 4 bytes width + 4 bytes height
4092+ if box_type == b"ispe" && box_end >= i + 20 {
4093+ let w = u32::from_be_bytes([data[i + 12], data[i + 13], data[i + 14], data[i + 15]]);
4094+ let h = u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
4095+ return Some((w, h));
4096+ }
4097+ // Recurse into container boxes (meta, iprp, ipco)
4098+ if matches!(
4099+ box_type,
4100+ b"meta" | b"iprp" | b"ipco" | b"moov" | b"trak" | b"mdia"
4101+ ) {
4102+ let header_size = if box_type == b"meta" { 12 } else { 8 };
4103+ if i + header_size < box_end
4104+ && let Some(dims) = read_avif_dimensions(&data[i + header_size..box_end])
4105+ {
4106+ return Some(dims);
4107+ }
23334108 }
4109+ i = box_end;
23344110 }
2335− (id, class)
4111+ None
23364112}
23374113
23384114fn html_escape(s: &str) -> String {
@@ -2373,24 +4149,10 @@ fn base64_encode(data: &[u8]) -> String {
23734149/// Generate a standard v3 source map with VLQ-encoded mappings.
23744150/// Compatible with browser devtools and source map tooling.
23754151pub 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 {
23824152 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− }
4153+ collect_source_lines(&doc.nodes, &mut mappings);
4154+ mappings.sort_by_key(|m| m.0);
4155+ mappings.dedup_by_key(|m| m.0);
23944156
23954157 // Build VLQ-encoded mappings string.
23964158 // Each generated line is separated by ';'. Each segment within a line is
@@ -2450,30 +4212,60 @@ fn vlq_encode(value: i64, out: &mut String) {
24504212 }
24514213}
24524214
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()));
4215+fn collect_source_lines(nodes: &[Node], mappings: &mut Vec<(usize, usize)>) {
4216+ for node in nodes {
4217+ if let Node::Element(elem) = node {
4218+ if elem.line_num > 0 {
4219+ mappings.push((mappings.len() + 1, elem.line_num));
4220+ }
4221+ collect_source_lines(&elem.children, mappings);
4222+ }
4223+ }
4224+}
4225+
4226+/// Check if a specific element kind exists anywhere in the node tree.
4227+fn has_element_kind(nodes: &[Node], target: &ElementKind) -> bool {
4228+ for node in nodes {
4229+ if let Node::Element(elem) = node {
4230+ if elem.kind == *target {
4231+ return true;
4232+ }
4233+ if has_element_kind(&elem.children, target) {
4234+ return true;
4235+ }
4236+ }
4237+ }
4238+ false
4239+}
4240+
4241+/// Collect unique external domains from generated HTML for DNS prefetch hints.
4242+fn collect_dns_prefetch(html: &str, dev: bool) -> String {
4243+ let mut domains = Vec::new();
4244+ let mut rest = html;
4245+ while let Some(pos) = rest.find("https://") {
4246+ let start = pos + 8; // skip "https://"
4247+ rest = &rest[start..];
4248+ let end = rest
4249+ .find(['/', '"', '\'', ' ', '>', ')'])
4250+ .unwrap_or(rest.len());
4251+ let domain = &rest[..end];
4252+ if !domain.is_empty() && domain.contains('.') && !domains.contains(&domain.to_string()) {
4253+ domains.push(domain.to_string());
4254+ }
4255+ }
4256+ let mut out = String::new();
4257+ for domain in &domains {
4258+ if dev {
4259+ out.push_str(&format!(
4260+ "<link rel=\"dns-prefetch\" href=\"//{}\">\n",
4261+ domain
4262+ ));
4263+ } else {
4264+ out.push_str(&format!(
4265+ "<link rel=\"dns-prefetch\" href=\"//{}\">",
4266+ domain
4267+ ));
4268+ }
24784269 }
4270+ out
24794271}