@@ -1,7 +1,8 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2−use std::hash::{Hash, Hasher};
2+use std::hash::Hash;
4use crate::ast::*;
4use crate::ast::*;
5+use crate::vocab::with_px;
6// ---------------------------------------------------------------------------
7// ---------------------------------------------------------------------------
7// Style collector: deduplicates CSS and assigns class names
8// Style collector: deduplicates CSS and assigns class names
@@ -16,52 +17,315 @@ const BREAKPOINTS: &[(&str, &str)] = &[
16 ("2xl", "1536px"),
17 ("2xl", "1536px"),
19−/// Generate short CSS class names: a, b, ..., z, a0, a1, ..., z9, aa, ab, ...
20+/// The prefix of every generated class (`hl-2k9xq0m`), which keeps them
20−pub(crate) fn short_class_name(idx: usize) -> String {
21+/// out of the author's own class names.
21− if idx < 26 {
22+pub const CLASS_PREFIX: &str = "hl-";
22− return String::from((b'a' + idx as u8) as char);
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;
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);
40+ hash = (hash ^ (hash >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
41+ hash = (hash ^ (hash >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
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";
51+ let digit = DIGITS[(n % 36) as usize] as char;
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)]
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)]
74+ selector: Vec<String>,
78+ /// The condition of an attribute's key, and the name after its
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()),
89+ condition.at.sort_unstable();
90+ condition.at.dedup();
24− let mut n = idx - 26;
93+
25− let mut name = String::new();
94+ /// Only the at-rule part: a direction under `hover:` is the one without
26− // First char is always a letter
95+ /// it.
27− name.push((b'a' + (n % 26) as u8) as char);
96+ fn at_only(at: &[usize]) -> Condition {
28− n /= 26;
97+ Condition {
29− loop {
98+ at: at.to_vec(),
30− name.push((b'a' + (n % 36).min(25) as u8) as char);
99+ selector: Vec::new(),
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)
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> {
113+ .position(|p| crate::vocab::element_prefix(p).is_some())
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| {
124+ .any(|&b| crate::vocab::at_rule_implied(a, b))
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))
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>);
142+fn at_order(at: &[usize]) -> AtOrder {
145+ at.last().copied().unwrap_or(0),
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
159+type SelectorOrder = (bool, Vec<(usize, String)>, Vec<(usize, String)>);
161+fn selector_order(selector: &[String]) -> SelectorOrder {
162+ let table = crate::vocab::PSEUDOS;
163+ let ranked = |chain: &[String]| -> Vec<(usize, String)> {
167+ let name = crate::vocab::pseudo_name(p);
170+ .position(|(q, _)| *q == name)
171+ .unwrap_or(table.len());
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])),
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) {
190+ .position(|p| crate::vocab::element_prefix(p).is_some())
191+ .unwrap_or(chain.len());
193+ selector_order(&chain[..at]),
194+ chain.get(at).cloned().unwrap_or_default(),
195+ selector_order(chain.get(at + 1..).unwrap_or_default()),
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);
214+ } else if let Some(pseudo) = crate::vocab::pseudo_selector(prefix) {
215+ out.push_str(&pseudo);
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);
238+ Some((root, target))
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()
246+ .unwrap_or_default();
247+ let name = prefix.trim_end_matches(':');
248+ let width = |name: &str| {
251+ .find(|(n, _)| *n == name)
252+ .map_or("0", |(_, w)| *w)
254+ let (kind, feature, value) = if let Some(size) = name.strip_prefix("cq-") {
255+ ("@container", "min-width", width(size))
259+ return "@media print".to_string();
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)),
269+ format!("{} ({}: {})", kind, feature, value)
271+ format!("{}({}:{})", kind, feature, value)
36− // Reverse so it reads naturally
273+}
37− name.chars().rev().collect()
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
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}"));
286+ for prefix in &condition.selector {
287+ text.push_str(prefix);
291+ text.push_str(body);
294+ text.push_str(distinct);
40struct StyleEntry {
298struct StyleEntry {
41 class_name: String,
299 class_name: String,
42− base: String,
300+ /// The hash of the style, which names the class
43− /// (CSS selector suffix, css_rules) — e.g. (":hover", "color:red;")
301+ style: u64,
44− pseudo: Vec<(String, String)>,
302+ /// The defaults of the element's kind (its layout, a heading's
45− /// Responsive overrides: (breakpoint_prefix, css)
303+ /// `margin:0`, ...), less what its own attributes set. They are written
46− responsive: Vec<(String, String)>,
304+ /// as `:where(.hl-a)` in the layer `hl-kind`, so an element prefix
47− /// Dark mode overrides
305+ /// around it (`@h2:`), its parent's `children:` styles and its own
48− dark: String,
306+ /// attributes, all in later layers, win over them.
49− /// Print overrides
307+ defaults: String,
50− print: String,
308+ /// The element's rules: under each condition, its declarations, in the
51− motion_safe: String,
309+ /// order they are written
52− motion_reduce: String,
310+ rules: Vec<(Condition, String)>,
53− landscape: String,
311+ /// What else tells two elements with the same CSS apart: the rules
54− portrait: String,
312+ /// keyed on this class (see [`StyleCollector::keyed`]). Not written.
55− /// Container query overrides: (breakpoint_prefix, css)
313+ distinct: String,
56− container: Vec<(String, String)>,
59struct StyleCollector {
316struct StyleCollector {
60 entries: Vec<StyleEntry>,
317 entries: Vec<StyleEntry>,
61− /// Maps a pre-hashed style signature to an index into `entries`.
318+ /// Maps a style's hash to its entries (more than one only when two
62− /// Using u64 as the key keeps lookups allocation-free; on the rare case of
319+ /// styles hash alike, which the full comparison tells apart).
63− /// a hash collision we fall back to a full equality check against the entry.
64 index: HashMap<u64, Vec<usize>>,
320 index: HashMap<u64, Vec<usize>>,
321+ /// The names given, which a style whose name is taken doesn't get
322+ names: std::collections::HashSet<String>,
323+ /// Rules for an element's children, keyed on its class and written in
324+ /// the block of an at-rule condition: `(at-rules, selector, body)`, e.g.
325+ /// `([md], ":where(.a)>.b", "flex:1;")` (see [`Flow`]).
326+ keyed: Vec<(Vec<usize>, String, String)>,
327+ /// The keyed rules already added
328+ keyed_seen: std::collections::HashSet<(Vec<usize>, String, String)>,
67impl StyleCollector {
331impl StyleCollector {
@@ -69,328 +333,282 @@ impl StyleCollector {
69 StyleCollector {
333 StyleCollector {
70 entries: Vec::new(),
334 entries: Vec::new(),
71 index: HashMap::new(),
335 index: HashMap::new(),
336+ names: std::collections::HashSet::new(),
338+ keyed_seen: std::collections::HashSet::new(),
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);
75 /// Returns a class name for this style combination, or None if all empty.
350 /// Returns a class name for this style combination, or None if all empty.
76− #[allow(clippy::too_many_arguments)]
77 fn get_class(
351 fn get_class(
78 &mut self,
352 &mut self,
79− base: String,
353+ defaults: String,
80− pseudo: Vec<(String, String)>,
354+ mut rules: Vec<(Condition, String)>,
81− responsive: Vec<(String, String)>,
355+ distinct: String,
85− motion_reduce: String,
88− container: Vec<(String, String)>,
89 ) -> Option<String> {
356 ) -> Option<String> {
90− if base.is_empty()
357+ rules.retain(|(_, body)| !body.is_empty());
91− && pseudo.is_empty()
358+ if defaults.is_empty() && rules.is_empty() {
92− && responsive.is_empty()
95− && motion_safe.is_empty()
96− && motion_reduce.is_empty()
97− && landscape.is_empty()
98− && portrait.is_empty()
99− && container.is_empty()
101 return None;
359 return None;
103− use std::collections::hash_map::DefaultHasher;
361+ rules.sort_by_cached_key(|(condition, _)| condition.order());
104− let mut h = DefaultHasher::new();
362+ let style = stable_hash(&style_text(&defaults, &rules, &distinct));
105− base.hash(&mut h);
363+
106− pseudo.hash(&mut h);
364+ if let Some(indices) = self.index.get(&style) {
107− responsive.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();
117− if let Some(indices) = self.index.get(&sig) {
118 for &idx in indices {
365 for &idx in indices {
119 let e = &self.entries[idx];
366 let e = &self.entries[idx];
120− if e.base == base
367+ if e.defaults == defaults && e.rules == rules && e.distinct == distinct {
121− && e.pseudo == pseudo
122− && e.responsive == responsive
125− && e.motion_safe == motion_safe
126− && e.motion_reduce == motion_reduce
127− && e.landscape == landscape
128− && e.portrait == portrait
129− && e.container == container
131 return Some(e.class_name.clone());
368 return Some(e.class_name.clone());
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
135 let idx = self.entries.len();
375 let idx = self.entries.len();
136− let name = short_class_name(idx);
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());
137 self.entries.push(StyleEntry {
381 self.entries.push(StyleEntry {
138 class_name: name.clone(),
382 class_name: name.clone(),
140− pseudo,
384+ defaults,
141− responsive,
385+ rules,
150− self.index.entry(sig).or_default().push(idx);
388+ self.index.entry(style).or_default().push(idx);
151 Some(name)
389 Some(name)
154− fn to_css_formatted(&self, dev: bool, use_layer: bool) -> String {
392+ /// The classes given, in the order they were
155− let mut css = String::new();
393+ fn classes(&self) -> impl Iterator<Item = Class> + '_ {
156− let inner_indent = if use_layer && dev { " " } else { "" };
394+ self.entries.iter().map(|e| Class {
395+ name: e.class_name.clone(),
158− // Wrap in @layer for specificity management
400+ /// All generated rules, in three layers (see [`LAYERS`]): the element
159− if use_layer {
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])),
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(","));
161− css.push_str("@layer htmlang {\n");
424+ kind.push_str(&format!(" {} {{{}}}\n", selector, body));
163− css.push_str("@layer htmlang{");
426+ kind.push_str(&format!("{}{{{}}}", selector, body));
167− // Non-responsive rules. Base and pseudo rules are merged separately by
430+ let mut inside = self.blocks(true, dev);
168− // identical body so that e.g. `.a,.b{display:flex;flex-direction:column;}`
431+ // A function's scoped `@style`, nested under its class
169− // replaces two identical rules. Pseudo variants are grouped per selector
432+ for block in scoped {
170− // suffix (`:hover` with `:hover`, etc.) to keep each pseudo's cascade
433+ if dev {
171− // position independent of others.
434+ inside.push_str(block);
172− let mut base_pairs: Vec<(&str, &str)> = Vec::with_capacity(self.entries.len());
435+ inside.push('\n');
173− for e in &self.entries {
436+ } else {
174− if !e.base.is_empty() {
437+ inside.push_str(&compact_css(block));
175− base_pairs.push((e.class_name.as_str(), e.base.as_str()));
178− emit_grouped_rules(&mut css, &base_pairs, "", inner_indent, dev);
440+
179−
441+ let mut css = String::new();
180− // Collect pseudo rules grouped by selector suffix, preserving the order
442+ for (name, rules) in [
181− // in which suffixes first appear across entries.
443+ ("hl-kind", kind),
182− let mut pseudo_order: Vec<&str> = Vec::new();
444+ ("hl-inside", inside),
183− let mut pseudo_buckets: HashMap<&str, Vec<(&str, &str)>> = HashMap::new();
445+ ("htmlang", self.blocks(false, dev)),
184− for e in &self.entries {
446+ ] {
185− for (selector, body) in &e.pseudo {
447+ if rules.is_empty() {
186− if body.is_empty() {
448+ continue;
189− let key = selector.as_str();
190− if !pseudo_buckets.contains_key(key) {
191− pseudo_order.push(key);
196− .push((e.class_name.as_str(), body.as_str()));
199− for selector in &pseudo_order {
451+ css.push_str(&format!("@layer {} {{\n{}}}\n", name, rules));
200− if let Some(pairs) = pseudo_buckets.get(selector) {
452+ } else {
201− emit_grouped_rules(&mut css, pairs, selector, inner_indent, dev);
453+ css.push_str(&format!("@layer {}{{{}}}", name, rules));
205− // Responsive rules grouped by breakpoint
459+ /// The rules of every block of at-rules, in order: those for the
206− for &(bp_name, bp_width) in BREAKPOINTS {
460+ /// elements inside (`inside`: rules under an element prefix, each in
207− let mut bp_pairs: Vec<(&str, &str)> = Vec::new();
461+ /// an `@scope` on its element's class), or the elements' own.
208− for e in &self.entries {
462+ fn blocks(&self, inside: bool, dev: bool) -> String {
209− for (bp, rule_css) in &e.responsive {
463+ let mut css = String::new();
210− if bp == bp_name && !rule_css.is_empty() {
464+ let rules = || {
211− bp_pairs.push((e.class_name.as_str(), rule_css.as_str()));
465+ self.entries.iter().flat_map(move |e| {
468+ .filter(move |(c, _)| c.inside().is_some() == inside)
469+ .map(move |(c, body)| (e, c, body))
472+ let mut blocks: Vec<&[usize]> = vec![&[]];
473+ let keyed = self.keyed.iter().filter(|_| !inside);
475+ .map(|(_, c, _)| c.at.as_slice())
476+ .chain(keyed.map(|(at, _, _)| at.as_slice()));
478+ if !blocks.contains(&at) {
482+ blocks.sort_by_key(|at| at_order(at));
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))
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
498+ let keyed: Vec<(&str, &str)> = self
501+ .filter(|(a, _, _)| a.as_slice() == at)
502+ .map(|(_, selector, body)| (selector.as_str(), body.as_str()))
504+ emit_selector_rules(&mut inner, &keyed, &indent, dev);
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);
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
519+ let mut scopes: Vec<(String, Vec<(String, &str)>)> = Vec::new();
520+ for chain in chains {
521+ let Some(element) = chain
523+ .position(|p| crate::vocab::element_prefix(p).is_some())
528+ rules().filter(|(_, c, _)| c.at == at && c.selector == chain)
530+ let Some((root, target)) = scoped_selector(&e.class_name, chain, element)
534+ match scopes.iter_mut().find(|(r, _)| *r == root) {
535+ Some((_, targets)) => targets.push((target, body)),
536+ None => scopes.push((root, vec![(target, body)])),
214− }
540+ let inner_indent = if dev {
215− emit_media_block(
541+ format!("{} ", indent)
216− &mut css,
542+ } else {
217− &format!("@media (min-width: {})", bp_width),
543+ String::new()
218− &format!("@media(min-width:{})", bp_width),
544+ };
219− &bp_pairs,
545+ for (root, targets) in scopes {
220− "",
546+ let targets: Vec<(&str, &str)> =
221− dev,
547+ targets.iter().map(|(t, b)| (t.as_str(), *b)).collect();
222− );
548+ inner.push_str(&indent);
223− }
549+ inner.push_str(&format!("@scope ({})", root));
224−
550+ inner.push_str(if dev { " {\n" } else { "{" });
225− // Dark mode rules
551+ emit_selector_rules(&mut inner, &targets, &inner_indent, dev);
226− let dark_pairs: Vec<(&str, &str)> = self
552+ inner.push_str(&indent);
227− .entries
553+ inner.push_str(if dev { "}\n" } else { "}" });
229− .filter(|e| !e.dark.is_empty())
230− .map(|e| (e.class_name.as_str(), e.dark.as_str()))
234− "@media (prefers-color-scheme: dark)",
235− "@media(prefers-color-scheme:dark)",
242− let print_pairs: Vec<(&str, &str)> = self
245− .filter(|e| !e.print.is_empty())
246− .map(|e| (e.class_name.as_str(), e.print.as_str()))
257− // Motion safe rules
258− let motion_safe_pairs: Vec<(&str, &str)> = self
261− .filter(|e| !e.motion_safe.is_empty())
262− .map(|e| (e.class_name.as_str(), e.motion_safe.as_str()))
266− "@media (prefers-reduced-motion: no-preference)",
267− "@media(prefers-reduced-motion:no-preference)",
273− // Motion reduce rules
274− let motion_reduce_pairs: Vec<(&str, &str)> = self
277− .filter(|e| !e.motion_reduce.is_empty())
278− .map(|e| (e.class_name.as_str(), e.motion_reduce.as_str()))
282− "@media (prefers-reduced-motion: reduce)",
283− "@media(prefers-reduced-motion:reduce)",
284− &motion_reduce_pairs,
290− let landscape_pairs: Vec<(&str, &str)> = self
293− .filter(|e| !e.landscape.is_empty())
294− .map(|e| (e.class_name.as_str(), e.landscape.as_str()))
298− "@media (orientation: landscape)",
299− "@media(orientation:landscape)",
306− let portrait_pairs: Vec<(&str, &str)> = self
309− .filter(|e| !e.portrait.is_empty())
310− .map(|e| (e.class_name.as_str(), e.portrait.as_str()))
314− "@media (orientation: portrait)",
315− "@media(orientation:portrait)",
321− // Container query rules grouped by breakpoint
322− for &(bp_name, bp_width) in BREAKPOINTS {
323− let mut cq_pairs: Vec<(&str, &str)> = Vec::new();
324− for e in &self.entries {
325− for (bp, rule_css) in &e.container {
326− if bp == bp_name && !rule_css.is_empty() {
327− cq_pairs.push((e.class_name.as_str(), rule_css.as_str()));
333− &format!("@container (min-width: {})", bp_width),
334− &format!("@container(min-width:{})", bp_width),
344− css.push_str("}\n");
346− css.push('}');
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()))
562+ emit_grouped_rules(&mut inner, &pairs, &indent, dev);
565+ if inner.is_empty() {
568+ // Each at-rule wraps the next, outermost first
569+ for (level, &rank) in at.iter().enumerate().rev() {
576+ format!("{pad}{} {{\n{inner}{pad}}}\n", at_rule(rank, true))
578+ format!("{}{{{inner}}}", at_rule(rank, false))
581+ css.push_str(&inner);
354−/// Emit CSS rules from `(class_name, body)` pairs, merging identical bodies
587+/// Emit CSS rules from `(selector, body)` pairs, merging identical bodies
355/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
588/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
356/// of each distinct body determines ordering, so output stays deterministic
589/// of each distinct body determines ordering, so output stays deterministic
357−/// across runs. `selector_suffix` is appended to each class (e.g. `":hover"`,
590+/// across runs. `indent` is prepended to each rule line.
358−/// or `""` for plain class rules). `indent` is prepended to each rule line.
591+fn emit_grouped_rules(out: &mut String, pairs: &[(String, &str)], indent: &str, dev: bool) {
359−fn emit_grouped_rules(
361− pairs: &[(&str, &str)],
362− selector_suffix: &str,
366 if pairs.is_empty() {
592 if pairs.is_empty() {
369 // Group in first-occurrence order.
595 // Group in first-occurrence order.
370 let mut order: Vec<&str> = Vec::new();
596 let mut order: Vec<&str> = Vec::new();
371 let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
597 let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
372− for &(name, body) in pairs {
598+ for (selector, body) in pairs {
373 if body.is_empty() {
599 if body.is_empty() {
374 continue;
600 continue;
376 if !groups.contains_key(body) {
602 if !groups.contains_key(body) {
377 order.push(body);
603 order.push(body);
379− groups.entry(body).or_default().push(name);
605+ groups.entry(body).or_default().push(selector);
381 let sp = if dev { " " } else { "" };
607 let sp = if dev { " " } else { "" };
382 let nl = if dev { "\n" } else { "" };
608 let nl = if dev { "\n" } else { "" };
383 for body in &order {
609 for body in &order {
384− let names = &groups[body];
385 out.push_str(indent);
610 out.push_str(indent);
386− for (i, n) in names.iter().enumerate() {
611+ out.push_str(&groups[body].join(","));
392− out.push_str(selector_suffix);
394 out.push_str(sp);
612 out.push_str(sp);
395 out.push('{');
613 out.push('{');
396 out.push_str(body);
614 out.push_str(body);
@@ -399,38 +617,44 @@ fn emit_grouped_rules(
402−/// Emit an `@media` / `@container` block containing grouped class rules.
620+/// Emit `(selector, body)` rules in their order, merging a run of rules
403−/// Skips the block entirely if no non-empty bodies are present.
621+/// with the same body into one rule with a selector list (the order
404−fn emit_media_block(
622+/// matters: two rules may apply to one element).
405− out: &mut String,
623+fn emit_selector_rules(out: &mut String, rules: &[(&str, &str)], indent: &str, dev: bool) {
406− header_dev: &str,
624+ let mut i = 0;
407− header_min: &str,
625+ while i < rules.len() {
408− pairs: &[(&str, &str)],
626+ let body = rules[i].1;
409− selector_suffix: &str,
627+ let run = rules[i..].iter().take_while(|(_, b)| *b == body).count();
410− dev: bool,
628+ if !body.is_empty() {
411−) {
629+ let selectors: Vec<&str> = rules[i..i + run].iter().map(|(s, _)| *s).collect();
412− if pairs.iter().all(|(_, body)| body.is_empty()) {
630+ out.push_str(indent);
413− return;
631+ out.push_str(&selectors.join(","));
415− let mut inner = String::new();
633+ out.push(' ');
416− let inner_indent = if dev { " " } else { "" };
634+ }
417− emit_grouped_rules(&mut inner, pairs, selector_suffix, inner_indent, dev);
635+ out.push('{');
418− if inner.is_empty() {
636+ out.push_str(body);
419− return;
637+ out.push('}');
421− if dev {
639+ out.push('\n');
422− out.push_str(&format!("{} {{\n{}}}\n", header_dev, inner));
640+ }
424− out.push_str(&format!("{}{{{}}}", header_min, inner));
642+ i += run;
428struct GenContext {
646struct GenContext {
429 dev: bool,
647 dev: bool,
430 depth: usize,
648 depth: usize,
432 has_interactive: bool,
649 has_interactive: bool,
433− has_defer: bool,
650+ /// Writing inside a text element, at any depth: htmlang's own `<div>`s
651+ /// are `<span>`s there, which text can hold.
653+ /// How the element whose children are being written lays them out
655+ /// Writing the children of a `@picture`, where `@source`'s leading
656+ /// argument is its `srcset`
436impl GenContext {
660impl GenContext {
@@ -456,23 +680,26 @@ pub struct CodegenOptions {
456 pub dev: bool,
680 pub dev: bool,
457 pub partial: bool,
681 pub partial: bool,
458 pub minify: bool,
682 pub minify: bool,
462/// Generate HTML from a parsed document using the given options.
685/// Generate HTML from a parsed document using the given options.
463pub fn generate_with(doc: &Document, opts: &CodegenOptions) -> String {
686pub fn generate_with(doc: &Document, opts: &CodegenOptions) -> String {
687+ generate_with_classes(doc, opts).0
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();
464 let mut html = if opts.partial {
694 let mut html = if opts.partial {
465− generate_partial_inner(doc, opts.dev)
695+ generate_partial_inner(doc, opts.dev, &mut classes)
467− generate_full_inner(doc, opts.dev)
697+ generate_full_inner(doc, opts.dev, &mut classes)
469 if opts.minify {
699 if opts.minify {
470 html = minify_html(&html);
700 html = minify_html(&html);
472− if opts.compat {
702+ (html, classes)
473− html = add_vendor_prefixes(&html);
478pub fn generate(doc: &Document) -> String {
705pub fn generate(doc: &Document) -> String {
@@ -520,38 +747,6 @@ pub fn generate_minified(doc: &Document) -> String {
523−pub fn generate_compat(doc: &Document) -> String {
528− ..Default::default()
533−pub fn generate_dev_compat(doc: &Document) -> String {
539− ..Default::default()
544−pub fn generate_minified_compat(doc: &Document) -> String {
550− ..Default::default()
555fn minify_html(html: &str) -> String {
750fn minify_html(html: &str) -> String {
556 let mut result = String::with_capacity(html.len());
751 let mut result = String::with_capacity(html.len());
557 let mut in_pre = false;
752 let mut in_pre = false;
@@ -566,9 +761,9 @@ fn minify_html(html: &str) -> String {
566 if i + 4 < chars.len() && chars[i] == '<' {
761 if i + 4 < chars.len() && chars[i] == '<' {
567 let rest: String = chars[i..].iter().take(10).collect();
762 let rest: String = chars[i..].iter().take(10).collect();
568 let rest_lower = rest.to_lowercase();
763 let rest_lower = rest.to_lowercase();
569− if rest_lower.starts_with("<pre") {
764+ if rest_lower.starts_with("<pre") || rest_lower.starts_with("<textarea") {
570 in_pre = true;
765 in_pre = true;
571− } else if rest_lower.starts_with("</pre") {
766+ } else if rest_lower.starts_with("</pre") || rest_lower.starts_with("</textarea") {
572 in_pre = false;
767 in_pre = false;
573 } else if rest_lower.starts_with("<script") {
768 } else if rest_lower.starts_with("<script") {
574 in_script = true;
769 in_script = true;
@@ -610,10 +805,11 @@ fn minify_html(html: &str) -> String {
610 continue;
805 continue;
613− // Collapse whitespace between tags
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).
614 if chars[i].is_whitespace() {
811 if chars[i].is_whitespace() {
615 if !prev_was_space {
812 if !prev_was_space {
616− // Only emit a space if we're between content (not between tags)
617 result.push(' ');
813 result.push(' ');
618 prev_was_space = true;
814 prev_was_space = true;
@@ -621,14 +817,6 @@ fn minify_html(html: &str) -> String {
621 continue;
817 continue;
624− // Trim space before closing tags
625− if chars[i] == '<' && prev_was_space {
626− // Remove trailing space before tag
627− if result.ends_with(' ') {
632 prev_was_space = false;
820 prev_was_space = false;
633 result.push(chars[i]);
821 result.push(chars[i]);
@@ -637,177 +825,152 @@ fn minify_html(html: &str) -> String {
640−/// Add vendor prefixes to CSS within <style> tags for broader browser compatibility.
828+fn generate_full_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
641−fn add_vendor_prefixes(html: &str) -> String {
829+ // Without `@page` the output is a fragment
642− // Find CSS within <style>...</style> and add vendor prefixes
830+ let Some(page) = &doc.page else {
643− let mut result = String::with_capacity(html.len() + 512);
831+ return generate_partial_inner(doc, dev, classes);
644− let mut rest = html;
832+ };
645− while let Some(start) = rest.find("<style>") {
646− let after_tag = start + 7;
647− result.push_str(&rest[..after_tag]);
648− rest = &rest[after_tag..];
649− if let Some(end) = rest.find("</style>") {
650− let css = &rest[..end];
651− result.push_str(&prefix_css(css));
652− result.push_str("</style>");
653− rest = &rest[end + 8..];
658− result.push_str(rest);
662−fn prefix_css(css: &str) -> String {
663− let mut out = String::with_capacity(css.len() + 256);
665− let bytes = css.as_bytes();
666− while i < bytes.len() {
667− // Find property declarations
668− if let Some(pos) = css[i..].find('{') {
669− let brace = i + pos;
670− out.push_str(&css[i..=brace]);
672− // Process declarations within this block
673− if let Some(close) = css[i..].find('}') {
674− let block = &css[i..i + close];
675− out.push_str(&prefix_declarations(block));
680− out.push_str(&css[i..]);
687−fn prefix_declarations(block: &str) -> String {
688− let mut out = String::with_capacity(block.len() + 128);
689− for decl in block.split(';') {
690− let decl = decl.trim();
691− if decl.is_empty() {
694− if let Some((prop, val)) = decl.split_once(':') {
695− let prop = prop.trim();
696− let val = val.trim();
698− "backdrop-filter" => {
699− out.push_str(&format!("-webkit-backdrop-filter:{};", val));
700− out.push_str(&format!("backdrop-filter:{};", val));
703− out.push_str(&format!("-webkit-user-select:{};", val));
704− out.push_str(&format!("-moz-user-select:{};", val));
705− out.push_str(&format!("user-select:{};", val));
708− out.push_str(&format!("-webkit-appearance:{};", val));
709− out.push_str(&format!("-moz-appearance:{};", val));
710− out.push_str(&format!("appearance:{};", val));
712− "background-clip" if val.contains("text") => {
713− out.push_str(&format!("-webkit-background-clip:{};", val));
714− out.push_str(&format!("background-clip:{};", val));
717− out.push_str(&format!("-webkit-hyphens:{};", val));
718− out.push_str(&format!("-ms-hyphens:{};", val));
719− out.push_str(&format!("hyphens:{};", val));
721− "text-size-adjust" => {
722− out.push_str(&format!("-webkit-text-size-adjust:{};", val));
723− out.push_str(&format!("-ms-text-size-adjust:{};", val));
724− out.push_str(&format!("text-size-adjust:{};", val));
726− "mask-image" | "mask-size" | "mask-repeat" | "mask-position" => {
727− out.push_str(&format!("-webkit-{}:{};", prop, val));
728− out.push_str(&format!("{}:{};", prop, val));
743−fn generate_full_inner(doc: &Document, dev: bool) -> String {
744 let mut styles = StyleCollector::new();
833 let mut styles = StyleCollector::new();
745 let mut ctx = GenContext {
834 let mut ctx = GenContext {
747 depth: 0,
836 depth: 0,
749 has_interactive: false,
837 has_interactive: false,
750− has_defer: false,
838+ in_text: false,
839+ flow: Flow::default(),
753− // Check if document has @main for skip-to-content link
843+ // The page is the root element: `<body>` is a column (the reset makes
754− let has_main = has_element_kind(&doc.nodes, &ElementKind::Main);
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(),
850+ children: Vec::new(),
854+ let mut own = Flow::of(&root);
855+ let top = Flow::default();
859+ has_overlay_children: holds_overlays(&doc.nodes),
863+ let body_class = element_class(&root, &site, &mut styles);
864+ own.class = body_class.clone();
756 let mut body = String::new();
867 let mut body = String::new();
870+ Some(Layout::Column),
758− // Skip-to-content link for accessibility (only when @main exists)
876+ let element_css = build_element_css(doc, &styles, dev);
759− if has_main {
877+ let nl = if dev { "\n" } else { "" };
761− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>\n");
879+ let mut meta_html = String::new();
762− } else {
880+ // A `@meta viewport` of the page's own replaces the usual one
763− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>");
881+ if !doc.meta_tags.iter().any(|(name, _)| name == "viewport") {
764− }
882+ meta_html.push_str(&format!(
883+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">{}",
887+ meta_html.push_str(&format!(
888+ "<title>{}</title>{}",
889+ html_escape(&page.title),
892+ for (name, content) in &doc.meta_tags {
893+ meta_html.push_str(&format!(
894+ "<meta name=\"{}\" content=\"{}\">{}",
896+ html_escape(content),
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),
908+ if let Some(path) = &page.favicon {
909+ meta_html.push_str(&format!(
910+ "<link rel=\"icon\" href=\"{}\">{}",
915+ for block in &doc.head_blocks {
916+ meta_html.push_str(block);
917+ meta_html.push_str(nl);
767− for node in &doc.nodes {
920+ // `@page`'s HTML attributes go on `<html>`
768− generate_node(node, None, &mut body, &mut styles, &mut ctx);
921+ let mut root_attrs = String::new();
922+ for attr in html_attrs(&page.html_attrs) {
923+ push_html_attr(&mut root_attrs, attr);
925+ let mut body_attrs = String::new();
926+ emit_class_attr(&mut body_attrs, body_class.as_deref(), None);
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";
933+ "{}{} {{ outline: 2px solid currentColor; outline-offset: 2px; }}\n",
934+ OWN_ELEMENTS, focusable
938+ "{}{}{{outline:2px solid currentColor;outline-offset:2px}}",
939+ OWN_ELEMENTS, focusable
945+ let reset_css = reset_css(dev, true, &focus_visible_css);
946+ classes.extend(styles.classes());
771− // Collect external domains for DNS prefetch
948+ format!(
772− let dns_prefetch_html = collect_dns_prefetch(&body, dev);
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}",
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 {
774 let mut element_css = String::new();
959 let mut element_css = String::new();
776− // Collect all CSS custom properties (explicit `@let --name` / `@theme`
961+ // Collect the CSS custom properties declared with `@let --name` so they
777− // tokens, plus any auto-extracted repeats) so they can be emitted in a
962+ // can be emitted in a single `:root` block below.
778− // single `:root` block below.
779 let mut root_vars: Vec<(String, String)> = Vec::new();
963 let mut root_vars: Vec<(String, String)> = Vec::new();
780 for (name, value) in &doc.css_vars {
964 for (name, value) in &doc.css_vars {
781 root_vars.push((name.clone(), value.clone()));
965 root_vars.push((name.clone(), value.clone()));
783− for (name, value) in &doc.theme_tokens {
784− let css_name = format!("--{}", name);
785− if !root_vars.iter().any(|(n, _)| *n == css_name) {
786− root_vars.push((css_name, value.clone()));
790− let has_custom_css = !doc.custom_css.is_empty();
968+ // Generated rules always go in htmlang's layers, so unlayered user CSS
791− let styles_css = styles.to_css_formatted(dev, !has_custom_css);
969+ // (`@style`, `@raw`) overrides them regardless of specificity.
792− // Fold literal values declared via `@theme` / `@let --name` back into
970+ let styles_css = styles.to_css_formatted(dev, &doc.scoped_css);
793− // `var(--name)` references so the generated CSS actually uses the
794− // custom properties emitted in `:root`. Saves bytes and makes runtime
795− // theming take effect.
796− let styles_css = substitute_css_vars(&styles_css, &root_vars);
797− // Further compress the CSS by auto-extracting any remaining literal
798− // values that appear often enough for `var(--hN)` references to come out
799− // shorter overall. Disabled in dev mode to keep the generated CSS
801− let styles_css = if dev {
804− let (new_css, auto_vars) = auto_extract_repeats(&styles_css, &root_vars);
805− root_vars.extend(auto_vars);
809− // Emit the (possibly extended) :root block first so the cascade picks up
972+ // Emit the :root block first so the cascade picks up the custom
810− // the custom properties before the class rules consume them.
973+ // properties before the class rules consume them.
811 if !root_vars.is_empty() {
974 if !root_vars.is_empty() {
813 element_css.push_str(":root {\n");
976 element_css.push_str(":root {\n");
@@ -829,538 +992,121 @@ fn generate_full_inner(doc: &Document, dev: bool) -> String {
830 element_css.push_str(&styles_css);
993 element_css.push_str(&styles_css);
833− for (name, kf_body) in &doc.keyframes {
835− element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
837− element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
841− // Auto-inject skeleton keyframe if skeleton attribute is used
842− let skeleton_used = element_css.contains("hl-skeleton");
845− element_css.push_str("@keyframes hl-skeleton {\n 0% { background-position: 200% 0; }\n 100% { background-position: -200% 0; }\n}\n");
847− element_css.push_str("@keyframes hl-skeleton{0%{background-position:200% 0}100%{background-position:-200% 0}}");
851− // Also inject carousel webkit scrollbar hiding
852− let carousel_used = element_css.contains("scroll-snap-type:x mandatory");
853− if carousel_used && !element_css.contains("::-webkit-scrollbar") {
854− // The carousel class already has scrollbar-width:none, but webkit needs pseudo-element
855− // We add a global rule for carousel-style elements
858 // @style blocks (custom CSS)
995 // @style blocks (custom CSS)
859 for block in &doc.custom_css {
996 for block in &doc.custom_css {
861 element_css.push_str(block);
998 element_css.push_str(block);
862 element_css.push('\n');
999 element_css.push('\n');
863 } else {
1000 } else {
864− // Minify: collapse whitespace
1001+ element_css.push_str(&compact_css(block));
865− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
866− element_css.push_str(&minified);
870− // @scope blocks
1005+ element_css
871− for block in &doc.scope_blocks {
1006+}
873− element_css.push_str(block);
874− element_css.push('\n');
876− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
877− element_css.push_str(&minified);
881− // @starting-style blocks
1008+/// An `@style` body on one line: each line trimmed, and the lines joined with
882− if !doc.starting_style_blocks.is_empty() {
1009+/// a space, so a value that goes on over two lines (`margin: 0` then `auto;`)
883− if dev {
1010+/// keeps its words apart.
884− element_css.push_str("@starting-style {\n");
1011+fn compact_css(block: &str) -> String {
885− for block in &doc.starting_style_blocks {
1012+ block
886− element_css.push_str(block);
1013+ .lines()
887− element_css.push('\n');
1014+ .map(str::trim)
888− }
1015+ .filter(|l| !l.is_empty())
889− element_css.push_str("}\n");
1016+ .collect::<Vec<_>>()
890− } else {
1017+ .join(" ")
891− element_css.push_str("@starting-style{");
1018+}
892− for block in &doc.starting_style_blocks {
893− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
894− element_css.push_str(&minified);
896− element_css.push('}');
900− // Build meta tags string
901− let meta_html = if doc.meta_tags.is_empty() {
904− let mut m = String::new();
905− for (name, content) in &doc.meta_tags {
907− m.push_str(&format!(
908− "<meta name=\"{}\" content=\"{}\">\n",
910− html_escape(content)
913− m.push_str(&format!(
914− "<meta name=\"{}\" content=\"{}\">",
916− html_escape(content)
923− // Build OG meta tags
924− let og_html = if doc.og_tags.is_empty() {
927− let mut o = String::new();
928− for (property, content) in &doc.og_tags {
930− o.push_str(&format!(
931− "<meta property=\"og:{}\" content=\"{}\">\n",
932− html_escape(property),
933− html_escape(content)
936− o.push_str(&format!(
937− "<meta property=\"og:{}\" content=\"{}\">",
938− html_escape(property),
939− html_escape(content)
946− // Build head blocks string
947− let head_html = if doc.head_blocks.is_empty() {
950− let mut h = String::new();
951− for block in &doc.head_blocks {
960− let lang_attr = match &doc.lang {
961− Some(lang) => format!(" lang=\"{}\"", html_escape(lang)),
962− None => String::new(),
965− let favicon_html = match &doc.favicon {
967− // Try to read and inline the favicon
968− if let Ok(data) = std::fs::read(path) {
969− let mime = if path.ends_with(".ico") {
971− } else if path.ends_with(".png") {
973− } else if path.ends_with(".svg") {
978− let b64 = base64_encode(&data);
981− "<link rel=\"icon\" href=\"data:{};base64,{}\">\n",
985− format!("<link rel=\"icon\" href=\"data:{};base64,{}\">", mime, b64)
988− // Fall back to href
990− format!("<link rel=\"icon\" href=\"{}\">\n", html_escape(path))
992− format!("<link rel=\"icon\" href=\"{}\">", html_escape(path))
996− None => String::new(),
1000− let canonical_html = match &doc.canonical {
1003− format!("<link rel=\"canonical\" href=\"{}\">\n", html_escape(url))
1005− format!("<link rel=\"canonical\" href=\"{}\">", html_escape(url))
1008− None => String::new(),
1012− let base_html = match &doc.base_url {
1015− format!("<base href=\"{}\">\n", html_escape(url))
1017− format!("<base href=\"{}\">", html_escape(url))
1020− None => String::new(),
1023− // @font-face CSS
1020+/// htmlang's own elements: those with a generated class, or the class of a
1024− for (name, url) in &doc.font_faces {
1021+/// function's scoped `@style`. The reset's rules for elements are kept to
1025− let format_hint = if url.ends_with(".woff2") {
1022+/// them, so `@raw` and `@markdown` content, and the page a fragment is put
1026− " format('woff2')"
1023+/// into, keep their own.
1027− } else if url.ends_with(".woff") {
1024+const OWN_ELEMENTS: &str = ":where([class^=\"hl-\"],[class*=\" hl-\"])";
1028− " format('woff')"
1025+
1029− } else if url.ends_with(".ttf") {
1026+/// htmlang's cascade layers, from the one that loses to the one that wins:
1030− " format('truetype')"
1027+/// the reset; the defaults of each element's kind (a heading's `margin:0`,
1031− } else if url.ends_with(".otf") {
1028+/// a column's `display:flex`); the styles an element gets from an
1032− " format('opentype')"
1029+/// element prefix on an element around it (`@td:padding 8`) and from a
1033− } else {
1030+/// function's scoped `@style`; and the element's own styles. So a
1034− ""
1031+/// scope's styles win over the defaults, and what an element says about
1035− };
1032+/// itself wins over both. CSS outside any layer (`@style`, `@raw`) wins
1036− if dev {
1033+/// over all of them.
1037− element_css.insert_str(0, &format!(
1034+const LAYERS: [&str; 4] = ["hl-reset", "hl-kind", "hl-inside", "htmlang"];
1038− "@font-face {{\n font-family: '{}';\n src: url('{}'){};\n font-display: swap;\n}}\n",
1035+
1039− name, url, format_hint
1036+/// Built-in reset rules, in a layer before `htmlang`: unlayered CSS beats
1040− ));
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();
1048+ rules.push(if dev {
1049+ "*, *::before, *::after { box-sizing: border-box; }".to_string()
1041 } else {
1050 } else {
1042− element_css.insert_str(
1051+ "*,*::before,*::after{box-sizing:border-box}".to_string()
1044− &format!(
1053+ rules.push(if dev {
1045− "@font-face{{font-family:'{}';src:url('{}'){};font-display:swap}}",
1054+ "body { margin: 0; font-family: system-ui, -apple-system, sans-serif; display: flex; flex-direction: column; min-height: 100dvh; }".to_string()
1046− name, url, format_hint
1053− let json_ld_html: String = doc
1059− "<script type=\"application/ld+json\">\n{}\n</script>\n",
1063− format!("<script type=\"application/ld+json\">{}</script>", block)
1069− let manifest_html = if let Some(ref manifest) = doc.manifest {
1070− let mut json = String::from("{");
1071− json.push_str(&format!("\"name\":\"{}\",", manifest.name));
1072− if let Some(ref short) = manifest.short_name {
1073− json.push_str(&format!("\"short_name\":\"{}\",", short));
1075− json.push_str(&format!("\"start_url\":\"{}\",", manifest.start_url));
1076− json.push_str(&format!("\"display\":\"{}\"", manifest.display));
1077− if let Some(ref bg) = manifest.background_color {
1078− json.push_str(&format!(",\"background_color\":\"{}\"", bg));
1080− if let Some(ref tc) = manifest.theme_color {
1081− json.push_str(&format!(",\"theme_color\":\"{}\"", tc));
1083− if let Some(ref desc) = manifest.description {
1084− json.push_str(&format!(",\"description\":\"{}\"", desc));
1086− if !manifest.icons.is_empty() {
1087− json.push_str(",\"icons\":[");
1088− for (i, (src, sizes)) in manifest.icons.iter().enumerate() {
1092− json.push_str(&format!(
1093− "{{\"src\":\"{}\",\"sizes\":\"{}\",\"type\":\"image/png\"}}",
1101− // Inline the manifest as a data URI
1102− let encoded = base64_encode(json.as_bytes());
1105− "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">\n",
1108 } else {
1055 } else {
1109− format!(
1056+ "body{margin:0;font-family:system-ui,-apple-system,sans-serif;display:flex;flex-direction:column;min-height:100dvh}".to_string()
1110− "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">",
1057+ });
1114 } else {
1058 } else {
1115− String::new()
1059+ rules.push(if dev {
1116− };
1060+ format!("{own}, {own}::before, {own}::after {{ box-sizing: border-box; }}")
1118− // Preload hints (auto-detect fonts from @font-face)
1119− let mut preload_html = String::new();
1120− for (_, url) in &doc.font_faces {
1122− preload_html.push_str(&format!(
1123− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>\n",
1126 } else {
1061 } else {
1127− preload_html.push_str(&format!(
1062+ format!("{own},{own}::before,{own}::after{{box-sizing:border-box}}")
1128− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>",
1063+ });
1133− // Explicit preload hints from the document
1134− for hint in &doc.preload_hints {
1136− preload_html.push_str(&format!(
1137− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>\n",
1138− html_escape(&hint.href),
1140− if hint.crossorigin { " crossorigin" } else { "" }
1143− preload_html.push_str(&format!(
1144− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>",
1145− html_escape(&hint.href),
1147− if hint.crossorigin { " crossorigin" } else { "" }
1151−
1065+ let hidden = "[hidden]:not([hidden=\"until-found\"]),dialog:not([open]):not(:popover-open),\
1152− // Auto theme-color meta from @theme primary token
1066+ [popover]:not(:popover-open):not(dialog[open])";
1153− let theme_color_html = doc
1067+ rules.push(if dev {
1154− .theme_tokens
1068+ format!("{own}:where({hidden}) {{ display: none !important; }}")
1156− .find(|(name, _)| name == "primary" || name == "theme-color")
1157− .map(|(_, value)| {
1160− "<meta name=\"theme-color\" content=\"{}\">\n",
1165− "<meta name=\"theme-color\" content=\"{}\">",
1170− .unwrap_or_default();
1172− // Focus-visible CSS for interactive elements (accessibility)
1173− let focus_visible_css = if ctx.has_interactive {
1175− "a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }\n"
1177− "a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid currentColor;outline-offset:2px}"
1183− // Skip-to-content CSS (visually hidden but accessible)
1184− let skip_link_css = if has_main {
1186− ".hl-skip { position: absolute; left: -9999px; top: auto; width: 1px; height: 1px; overflow: hidden; z-index: 9999; padding: 8px 16px; background: #000; color: #fff; text-decoration: none; font-size: 14px; }\n.hl-skip:focus { left: 8px; top: 8px; width: auto; height: auto; overflow: visible; }\n"
1188− ".hl-skip{position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden;z-index:9999;padding:8px 16px;background:#000;color:#fff;text-decoration:none;font-size:14px}.hl-skip:focus{left:8px;top:8px;width:auto;height:auto;overflow:visible}"
1190 } else {
1069 } else {
1191− ""
1070+ format!("{own}:where({hidden}){{display:none!important}}")
1193−
1072+ let mut rules = rules.join(if dev { "\n" } else { "" });
1194− // Noscript fallback: show deferred content if JS is disabled
1073+ if dev {
1195− let noscript_html = if ctx.has_defer {
1074+ rules.push('\n');
1197− "<noscript><style>.hl-defer-placeholder { display: none; }</style></noscript>\n"
1076+ rules.push_str(focus_visible_css);
1198− } else {
1077+ if dev {
1199− "<noscript><style>.hl-defer-placeholder{display:none}</style></noscript>"
1078+ format!(
1200− }
1079+ "@layer {};\n@layer hl-reset {{\n{}}}\n",
1201 } else {
1083 } else {
1202− ""
1084+ format!("@layer {};@layer hl-reset{{{}}}", LAYERS.join(","), rules)
1205− match &doc.page_title {
1213−<meta charset=\"utf-8\">
1214−<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
1215−<title>{title}</title>
1216−{theme_color_html}{base_html}{canonical_html}{manifest_html}{preload_html}{dns_prefetch_html}{meta_html}{og_html}{favicon_html}{json_ld_html}{head_html}\
1218−*, *::before, *::after {{ box-sizing: border-box; }}
1219−body {{ margin: 0; font-family: system-ui, -apple-system, sans-serif; }}
1220−img {{ display: block; }}
1221−a {{ text-decoration: none; color: inherit; }}
1222−{focus_visible_css}{skip_link_css}{element_css}\
1231− title = html_escape(title),
1232− lang_attr = lang_attr,
1233− theme_color_html = theme_color_html,
1234− base_html = base_html,
1235− canonical_html = canonical_html,
1236− manifest_html = manifest_html,
1237− preload_html = preload_html,
1238− dns_prefetch_html = dns_prefetch_html,
1239− meta_html = meta_html,
1240− favicon_html = favicon_html,
1241− json_ld_html = json_ld_html,
1242− head_html = head_html,
1244− focus_visible_css = focus_visible_css,
1245− skip_link_css = skip_link_css,
1246− noscript_html = noscript_html,
1247− element_css = element_css,
1252− "<!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}}a{{text-decoration:none;color:inherit}}{focus_visible_css}{skip_link_css}{element_css}</style>{noscript_html}</head><body>{body}</body></html>",
1253− title = html_escape(title),
1254− lang_attr = lang_attr,
1255− theme_color_html = theme_color_html,
1256− base_html = base_html,
1257− canonical_html = canonical_html,
1258− manifest_html = manifest_html,
1259− preload_html = preload_html,
1260− dns_prefetch_html = dns_prefetch_html,
1261− meta_html = meta_html,
1263− favicon_html = favicon_html,
1264− json_ld_html = json_ld_html,
1265− head_html = head_html,
1266− focus_visible_css = focus_visible_css,
1267− skip_link_css = skip_link_css,
1268− noscript_html = noscript_html,
1269− element_css = element_css,
1275− if element_css.is_empty() {
1278− format!("<style>\n{}</style>\n{}", element_css, body)
1280− format!("<style>{}</style>{}", element_css, body)
1286/// Generate an HTML fragment: body + optional <style>, no <html>/<head>/<body> wrapper.
1088/// Generate an HTML fragment: body + optional <style>, no <html>/<head>/<body> wrapper.
1287−fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1089+fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
1288 let mut styles = StyleCollector::new();
1090 let mut styles = StyleCollector::new();
1289 let mut ctx = GenContext {
1091 let mut ctx = GenContext {
1291 depth: 0,
1093 depth: 0,
1293 has_interactive: false,
1094 has_interactive: false,
1294− has_defer: false,
1095+ in_text: false,
1096+ flow: Flow::default(),
1296 let mut body = String::new();
1099 let mut body = String::new();
1298− for node in &doc.nodes {
1101+ generate_children(&doc.nodes, None, &mut body, &mut styles, &mut ctx);
1299− generate_node(node, None, &mut body, &mut styles, &mut ctx);
1302− let has_custom_css = !doc.custom_css.is_empty();
1303− let mut element_css = String::new();
1305− let mut root_vars: Vec<(String, String)> = Vec::new();
1306− for (name, value) in &doc.css_vars {
1307− root_vars.push((name.clone(), value.clone()));
1309− for (name, value) in &doc.theme_tokens {
1310− let css_name = format!("--{}", name);
1311− if !root_vars.iter().any(|(n, _)| *n == css_name) {
1312− root_vars.push((css_name, value.clone()));
1316− let styles_css = styles.to_css_formatted(dev, !has_custom_css);
1317− let styles_css = substitute_css_vars(&styles_css, &root_vars);
1318− let styles_css = if dev {
1321− let (new_css, auto_vars) = auto_extract_repeats(&styles_css, &root_vars);
1322− root_vars.extend(auto_vars);
1326− if !root_vars.is_empty() {
1328− element_css.push_str(":root {\n");
1329− for (name, value) in &root_vars {
1330− element_css.push_str(&format!(" {}: {};\n", name, value));
1332− element_css.push_str("}\n");
1334− element_css.push_str(":root{");
1335− for (name, value) in &root_vars {
1336− element_css.push_str(name);
1337− element_css.push(':');
1338− element_css.push_str(value);
1339− element_css.push(';');
1341− element_css.push('}');
1345− element_css.push_str(&styles_css);
1347− for (name, kf_body) in &doc.keyframes {
1349− element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1351− element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1355− for block in &doc.custom_css {
1103+ let mut element_css = build_element_css(doc, &styles, dev);
1356− if dev {
1104+ // htmlang's own elements get the reset's rules for elements (which
1357− element_css.push_str(block);
1105+ // also puts htmlang's layers in order)
1358− element_css.push('\n');
1106+ if !styles.entries.is_empty() || !doc.scoped_css.is_empty() {
1359− } else {
1107+ element_css.insert_str(0, &reset_css(dev, false, ""));
1360− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1361− element_css.push_str(&minified);
1109+ classes.extend(styles.classes());
1365 if element_css.is_empty() {
1111 if element_css.is_empty() {
@@ -1375,44 +1121,20 @@ fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1375// Node generation
1121// Node generation
1376// ---------------------------------------------------------------------------
1122// ---------------------------------------------------------------------------
1124+/// Write `node`, which is inside an element with the layout `parent`
1125+/// (`None` at the top of the page).
1378fn generate_node(
1126fn generate_node(
1379 node: &Node,
1127 node: &Node,
1380− parent_kind: Option<&ElementKind>,
1128+ parent: Option<Layout>,
1381 out: &mut String,
1129 out: &mut String,
1382 styles: &mut StyleCollector,
1130 styles: &mut StyleCollector,
1383 ctx: &mut GenContext,
1131 ctx: &mut GenContext,
1385 match node {
1133 match node {
1386− Node::Element(elem) => generate_element(elem, parent_kind, out, styles, ctx),
1134+ Node::Element(elem) => generate_element(elem, parent, out, styles, ctx),
1387 Node::Text(segments) => {
1135 Node::Text(segments) => {
1388− let needs_wrap = matches!(
1136+ // In a row, column or grid each line of text is a child
1389− parent_kind,
1137+ let needs_wrap = parent.is_some_and(Layout::is_container);
1390− Some(ElementKind::Row)
1391− | Some(ElementKind::Column)
1392− | Some(ElementKind::El)
1393− | Some(ElementKind::Nav)
1394− | Some(ElementKind::Header)
1395− | Some(ElementKind::Footer)
1396− | Some(ElementKind::Main)
1397− | Some(ElementKind::Section)
1398− | Some(ElementKind::Article)
1399− | Some(ElementKind::Aside)
1400− | Some(ElementKind::ListItem)
1401− | Some(ElementKind::Form)
1402− | Some(ElementKind::Details)
1403− | Some(ElementKind::Figure)
1404− | Some(ElementKind::Blockquote)
1405− | Some(ElementKind::Dialog)
1406− | Some(ElementKind::DefinitionList)
1407− | Some(ElementKind::DefinitionDescription)
1408− | Some(ElementKind::Fieldset)
1409− | Some(ElementKind::Datalist)
1410− | Some(ElementKind::Grid)
1411− | Some(ElementKind::Stack)
1412− | Some(ElementKind::Noscript)
1413− | Some(ElementKind::Address)
1414− | Some(ElementKind::Search)
1416 if needs_wrap {
1138 if needs_wrap {
1417 out.push_str(&ctx.indent());
1139 out.push_str(&ctx.indent());
1418 out.push_str("<span>");
1140 out.push_str("<span>");
@@ -1431,197 +1153,191 @@ fn generate_node(
1434−/// HTML attributes that are passed through to the HTML tag rather than converted to CSS.
1156+/// What goes between two things written one after the other in an element
1435−const HTML_PASSTHROUGH_ATTRS: &[&str] = &[
1157+/// with this layout (`None`: the top of the page): text flows, so its lines
1436− "type",
1158+/// and children are joined with a space; in HTML's own layout, and at the
1437− "placeholder",
1159+/// top of the page, two lines of text are separated by a line break (a
1438− "name",
1160+/// space, except where whitespace is kept, as in `@pre`).
1439− "value",
1161+fn separator(layout: Option<Layout>, previous_is_text: bool, next: &Node) -> Option<char> {
1440− "disabled",
1162+ match layout {
1441− "required",
1163+ Some(Layout::Text) => Some(' '),
1442− "checked",
1164+ Some(Layout::Native) | None if previous_is_text && matches!(next, Node::Text(_)) => {
1443− "for",
1165+ Some('\n')
1445− "method",
1167+ _ => None,
1446− "autocomplete",
1168+ }
1468− // Image optimization
1471− // Media src (explicit attribute form)
1473− // New element attributes
1494− "popovertargetaction",
1495− // Modern form/input hints
1498− // Performance hints
1504− // ARIA live regions
1510−/// Boolean HTML attributes (rendered without a value, e.g., `<input disabled>`).
1171+/// Write the children of an element (or of a `@fragment`, which has no
1511−const BOOLEAN_HTML_ATTRS: &[&str] = &[
1172+/// element of its own) laid out as `layout` (`None`: the top of the page).
1512− "disabled",
1173+/// The first line of an element's text is its first child.
1513− "required",
1174+fn generate_children(
1514− "checked",
1175+ children: &[Node],
1515− "multiple",
1176+ layout: Option<Layout>,
1516− "controls",
1177+ out: &mut String,
1517− "autoplay",
1178+ styles: &mut StyleCollector,
1518− "loop",
1179+ ctx: &mut GenContext,
1520− "playsinline",
1181+ generate_run(children, layout, &mut None, out, styles, ctx);
1531−fn emit_html_passthrough_attrs(out: &mut String, attrs: &[Attribute]) {
1184+/// [`generate_children`], with `previous` saying whether what was written
1532− for attr in attrs {
1185+/// last was a line of text (`None`: nothing yet). A `@fragment`'s children
1533− let key = attr.key.as_str();
1186+/// are written as if they stood in its place, so its lines are separated
1534− let is_passthrough = HTML_PASSTHROUGH_ATTRS.contains(&key)
1187+/// from the lines around it like any other lines.
1535− || key.starts_with("aria-")
1188+fn generate_run(
1536− || key.starts_with("data-");
1189+ children: &[Node],
1537− if !is_passthrough {
1190+ layout: Option<Layout>,
1191+ previous: &mut Option<bool>,
1193+ styles: &mut StyleCollector,
1194+ ctx: &mut GenContext,
1196+ for child in children {
1197+ if let Node::Element(elem) = child
1198+ && elem.kind == ElementKind::Fragment
1200+ generate_run(&elem.children, layout, previous, out, styles, ctx);
1538 continue;
1201 continue;
1540− if BOOLEAN_HTML_ATTRS.contains(&key) && attr.value.is_none() {
1203+ let start = out.len();
1541− out.push(' ');
1204+ if let Some(previous_is_text) = *previous
1542− out.push_str(key);
1205+ && let Some(sep) = separator(layout, previous_is_text, child)
1543− } else if let Some(val) = &attr.value {
1206+ {
1544− out.push(' ');
1207+ out.push(sep);
1545− out.push_str(key);
1208+ }
1546− out.push_str("=\"");
1209+ let body = out.len();
1547− out.push_str(&html_escape(strip_string_quotes(val)));
1210+ generate_node(child, layout, out, styles, ctx);
1548− out.push('"');
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);
1217+ *previous = Some(matches!(child, Node::Text(_)));
1553−/// If the value is wrapped in a single pair of matching quotes (e.g.
1221+/// Emit the element's leading argument as its attribute (`@iframe URL` →
1554−/// `"Avatar"`), return the inner content. Quotes act as source-level
1222+/// `src="URL"`, `@form /submit` → `action="/submit"`, `@link /a` →
1555−/// delimiters in the `.hl` syntax and shouldn't leak into HTML attribute
1223+/// `href="/a"`), first, before the class. `@image [inline] photo.png` puts
1556−/// values. Multi-quoted values like `"h h" "s m"` are left unchanged —
1224+/// the file itself into the page.
1557−/// those are real string tokens (used e.g. by CSS `grid-template-areas`).
1225+fn emit_argument_attr(out: &mut String, elem: &Element, in_picture: bool) {
1558−fn strip_string_quotes(val: &str) -> &str {
1226+ let (Some(attr), Some(value)) = (elem.kind.leading_attribute(in_picture), &elem.argument)
1559− let bytes = val.as_bytes();
1227+ else {
1560− if bytes.len() < 2 {
1228+ return;
1561− return val;
1229+ };
1562− }
1230+ // `@image [inline]`'s file is already a `data:` URI (see the parser)
1563− let first = bytes[0];
1231+ let value = html_escape(value);
1564− let last = bytes[bytes.len() - 1];
1232+ out.push(' ');
1565− if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
1233+ out.push_str(attr);
1566− let inner = &val[1..val.len() - 1];
1234+ out.push_str("=\"");
1567− if !inner.as_bytes().contains(&first) {
1235+ out.push_str(&value);
1568− return inner;
1236+ out.push('"');
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
1244+ .map(str::to_ascii_lowercase)
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",
1256+ format!("data:{};base64,{}", mime, base64_encode(data))
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);
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> {
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..]
1280+ .any(|other| is_html(other) && other.key == attr.key);
1281+ (is_html(attr) && !later).then_some(attr)
1285+/// ` key="value"`, or ` key` for a flag.
1286+fn push_html_attr(out: &mut String, attr: &Attribute) {
1288+ out.push_str(&attr.key);
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("")));
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)
1304+fn holds_overlays(children: &[Node]) -> bool {
1305+ children.iter().any(|child| {
1308+ Node::Element(e) if e.kind.is_tag("in-front") || e.kind.is_tag("behind")
1574fn generate_element(
1313fn generate_element(
1575 elem: &Element,
1314 elem: &Element,
1576− parent_kind: Option<&ElementKind>,
1315+ parent: Option<Layout>,
1577 out: &mut String,
1316 out: &mut String,
1578 styles: &mut StyleCollector,
1317 styles: &mut StyleCollector,
1579 ctx: &mut GenContext,
1318 ctx: &mut GenContext,
1581 // Self-closing elements
1320 // Self-closing elements
1582− if matches!(
1321+ if elem.kind.layout() == Layout::Void {
1583− elem.kind,
1322+ generate_self_closing(elem, parent, out, styles, ctx);
1585− | ElementKind::Input
1586− | ElementKind::HorizontalRule
1587− | ElementKind::Source
1588− | ElementKind::Spacer
1590− generate_self_closing(elem, parent_kind, out, styles, ctx);
1593− // @script renders as <script> with raw body content (no HTML escaping)
1325+ // A verbatim element (@script) writes its body as it is, with no HTML
1594− if elem.kind == ElementKind::Script {
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);
1595 out.push_str(&ctx.indent());
1329 out.push_str(&ctx.indent());
1596− out.push_str("<script");
1330+ out.push('<');
1597− // Pass through src, type, defer, async, etc.
1331+ out.push_str(tag);
1598− for attr in &elem.attrs {
1332+ emit_argument_attr(out, elem, false);
1599− let key = attr.key.as_str();
1333+ let (id, class) = extract_id_class(&elem.attrs);
1600− if matches!(
1334+ for (key, value) in [("id", id), ("class", class)] {
1601− key,
1335+ if let Some(value) = value {
1602− "src"
1336+ out.push_str(&format!(" {}=\"{}\"", key, html_escape(&value)));
1611− if let Some(val) = &attr.value {
1614− out.push_str("=\"");
1615− out.push_str(&html_escape(val));
1339+ emit_html_attrs(out, &elem.attrs);
1623 out.push('>');
1340 out.push('>');
1624− // Children are raw JS code, not HTML
1625 for child in &elem.children {
1341 for child in &elem.children {
1626 match child {
1342 match child {
1627 Node::Text(segments) => {
1343 Node::Text(segments) => {
@@ -1635,46 +1351,10 @@ fn generate_element(
1638− out.push_str("</script>");
1354+ out.push_str("</");
1639− out.push_str(ctx.nl());
1355+ out.push_str(tag);
1642− // @breadcrumb generates semantic <nav aria-label="breadcrumb"><ol>...</ol></nav>
1643− if elem.kind == ElementKind::Breadcrumb {
1644− let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
1645− let (id, user_class) = extract_id_class(&elem.attrs);
1646− out.push_str(&ctx.indent());
1647− out.push_str("<nav aria-label=\"breadcrumb\"");
1648− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1649− if let Some(id) = id {
1650− out.push_str(" id=\"");
1651− out.push_str(&html_escape(&id));
1654 out.push('>');
1356 out.push('>');
1655 out.push_str(ctx.nl());
1357 out.push_str(ctx.nl());
1657− out.push_str(&ctx.indent());
1658− out.push_str("<ol>");
1659− out.push_str(ctx.nl());
1661− for child in &elem.children {
1662− out.push_str(&ctx.indent());
1663− out.push_str("<li>");
1664− let mut buf = String::new();
1665− generate_node(child, Some(&elem.kind), &mut buf, styles, ctx);
1666− out.push_str(buf.trim());
1667− out.push_str("</li>");
1668− out.push_str(ctx.nl());
1671− out.push_str(&ctx.indent());
1672− out.push_str("</ol>");
1673− out.push_str(ctx.nl());
1675− out.push_str(&ctx.indent());
1676− out.push_str("</nav>");
1677− out.push_str(ctx.nl());
1680 if elem.kind == ElementKind::Children {
1360 if elem.kind == ElementKind::Children {
@@ -1684,198 +1364,38 @@ fn generate_element(
1686 if elem.kind == ElementKind::Fragment {
1366 if elem.kind == ElementKind::Fragment {
1687− // Render children without a wrapper element
1367+ // Render children without a wrapper element, as if they were
1688− for child in &elem.children {
1368+ // written where the fragment is
1689− generate_node(child, parent_kind, out, styles, ctx);
1369+ generate_children(&elem.children, parent, out, styles, ctx);
1373+ let mut own = Flow::of(elem);
1694 let tag = match &elem.kind {
1374 let tag = match &elem.kind {
1695− ElementKind::Row
1375+ ElementKind::Row | ElementKind::El => "div",
1696− | ElementKind::Column
1698− | ElementKind::Grid
1699− | ElementKind::Stack => "div",
1700 ElementKind::Text => "span",
1376 ElementKind::Text => "span",
1701 ElementKind::Paragraph => "p",
1377 ElementKind::Paragraph => "p",
1702 ElementKind::Link => "a",
1378 ElementKind::Link => "a",
1703− ElementKind::Button => "button",
1379+ ElementKind::Tag(spec) => spec.html,
1704− ElementKind::Select => "select",
1705− ElementKind::Textarea => "textarea",
1706− ElementKind::Option => "option",
1707− ElementKind::Label => "label",
1708− // Semantic elements
1709− ElementKind::Nav => "nav",
1710− ElementKind::Header => "header",
1711− ElementKind::Footer => "footer",
1712− ElementKind::Main => "main",
1713− ElementKind::Section => "section",
1714− ElementKind::Article => "article",
1715− ElementKind::Aside => "aside",
1717− ElementKind::List => {
1718− if elem.attrs.iter().any(|a| a.key == "ordered") {
1724− ElementKind::ListItem => "li",
1726− ElementKind::Table => "table",
1727− ElementKind::TableHead => "thead",
1728− ElementKind::TableBody => "tbody",
1729− ElementKind::TableRow => "tr",
1730− ElementKind::TableCell => "td",
1731− ElementKind::TableHeaderCell => "th",
1733− ElementKind::Video => "video",
1734− ElementKind::Audio => "audio",
1735− // Additional semantic elements
1736− ElementKind::Form => "form",
1737− ElementKind::Details => "details",
1738− ElementKind::Summary => "summary",
1739− ElementKind::Blockquote => "blockquote",
1740− ElementKind::Cite => "cite",
1741− ElementKind::Code => "code",
1742− ElementKind::Pre => "pre",
1743− ElementKind::Figure => "figure",
1744− ElementKind::FigCaption => "figcaption",
1745− ElementKind::Progress => "progress",
1746− ElementKind::Meter => "meter",
1748− ElementKind::Dialog => "dialog",
1749− ElementKind::DefinitionList => "dl",
1750− ElementKind::DefinitionTerm => "dt",
1751− ElementKind::DefinitionDescription => "dd",
1752− ElementKind::Fieldset => "fieldset",
1753− ElementKind::Legend => "legend",
1754− ElementKind::Picture => "picture",
1755− ElementKind::Time => "time",
1756− ElementKind::Mark => "mark",
1757− ElementKind::Kbd => "kbd",
1758− ElementKind::Abbr => "abbr",
1759− ElementKind::Datalist => "datalist",
1760− ElementKind::Iframe => "iframe",
1761− ElementKind::Output => "output",
1762− ElementKind::Canvas => "canvas",
1763− ElementKind::Badge => "span",
1764− ElementKind::Tooltip => "span",
1765− ElementKind::Avatar => "div",
1766− ElementKind::Carousel => "div",
1767− ElementKind::Chip => "span",
1768− ElementKind::Tag => "span",
1769− ElementKind::Noscript => "noscript",
1770− ElementKind::Address => "address",
1771− ElementKind::Search => "search",
1772− // Heading elements
1773− ElementKind::H1 => "h1",
1774− ElementKind::H2 => "h2",
1775− ElementKind::H3 => "h3",
1776− ElementKind::H4 => "h4",
1777− ElementKind::H5 => "h5",
1778− ElementKind::H6 => "h6",
1780− | ElementKind::Input
1781− | ElementKind::HorizontalRule
1782− | ElementKind::Children
1783− | ElementKind::Slot(_)
1784− | ElementKind::Fragment
1785− | ElementKind::Source
1786− | ElementKind::Spacer
1787− | ElementKind::Script
1788− | ElementKind::Breadcrumb => unreachable!(),
1791− let kind_label = match elem.kind {
1792− ElementKind::Row => "row",
1793− ElementKind::Column => "column",
1794− ElementKind::El => "el",
1795− ElementKind::Text => "text",
1796− ElementKind::Paragraph => "paragraph",
1797− ElementKind::Link => "link",
1798− ElementKind::Button => "button",
1799− ElementKind::Select => "select",
1800− ElementKind::Textarea => "textarea",
1801− ElementKind::Option => "option",
1802− ElementKind::Label => "label",
1803− ElementKind::Nav => "nav",
1804− ElementKind::Header => "header",
1805− ElementKind::Footer => "footer",
1806− ElementKind::Main => "main",
1807− ElementKind::Section => "section",
1808− ElementKind::Article => "article",
1809− ElementKind::Aside => "aside",
1810− ElementKind::List => "list",
1811− ElementKind::ListItem => "item",
1812− ElementKind::Table => "table",
1813− ElementKind::TableHead => "thead",
1814− ElementKind::TableBody => "tbody",
1815− ElementKind::TableRow => "tr",
1816− ElementKind::TableCell => "td",
1817− ElementKind::TableHeaderCell => "th",
1818− ElementKind::Video => "video",
1819− ElementKind::Audio => "audio",
1820− ElementKind::Form => "form",
1821− ElementKind::Details => "details",
1822− ElementKind::Summary => "summary",
1823− ElementKind::Blockquote => "blockquote",
1824− ElementKind::Cite => "cite",
1825− ElementKind::Code => "code",
1826− ElementKind::Pre => "pre",
1827− ElementKind::Figure => "figure",
1828− ElementKind::FigCaption => "figcaption",
1829− ElementKind::Fragment => "fragment",
1830− ElementKind::Dialog => "dialog",
1831− ElementKind::DefinitionList => "dl",
1832− ElementKind::DefinitionTerm => "dt",
1833− ElementKind::DefinitionDescription => "dd",
1834− ElementKind::Fieldset => "fieldset",
1835− ElementKind::Legend => "legend",
1836− ElementKind::Picture => "picture",
1837− ElementKind::Time => "time",
1838− ElementKind::Mark => "mark",
1839− ElementKind::Kbd => "kbd",
1840− ElementKind::Abbr => "abbr",
1841− ElementKind::Datalist => "datalist",
1842− ElementKind::Iframe => "iframe",
1843− ElementKind::Output => "output",
1844− ElementKind::Canvas => "canvas",
1845− ElementKind::Grid => "grid",
1846− ElementKind::Stack => "stack",
1847− ElementKind::Badge => "badge",
1848− ElementKind::Tooltip => "tooltip",
1849− ElementKind::Avatar => "avatar",
1850− ElementKind::Carousel => "carousel",
1851− ElementKind::Chip => "chip",
1852− ElementKind::Tag => "tag",
1853− ElementKind::Noscript => "noscript",
1854− ElementKind::Address => "address",
1855− ElementKind::Search => "search",
1856− ElementKind::H1 => "h1",
1857− ElementKind::H2 => "h2",
1858− ElementKind::H3 => "h3",
1859− ElementKind::H4 => "h4",
1860− ElementKind::H5 => "h5",
1861− ElementKind::H6 => "h6",
1862 _ => "",
1380 _ => "",
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();
1865 // Track interactive elements for focus-visible CSS
1389 // Track interactive elements for focus-visible CSS
1866− if matches!(
1390+ if elem.kind == ElementKind::Link
1867− elem.kind,
1391+ || matches!(kind_label, "button" | "input" | "select" | "textarea")
1868− ElementKind::Link
1392+ {
1869− | ElementKind::Button
1870− | ElementKind::Input
1871− | ElementKind::Select
1872− | ElementKind::Textarea
1874 ctx.has_interactive = true;
1393 ctx.has_interactive = true;
1877 // Compute CSS for each state and get a class name
1396 // Compute CSS for each state and get a class name
1878− let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
1397+ let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
1398+ own.class = gen_class.clone();
1879 let (id, user_class) = extract_id_class(&elem.attrs);
1399 let (id, user_class) = extract_id_class(&elem.attrs);
1881 if ctx.dev && elem.line_num > 0 {
1401 if ctx.dev && elem.line_num > 0 {
@@ -1889,93 +1409,17 @@ fn generate_element(
1889 out.push('<');
1409 out.push('<');
1890 out.push_str(tag);
1410 out.push_str(tag);
1892− // @main gets id="hl-main" for skip-to-content link (unless user set an id)
1412+ emit_argument_attr(out, elem, ctx.in_picture);
1893− if elem.kind == ElementKind::Main && id.is_none() {
1894− out.push_str(" id=\"hl-main\"");
1897− if elem.kind == ElementKind::Link
1414+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1898− && let Some(url) = &elem.argument
1415+
1899− {
1416+ if let Some(id) = id {
1900− out.push_str(" href=\"");
1417+ out.push_str(" id=\"");
1901− out.push_str(&html_escape(url));
1418+ out.push_str(&html_escape(&id));
1902 out.push('"');
1419 out.push('"');
1903− // Auto rel="noopener noreferrer" and target="_blank" for external links
1904− let is_external = url.starts_with("http://") || url.starts_with("https://");
1906− let has_rel = elem.attrs.iter().any(|a| a.key == "rel");
1907− let has_target = elem.attrs.iter().any(|a| a.key == "target");
1909− out.push_str(" rel=\"noopener noreferrer\"");
1912− out.push_str(" target=\"_blank\"");
1917− // Video/Audio src
1422+ emit_html_attrs(out, &elem.attrs);
1918− if matches!(elem.kind, ElementKind::Video | ElementKind::Audio)
1919− && let Some(src) = &elem.argument
1921− out.push_str(" src=\"");
1922− out.push_str(&html_escape(src));
1927− if elem.kind == ElementKind::Form
1928− && let Some(action) = &elem.argument
1930− out.push_str(" action=\"");
1931− out.push_str(&html_escape(action));
1936− if elem.kind == ElementKind::Iframe
1937− && let Some(src) = &elem.argument
1939− out.push_str(" src=\"");
1940− out.push_str(&html_escape(src));
1945− if elem.kind == ElementKind::Tooltip
1946− && let Some(text) = &elem.argument
1948− out.push_str(" title=\"");
1949− out.push_str(&html_escape(text));
1953− // Critical CSS: inline styles directly instead of using a class
1954− let is_critical = elem.attrs.iter().any(|a| a.key == "critical");
1956− let inline_css = attrs_to_css(&elem.attrs, "", &elem.kind, parent_kind);
1957− if !inline_css.is_empty() {
1958− out.push_str(" style=\"");
1959− out.push_str(&html_escape(&inline_css));
1962− // Still use class for non-base styles (pseudo, responsive, etc.)
1963− if gen_class.as_deref().is_some_and(|c| !c.is_empty()) {
1964− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1965− } else if let Some(ref uc) = user_class {
1966− emit_class_attr(out, None, Some(uc));
1969− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1972− if let Some(id) = id {
1973− out.push_str(" id=\"");
1974− out.push_str(&html_escape(&id));
1978− emit_html_passthrough_attrs(out, &elem.attrs);
1980 // Source map attributes in dev mode
1424 // Source map attributes in dev mode
1981 if ctx.dev && elem.line_num > 0 {
1425 if ctx.dev && elem.line_num > 0 {
@@ -1986,66 +1430,27 @@ fn generate_element(
1988 out.push('>');
1432 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");
1989 out.push_str(ctx.nl());
1438 out.push_str(ctx.nl());
1991− // Inline text argument
1440+ let layout = elem.kind.layout();
1995− | ElementKind::Button
1996− | ElementKind::Label
1997− | ElementKind::Option
1998− | ElementKind::Textarea
1999− | ElementKind::ListItem
2000− | ElementKind::TableCell
2001− | ElementKind::TableHeaderCell
2002− | ElementKind::Summary
2003− | ElementKind::Cite
2004− | ElementKind::Code
2005− | ElementKind::FigCaption
2006− | ElementKind::Legend
2007− | ElementKind::DefinitionTerm
2008− | ElementKind::Mark
2010− | ElementKind::Abbr
2011− | ElementKind::Time
2012− | ElementKind::DefinitionDescription
2013− | ElementKind::Badge
2014− | ElementKind::Tooltip
2015− | ElementKind::Chip
2023− ) && let Some(text) = &elem.argument
2025− out.push_str(&html_escape(text));
2029 ctx.depth += 1;
1441 ctx.depth += 1;
2030− let is_paragraph = matches!(
1442+ let outer_in_text = ctx.in_text;
2031− elem.kind,
1443+ ctx.in_text = in_text || layout == Layout::Text;
2032− ElementKind::Paragraph
1444+ let outer_flow = std::mem::replace(&mut ctx.flow, own);
2033− | ElementKind::H1
1445+ let outer_picture = std::mem::replace(&mut ctx.in_picture, elem.kind.is_tag("picture"));
2034− | ElementKind::H2
1446+ generate_children(&elem.children, Some(layout), out, styles, ctx);
2035− | ElementKind::H3
1447+ ctx.in_picture = outer_picture;
2036− | ElementKind::H4
1448+ ctx.flow = outer_flow;
2037− | ElementKind::H5
1449+ ctx.in_text = outer_in_text;
2040− for (i, child) in elem.children.iter().enumerate() {
2041− generate_node(child, Some(&elem.kind), out, styles, ctx);
2042− if is_paragraph && i < elem.children.len() - 1 {
2046 ctx.depth -= 1;
1450 ctx.depth -= 1;
2048 out.push_str(&ctx.indent());
1452 out.push_str(&ctx.indent());
1453+ ctx.dev = outer_dev;
2049 out.push_str("</");
1454 out.push_str("</");
2050 out.push_str(tag);
1455 out.push_str(tag);
2051 out.push('>');
1456 out.push('>');
@@ -2054,21 +1459,18 @@ fn generate_element(
2055fn generate_self_closing(
1460fn generate_self_closing(
2056 elem: &Element,
1461 elem: &Element,
2057− parent_kind: Option<&ElementKind>,
1462+ parent: Option<Layout>,
2058 out: &mut String,
1463 out: &mut String,
2059 styles: &mut StyleCollector,
1464 styles: &mut StyleCollector,
2060 ctx: &mut GenContext,
1465 ctx: &mut GenContext,
2062− let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
1467+ let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
2063 let (id, user_class) = extract_id_class(&elem.attrs);
1468 let (id, user_class) = extract_id_class(&elem.attrs);
2065− let (tag, kind_label) = match elem.kind {
1470+ let (tag, kind_label) = match &elem.kind {
2066 ElementKind::Image => ("img", "image"),
1471 ElementKind::Image => ("img", "image"),
2067− ElementKind::Input => ("input", "input"),
1472+ ElementKind::Tag(spec) => (spec.html, spec.name),
2068− ElementKind::HorizontalRule => ("hr", "hr"),
1473+ _ => unreachable!("not a void element: {:?}", elem.kind),
2069− ElementKind::Source => ("source", "source"),
2070− ElementKind::Spacer => ("div", "spacer"),
2071− _ => unreachable!(),
2074 if ctx.dev && elem.line_num > 0 {
1476 if ctx.dev && elem.line_num > 0 {
@@ -2081,43 +1483,7 @@ fn generate_self_closing(
2081 out.push_str(&ctx.indent());
1483 out.push_str(&ctx.indent());
2082 out.push('<');
1484 out.push('<');
2083 out.push_str(tag);
1485 out.push_str(tag);
2084−
1486+ emit_argument_attr(out, elem, ctx.in_picture);
2085− // Image src (with optional non-SVG base64 inlining)
2086− if elem.kind == ElementKind::Image {
2087− let src = elem.argument.as_deref().unwrap_or("");
2088− let is_inline = elem.attrs.iter().any(|a| a.key == "inline");
2089− if is_inline && !src.is_empty() && !src.ends_with(".svg") {
2090− let mime = if src.ends_with(".png") {
2092− } else if src.ends_with(".jpg") || src.ends_with(".jpeg") {
2094− } else if src.ends_with(".gif") {
2096− } else if src.ends_with(".webp") {
2098− } else if src.ends_with(".avif") {
2101− "application/octet-stream"
2103− if let Ok(data) = std::fs::read(src) {
2104− let b64 = base64_encode(&data);
2105− out.push_str(" src=\"data:");
2106− out.push_str(mime);
2107− out.push_str(";base64,");
2108− out.push_str(&b64);
2111− out.push_str(" src=\"");
2112− out.push_str(&html_escape(src));
2116− out.push_str(" src=\"");
2117− out.push_str(&html_escape(src));
2122 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1488 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
@@ -2127,7 +1493,7 @@ fn generate_self_closing(
2127 out.push('"');
1493 out.push('"');
2130− emit_html_passthrough_attrs(out, &elem.attrs);
1496+ emit_html_attrs(out, &elem.attrs);
2132 // Source map attributes in dev mode (self-closing)
1498 // Source map attributes in dev mode (self-closing)
2133 if ctx.dev && elem.line_num > 0 {
1499 if ctx.dev && elem.line_num > 0 {
@@ -2137,93 +1503,6 @@ fn generate_self_closing(
2140− // Image optimization: auto-add loading="lazy" and decoding="async"
2141− if elem.kind == ElementKind::Image {
2142− // SVG inlining: @image [inline] logo.svg
2143− if elem.attrs.iter().any(|a| a.key == "inline")
2144− && let Some(src) = &elem.argument
2145− && src.ends_with(".svg")
2146− && let Ok(svg_content) = std::fs::read_to_string(src)
2148− // Close the tag we opened, then emit inline SVG instead
2149− out.truncate(out.rfind('<').unwrap_or(0));
2150− out.push_str(&ctx.indent());
2151− out.push_str(svg_content.trim());
2152− out.push_str(ctx.nl());
2155− // Responsive srcset: @image photo.jpg [responsive 400 800 1200]
2156− let responsive_attr = elem.attrs.iter().find(|a| a.key == "responsive");
2157− if let Some(resp) = responsive_attr
2158− && let Some(ref sizes_str) = resp.value
2160− let widths: Vec<&str> = sizes_str.split_whitespace().collect();
2161− if !widths.is_empty() {
2162− let src = elem.argument.as_deref().unwrap_or("");
2163− if !src.is_empty() {
2164− // Generate srcset with width descriptors
2165− // Convention: file-{width}.ext (e.g., photo-400.jpg)
2166− let dot_pos = src.rfind('.').unwrap_or(src.len());
2167− let base = &src[..dot_pos];
2168− let ext = &src[dot_pos..];
2169− let mut srcset_parts = Vec::new();
2171− srcset_parts.push(format!("{}-{}{} {}w", base, w, ext, w));
2173− out.push_str(" srcset=\"");
2174− out.push_str(&srcset_parts.join(", "));
2176− // Generate sizes attribute
2177− let max_width = widths.last().unwrap_or(&"100vw");
2178− out.push_str(&format!(
2179− " sizes=\"(max-width: {}px) 100vw, {}px\"",
2180− max_width, max_width
2186− // Auto image dimensions: read local image file to inject width/height + aspect-ratio
2187− let has_width = elem.attrs.iter().any(|a| a.key == "width");
2188− let has_height = elem.attrs.iter().any(|a| a.key == "height");
2189− if (!has_width || !has_height)
2190− && let Some(ref src) = elem.argument
2191− && !src.starts_with("http://")
2192− && !src.starts_with("https://")
2193− && !src.starts_with("data:")
2194− && let Some((w, h)) = read_image_dimensions(src)
2197− out.push_str(&format!(" width=\"{}\"", w));
2200− out.push_str(&format!(" height=\"{}\"", h));
2202− // Auto aspect-ratio to prevent CLS
2203− if !elem.attrs.iter().any(|a| a.key == "aspect-ratio") {
2204− out.push_str(&format!(" style=\"aspect-ratio:{}/{}\"", w, h));
2208− // Smart image loading: first 3 images get fetchpriority="high" (above the fold),
2209− // subsequent images get loading="lazy" + decoding="async"
2210− ctx.image_count += 1;
2211− if ctx.image_count <= 3 {
2212− // Above-the-fold: eager loading with high priority
2213− if !elem.attrs.iter().any(|a| a.key == "fetchpriority") {
2214− out.push_str(" fetchpriority=\"high\"");
2217− // Below-the-fold: lazy loading
2218− if !elem.attrs.iter().any(|a| a.key == "loading") {
2219− out.push_str(" loading=\"lazy\"");
2221− if !elem.attrs.iter().any(|a| a.key == "decoding") {
2222− out.push_str(" decoding=\"async\"");
2227 out.push('>');
1506 out.push('>');
2228 out.push_str(ctx.nl());
1507 out.push_str(ctx.nl());
@@ -2239,7 +1518,10 @@ fn generate_text_segments(
2239 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
1518 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
2240 TextSegment::Inline(elem) => {
1519 TextSegment::Inline(elem) => {
2241 let mut buf = String::new();
1520 let mut buf = String::new();
2242− generate_element(elem, None, &mut buf, styles, ctx);
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;
2243 out.push_str(buf.trim_end());
1525 out.push_str(buf.trim_end());
@@ -2252,141 +1534,97 @@ fn generate_text_segments(
2253fn compute_class(
1535fn compute_class(
2254 attrs: &[Attribute],
1536 attrs: &[Attribute],
2255− kind: &ElementKind,
1537+ site: &Site,
2256− parent_kind: Option<&ElementKind>,
2257 styles: &mut StyleCollector,
1538 styles: &mut StyleCollector,
2258) -> Option<String> {
1540) -> Option<String> {
2259− let base = attrs_to_css(attrs, "", kind, parent_kind);
1541+ // Every condition an attribute is under, and none
2260−
1542+ let mut conditions = vec![Condition::default()];
2261− // Collect pseudo-state overrides
1543+ for attr in attrs.iter().filter(|a| !a.html) {
2262− let mut pseudo = Vec::new();
1544+ let (condition, _) = Condition::of(&attr.key);
2263− for &(prefix, selector) in PSEUDO_PREFIXES {
1545+ if !conditions.contains(&condition) {
2264− let css = attrs_to_css(attrs, prefix, kind, parent_kind);
1546+ conditions.push(condition);
2265− if !css.is_empty() {
2266− pseudo.push((selector.to_string(), css));
2270− // Auto-add ::-webkit-scrollbar pseudo for no-scrollbar attribute
2271− if attrs.iter().any(|a| a.key == "no-scrollbar") {
2273− "::-webkit-scrollbar".to_string(),
2274− "display:none;".to_string(),
2278− // Collect nth:EXPR: dynamic pseudo selectors
2279− let mut nth_prefixes: Vec<String> = Vec::new();
2280− for attr in attrs {
2281− if attr.key.starts_with("nth:") {
2282− let rest = &attr.key[4..];
2283− if let Some(colon_pos) = rest.find(':') {
2284− let prefix = format!("nth:{}:", &rest[..colon_pos]);
2285− if !nth_prefixes.contains(&prefix) {
2286− nth_prefixes.push(prefix);
2291− for prefix in &nth_prefixes {
2292− let expr = &prefix[4..prefix.len() - 1];
2293− let selector = format!(":nth-child({})", expr);
2294− let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2295− if !css.is_empty() {
2296− pseudo.push((selector, css));
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
1554+ let css = dedupe_declarations(&attrs_to_css(attrs, &condition, site));
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)
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)
1570+ styles.get_class(defaults, rules, distinct)
2300− // Collect has(...): dynamic pseudo selectors
1573+/// The defaults of an element's kind where it is: an overlay's positioning
2301− let mut has_prefixes: Vec<String> = Vec::new();
1574+/// context, its layout, and its kind's own CSS (a heading's `margin:0`).
2302− for attr in attrs {
1575+fn default_css(site: &Site) -> String {
2303− if attr.key.starts_with("has(")
1576+ let mut css = String::new();
2304− && let Some(close) = attr.key.find("):")
1577+ // Elements with @in-front / @behind children become positioning
2306− let prefix = format!("{}:", &attr.key[..close + 1]);
1579+ if site.has_overlay_children {
2307− if !has_prefixes.contains(&prefix) {
1580+ css.push_str("position:relative;isolation:isolate;");
2308− has_prefixes.push(prefix);
2312− for prefix in &has_prefixes {
1582+ if !site.root {
2313− let inner = &prefix[4..prefix.len() - 2]; // extract selector from has(selector):
1583+ css.push_str(layout_css(site.kind.layout(), site.inline));
2314− let selector = format!(":has({})", inner);
2315− let css = attrs_to_css(attrs, prefix, kind, parent_kind);
2316− if !css.is_empty() {
2317− pseudo.push((selector, css));
1585+ css.push_str(site.kind.css());
2321− // Collect responsive overrides
1589+/// The declarations of a rule body, as (property, `property:value;`), for
2322− let mut responsive = Vec::new();
1590+/// bodies htmlang wrote: every declaration ends in `;`, and a `;` inside
2323− for &(bp_name, _) in BREAKPOINTS {
1591+/// quotes or parentheses doesn't end one.
2324− let prefix = format!("{}:", bp_name);
1592+fn declarations(css: &str) -> impl Iterator<Item = (&str, &str)> {
2325− let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1593+ let mut rest = css;
2326− if !css.is_empty() {
1594+ std::iter::from_fn(move || {
2327− responsive.push((bp_name.to_string(), css));
1595+ if rest.is_empty() {
2329− }
1598+ let (mut depth, mut quote, mut escaped) = (0i32, None, false);
2330−
1599+ let mut end = rest.len();
2331− // Collect container query overrides
1600+ for (i, c) in rest.char_indices() {
2332− let mut container = Vec::new();
1601+ match c {
2333− for &(bp_name, _) in BREAKPOINTS {
1602+ _ if escaped => escaped = false,
2334− let prefix = format!("cq-{}:", bp_name);
1603+ '\\' => escaped = true,
2335− let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1604+ c if Some(c) == quote => quote = None,
2336− if !css.is_empty() {
1605+ _ if quote.is_some() => {}
2337− container.push((bp_name.to_string(), css));
1606+ '"' | '\'' => quote = Some(c),
1609+ ';' if depth == 0 => {
2339− }
1616+ let (declaration, after) = rest.split_at(end);
2341− let dark = attrs_to_css(attrs, "dark:", kind, parent_kind);
1618+ let name = declaration.split(':').next().unwrap_or("").trim();
2342− let print = attrs_to_css(attrs, "print:", kind, parent_kind);
1619+ Some((name, declaration))
2343− let motion_safe = attrs_to_css(attrs, "motion-safe:", kind, parent_kind);
1620+ })
2344− let motion_reduce = attrs_to_css(attrs, "motion-reduce:", kind, parent_kind);
2345− let landscape = attrs_to_css(attrs, "landscape:", kind, parent_kind);
2346− let portrait = attrs_to_css(attrs, "portrait:", kind, parent_kind);
2348− // Dedupe: if a property is declared twice within a single rule, keep only
2349− // the last occurrence (element-kind defaults are written before
2350− // user attributes, so a user [list-style disc] correctly overrides the
2351− // default list-style:none, and we don't need to ship both).
2352− let base = dedupe_declarations(&base);
2353− let pseudo: Vec<(String, String)> = pseudo
2355− .map(|(sel, css)| (sel, dedupe_declarations(&css)))
2357− let responsive: Vec<(String, String)> = responsive
2359− .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2361− let dark = dedupe_declarations(&dark);
2362− let print = dedupe_declarations(&print);
2363− let motion_safe = dedupe_declarations(&motion_safe);
2364− let motion_reduce = dedupe_declarations(&motion_reduce);
2365− let landscape = dedupe_declarations(&landscape);
2366− let portrait = dedupe_declarations(&portrait);
2367− let container: Vec<(String, String)> = container
2369− .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2386/// Dedupe CSS declarations within a single rule body: for any property
1623/// Dedupe CSS declarations within a single rule body: for any property
2387/// declared more than once, keep only the last occurrence. Unparseable
1624/// declared more than once, keep only the last occurrence. Unparseable
2388−/// segments (no `:`) are preserved as-is. Semicolons inside parentheses are
1625+/// segments (no `:`) are preserved as-is. Semicolons inside parentheses or
2389−/// treated as part of a value, not as declaration separators.
1626+/// quoted strings are treated as part of a value, not as declaration
2390fn dedupe_declarations(css: &str) -> String {
1628fn dedupe_declarations(css: &str) -> String {
2391 if css.is_empty() {
1629 if css.is_empty() {
2392 return String::new();
1630 return String::new();
@@ -2401,8 +1639,26 @@ fn dedupe_declarations(css: &str) -> String {
2401 let mut decls: Vec<(Option<String>, String)> = Vec::new();
1639 let mut decls: Vec<(Option<String>, String)> = Vec::new();
2402 let mut current = String::new();
1640 let mut current = String::new();
2403 let mut depth: i32 = 0;
1641 let mut depth: i32 = 0;
1642+ // A quoted string's `;` (`content "a;b"`) is text; a backslash escapes
1643+ // the character after it
1644+ let mut quote: Option<char> = None;
1645+ let mut escaped = false;
2404 for ch in css.chars() {
1646 for ch in css.chars() {
2405− if ch == '(' {
1647+ if escaped {
1650+ } else if ch == '\\' {
1653+ } else if let Some(q) = quote {
1658+ } else if ch == '"' || ch == '\'' {
1661+ } else if ch == '(' {
2406 depth += 1;
1662 depth += 1;
2407 current.push(ch);
1663 current.push(ch);
2408 } else if ch == ')' {
1664 } else if ch == ')' {
@@ -2436,1724 +1692,647 @@ fn dedupe_declarations(css: &str) -> String {
2438 // Find index of last occurrence of each property.
1694 // Find index of last occurrence of each property.
2439− use std::collections::HashMap;
1695+ use std::collections::HashMap;
2440− let mut last: HashMap<String, usize> = HashMap::new();
1696+ let mut last: HashMap<String, usize> = HashMap::new();
2441− for (i, (prop, _)) in decls.iter().enumerate() {
1697+ for (i, (prop, _)) in decls.iter().enumerate() {
2442− if let Some(p) = prop {
1698+ if let Some(p) = prop {
2443− last.insert(p.clone(), i);
1699+ last.insert(p.clone(), i);
2447− let mut out = String::with_capacity(css.len());
2448− for (i, (prop, raw)) in decls.iter().enumerate() {
2449− let keep = match prop {
2450− Some(p) => last.get(p) == Some(&i),
2460−fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option<&str>) {
2461− match (gen_class, user_class) {
2462− (Some(g), Some(u)) => {
2463− out.push_str(" class=\"");
2466− out.push_str(&html_escape(u));
2469− (Some(g), None) => {
2470− out.push_str(" class=\"");
2474− (None, Some(u)) => {
2475− out.push_str(" class=\"");
2476− out.push_str(&html_escape(u));
2483−// ---------------------------------------------------------------------------
2484−// Attribute → CSS mapping
2485−// ---------------------------------------------------------------------------
2487−/// (htmlang prefix, CSS selector suffix)
2488−const PSEUDO_PREFIXES: &[(&str, &str)] = &[
2489− ("hover:", ":hover"),
2490− ("active:", ":active"),
2491− ("focus:", ":focus"),
2492− ("focus-visible:", ":focus-visible"),
2493− ("focus-within:", ":focus-within"),
2494− ("disabled:", ":disabled"),
2495− ("checked:", ":checked"),
2496− ("placeholder:", "::placeholder"),
2497− ("first:", ":first-child"),
2498− ("last:", ":last-child"),
2499− ("odd:", ":nth-child(odd)"),
2500− ("even:", ":nth-child(even)"),
2501− ("before:", "::before"),
2502− ("after:", "::after"),
2503− ("selection:", "::selection"),
2504− ("visited:", ":visited"),
2505− ("empty:", ":empty"),
2506− ("target:", ":target"),
2507− ("valid:", ":valid"),
2508− ("invalid:", ":invalid"),
2510−const RESPONSIVE_PREFIXES: &[&str] = &["sm:", "md:", "lg:", "xl:", "2xl:"];
2511−const MEDIA_PREFIXES: &[&str] = &[
2519−const CONTAINER_QUERY_PREFIXES: &[&str] = &["cq-sm:", "cq-md:", "cq-lg:", "cq-xl:", "cq-2xl:"];
2521−fn is_prefixed_attr(key: &str) -> bool {
2522− PSEUDO_PREFIXES.iter().any(|&(p, _)| key.starts_with(p))
2523− || RESPONSIVE_PREFIXES.iter().any(|p| key.starts_with(p))
2524− || MEDIA_PREFIXES.iter().any(|p| key.starts_with(p))
2525− || CONTAINER_QUERY_PREFIXES.iter().any(|p| key.starts_with(p))
2526− || key.starts_with("nth:")
2527− || key.starts_with("has(")
2530−/// `display:flex;flex-direction:column;` — base layout for `@el` and every
2531−/// semantic wrapper that behaves like a column.
2532−const FLEX_COLUMN: &str = "display:flex;flex-direction:column;";
2534−/// Font stack shared by `@pre`, `@code`, `@kbd`.
2535−const MONOSPACE_STACK: &str = "font-family:ui-monospace,monospace;";
2537−/// Declarations common to `@badge` and `@tag`. They differ only in
2538−/// `border-radius` (and `@badge` additionally centers content / pins
2539−/// line-height:1), so keeping the shared base here avoids drift.
2540−const PILL_BASE: &str =
2541− "display:inline-flex;align-items:center;padding:2px 8px;font-size:0.75rem;font-weight:600;";
2544− attrs: &[Attribute],
2545− state_prefix: &str,
2546− kind: &ElementKind,
2547− parent_kind: Option<&ElementKind>,
2549− let mut css = String::new();
2551− // Base element styles only for the default (non-state) pass
2552− if state_prefix.is_empty() {
2554− ElementKind::Row => css.push_str("display:flex;flex-direction:row;"),
2555− ElementKind::Column
2557− // Semantic elements get flex column layout like @el
2559− | ElementKind::Header
2560− | ElementKind::Footer
2561− | ElementKind::Main
2562− | ElementKind::Section
2563− | ElementKind::Article
2564− | ElementKind::Aside
2565− | ElementKind::ListItem
2566− | ElementKind::Form
2567− | ElementKind::Details
2568− | ElementKind::Dialog => css.push_str(FLEX_COLUMN),
2569− ElementKind::Paragraph
2575− | ElementKind::H6 => css.push_str("margin:0;"),
2576− // Lists: reset browser defaults
2577− ElementKind::List => css.push_str("margin:0;padding-left:0;list-style:none;"),
2578− // Figure / Blockquote: flex column with browser margin reset
2579− ElementKind::Figure | ElementKind::Blockquote => {
2580− css.push_str(FLEX_COLUMN);
2581− css.push_str("margin:0;");
2583− // Pre: preserve whitespace
2584− ElementKind::Pre => {
2585− css.push_str("margin:0;white-space:pre;");
2586− css.push_str(MONOSPACE_STACK);
2588− // Code / Kbd: monospace font
2589− ElementKind::Code | ElementKind::Kbd => css.push_str(MONOSPACE_STACK),
2590− ElementKind::DefinitionList => css.push_str("margin:0;"),
2591− ElementKind::DefinitionDescription => {
2592− css.push_str("margin:0;");
2593− css.push_str(FLEX_COLUMN);
2595− ElementKind::Fieldset => {
2596− css.push_str(FLEX_COLUMN);
2597− // Align padding to the px-based scale used by Badge/Tag/Chip
2598− // rather than the old 0.5em (which depended on font-size).
2599− css.push_str("border:1px solid currentColor;padding:8px;margin:0;");
2601− ElementKind::Grid => css.push_str("display:grid;"),
2602− ElementKind::Stack => css.push_str("position:relative;"),
2603− ElementKind::Badge => {
2604− css.push_str(PILL_BASE);
2605− css.push_str("justify-content:center;border-radius:9999px;line-height:1;");
2607− ElementKind::Tag => {
2608− css.push_str(PILL_BASE);
2609− css.push_str("border-radius:4px;");
2611− ElementKind::Tooltip => css.push_str("position:relative;cursor:help;"),
2612− ElementKind::Spacer => css.push_str("flex:1;"),
2613− ElementKind::Avatar => css.push_str("display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;overflow:hidden;flex-shrink:0;"),
2614− 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;"),
2615− 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;"),
2618− // Children of @carousel get scroll-snap-align and flex-shrink
2619− if matches!(parent_kind, Some(ElementKind::Carousel)) {
2620− css.push_str("scroll-snap-align:start;flex-shrink:0;");
2624− for attr in attrs {
2625− // Determine the effective key for this pass
2626− let effective_key = if state_prefix.is_empty() {
2627− if is_prefixed_attr(&attr.key) {
2632− match attr.key.strip_prefix(state_prefix) {
2638− let val = attr.value.as_deref();
2640− match effective_key {
2642− "spacing" | "gap" => {
2643− if let Some(v) = val {
2644− push_css(&mut css, "gap", &css_px(v));
2648− if let Some(v) = val {
2649− push_css(&mut css, "padding", &css_px_multi(v));
2653− if let Some(v) = val {
2654− // Logical property covers both inline sides in one
2655− // declaration; for symmetric values this is visually
2656− // identical to padding-left/right in LTR and RTL.
2657− push_css(&mut css, "padding-inline", &css_px(v));
2661− if let Some(v) = val {
2662− push_css(&mut css, "padding-block", &css_px(v));
2666− if let Some(v) = val {
2667− push_css(&mut css, "padding-top", &css_px(v));
2670− "padding-bottom" => {
2671− if let Some(v) = val {
2672− push_css(&mut css, "padding-bottom", &css_px(v));
2675− "padding-left" => {
2676− if let Some(v) = val {
2677− push_css(&mut css, "padding-left", &css_px(v));
2680− "padding-right" => {
2681− if let Some(v) = val {
2682− push_css(&mut css, "padding-right", &css_px(v));
2688− if let Some(v) = val {
2690− "fill" => match parent_kind {
2691− Some(ElementKind::Row) => {
2692− push_css(&mut css, "flex", "1");
2693− push_css(&mut css, "min-width", "0");
2695− _ => push_css(&mut css, "width", "100%"),
2697− "shrink" => push_css(&mut css, "flex-shrink", "0"),
2698− _ => push_css(&mut css, "width", &css_px(v)),
2703− if let Some(v) = val {
2705− "fill" => match parent_kind {
2706− Some(ElementKind::Column) => {
2707− push_css(&mut css, "flex", "1");
2708− push_css(&mut css, "min-height", "0");
2710− _ => push_css(&mut css, "height", "100%"),
2712− "shrink" => push_css(&mut css, "flex-shrink", "0"),
2713− _ => push_css(&mut css, "height", &css_px(v)),
2718− if let Some(v) = val {
2719− push_css(&mut css, "min-width", &css_px(v));
2723− if let Some(v) = val {
2724− push_css(&mut css, "max-width", &css_px(v));
2728− if let Some(v) = val {
2729− push_css(&mut css, "min-height", &css_px(v));
2733− if let Some(v) = val {
2734− push_css(&mut css, "max-height", &css_px(v));
2739− "center-x" => match parent_kind {
2740− Some(ElementKind::Column) | Some(ElementKind::El) => {
2741− push_css(&mut css, "align-self", "center");
2744− push_css(&mut css, "margin-left", "auto");
2745− push_css(&mut css, "margin-right", "auto");
2748− "center-y" => match parent_kind {
2749− Some(ElementKind::Row) => push_css(&mut css, "align-self", "center"),
2751− push_css(&mut css, "margin-top", "auto");
2752− push_css(&mut css, "margin-bottom", "auto");
2755− "align-left" => match parent_kind {
2756− Some(ElementKind::Column) | Some(ElementKind::El) => {
2757− push_css(&mut css, "align-self", "flex-start");
2759− _ => push_css(&mut css, "margin-right", "auto"),
2761− "align-right" => match parent_kind {
2762− Some(ElementKind::Column) | Some(ElementKind::El) => {
2763− push_css(&mut css, "align-self", "flex-end");
2765− _ => push_css(&mut css, "margin-left", "auto"),
2767− "align-top" => match parent_kind {
2768− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-start"),
2769− _ => push_css(&mut css, "margin-bottom", "auto"),
2771− "align-bottom" => match parent_kind {
2772− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-end"),
2773− _ => push_css(&mut css, "margin-top", "auto"),
2778− if let Some(v) = val {
2779− push_css(&mut css, "background", v);
2783− if let Some(v) = val {
2784− push_css(&mut css, "color", v);
2788− if let Some(v) = val {
2789− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2790− if parts.len() == 2 {
2794− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2800− &format!("{} solid currentColor", css_px(parts[0])),
2805− "border-top" | "border-bottom" | "border-left" | "border-right" => {
2806− if let Some(v) = val {
2807− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2808− if parts.len() == 2 {
2812− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2818− &format!("{} solid currentColor", css_px(parts[0])),
2824− if let Some(v) = val {
2825− push_css(&mut css, "border-radius", &css_px(v));
2828− "bold" => push_css(&mut css, "font-weight", "bold"),
2829− "italic" => push_css(&mut css, "font-style", "italic"),
2830− "underline" => push_css(&mut css, "text-decoration", "underline"),
2832− if let Some(v) = val {
2833− push_css(&mut css, "font-size", &css_px(v));
2837− if let Some(v) = val {
2838− push_css(&mut css, "font-family", v);
2842− if let Some(v) = val {
2843− push_css(&mut css, "transition", v);
2847− if let Some(v) = val {
2848− push_css(&mut css, "cursor", v);
2852− if let Some(v) = val {
2853− push_css(&mut css, "opacity", v);
2859− if let Some(v) = val {
2860− push_css(&mut css, "text-align", v);
2864− if let Some(v) = val {
2865− push_css(&mut css, "line-height", &css_line_height(v));
2868− "letter-spacing" => {
2869− if let Some(v) = val {
2870− push_css(&mut css, "letter-spacing", &css_px(v));
2873− "text-transform" => {
2874− if let Some(v) = val {
2875− push_css(&mut css, "text-transform", v);
2879− if let Some(v) = val {
2880− push_css(&mut css, "white-space", v);
2884− // Overflow & positioning
2886− if let Some(v) = val {
2887− push_css(&mut css, "overflow", v);
2891− if let Some(v) = val {
2892− push_css(&mut css, "position", v);
2896− if let Some(v) = val {
2897− push_css(&mut css, "top", &css_px(v));
2901− if let Some(v) = val {
2902− push_css(&mut css, "right", &css_px(v));
2906− if let Some(v) = val {
2907− push_css(&mut css, "bottom", &css_px(v));
2911− if let Some(v) = val {
2912− push_css(&mut css, "left", &css_px(v));
2916− if let Some(v) = val {
2917− push_css(&mut css, "z-index", v);
2921− // Display & visibility
2923− if let Some(v) = val {
2924− push_css(&mut css, "display", v);
2928− if let Some(v) = val {
2929− push_css(&mut css, "visibility", v);
2932− "hidden" => push_css(&mut css, "display", "none"),
2934− // Transform & filters
2936− if let Some(v) = val {
2937− push_css(&mut css, "transform", v);
2940− "backdrop-filter" => {
2941− if let Some(v) = val {
2942− push_css(&mut css, "backdrop-filter", v);
2948− if let Some(v) = val {
2949− push_css(&mut css, "box-shadow", v);
2954− "wrap" => push_css(&mut css, "flex-wrap", "wrap"),
2956− if let Some(v) = val {
2957− push_css(&mut css, "column-gap", &css_px(v));
2961− if let Some(v) = val {
2962− push_css(&mut css, "row-gap", &css_px(v));
2968− push_css(&mut css, "display", "grid");
2971− if let Some(v) = val {
2972− if let Ok(n) = v.parse::<u32>() {
2975− "grid-template-columns",
2976− &format!("repeat({},1fr)", n),
2979− push_css(&mut css, "grid-template-columns", v);
2984− if let Some(v) = val {
2985− if let Ok(n) = v.parse::<u32>() {
2988− "grid-template-rows",
2989− &format!("repeat({},1fr)", n),
2992− push_css(&mut css, "grid-template-rows", v);
2997− if let Some(v) = val {
2998− push_css(&mut css, "grid-column", &format!("span {}", v));
3002− if let Some(v) = val {
3003− push_css(&mut css, "grid-row", &format!("span {}", v));
3009− if let Some(v) = val {
3010− push_css(&mut css, "animation", v);
3015− "aspect-ratio" => {
3016− if let Some(v) = val {
3017− push_css(&mut css, "aspect-ratio", v);
3021− // CSS containment for rendering performance
3023− if let Some(v) = val {
3024− push_css(&mut css, "contain", v);
3026− push_css(&mut css, "contain", "layout style paint");
3029− "content-visibility" => {
3030− if let Some(v) = val {
3031− push_css(&mut css, "content-visibility", v);
3033− push_css(&mut css, "content-visibility", "auto");
3037− // Outline (like border but doesn't affect layout)
3039− if let Some(v) = val {
3040− let parts: Vec<&str> = v.splitn(2, ' ').collect();
3041− if parts.len() == 2 {
3045− &format!("{} solid {}", css_px(parts[0]), parts[1]),
3051− &format!("{} solid currentColor", css_px(parts[0])),
3057− // Logical properties (i18n-aware)
3058− "padding-inline" => {
3059− if let Some(v) = val {
3060− push_css(&mut css, "padding-inline", &css_px_multi(v));
3063− "padding-block" => {
3064− if let Some(v) = val {
3065− push_css(&mut css, "padding-block", &css_px_multi(v));
3068− "margin-inline" => {
3069− if let Some(v) = val {
3070− push_css(&mut css, "margin-inline", &css_px_multi(v));
3073− "margin-block" => {
3074− if let Some(v) = val {
3075− push_css(&mut css, "margin-block", &css_px_multi(v));
3079− // Logical property start/end variants
3080− "padding-inline-start"
3081− | "padding-inline-end"
3082− | "padding-block-start"
3083− | "padding-block-end"
3084− | "margin-inline-start"
3085− | "margin-inline-end"
3086− | "margin-block-start"
3087− | "margin-block-end" => {
3088− if let Some(v) = val {
3089− push_css(&mut css, effective_key, &css_px(v));
3094− "inset-inline" | "inset-block" => {
3095− if let Some(v) = val {
3096− push_css(&mut css, effective_key, &css_px_multi(v));
3099− "inset-inline-start" | "inset-inline-end" | "inset-block-start" | "inset-block-end" => {
3100− if let Some(v) = val {
3101− push_css(&mut css, effective_key, &css_px(v));
3108− | "border-inline-start"
3109− | "border-inline-end"
3110− | "border-block-start"
3111− | "border-block-end" => {
3112− if let Some(v) = val {
3113− push_css(&mut css, effective_key, v);
3117− // Logical border-radius
3118− "border-start-start-radius"
3119− | "border-start-end-radius"
3120− | "border-end-start-radius"
3121− | "border-end-end-radius" => {
3122− if let Some(v) = val {
3123− push_css(&mut css, effective_key, &css_px(v));
3127− // Logical scroll margins & padding
3128− "scroll-margin-inline"
3129− | "scroll-margin-block"
3130− | "scroll-padding-inline"
3131− | "scroll-padding-block" => {
3132− if let Some(v) = val {
3133− push_css(&mut css, effective_key, &css_px_multi(v));
3138− "inline-size" | "block-size" | "min-inline-size" | "max-inline-size"
3139− | "min-block-size" | "max-block-size" => {
3140− if let Some(v) = val {
3141− push_css(&mut css, effective_key, &css_px(v));
3146− "scroll-snap-type" => {
3147− if let Some(v) = val {
3148− push_css(&mut css, "scroll-snap-type", v);
3151− "scroll-snap-align" => {
3152− if let Some(v) = val {
3153− push_css(&mut css, "scroll-snap-align", v);
3159− if let Some(v) = val {
3160− push_css(&mut css, "margin", &css_px_multi(v));
3164− if let Some(v) = val {
3165− push_css(&mut css, "margin-inline", &css_px(v));
3169− if let Some(v) = val {
3170− push_css(&mut css, "margin-block", &css_px(v));
3176− if let Some(v) = val {
3177− push_css(&mut css, "filter", v);
3181− // Object fit/position (for images)
3183− if let Some(v) = val {
3184− push_css(&mut css, "object-fit", v);
3187− "object-position" => {
3188− if let Some(v) = val {
3189− push_css(&mut css, "object-position", v);
3195− if let Some(v) = val {
3196− push_css(&mut css, "text-shadow", v);
3201− "text-overflow" => {
3202− if let Some(v) = val {
3203− push_css(&mut css, "text-overflow", v);
3208− "pointer-events" => {
3209− if let Some(v) = val {
3210− push_css(&mut css, "pointer-events", v);
3214− if let Some(v) = val {
3215− push_css(&mut css, "user-select", v);
3219− // Flexbox/grid alignment
3220− "justify-content" => {
3221− if let Some(v) = val {
3222− push_css(&mut css, "justify-content", v);
3226− if let Some(v) = val {
3227− push_css(&mut css, "align-items", v);
3233− if let Some(v) = val {
3234− push_css(&mut css, "order", v);
3238− // Background extras
3239− "background-size" => {
3240− if let Some(v) = val {
3241− push_css(&mut css, "background-size", v);
3244− "background-position" => {
3245− if let Some(v) = val {
3246− push_css(&mut css, "background-position", v);
3249− "background-repeat" => {
3250− if let Some(v) = val {
3251− push_css(&mut css, "background-repeat", v);
3257− if let Some(v) = val {
3258− push_css(&mut css, "word-break", v);
3261− "overflow-wrap" => {
3262− if let Some(v) = val {
3263− push_css(&mut css, "overflow-wrap", v);
3267− // Container queries
3269− push_css(&mut css, "container-type", "inline-size");
3271− "container-name" => {
3272− if let Some(v) = val {
3273− push_css(&mut css, "container-name", v);
3276− "container-type" => {
3277− if let Some(v) = val {
3278− push_css(&mut css, "container-type", v);
3284− if let Some(v) = val {
3285− push_css(&mut css, "overflow-x", v);
3289− if let Some(v) = val {
3290− push_css(&mut css, "overflow-y", v);
3294− // Inset (shorthand for top/right/bottom/left)
3296− if let Some(v) = val {
3297− push_css(&mut css, "inset", &css_px(v));
3301− // Accent & caret colors
3302− "accent-color" => {
3303− if let Some(v) = val {
3304− push_css(&mut css, "accent-color", v);
3308− if let Some(v) = val {
3309− push_css(&mut css, "caret-color", v);
3313− // Color scheme & appearance
3314− "color-scheme" => {
3315− if let Some(v) = val {
3316− push_css(&mut css, "color-scheme", v);
3320− if let Some(v) = val {
3321− push_css(&mut css, "appearance", v);
3327− if let Some(v) = val {
3328− push_css(&mut css, "list-style", v);
3333− "border-collapse" => {
3334− if let Some(v) = val {
3335− push_css(&mut css, "border-collapse", v);
3338− "border-spacing" => {
3339− if let Some(v) = val {
3340− push_css(&mut css, "border-spacing", &css_px(v));
3345− "text-decoration" => {
3346− if let Some(v) = val {
3347− push_css(&mut css, "text-decoration", v);
3350− "text-decoration-color" => {
3351− if let Some(v) = val {
3352− push_css(&mut css, "text-decoration-color", v);
3355− "text-decoration-thickness" => {
3356− if let Some(v) = val {
3357− push_css(&mut css, "text-decoration-thickness", &css_px(v));
3360− "text-decoration-style" => {
3361− if let Some(v) = val {
3362− push_css(&mut css, "text-decoration-style", v);
3365− "text-underline-offset" => {
3366− if let Some(v) = val {
3367− push_css(&mut css, "text-underline-offset", &css_px(v));
3372− "column-width" => {
3373− if let Some(v) = val {
3374− push_css(&mut css, "column-width", &css_px(v));
3378− if let Some(v) = val {
3379− push_css(&mut css, "column-rule", v);
3383− // Place items/self
3385− if let Some(v) = val {
3386− push_css(&mut css, "place-items", v);
3390− if let Some(v) = val {
3391− push_css(&mut css, "place-self", v);
3396− "scroll-behavior" => {
3397− if let Some(v) = val {
3398− push_css(&mut css, "scroll-behavior", v);
3404− if let Some(v) = val {
3405− push_css(&mut css, "resize", v);
3409− // New CSS properties
3411− if let Some(v) = val {
3412− push_css(&mut css, "clip-path", v);
3415− "mix-blend-mode" => {
3416− if let Some(v) = val {
3417− push_css(&mut css, "mix-blend-mode", v);
3420− "background-blend-mode" => {
3421− if let Some(v) = val {
3422− push_css(&mut css, "background-blend-mode", v);
3425− "writing-mode" => {
3426− if let Some(v) = val {
3427− push_css(&mut css, "writing-mode", v);
3430− "column-count" => {
3431− if let Some(v) = val {
3432− push_css(&mut css, "column-count", v);
3436− if let Some(v) = val {
3437− push_css(&mut css, "column-gap", &css_px(v));
3441− if let Some(v) = val {
3442− push_css(&mut css, "text-indent", &css_px(v));
3446− if let Some(v) = val {
3447− push_css(&mut css, "hyphens", v);
3451− if let Some(v) = val {
3452− push_css(&mut css, "flex-grow", v);
3456− if let Some(v) = val {
3457− push_css(&mut css, "flex-shrink", v);
3461− if let Some(v) = val {
3462− push_css(&mut css, "flex-basis", &css_px(v));
3466− if let Some(v) = val {
3467− push_css(&mut css, "isolation", v);
3470− "place-content" => {
3471− if let Some(v) = val {
3472− push_css(&mut css, "place-content", v);
3475− "background-image" => {
3476− if let Some(v) = val {
3477− push_css(&mut css, "background-image", v);
3481− if let Some(v) = val {
3482− push_css(&mut css, "font-weight", v);
3486− if let Some(v) = val {
3487− push_css(&mut css, "font-style", v);
3491− if let Some(v) = val {
3492− push_css(&mut css, "text-wrap", v);
3496− if let Some(v) = val {
3497− push_css(&mut css, "will-change", v);
3500− "touch-action" => {
3501− if let Some(v) = val {
3502− push_css(&mut css, "touch-action", v);
3505− "vertical-align" => {
3506− if let Some(v) = val {
3507− push_css(&mut css, "vertical-align", v);
3510− "scroll-margin" => {
3511− if let Some(v) = val {
3512− push_css(&mut css, "scroll-margin", &css_px(v));
3515− "scroll-margin-top"
3516− | "scroll-margin-bottom"
3517− | "scroll-margin-left"
3518− | "scroll-margin-right" => {
3519− if let Some(v) = val {
3520− push_css(&mut css, effective_key, &css_px(v));
3523− "scroll-padding" => {
3524− if let Some(v) = val {
3525− push_css(&mut css, "scroll-padding", &css_px(v));
3528− "scroll-padding-top"
3529− | "scroll-padding-bottom"
3530− | "scroll-padding-left"
3531− | "scroll-padding-right" => {
3532− if let Some(v) = val {
3533− push_css(&mut css, effective_key, &css_px(v));
3537− if let Some(v) = val {
3538− push_css(&mut css, "direction", v);
3543− if let Some(v) = val {
3544− // Wrap in quotes if not already quoted and not a CSS keyword
3545− if v.starts_with('"')
3546− || v.starts_with('\'')
3549− || v.starts_with("attr(")
3550− || v.starts_with("counter(")
3552− push_css(&mut css, "content", v);
3554− push_css(&mut css, "content", &format!("\"{}\"", v));
3559− // --- CSS Shorthands ---
3561− push_css(&mut css, "overflow", "hidden");
3562− push_css(&mut css, "text-overflow", "ellipsis");
3563− push_css(&mut css, "white-space", "nowrap");
3566− if let Some(v) = val {
3567− push_css(&mut css, "display", "-webkit-box");
3568− push_css(&mut css, "-webkit-line-clamp", v);
3569− push_css(&mut css, "-webkit-box-orient", "vertical");
3570− push_css(&mut css, "overflow", "hidden");
3574− if let Some(v) = val {
3575− push_css(&mut css, "filter", &format!("blur({})", css_px(v)));
3578− "backdrop-blur" => {
3579− if let Some(v) = val {
3580− push_css(&mut css, "backdrop-filter", &format!("blur({})", css_px(v)));
3583− "no-scrollbar" => {
3584− push_css(&mut css, "scrollbar-width", "none");
3585− push_css(&mut css, "-ms-overflow-style", "none");
3591− "linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%)",
3593− push_css(&mut css, "background-size", "200% 100%");
3597− "hl-skeleton 1.5s ease-in-out infinite",
3601− if let Some(v) = val {
3602− // Parse: "from to [angle]" or "color1 color2 [angle]"
3603− let parts: Vec<&str> = v.split_whitespace().collect();
3604− let bg = if parts.len() >= 3
3605− && (parts[2].ends_with("deg")
3606− || parts[2].ends_with("turn")
3607− || parts[2].ends_with("rad"))
3609− format!("linear-gradient({},{},{})", parts[2], parts[0], parts[1])
3610− } else if parts.len() >= 2 {
3611− format!("linear-gradient({},{})", parts[0], parts[1])
3613− format!("linear-gradient({},transparent)", parts[0])
3615− push_css(&mut css, "background", &bg);
3620− "grid-template-areas" => {
3621− if let Some(v) = val {
3622− push_css(&mut css, "grid-template-areas", v);
3626− if let Some(v) = val {
3627− push_css(&mut css, "grid-area", v);
3631− // View transitions
3632− "view-transition-name" => {
3633− if let Some(v) = val {
3634− push_css(&mut css, "view-transition-name", v);
3638− // Animate shorthand (alias for animation)
3640− if let Some(v) = val {
3641− push_css(&mut css, "animation", v);
3646− "grid-template-columns" => {
3647− if let Some(v) = val {
3648− push_css(&mut css, "grid-template-columns", v);
3651− "grid-template-rows" => {
3652− if let Some(v) = val {
3653− push_css(&mut css, "grid-template-rows", v);
3657− // Scroll-driven animations
3658− "animation-timeline" => {
3659− if let Some(v) = val {
3660− push_css(&mut css, "animation-timeline", v);
3663− "animation-range" => {
3664− if let Some(v) = val {
3665− push_css(&mut css, "animation-range", v);
3668− "view-timeline-name" => {
3669− if let Some(v) = val {
3670− push_css(&mut css, "view-timeline-name", v);
3673− "view-timeline-axis" => {
3674− if let Some(v) = val {
3675− push_css(&mut css, "view-timeline-axis", v);
3678− "scroll-timeline-name" => {
3679− if let Some(v) = val {
3680− push_css(&mut css, "scroll-timeline-name", v);
3683− "scroll-timeline-axis" => {
3684− if let Some(v) = val {
3685− push_css(&mut css, "scroll-timeline-axis", v);
3689− // Anchor positioning
3691− if let Some(v) = val {
3692− push_css(&mut css, "anchor-name", v);
3695− "position-anchor" => {
3696− if let Some(v) = val {
3697− push_css(&mut css, "position-anchor", v);
3700− "position-area" => {
3701− if let Some(v) = val {
3702− push_css(&mut css, "position-area", v);
3706− // Legacy alias for position-area
3707− if let Some(v) = val {
3708− push_css(&mut css, "position-area", v);
3712− // initial-letter (drop caps)
3713− "initial-letter" => {
3714− if let Some(v) = val {
3715− push_css(&mut css, "initial-letter", v);
3719− // Critical CSS hint — not CSS, handled elsewhere
1703+ let mut out = String::with_capacity(css.len());
3720− "critical" => {}
1704+ for (i, (prop, raw)) in decls.iter().enumerate() {
3721−
1705+ let keep = match prop {
3722− // Identity and HTML passthrough — not CSS
1706+ Some(p) => last.get(p) == Some(&i),
3723− "id" | "class" => {}
1707+ None => true,
3724− "type" | "placeholder" | "name" | "value" | "disabled" | "required" | "checked"
1708+ };
3725− | "for" | "action" | "method" | "autocomplete" | "min" | "max" | "step" | "pattern"
1709+ if keep {
3726− | "maxlength" | "rows" | "cols" | "multiple" | "alt" | "role" | "tabindex"
1710+ out.push_str(raw);
3727− | "title" | "controls" | "autoplay" | "loop" | "muted" | "playsinline" | "poster"
1711+ }
3728− | "preload" | "loading" | "decoding" | "ordered" | "src" | "open" | "novalidate"
1712+ }
3729− | "low" | "high" | "optimum" | "colspan" | "rowspan" | "scope" | "inline"
1713+ out
3730− | "responsive" | "datetime" | "media" | "sizes" | "srcset" | "cite" | "list"
1714+}
3731− | "sandbox" | "allow" | "allowfullscreen" | "referrerpolicy" | "formaction"
3732− | "formmethod" | "formtarget" | "target" | "autofocus" => {}
3734− _ => {}
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=\"");
1722+ out.push_str(&html_escape(u));
1725+ (Some(g), None) => {
1726+ out.push_str(" class=\"");
1730+ (None, Some(u)) => {
1731+ out.push_str(" class=\"");
1732+ out.push_str(&html_escape(u));
3738− css
1739+// ---------------------------------------------------------------------------
1740+// Attribute → CSS mapping
1741+// ---------------------------------------------------------------------------
1743+/// Where an element is written, which its CSS depends on.
1745+ kind: &'a ElementKind,
1746+ /// How its parent lays out its children: its `width fill`, `height
1747+ /// fill` and `shrink` compile against it.
1749+ /// It has `@in-front` / `@behind` children.
1750+ has_overlay_children: bool,
1751+ /// A row, column or grid inside text, laid out inline.
1753+ /// The page's `<body>`, which the reset already makes a column.
3741−fn push_css(css: &mut String, prop: &str, value: &str) {
1757+impl Site<'_> {
3742− css.push_str(prop);
1758+ /// Where an element in a parent with the layout `layout` and the flow
3743− css.push(':');
1759+ /// `parent` is.
3744− css.push_str(value);
1760+ fn new<'a>(elem: &'a Element, layout: Option<Layout>, parent: &'a Flow) -> Site<'a> {
3745− css.push(';');
1761+ Site {
1764+ has_overlay_children: has_overlay_children(elem),
1765+ inline: layout == Some(Layout::Text) && elem.kind.layout().is_container(),
3748−/// Known CSS units — if a value ends with one, skip appending `px`.
1771+// ---------------------------------------------------------------------------
3749−const CSS_UNITS: &[&str] = &[
1772+// Direction: what a child's `fill` and `shrink` compile against
3750− "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh", "ch", "ex", "cm", "mm",
1773+// ---------------------------------------------------------------------------
3751− "in", "pt", "pc", "fr",
3754−/// Format a numeric value: if it already has a CSS unit, pass through as-is;
1775+/// The way a flex row or column lays out its children.
3755−/// otherwise append `px`.
1776+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
3756−fn css_px(value: &str) -> String {
1777+enum Axis {
3757− let v = value.trim();
1778+ Row,
3758− if v == "0" {
1779+ Column,
3759− return "0".to_string();
3761− if CSS_UNITS.iter().any(|u| v.ends_with(u)) {
3762− return v.to_string();
3764− if v.starts_with("var(")
3765− || v.starts_with("calc(")
3766− || v.starts_with("clamp(")
3767− || v.starts_with("min(")
3768− || v.starts_with("max(")
3770− return v.to_string();
3775−/// Rewrite literal values that match a declared CSS custom property (from
1782+impl Axis {
3776−/// `@theme` or `@let --name value`) to `var(--name)` references. Matches are
1783+ /// The direction a `flex-direction` or `flex-flow` value sets, if it
3777−/// anchored to CSS value boundaries so e.g. `#3b82f6` inside a longer hex or
1784+ /// names one (not `var(--dir)`, which only the browser knows).
3778−/// inside an identifier is not replaced. The `:root` block is emitted before
1785+ fn of_value(value: &str) -> Option<Axis> {
3779−/// this call runs, so its declarations are not affected.
1786+ value.split_whitespace().find_map(|word| match word {
3780−fn substitute_css_vars(css: &str, vars: &[(String, String)]) -> String {
1787+ "row" | "row-reverse" => Some(Axis::Row),
3781− if css.is_empty() || vars.is_empty() {
1788+ "column" | "column-reverse" => Some(Axis::Column),
3782− return css.to_string();
1789+ _ => None,
3784− // Prefer longer values first so that if two vars share a prefix, the
3785− // longer (more specific) match wins.
3786− let mut pairs: Vec<(&str, String)> = vars
3788− .filter(|(name, value)| name.starts_with("--") && !value.is_empty())
3789− .map(|(name, value)| (value.as_str(), format!("var({})", name)))
3791− pairs.sort_by_key(|(v, _)| std::cmp::Reverse(v.len()));
3792− if pairs.is_empty() {
3793− return css.to_string();
3796− let is_boundary_before = |b: Option<u8>| match b {
1794+/// How an element lays out its children, as its CSS sets it: the
3797− None => true,
1795+/// direction its children's `width`/`height` `fill` and `shrink` compile
3798− Some(c) => matches!(c, b':' | b' ' | b',' | b'(' | b';' | b'{' | b'\n' | b'\t'),
1796+/// against. That is the direction of `@row` or of a column, or the one its
3799− };
1797+/// own `flex-direction` (or `flex-flow`) sets, with or without media or
3800− let is_boundary_after = |b: Option<u8>| match b {
1798+/// container prefixes. Like elm-ui's `.r > .wf`, the rules for a direction
3801− None => true,
1799+/// set under a prefix are keyed on the element's class: `@media (...) {
3802− Some(c) => matches!(c, b';' | b'}' | b',' | b' ' | b')' | b'\n' | b'\t'),
1800+/// :where(.a)>.b {...} }`.
3803− };
1801+#[derive(Clone, Default)]
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
1811+ class: Option<String>,
3805− let bytes = css.as_bytes();
1814+impl Flow {
3806− let mut out = String::with_capacity(css.len());
1815+ fn of(elem: &Element) -> Flow {
3807− let mut i = 0;
1816+ let mut base = match elem.kind.layout() {
3808− let mut prev: Option<u8> = None;
1817+ Layout::Row => Axis::Row,
3809− while i < bytes.len() {
1818+ Layout::Column => Axis::Column,
3810− if is_boundary_before(prev) {
1819+ _ => return Flow::default(),
3811− let mut matched = false;
1820+ };
3812− for (val, repl) in &pairs {
1821+ let mut changes: Vec<(Vec<usize>, Axis)> = Vec::new();
3813− let vb = val.as_bytes();
1822+ for attr in elem.attrs.iter().filter(|a| !a.html) {
3814− if i + vb.len() <= bytes.len() && &bytes[i..i + vb.len()] == vb {
1823+ let (condition, name) = Condition::of(&attr.key);
3815− let next = bytes.get(i + vb.len()).copied();
1824+ if !matches!(name, "flex-direction" | "flex-flow") || !condition.selector.is_empty() {
3816− if is_boundary_after(next) {
1825+ continue;
3817− out.push_str(repl);
3818− prev = repl.as_bytes().last().copied();
3825− if matched {
1827+ let Some(axis) = attr.value.as_deref().and_then(Axis::of_value) else {
3826 continue;
1828 continue;
1830+ if condition.at.is_empty() {
1833+ // The later one wins, as in the CSS
1834+ changes.retain(|(at, _)| *at != condition.at);
1835+ changes.push((condition.at, axis));
3829− // Advance by one UTF-8 code point.
1838+ changes.sort_by_key(|(at, _)| at_order(at));
3830− let start = i;
1839+ Flow {
3831− i += 1;
1840+ base: Some(base),
3832− while i < bytes.len() && (bytes[i] & 0xC0) == 0x80 {
1841+ changes,
3833− i += 1;
1842+ class: None,
3835− out.push_str(&css[start..i]);
3836− prev = bytes.get(i - 1).copied();
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);
1856+ .find(|(chain, _)| Condition::at_only(chain).holds_at(&here))
1857+ .map(|&(_, axis)| axis);
1858+ Some(changed.unwrap_or(base))
3841−/// Scan generated CSS for literal property values that repeat often enough
1862+/// `width` or `height`.
3842−/// that substituting them with an auto-named custom property would reduce
1863+#[derive(Clone, Copy, PartialEq, Eq)]
3843−/// total byte count. Returns the rewritten CSS and any new vars that should
1864+enum Dim {
3844−/// be appended to `:root`.
1865+ Width,
3846−/// The algorithm only promotes a value if it strictly saves bytes after
1867+}
3847−/// accounting for the `--xN:value;` declaration overhead plus the
1868+
3848−/// `var(--xN)` reference cost at each call site. Values that are already
1869+/// What a `width` or `height` says.
3849−/// `var(...)` references or contain `var(` calls are skipped so we never
1870+#[derive(Clone, Copy, PartialEq, Eq)]
3850−/// nest references. Names avoid collisions with `existing_vars`.
1871+enum Size {
3851−fn auto_extract_repeats(
1872+ Fill,
3852− css: &str,
1873+ Shrink,
3853− existing_vars: &[(String, String)],
1874+ /// A size of its own (`width 300`)
3854−) -> (String, Vec<(String, String)>) {
1875+ Set,
3855− if css.is_empty() {
1876+}
3856− return (css.to_string(), Vec::new());
1877+
1879+ fn of(value: &str) -> Size {
1880+ match value.trim() {
1881+ "fill" => Size::Fill,
1882+ "shrink" => Size::Shrink,
3858− // Count occurrences of each distinct property value (the text between
1886+}
3859− // `:` and the next `;` or `}` at the top level of a declaration block,
1887+
3860− // ignoring balanced parentheses so that e.g. `rgba(...)` stays intact).
1888+/// The declarations `fill` and `shrink` make in a parent laid out along
3861− let bytes = css.as_bytes();
1889+/// `axis` (`None`: not a flex row or column). Along the parent's direction,
3862− let mut counts: HashMap<String, usize> = HashMap::new();
1890+/// `fill` takes the remaining space and `shrink` keeps the content's size;
3863− let mut depth: i32 = 0;
1891+/// across it (or outside flex), `fill` is the full size and `shrink` fits
3864− let mut i = 0;
1892+/// the content.
3865− while i < bytes.len() {
1893+fn sizing(dim: Dim, size: Size, axis: Option<Axis>) -> &'static [(&'static str, &'static str)] {
3866− match bytes[i] {
1894+ match (dim, size, axis) {
3867− b'{' => {
1895+ (_, Size::Set, _) => &[],
3868− depth += 1;
1896+ (Dim::Width, Size::Fill, Some(Axis::Row)) => &[("flex", "1"), ("min-width", "0")],
3869− i += 1;
1897+ (Dim::Width, Size::Fill, _) => &[("width", "100%")],
3870− continue;
1898+ (Dim::Width, Size::Shrink, Some(Axis::Row)) => &[("flex-shrink", "0")],
3871− }
1899+ (Dim::Width, Size::Shrink, _) => &[("width", "fit-content")],
3872− b'}' => {
1900+ (Dim::Height, Size::Fill, Some(Axis::Column)) => &[("flex", "1"), ("min-height", "0")],
3873− if depth > 0 {
1901+ (Dim::Height, Size::Fill, _) => &[("height", "100%")],
3874− depth -= 1;
1902+ (Dim::Height, Size::Shrink, Some(Axis::Column)) => &[("flex-shrink", "0")],
3875− }
1903+ (Dim::Height, Size::Shrink, _) => &[("height", "fit-content")],
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] {
1912+ ("flex", "0 1 auto"),
1913+ ("min-width", "auto"),
1917+ ("flex", "0 1 auto"),
1918+ ("min-height", "auto"),
1919+ ("height", "auto"),
1924+/// What an element's attributes under some prefixes say about its size.
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)
1934+ /// It writes `flex`, one of its longhands (`flex-grow`, `flex-shrink`,
1935+ /// `flex-basis`), `min-width` or `min-height` itself
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 {
3877 continue;
1953 continue;
1955+ if condition.holds_at(at) {
1956+ read.push((condition, name, value));
1959+ read.sort_by_cached_key(|(condition, _, _)| condition.order());
1960+ for (_, name, value) in read {
1963+ let size = Size::of(value);
1964+ sizes.width = Some(size);
1965+ sizes.width_word |= size != Size::Set;
1968+ let size = Size::of(value);
1969+ sizes.height = Some(size);
1970+ sizes.height_word |= size != Size::Set;
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,
3881− if depth > 0 && bytes[i] == b':' {
1981+ sizes
3882− // Skip past `:` then walk to the terminator.
1982+ }
3883− let start = i + 1;
1983+
3884− let mut end = start;
1984+ /// The element writes `property` itself: a layout word leaves it alone.
3885− let mut pdepth = 0i32;
1985+ fn writes(&self, property: &str) -> bool {
3886− while end < bytes.len() {
1986+ match property {
3887− match bytes[end] {
1987+ "flex" => self.flex,
3888− b'(' => pdepth += 1,
1988+ "flex-grow" => self.flex || self.flex_grow,
3889− b')' => {
1989+ "flex-shrink" => self.flex || self.flex_shrink,
3890− if pdepth > 0 {
1990+ "flex-basis" => self.flex || self.flex_basis,
3891− pdepth -= 1;
1991+ "min-width" => self.min_width,
3892− }
1992+ "min-height" => self.min_height,
1993+ "width" => self.width == Some(Size::Set),
1994+ "height" => self.height == Some(Size::Set),
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
2003+ fn push(&self, css: &mut String, property: &str, value: &str) {
2004+ if property == "flex" && !self.flex {
2005+ let longhands = match value {
2007+ ("flex-grow", "1"),
2008+ ("flex-shrink", "1"),
2009+ ("flex-basis", "0%"),
2011+ // The reset, `0 1 auto`
2013+ ("flex-grow", "0"),
2014+ ("flex-shrink", "1"),
2015+ ("flex-basis", "auto"),
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);
3894− b';' | b'}' if pdepth == 0 => break,
3895− b'{' if pdepth == 0 => break,
3898− end += 1;
2024+ return;
3900− let val = css[start..end].trim();
3901− if !val.is_empty() && !val.starts_with("var(") && !val.contains("var(") {
3902− *counts.entry(val.to_string()).or_default() += 1;
3907− i += 1;
2027+ if !self.writes(property) {
3908− }
2028+ push_css(css, property, value);
3910− // Decide which values are worth extracting. A value of length L appearing
3911− // N times costs N*L bytes inline; promoting it costs (L + 6) for the
3912− // `--hK:V;` declaration plus N * ref_len for the call sites. We estimate
3913− // ref_len optimistically as `var(--h0)` (9 bytes) and fall back to 10 for
3914− // two-digit indices, which only affects very large extraction counts.
3915− let existing: std::collections::HashSet<&str> =
3916− existing_vars.iter().map(|(n, _)| n.as_str()).collect();
3917− let mut candidates: Vec<(String, usize)> =
3918− counts.into_iter().filter(|(_, n)| *n >= 2).collect();
3919− // Stable, deterministic ordering — longest values first, tiebreak by text.
3920− candidates.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
3922− let mut extracted: Vec<(String, String)> = Vec::new();
3923− let mut next_idx: usize = 0;
3924− for (value, n) in candidates {
3925− let l = value.len();
3926− // Allocate the next unused `--hN` name.
3927− let (name, ref_len) = loop {
3928− let candidate = format!("--h{}", next_idx);
3930− let rl = candidate.len() + 6; // `var(` + name + `)`
3931− if !existing.contains(candidate.as_str())
3932− && !extracted.iter().any(|(n, _)| *n == candidate)
3934− break (candidate, rl);
3937− // Skip if promotion would not strictly reduce byte count.
3938− // Before: n * l bytes. After: (l + name.len() + 2) for the :root
3939− // declaration (`<name>:<value>;`) plus n * ref_len for the sites.
3940− let decl_overhead = l + name.len() + 2;
3941− let before = n * l;
3942− let after = decl_overhead + n * ref_len;
3943− if after < before {
3944− extracted.push((name, value));
3946− // Rewind the index so the next value can reuse this slot.
3951− if extracted.is_empty() {
3952− return (css.to_string(), Vec::new());
3954− let new_css = substitute_css_vars(css, &extracted);
3955− (new_css, extracted)
3958−/// Format a `line-height` value. CSS accepts either a unitless multiplier
2033+/// The rule that gives an element's `fill` and `shrink`, as its attributes
3959−/// (e.g. `1.5`) or a length (e.g. `24px`). Plain integers in htmlang source
2034+/// under the at-rules `at` set them, their meaning in a parent laid out
3960−/// are ambiguous: `[line-height 24]` was historically emitted as `24` (which
2035+/// along `axis`. Every other property a layout word could have set is put
3961−/// CSS interprets as 24× font-size — almost never what anyone wants). Treat
2036+/// back to its initial value, so the rule is right whichever earlier rule
3962−/// integers ≥ 2 as pixel lengths; anything with a decimal, an existing unit,
2037+/// it overrides. Properties the element writes itself are left alone.
3963−/// or the value `0`/`1` passes through unchanged.
2038+fn sizing_rule(attrs: &[Attribute], at: &[usize], axis: Axis) -> String {
3964−fn css_line_height(value: &str) -> String {
2039+ let sizes = Sizes::of(attrs, &Condition::at_only(at));
3965− let v = value.trim();
2040+ let mut sets: Vec<(&str, &str)> = Vec::new();
3966− if v == "0" || v == "1" {
2041+ let mut resets: Vec<(&str, &str)> = Vec::new();
3967− return v.to_string();
2042+ for (dim, size, word) in [
3968− }
2043+ (Dim::Width, sizes.width, sizes.width_word),
3969− if v.contains('.') {
2044+ (Dim::Height, sizes.height, sizes.height_word),
3970− return v.to_string();
2045+ ] {
3972− if CSS_UNITS.iter().any(|u| v.ends_with(u)) || v.ends_with("px") {
2047+ continue;
3973− return v.to_string();
2048+ }
2049+ if let Some(size) = size {
2050+ sets.extend_from_slice(sizing(dim, size, Some(axis)));
2052+ resets.extend_from_slice(&sizing_properties(dim));
3975− if v.starts_with("var(")
2054+ let mut css = String::new();
3976− || v.starts_with("calc(")
2055+ let mut written: Vec<&str> = Vec::new();
3977− || v.starts_with("clamp(")
2056+ for &(property, value) in &resets {
3978− || v.starts_with("min(")
2057+ if sets.iter().any(|&(p, _)| p == property) || written.contains(&property) {
3979− || v.starts_with("max(")
2058+ continue;
3981− return v.to_string();
2060+ written.push(property);
2061+ sizes.push(&mut css, property, value);
3983− // Plain integer — treat as pixel length.
2063+ for &(property, value) in &sets {
3984− if v.chars().all(|c| c.is_ascii_digit()) {
2064+ sizes.push(&mut css, property, value);
3985− return format!("{}px", v);
3987− v.to_string()
2066+ css
3990−/// Format multiple space-separated values, each getting px if needed.
2069+/// The rules an element's `fill` and `shrink` need under each chain of
3991−fn css_px_multi(value: &str) -> String {
2070+/// at-rules where the direction of `flow` (its parent's) changes: `(at,
3992− value
2071+/// body)`.
3993− .split_whitespace()
2072+fn sizing_changes(attrs: &[Attribute], flow: &Flow) -> Vec<(Vec<usize>, String)> {
3994− .map(css_px)
2073+ flow.changes
3995− .collect::<Vec<_>>()
2074+ .iter()
3996− .join(" ")
2075+ .map(|(at, axis)| (at.clone(), sizing_rule(attrs, at, *axis)))
2076+ .filter(|(_, body)| !body.is_empty())
3999−fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
2080+/// An element's generated class, with the rules keyed on its parent's
4000− let mut id = None;
2081+/// class that its `fill` and `shrink` need where the parent's direction
4001− let mut class = None;
2082+/// changes under a prefix (see [`Flow`]): `:where(.a)>.b`, one class of
4002− for attr in attrs {
2083+/// specificity like any class rule.
4003− match attr.key.as_str() {
2084+fn element_class(elem: &Element, site: &Site, styles: &mut StyleCollector) -> Option<String> {
4004− "id" => id = attr.value.clone(),
2085+ let as_child = match site.parent.class {
4005− "class" => class = attr.value.clone(),
2086+ Some(_) => sizing_changes(&elem.attrs, site.parent),
4006− _ => {}
2087+ None => Vec::new(),
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));
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);
4009− (id, class)
2101+ Some(class)
4012−/// Read image dimensions from a local file by parsing the header bytes.
2104+/// The `display` of a layout (nothing for text, native and void elements,
4013−/// Supports PNG, JPEG, GIF, WebP, AVIF, and SVG.
2105+/// which keep HTML's own).
4014−fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
2106+fn layout_css(layout: Layout, inline: bool) -> &'static str {
4015− // SVG: parse as text for viewBox/width/height attributes
2107+ match (layout, inline) {
4016− if path.ends_with(".svg") || path.ends_with(".SVG") {
2108+ (Layout::Column, false) => "display:flex;flex-direction:column;",
4017− let text = std::fs::read_to_string(path).ok()?;
2109+ (Layout::Column, true) => "display:inline-flex;flex-direction:column;",
4018− return read_svg_dimensions(&text);
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;",
4021− let data = std::fs::read(path).ok()?;
2118+/// The declarations of the attributes under `condition` (the defaults of
4022− if data.len() < 12 {
2119+/// the element's kind are [`default_css`]'s).
4023− return None;
2120+fn attrs_to_css(attrs: &[Attribute], condition: &Condition, site: &Site) -> String {
4024− }
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);
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)
2143+ for (index, attr) in attrs.iter().enumerate() {
2147+ let Some(effective_key) = under(&attr.key, condition) else {
2150+ if on_children && crate::vocab::places_in_parent(effective_key, attr.value.as_deref()) {
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()) {
4026− // PNG: 8-byte signature, then IHDR chunk with width/height at bytes 16-23
2160+ let val = attr.value.as_deref();
4027− if data.len() >= 24 && data.starts_with(b"\x89PNG\r\n\x1a\n") {
2161+ // A style whose value came out empty (a field a record doesn't
4028− let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
2162+ // have, `${if()}` without its other branch) is left out
4029− let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
2163+ if val.is_some_and(|v| v.trim().is_empty()) {
4030− return Some((w, h));
2164+ continue;
4033− // GIF: "GIF87a" or "GIF89a", width/height at bytes 6-9 (little-endian)
2167+ match effective_key {
4034− if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
2168+ // htmlang's own words: they lay out children or place the
4035− let w = u16::from_le_bytes([data[6], data[7]]) as u32;
2169+ // element in its parent, and mean more than one CSS property
4036− let h = u16::from_le_bytes([data[8], data[9]]) as u32;
2170+ "spacing" if !lays_out_children => {}
4037− return Some((w, h));
2171+ "spacing" => {
4038− }
2172+ if let Some(v) = val {
2173+ push_css(&mut css, "gap", &with_px("gap", v));
4040− // JPEG: scan for SOF0/SOF2 marker (0xFF 0xC0 or 0xFF 0xC2)
2177+ // Sizing: `fill` and `shrink` compile against the parent's
4041− if data.starts_with(b"\xff\xd8") {
2178+ // direction. Only the last `width` (`height`) counts, as for
4042− let mut i = 2;
2179+ // any style written twice.
4043− while i + 9 < data.len() {
2180+ "width" | "height" if val.is_some_and(|v| Size::of(v) != Size::Set) => {
4044− if data[i] != 0xFF {
2181+ let later = attrs[index + 1..].iter().any(|a| {
4045− i += 1;
2182+ !a.html
4046− continue;
2183+ && under(&a.key, condition) == Some(effective_key)
2184+ && a.value.as_deref().is_some_and(|v| !v.trim().is_empty())
2189+ let dim = if effective_key == "width" {
2194+ let size = Size::of(val.unwrap_or_default());
2195+ // What the element writes itself, which a layout word
2197+ let sizes = Sizes::of(attrs, condition);
2198+ for &(property, value) in sizing(dim, size, axis) {
2199+ sizes.push(&mut css, property, value);
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`
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",
2218+ && name == effective_key
2221+ && c.holds_at(condition)
2224+ .is_some_and(|v| !v.trim().is_empty() && Size::of(v) != Size::Set)
2227+ let dim = if effective_key == "width" {
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);
2238+ if let Some(v) = val {
2239+ push_css(&mut css, effective_key, &with_px(effective_key, v));
4048− let marker = data[i + 1];
2242+
4049− if marker == 0xC0 || marker == 0xC2 {
2243+ // Alignment: auto margins, which work along either direction.
4050− let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
2244+ // They are written last, so a `margin` on the same element
4051− let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
2245+ // keeps its other sides (`center-x, margin 20`)
4052− return Some((w, h));
2246+ "center-x" => {
2247+ push_css(&mut aligned, "margin-left", "auto");
2248+ push_css(&mut aligned, "margin-right", "auto");
4054− if i + 3 < data.len() {
2250+ "center-y" => {
4055− let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
2251+ push_css(&mut aligned, "margin-top", "auto");
4056− i += 2 + len;
2252+ push_css(&mut aligned, "margin-bottom", "auto");
4060− }
2254+ "align-left" => push_css(&mut aligned, "margin-right", "auto"),
4061− }
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"),
4063− // WebP: "RIFF" ... "WEBP", VP8 header at byte 20
2259+ "wrap" if lays_out_children => push_css(&mut css, "flex-wrap", "wrap"),
4064− if data.len() >= 30 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
2260+ "wrap" => {}
4065− if &data[12..16] == b"VP8 " && data.len() >= 30 {
4066− let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
4067− let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
4068− return Some((w, h));
4070− if &data[12..16] == b"VP8L" && data.len() >= 25 && data[21] == 0x2F {
4071− let bits = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
4072− let w = (bits & 0x3FFF) + 1;
4073− let h = ((bits >> 14) & 0x3FFF) + 1;
4074− return Some((w, h));
4078− // AVIF: ISOBMFF container with "ftyp" box containing "avif"/"avis" brand,
2262+ // Grid
4079− // then "ispe" box with width/height
2263+ "grid-cols" | "grid-rows" if !lays_out_children => {}
4080− if data.len() >= 12 && &data[4..8] == b"ftyp" {
2264+ "grid-cols" | "grid-rows" => {
4081− let brand = &data[8..12];
2265+ if let Some(v) = val {
4082− if brand == b"avif" || brand == b"avis" || brand == b"mif1" {
2266+ let property = if effective_key == "grid-cols" {
4083− return read_avif_dimensions(&data);
2267+ "grid-template-columns"
4085− }
2269+ "grid-template-rows"
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)),
2277+ "col-span" | "row-span" => {
2278+ if let Some(v) = val {
2279+ let property = if effective_key == "col-span" {
2284+ push_css(&mut css, property, &format!("span {}", v));
4087− None
2288+ // CSS's `line-clamp` has no support yet without its
4088−}
2289+ // `-webkit-` fallback, which needs a box to 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");
4090−/// Parse SVG viewBox or width/height attributes to get dimensions.
2299+ // Every other name is a CSS property (standard, custom,
4091−fn read_svg_dimensions(text: &str) -> Option<(u32, u32)> {
2300+ // vendor-prefixed, or one htmlang doesn't know, which the
4092− // Try viewBox first: viewBox="minX minY width height"
2301+ // parser warned about), written under its own name with the
4093− if let Some(vb_start) = text.find("viewBox=\"") {
2302+ // value as written, except for `px` after a bare number where
4094− let rest = &text[vb_start + 9..];
2303+ // the property takes a length
4095− if let Some(end) = rest.find('"') {
2304+ key if crate::vocab::is_property_name(key) => {
4096− let parts: Vec<&str> = rest[..end].split_whitespace().collect();
2305+ if let Some(v) = val {
4097− if parts.len() == 4
2306+ push_css(&mut css, key, &with_px(key, v));
4098− && let (Ok(w), Ok(h)) = (parts[2].parse::<f64>(), parts[3].parse::<f64>())
2307+ }
4102− return Some((w.round() as u32, h.round() as u32));
4106− // Fall back to width/height attributes on <svg>
2313+
4107− let svg_tag = text.find("<svg")?;
2314+ css.push_str(&aligned);
4108− let tag_end = text[svg_tag..].find('>')? + svg_tag;
2315+ css
4109− let tag = &text[svg_tag..tag_end];
4110− let w = extract_svg_attr(tag, "width")?;
4111− let h = extract_svg_attr(tag, "height")?;
4115−fn extract_svg_attr(tag: &str, attr: &str) -> Option<u32> {
2318+fn push_css(css: &mut String, prop: &str, value: &str) {
4116− let needle = format!("{}=\"", attr);
2319+ css.push_str(prop);
4117− let start = tag.find(&needle)? + needle.len();
2320+ css.push(':');
4118− let rest = &tag[start..];
2321+ css.push_str(value);
4119− let end = rest.find('"')?;
2322+ css.push(';');
4120− let val = rest[..end].trim_end_matches("px");
4121− val.parse::<f64>().ok().map(|v| v.round() as u32)
4124−/// Parse AVIF (ISOBMFF) container to find ispe box with image dimensions.
2325+fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
4125−fn read_avif_dimensions(data: &[u8]) -> Option<(u32, u32)> {
2326+ let mut id = None;
4126− // Walk ISOBMFF boxes looking for "ispe" (image spatial extents)
2327+ let mut class = None;
4127− let mut i = 0;
2328+ for attr in attrs.iter().filter(|a| a.html) {
4128− while i + 8 <= data.len() {
2329+ match attr.key.as_str() {
4129− let box_size =
2330+ "id" => id = attr.value.clone(),
4130− u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as usize;
2331+ "class" => class = attr.value.clone(),
4131− let box_type = &data[i + 4..i + 8];
2332+ _ => {}
4135− let box_end = (i + box_size).min(data.len());
4136− // ispe box: 4 bytes version/flags + 4 bytes width + 4 bytes height
4137− if box_type == b"ispe" && box_end >= i + 20 {
4138− let w = u32::from_be_bytes([data[i + 12], data[i + 13], data[i + 14], data[i + 15]]);
4139− let h = u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
4140− return Some((w, h));
4142− // Recurse into container boxes (meta, iprp, ipco)
4145− b"meta" | b"iprp" | b"ipco" | b"moov" | b"trak" | b"mdia"
4147− let header_size = if box_type == b"meta" { 12 } else { 8 };
4148− if i + header_size < box_end
4149− && let Some(dims) = read_avif_dimensions(&data[i + header_size..box_end])
4156− None
2335+ (id, class)
4159fn html_escape(s: &str) -> String {
2338fn html_escape(s: &str) -> String {
@@ -4194,10 +2373,24 @@ fn base64_encode(data: &[u8]) -> String {
4194/// Generate a standard v3 source map with VLQ-encoded mappings.
2373/// Generate a standard v3 source map with VLQ-encoded mappings.
4195/// Compatible with browser devtools and source map tooling.
2374/// Compatible with browser devtools and source map tooling.
4196pub fn generate_source_map(doc: &Document, source_file: &str) -> String {
2375pub fn generate_source_map(doc: &Document, source_file: &str) -> String {
2376+ source_map_for_html(&generate_dev(doc), source_file)
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 {
4197 let mut mappings: Vec<(usize, usize)> = Vec::new(); // (html_line, hl_line)
2382 let mut mappings: Vec<(usize, usize)> = Vec::new(); // (html_line, hl_line)
4198− collect_source_lines(&doc.nodes, &mut mappings);
2383+ for (idx, line) in html.lines().enumerate() {
4199− mappings.sort_by_key(|m| m.0);
2384+ if let Some(pos) = line.find("data-hl-line=\"") {
4200− mappings.dedup_by_key(|m| m.0);
2385+ let digits: String = line[pos + "data-hl-line=\"".len()..]
2387+ .take_while(|c| c.is_ascii_digit())
2389+ if let Ok(hl_line) = digits.parse::<usize>() {
2390+ mappings.push((idx + 1, hl_line));
4202 // Build VLQ-encoded mappings string.
2395 // Build VLQ-encoded mappings string.
4203 // Each generated line is separated by ';'. Each segment within a line is
2396 // Each generated line is separated by ';'. Each segment within a line is
@@ -4257,60 +2450,30 @@ fn vlq_encode(value: i64, out: &mut String) {
4260−fn collect_source_lines(nodes: &[Node], mappings: &mut Vec<(usize, usize)>) {
2453+#[cfg(test)]
4261− for node in nodes {
2454+mod tests {
4262− if let Node::Element(elem) = node {
2455+ use super::*;
4263− if elem.line_num > 0 {
2456+
4264− mappings.push((mappings.len() + 1, elem.line_num));
2457+ #[test]
4265− }
2458+ fn a_name_is_a_stable_hash_of_the_style() {
4266− collect_source_lines(&elem.children, mappings);
2459+ // The same in every build and on every platform
4267− }
2460+ assert_eq!(stable_hash(""), 0xf52a_15e9_a9b5_e89b);
4268− }
2461+ assert_eq!(hash_digits(35, 3), "z00");
4269−}
2462+ assert_eq!(hash_digits(u64::MAX, 13), "fsgs46211e5w3");
4271−/// Check if a specific element kind exists anywhere in the node tree.
2464+
4272−fn has_element_kind(nodes: &[Node], target: &ElementKind) -> bool {
2465+ #[test]
4273− for node in nodes {
2466+ fn a_name_taken_in_the_file_takes_more_digits() {
4274− if let Node::Element(elem) = node {
2467+ // These two styles' hashes end in the same 7 digits
4275− if elem.kind == *target {
2468+ let mut styles = StyleCollector::new();
4276− return true;
2469+ let first = styles.get_class("width:129555px;".into(), Vec::new(), String::new());
4277− }
2470+ let second = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
4278− if has_element_kind(&elem.children, target) {
2471+ let (first, second) = (first.unwrap(), second.unwrap());
4279− return true;
2472+ assert_eq!(first.len(), 3 + CLASS_DIGITS, "{first}");
4280− }
2473+ assert_eq!(second.len(), 3 + CLASS_DIGITS + 1, "{second}");
4281− }
2474+ assert!(second.starts_with(&first), "{first} {second}");
4282− }
2475+ // The same style gets the name it got before
4283− false
2476+ let again = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
4284−}
2477+ assert_eq!(again.as_deref(), Some(second.as_str()));
4286−/// Collect unique external domains from generated HTML for DNS prefetch hints.
4287−fn collect_dns_prefetch(html: &str, dev: bool) -> String {
4288− let mut domains = Vec::new();
4289− let mut rest = html;
4290− while let Some(pos) = rest.find("https://") {
4291− let start = pos + 8; // skip "https://"
4292− rest = &rest[start..];
4294− .find(['/', '"', '\'', ' ', '>', ')'])
4295− .unwrap_or(rest.len());
4296− let domain = &rest[..end];
4297− if !domain.is_empty() && domain.contains('.') && !domains.contains(&domain.to_string()) {
4298− domains.push(domain.to_string());
4301− let mut out = String::new();
4302− for domain in &domains {
4304− out.push_str(&format!(
4305− "<link rel=\"dns-prefetch\" href=\"//{}\">\n",
4309− out.push_str(&format!(
4310− "<link rel=\"dns-prefetch\" href=\"//{}\">",