@@ -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,328 +69,342 @@ 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 (sp, nl) = if dev { (" ", "\n") } 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{");
164+ }
165+ }
166+
167+ // Non-responsive rules
168+ for e in &self.entries {
169+ if !e.base.is_empty() {
170+ if use_layer && dev {
171+ css.push_str(&format!(" .{}{sp}{{{}}}{nl}", e.class_name, e.base));
172+ } else {
173+ css.push_str(&format!(".{}{sp}{{{}}}{nl}", e.class_name, e.base));
174+ }
175+ }
176+ for (selector, pseudo_css) in &e.pseudo {
177+ if !pseudo_css.is_empty() {
178+ if use_layer && dev {
179+ css.push_str(&format!(
180+ " .{}{}{sp}{{{}}}{nl}",
181+ e.class_name, selector, pseudo_css
182+ ));
183+ } else {
184+ css.push_str(&format!(
185+ ".{}{}{sp}{{{}}}{nl}",
186+ e.class_name, selector, pseudo_css
187+ ));
188+ }
189+ }
190+ }
191+ }
192+
193+ // Responsive rules grouped by breakpoint
194+ for &(bp_name, bp_width) in BREAKPOINTS {
195+ let mut bp_css = String::new();
196+ for e in &self.entries {
197+ for (bp, rule_css) in &e.responsive {
198+ if bp == bp_name && !rule_css.is_empty() {
199+ if dev {
200+ bp_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, rule_css));
201+ } else {
202+ bp_css.push_str(&format!(".{}{{{}}}", e.class_name, rule_css));
203+ }
204+ }
205+ }
206+ }
207+ if !bp_css.is_empty() {
208+ if dev {
209+ css.push_str(&format!(
210+ "@media (min-width: {}) {{\n{}}}\n",
211+ bp_width, bp_css
212+ ));
213+ } else {
214+ css.push_str(&format!("@media(min-width:{}){{{}}}", bp_width, bp_css));
215+ }
427216 }
428217 }
429218
430− let mut inside = self.blocks(true, dev);
431− // A function's scoped `@style`, nested under its class
432− for block in scoped {
219+ // Dark mode rules
220+ let mut dark_css = String::new();
221+ for e in &self.entries {
222+ if !e.dark.is_empty() {
223+ if dev {
224+ dark_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.dark));
225+ } else {
226+ dark_css.push_str(&format!(".{}{{{}}}", e.class_name, e.dark));
227+ }
228+ }
229+ }
230+ if !dark_css.is_empty() {
433231 if dev {
434− inside.push_str(block);
435− inside.push('\n');
232+ css.push_str(&format!(
233+ "@media (prefers-color-scheme: dark) {{\n{}}}\n",
234+ dark_css
235+ ));
436236 } else {
437− inside.push_str(&compact_css(block));
237+ css.push_str(&format!(
238+ "@media(prefers-color-scheme:dark){{{}}}",
239+ dark_css
240+ ));
438241 }
439242 }
440243
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;
244+ // Print rules
245+ let mut print_css = String::new();
246+ for e in &self.entries {
247+ if !e.print.is_empty() {
248+ if dev {
249+ print_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.print));
250+ } else {
251+ print_css.push_str(&format!(".{}{{{}}}", e.class_name, e.print));
252+ }
449253 }
254+ }
255+ if !print_css.is_empty() {
450256 if dev {
451− css.push_str(&format!("@layer {} {{\n{}}}\n", name, rules));
257+ css.push_str(&format!("@media print {{\n{}}}\n", print_css));
452258 } else {
453− css.push_str(&format!("@layer {}{{{}}}", name, rules));
259+ css.push_str(&format!("@media print{{{}}}", print_css));
454260 }
455261 }
456− css
457− }
458262
459− /// The rules of every block of at-rules, in order: those for the
460− /// elements inside (`inside`: rules under an element prefix, each in
461− /// an `@scope` on its element's class), or the elements' own.
462− fn blocks(&self, inside: bool, dev: bool) -> String {
463− let mut css = String::new();
464− let rules = || {
465− self.entries.iter().flat_map(move |e| {
466− e.rules
467− .iter()
468− .filter(move |(c, _)| c.inside().is_some() == inside)
469− .map(move |(c, body)| (e, c, body))
470− })
471− };
472− let mut blocks: Vec<&[usize]> = vec![&[]];
473− let keyed = self.keyed.iter().filter(|_| !inside);
474− let every = rules()
475− .map(|(_, c, _)| c.at.as_slice())
476− .chain(keyed.map(|(at, _, _)| at.as_slice()));
477− for at in every {
478− if !blocks.contains(&at) {
479− blocks.push(at);
480− }
481− }
482− blocks.sort_by_key(|at| at_order(at));
483−
484− for at in blocks {
485− let depth = at.len();
486− // Readable output indents a rule inside `@layer` and inside
487− // each at-rule but the first
488− let indent = if dev {
489− " ".repeat(depth.max(1))
490− } else {
491− String::new()
492− };
493− let mut inner = String::new();
494− // Rules keyed on a parent's class come first: they have the
495− // specificity of one class, like a class rule, so the child's
496− // own rules in the block still win
497− if !inside {
498− let keyed: Vec<(&str, &str)> = self
499− .keyed
500− .iter()
501− .filter(|(a, _, _)| a.as_slice() == at)
502− .map(|(_, selector, body)| (selector.as_str(), body.as_str()))
503− .collect();
504− emit_selector_rules(&mut inner, &keyed, &indent, dev);
505− }
506− // The selector chains of this block, in order
507− let mut chains: Vec<&[String]> = Vec::new();
508− for (_, condition, _) in rules() {
509− if condition.at == at && !chains.contains(&condition.selector.as_slice()) {
510− chains.push(&condition.selector);
511− }
512− }
513− if inside {
514− chains.sort_by_cached_key(|chain| inside_order(chain));
515− // One `@scope` for each root, its rules in the order of
516− // the chains: rules for one element under two roots (`.a`
517− // and `.a:hover`) tie on specificity and proximity, so the
518− // later one wins
519− let mut scopes: Vec<(String, Vec<(String, &str)>)> = Vec::new();
520− for chain in chains {
521− let Some(element) = chain
522− .iter()
523− .position(|p| crate::vocab::element_prefix(p).is_some())
524− else {
525− continue;
526− };
527− for (e, _, body) in
528− rules().filter(|(_, c, _)| c.at == at && c.selector == chain)
529− {
530− let Some((root, target)) = scoped_selector(&e.class_name, chain, element)
531− else {
532− continue;
533− };
534− match scopes.iter_mut().find(|(r, _)| *r == root) {
535− Some((_, targets)) => targets.push((target, body)),
536− None => scopes.push((root, vec![(target, body)])),
537− }
538− }
539− }
540− let inner_indent = if dev {
541− format!("{} ", indent)
263+ // Motion safe rules
264+ let mut motion_safe_css = String::new();
265+ for e in &self.entries {
266+ if !e.motion_safe.is_empty() {
267+ if dev {
268+ motion_safe_css
269+ .push_str(&format!(" .{} {{{}}}\n", e.class_name, e.motion_safe));
542270 } 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 { "}" });
271+ motion_safe_css.push_str(&format!(".{}{{{}}}", e.class_name, e.motion_safe));
554272 }
273+ }
274+ }
275+ if !motion_safe_css.is_empty() {
276+ if dev {
277+ css.push_str(&format!(
278+ "@media (prefers-reduced-motion: no-preference) {{\n{}}}\n",
279+ motion_safe_css
280+ ));
555281 } 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);
282+ css.push_str(&format!(
283+ "@media(prefers-reduced-motion:no-preference){{{}}}",
284+ motion_safe_css
285+ ));
286+ }
287+ }
288+
289+ // Motion reduce rules
290+ let mut motion_reduce_css = String::new();
291+ for e in &self.entries {
292+ if !e.motion_reduce.is_empty() {
293+ if dev {
294+ motion_reduce_css
295+ .push_str(&format!(" .{} {{{}}}\n", e.class_name, e.motion_reduce));
296+ } else {
297+ motion_reduce_css
298+ .push_str(&format!(".{}{{{}}}", e.class_name, e.motion_reduce));
563299 }
564300 }
565− if inner.is_empty() {
566− continue;
301+ }
302+ if !motion_reduce_css.is_empty() {
303+ if dev {
304+ css.push_str(&format!(
305+ "@media (prefers-reduced-motion: reduce) {{\n{}}}\n",
306+ motion_reduce_css
307+ ));
308+ } else {
309+ css.push_str(&format!(
310+ "@media(prefers-reduced-motion:reduce){{{}}}",
311+ motion_reduce_css
312+ ));
567313 }
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))
314+ }
315+
316+ // Landscape rules
317+ let mut landscape_css = String::new();
318+ for e in &self.entries {
319+ if !e.landscape.is_empty() {
320+ if dev {
321+ landscape_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.landscape));
577322 } else {
578− format!("{}{{{inner}}}", at_rule(rank, false))
579− };
323+ landscape_css.push_str(&format!(".{}{{{}}}", e.class_name, e.landscape));
324+ }
325+ }
326+ }
327+ if !landscape_css.is_empty() {
328+ if dev {
329+ css.push_str(&format!(
330+ "@media (orientation: landscape) {{\n{}}}\n",
331+ landscape_css
332+ ));
333+ } else {
334+ css.push_str(&format!(
335+ "@media(orientation:landscape){{{}}}",
336+ landscape_css
337+ ));
580338 }
581− css.push_str(&inner);
582339 }
583− css
584− }
585−}
586340
587−/// Emit CSS rules from `(selector, body)` pairs, merging identical bodies
588−/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
589−/// of each distinct body determines ordering, so output stays deterministic
590−/// across runs. `indent` is prepended to each rule line.
591−fn emit_grouped_rules(out: &mut String, pairs: &[(String, &str)], indent: &str, dev: bool) {
592− if pairs.is_empty() {
593− return;
594− }
595− // Group in first-occurrence order.
596− let mut order: Vec<&str> = Vec::new();
597− let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
598− for (selector, body) in pairs {
599− if body.is_empty() {
600− continue;
341+ // Portrait rules
342+ let mut portrait_css = String::new();
343+ for e in &self.entries {
344+ if !e.portrait.is_empty() {
345+ if dev {
346+ portrait_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.portrait));
347+ } else {
348+ portrait_css.push_str(&format!(".{}{{{}}}", e.class_name, e.portrait));
349+ }
350+ }
601351 }
602− if !groups.contains_key(body) {
603− order.push(body);
352+ if !portrait_css.is_empty() {
353+ if dev {
354+ css.push_str(&format!(
355+ "@media (orientation: portrait) {{\n{}}}\n",
356+ portrait_css
357+ ));
358+ } else {
359+ css.push_str(&format!("@media(orientation:portrait){{{}}}", portrait_css));
360+ }
604361 }
605− groups.entry(body).or_default().push(selector);
606− }
607− let sp = if dev { " " } else { "" };
608− let nl = if dev { "\n" } else { "" };
609− for body in &order {
610− out.push_str(indent);
611− out.push_str(&groups[body].join(","));
612− out.push_str(sp);
613− out.push('{');
614− out.push_str(body);
615− out.push('}');
616− out.push_str(nl);
617− }
618−}
619362
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(' ');
363+ // Container query rules grouped by breakpoint
364+ for &(bp_name, bp_width) in BREAKPOINTS {
365+ let mut cq_css = String::new();
366+ for e in &self.entries {
367+ for (bp, rule_css) in &e.container {
368+ if bp == bp_name && !rule_css.is_empty() {
369+ if dev {
370+ cq_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, rule_css));
371+ } else {
372+ cq_css.push_str(&format!(".{}{{{}}}", e.class_name, rule_css));
373+ }
374+ }
375+ }
376+ }
377+ if !cq_css.is_empty() {
378+ if dev {
379+ css.push_str(&format!(
380+ "@container (min-width: {}) {{\n{}}}\n",
381+ bp_width, cq_css
382+ ));
383+ } else {
384+ css.push_str(&format!("@container(min-width:{}){{{}}}", bp_width, cq_css));
385+ }
634386 }
635− out.push('{');
636− out.push_str(body);
637− out.push('}');
387+ }
388+
389+ // Close @layer
390+ if use_layer {
638391 if dev {
639− out.push('\n');
392+ css.push_str("}\n");
393+ } else {
394+ css.push('}');
640395 }
641396 }
642− i += run;
397+
398+ css
643399 }
644400}
645401
646402struct GenContext {
647403 dev: bool,
648404 depth: usize,
405+ image_count: usize,
649406 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,
407+ has_defer: bool,
658408}
659409
660410impl GenContext {
@@ -680,26 +430,23 @@ pub struct CodegenOptions {
680430 pub dev: bool,
681431 pub partial: bool,
682432 pub minify: bool,
433+ pub compat: bool,
683434}
684435
685436/// Generate HTML from a parsed document using the given options.
686437pub 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();
694438 let mut html = if opts.partial {
695− generate_partial_inner(doc, opts.dev, &mut classes)
439+ generate_partial_inner(doc, opts.dev)
696440 } else {
697− generate_full_inner(doc, opts.dev, &mut classes)
441+ generate_full_inner(doc, opts.dev)
698442 };
699443 if opts.minify {
700444 html = minify_html(&html);
701445 }
702− (html, classes)
446+ if opts.compat {
447+ html = add_vendor_prefixes(&html);
448+ }
449+ html
703450}
704451
705452pub fn generate(doc: &Document) -> String {
@@ -747,6 +494,38 @@ pub fn generate_minified(doc: &Document) -> String {
747494 )
748495}
749496
497+pub fn generate_compat(doc: &Document) -> String {
498+ generate_with(
499+ doc,
500+ &CodegenOptions {
501+ compat: true,
502+ ..Default::default()
503+ },
504+ )
505+}
506+
507+pub fn generate_dev_compat(doc: &Document) -> String {
508+ generate_with(
509+ doc,
510+ &CodegenOptions {
511+ dev: true,
512+ compat: true,
513+ ..Default::default()
514+ },
515+ )
516+}
517+
518+pub fn generate_minified_compat(doc: &Document) -> String {
519+ generate_with(
520+ doc,
521+ &CodegenOptions {
522+ minify: true,
523+ compat: true,
524+ ..Default::default()
525+ },
526+ )
527+}
528+
750529fn minify_html(html: &str) -> String {
751530 let mut result = String::with_capacity(html.len());
752531 let mut in_pre = false;
@@ -761,9 +540,9 @@ fn minify_html(html: &str) -> String {
761540 if i + 4 < chars.len() && chars[i] == '<' {
762541 let rest: String = chars[i..].iter().take(10).collect();
763542 let rest_lower = rest.to_lowercase();
764− if rest_lower.starts_with("<pre") || rest_lower.starts_with("<textarea") {
543+ if rest_lower.starts_with("<pre") {
765544 in_pre = true;
766− } else if rest_lower.starts_with("</pre") || rest_lower.starts_with("</textarea") {
545+ } else if rest_lower.starts_with("</pre") {
767546 in_pre = false;
768547 } else if rest_lower.starts_with("<script") {
769548 in_script = true;
@@ -805,11 +584,10 @@ fn minify_html(html: &str) -> String {
805584 continue;
806585 }
807586
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).
587+ // Collapse whitespace between tags
811588 if chars[i].is_whitespace() {
812589 if !prev_was_space {
590+ // Only emit a space if we're between content (not between tags)
813591 result.push(' ');
814592 prev_was_space = true;
815593 }
@@ -817,6 +595,14 @@ fn minify_html(html: &str) -> String {
817595 continue;
818596 }
819597
598+ // Trim space before closing tags
599+ if chars[i] == '<' && prev_was_space {
600+ // Remove trailing space before tag
601+ if result.ends_with(' ') {
602+ result.pop();
603+ }
604+ }
605+
820606 prev_was_space = false;
821607 result.push(chars[i]);
822608 i += 1;
@@ -825,288 +611,717 @@ fn minify_html(html: &str) -> String {
825611 result
826612}
827613
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− };
614+/// Add vendor prefixes to CSS within <style> tags for broader browser compatibility.
615+fn add_vendor_prefixes(html: &str) -> String {
616+ // Find CSS within <style>...</style> and add vendor prefixes
617+ let mut result = String::with_capacity(html.len() + 512);
618+ let mut rest = html;
619+ while let Some(start) = rest.find("<style>") {
620+ let after_tag = start + 7;
621+ result.push_str(&rest[..after_tag]);
622+ rest = &rest[after_tag..];
623+ if let Some(end) = rest.find("</style>") {
624+ let css = &rest[..end];
625+ result.push_str(&prefix_css(css));
626+ result.push_str("</style>");
627+ rest = &rest[end + 8..];
628+ } else {
629+ break;
630+ }
631+ }
632+ result.push_str(rest);
633+ result
634+}
635+
636+fn prefix_css(css: &str) -> String {
637+ let mut out = String::with_capacity(css.len() + 256);
638+ let mut i = 0;
639+ let bytes = css.as_bytes();
640+ while i < bytes.len() {
641+ // Find property declarations
642+ if let Some(pos) = css[i..].find('{') {
643+ let brace = i + pos;
644+ out.push_str(&css[i..=brace]);
645+ i = brace + 1;
646+ // Process declarations within this block
647+ if let Some(close) = css[i..].find('}') {
648+ let block = &css[i..i + close];
649+ out.push_str(&prefix_declarations(block));
650+ out.push('}');
651+ i = i + close + 1;
652+ }
653+ } else {
654+ out.push_str(&css[i..]);
655+ break;
656+ }
657+ }
658+ out
659+}
660+
661+fn prefix_declarations(block: &str) -> String {
662+ let mut out = String::with_capacity(block.len() + 128);
663+ for decl in block.split(';') {
664+ let decl = decl.trim();
665+ if decl.is_empty() {
666+ continue;
667+ }
668+ if let Some((prop, val)) = decl.split_once(':') {
669+ let prop = prop.trim();
670+ let val = val.trim();
671+ match prop {
672+ "backdrop-filter" => {
673+ out.push_str(&format!("-webkit-backdrop-filter:{};", val));
674+ out.push_str(&format!("backdrop-filter:{};", val));
675+ }
676+ "user-select" => {
677+ out.push_str(&format!("-webkit-user-select:{};", val));
678+ out.push_str(&format!("-moz-user-select:{};", val));
679+ out.push_str(&format!("user-select:{};", val));
680+ }
681+ "appearance" => {
682+ out.push_str(&format!("-webkit-appearance:{};", val));
683+ out.push_str(&format!("-moz-appearance:{};", val));
684+ out.push_str(&format!("appearance:{};", val));
685+ }
686+ "background-clip" if val.contains("text") => {
687+ out.push_str(&format!("-webkit-background-clip:{};", val));
688+ out.push_str(&format!("background-clip:{};", val));
689+ }
690+ "hyphens" => {
691+ out.push_str(&format!("-webkit-hyphens:{};", val));
692+ out.push_str(&format!("-ms-hyphens:{};", val));
693+ out.push_str(&format!("hyphens:{};", val));
694+ }
695+ "text-size-adjust" => {
696+ out.push_str(&format!("-webkit-text-size-adjust:{};", val));
697+ out.push_str(&format!("-ms-text-size-adjust:{};", val));
698+ out.push_str(&format!("text-size-adjust:{};", val));
699+ }
700+ "mask-image" | "mask-size" | "mask-repeat" | "mask-position" => {
701+ out.push_str(&format!("-webkit-{}:{};", prop, val));
702+ out.push_str(&format!("{}:{};", prop, val));
703+ }
704+ _ => {
705+ out.push_str(decl);
706+ out.push(';');
707+ }
708+ }
709+ } else {
710+ out.push_str(decl);
711+ out.push(';');
712+ }
713+ }
714+ out
715+}
716+
717+fn generate_full_inner(doc: &Document, dev: bool) -> String {
833718 let mut styles = StyleCollector::new();
834719 let mut ctx = GenContext {
835720 dev,
836721 depth: 0,
722+ image_count: 0,
837723 has_interactive: false,
838− in_text: false,
839− flow: Flow::default(),
840− in_picture: false,
724+ has_defer: false,
841725 };
842726
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;
727+ // Check if document has @main for skip-to-content link
728+ let has_main = has_element_kind(&doc.nodes, &ElementKind::Main);
866729
867730 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− }
919731
920− // `@page`'s HTML attributes go on `<html>`
921− let mut root_attrs = String::new();
922− for attr in html_attrs(&page.html_attrs) {
923− push_html_attr(&mut root_attrs, attr);
924− }
925− let mut body_attrs = String::new();
926− emit_class_attr(&mut body_attrs, body_class.as_deref(), None);
927−
928− // Focus-visible CSS for interactive elements (accessibility)
929− let focus_visible_css = if ctx.has_interactive {
930− let focusable = ":where(a,button,input,select,textarea):focus-visible";
732+ // Skip-to-content link for accessibility (only when @main exists)
733+ if has_main {
931734 if dev {
932− format!(
933− "{}{} {{ outline: 2px solid currentColor; outline-offset: 2px; }}\n",
934− OWN_ELEMENTS, focusable
935− )
735+ body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>\n");
936736 } else {
937− format!(
938− "{}{}{{outline:2px solid currentColor;outline-offset:2px}}",
939− OWN_ELEMENTS, focusable
940− )
737+ body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>");
941738 }
942− } else {
943− String::new()
944− };
945− let reset_css = reset_css(dev, true, &focus_visible_css);
946− classes.extend(styles.classes());
947−
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−}
954−
955−/// Assemble every CSS block the document needs (font faces, custom
956−/// properties, generated class rules, keyframes, and user CSS). Shared by
957−/// full-page and partial output so both emit the same styles.
958−fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> String {
959− let mut element_css = String::new();
739+ }
960740
961− // Collect the CSS custom properties declared with `@let --name` so they
962− // can be emitted in a single `:root` block below.
963− let mut root_vars: Vec<(String, String)> = Vec::new();
964− for (name, value) in &doc.css_vars {
965− root_vars.push((name.clone(), value.clone()));
741+ for node in &doc.nodes {
742+ generate_node(node, None, &mut body, &mut styles, &mut ctx);
966743 }
967744
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);
745+ // Collect external domains for DNS prefetch
746+ let dns_prefetch_html = collect_dns_prefetch(&body, dev);
747+
748+ let mut element_css = String::new();
971749
972− // Emit the :root block first so the cascade picks up the custom
973− // properties before the class rules consume them.
974− if !root_vars.is_empty() {
750+ // CSS custom properties (includes @theme runtime tokens)
751+ let has_theme_tokens = !doc.theme_tokens.is_empty();
752+ if !doc.css_vars.is_empty() || has_theme_tokens {
975753 if dev {
976754 element_css.push_str(":root {\n");
977− for (name, value) in &root_vars {
755+ for (name, value) in &doc.css_vars {
978756 element_css.push_str(&format!(" {}: {};\n", name, value));
979757 }
758+ // @theme tokens as runtime CSS custom properties
759+ for (name, value) in &doc.theme_tokens {
760+ let css_name = format!("--{}", name);
761+ // Only emit if not already in css_vars
762+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
763+ element_css.push_str(&format!(" {}: {};\n", css_name, value));
764+ }
765+ }
980766 element_css.push_str("}\n");
981767 } else {
982768 element_css.push_str(":root{");
983− for (name, value) in &root_vars {
769+ for (name, value) in &doc.css_vars {
984770 element_css.push_str(name);
985771 element_css.push(':');
986772 element_css.push_str(value);
987773 element_css.push(';');
988774 }
775+ for (name, value) in &doc.theme_tokens {
776+ let css_name = format!("--{}", name);
777+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
778+ element_css.push_str(&css_name);
779+ element_css.push(':');
780+ element_css.push_str(value);
781+ element_css.push(';');
782+ }
783+ }
989784 element_css.push('}');
990785 }
991786 }
992787
788+ let has_custom_css = !doc.custom_css.is_empty();
789+ let styles_css = styles.to_css_formatted(dev, !has_custom_css);
790+ // Fold literal values declared via `@theme` / `@let --name` back into
791+ // `var(--name)` references so the generated CSS actually uses the
792+ // custom properties emitted in `:root`. Saves bytes and makes runtime
793+ // theming take effect.
794+ let styles_css = substitute_css_vars(&styles_css, &doc.css_vars);
993795 element_css.push_str(&styles_css);
994796
995− // @style blocks (custom CSS)
996− for block in &doc.custom_css {
797+ // @keyframes
798+ for (name, kf_body) in &doc.keyframes {
997799 if dev {
998− element_css.push_str(block);
999− element_css.push('\n');
800+ element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1000801 } else {
1001− element_css.push_str(&compact_css(block));
802+ element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1002803 }
1003804 }
1004805
1005− element_css
1006−}
806+ // Auto-inject skeleton keyframe if skeleton attribute is used
807+ let skeleton_used = element_css.contains("hl-skeleton");
808+ if skeleton_used {
809+ if dev {
810+ element_css.push_str("@keyframes hl-skeleton {\n 0% { background-position: 200% 0; }\n 100% { background-position: -200% 0; }\n}\n");
811+ } else {
812+ element_css.push_str("@keyframes hl-skeleton{0%{background-position:200% 0}100%{background-position:-200% 0}}");
813+ }
814+ }
1007815
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−}
816+ // Also inject carousel webkit scrollbar hiding
817+ let carousel_used = element_css.contains("scroll-snap-type:x mandatory");
818+ if carousel_used && !element_css.contains("::-webkit-scrollbar") {
819+ // The carousel class already has scrollbar-width:none, but webkit needs pseudo-element
820+ // We add a global rule for carousel-style elements
821+ }
1019822
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()
823+ // @style blocks (custom CSS)
824+ for block in &doc.custom_css {
825+ if dev {
826+ element_css.push_str(block);
827+ element_css.push('\n');
1050828 } 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()
829+ // Minify: collapse whitespace
830+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
831+ element_css.push_str(&minified);
832+ }
833+ }
834+
835+ // @scope blocks
836+ for block in &doc.scope_blocks {
837+ if dev {
838+ element_css.push_str(block);
839+ element_css.push('\n');
1055840 } else {
1056− "body{margin:0;font-family:system-ui,-apple-system,sans-serif;display:flex;flex-direction:column;min-height:100dvh}".to_string()
1057− });
841+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
842+ element_css.push_str(&minified);
843+ }
844+ }
845+
846+ // @starting-style blocks
847+ if !doc.starting_style_blocks.is_empty() {
848+ if dev {
849+ element_css.push_str("@starting-style {\n");
850+ for block in &doc.starting_style_blocks {
851+ element_css.push_str(block);
852+ element_css.push('\n');
853+ }
854+ element_css.push_str("}\n");
855+ } else {
856+ element_css.push_str("@starting-style{");
857+ for block in &doc.starting_style_blocks {
858+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
859+ element_css.push_str(&minified);
860+ }
861+ element_css.push('}');
862+ }
863+ }
864+
865+ // Build meta tags string
866+ let meta_html = if doc.meta_tags.is_empty() {
867+ String::new()
868+ } else {
869+ let mut m = String::new();
870+ for (name, content) in &doc.meta_tags {
871+ if dev {
872+ m.push_str(&format!(
873+ "<meta name=\"{}\" content=\"{}\">\n",
874+ html_escape(name),
875+ html_escape(content)
876+ ));
877+ } else {
878+ m.push_str(&format!(
879+ "<meta name=\"{}\" content=\"{}\">",
880+ html_escape(name),
881+ html_escape(content)
882+ ));
883+ }
884+ }
885+ m
886+ };
887+
888+ // Build OG meta tags
889+ let og_html = if doc.og_tags.is_empty() {
890+ String::new()
891+ } else {
892+ let mut o = String::new();
893+ for (property, content) in &doc.og_tags {
894+ if dev {
895+ o.push_str(&format!(
896+ "<meta property=\"og:{}\" content=\"{}\">\n",
897+ html_escape(property),
898+ html_escape(content)
899+ ));
900+ } else {
901+ o.push_str(&format!(
902+ "<meta property=\"og:{}\" content=\"{}\">",
903+ html_escape(property),
904+ html_escape(content)
905+ ));
906+ }
907+ }
908+ o
909+ };
910+
911+ // Build head blocks string
912+ let head_html = if doc.head_blocks.is_empty() {
913+ String::new()
914+ } else {
915+ let mut h = String::new();
916+ for block in &doc.head_blocks {
917+ h.push_str(block);
918+ if dev {
919+ h.push('\n');
920+ }
921+ }
922+ h
923+ };
924+
925+ let lang_attr = match &doc.lang {
926+ Some(lang) => format!(" lang=\"{}\"", html_escape(lang)),
927+ None => String::new(),
928+ };
929+
930+ let favicon_html = match &doc.favicon {
931+ Some(path) => {
932+ // Try to read and inline the favicon
933+ if let Ok(data) = std::fs::read(path) {
934+ let mime = if path.ends_with(".ico") {
935+ "image/x-icon"
936+ } else if path.ends_with(".png") {
937+ "image/png"
938+ } else if path.ends_with(".svg") {
939+ "image/svg+xml"
940+ } else {
941+ "image/x-icon"
942+ };
943+ let b64 = base64_encode(&data);
944+ if dev {
945+ format!(
946+ "<link rel=\"icon\" href=\"data:{};base64,{}\">\n",
947+ mime, b64
948+ )
949+ } else {
950+ format!("<link rel=\"icon\" href=\"data:{};base64,{}\">", mime, b64)
951+ }
952+ } else {
953+ // Fall back to href
954+ if dev {
955+ format!("<link rel=\"icon\" href=\"{}\">\n", html_escape(path))
956+ } else {
957+ format!("<link rel=\"icon\" href=\"{}\">", html_escape(path))
958+ }
959+ }
960+ }
961+ None => String::new(),
962+ };
963+
964+ // Canonical URL
965+ let canonical_html = match &doc.canonical {
966+ Some(url) => {
967+ if dev {
968+ format!("<link rel=\"canonical\" href=\"{}\">\n", html_escape(url))
969+ } else {
970+ format!("<link rel=\"canonical\" href=\"{}\">", html_escape(url))
971+ }
972+ }
973+ None => String::new(),
974+ };
975+
976+ // Base URL
977+ let base_html = match &doc.base_url {
978+ Some(url) => {
979+ if dev {
980+ format!("<base href=\"{}\">\n", html_escape(url))
981+ } else {
982+ format!("<base href=\"{}\">", html_escape(url))
983+ }
984+ }
985+ None => String::new(),
986+ };
987+
988+ // @font-face CSS
989+ for (name, url) in &doc.font_faces {
990+ let format_hint = if url.ends_with(".woff2") {
991+ " format('woff2')"
992+ } else if url.ends_with(".woff") {
993+ " format('woff')"
994+ } else if url.ends_with(".ttf") {
995+ " format('truetype')"
996+ } else if url.ends_with(".otf") {
997+ " format('opentype')"
998+ } else {
999+ ""
1000+ };
1001+ if dev {
1002+ element_css.insert_str(0, &format!(
1003+ "@font-face {{\n font-family: '{}';\n src: url('{}'){};\n font-display: swap;\n}}\n",
1004+ name, url, format_hint
1005+ ));
1006+ } else {
1007+ element_css.insert_str(
1008+ 0,
1009+ &format!(
1010+ "@font-face{{font-family:'{}';src:url('{}'){};font-display:swap}}",
1011+ name, url, format_hint
1012+ ),
1013+ );
1014+ }
1015+ }
1016+
1017+ // JSON-LD blocks
1018+ let json_ld_html: String = doc
1019+ .json_ld_blocks
1020+ .iter()
1021+ .map(|block| {
1022+ if dev {
1023+ format!(
1024+ "<script type=\"application/ld+json\">\n{}\n</script>\n",
1025+ block
1026+ )
1027+ } else {
1028+ format!("<script type=\"application/ld+json\">{}</script>", block)
1029+ }
1030+ })
1031+ .collect();
1032+
1033+ // Manifest link
1034+ let manifest_html = if let Some(ref manifest) = doc.manifest {
1035+ let mut json = String::from("{");
1036+ json.push_str(&format!("\"name\":\"{}\",", manifest.name));
1037+ if let Some(ref short) = manifest.short_name {
1038+ json.push_str(&format!("\"short_name\":\"{}\",", short));
1039+ }
1040+ json.push_str(&format!("\"start_url\":\"{}\",", manifest.start_url));
1041+ json.push_str(&format!("\"display\":\"{}\"", manifest.display));
1042+ if let Some(ref bg) = manifest.background_color {
1043+ json.push_str(&format!(",\"background_color\":\"{}\"", bg));
1044+ }
1045+ if let Some(ref tc) = manifest.theme_color {
1046+ json.push_str(&format!(",\"theme_color\":\"{}\"", tc));
1047+ }
1048+ if let Some(ref desc) = manifest.description {
1049+ json.push_str(&format!(",\"description\":\"{}\"", desc));
1050+ }
1051+ if !manifest.icons.is_empty() {
1052+ json.push_str(",\"icons\":[");
1053+ for (i, (src, sizes)) in manifest.icons.iter().enumerate() {
1054+ if i > 0 {
1055+ json.push(',');
1056+ }
1057+ json.push_str(&format!(
1058+ "{{\"src\":\"{}\",\"sizes\":\"{}\",\"type\":\"image/png\"}}",
1059+ src, sizes
1060+ ));
1061+ }
1062+ json.push(']');
1063+ }
1064+ json.push('}');
1065+
1066+ // Inline the manifest as a data URI
1067+ let encoded = base64_encode(json.as_bytes());
1068+ if dev {
1069+ format!(
1070+ "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">\n",
1071+ encoded
1072+ )
1073+ } else {
1074+ format!(
1075+ "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">",
1076+ encoded
1077+ )
1078+ }
10581079 } else {
1059− rules.push(if dev {
1060− format!("{own}, {own}::before, {own}::after {{ box-sizing: border-box; }}")
1080+ String::new()
1081+ };
1082+
1083+ // Preload hints (auto-detect fonts from @font-face)
1084+ let mut preload_html = String::new();
1085+ for (_, url) in &doc.font_faces {
1086+ if dev {
1087+ preload_html.push_str(&format!(
1088+ "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>\n",
1089+ url
1090+ ));
10611091 } else {
1062− format!("{own},{own}::before,{own}::after{{box-sizing:border-box}}")
1063− });
1092+ preload_html.push_str(&format!(
1093+ "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>",
1094+ url
1095+ ));
1096+ }
1097+ }
1098+ // Explicit preload hints from the document
1099+ for hint in &doc.preload_hints {
1100+ if dev {
1101+ preload_html.push_str(&format!(
1102+ "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>\n",
1103+ html_escape(&hint.href),
1104+ hint.as_type,
1105+ if hint.crossorigin { " crossorigin" } else { "" }
1106+ ));
1107+ } else {
1108+ preload_html.push_str(&format!(
1109+ "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>",
1110+ html_escape(&hint.href),
1111+ hint.as_type,
1112+ if hint.crossorigin { " crossorigin" } else { "" }
1113+ ));
1114+ }
10641115 }
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; }}")
1116+
1117+ // Auto theme-color meta from @theme primary token
1118+ let theme_color_html = doc
1119+ .theme_tokens
1120+ .iter()
1121+ .find(|(name, _)| name == "primary" || name == "theme-color")
1122+ .map(|(_, value)| {
1123+ if dev {
1124+ format!(
1125+ "<meta name=\"theme-color\" content=\"{}\">\n",
1126+ html_escape(value)
1127+ )
1128+ } else {
1129+ format!(
1130+ "<meta name=\"theme-color\" content=\"{}\">",
1131+ html_escape(value)
1132+ )
1133+ }
1134+ })
1135+ .unwrap_or_default();
1136+
1137+ // Focus-visible CSS for interactive elements (accessibility)
1138+ let focus_visible_css = if ctx.has_interactive {
1139+ if dev {
1140+ "a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }\n"
1141+ } else {
1142+ "a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid currentColor;outline-offset:2px}"
1143+ }
1144+ } else {
1145+ ""
1146+ };
1147+
1148+ // Skip-to-content CSS (visually hidden but accessible)
1149+ let skip_link_css = if has_main {
1150+ if dev {
1151+ ".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"
1152+ } else {
1153+ ".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}"
1154+ }
10691155 } else {
1070− format!("{own}:where({hidden}){{display:none!important}}")
1071− });
1072− let mut rules = rules.join(if dev { "\n" } else { "" });
1073− if dev {
1074− rules.push('\n');
1075− }
1076− rules.push_str(focus_visible_css);
1077− if dev {
1078− format!(
1079− "@layer {};\n@layer hl-reset {{\n{}}}\n",
1080− LAYERS.join(", "),
1081− rules
1082− )
1156+ ""
1157+ };
1158+
1159+ // Noscript fallback: show deferred content if JS is disabled
1160+ let noscript_html = if ctx.has_defer {
1161+ if dev {
1162+ "<noscript><style>.hl-defer-placeholder { display: none; }</style></noscript>\n"
1163+ } else {
1164+ "<noscript><style>.hl-defer-placeholder{display:none}</style></noscript>"
1165+ }
10831166 } else {
1084− format!("@layer {};@layer hl-reset{{{}}}", LAYERS.join(","), rules)
1167+ ""
1168+ };
1169+
1170+ match &doc.page_title {
1171+ Some(title) => {
1172+ if dev {
1173+ format!(
1174+ "\
1175+<!DOCTYPE html>
1176+<html{lang_attr}>
1177+<head>
1178+<meta charset=\"utf-8\">
1179+<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
1180+<title>{title}</title>
1181+{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}\
1182+<style>
1183+*, *::before, *::after {{ box-sizing: border-box; }}
1184+body {{ margin: 0; font-family: system-ui, -apple-system, sans-serif; }}
1185+img {{ display: block; }}
1186+{focus_visible_css}{skip_link_css}{element_css}\
1187+</style>
1188+{noscript_html}\
1189+</head>
1190+<body>
1191+{body}\
1192+</body>
1193+</html>
1194+",
1195+ title = html_escape(title),
1196+ lang_attr = lang_attr,
1197+ theme_color_html = theme_color_html,
1198+ base_html = base_html,
1199+ canonical_html = canonical_html,
1200+ manifest_html = manifest_html,
1201+ preload_html = preload_html,
1202+ dns_prefetch_html = dns_prefetch_html,
1203+ meta_html = meta_html,
1204+ favicon_html = favicon_html,
1205+ json_ld_html = json_ld_html,
1206+ head_html = head_html,
1207+ og_html = og_html,
1208+ focus_visible_css = focus_visible_css,
1209+ skip_link_css = skip_link_css,
1210+ noscript_html = noscript_html,
1211+ element_css = element_css,
1212+ body = body,
1213+ )
1214+ } else {
1215+ format!(
1216+ "<!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>",
1217+ title = html_escape(title),
1218+ lang_attr = lang_attr,
1219+ theme_color_html = theme_color_html,
1220+ base_html = base_html,
1221+ canonical_html = canonical_html,
1222+ manifest_html = manifest_html,
1223+ preload_html = preload_html,
1224+ dns_prefetch_html = dns_prefetch_html,
1225+ meta_html = meta_html,
1226+ og_html = og_html,
1227+ favicon_html = favicon_html,
1228+ json_ld_html = json_ld_html,
1229+ head_html = head_html,
1230+ focus_visible_css = focus_visible_css,
1231+ skip_link_css = skip_link_css,
1232+ noscript_html = noscript_html,
1233+ element_css = element_css,
1234+ body = body,
1235+ )
1236+ }
1237+ }
1238+ None => {
1239+ if element_css.is_empty() {
1240+ body
1241+ } else if dev {
1242+ format!("<style>\n{}</style>\n{}", element_css, body)
1243+ } else {
1244+ format!("<style>{}</style>{}", element_css, body)
1245+ }
1246+ }
10851247 }
10861248}
10871249
10881250/// 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 {
1251+fn generate_partial_inner(doc: &Document, dev: bool) -> String {
10901252 let mut styles = StyleCollector::new();
10911253 let mut ctx = GenContext {
10921254 dev,
10931255 depth: 0,
1256+ image_count: 0,
10941257 has_interactive: false,
1095− in_text: false,
1096− flow: Flow::default(),
1097− in_picture: false,
1258+ has_defer: false,
10981259 };
10991260 let mut body = String::new();
11001261
1101− generate_children(&doc.nodes, None, &mut body, &mut styles, &mut ctx);
1262+ for node in &doc.nodes {
1263+ generate_node(node, None, &mut body, &mut styles, &mut ctx);
1264+ }
1265+
1266+ let has_custom_css = !doc.custom_css.is_empty();
1267+ let mut element_css = String::new();
1268+
1269+ // CSS custom properties
1270+ if !doc.css_vars.is_empty() || !doc.theme_tokens.is_empty() {
1271+ if dev {
1272+ element_css.push_str(":root {\n");
1273+ for (name, value) in &doc.css_vars {
1274+ element_css.push_str(&format!(" {}: {};\n", name, value));
1275+ }
1276+ for (name, value) in &doc.theme_tokens {
1277+ let css_name = format!("--{}", name);
1278+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
1279+ element_css.push_str(&format!(" {}: {};\n", css_name, value));
1280+ }
1281+ }
1282+ element_css.push_str("}\n");
1283+ } else {
1284+ element_css.push_str(":root{");
1285+ for (name, value) in &doc.css_vars {
1286+ element_css.push_str(name);
1287+ element_css.push(':');
1288+ element_css.push_str(value);
1289+ element_css.push(';');
1290+ }
1291+ for (name, value) in &doc.theme_tokens {
1292+ let css_name = format!("--{}", name);
1293+ if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
1294+ element_css.push_str(&css_name);
1295+ element_css.push(':');
1296+ element_css.push_str(value);
1297+ element_css.push(';');
1298+ }
1299+ }
1300+ element_css.push('}');
1301+ }
1302+ }
1303+
1304+ let styles_css = styles.to_css_formatted(dev, !has_custom_css);
1305+ let styles_css = substitute_css_vars(&styles_css, &doc.css_vars);
1306+ element_css.push_str(&styles_css);
1307+
1308+ for (name, kf_body) in &doc.keyframes {
1309+ if dev {
1310+ element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1311+ } else {
1312+ element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1313+ }
1314+ }
11021315
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, ""));
1316+ for block in &doc.custom_css {
1317+ if dev {
1318+ element_css.push_str(block);
1319+ element_css.push('\n');
1320+ } else {
1321+ let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1322+ element_css.push_str(&minified);
1323+ }
11081324 }
1109− classes.extend(styles.classes());
11101325
11111326 if element_css.is_empty() {
11121327 body
@@ -1121,20 +1336,44 @@ fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -
11211336// Node generation
11221337// ---------------------------------------------------------------------------
11231338
1124−/// Write `node`, which is inside an element with the layout `parent`
1125−/// (`None` at the top of the page).
11261339fn generate_node(
11271340 node: &Node,
1128− parent: Option<Layout>,
1341+ parent_kind: Option<&ElementKind>,
11291342 out: &mut String,
11301343 styles: &mut StyleCollector,
11311344 ctx: &mut GenContext,
11321345) {
11331346 match node {
1134− Node::Element(elem) => generate_element(elem, parent, out, styles, ctx),
1347+ Node::Element(elem) => generate_element(elem, parent_kind, out, styles, ctx),
11351348 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);
1349+ let needs_wrap = matches!(
1350+ parent_kind,
1351+ Some(ElementKind::Row)
1352+ | Some(ElementKind::Column)
1353+ | Some(ElementKind::El)
1354+ | Some(ElementKind::Nav)
1355+ | Some(ElementKind::Header)
1356+ | Some(ElementKind::Footer)
1357+ | Some(ElementKind::Main)
1358+ | Some(ElementKind::Section)
1359+ | Some(ElementKind::Article)
1360+ | Some(ElementKind::Aside)
1361+ | Some(ElementKind::ListItem)
1362+ | Some(ElementKind::Form)
1363+ | Some(ElementKind::Details)
1364+ | Some(ElementKind::Figure)
1365+ | Some(ElementKind::Blockquote)
1366+ | Some(ElementKind::Dialog)
1367+ | Some(ElementKind::DefinitionList)
1368+ | Some(ElementKind::DefinitionDescription)
1369+ | Some(ElementKind::Fieldset)
1370+ | Some(ElementKind::Datalist)
1371+ | Some(ElementKind::Grid)
1372+ | Some(ElementKind::Stack)
1373+ | Some(ElementKind::Noscript)
1374+ | Some(ElementKind::Address)
1375+ | Some(ElementKind::Search)
1376+ );
11381377 if needs_wrap {
11391378 out.push_str(&ctx.indent());
11401379 out.push_str("<span>");
@@ -1153,191 +1392,195 @@ fn generate_node(
11531392 }
11541393}
11551394
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−}
1395+/// HTML attributes that are passed through to the HTML tag rather than converted to CSS.
1396+const HTML_PASSTHROUGH_ATTRS: &[&str] = &[
1397+ "type",
1398+ "placeholder",
1399+ "name",
1400+ "value",
1401+ "disabled",
1402+ "required",
1403+ "checked",
1404+ "for",
1405+ "action",
1406+ "method",
1407+ "autocomplete",
1408+ "min",
1409+ "max",
1410+ "step",
1411+ "pattern",
1412+ "maxlength",
1413+ "rows",
1414+ "cols",
1415+ "multiple",
1416+ "alt",
1417+ "role",
1418+ "tabindex",
1419+ "title",
1420+ "autofocus",
1421+ // Media
1422+ "controls",
1423+ "autoplay",
1424+ "loop",
1425+ "muted",
1426+ "poster",
1427+ "preload",
1428+ // Image optimization
1429+ "loading",
1430+ "decoding",
1431+ // Media src (explicit attribute form)
1432+ "src",
1433+ // New element attributes
1434+ "datetime",
1435+ "media",
1436+ "sizes",
1437+ "srcset",
1438+ "list",
1439+ // Details
1440+ "open",
1441+ // Form
1442+ "novalidate",
1443+ // Progress/Meter
1444+ "low",
1445+ "high",
1446+ "optimum",
1447+ // Table
1448+ "colspan",
1449+ "rowspan",
1450+ "scope",
1451+ // Popover API
1452+ "popover",
1453+ "popovertarget",
1454+ "popovertargetaction",
1455+ // Modern form/input hints
1456+ "inputmode",
1457+ "enterkeyhint",
1458+ // Performance hints
1459+ "fetchpriority",
1460+ "blocking",
1461+ // Global attrs
1462+ "translate",
1463+ "spellcheck",
1464+ // ARIA live regions
1465+ "aria-live",
1466+ "aria-atomic",
1467+ "aria-relevant",
1468+];
11701469
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−}
1470+/// Boolean HTML attributes (rendered without a value, e.g., `<input disabled>`).
1471+const BOOLEAN_HTML_ATTRS: &[&str] = &[
1472+ "disabled",
1473+ "required",
1474+ "checked",
1475+ "multiple",
1476+ "controls",
1477+ "autoplay",
1478+ "loop",
1479+ "muted",
1480+ "open",
1481+ "novalidate",
1482+ "autofocus",
1483+ "defer",
1484+ "async",
1485+ "nomodule",
1486+ // Popover
1487+ "popover",
1488+];
11831489
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);
1490+fn emit_html_passthrough_attrs(out: &mut String, attrs: &[Attribute]) {
1491+ for attr in attrs {
1492+ let key = attr.key.as_str();
1493+ let is_passthrough = HTML_PASSTHROUGH_ATTRS.contains(&key)
1494+ || key.starts_with("aria-")
1495+ || key.starts_with("data-");
1496+ if !is_passthrough {
12011497 continue;
12021498 }
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;
1499+ if BOOLEAN_HTML_ATTRS.contains(&key) && attr.value.is_none() {
1500+ out.push(' ');
1501+ out.push_str(key);
1502+ } else if let Some(val) = &attr.value {
1503+ out.push(' ');
1504+ out.push_str(key);
1505+ out.push_str("=\"");
1506+ out.push_str(&html_escape(strip_string_quotes(val)));
1507+ out.push('"');
12161508 }
1217− *previous = Some(matches!(child, Node::Text(_)));
12181509 }
12191510}
12201511
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− }
1512+/// If the value is wrapped in a single pair of matching quotes (e.g.
1513+/// `"Avatar"`), return the inner content. Quotes act as source-level
1514+/// delimiters in the `.hl` syntax and shouldn't leak into HTML attribute
1515+/// values. Multi-quoted values like `"h h" "s m"` are left unchanged —
1516+/// those are real string tokens (used e.g. by CSS `grid-template-areas`).
1517+fn strip_string_quotes(val: &str) -> &str {
1518+ let bytes = val.as_bytes();
1519+ if bytes.len() < 2 {
1520+ return val;
12671521 }
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('"');
1522+ let first = bytes[0];
1523+ let last = bytes[bytes.len() - 1];
1524+ if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
1525+ let inner = &val[1..val.len() - 1];
1526+ if !inner.as_bytes().contains(&first) {
1527+ return inner;
1528+ }
12941529 }
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− })
1530+ val
13111531}
13121532
13131533fn generate_element(
13141534 elem: &Element,
1315− parent: Option<Layout>,
1535+ parent_kind: Option<&ElementKind>,
13161536 out: &mut String,
13171537 styles: &mut StyleCollector,
13181538 ctx: &mut GenContext,
13191539) {
13201540 // Self-closing elements
1321− if elem.kind.layout() == Layout::Void {
1322− generate_self_closing(elem, parent, out, styles, ctx);
1541+ if matches!(
1542+ elem.kind,
1543+ ElementKind::Image
1544+ | ElementKind::Input
1545+ | ElementKind::HorizontalRule
1546+ | ElementKind::Source
1547+ | ElementKind::Spacer
1548+ ) {
1549+ generate_self_closing(elem, parent_kind, out, styles, ctx);
13231550 return;
13241551 }
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);
1552+ // @script renders as <script> with raw body content (no HTML escaping)
1553+ if elem.kind == ElementKind::Script {
13291554 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)));
1555+ out.push_str("<script");
1556+ // Pass through src, type, defer, async, etc.
1557+ for attr in &elem.attrs {
1558+ let key = attr.key.as_str();
1559+ if matches!(
1560+ key,
1561+ "src"
1562+ | "type"
1563+ | "defer"
1564+ | "async"
1565+ | "crossorigin"
1566+ | "integrity"
1567+ | "nomodule"
1568+ | "id"
1569+ ) {
1570+ if let Some(val) = &attr.value {
1571+ out.push(' ');
1572+ out.push_str(key);
1573+ out.push_str("=\"");
1574+ out.push_str(&html_escape(val));
1575+ out.push('"');
1576+ } else {
1577+ out.push(' ');
1578+ out.push_str(key);
1579+ }
13371580 }
13381581 }
1339− emit_html_attrs(out, &elem.attrs);
13401582 out.push('>');
1583+ // Children are raw JS code, not HTML
13411584 for child in &elem.children {
13421585 match child {
13431586 Node::Text(segments) => {
@@ -1351,10 +1594,46 @@ fn generate_element(
13511594 _ => {}
13521595 }
13531596 }
1354− out.push_str("</");
1355− out.push_str(tag);
1597+ out.push_str("</script>");
1598+ out.push_str(ctx.nl());
1599+ return;
1600+ }
1601+ // @breadcrumb generates semantic <nav aria-label="breadcrumb"><ol>...</ol></nav>
1602+ if elem.kind == ElementKind::Breadcrumb {
1603+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
1604+ let (id, user_class) = extract_id_class(&elem.attrs);
1605+ out.push_str(&ctx.indent());
1606+ out.push_str("<nav aria-label=\"breadcrumb\"");
1607+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1608+ if let Some(id) = id {
1609+ out.push_str(" id=\"");
1610+ out.push_str(&html_escape(&id));
1611+ out.push('"');
1612+ }
13561613 out.push('>');
13571614 out.push_str(ctx.nl());
1615+ ctx.depth += 1;
1616+ out.push_str(&ctx.indent());
1617+ out.push_str("<ol>");
1618+ out.push_str(ctx.nl());
1619+ ctx.depth += 1;
1620+ for child in &elem.children {
1621+ out.push_str(&ctx.indent());
1622+ out.push_str("<li>");
1623+ let mut buf = String::new();
1624+ generate_node(child, Some(&elem.kind), &mut buf, styles, ctx);
1625+ out.push_str(buf.trim());
1626+ out.push_str("</li>");
1627+ out.push_str(ctx.nl());
1628+ }
1629+ ctx.depth -= 1;
1630+ out.push_str(&ctx.indent());
1631+ out.push_str("</ol>");
1632+ out.push_str(ctx.nl());
1633+ ctx.depth -= 1;
1634+ out.push_str(&ctx.indent());
1635+ out.push_str("</nav>");
1636+ out.push_str(ctx.nl());
13581637 return;
13591638 }
13601639 if elem.kind == ElementKind::Children {
@@ -1364,38 +1643,185 @@ fn generate_element(
13641643 return;
13651644 }
13661645 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);
1646+ // Render children without a wrapper element
1647+ for child in &elem.children {
1648+ generate_node(child, parent_kind, out, styles, ctx);
1649+ }
13701650 return;
13711651 }
13721652
1373− let mut own = Flow::of(elem);
13741653 let tag = match &elem.kind {
1375− ElementKind::Row | ElementKind::El => "div",
1654+ ElementKind::Row
1655+ | ElementKind::Column
1656+ | ElementKind::El
1657+ | ElementKind::Grid
1658+ | ElementKind::Stack => "div",
13761659 ElementKind::Text => "span",
13771660 ElementKind::Paragraph => "p",
13781661 ElementKind::Link => "a",
1379− ElementKind::Tag(spec) => spec.html,
1662+ ElementKind::Button => "button",
1663+ ElementKind::Select => "select",
1664+ ElementKind::Textarea => "textarea",
1665+ ElementKind::Option => "option",
1666+ ElementKind::Label => "label",
1667+ // Semantic elements
1668+ ElementKind::Nav => "nav",
1669+ ElementKind::Header => "header",
1670+ ElementKind::Footer => "footer",
1671+ ElementKind::Main => "main",
1672+ ElementKind::Section => "section",
1673+ ElementKind::Article => "article",
1674+ ElementKind::Aside => "aside",
1675+ // List
1676+ ElementKind::List => {
1677+ if elem.attrs.iter().any(|a| a.key == "ordered") {
1678+ "ol"
1679+ } else {
1680+ "ul"
1681+ }
1682+ }
1683+ ElementKind::ListItem => "li",
1684+ // Table
1685+ ElementKind::Table => "table",
1686+ ElementKind::TableHead => "thead",
1687+ ElementKind::TableBody => "tbody",
1688+ ElementKind::TableRow => "tr",
1689+ ElementKind::TableCell => "td",
1690+ ElementKind::TableHeaderCell => "th",
1691+ // Media
1692+ ElementKind::Video => "video",
1693+ ElementKind::Audio => "audio",
1694+ // Additional semantic elements
1695+ ElementKind::Form => "form",
1696+ ElementKind::Details => "details",
1697+ ElementKind::Summary => "summary",
1698+ ElementKind::Blockquote => "blockquote",
1699+ ElementKind::Cite => "cite",
1700+ ElementKind::Code => "code",
1701+ ElementKind::Pre => "pre",
1702+ ElementKind::Figure => "figure",
1703+ ElementKind::FigCaption => "figcaption",
1704+ ElementKind::Progress => "progress",
1705+ ElementKind::Meter => "meter",
1706+ // New elements
1707+ ElementKind::Dialog => "dialog",
1708+ ElementKind::DefinitionList => "dl",
1709+ ElementKind::DefinitionTerm => "dt",
1710+ ElementKind::DefinitionDescription => "dd",
1711+ ElementKind::Fieldset => "fieldset",
1712+ ElementKind::Legend => "legend",
1713+ ElementKind::Picture => "picture",
1714+ ElementKind::Time => "time",
1715+ ElementKind::Mark => "mark",
1716+ ElementKind::Kbd => "kbd",
1717+ ElementKind::Abbr => "abbr",
1718+ ElementKind::Datalist => "datalist",
1719+ ElementKind::Iframe => "iframe",
1720+ ElementKind::Output => "output",
1721+ ElementKind::Canvas => "canvas",
1722+ ElementKind::Badge => "span",
1723+ ElementKind::Tooltip => "span",
1724+ ElementKind::Avatar => "div",
1725+ ElementKind::Carousel => "div",
1726+ ElementKind::Chip => "span",
1727+ ElementKind::Tag => "span",
1728+ ElementKind::Noscript => "noscript",
1729+ ElementKind::Address => "address",
1730+ ElementKind::Search => "search",
1731+ ElementKind::Image
1732+ | ElementKind::Input
1733+ | ElementKind::HorizontalRule
1734+ | ElementKind::Children
1735+ | ElementKind::Slot(_)
1736+ | ElementKind::Fragment
1737+ | ElementKind::Source
1738+ | ElementKind::Spacer
1739+ | ElementKind::Script
1740+ | ElementKind::Breadcrumb => unreachable!(),
1741+ };
1742+
1743+ let kind_label = match elem.kind {
1744+ ElementKind::Row => "row",
1745+ ElementKind::Column => "column",
1746+ ElementKind::El => "el",
1747+ ElementKind::Text => "text",
1748+ ElementKind::Paragraph => "paragraph",
1749+ ElementKind::Link => "link",
1750+ ElementKind::Button => "button",
1751+ ElementKind::Select => "select",
1752+ ElementKind::Textarea => "textarea",
1753+ ElementKind::Option => "option",
1754+ ElementKind::Label => "label",
1755+ ElementKind::Nav => "nav",
1756+ ElementKind::Header => "header",
1757+ ElementKind::Footer => "footer",
1758+ ElementKind::Main => "main",
1759+ ElementKind::Section => "section",
1760+ ElementKind::Article => "article",
1761+ ElementKind::Aside => "aside",
1762+ ElementKind::List => "list",
1763+ ElementKind::ListItem => "item",
1764+ ElementKind::Table => "table",
1765+ ElementKind::TableHead => "thead",
1766+ ElementKind::TableBody => "tbody",
1767+ ElementKind::TableRow => "tr",
1768+ ElementKind::TableCell => "td",
1769+ ElementKind::TableHeaderCell => "th",
1770+ ElementKind::Video => "video",
1771+ ElementKind::Audio => "audio",
1772+ ElementKind::Form => "form",
1773+ ElementKind::Details => "details",
1774+ ElementKind::Summary => "summary",
1775+ ElementKind::Blockquote => "blockquote",
1776+ ElementKind::Cite => "cite",
1777+ ElementKind::Code => "code",
1778+ ElementKind::Pre => "pre",
1779+ ElementKind::Figure => "figure",
1780+ ElementKind::FigCaption => "figcaption",
1781+ ElementKind::Fragment => "fragment",
1782+ ElementKind::Dialog => "dialog",
1783+ ElementKind::DefinitionList => "dl",
1784+ ElementKind::DefinitionTerm => "dt",
1785+ ElementKind::DefinitionDescription => "dd",
1786+ ElementKind::Fieldset => "fieldset",
1787+ ElementKind::Legend => "legend",
1788+ ElementKind::Picture => "picture",
1789+ ElementKind::Time => "time",
1790+ ElementKind::Mark => "mark",
1791+ ElementKind::Kbd => "kbd",
1792+ ElementKind::Abbr => "abbr",
1793+ ElementKind::Datalist => "datalist",
1794+ ElementKind::Iframe => "iframe",
1795+ ElementKind::Output => "output",
1796+ ElementKind::Canvas => "canvas",
1797+ ElementKind::Grid => "grid",
1798+ ElementKind::Stack => "stack",
1799+ ElementKind::Badge => "badge",
1800+ ElementKind::Tooltip => "tooltip",
1801+ ElementKind::Avatar => "avatar",
1802+ ElementKind::Carousel => "carousel",
1803+ ElementKind::Chip => "chip",
1804+ ElementKind::Tag => "tag",
1805+ ElementKind::Noscript => "noscript",
1806+ ElementKind::Address => "address",
1807+ ElementKind::Search => "search",
13801808 _ => "",
13811809 };
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();
13881810
13891811 // Track interactive elements for focus-visible CSS
1390− if elem.kind == ElementKind::Link
1391− || matches!(kind_label, "button" | "input" | "select" | "textarea")
1392− {
1812+ if matches!(
1813+ elem.kind,
1814+ ElementKind::Link
1815+ | ElementKind::Button
1816+ | ElementKind::Input
1817+ | ElementKind::Select
1818+ | ElementKind::Textarea
1819+ ) {
13931820 ctx.has_interactive = true;
13941821 }
13951822
13961823 // 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();
1824+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
13991825 let (id, user_class) = extract_id_class(&elem.attrs);
14001826
14011827 if ctx.dev && elem.line_num > 0 {
@@ -1409,9 +1835,85 @@ fn generate_element(
14091835 out.push('<');
14101836 out.push_str(tag);
14111837
1412− emit_argument_attr(out, elem, ctx.in_picture);
1838+ // @main gets id="hl-main" for skip-to-content link (unless user set an id)
1839+ if elem.kind == ElementKind::Main && id.is_none() {
1840+ out.push_str(" id=\"hl-main\"");
1841+ }
14131842
1414− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1843+ if elem.kind == ElementKind::Link
1844+ && let Some(url) = &elem.argument
1845+ {
1846+ out.push_str(" href=\"");
1847+ out.push_str(&html_escape(url));
1848+ out.push('"');
1849+ // Auto rel="noopener noreferrer" and target="_blank" for external links
1850+ let is_external = url.starts_with("http://") || url.starts_with("https://");
1851+ if is_external {
1852+ let has_rel = elem.attrs.iter().any(|a| a.key == "rel");
1853+ let has_target = elem.attrs.iter().any(|a| a.key == "target");
1854+ if !has_rel {
1855+ out.push_str(" rel=\"noopener noreferrer\"");
1856+ }
1857+ if !has_target {
1858+ out.push_str(" target=\"_blank\"");
1859+ }
1860+ }
1861+ }
1862+
1863+ // Video/Audio src
1864+ if matches!(elem.kind, ElementKind::Video | ElementKind::Audio)
1865+ && let Some(src) = &elem.argument
1866+ {
1867+ out.push_str(" src=\"");
1868+ out.push_str(&html_escape(src));
1869+ out.push('"');
1870+ }
1871+
1872+ // Form action
1873+ if elem.kind == ElementKind::Form
1874+ && let Some(action) = &elem.argument
1875+ {
1876+ out.push_str(" action=\"");
1877+ out.push_str(&html_escape(action));
1878+ out.push('"');
1879+ }
1880+
1881+ // Iframe src
1882+ if elem.kind == ElementKind::Iframe
1883+ && let Some(src) = &elem.argument
1884+ {
1885+ out.push_str(" src=\"");
1886+ out.push_str(&html_escape(src));
1887+ out.push('"');
1888+ }
1889+
1890+ // Tooltip title
1891+ if elem.kind == ElementKind::Tooltip
1892+ && let Some(text) = &elem.argument
1893+ {
1894+ out.push_str(" title=\"");
1895+ out.push_str(&html_escape(text));
1896+ out.push('"');
1897+ }
1898+
1899+ // Critical CSS: inline styles directly instead of using a class
1900+ let is_critical = elem.attrs.iter().any(|a| a.key == "critical");
1901+ if is_critical {
1902+ let inline_css = attrs_to_css(&elem.attrs, "", &elem.kind, parent_kind);
1903+ if !inline_css.is_empty() {
1904+ out.push_str(" style=\"");
1905+ out.push_str(&html_escape(&inline_css));
1906+ out.push('"');
1907+ }
1908+ // Still use class for non-base styles (pseudo, responsive, etc.)
1909+ if gen_class.as_deref().is_some_and(|c| !c.is_empty()) {
1910+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1911+ } else if let Some(ref uc) = user_class {
1912+ emit_class_attr(out, None, Some(uc));
1913+ }
1914+ } else {
1915+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1916+ }
14151917
14161918 if let Some(id) = id {
14171919 out.push_str(" id=\"");
@@ -1419,7 +1921,7 @@ fn generate_element(
14191921 out.push('"');
14201922 }
14211923
1422− emit_html_attrs(out, &elem.attrs);
1924+ emit_html_passthrough_attrs(out, &elem.attrs);
14231925
14241926 // Source map attributes in dev mode
14251927 if ctx.dev && elem.line_num > 0 {
@@ -1430,27 +1932,51 @@ fn generate_element(
14301932 }
14311933
14321934 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");
14381935 out.push_str(ctx.nl());
14391936
1440− let layout = elem.kind.layout();
1937+ // Inline text argument
1938+ if matches!(
1939+ elem.kind,
1940+ ElementKind::Text
1941+ | ElementKind::Button
1942+ | ElementKind::Label
1943+ | ElementKind::Option
1944+ | ElementKind::Textarea
1945+ | ElementKind::ListItem
1946+ | ElementKind::TableCell
1947+ | ElementKind::TableHeaderCell
1948+ | ElementKind::Summary
1949+ | ElementKind::Cite
1950+ | ElementKind::Code
1951+ | ElementKind::FigCaption
1952+ | ElementKind::Legend
1953+ | ElementKind::DefinitionTerm
1954+ | ElementKind::Mark
1955+ | ElementKind::Kbd
1956+ | ElementKind::Abbr
1957+ | ElementKind::Time
1958+ | ElementKind::DefinitionDescription
1959+ | ElementKind::Badge
1960+ | ElementKind::Tooltip
1961+ | ElementKind::Chip
1962+ | ElementKind::Tag
1963+ ) && let Some(text) = &elem.argument
1964+ {
1965+ out.push_str(&html_escape(text));
1966+ }
1967+
1968+ // Children
14411969 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;
1970+ let is_paragraph = elem.kind == ElementKind::Paragraph;
1971+ for (i, child) in elem.children.iter().enumerate() {
1972+ generate_node(child, Some(&elem.kind), out, styles, ctx);
1973+ if is_paragraph && i < elem.children.len() - 1 {
1974+ out.push(' ');
1975+ }
1976+ }
14501977 ctx.depth -= 1;
14511978
14521979 out.push_str(&ctx.indent());
1453− ctx.dev = outer_dev;
14541980 out.push_str("</");
14551981 out.push_str(tag);
14561982 out.push('>');
@@ -1459,18 +1985,21 @@ fn generate_element(
14591985
14601986fn generate_self_closing(
14611987 elem: &Element,
1462− parent: Option<Layout>,
1988+ parent_kind: Option<&ElementKind>,
14631989 out: &mut String,
14641990 styles: &mut StyleCollector,
14651991 ctx: &mut GenContext,
14661992) {
1467− let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
1993+ let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
14681994 let (id, user_class) = extract_id_class(&elem.attrs);
14691995
1470− let (tag, kind_label) = match &elem.kind {
1996+ let (tag, kind_label) = match elem.kind {
14711997 ElementKind::Image => ("img", "image"),
1472− ElementKind::Tag(spec) => (spec.html, spec.name),
1473− _ => unreachable!("not a void element: {:?}", elem.kind),
1998+ ElementKind::Input => ("input", "input"),
1999+ ElementKind::HorizontalRule => ("hr", "hr"),
2000+ ElementKind::Source => ("source", "source"),
2001+ ElementKind::Spacer => ("div", "spacer"),
2002+ _ => unreachable!(),
14742003 };
14752004
14762005 if ctx.dev && elem.line_num > 0 {
@@ -1483,7 +2012,43 @@ fn generate_self_closing(
14832012 out.push_str(&ctx.indent());
14842013 out.push('<');
14852014 out.push_str(tag);
1486− emit_argument_attr(out, elem, ctx.in_picture);
2015+
2016+ // Image src (with optional non-SVG base64 inlining)
2017+ if elem.kind == ElementKind::Image {
2018+ let src = elem.argument.as_deref().unwrap_or("");
2019+ let is_inline = elem.attrs.iter().any(|a| a.key == "inline");
2020+ if is_inline && !src.is_empty() && !src.ends_with(".svg") {
2021+ let mime = if src.ends_with(".png") {
2022+ "image/png"
2023+ } else if src.ends_with(".jpg") || src.ends_with(".jpeg") {
2024+ "image/jpeg"
2025+ } else if src.ends_with(".gif") {
2026+ "image/gif"
2027+ } else if src.ends_with(".webp") {
2028+ "image/webp"
2029+ } else if src.ends_with(".avif") {
2030+ "image/avif"
2031+ } else {
2032+ "application/octet-stream"
2033+ };
2034+ if let Ok(data) = std::fs::read(src) {
2035+ let b64 = base64_encode(&data);
2036+ out.push_str(" src=\"data:");
2037+ out.push_str(mime);
2038+ out.push_str(";base64,");
2039+ out.push_str(&b64);
2040+ out.push('"');
2041+ } else {
2042+ out.push_str(" src=\"");
2043+ out.push_str(&html_escape(src));
2044+ out.push('"');
2045+ }
2046+ } else {
2047+ out.push_str(" src=\"");
2048+ out.push_str(&html_escape(src));
2049+ out.push('"');
2050+ }
2051+ }
14872052
14882053 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
14892054
@@ -1493,7 +2058,7 @@ fn generate_self_closing(
14932058 out.push('"');
14942059 }
14952060
1496− emit_html_attrs(out, &elem.attrs);
2061+ emit_html_passthrough_attrs(out, &elem.attrs);
14972062
14982063 // Source map attributes in dev mode (self-closing)
14992064 if ctx.dev && elem.line_num > 0 {
@@ -1503,6 +2068,93 @@ fn generate_self_closing(
15032068 ));
15042069 }
15052070
2071+ // Image optimization: auto-add loading="lazy" and decoding="async"
2072+ if elem.kind == ElementKind::Image {
2073+ // SVG inlining: @image [inline] logo.svg
2074+ if elem.attrs.iter().any(|a| a.key == "inline")
2075+ && let Some(src) = &elem.argument
2076+ && src.ends_with(".svg")
2077+ && let Ok(svg_content) = std::fs::read_to_string(src)
2078+ {
2079+ // Close the tag we opened, then emit inline SVG instead
2080+ out.truncate(out.rfind('<').unwrap_or(0));
2081+ out.push_str(&ctx.indent());
2082+ out.push_str(svg_content.trim());
2083+ out.push_str(ctx.nl());
2084+ return;
2085+ }
2086+ // Responsive srcset: @image photo.jpg [responsive 400 800 1200]
2087+ let responsive_attr = elem.attrs.iter().find(|a| a.key == "responsive");
2088+ if let Some(resp) = responsive_attr
2089+ && let Some(ref sizes_str) = resp.value
2090+ {
2091+ let widths: Vec<&str> = sizes_str.split_whitespace().collect();
2092+ if !widths.is_empty() {
2093+ let src = elem.argument.as_deref().unwrap_or("");
2094+ if !src.is_empty() {
2095+ // Generate srcset with width descriptors
2096+ // Convention: file-{width}.ext (e.g., photo-400.jpg)
2097+ let dot_pos = src.rfind('.').unwrap_or(src.len());
2098+ let base = &src[..dot_pos];
2099+ let ext = &src[dot_pos..];
2100+ let mut srcset_parts = Vec::new();
2101+ for w in &widths {
2102+ srcset_parts.push(format!("{}-{}{} {}w", base, w, ext, w));
2103+ }
2104+ out.push_str(" srcset=\"");
2105+ out.push_str(&srcset_parts.join(", "));
2106+ out.push('"');
2107+ // Generate sizes attribute
2108+ let max_width = widths.last().unwrap_or(&"100vw");
2109+ out.push_str(&format!(
2110+ " sizes=\"(max-width: {}px) 100vw, {}px\"",
2111+ max_width, max_width
2112+ ));
2113+ }
2114+ }
2115+ }
2116+
2117+ // Auto image dimensions: read local image file to inject width/height + aspect-ratio
2118+ let has_width = elem.attrs.iter().any(|a| a.key == "width");
2119+ let has_height = elem.attrs.iter().any(|a| a.key == "height");
2120+ if (!has_width || !has_height)
2121+ && let Some(ref src) = elem.argument
2122+ && !src.starts_with("http://")
2123+ && !src.starts_with("https://")
2124+ && !src.starts_with("data:")
2125+ && let Some((w, h)) = read_image_dimensions(src)
2126+ {
2127+ if !has_width {
2128+ out.push_str(&format!(" width=\"{}\"", w));
2129+ }
2130+ if !has_height {
2131+ out.push_str(&format!(" height=\"{}\"", h));
2132+ }
2133+ // Auto aspect-ratio to prevent CLS
2134+ if !elem.attrs.iter().any(|a| a.key == "aspect-ratio") {
2135+ out.push_str(&format!(" style=\"aspect-ratio:{}/{}\"", w, h));
2136+ }
2137+ }
2138+
2139+ // Smart image loading: first 3 images get fetchpriority="high" (above the fold),
2140+ // subsequent images get loading="lazy" + decoding="async"
2141+ ctx.image_count += 1;
2142+ if ctx.image_count <= 3 {
2143+ // Above-the-fold: eager loading with high priority
2144+ if !elem.attrs.iter().any(|a| a.key == "fetchpriority") {
2145+ out.push_str(" fetchpriority=\"high\"");
2146+ }
2147+ } else {
2148+ // Below-the-fold: lazy loading
2149+ if !elem.attrs.iter().any(|a| a.key == "loading") {
2150+ out.push_str(" loading=\"lazy\"");
2151+ }
2152+ if !elem.attrs.iter().any(|a| a.key == "decoding") {
2153+ out.push_str(" decoding=\"async\"");
2154+ }
2155+ }
2156+ }
2157+
15062158 out.push('>');
15072159 out.push_str(ctx.nl());
15082160}
@@ -1518,10 +2170,7 @@ fn generate_text_segments(
15182170 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
15192171 TextSegment::Inline(elem) => {
15202172 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;
2173+ generate_element(elem, None, &mut buf, styles, ctx);
15252174 out.push_str(buf.trim_end());
15262175 }
15272176 }
@@ -1534,97 +2183,141 @@ fn generate_text_segments(
15342183
15352184fn compute_class(
15362185 attrs: &[Attribute],
1537− site: &Site,
2186+ kind: &ElementKind,
2187+ parent_kind: Option<&ElementKind>,
15382188 styles: &mut StyleCollector,
1539− distinct: String,
15402189) -> 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);
2190+ let base = attrs_to_css(attrs, "", kind, parent_kind);
2191+
2192+ // Collect pseudo-state overrides
2193+ let mut pseudo = Vec::new();
2194+ for &(prefix, selector) in PSEUDO_PREFIXES {
2195+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2196+ if !css.is_empty() {
2197+ pseudo.push((selector.to_string(), css));
15472198 }
15482199 }
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−}
15722200
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));
2201+ // Auto-add ::-webkit-scrollbar pseudo for no-scrollbar attribute
2202+ if attrs.iter().any(|a| a.key == "no-scrollbar") {
2203+ pseudo.push((
2204+ "::-webkit-scrollbar".to_string(),
2205+ "display:none;".to_string(),
2206+ ));
15842207 }
1585− css.push_str(site.kind.css());
1586− css
1587−}
15882208
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;
2209+ // Collect nth:EXPR: dynamic pseudo selectors
2210+ let mut nth_prefixes: Vec<String> = Vec::new();
2211+ for attr in attrs {
2212+ if attr.key.starts_with("nth:") {
2213+ let rest = &attr.key[4..];
2214+ if let Some(colon_pos) = rest.find(':') {
2215+ let prefix = format!("nth:{}:", &rest[..colon_pos]);
2216+ if !nth_prefixes.contains(&prefix) {
2217+ nth_prefixes.push(prefix);
16122218 }
1613− _ => {}
16142219 }
16152220 }
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− })
2221+ }
2222+ for prefix in &nth_prefixes {
2223+ let expr = &prefix[4..prefix.len() - 1];
2224+ let selector = format!(":nth-child({})", expr);
2225+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2226+ if !css.is_empty() {
2227+ pseudo.push((selector, css));
2228+ }
2229+ }
2230+
2231+ // Collect has(...): dynamic pseudo selectors
2232+ let mut has_prefixes: Vec<String> = Vec::new();
2233+ for attr in attrs {
2234+ if attr.key.starts_with("has(")
2235+ && let Some(close) = attr.key.find("):")
2236+ {
2237+ let prefix = format!("{}:", &attr.key[..close + 1]);
2238+ if !has_prefixes.contains(&prefix) {
2239+ has_prefixes.push(prefix);
2240+ }
2241+ }
2242+ }
2243+ for prefix in &has_prefixes {
2244+ let inner = &prefix[4..prefix.len() - 2]; // extract selector from has(selector):
2245+ let selector = format!(":has({})", inner);
2246+ let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2247+ if !css.is_empty() {
2248+ pseudo.push((selector, css));
2249+ }
2250+ }
2251+
2252+ // Collect responsive overrides
2253+ let mut responsive = Vec::new();
2254+ for &(bp_name, _) in BREAKPOINTS {
2255+ let prefix = format!("{}:", bp_name);
2256+ let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
2257+ if !css.is_empty() {
2258+ responsive.push((bp_name.to_string(), css));
2259+ }
2260+ }
2261+
2262+ // Collect container query overrides
2263+ let mut container = Vec::new();
2264+ for &(bp_name, _) in BREAKPOINTS {
2265+ let prefix = format!("cq-{}:", bp_name);
2266+ let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
2267+ if !css.is_empty() {
2268+ container.push((bp_name.to_string(), css));
2269+ }
2270+ }
2271+
2272+ let dark = attrs_to_css(attrs, "dark:", kind, parent_kind);
2273+ let print = attrs_to_css(attrs, "print:", kind, parent_kind);
2274+ let motion_safe = attrs_to_css(attrs, "motion-safe:", kind, parent_kind);
2275+ let motion_reduce = attrs_to_css(attrs, "motion-reduce:", kind, parent_kind);
2276+ let landscape = attrs_to_css(attrs, "landscape:", kind, parent_kind);
2277+ let portrait = attrs_to_css(attrs, "portrait:", kind, parent_kind);
2278+
2279+ // Dedupe: if a property is declared twice within a single rule, keep only
2280+ // the last occurrence (element-kind defaults are written before
2281+ // user attributes, so a user [list-style disc] correctly overrides the
2282+ // default list-style:none, and we don't need to ship both).
2283+ let base = dedupe_declarations(&base);
2284+ let pseudo: Vec<(String, String)> = pseudo
2285+ .into_iter()
2286+ .map(|(sel, css)| (sel, dedupe_declarations(&css)))
2287+ .collect();
2288+ let responsive: Vec<(String, String)> = responsive
2289+ .into_iter()
2290+ .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2291+ .collect();
2292+ let dark = dedupe_declarations(&dark);
2293+ let print = dedupe_declarations(&print);
2294+ let motion_safe = dedupe_declarations(&motion_safe);
2295+ let motion_reduce = dedupe_declarations(&motion_reduce);
2296+ let landscape = dedupe_declarations(&landscape);
2297+ let portrait = dedupe_declarations(&portrait);
2298+ let container: Vec<(String, String)> = container
2299+ .into_iter()
2300+ .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2301+ .collect();
2302+
2303+ styles.get_class(
2304+ base,
2305+ pseudo,
2306+ responsive,
2307+ dark,
2308+ print,
2309+ motion_safe,
2310+ motion_reduce,
2311+ landscape,
2312+ portrait,
2313+ container,
2314+ )
16212315}
16222316
16232317/// Dedupe CSS declarations within a single rule body: for any property
16242318/// 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.
2319+/// segments (no `:`) are preserved as-is. Semicolons inside parentheses are
2320+/// treated as part of a value, not as declaration separators.
16282321fn dedupe_declarations(css: &str) -> String {
16292322 if css.is_empty() {
16302323 return String::new();
@@ -1639,26 +2332,8 @@ fn dedupe_declarations(css: &str) -> String {
16392332 let mut decls: Vec<(Option<String>, String)> = Vec::new();
16402333 let mut current = String::new();
16412334 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;
16462335 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 == '(' {
2336+ if ch == '(' {
16622337 depth += 1;
16632338 current.push(ch);
16642339 } else if ch == ')' {
@@ -1687,652 +2362,1562 @@ fn dedupe_declarations(css: &str) -> String {
16872362 decls.push((prop, std::mem::take(&mut current)));
16882363 }
16892364
1690− if decls.len() < 2 {
1691− return css.to_string();
1692− }
2365+ if decls.len() < 2 {
2366+ return css.to_string();
2367+ }
2368+
2369+ // Find index of last occurrence of each property.
2370+ use std::collections::HashMap;
2371+ let mut last: HashMap<String, usize> = HashMap::new();
2372+ for (i, (prop, _)) in decls.iter().enumerate() {
2373+ if let Some(p) = prop {
2374+ last.insert(p.clone(), i);
2375+ }
2376+ }
2377+
2378+ let mut out = String::with_capacity(css.len());
2379+ for (i, (prop, raw)) in decls.iter().enumerate() {
2380+ let keep = match prop {
2381+ Some(p) => last.get(p) == Some(&i),
2382+ None => true,
2383+ };
2384+ if keep {
2385+ out.push_str(raw);
2386+ }
2387+ }
2388+ out
2389+}
2390+
2391+fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option<&str>) {
2392+ match (gen_class, user_class) {
2393+ (Some(g), Some(u)) => {
2394+ out.push_str(" class=\"");
2395+ out.push_str(g);
2396+ out.push(' ');
2397+ out.push_str(&html_escape(u));
2398+ out.push('"');
2399+ }
2400+ (Some(g), None) => {
2401+ out.push_str(" class=\"");
2402+ out.push_str(g);
2403+ out.push('"');
2404+ }
2405+ (None, Some(u)) => {
2406+ out.push_str(" class=\"");
2407+ out.push_str(&html_escape(u));
2408+ out.push('"');
2409+ }
2410+ (None, None) => {}
2411+ }
2412+}
2413+
2414+// ---------------------------------------------------------------------------
2415+// Attribute → CSS mapping
2416+// ---------------------------------------------------------------------------
2417+
2418+/// (htmlang prefix, CSS selector suffix)
2419+const PSEUDO_PREFIXES: &[(&str, &str)] = &[
2420+ ("hover:", ":hover"),
2421+ ("active:", ":active"),
2422+ ("focus:", ":focus"),
2423+ ("focus-visible:", ":focus-visible"),
2424+ ("focus-within:", ":focus-within"),
2425+ ("disabled:", ":disabled"),
2426+ ("checked:", ":checked"),
2427+ ("placeholder:", "::placeholder"),
2428+ ("first:", ":first-child"),
2429+ ("last:", ":last-child"),
2430+ ("odd:", ":nth-child(odd)"),
2431+ ("even:", ":nth-child(even)"),
2432+ ("before:", "::before"),
2433+ ("after:", "::after"),
2434+ ("selection:", "::selection"),
2435+ ("visited:", ":visited"),
2436+ ("empty:", ":empty"),
2437+ ("target:", ":target"),
2438+ ("valid:", ":valid"),
2439+ ("invalid:", ":invalid"),
2440+];
2441+const RESPONSIVE_PREFIXES: &[&str] = &["sm:", "md:", "lg:", "xl:", "2xl:"];
2442+const MEDIA_PREFIXES: &[&str] = &[
2443+ "dark:",
2444+ "print:",
2445+ "motion-safe:",
2446+ "motion-reduce:",
2447+ "landscape:",
2448+ "portrait:",
2449+];
2450+const CONTAINER_QUERY_PREFIXES: &[&str] = &["cq-sm:", "cq-md:", "cq-lg:", "cq-xl:", "cq-2xl:"];
2451+
2452+fn is_prefixed_attr(key: &str) -> bool {
2453+ PSEUDO_PREFIXES.iter().any(|&(p, _)| key.starts_with(p))
2454+ || RESPONSIVE_PREFIXES.iter().any(|p| key.starts_with(p))
2455+ || MEDIA_PREFIXES.iter().any(|p| key.starts_with(p))
2456+ || CONTAINER_QUERY_PREFIXES.iter().any(|p| key.starts_with(p))
2457+ || key.starts_with("nth:")
2458+ || key.starts_with("has(")
2459+}
2460+
2461+fn attrs_to_css(
2462+ attrs: &[Attribute],
2463+ state_prefix: &str,
2464+ kind: &ElementKind,
2465+ parent_kind: Option<&ElementKind>,
2466+) -> String {
2467+ let mut css = String::new();
2468+
2469+ // Base element styles only for the default (non-state) pass
2470+ if state_prefix.is_empty() {
2471+ match kind {
2472+ ElementKind::Row => css.push_str("display:flex;flex-direction:row;"),
2473+ ElementKind::Column => css.push_str("display:flex;flex-direction:column;"),
2474+ ElementKind::El => css.push_str("display:flex;flex-direction:column;"),
2475+ ElementKind::Paragraph => css.push_str("margin:0;"),
2476+ // Semantic elements get flex column layout like @el
2477+ ElementKind::Nav | ElementKind::Header | ElementKind::Footer
2478+ | ElementKind::Main | ElementKind::Section | ElementKind::Article
2479+ | ElementKind::Aside => css.push_str("display:flex;flex-direction:column;"),
2480+ // Lists: reset browser defaults
2481+ ElementKind::List => css.push_str("margin:0;padding-left:0;list-style:none;"),
2482+ ElementKind::ListItem => css.push_str("display:flex;flex-direction:column;"),
2483+ // Form: flex column like @el
2484+ ElementKind::Form => css.push_str("display:flex;flex-direction:column;"),
2485+ // Details: flex column
2486+ ElementKind::Details => css.push_str("display:flex;flex-direction:column;"),
2487+ // Figure: flex column
2488+ ElementKind::Figure => css.push_str("display:flex;flex-direction:column;margin:0;"),
2489+ // Blockquote: flex column, reset browser margin
2490+ ElementKind::Blockquote => css.push_str("display:flex;flex-direction:column;margin:0;"),
2491+ // Pre: preserve whitespace
2492+ ElementKind::Pre => css.push_str("margin:0;white-space:pre;font-family:ui-monospace,monospace;"),
2493+ // Code: monospace font
2494+ ElementKind::Code => css.push_str("font-family:ui-monospace,monospace;"),
2495+ // New elements
2496+ ElementKind::Dialog => css.push_str("display:flex;flex-direction:column;"),
2497+ ElementKind::DefinitionList => css.push_str("margin:0;"),
2498+ ElementKind::DefinitionDescription => css.push_str("margin:0;display:flex;flex-direction:column;"),
2499+ ElementKind::Fieldset => css.push_str("display:flex;flex-direction:column;border:1px solid currentColor;padding:0.5em;margin:0;"),
2500+ ElementKind::Kbd => css.push_str("font-family:ui-monospace,monospace;"),
2501+ ElementKind::Grid => css.push_str("display:grid;"),
2502+ ElementKind::Stack => css.push_str("position:relative;"),
2503+ ElementKind::Badge => css.push_str("display:inline-flex;align-items:center;justify-content:center;padding:2px 8px;border-radius:9999px;font-size:0.75rem;font-weight:600;line-height:1;"),
2504+ ElementKind::Tooltip => css.push_str("position:relative;cursor:help;"),
2505+ ElementKind::Spacer => css.push_str("flex:1;"),
2506+ ElementKind::Avatar => css.push_str("display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;overflow:hidden;flex-shrink:0;"),
2507+ 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;"),
2508+ 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;"),
2509+ ElementKind::Tag => css.push_str("display:inline-flex;align-items:center;padding:2px 8px;border-radius:4px;font-size:0.75rem;font-weight:600;"),
2510+ _ => {}
2511+ }
2512+ // Children of @carousel get scroll-snap-align and flex-shrink
2513+ if matches!(parent_kind, Some(ElementKind::Carousel)) {
2514+ css.push_str("scroll-snap-align:start;flex-shrink:0;");
2515+ }
2516+ }
2517+
2518+ for attr in attrs {
2519+ // Determine the effective key for this pass
2520+ let effective_key = if state_prefix.is_empty() {
2521+ if is_prefixed_attr(&attr.key) {
2522+ continue;
2523+ }
2524+ attr.key.as_str()
2525+ } else {
2526+ match attr.key.strip_prefix(state_prefix) {
2527+ Some(k) => k,
2528+ None => continue,
2529+ }
2530+ };
2531+
2532+ let val = attr.value.as_deref();
2533+
2534+ match effective_key {
2535+ // Layout
2536+ "spacing" | "gap" => {
2537+ if let Some(v) = val {
2538+ push_css(&mut css, "gap", &css_px(v));
2539+ }
2540+ }
2541+ "padding" => {
2542+ if let Some(v) = val {
2543+ push_css(&mut css, "padding", &css_px_multi(v));
2544+ }
2545+ }
2546+ "padding-x" => {
2547+ if let Some(v) = val {
2548+ push_css(&mut css, "padding-left", &css_px(v));
2549+ push_css(&mut css, "padding-right", &css_px(v));
2550+ }
2551+ }
2552+ "padding-y" => {
2553+ if let Some(v) = val {
2554+ push_css(&mut css, "padding-top", &css_px(v));
2555+ push_css(&mut css, "padding-bottom", &css_px(v));
2556+ }
2557+ }
2558+
2559+ // Sizing
2560+ "width" => {
2561+ if let Some(v) = val {
2562+ match v {
2563+ "fill" => match parent_kind {
2564+ Some(ElementKind::Row) => {
2565+ push_css(&mut css, "flex", "1");
2566+ push_css(&mut css, "min-width", "0");
2567+ }
2568+ _ => push_css(&mut css, "width", "100%"),
2569+ },
2570+ "shrink" => push_css(&mut css, "flex-shrink", "0"),
2571+ _ => push_css(&mut css, "width", &css_px(v)),
2572+ }
2573+ }
2574+ }
2575+ "height" => {
2576+ if let Some(v) = val {
2577+ match v {
2578+ "fill" => match parent_kind {
2579+ Some(ElementKind::Column) => {
2580+ push_css(&mut css, "flex", "1");
2581+ push_css(&mut css, "min-height", "0");
2582+ }
2583+ _ => push_css(&mut css, "height", "100%"),
2584+ },
2585+ "shrink" => push_css(&mut css, "flex-shrink", "0"),
2586+ _ => push_css(&mut css, "height", &css_px(v)),
2587+ }
2588+ }
2589+ }
2590+ "min-width" => {
2591+ if let Some(v) = val {
2592+ push_css(&mut css, "min-width", &css_px(v));
2593+ }
2594+ }
2595+ "max-width" => {
2596+ if let Some(v) = val {
2597+ push_css(&mut css, "max-width", &css_px(v));
2598+ }
2599+ }
2600+ "min-height" => {
2601+ if let Some(v) = val {
2602+ push_css(&mut css, "min-height", &css_px(v));
2603+ }
2604+ }
2605+ "max-height" => {
2606+ if let Some(v) = val {
2607+ push_css(&mut css, "max-height", &css_px(v));
2608+ }
2609+ }
2610+
2611+ // Alignment
2612+ "center-x" => match parent_kind {
2613+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2614+ push_css(&mut css, "align-self", "center");
2615+ }
2616+ _ => {
2617+ push_css(&mut css, "margin-left", "auto");
2618+ push_css(&mut css, "margin-right", "auto");
2619+ }
2620+ },
2621+ "center-y" => match parent_kind {
2622+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "center"),
2623+ _ => {
2624+ push_css(&mut css, "margin-top", "auto");
2625+ push_css(&mut css, "margin-bottom", "auto");
2626+ }
2627+ },
2628+ "align-left" => match parent_kind {
2629+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2630+ push_css(&mut css, "align-self", "flex-start");
2631+ }
2632+ _ => push_css(&mut css, "margin-right", "auto"),
2633+ },
2634+ "align-right" => match parent_kind {
2635+ Some(ElementKind::Column) | Some(ElementKind::El) => {
2636+ push_css(&mut css, "align-self", "flex-end");
2637+ }
2638+ _ => push_css(&mut css, "margin-left", "auto"),
2639+ },
2640+ "align-top" => match parent_kind {
2641+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-start"),
2642+ _ => push_css(&mut css, "margin-bottom", "auto"),
2643+ },
2644+ "align-bottom" => match parent_kind {
2645+ Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-end"),
2646+ _ => push_css(&mut css, "margin-top", "auto"),
2647+ },
2648+
2649+ // Style
2650+ "background" => {
2651+ if let Some(v) = val {
2652+ push_css(&mut css, "background", v);
2653+ }
2654+ }
2655+ "color" => {
2656+ if let Some(v) = val {
2657+ push_css(&mut css, "color", v);
2658+ }
2659+ }
2660+ "border" => {
2661+ if let Some(v) = val {
2662+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2663+ if parts.len() == 2 {
2664+ push_css(
2665+ &mut css,
2666+ "border",
2667+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2668+ );
2669+ } else {
2670+ push_css(
2671+ &mut css,
2672+ "border",
2673+ &format!("{} solid currentColor", css_px(parts[0])),
2674+ );
2675+ }
2676+ }
2677+ }
2678+ "border-top" | "border-bottom" | "border-left" | "border-right" => {
2679+ if let Some(v) = val {
2680+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2681+ if parts.len() == 2 {
2682+ push_css(
2683+ &mut css,
2684+ effective_key,
2685+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2686+ );
2687+ } else {
2688+ push_css(
2689+ &mut css,
2690+ effective_key,
2691+ &format!("{} solid currentColor", css_px(parts[0])),
2692+ );
2693+ }
2694+ }
2695+ }
2696+ "rounded" => {
2697+ if let Some(v) = val {
2698+ push_css(&mut css, "border-radius", &css_px(v));
2699+ }
2700+ }
2701+ "bold" => push_css(&mut css, "font-weight", "bold"),
2702+ "italic" => push_css(&mut css, "font-style", "italic"),
2703+ "underline" => push_css(&mut css, "text-decoration", "underline"),
2704+ "size" => {
2705+ if let Some(v) = val {
2706+ push_css(&mut css, "font-size", &css_px(v));
2707+ }
2708+ }
2709+ "font" => {
2710+ if let Some(v) = val {
2711+ push_css(&mut css, "font-family", v);
2712+ }
2713+ }
2714+ "transition" => {
2715+ if let Some(v) = val {
2716+ push_css(&mut css, "transition", v);
2717+ }
2718+ }
2719+ "cursor" => {
2720+ if let Some(v) = val {
2721+ push_css(&mut css, "cursor", v);
2722+ }
2723+ }
2724+ "opacity" => {
2725+ if let Some(v) = val {
2726+ push_css(&mut css, "opacity", v);
2727+ }
2728+ }
2729+
2730+ // Typography
2731+ "text-align" => {
2732+ if let Some(v) = val {
2733+ push_css(&mut css, "text-align", v);
2734+ }
2735+ }
2736+ "line-height" => {
2737+ if let Some(v) = val {
2738+ push_css(&mut css, "line-height", &css_line_height(v));
2739+ }
2740+ }
2741+ "letter-spacing" => {
2742+ if let Some(v) = val {
2743+ push_css(&mut css, "letter-spacing", &css_px(v));
2744+ }
2745+ }
2746+ "text-transform" => {
2747+ if let Some(v) = val {
2748+ push_css(&mut css, "text-transform", v);
2749+ }
2750+ }
2751+ "white-space" => {
2752+ if let Some(v) = val {
2753+ push_css(&mut css, "white-space", v);
2754+ }
2755+ }
2756+
2757+ // Overflow & positioning
2758+ "overflow" => {
2759+ if let Some(v) = val {
2760+ push_css(&mut css, "overflow", v);
2761+ }
2762+ }
2763+ "position" => {
2764+ if let Some(v) = val {
2765+ push_css(&mut css, "position", v);
2766+ }
2767+ }
2768+ "top" => {
2769+ if let Some(v) = val {
2770+ push_css(&mut css, "top", &css_px(v));
2771+ }
2772+ }
2773+ "right" => {
2774+ if let Some(v) = val {
2775+ push_css(&mut css, "right", &css_px(v));
2776+ }
2777+ }
2778+ "bottom" => {
2779+ if let Some(v) = val {
2780+ push_css(&mut css, "bottom", &css_px(v));
2781+ }
2782+ }
2783+ "left" => {
2784+ if let Some(v) = val {
2785+ push_css(&mut css, "left", &css_px(v));
2786+ }
2787+ }
2788+ "z-index" => {
2789+ if let Some(v) = val {
2790+ push_css(&mut css, "z-index", v);
2791+ }
2792+ }
2793+
2794+ // Display & visibility
2795+ "display" => {
2796+ if let Some(v) = val {
2797+ push_css(&mut css, "display", v);
2798+ }
2799+ }
2800+ "visibility" => {
2801+ if let Some(v) = val {
2802+ push_css(&mut css, "visibility", v);
2803+ }
2804+ }
2805+ "hidden" => push_css(&mut css, "display", "none"),
2806+
2807+ // Transform & filters
2808+ "transform" => {
2809+ if let Some(v) = val {
2810+ push_css(&mut css, "transform", v);
2811+ }
2812+ }
2813+ "backdrop-filter" => {
2814+ if let Some(v) = val {
2815+ push_css(&mut css, "backdrop-filter", v);
2816+ }
2817+ }
2818+
2819+ // Effects
2820+ "shadow" => {
2821+ if let Some(v) = val {
2822+ push_css(&mut css, "box-shadow", v);
2823+ }
2824+ }
2825+
2826+ // Flow
2827+ "wrap" => push_css(&mut css, "flex-wrap", "wrap"),
2828+ "gap-x" => {
2829+ if let Some(v) = val {
2830+ push_css(&mut css, "column-gap", &css_px(v));
2831+ }
2832+ }
2833+ "gap-y" => {
2834+ if let Some(v) = val {
2835+ push_css(&mut css, "row-gap", &css_px(v));
2836+ }
2837+ }
2838+
2839+ // Grid
2840+ "grid" => {
2841+ push_css(&mut css, "display", "grid");
2842+ }
2843+ "grid-cols" => {
2844+ if let Some(v) = val {
2845+ if let Ok(n) = v.parse::<u32>() {
2846+ push_css(
2847+ &mut css,
2848+ "grid-template-columns",
2849+ &format!("repeat({},1fr)", n),
2850+ );
2851+ } else {
2852+ push_css(&mut css, "grid-template-columns", v);
2853+ }
2854+ }
2855+ }
2856+ "grid-rows" => {
2857+ if let Some(v) = val {
2858+ if let Ok(n) = v.parse::<u32>() {
2859+ push_css(
2860+ &mut css,
2861+ "grid-template-rows",
2862+ &format!("repeat({},1fr)", n),
2863+ );
2864+ } else {
2865+ push_css(&mut css, "grid-template-rows", v);
2866+ }
2867+ }
2868+ }
2869+ "col-span" => {
2870+ if let Some(v) = val {
2871+ push_css(&mut css, "grid-column", &format!("span {}", v));
2872+ }
2873+ }
2874+ "row-span" => {
2875+ if let Some(v) = val {
2876+ push_css(&mut css, "grid-row", &format!("span {}", v));
2877+ }
2878+ }
2879+
2880+ // Animation
2881+ "animation" => {
2882+ if let Some(v) = val {
2883+ push_css(&mut css, "animation", v);
2884+ }
2885+ }
2886+
2887+ // Aspect ratio
2888+ "aspect-ratio" => {
2889+ if let Some(v) = val {
2890+ push_css(&mut css, "aspect-ratio", v);
2891+ }
2892+ }
2893+
2894+ // CSS containment for rendering performance
2895+ "contain" => {
2896+ if let Some(v) = val {
2897+ push_css(&mut css, "contain", v);
2898+ } else {
2899+ push_css(&mut css, "contain", "layout style paint");
2900+ }
2901+ }
2902+ "content-visibility" => {
2903+ if let Some(v) = val {
2904+ push_css(&mut css, "content-visibility", v);
2905+ } else {
2906+ push_css(&mut css, "content-visibility", "auto");
2907+ }
2908+ }
2909+
2910+ // Outline (like border but doesn't affect layout)
2911+ "outline" => {
2912+ if let Some(v) = val {
2913+ let parts: Vec<&str> = v.splitn(2, ' ').collect();
2914+ if parts.len() == 2 {
2915+ push_css(
2916+ &mut css,
2917+ "outline",
2918+ &format!("{} solid {}", css_px(parts[0]), parts[1]),
2919+ );
2920+ } else {
2921+ push_css(
2922+ &mut css,
2923+ "outline",
2924+ &format!("{} solid currentColor", css_px(parts[0])),
2925+ );
2926+ }
2927+ }
2928+ }
2929+
2930+ // Logical properties (i18n-aware)
2931+ "padding-inline" => {
2932+ if let Some(v) = val {
2933+ push_css(&mut css, "padding-inline", &css_px_multi(v));
2934+ }
2935+ }
2936+ "padding-block" => {
2937+ if let Some(v) = val {
2938+ push_css(&mut css, "padding-block", &css_px_multi(v));
2939+ }
2940+ }
2941+ "margin-inline" => {
2942+ if let Some(v) = val {
2943+ push_css(&mut css, "margin-inline", &css_px_multi(v));
2944+ }
2945+ }
2946+ "margin-block" => {
2947+ if let Some(v) = val {
2948+ push_css(&mut css, "margin-block", &css_px_multi(v));
2949+ }
2950+ }
2951+
2952+ // Logical property start/end variants
2953+ "padding-inline-start"
2954+ | "padding-inline-end"
2955+ | "padding-block-start"
2956+ | "padding-block-end"
2957+ | "margin-inline-start"
2958+ | "margin-inline-end"
2959+ | "margin-block-start"
2960+ | "margin-block-end" => {
2961+ if let Some(v) = val {
2962+ push_css(&mut css, effective_key, &css_px(v));
2963+ }
2964+ }
2965+
2966+ // Logical inset
2967+ "inset-inline" | "inset-block" => {
2968+ if let Some(v) = val {
2969+ push_css(&mut css, effective_key, &css_px_multi(v));
2970+ }
2971+ }
2972+ "inset-inline-start" | "inset-inline-end" | "inset-block-start" | "inset-block-end" => {
2973+ if let Some(v) = val {
2974+ push_css(&mut css, effective_key, &css_px(v));
2975+ }
2976+ }
2977+
2978+ // Logical border
2979+ "border-inline"
2980+ | "border-block"
2981+ | "border-inline-start"
2982+ | "border-inline-end"
2983+ | "border-block-start"
2984+ | "border-block-end" => {
2985+ if let Some(v) = val {
2986+ push_css(&mut css, effective_key, v);
2987+ }
2988+ }
2989+
2990+ // Logical border-radius
2991+ "border-start-start-radius"
2992+ | "border-start-end-radius"
2993+ | "border-end-start-radius"
2994+ | "border-end-end-radius" => {
2995+ if let Some(v) = val {
2996+ push_css(&mut css, effective_key, &css_px(v));
2997+ }
2998+ }
2999+
3000+ // Logical scroll margins & padding
3001+ "scroll-margin-inline"
3002+ | "scroll-margin-block"
3003+ | "scroll-padding-inline"
3004+ | "scroll-padding-block" => {
3005+ if let Some(v) = val {
3006+ push_css(&mut css, effective_key, &css_px_multi(v));
3007+ }
3008+ }
3009+
3010+ // Logical sizing
3011+ "inline-size" | "block-size" | "min-inline-size" | "max-inline-size"
3012+ | "min-block-size" | "max-block-size" => {
3013+ if let Some(v) = val {
3014+ push_css(&mut css, effective_key, &css_px(v));
3015+ }
3016+ }
3017+
3018+ // Scroll snap
3019+ "scroll-snap-type" => {
3020+ if let Some(v) = val {
3021+ push_css(&mut css, "scroll-snap-type", v);
3022+ }
3023+ }
3024+ "scroll-snap-align" => {
3025+ if let Some(v) = val {
3026+ push_css(&mut css, "scroll-snap-align", v);
3027+ }
3028+ }
3029+
3030+ // Margin
3031+ "margin" => {
3032+ if let Some(v) = val {
3033+ push_css(&mut css, "margin", &css_px_multi(v));
3034+ }
3035+ }
3036+ "margin-x" => {
3037+ if let Some(v) = val {
3038+ push_css(&mut css, "margin-left", &css_px(v));
3039+ push_css(&mut css, "margin-right", &css_px(v));
3040+ }
3041+ }
3042+ "margin-y" => {
3043+ if let Some(v) = val {
3044+ push_css(&mut css, "margin-top", &css_px(v));
3045+ push_css(&mut css, "margin-bottom", &css_px(v));
3046+ }
3047+ }
3048+
3049+ // Filter
3050+ "filter" => {
3051+ if let Some(v) = val {
3052+ push_css(&mut css, "filter", v);
3053+ }
3054+ }
3055+
3056+ // Object fit/position (for images)
3057+ "object-fit" => {
3058+ if let Some(v) = val {
3059+ push_css(&mut css, "object-fit", v);
3060+ }
3061+ }
3062+ "object-position" => {
3063+ if let Some(v) = val {
3064+ push_css(&mut css, "object-position", v);
3065+ }
3066+ }
3067+
3068+ // Text shadow
3069+ "text-shadow" => {
3070+ if let Some(v) = val {
3071+ push_css(&mut css, "text-shadow", v);
3072+ }
3073+ }
3074+
3075+ // Text overflow
3076+ "text-overflow" => {
3077+ if let Some(v) = val {
3078+ push_css(&mut css, "text-overflow", v);
3079+ }
3080+ }
3081+
3082+ // Interaction
3083+ "pointer-events" => {
3084+ if let Some(v) = val {
3085+ push_css(&mut css, "pointer-events", v);
3086+ }
3087+ }
3088+ "user-select" => {
3089+ if let Some(v) = val {
3090+ push_css(&mut css, "user-select", v);
3091+ }
3092+ }
3093+
3094+ // Flexbox/grid alignment
3095+ "justify-content" => {
3096+ if let Some(v) = val {
3097+ push_css(&mut css, "justify-content", v);
3098+ }
3099+ }
3100+ "align-items" => {
3101+ if let Some(v) = val {
3102+ push_css(&mut css, "align-items", v);
3103+ }
3104+ }
3105+
3106+ // Flex item order
3107+ "order" => {
3108+ if let Some(v) = val {
3109+ push_css(&mut css, "order", v);
3110+ }
3111+ }
3112+
3113+ // Background extras
3114+ "background-size" => {
3115+ if let Some(v) = val {
3116+ push_css(&mut css, "background-size", v);
3117+ }
3118+ }
3119+ "background-position" => {
3120+ if let Some(v) = val {
3121+ push_css(&mut css, "background-position", v);
3122+ }
3123+ }
3124+ "background-repeat" => {
3125+ if let Some(v) = val {
3126+ push_css(&mut css, "background-repeat", v);
3127+ }
3128+ }
3129+
3130+ // Text wrapping
3131+ "word-break" => {
3132+ if let Some(v) = val {
3133+ push_css(&mut css, "word-break", v);
3134+ }
3135+ }
3136+ "overflow-wrap" => {
3137+ if let Some(v) = val {
3138+ push_css(&mut css, "overflow-wrap", v);
3139+ }
3140+ }
3141+
3142+ // Container queries
3143+ "container" => {
3144+ push_css(&mut css, "container-type", "inline-size");
3145+ }
3146+ "container-name" => {
3147+ if let Some(v) = val {
3148+ push_css(&mut css, "container-name", v);
3149+ }
3150+ }
3151+ "container-type" => {
3152+ if let Some(v) = val {
3153+ push_css(&mut css, "container-type", v);
3154+ }
3155+ }
3156+
3157+ // Overflow axis
3158+ "overflow-x" => {
3159+ if let Some(v) = val {
3160+ push_css(&mut css, "overflow-x", v);
3161+ }
3162+ }
3163+ "overflow-y" => {
3164+ if let Some(v) = val {
3165+ push_css(&mut css, "overflow-y", v);
3166+ }
3167+ }
3168+
3169+ // Inset (shorthand for top/right/bottom/left)
3170+ "inset" => {
3171+ if let Some(v) = val {
3172+ push_css(&mut css, "inset", &css_px(v));
3173+ }
3174+ }
3175+
3176+ // Accent & caret colors
3177+ "accent-color" => {
3178+ if let Some(v) = val {
3179+ push_css(&mut css, "accent-color", v);
3180+ }
3181+ }
3182+ "caret-color" => {
3183+ if let Some(v) = val {
3184+ push_css(&mut css, "caret-color", v);
3185+ }
3186+ }
3187+
3188+ // Color scheme & appearance
3189+ "color-scheme" => {
3190+ if let Some(v) = val {
3191+ push_css(&mut css, "color-scheme", v);
3192+ }
3193+ }
3194+ "appearance" => {
3195+ if let Some(v) = val {
3196+ push_css(&mut css, "appearance", v);
3197+ }
3198+ }
3199+
3200+ // List style
3201+ "list-style" => {
3202+ if let Some(v) = val {
3203+ push_css(&mut css, "list-style", v);
3204+ }
3205+ }
3206+
3207+ // Table
3208+ "border-collapse" => {
3209+ if let Some(v) = val {
3210+ push_css(&mut css, "border-collapse", v);
3211+ }
3212+ }
3213+ "border-spacing" => {
3214+ if let Some(v) = val {
3215+ push_css(&mut css, "border-spacing", &css_px(v));
3216+ }
3217+ }
3218+
3219+ // Text decoration
3220+ "text-decoration" => {
3221+ if let Some(v) = val {
3222+ push_css(&mut css, "text-decoration", v);
3223+ }
3224+ }
3225+ "text-decoration-color" => {
3226+ if let Some(v) = val {
3227+ push_css(&mut css, "text-decoration-color", v);
3228+ }
3229+ }
3230+ "text-decoration-thickness" => {
3231+ if let Some(v) = val {
3232+ push_css(&mut css, "text-decoration-thickness", &css_px(v));
3233+ }
3234+ }
3235+ "text-decoration-style" => {
3236+ if let Some(v) = val {
3237+ push_css(&mut css, "text-decoration-style", v);
3238+ }
3239+ }
3240+ "text-underline-offset" => {
3241+ if let Some(v) = val {
3242+ push_css(&mut css, "text-underline-offset", &css_px(v));
3243+ }
3244+ }
3245+
3246+ // Multi-column
3247+ "column-width" => {
3248+ if let Some(v) = val {
3249+ push_css(&mut css, "column-width", &css_px(v));
3250+ }
3251+ }
3252+ "column-rule" => {
3253+ if let Some(v) = val {
3254+ push_css(&mut css, "column-rule", v);
3255+ }
3256+ }
3257+
3258+ // Place items/self
3259+ "place-items" => {
3260+ if let Some(v) = val {
3261+ push_css(&mut css, "place-items", v);
3262+ }
3263+ }
3264+ "place-self" => {
3265+ if let Some(v) = val {
3266+ push_css(&mut css, "place-self", v);
3267+ }
3268+ }
3269+
3270+ // Scroll behavior
3271+ "scroll-behavior" => {
3272+ if let Some(v) = val {
3273+ push_css(&mut css, "scroll-behavior", v);
3274+ }
3275+ }
3276+
3277+ // Resize
3278+ "resize" => {
3279+ if let Some(v) = val {
3280+ push_css(&mut css, "resize", v);
3281+ }
3282+ }
3283+
3284+ // New CSS properties
3285+ "clip-path" => {
3286+ if let Some(v) = val {
3287+ push_css(&mut css, "clip-path", v);
3288+ }
3289+ }
3290+ "mix-blend-mode" => {
3291+ if let Some(v) = val {
3292+ push_css(&mut css, "mix-blend-mode", v);
3293+ }
3294+ }
3295+ "background-blend-mode" => {
3296+ if let Some(v) = val {
3297+ push_css(&mut css, "background-blend-mode", v);
3298+ }
3299+ }
3300+ "writing-mode" => {
3301+ if let Some(v) = val {
3302+ push_css(&mut css, "writing-mode", v);
3303+ }
3304+ }
3305+ "column-count" => {
3306+ if let Some(v) = val {
3307+ push_css(&mut css, "column-count", v);
3308+ }
3309+ }
3310+ "column-gap" => {
3311+ if let Some(v) = val {
3312+ push_css(&mut css, "column-gap", &css_px(v));
3313+ }
3314+ }
3315+ "text-indent" => {
3316+ if let Some(v) = val {
3317+ push_css(&mut css, "text-indent", &css_px(v));
3318+ }
3319+ }
3320+ "hyphens" => {
3321+ if let Some(v) = val {
3322+ push_css(&mut css, "hyphens", v);
3323+ }
3324+ }
3325+ "flex-grow" => {
3326+ if let Some(v) = val {
3327+ push_css(&mut css, "flex-grow", v);
3328+ }
3329+ }
3330+ "flex-shrink" => {
3331+ if let Some(v) = val {
3332+ push_css(&mut css, "flex-shrink", v);
3333+ }
3334+ }
3335+ "flex-basis" => {
3336+ if let Some(v) = val {
3337+ push_css(&mut css, "flex-basis", &css_px(v));
3338+ }
3339+ }
3340+ "isolation" => {
3341+ if let Some(v) = val {
3342+ push_css(&mut css, "isolation", v);
3343+ }
3344+ }
3345+ "place-content" => {
3346+ if let Some(v) = val {
3347+ push_css(&mut css, "place-content", v);
3348+ }
3349+ }
3350+ "background-image" => {
3351+ if let Some(v) = val {
3352+ push_css(&mut css, "background-image", v);
3353+ }
3354+ }
3355+ "font-weight" => {
3356+ if let Some(v) = val {
3357+ push_css(&mut css, "font-weight", v);
3358+ }
3359+ }
3360+ "font-style" => {
3361+ if let Some(v) = val {
3362+ push_css(&mut css, "font-style", v);
3363+ }
3364+ }
3365+ "text-wrap" => {
3366+ if let Some(v) = val {
3367+ push_css(&mut css, "text-wrap", v);
3368+ }
3369+ }
3370+ "will-change" => {
3371+ if let Some(v) = val {
3372+ push_css(&mut css, "will-change", v);
3373+ }
3374+ }
3375+ "touch-action" => {
3376+ if let Some(v) = val {
3377+ push_css(&mut css, "touch-action", v);
3378+ }
3379+ }
3380+ "vertical-align" => {
3381+ if let Some(v) = val {
3382+ push_css(&mut css, "vertical-align", v);
3383+ }
3384+ }
3385+ "scroll-margin" => {
3386+ if let Some(v) = val {
3387+ push_css(&mut css, "scroll-margin", &css_px(v));
3388+ }
3389+ }
3390+ "scroll-margin-top"
3391+ | "scroll-margin-bottom"
3392+ | "scroll-margin-left"
3393+ | "scroll-margin-right" => {
3394+ if let Some(v) = val {
3395+ push_css(&mut css, effective_key, &css_px(v));
3396+ }
3397+ }
3398+ "scroll-padding" => {
3399+ if let Some(v) = val {
3400+ push_css(&mut css, "scroll-padding", &css_px(v));
3401+ }
3402+ }
3403+ "scroll-padding-top"
3404+ | "scroll-padding-bottom"
3405+ | "scroll-padding-left"
3406+ | "scroll-padding-right" => {
3407+ if let Some(v) = val {
3408+ push_css(&mut css, effective_key, &css_px(v));
3409+ }
3410+ }
3411+ "direction" => {
3412+ if let Some(v) = val {
3413+ push_css(&mut css, "direction", v);
3414+ }
3415+ }
3416+
3417+ "content" => {
3418+ if let Some(v) = val {
3419+ // Wrap in quotes if not already quoted and not a CSS keyword
3420+ if v.starts_with('"')
3421+ || v.starts_with('\'')
3422+ || v == "none"
3423+ || v == "normal"
3424+ || v.starts_with("attr(")
3425+ || v.starts_with("counter(")
3426+ {
3427+ push_css(&mut css, "content", v);
3428+ } else {
3429+ push_css(&mut css, "content", &format!("\"{}\"", v));
3430+ }
3431+ }
3432+ }
3433+
3434+ // --- CSS Shorthands ---
3435+ "truncate" => {
3436+ push_css(&mut css, "overflow", "hidden");
3437+ push_css(&mut css, "text-overflow", "ellipsis");
3438+ push_css(&mut css, "white-space", "nowrap");
3439+ }
3440+ "line-clamp" => {
3441+ if let Some(v) = val {
3442+ push_css(&mut css, "display", "-webkit-box");
3443+ push_css(&mut css, "-webkit-line-clamp", v);
3444+ push_css(&mut css, "-webkit-box-orient", "vertical");
3445+ push_css(&mut css, "overflow", "hidden");
3446+ }
3447+ }
3448+ "blur" => {
3449+ if let Some(v) = val {
3450+ push_css(&mut css, "filter", &format!("blur({})", css_px(v)));
3451+ }
3452+ }
3453+ "backdrop-blur" => {
3454+ if let Some(v) = val {
3455+ push_css(&mut css, "backdrop-filter", &format!("blur({})", css_px(v)));
3456+ }
3457+ }
3458+ "no-scrollbar" => {
3459+ push_css(&mut css, "scrollbar-width", "none");
3460+ push_css(&mut css, "-ms-overflow-style", "none");
3461+ }
3462+ "skeleton" => {
3463+ push_css(
3464+ &mut css,
3465+ "background",
3466+ "linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%)",
3467+ );
3468+ push_css(&mut css, "background-size", "200% 100%");
3469+ push_css(
3470+ &mut css,
3471+ "animation",
3472+ "hl-skeleton 1.5s ease-in-out infinite",
3473+ );
3474+ }
3475+ "gradient" => {
3476+ if let Some(v) = val {
3477+ // Parse: "from to [angle]" or "color1 color2 [angle]"
3478+ let parts: Vec<&str> = v.split_whitespace().collect();
3479+ let bg = if parts.len() >= 3
3480+ && (parts[2].ends_with("deg")
3481+ || parts[2].ends_with("turn")
3482+ || parts[2].ends_with("rad"))
3483+ {
3484+ format!("linear-gradient({},{},{})", parts[2], parts[0], parts[1])
3485+ } else if parts.len() >= 2 {
3486+ format!("linear-gradient({},{})", parts[0], parts[1])
3487+ } else {
3488+ format!("linear-gradient({},transparent)", parts[0])
3489+ };
3490+ push_css(&mut css, "background", &bg);
3491+ }
3492+ }
3493+
3494+ // Grid areas
3495+ "grid-template-areas" => {
3496+ if let Some(v) = val {
3497+ push_css(&mut css, "grid-template-areas", v);
3498+ }
3499+ }
3500+ "grid-area" => {
3501+ if let Some(v) = val {
3502+ push_css(&mut css, "grid-area", v);
3503+ }
3504+ }
3505+
3506+ // View transitions
3507+ "view-transition-name" => {
3508+ if let Some(v) = val {
3509+ push_css(&mut css, "view-transition-name", v);
3510+ }
3511+ }
3512+
3513+ // Animate shorthand (alias for animation)
3514+ "animate" => {
3515+ if let Some(v) = val {
3516+ push_css(&mut css, "animation", v);
3517+ }
3518+ }
3519+
3520+ // CSS subgrid
3521+ "grid-template-columns" => {
3522+ if let Some(v) = val {
3523+ push_css(&mut css, "grid-template-columns", v);
3524+ }
3525+ }
3526+ "grid-template-rows" => {
3527+ if let Some(v) = val {
3528+ push_css(&mut css, "grid-template-rows", v);
3529+ }
3530+ }
3531+
3532+ // Scroll-driven animations
3533+ "animation-timeline" => {
3534+ if let Some(v) = val {
3535+ push_css(&mut css, "animation-timeline", v);
3536+ }
3537+ }
3538+ "animation-range" => {
3539+ if let Some(v) = val {
3540+ push_css(&mut css, "animation-range", v);
3541+ }
3542+ }
3543+ "view-timeline-name" => {
3544+ if let Some(v) = val {
3545+ push_css(&mut css, "view-timeline-name", v);
3546+ }
3547+ }
3548+ "view-timeline-axis" => {
3549+ if let Some(v) = val {
3550+ push_css(&mut css, "view-timeline-axis", v);
3551+ }
3552+ }
3553+ "scroll-timeline-name" => {
3554+ if let Some(v) = val {
3555+ push_css(&mut css, "scroll-timeline-name", v);
3556+ }
3557+ }
3558+ "scroll-timeline-axis" => {
3559+ if let Some(v) = val {
3560+ push_css(&mut css, "scroll-timeline-axis", v);
3561+ }
3562+ }
3563+
3564+ // Anchor positioning
3565+ "anchor-name" => {
3566+ if let Some(v) = val {
3567+ push_css(&mut css, "anchor-name", v);
3568+ }
3569+ }
3570+ "position-anchor" => {
3571+ if let Some(v) = val {
3572+ push_css(&mut css, "position-anchor", v);
3573+ }
3574+ }
3575+ "position-area" => {
3576+ if let Some(v) = val {
3577+ push_css(&mut css, "position-area", v);
3578+ }
3579+ }
3580+ "inset-area" => {
3581+ // Legacy alias for position-area
3582+ if let Some(v) = val {
3583+ push_css(&mut css, "position-area", v);
3584+ }
3585+ }
16933586
1694− // Find index of last occurrence of each property.
1695− use std::collections::HashMap;
1696− let mut last: HashMap<String, usize> = HashMap::new();
1697− for (i, (prop, _)) in decls.iter().enumerate() {
1698− if let Some(p) = prop {
1699− last.insert(p.clone(), i);
1700− }
1701− }
3587+ // initial-letter (drop caps)
3588+ "initial-letter" => {
3589+ if let Some(v) = val {
3590+ push_css(&mut css, "initial-letter", v);
3591+ }
3592+ }
17023593
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−}
3594+ // Critical CSS hint — not CSS, handled elsewhere
3595+ "critical" => {}
3596+
3597+ // Identity and HTML passthrough — not CSS
3598+ "id" | "class" => {}
3599+ "type" | "placeholder" | "name" | "value" | "disabled" | "required" | "checked"
3600+ | "for" | "action" | "method" | "autocomplete" | "min" | "max" | "step" | "pattern"
3601+ | "maxlength" | "rows" | "cols" | "multiple" | "alt" | "role" | "tabindex"
3602+ | "title" | "controls" | "autoplay" | "loop" | "muted" | "poster" | "preload"
3603+ | "loading" | "decoding" | "ordered" | "src" | "open" | "novalidate" | "low"
3604+ | "high" | "optimum" | "colspan" | "rowspan" | "scope" | "inline" | "responsive"
3605+ | "datetime" | "media" | "sizes" | "srcset" | "cite" | "list" | "sandbox" | "allow"
3606+ | "allowfullscreen" | "referrerpolicy" | "formaction" | "formmethod" | "formtarget"
3607+ | "target" | "autofocus" => {}
17153608
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('"');
3609+ _ => {}
17343610 }
1735− (None, None) => {}
17363611 }
1737−}
1738−
1739−// ---------------------------------------------------------------------------
1740−// Attribute → CSS mapping
1741−// ---------------------------------------------------------------------------
17423612
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,
3613+ css
17553614}
17563615
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− }
3616+fn push_css(css: &mut String, prop: &str, value: &str) {
3617+ css.push_str(prop);
3618+ css.push(':');
3619+ css.push_str(value);
3620+ css.push(';');
17693621}
17703622
1771−// ---------------------------------------------------------------------------
1772−// Direction: what a child's `fill` and `shrink` compile against
1773−// ---------------------------------------------------------------------------
3623+/// Known CSS units — if a value ends with one, skip appending `px`.
3624+const CSS_UNITS: &[&str] = &[
3625+ "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh", "ch", "ex", "cm", "mm",
3626+ "in", "pt", "pc", "fr",
3627+];
17743628
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,
3629+/// Format a numeric value: if it already has a CSS unit, pass through as-is;
3630+/// otherwise append `px`.
3631+fn css_px(value: &str) -> String {
3632+ let v = value.trim();
3633+ if v == "0" {
3634+ return "0".to_string();
3635+ }
3636+ if CSS_UNITS.iter().any(|u| v.ends_with(u)) {
3637+ return v.to_string();
3638+ }
3639+ if v.starts_with("var(")
3640+ || v.starts_with("calc(")
3641+ || v.starts_with("clamp(")
3642+ || v.starts_with("min(")
3643+ || v.starts_with("max(")
3644+ {
3645+ return v.to_string();
3646+ }
3647+ format!("{}px", v)
17803648}
17813649
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− })
3650+/// Rewrite literal values that match a declared CSS custom property (from
3651+/// `@theme` or `@let --name value`) to `var(--name)` references. Matches are
3652+/// anchored to CSS value boundaries so e.g. `#3b82f6` inside a longer hex or
3653+/// inside an identifier is not replaced. The `:root` block is emitted before
3654+/// this call runs, so its declarations are not affected.
3655+fn substitute_css_vars(css: &str, vars: &[(String, String)]) -> String {
3656+ if css.is_empty() || vars.is_empty() {
3657+ return css.to_string();
3658+ }
3659+ // Prefer longer values first so that if two vars share a prefix, the
3660+ // longer (more specific) match wins.
3661+ let mut pairs: Vec<(&str, String)> = vars
3662+ .iter()
3663+ .filter(|(name, value)| name.starts_with("--") && !value.is_empty())
3664+ .map(|(name, value)| (value.as_str(), format!("var({})", name)))
3665+ .collect();
3666+ pairs.sort_by_key(|(v, _)| std::cmp::Reverse(v.len()));
3667+ if pairs.is_empty() {
3668+ return css.to_string();
17913669 }
1792−}
17933670
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−}
3671+ let is_boundary_before = |b: Option<u8>| match b {
3672+ None => true,
3673+ Some(c) => matches!(
3674+ c,
3675+ b':' | b' ' | b',' | b'(' | b';' | b'{' | b'\n' | b'\t'
3676+ ),
3677+ };
3678+ let is_boundary_after = |b: Option<u8>| match b {
3679+ None => true,
3680+ Some(c) => matches!(
3681+ c,
3682+ b';' | b'}' | b',' | b' ' | b')' | b'\n' | b'\t'
3683+ ),
3684+ };
18133685
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;
3686+ let bytes = css.as_bytes();
3687+ let mut out = String::with_capacity(css.len());
3688+ let mut i = 0;
3689+ let mut prev: Option<u8> = None;
3690+ while i < bytes.len() {
3691+ if is_boundary_before(prev) {
3692+ let mut matched = false;
3693+ for (val, repl) in &pairs {
3694+ let vb = val.as_bytes();
3695+ if i + vb.len() <= bytes.len() && &bytes[i..i + vb.len()] == vb {
3696+ let next = bytes.get(i + vb.len()).copied();
3697+ if is_boundary_after(next) {
3698+ out.push_str(repl);
3699+ prev = repl.as_bytes().last().copied();
3700+ i += vb.len();
3701+ matched = true;
3702+ break;
3703+ }
3704+ }
18263705 }
1827− let Some(axis) = attr.value.as_deref().and_then(Axis::of_value) else {
3706+ if matched {
18283707 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));
18363708 }
18373709 }
1838− changes.sort_by_key(|(at, _)| at_order(at));
1839− Flow {
1840− base: Some(base),
1841− changes,
1842− class: None,
3710+ // Advance by one UTF-8 code point.
3711+ let start = i;
3712+ i += 1;
3713+ while i < bytes.len() && (bytes[i] & 0xC0) == 0x80 {
3714+ i += 1;
18433715 }
3716+ out.push_str(&css[start..i]);
3717+ prev = bytes.get(i - 1).copied();
18443718 }
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− }
3719+ out
18603720}
18613721
1862−/// `width` or `height`.
1863−#[derive(Clone, Copy, PartialEq, Eq)]
1864−enum Dim {
1865− Width,
1866− Height,
3722+/// Format a `line-height` value. CSS accepts either a unitless multiplier
3723+/// (e.g. `1.5`) or a length (e.g. `24px`). Plain integers in htmlang source
3724+/// are ambiguous: `[line-height 24]` was historically emitted as `24` (which
3725+/// CSS interprets as 24× font-size — almost never what anyone wants). Treat
3726+/// integers ≥ 2 as pixel lengths; anything with a decimal, an existing unit,
3727+/// or the value `0`/`1` passes through unchanged.
3728+fn css_line_height(value: &str) -> String {
3729+ let v = value.trim();
3730+ if v == "0" || v == "1" {
3731+ return v.to_string();
3732+ }
3733+ if v.contains('.') {
3734+ return v.to_string();
3735+ }
3736+ if CSS_UNITS.iter().any(|u| v.ends_with(u)) || v.ends_with("px") {
3737+ return v.to_string();
3738+ }
3739+ if v.starts_with("var(")
3740+ || v.starts_with("calc(")
3741+ || v.starts_with("clamp(")
3742+ || v.starts_with("min(")
3743+ || v.starts_with("max(")
3744+ {
3745+ return v.to_string();
3746+ }
3747+ // Plain integer — treat as pixel length.
3748+ if v.chars().all(|c| c.is_ascii_digit()) {
3749+ return format!("{}px", v);
3750+ }
3751+ v.to_string()
18673752}
18683753
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,
3754+/// Format multiple space-separated values, each getting px if needed.
3755+fn css_px_multi(value: &str) -> String {
3756+ value
3757+ .split_whitespace()
3758+ .map(css_px)
3759+ .collect::<Vec<_>>()
3760+ .join(" ")
18763761}
18773762
1878−impl Size {
1879− fn of(value: &str) -> Size {
1880− match value.trim() {
1881− "fill" => Size::Fill,
1882− "shrink" => Size::Shrink,
1883− _ => Size::Set,
3763+fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
3764+ let mut id = None;
3765+ let mut class = None;
3766+ for attr in attrs {
3767+ match attr.key.as_str() {
3768+ "id" => id = attr.value.clone(),
3769+ "class" => class = attr.value.clone(),
3770+ _ => {}
18843771 }
18853772 }
3773+ (id, class)
18863774}
18873775
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")],
3776+/// Read image dimensions from a local file by parsing the header bytes.
3777+/// Supports PNG, JPEG, GIF, WebP, AVIF, and SVG.
3778+fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
3779+ // SVG: parse as text for viewBox/width/height attributes
3780+ if path.ends_with(".svg") || path.ends_with(".SVG") {
3781+ let text = std::fs::read_to_string(path).ok()?;
3782+ return read_svg_dimensions(&text);
19043783 }
1905−}
19063784
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− ],
3785+ let data = std::fs::read(path).ok()?;
3786+ if data.len() < 12 {
3787+ return None;
19213788 }
1922−}
19233789
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−}
3790+ // PNG: 8-byte signature, then IHDR chunk with width/height at bytes 16-23
3791+ if data.len() >= 24 && data.starts_with(b"\x89PNG\r\n\x1a\n") {
3792+ let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
3793+ let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
3794+ return Some((w, h));
3795+ }
3796+
3797+ // GIF: "GIF87a" or "GIF89a", width/height at bytes 6-9 (little-endian)
3798+ if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
3799+ let w = u16::from_le_bytes([data[6], data[7]]) as u32;
3800+ let h = u16::from_le_bytes([data[8], data[9]]) as u32;
3801+ return Some((w, h));
3802+ }
19433803
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 {
3804+ // JPEG: scan for SOF0/SOF2 marker (0xFF 0xC0 or 0xFF 0xC2)
3805+ if data.starts_with(b"\xff\xd8") {
3806+ let mut i = 2;
3807+ while i + 9 < data.len() {
3808+ if data[i] != 0xFF {
3809+ i += 1;
19533810 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− _ => {}
19793811 }
1980− }
1981− sizes
1982− }
1983−
1984− /// The element writes `property` itself: a layout word leaves it alone.
1985− fn writes(&self, property: &str) -> bool {
1986− match property {
1987− "flex" => self.flex,
1988− "flex-grow" => self.flex || self.flex_grow,
1989− "flex-shrink" => self.flex || self.flex_shrink,
1990− "flex-basis" => self.flex || self.flex_basis,
1991− "min-width" => self.min_width,
1992− "min-height" => self.min_height,
1993− "width" => self.width == Some(Size::Set),
1994− "height" => self.height == Some(Size::Set),
1995− _ => false,
1996− }
1997− }
1998−
1999− /// Write a layout word's `property: value`, unless the element writes
2000− /// the property itself. When it writes some of `flex`'s longhands, a
2001− /// `flex` is written as the others (`flex-shrink 0, width fill` still
2002− /// grows).
2003− fn push(&self, css: &mut String, property: &str, value: &str) {
2004− if property == "flex" && !self.flex {
2005− let longhands = match value {
2006− "1" => [
2007− ("flex-grow", "1"),
2008− ("flex-shrink", "1"),
2009− ("flex-basis", "0%"),
2010− ],
2011− // The reset, `0 1 auto`
2012− _ => [
2013− ("flex-grow", "0"),
2014− ("flex-shrink", "1"),
2015− ("flex-basis", "auto"),
2016− ],
2017− };
2018− if longhands.iter().any(|&(p, _)| self.writes(p)) {
2019− for (longhand, value) in longhands {
2020− if !self.writes(longhand) {
2021− push_css(css, longhand, value);
2022− }
2023− }
2024− return;
3812+ let marker = data[i + 1];
3813+ if marker == 0xC0 || marker == 0xC2 {
3814+ let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
3815+ let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
3816+ return Some((w, h));
3817+ }
3818+ if i + 3 < data.len() {
3819+ let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
3820+ i += 2 + len;
3821+ } else {
3822+ break;
20253823 }
2026− }
2027− if !self.writes(property) {
2028− push_css(css, property, value);
20293824 }
20303825 }
2031−}
20323826
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)));
3827+ // WebP: "RIFF" ... "WEBP", VP8 header at byte 20
3828+ if data.len() >= 30 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
3829+ if &data[12..16] == b"VP8 " && data.len() >= 30 {
3830+ let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
3831+ let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
3832+ return Some((w, h));
20513833 }
2052− resets.extend_from_slice(&sizing_properties(dim));
2053− }
2054− let mut css = String::new();
2055− let mut written: Vec<&str> = Vec::new();
2056− for &(property, value) in &resets {
2057− if sets.iter().any(|&(p, _)| p == property) || written.contains(&property) {
2058− continue;
3834+ if &data[12..16] == b"VP8L" && data.len() >= 25 && data[21] == 0x2F {
3835+ let bits = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
3836+ let w = (bits & 0x3FFF) + 1;
3837+ let h = ((bits >> 14) & 0x3FFF) + 1;
3838+ return Some((w, h));
20593839 }
2060− written.push(property);
2061− sizes.push(&mut css, property, value);
2062− }
2063− for &(property, value) in &sets {
2064− sizes.push(&mut css, property, value);
20653840 }
2066− css
2067−}
2068−
2069−/// The rules an element's `fill` and `shrink` need under each chain of
2070−/// at-rules where the direction of `flow` (its parent's) changes: `(at,
2071−/// body)`.
2072−fn sizing_changes(attrs: &[Attribute], flow: &Flow) -> Vec<(Vec<usize>, String)> {
2073− flow.changes
2074− .iter()
2075− .map(|(at, axis)| (at.clone(), sizing_rule(attrs, at, *axis)))
2076− .filter(|(_, body)| !body.is_empty())
2077− .collect()
2078−}
20793841
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);
3842+ // AVIF: ISOBMFF container with "ftyp" box containing "avif"/"avis" brand,
3843+ // then "ispe" box with width/height
3844+ if data.len() >= 12 && &data[4..8] == b"ftyp" {
3845+ let brand = &data[8..12];
3846+ if brand == b"avif" || brand == b"avis" || brand == b"mif1" {
3847+ return read_avif_dimensions(&data);
20993848 }
21003849 }
2101− Some(class)
2102−}
21033850
2104−/// The `display` of a layout (nothing for text, native and void elements,
2105−/// which keep HTML's own).
2106−fn layout_css(layout: Layout, inline: bool) -> &'static str {
2107− match (layout, inline) {
2108− (Layout::Column, false) => "display:flex;flex-direction:column;",
2109− (Layout::Column, true) => "display:inline-flex;flex-direction:column;",
2110− (Layout::Row, false) => "display:flex;flex-direction:row;",
2111− (Layout::Row, true) => "display:inline-flex;flex-direction:row;",
2112− (Layout::Grid, false) => "display:grid;",
2113− (Layout::Grid, true) => "display:inline-grid;",
2114− _ => "",
2115− }
3851+ None
21163852}
21173853
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− }
2159−
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− }
2166−
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− }
2176−
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− }) =>
3854+/// Parse SVG viewBox or width/height attributes to get dimensions.
3855+fn read_svg_dimensions(text: &str) -> Option<(u32, u32)> {
3856+ // Try viewBox first: viewBox="minX minY width height"
3857+ if let Some(vb_start) = text.find("viewBox=\"") {
3858+ let rest = &text[vb_start + 9..];
3859+ if let Some(end) = rest.find('"') {
3860+ let parts: Vec<&str> = rest[..end].split_whitespace().collect();
3861+ if parts.len() == 4
3862+ && let (Ok(w), Ok(h)) = (parts[2].parse::<f64>(), parts[3].parse::<f64>())
3863+ && w > 0.0
3864+ && h > 0.0
22263865 {
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− }
2241− }
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");
2249− }
2250− "center-y" => {
2251− push_css(&mut aligned, "margin-top", "auto");
2252− push_css(&mut aligned, "margin-bottom", "auto");
2253− }
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"),
2258−
2259− "wrap" if lays_out_children => push_css(&mut css, "flex-wrap", "wrap"),
2260− "wrap" => {}
2261−
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− }
2287−
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− }
3866+ return Some((w.round() as u32, h.round() as u32));
22973867 }
2298−
2299− // Every other name is a CSS property (standard, custom,
2300− // vendor-prefixed, or one htmlang doesn't know, which the
2301− // parser warned about), written under its own name with the
2302− // value as written, except for `px` after a bare number where
2303− // the property takes a length
2304− key if crate::vocab::is_property_name(key) => {
2305− if let Some(v) = val {
2306− push_css(&mut css, key, &with_px(key, v));
2307− }
2308− }
2309−
2310− _ => {}
23113868 }
23123869 }
2313−
2314− css.push_str(&aligned);
2315− css
3870+ // Fall back to width/height attributes on <svg>
3871+ let svg_tag = text.find("<svg")?;
3872+ let tag_end = text[svg_tag..].find('>')? + svg_tag;
3873+ let tag = &text[svg_tag..tag_end];
3874+ let w = extract_svg_attr(tag, "width")?;
3875+ let h = extract_svg_attr(tag, "height")?;
3876+ Some((w, h))
23163877}
23173878
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(';');
3879+fn extract_svg_attr(tag: &str, attr: &str) -> Option<u32> {
3880+ let needle = format!("{}=\"", attr);
3881+ let start = tag.find(&needle)? + needle.len();
3882+ let rest = &tag[start..];
3883+ let end = rest.find('"')?;
3884+ let val = rest[..end].trim_end_matches("px");
3885+ val.parse::<f64>().ok().map(|v| v.round() as u32)
23233886}
23243887
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− _ => {}
3888+/// Parse AVIF (ISOBMFF) container to find ispe box with image dimensions.
3889+fn read_avif_dimensions(data: &[u8]) -> Option<(u32, u32)> {
3890+ // Walk ISOBMFF boxes looking for "ispe" (image spatial extents)
3891+ let mut i = 0;
3892+ while i + 8 <= data.len() {
3893+ let box_size =
3894+ u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as usize;
3895+ let box_type = &data[i + 4..i + 8];
3896+ if box_size < 8 {
3897+ break;
3898+ }
3899+ let box_end = (i + box_size).min(data.len());
3900+ // ispe box: 4 bytes version/flags + 4 bytes width + 4 bytes height
3901+ if box_type == b"ispe" && box_end >= i + 20 {
3902+ let w = u32::from_be_bytes([data[i + 12], data[i + 13], data[i + 14], data[i + 15]]);
3903+ let h = u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
3904+ return Some((w, h));
3905+ }
3906+ // Recurse into container boxes (meta, iprp, ipco)
3907+ if matches!(
3908+ box_type,
3909+ b"meta" | b"iprp" | b"ipco" | b"moov" | b"trak" | b"mdia"
3910+ ) {
3911+ let header_size = if box_type == b"meta" { 12 } else { 8 };
3912+ if i + header_size < box_end
3913+ && let Some(dims) = read_avif_dimensions(&data[i + header_size..box_end])
3914+ {
3915+ return Some(dims);
3916+ }
23333917 }
3918+ i = box_end;
23343919 }
2335− (id, class)
3920+ None
23363921}
23373922
23383923fn html_escape(s: &str) -> String {
@@ -2373,24 +3958,10 @@ fn base64_encode(data: &[u8]) -> String {
23733958/// Generate a standard v3 source map with VLQ-encoded mappings.
23743959/// Compatible with browser devtools and source map tooling.
23753960pub 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 {
23823961 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− }
3962+ collect_source_lines(&doc.nodes, &mut mappings);
3963+ mappings.sort_by_key(|m| m.0);
3964+ mappings.dedup_by_key(|m| m.0);
23943965
23953966 // Build VLQ-encoded mappings string.
23963967 // Each generated line is separated by ';'. Each segment within a line is
@@ -2450,30 +4021,60 @@ fn vlq_encode(value: i64, out: &mut String) {
24504021 }
24514022}
24524023
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()));
4024+fn collect_source_lines(nodes: &[Node], mappings: &mut Vec<(usize, usize)>) {
4025+ for node in nodes {
4026+ if let Node::Element(elem) = node {
4027+ if elem.line_num > 0 {
4028+ mappings.push((mappings.len() + 1, elem.line_num));
4029+ }
4030+ collect_source_lines(&elem.children, mappings);
4031+ }
4032+ }
4033+}
4034+
4035+/// Check if a specific element kind exists anywhere in the node tree.
4036+fn has_element_kind(nodes: &[Node], target: &ElementKind) -> bool {
4037+ for node in nodes {
4038+ if let Node::Element(elem) = node {
4039+ if elem.kind == *target {
4040+ return true;
4041+ }
4042+ if has_element_kind(&elem.children, target) {
4043+ return true;
4044+ }
4045+ }
4046+ }
4047+ false
4048+}
4049+
4050+/// Collect unique external domains from generated HTML for DNS prefetch hints.
4051+fn collect_dns_prefetch(html: &str, dev: bool) -> String {
4052+ let mut domains = Vec::new();
4053+ let mut rest = html;
4054+ while let Some(pos) = rest.find("https://") {
4055+ let start = pos + 8; // skip "https://"
4056+ rest = &rest[start..];
4057+ let end = rest
4058+ .find(['/', '"', '\'', ' ', '>', ')'])
4059+ .unwrap_or(rest.len());
4060+ let domain = &rest[..end];
4061+ if !domain.is_empty() && domain.contains('.') && !domains.contains(&domain.to_string()) {
4062+ domains.push(domain.to_string());
4063+ }
4064+ }
4065+ let mut out = String::new();
4066+ for domain in &domains {
4067+ if dev {
4068+ out.push_str(&format!(
4069+ "<link rel=\"dns-prefetch\" href=\"//{}\">\n",
4070+ domain
4071+ ));
4072+ } else {
4073+ out.push_str(&format!(
4074+ "<link rel=\"dns-prefetch\" href=\"//{}\">",
4075+ domain
4076+ ));
4077+ }
24784078 }
4079+ out
24794080}