@@ -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,50 +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(),
31− if n < 36 { break; }
100+ }
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)
34− // Reverse so it reads naturally
273+}
35− 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);
38struct StyleEntry {
298struct StyleEntry {
39 class_name: String,
299 class_name: String,
300+ /// The hash of the style, which names the class
302+ /// The defaults of the element's kind (its layout, a heading's
303+ /// `margin:0`, ...), less what its own attributes set. They are written
304+ /// as `:where(.hl-a)` in the layer `hl-kind`, so an element prefix
305+ /// around it (`@h2:`), its parent's `children:` styles and its own
306+ /// attributes, all in later layers, win over them.
40− base: String,
307+ defaults: String,
41− /// (CSS selector suffix, css_rules) — e.g. (":hover", "color:red;")
308+ /// The element's rules: under each condition, its declarations, in the
42− pseudo: Vec<(String, String)>,
309+ /// order they are written
43− /// Responsive overrides: (breakpoint_prefix, css)
310+ rules: Vec<(Condition, String)>,
44− responsive: Vec<(String, String)>,
311+ /// What else tells two elements with the same CSS apart: the rules
45− /// Dark mode overrides
312+ /// keyed on this class (see [`StyleCollector::keyed`]). Not written.
46− dark: String,
313+ distinct: String,
50− motion_reduce: String,
53− /// Container query overrides: (breakpoint_prefix, css)
54− container: Vec<(String, String)>,
57struct StyleCollector {
316struct StyleCollector {
58 entries: Vec<StyleEntry>,
317 entries: Vec<StyleEntry>,
59− /// 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
60− /// Using u64 as the key keeps lookups allocation-free; on the rare case of
319+ /// styles hash alike, which the full comparison tells apart).
61− /// a hash collision we fall back to a full equality check against the entry.
62 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)>,
65impl StyleCollector {
331impl StyleCollector {
@@ -67,311 +333,328 @@ impl StyleCollector {
67 StyleCollector {
333 StyleCollector {
68 entries: Vec::new(),
334 entries: Vec::new(),
69 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);
73 /// 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.
74 fn get_class(
351 fn get_class(
75 &mut self,
352 &mut self,
76− base: String,
353+ defaults: String,
77− pseudo: Vec<(String, String)>,
354+ mut rules: Vec<(Condition, String)>,
78− responsive: Vec<(String, String)>,
355+ distinct: String,
82− motion_reduce: String,
85− container: Vec<(String, String)>,
86 ) -> Option<String> {
356 ) -> Option<String> {
357+ rules.retain(|(_, body)| !body.is_empty());
87− if base.is_empty()
358+ if defaults.is_empty() && rules.is_empty() {
89− && responsive.is_empty()
92− && motion_safe.is_empty()
93− && motion_reduce.is_empty()
94− && landscape.is_empty()
95− && portrait.is_empty()
96− && container.is_empty()
98 return None;
359 return None;
100− use std::collections::hash_map::DefaultHasher;
361+ rules.sort_by_cached_key(|(condition, _)| condition.order());
101− let mut h = DefaultHasher::new();
362+ let style = stable_hash(&style_text(&defaults, &rules, &distinct));
102− base.hash(&mut h);
363+
103− pseudo.hash(&mut h);
104− responsive.hash(&mut h);
107− motion_safe.hash(&mut h);
108− motion_reduce.hash(&mut h);
109− landscape.hash(&mut h);
110− portrait.hash(&mut h);
111− container.hash(&mut h);
112− let sig = h.finish();
114− if let Some(indices) = self.index.get(&sig) {
364+ if let Some(indices) = self.index.get(&style) {
115 for &idx in indices {
365 for &idx in indices {
116 let e = &self.entries[idx];
366 let e = &self.entries[idx];
117− if e.base == base
367+ if e.defaults == defaults && e.rules == rules && e.distinct == distinct {
118− && e.pseudo == pseudo
119− && e.responsive == responsive
122− && e.motion_safe == motion_safe
123− && e.motion_reduce == motion_reduce
124− && e.landscape == landscape
125− && e.portrait == portrait
126− && e.container == container
128 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
132 let idx = self.entries.len();
375 let idx = self.entries.len();
133− 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());
134 self.entries.push(StyleEntry {
381 self.entries.push(StyleEntry {
135 class_name: name.clone(),
382 class_name: name.clone(),
137− pseudo,
384+ defaults,
138− responsive,
385+ rules,
147− self.index.entry(sig).or_default().push(idx);
388+ self.index.entry(style).or_default().push(idx);
148 Some(name)
389 Some(name)
151− fn to_css_formatted(&self, dev: bool, use_layer: bool) -> String {
392+ /// The classes given, in the order they were
152− let mut css = String::new();
393+ fn classes(&self) -> impl Iterator<Item = Class> + '_ {
153− let (sp, nl) = if dev { (" ", "\n") } else { ("", "") };
394+ self.entries.iter().map(|e| Class {
395+ name: e.class_name.clone(),
155− // Wrap in @layer for specificity management
400+ /// All generated rules, in three layers (see [`LAYERS`]): the element
156− 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(","));
158− css.push_str("@layer htmlang {\n");
424+ kind.push_str(&format!(" {} {{{}}}\n", selector, body));
160− css.push_str("@layer htmlang{");
164− // Non-responsive rules
165− for e in &self.entries {
166− if !e.base.is_empty() {
167− if use_layer && dev {
168− css.push_str(&format!(" .{}{sp}{{{}}}{nl}", e.class_name, e.base));
426+ kind.push_str(&format!("{}{{{}}}", selector, body));
170− css.push_str(&format!(".{}{sp}{{{}}}{nl}", e.class_name, e.base));
173− for (selector, pseudo_css) in &e.pseudo {
174− if !pseudo_css.is_empty() {
175− if use_layer && dev {
176− css.push_str(&format!(" .{}{}{sp}{{{}}}{nl}", e.class_name, selector, pseudo_css));
178− css.push_str(&format!(".{}{}{sp}{{{}}}{nl}", e.class_name, selector, pseudo_css));
184− // Responsive rules grouped by breakpoint
185− for &(bp_name, bp_width) in BREAKPOINTS {
186− let mut bp_css = String::new();
187− for e in &self.entries {
188− for (bp, rule_css) in &e.responsive {
189− if bp == bp_name && !rule_css.is_empty() {
191− bp_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, rule_css));
193− bp_css.push_str(&format!(".{}{{{}}}", e.class_name, rule_css));
198− if !bp_css.is_empty() {
200− css.push_str(&format!(
201− "@media (min-width: {}) {{\n{}}}\n",
205− css.push_str(&format!(
206− "@media(min-width:{}){{{}}}",
213− // Dark mode rules
430+ let mut inside = self.blocks(true, dev);
214− let mut dark_css = String::new();
431+ // A function's scoped `@style`, nested under its class
215− for e in &self.entries {
432+ for block in scoped {
216− if !e.dark.is_empty() {
218− dark_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.dark));
220− dark_css.push_str(&format!(".{}{{{}}}", e.class_name, e.dark));
224− if !dark_css.is_empty() {
226− css.push_str(&format!("@media (prefers-color-scheme: dark) {{\n{}}}\n", dark_css));
434+ inside.push_str(block);
228− css.push_str(&format!("@media(prefers-color-scheme:dark){{{}}}", dark_css));
437+ inside.push_str(&compact_css(block));
233− let mut print_css = String::new();
441+ let mut css = String::new();
234− for e in &self.entries {
442+ for (name, rules) in [
235− if !e.print.is_empty() {
443+ ("hl-kind", kind),
236− if dev {
444+ ("hl-inside", inside),
237− print_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.print));
445+ ("htmlang", self.blocks(false, dev)),
239− print_css.push_str(&format!(".{}{{{}}}", e.class_name, e.print));
447+ if rules.is_empty() {
243− if !print_css.is_empty() {
245− css.push_str(&format!("@media print {{\n{}}}\n", print_css));
451+ css.push_str(&format!("@layer {} {{\n{}}}\n", name, rules));
247− css.push_str(&format!("@media print{{{}}}", print_css));
453+ css.push_str(&format!("@layer {}{{{}}}", name, rules));
251− // Motion safe rules
459+ /// The rules of every block of at-rules, in order: those for the
460+ /// elements inside (`inside`: rules under an element prefix, each in
461+ /// an `@scope` on its element's class), or the elements' own.
462+ fn blocks(&self, inside: bool, dev: bool) -> String {
252− let mut motion_safe_css = String::new();
463+ let mut css = String::new();
253− for e in &self.entries {
465+ self.entries.iter().flat_map(move |e| {
254− if !e.motion_safe.is_empty() {
466+ e.rules
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
255− if dev {
488+ let indent = if dev {
256− motion_safe_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.motion_safe));
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)])),
540+ let inner_indent = if dev {
541+ format!("{} ", indent)
258− motion_safe_css.push_str(&format!(".{}{{{}}}", e.class_name, e.motion_safe));
543+ String::new()
545+ for (root, targets) in scopes {
546+ let targets: Vec<(&str, &str)> =
547+ targets.iter().map(|(t, b)| (t.as_str(), *b)).collect();
548+ inner.push_str(&indent);
549+ inner.push_str(&format!("@scope ({})", root));
550+ inner.push_str(if dev { " {\n" } else { "{" });
551+ emit_selector_rules(&mut inner, &targets, &inner_indent, dev);
552+ inner.push_str(&indent);
553+ inner.push_str(if dev { "}\n" } else { "}" });
262− if !motion_safe_css.is_empty() {
264− css.push_str(&format!("@media (prefers-reduced-motion: no-preference) {{\n{}}}\n", motion_safe_css));
266− css.push_str(&format!("@media(prefers-reduced-motion:no-preference){{{}}}", motion_safe_css));
556+ chains.sort_by_cached_key(|chain| selector_order(chain));
267− }
557+ for chain in chains {
268− }
558+ let pairs: Vec<(String, &str)> = rules()
269−
559+ .filter(|(_, c, _)| c.at == at && c.selector == chain)
270− // Motion reduce rules
560+ .map(|(e, _, body)| (selector(&e.class_name, chain), body.as_str()))
271− let mut motion_reduce_css = String::new();
561+ .collect();
272− for e in &self.entries {
562+ emit_grouped_rules(&mut inner, &pairs, &indent, dev);
273− if !e.motion_reduce.is_empty() {
275− motion_reduce_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.motion_reduce));
277− motion_reduce_css.push_str(&format!(".{}{{{}}}", e.class_name, e.motion_reduce));
281− if !motion_reduce_css.is_empty() {
565+ if inner.is_empty() {
282− if dev {
566+ continue;
283− css.push_str(&format!("@media (prefers-reduced-motion: reduce) {{\n{}}}\n", motion_reduce_css));
285− css.push_str(&format!("@media(prefers-reduced-motion:reduce){{{}}}", motion_reduce_css));
287− }
568+ // Each at-rule wraps the next, outermost first
288−
569+ for (level, &rank) in at.iter().enumerate().rev() {
290− let mut landscape_css = String::new();
291− for e in &self.entries {
292− if !e.landscape.is_empty() {
293− if dev {
570+ let pad = if dev {
294− landscape_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.landscape));
571+ " ".repeat(level)
296− landscape_css.push_str(&format!(".{}{{{}}}", e.class_name, e.landscape));
573+ String::new()
300− if !landscape_css.is_empty() {
301− if dev {
575+ inner = if dev {
302− css.push_str(&format!("@media (orientation: landscape) {{\n{}}}\n", landscape_css));
576+ format!("{pad}{} {{\n{inner}{pad}}}\n", at_rule(rank, true))
303− } else {
577+ } else {
304− css.push_str(&format!("@media(orientation:landscape){{{}}}", landscape_css));
578+ format!("{}{{{inner}}}", at_rule(rank, false))
581+ css.push_str(&inner);
308− // Portrait rules
587+/// Emit CSS rules from `(selector, body)` pairs, merging identical bodies
309− let mut portrait_css = String::new();
588+/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
310− for e in &self.entries {
589+/// of each distinct body determines ordering, so output stays deterministic
311− if !e.portrait.is_empty() {
590+/// across runs. `indent` is prepended to each rule line.
312− if dev {
591+fn emit_grouped_rules(out: &mut String, pairs: &[(String, &str)], indent: &str, dev: bool) {
313− portrait_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, e.portrait));
592+ if pairs.is_empty() {
314− } else {
593+ return;
315− portrait_css.push_str(&format!(".{}{{{}}}", e.class_name, e.portrait));
594+ }
316− }
595+ // Group in first-occurrence order.
317− }
596+ let mut order: Vec<&str> = Vec::new();
597+ let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
598+ for (selector, body) in pairs {
599+ if body.is_empty() {
319− if !portrait_css.is_empty() {
602+ if !groups.contains_key(body) {
320− if dev {
603+ order.push(body);
321− css.push_str(&format!("@media (orientation: portrait) {{\n{}}}\n", portrait_css));
323− css.push_str(&format!("@media(orientation:portrait){{{}}}", portrait_css));
605+ groups.entry(body).or_default().push(selector);
607+ let sp = if dev { " " } else { "" };
608+ let nl = if dev { "\n" } else { "" };
609+ for body in &order {
610+ out.push_str(indent);
611+ out.push_str(&groups[body].join(","));
327− // Container query rules grouped by breakpoint
620+/// Emit `(selector, body)` rules in their order, merging a run of rules
328− for &(bp_name, bp_width) in BREAKPOINTS {
621+/// with the same body into one rule with a selector list (the order
329− let mut cq_css = String::new();
622+/// matters: two rules may apply to one element).
330− for e in &self.entries {
623+fn emit_selector_rules(out: &mut String, rules: &[(&str, &str)], indent: &str, dev: bool) {
331− for (bp, rule_css) in &e.container {
624+ let mut i = 0;
332− if bp == bp_name && !rule_css.is_empty() {
625+ while i < rules.len() {
333− if dev {
626+ let body = rules[i].1;
334− cq_css.push_str(&format!(" .{} {{{}}}\n", e.class_name, rule_css));
627+ let run = rules[i..].iter().take_while(|(_, b)| *b == body).count();
335− } else {
628+ if !body.is_empty() {
336− cq_css.push_str(&format!(".{}{{{}}}", e.class_name, rule_css));
629+ let selectors: Vec<&str> = rules[i..i + run].iter().map(|(s, _)| *s).collect();
337− }
630+ out.push_str(indent);
338− }
631+ out.push_str(&selectors.join(","));
340− }
633+ out.push(' ');
341− if !cq_css.is_empty() {
343− css.push_str(&format!(
344− "@container (min-width: {}) {{\n{}}}\n",
348− css.push_str(&format!(
349− "@container(min-width:{}){{{}}}",
354− }
635+ out.push('{');
355−
636+ out.push_str(body);
356− // Close @layer
637+ out.push('}');
359− css.push_str("}\n");
639+ out.push('\n');
369struct GenContext {
646struct GenContext {
370 dev: bool,
647 dev: bool,
371 depth: usize,
648 depth: usize,
373 has_interactive: bool,
649 has_interactive: bool,
374− 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`
377impl GenContext {
660impl GenContext {
@@ -397,23 +680,26 @@ pub struct CodegenOptions {
397 pub dev: bool,
680 pub dev: bool,
398 pub partial: bool,
681 pub partial: bool,
399 pub minify: bool,
682 pub minify: bool,
403/// Generate HTML from a parsed document using the given options.
685/// Generate HTML from a parsed document using the given options.
404pub 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();
405 let mut html = if opts.partial {
694 let mut html = if opts.partial {
406− generate_partial_inner(doc, opts.dev)
695+ generate_partial_inner(doc, opts.dev, &mut classes)
408− generate_full_inner(doc, opts.dev)
697+ generate_full_inner(doc, opts.dev, &mut classes)
410 if opts.minify {
699 if opts.minify {
411 html = minify_html(&html);
700 html = minify_html(&html);
413− if opts.compat {
702+ (html, classes)
414− html = add_vendor_prefixes(&html);
419pub fn generate(doc: &Document) -> String {
705pub fn generate(doc: &Document) -> String {
@@ -421,31 +707,44 @@ pub fn generate(doc: &Document) -> String {
423pub fn generate_dev(doc: &Document) -> String {
709pub fn generate_dev(doc: &Document) -> String {
424− generate_with(doc, &CodegenOptions { dev: true, ..Default::default() })
712+ &CodegenOptions {
714+ ..Default::default()
427pub fn generate_partial(doc: &Document) -> String {
719pub fn generate_partial(doc: &Document) -> String {
428− generate_with(doc, &CodegenOptions { partial: true, ..Default::default() })
722+ &CodegenOptions {
724+ ..Default::default()
431pub fn generate_partial_dev(doc: &Document) -> String {
729pub fn generate_partial_dev(doc: &Document) -> String {
432− generate_with(doc, &CodegenOptions { dev: true, partial: true, ..Default::default() })
730+ generate_with(
735+ ..Default::default()
435pub fn generate_minified(doc: &Document) -> String {
740pub fn generate_minified(doc: &Document) -> String {
436− generate_with(doc, &CodegenOptions { minify: true, ..Default::default() })
743+ &CodegenOptions {
439−pub fn generate_compat(doc: &Document) -> String {
440− generate_with(doc, &CodegenOptions { compat: true, ..Default::default() })
745+ ..Default::default()
443−pub fn generate_dev_compat(doc: &Document) -> String {
444− generate_with(doc, &CodegenOptions { dev: true, compat: true, ..Default::default() })
447−pub fn generate_minified_compat(doc: &Document) -> String {
448− generate_with(doc, &CodegenOptions { minify: true, compat: true, ..Default::default() })
451fn minify_html(html: &str) -> String {
750fn minify_html(html: &str) -> String {
@@ -462,9 +761,9 @@ fn minify_html(html: &str) -> String {
462 if i + 4 < chars.len() && chars[i] == '<' {
761 if i + 4 < chars.len() && chars[i] == '<' {
463 let rest: String = chars[i..].iter().take(10).collect();
762 let rest: String = chars[i..].iter().take(10).collect();
464 let rest_lower = rest.to_lowercase();
763 let rest_lower = rest.to_lowercase();
465− if rest_lower.starts_with("<pre") {
764+ if rest_lower.starts_with("<pre") || rest_lower.starts_with("<textarea") {
466 in_pre = true;
765 in_pre = true;
467− } else if rest_lower.starts_with("</pre") {
766+ } else if rest_lower.starts_with("</pre") || rest_lower.starts_with("</textarea") {
468 in_pre = false;
767 in_pre = false;
469 } else if rest_lower.starts_with("<script") {
768 } else if rest_lower.starts_with("<script") {
470 in_script = true;
769 in_script = true;
@@ -478,13 +777,18 @@ fn minify_html(html: &str) -> String {
480 // Strip HTML comments (<!-- ... -->)
779 // Strip HTML comments (<!-- ... -->)
481− if !in_script && !in_style && i + 3 < chars.len()
780+ if !in_script
782+ && i + 3 < chars.len()
482− && chars[i] == '<' && chars[i+1] == '!' && chars[i+2] == '-' && chars[i+3] == '-'
784+ && chars[i + 1] == '!'
785+ && chars[i + 2] == '-'
786+ && chars[i + 3] == '-'
484 // Skip to -->
788 // Skip to -->
485 let mut j = i + 4;
789 let mut j = i + 4;
486 while j + 2 < chars.len() {
790 while j + 2 < chars.len() {
487− if chars[j] == '-' && chars[j+1] == '-' && chars[j+2] == '>' {
791+ if chars[j] == '-' && chars[j + 1] == '-' && chars[j + 2] == '>' {
@@ -501,10 +805,11 @@ fn minify_html(html: &str) -> String {
501 continue;
805 continue;
504− // 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).
505 if chars[i].is_whitespace() {
811 if chars[i].is_whitespace() {
506 if !prev_was_space {
812 if !prev_was_space {
507− // Only emit a space if we're between content (not between tags)
508 result.push(' ');
813 result.push(' ');
509 prev_was_space = true;
814 prev_was_space = true;
@@ -512,14 +817,6 @@ fn minify_html(html: &str) -> String {
512 continue;
817 continue;
515− // Trim space before closing tags
516− if chars[i] == '<' && prev_was_space {
517− // Remove trailing space before tag
518− if result.ends_with(' ') {
523 prev_was_space = false;
820 prev_was_space = false;
524 result.push(chars[i]);
821 result.push(chars[i]);
@@ -528,202 +825,172 @@ fn minify_html(html: &str) -> String {
531−/// 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 {
532−fn add_vendor_prefixes(html: &str) -> String {
829+ // Without `@page` the output is a fragment
533− // Find CSS within <style>...</style> and add vendor prefixes
830+ let Some(page) = &doc.page else {
534− let mut result = String::with_capacity(html.len() + 512);
831+ return generate_partial_inner(doc, dev, classes);
535− let mut rest = html;
832+ };
536− while let Some(start) = rest.find("<style>") {
537− let after_tag = start + 7;
538− result.push_str(&rest[..after_tag]);
539− rest = &rest[after_tag..];
540− if let Some(end) = rest.find("</style>") {
541− let css = &rest[..end];
542− result.push_str(&prefix_css(css));
543− result.push_str("</style>");
544− rest = &rest[end + 8..];
549− result.push_str(rest);
553−fn prefix_css(css: &str) -> String {
554− let mut out = String::with_capacity(css.len() + 256);
556− let bytes = css.as_bytes();
557− while i < bytes.len() {
558− // Find property declarations
559− if let Some(pos) = css[i..].find('{') {
560− let brace = i + pos;
561− out.push_str(&css[i..=brace]);
563− // Process declarations within this block
564− if let Some(close) = css[i..].find('}') {
565− let block = &css[i..i + close];
566− out.push_str(&prefix_declarations(block));
571− out.push_str(&css[i..]);
578−fn prefix_declarations(block: &str) -> String {
579− let mut out = String::with_capacity(block.len() + 128);
580− for decl in block.split(';') {
581− let decl = decl.trim();
582− if decl.is_empty() {
585− if let Some((prop, val)) = decl.split_once(':') {
586− let prop = prop.trim();
587− let val = val.trim();
589− "backdrop-filter" => {
590− out.push_str(&format!("-webkit-backdrop-filter:{};", val));
591− out.push_str(&format!("backdrop-filter:{};", val));
594− out.push_str(&format!("-webkit-user-select:{};", val));
595− out.push_str(&format!("-moz-user-select:{};", val));
596− out.push_str(&format!("user-select:{};", val));
599− out.push_str(&format!("-webkit-appearance:{};", val));
600− out.push_str(&format!("-moz-appearance:{};", val));
601− out.push_str(&format!("appearance:{};", val));
603− "background-clip" if val.contains("text") => {
604− out.push_str(&format!("-webkit-background-clip:{};", val));
605− out.push_str(&format!("background-clip:{};", val));
608− out.push_str(&format!("-webkit-hyphens:{};", val));
609− out.push_str(&format!("-ms-hyphens:{};", val));
610− out.push_str(&format!("hyphens:{};", val));
612− "text-size-adjust" => {
613− out.push_str(&format!("-webkit-text-size-adjust:{};", val));
614− out.push_str(&format!("-ms-text-size-adjust:{};", val));
615− out.push_str(&format!("text-size-adjust:{};", val));
617− "mask-image" | "mask-size" | "mask-repeat" | "mask-position" => {
618− out.push_str(&format!("-webkit-{}:{};", prop, val));
619− out.push_str(&format!("{}:{};", prop, val));
634−fn generate_full_inner(doc: &Document, dev: bool) -> String {
635 let mut styles = StyleCollector::new();
833 let mut styles = StyleCollector::new();
636− let mut ctx = GenContext { dev, depth: 0, image_count: 0, has_interactive: false, has_defer: false };
834+ let mut ctx = GenContext {
837+ has_interactive: false,
839+ flow: Flow::default(),
638− // Check if document has @main for skip-to-content link
843+ // The page is the root element: `<body>` is a column (the reset makes
639− 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();
641 let mut body = String::new();
867 let mut body = String::new();
870+ Some(Layout::Column),
876+ let element_css = build_element_css(doc, &styles, dev);
877+ let nl = if dev { "\n" } else { "" };
879+ let mut meta_html = String::new();
880+ // A `@meta viewport` of the page's own replaces the usual one
881+ if !doc.meta_tags.iter().any(|(name, _)| name == "viewport") {
882+ meta_html.push_str(&format!(
883+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">{}",
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);
920+ // `@page`'s HTML attributes go on `<html>`
921+ let mut root_attrs = String::new();
922+ for attr in html_attrs(&page.html_attrs) {
923+ push_html_attr(&mut root_attrs, attr);
925+ let mut body_attrs = String::new();
926+ emit_class_attr(&mut body_attrs, body_class.as_deref(), None);
643− // Skip-to-content link for accessibility (only when @main exists)
928+ // Focus-visible CSS for interactive elements (accessibility)
644− if has_main {
929+ let focus_visible_css = if ctx.has_interactive {
930+ let focusable = ":where(a,button,input,select,textarea):focus-visible";
646− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>\n");
932+ format!(
933+ "{}{} {{ outline: 2px solid currentColor; outline-offset: 2px; }}\n",
934+ OWN_ELEMENTS, focusable
648− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>");
937+ format!(
938+ "{}{}{{outline:2px solid currentColor;outline-offset:2px}}",
939+ OWN_ELEMENTS, focusable
652− for node in &doc.nodes {
944+ };
653− generate_node(node, None, &mut body, &mut styles, &mut ctx);
945+ let reset_css = reset_css(dev, true, &focus_visible_css);
654− }
946+ classes.extend(styles.classes());
656− // Collect external domains for DNS prefetch
948+ format!(
657− 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 {
659 let mut element_css = String::new();
959 let mut element_css = String::new();
661− // CSS custom properties (includes @theme runtime tokens)
961+ // Collect the CSS custom properties declared with `@let --name` so they
662− let has_theme_tokens = !doc.theme_tokens.is_empty();
962+ // can be emitted in a single `:root` block below.
663− if !doc.css_vars.is_empty() || has_theme_tokens {
963+ let mut root_vars: Vec<(String, String)> = Vec::new();
964+ for (name, value) in &doc.css_vars {
965+ root_vars.push((name.clone(), value.clone()));
968+ // Generated rules always go in htmlang's layers, so unlayered user CSS
969+ // (`@style`, `@raw`) overrides them regardless of specificity.
970+ let styles_css = styles.to_css_formatted(dev, &doc.scoped_css);
972+ // Emit the :root block first so the cascade picks up the custom
973+ // properties before the class rules consume them.
974+ if !root_vars.is_empty() {
665 element_css.push_str(":root {\n");
976 element_css.push_str(":root {\n");
666− for (name, value) in &doc.css_vars {
977+ for (name, value) in &root_vars {
667 element_css.push_str(&format!(" {}: {};\n", name, value));
978 element_css.push_str(&format!(" {}: {};\n", name, value));
669− // @theme tokens as runtime CSS custom properties
670− for (name, value) in &doc.theme_tokens {
671− let css_name = format!("--{}", name);
672− // Only emit if not already in css_vars
673− if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
674− element_css.push_str(&format!(" {}: {};\n", css_name, value));
677 element_css.push_str("}\n");
980 element_css.push_str("}\n");
679 element_css.push_str(":root{");
982 element_css.push_str(":root{");
680− for (name, value) in &doc.css_vars {
983+ for (name, value) in &root_vars {
681 element_css.push_str(name);
984 element_css.push_str(name);
682 element_css.push(':');
985 element_css.push(':');
683 element_css.push_str(value);
986 element_css.push_str(value);
684 element_css.push(';');
987 element_css.push(';');
686− for (name, value) in &doc.theme_tokens {
687− let css_name = format!("--{}", name);
688− if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
689− element_css.push_str(&css_name);
690− element_css.push(':');
691− element_css.push_str(value);
692− element_css.push(';');
695 element_css.push('}');
989 element_css.push('}');
699− let has_custom_css = !doc.custom_css.is_empty();
993+ element_css.push_str(&styles_css);
700− element_css.push_str(&styles.to_css_formatted(dev, !has_custom_css));
703− for (name, kf_body) in &doc.keyframes {
705− element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
707− element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
711− // Auto-inject skeleton keyframe if skeleton attribute is used
712− let skeleton_used = element_css.contains("hl-skeleton");
715− element_css.push_str("@keyframes hl-skeleton {\n 0% { background-position: 200% 0; }\n 100% { background-position: -200% 0; }\n}\n");
717− element_css.push_str("@keyframes hl-skeleton{0%{background-position:200% 0}100%{background-position:-200% 0}}");
721− // Also inject carousel webkit scrollbar hiding
722− let carousel_used = element_css.contains("scroll-snap-type:x mandatory");
723− if carousel_used && !element_css.contains("::-webkit-scrollbar") {
724− // The carousel class already has scrollbar-width:none, but webkit needs pseudo-element
725− // We add a global rule for carousel-style elements
728 // @style blocks (custom CSS)
995 // @style blocks (custom CSS)
729 for block in &doc.custom_css {
996 for block in &doc.custom_css {
@@ -731,464 +998,115 @@ fn generate_full_inner(doc: &Document, dev: bool) -> String {
731 element_css.push_str(block);
998 element_css.push_str(block);
732 element_css.push('\n');
999 element_css.push('\n');
733 } else {
1000 } else {
734− // Minify: collapse whitespace
1001+ element_css.push_str(&compact_css(block));
735− let minified: String = block
738− .collect::<Vec<_>>()
740− element_css.push_str(&minified);
744− // @scope blocks
1005+ element_css
745− for block in &doc.scope_blocks {
1006+}
747− element_css.push_str(block);
748− element_css.push('\n');
750− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
751− element_css.push_str(&minified);
755− // @starting-style blocks
1008+/// An `@style` body on one line: each line trimmed, and the lines joined with
756− if !doc.starting_style_blocks.is_empty() {
1009+/// a space, so a value that goes on over two lines (`margin: 0` then `auto;`)
757− if dev {
1010+/// keeps its words apart.
758− element_css.push_str("@starting-style {\n");
1011+fn compact_css(block: &str) -> String {
759− for block in &doc.starting_style_blocks {
1012+ block
760− element_css.push_str(block);
1013+ .lines()
761− element_css.push('\n');
1014+ .map(str::trim)
762− }
1015+ .filter(|l| !l.is_empty())
763− element_css.push_str("}\n");
1016+ .collect::<Vec<_>>()
1020+/// htmlang's own elements: those with a generated class, or the class of a
1021+/// function's scoped `@style`. The reset's rules for elements are kept to
1022+/// them, so `@raw` and `@markdown` content, and the page a fragment is put
1023+/// into, keep their own.
1024+const OWN_ELEMENTS: &str = ":where([class^=\"hl-\"],[class*=\" hl-\"])";
1026+/// htmlang's cascade layers, from the one that loses to the one that wins:
1027+/// the reset; the defaults of each element's kind (a heading's `margin:0`,
1028+/// a column's `display:flex`); the styles an element gets from an
1029+/// element prefix on an element around it (`@td:padding 8`) and from a
1030+/// function's scoped `@style`; and the element's own styles. So a
1031+/// scope's styles win over the defaults, and what an element says about
1032+/// itself wins over both. CSS outside any layer (`@style`, `@raw`) wins
1033+/// over all of them.
1034+const LAYERS: [&str; 4] = ["hl-reset", "hl-kind", "hl-inside", "htmlang"];
1036+/// Built-in reset rules, in a layer before `htmlang`: unlayered CSS beats
1037+/// every layer, so an unlayered rule here would override the generated
1038+/// ones. A page resets `box-sizing` everywhere and makes `<body>` a column
1039+/// that fills the window; a fragment, which goes into a page it doesn't
1040+/// own, touches only htmlang's own elements. In both, an element htmlang
1041+/// lays out stays hidden while it is `hidden`, a closed `<dialog>` or a
1042+/// popover that isn't showing: its generated `display` would otherwise
1043+/// beat the browser's `display: none`.
1044+fn reset_css(dev: bool, page: bool, focus_visible_css: &str) -> String {
1045+ let own = OWN_ELEMENTS;
1046+ let mut rules = Vec::new();
1048+ rules.push(if dev {
1049+ "*, *::before, *::after { box-sizing: border-box; }".to_string()
764 } else {
1050 } else {
765− element_css.push_str("@starting-style{");
1051+ "*,*::before,*::after{box-sizing:border-box}".to_string()
766− for block in &doc.starting_style_blocks {
1052+ });
767− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1053+ rules.push(if dev {
768− element_css.push_str(&minified);
1054+ "body { margin: 0; font-family: system-ui, -apple-system, sans-serif; display: flex; flex-direction: column; min-height: 100dvh; }".to_string()
770− element_css.push('}');
1056+ "body{margin:0;font-family:system-ui,-apple-system,sans-serif;display:flex;flex-direction:column;min-height:100dvh}".to_string()
1059+ rules.push(if dev {
1060+ format!("{own}, {own}::before, {own}::after {{ box-sizing: border-box; }}")
1062+ format!("{own},{own}::before,{own}::after{{box-sizing:border-box}}")
773−
1065+ let hidden = "[hidden]:not([hidden=\"until-found\"]),dialog:not([open]):not(:popover-open),\
774− // Build meta tags string
1066+ [popover]:not(:popover-open):not(dialog[open])";
775− let meta_html = if doc.meta_tags.is_empty() {
1067+ rules.push(if dev {
776− String::new()
1068+ format!("{own}:where({hidden}) {{ display: none !important; }}")
777 } else {
1069 } else {
778− let mut m = String::new();
1070+ format!("{own}:where({hidden}){{display:none!important}}")
779− for (name, content) in &doc.meta_tags {
1071+ });
780− if dev {
1072+ let mut rules = rules.join(if dev { "\n" } else { "" });
781− m.push_str(&format!(
1073+ if dev {
782− "<meta name=\"{}\" content=\"{}\">\n",
1074+ rules.push('\n');
783− html_escape(name),
1075+ }
784− html_escape(content)
1076+ rules.push_str(focus_visible_css);
786− } else {
1078+ format!(
787− m.push_str(&format!(
1079+ "@layer {};\n@layer hl-reset {{\n{}}}\n",
788− "<meta name=\"{}\" content=\"{}\">",
1080+ LAYERS.join(", "),
789− html_escape(name),
1081+ rules
790− html_escape(content)
1082+ )
797− // Build OG meta tags
798− let og_html = if doc.og_tags.is_empty() {
801− let mut o = String::new();
802− for (property, content) in &doc.og_tags {
804− o.push_str(&format!(
805− "<meta property=\"og:{}\" content=\"{}\">\n",
806− html_escape(property),
807− html_escape(content)
810− o.push_str(&format!(
811− "<meta property=\"og:{}\" content=\"{}\">",
812− html_escape(property),
813− html_escape(content)
820− // Build head blocks string
821− let head_html = if doc.head_blocks.is_empty() {
824− let mut h = String::new();
825− for block in &doc.head_blocks {
834− let lang_attr = match &doc.lang {
835− Some(lang) => format!(" lang=\"{}\"", html_escape(lang)),
836− None => String::new(),
839− let favicon_html = match &doc.favicon {
841− // Try to read and inline the favicon
842− if let Ok(data) = std::fs::read(path) {
843− let mime = if path.ends_with(".ico") {
845− } else if path.ends_with(".png") {
847− } else if path.ends_with(".svg") {
852− let b64 = base64_encode(&data);
854− format!("<link rel=\"icon\" href=\"data:{};base64,{}\">\n", mime, b64)
856− format!("<link rel=\"icon\" href=\"data:{};base64,{}\">", mime, b64)
859− // Fall back to href
861− format!("<link rel=\"icon\" href=\"{}\">\n", html_escape(path))
863− format!("<link rel=\"icon\" href=\"{}\">", html_escape(path))
867− None => String::new(),
871− let canonical_html = match &doc.canonical {
874− format!("<link rel=\"canonical\" href=\"{}\">\n", html_escape(url))
876− format!("<link rel=\"canonical\" href=\"{}\">", html_escape(url))
879− None => String::new(),
883− let base_html = match &doc.base_url {
886− format!("<base href=\"{}\">\n", html_escape(url))
888− format!("<base href=\"{}\">", html_escape(url))
891− None => String::new(),
895− for (name, url) in &doc.font_faces {
896− let format_hint = if url.ends_with(".woff2") {
898− } else if url.ends_with(".woff") {
900− } else if url.ends_with(".ttf") {
901− " format('truetype')"
902− } else if url.ends_with(".otf") {
903− " format('opentype')"
908− element_css.insert_str(0, &format!(
909− "@font-face {{\n font-family: '{}';\n src: url('{}'){};\n font-display: swap;\n}}\n",
910− name, url, format_hint
913− element_css.insert_str(0, &format!(
914− "@font-face{{font-family:'{}';src:url('{}'){};font-display:swap}}",
915− name, url, format_hint
921− let json_ld_html: String = doc.json_ld_blocks.iter().map(|block| {
923− format!("<script type=\"application/ld+json\">\n{}\n</script>\n", block)
925− format!("<script type=\"application/ld+json\">{}</script>", block)
930− let manifest_html = if let Some(ref manifest) = doc.manifest {
931− let mut json = String::from("{");
932− json.push_str(&format!("\"name\":\"{}\",", manifest.name));
933− if let Some(ref short) = manifest.short_name {
934− json.push_str(&format!("\"short_name\":\"{}\",", short));
936− json.push_str(&format!("\"start_url\":\"{}\",", manifest.start_url));
937− json.push_str(&format!("\"display\":\"{}\"", manifest.display));
938− if let Some(ref bg) = manifest.background_color {
939− json.push_str(&format!(",\"background_color\":\"{}\"", bg));
941− if let Some(ref tc) = manifest.theme_color {
942− json.push_str(&format!(",\"theme_color\":\"{}\"", tc));
944− if let Some(ref desc) = manifest.description {
945− json.push_str(&format!(",\"description\":\"{}\"", desc));
947− if !manifest.icons.is_empty() {
948− json.push_str(",\"icons\":[");
949− for (i, (src, sizes)) in manifest.icons.iter().enumerate() {
950− if i > 0 { json.push(','); }
951− json.push_str(&format!("{{\"src\":\"{}\",\"sizes\":\"{}\",\"type\":\"image/png\"}}", src, sizes));
957− // Inline the manifest as a data URI
958− let encoded = base64_encode(json.as_bytes());
960− format!("<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">\n", encoded)
962− format!("<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">", encoded)
968− // Preload hints (auto-detect fonts from @font-face)
969− let mut preload_html = String::new();
970− for (_, url) in &doc.font_faces {
972− preload_html.push_str(&format!(
973− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>\n", url
976− preload_html.push_str(&format!(
977− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>", url
981− // Explicit preload hints from the document
982− for hint in &doc.preload_hints {
984− preload_html.push_str(&format!(
985− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>\n",
986− html_escape(&hint.href), hint.as_type,
987− if hint.crossorigin { " crossorigin" } else { "" }
990− preload_html.push_str(&format!(
991− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>",
992− html_escape(&hint.href), hint.as_type,
993− if hint.crossorigin { " crossorigin" } else { "" }
998− // Auto theme-color meta from @theme primary token
999− let theme_color_html = doc.theme_tokens.iter()
1000− .find(|(name, _)| name == "primary" || name == "theme-color")
1001− .map(|(_, value)| {
1003− format!("<meta name=\"theme-color\" content=\"{}\">\n", html_escape(value))
1005− format!("<meta name=\"theme-color\" content=\"{}\">", html_escape(value))
1008− .unwrap_or_default();
1010− // Focus-visible CSS for interactive elements (accessibility)
1011− let focus_visible_css = if ctx.has_interactive {
1013− "a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }\n"
1015− "a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid currentColor;outline-offset:2px}"
1021− // Skip-to-content CSS (visually hidden but accessible)
1022− let skip_link_css = if has_main {
1024− ".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"
1026− ".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}"
1028 } else {
1083 } else {
1029− ""
1084+ format!("@layer {};@layer hl-reset{{{}}}", LAYERS.join(","), rules)
1032− // Noscript fallback: show deferred content if JS is disabled
1033− let noscript_html = if ctx.has_defer {
1035− "<noscript><style>.hl-defer-placeholder { display: none; }</style></noscript>\n"
1037− "<noscript><style>.hl-defer-placeholder{display:none}</style></noscript>"
1043− match &doc.page_title {
1051−<meta charset=\"utf-8\">
1052−<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
1053−<title>{title}</title>
1054−{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}\
1056−*, *::before, *::after {{ box-sizing: border-box; }}
1057−body {{ margin: 0; font-family: system-ui, -apple-system, sans-serif; }}
1058−img {{ display: block; }}
1059−{focus_visible_css}{skip_link_css}{element_css}\
1068− title = html_escape(title),
1069− lang_attr = lang_attr,
1070− theme_color_html = theme_color_html,
1071− base_html = base_html,
1072− canonical_html = canonical_html,
1073− manifest_html = manifest_html,
1074− preload_html = preload_html,
1075− dns_prefetch_html = dns_prefetch_html,
1076− meta_html = meta_html,
1077− favicon_html = favicon_html,
1078− json_ld_html = json_ld_html,
1079− head_html = head_html,
1081− focus_visible_css = focus_visible_css,
1082− skip_link_css = skip_link_css,
1083− noscript_html = noscript_html,
1084− element_css = element_css,
1089− "<!DOCTYPE html><html{lang_attr}><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>{title}</title>{theme_color_html}{base_html}{canonical_html}{manifest_html}{preload_html}{dns_prefetch_html}{meta_html}{og_html}{favicon_html}{json_ld_html}{head_html}<style>*,*::before,*::after{{box-sizing:border-box}}body{{margin:0;font-family:system-ui,-apple-system,sans-serif}}img{{display:block}}{focus_visible_css}{skip_link_css}{element_css}</style>{noscript_html}</head><body>{body}</body></html>",
1090− title = html_escape(title),
1091− lang_attr = lang_attr,
1092− theme_color_html = theme_color_html,
1093− base_html = base_html,
1094− canonical_html = canonical_html,
1095− manifest_html = manifest_html,
1096− preload_html = preload_html,
1097− dns_prefetch_html = dns_prefetch_html,
1098− meta_html = meta_html,
1100− favicon_html = favicon_html,
1101− json_ld_html = json_ld_html,
1102− head_html = head_html,
1103− focus_visible_css = focus_visible_css,
1104− skip_link_css = skip_link_css,
1105− noscript_html = noscript_html,
1106− element_css = element_css,
1112− if element_css.is_empty() {
1116− format!("<style>\n{}</style>\n{}", element_css, body)
1118− format!("<style>{}</style>{}", element_css, body)
1125/// 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.
1126−fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1089+fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
1127 let mut styles = StyleCollector::new();
1090 let mut styles = StyleCollector::new();
1128− let mut ctx = GenContext { dev, depth: 0, image_count: 0, has_interactive: false, has_defer: false };
1091+ let mut ctx = GenContext {
1094+ has_interactive: false,
1096+ flow: Flow::default(),
1129 let mut body = String::new();
1099 let mut body = String::new();
1131− for node in &doc.nodes {
1101+ generate_children(&doc.nodes, None, &mut body, &mut styles, &mut ctx);
1132− generate_node(node, None, &mut body, &mut styles, &mut ctx);
1135− let has_custom_css = !doc.custom_css.is_empty();
1136− let mut element_css = String::new();
1138− // CSS custom properties
1139− if !doc.css_vars.is_empty() || !doc.theme_tokens.is_empty() {
1141− element_css.push_str(":root {\n");
1142− for (name, value) in &doc.css_vars {
1143− element_css.push_str(&format!(" {}: {};\n", name, value));
1145− for (name, value) in &doc.theme_tokens {
1146− let css_name = format!("--{}", name);
1147− if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
1148− element_css.push_str(&format!(" {}: {};\n", css_name, value));
1151− element_css.push_str("}\n");
1153− element_css.push_str(":root{");
1154− for (name, value) in &doc.css_vars {
1155− element_css.push_str(name);
1156− element_css.push(':');
1157− element_css.push_str(value);
1158− element_css.push(';');
1160− for (name, value) in &doc.theme_tokens {
1161− let css_name = format!("--{}", name);
1162− if !doc.css_vars.iter().any(|(n, _)| *n == css_name) {
1163− element_css.push_str(&css_name);
1164− element_css.push(':');
1165− element_css.push_str(value);
1166− element_css.push(';');
1169− element_css.push('}');
1173− element_css.push_str(&styles.to_css_formatted(dev, !has_custom_css));
1175− for (name, kf_body) in &doc.keyframes {
1177− element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1179− element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1183− for block in &doc.custom_css {
1103+ let mut element_css = build_element_css(doc, &styles, dev);
1184− if dev {
1104+ // htmlang's own elements get the reset's rules for elements (which
1185− element_css.push_str(block);
1105+ // also puts htmlang's layers in order)
1186− element_css.push('\n');
1106+ if !styles.entries.is_empty() || !doc.scoped_css.is_empty() {
1187− } else {
1107+ element_css.insert_str(0, &reset_css(dev, false, ""));
1188− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1189− element_css.push_str(&minified);
1109+ classes.extend(styles.classes());
1193 if element_css.is_empty() {
1111 if element_css.is_empty() {
@@ -1203,29 +1121,20 @@ fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1203// Node generation
1121// Node generation
1204// ---------------------------------------------------------------------------
1122// ---------------------------------------------------------------------------
1124+/// Write `node`, which is inside an element with the layout `parent`
1125+/// (`None` at the top of the page).
1206fn generate_node(
1126fn generate_node(
1207 node: &Node,
1127 node: &Node,
1208− parent_kind: Option<&ElementKind>,
1128+ parent: Option<Layout>,
1209 out: &mut String,
1129 out: &mut String,
1210 styles: &mut StyleCollector,
1130 styles: &mut StyleCollector,
1211 ctx: &mut GenContext,
1131 ctx: &mut GenContext,
1213 match node {
1133 match node {
1214− Node::Element(elem) => generate_element(elem, parent_kind, out, styles, ctx),
1134+ Node::Element(elem) => generate_element(elem, parent, out, styles, ctx),
1215 Node::Text(segments) => {
1135 Node::Text(segments) => {
1216− let needs_wrap = matches!(
1136+ // In a row, column or grid each line of text is a child
1217− parent_kind,
1137+ let needs_wrap = parent.is_some_and(Layout::is_container);
1218− Some(ElementKind::Row) | Some(ElementKind::Column) | Some(ElementKind::El)
1219− | Some(ElementKind::Nav) | Some(ElementKind::Header) | Some(ElementKind::Footer)
1220− | Some(ElementKind::Main) | Some(ElementKind::Section) | Some(ElementKind::Article)
1221− | Some(ElementKind::Aside) | Some(ElementKind::ListItem)
1222− | Some(ElementKind::Form) | Some(ElementKind::Details) | Some(ElementKind::Figure)
1223− | Some(ElementKind::Blockquote)
1224− | Some(ElementKind::Dialog) | Some(ElementKind::DefinitionList)
1225− | Some(ElementKind::DefinitionDescription) | Some(ElementKind::Fieldset)
1226− | Some(ElementKind::Datalist) | Some(ElementKind::Grid) | Some(ElementKind::Stack)
1227− | Some(ElementKind::Noscript) | Some(ElementKind::Address) | Some(ElementKind::Search)
1229 if needs_wrap {
1138 if needs_wrap {
1230 out.push_str(&ctx.indent());
1139 out.push_str(&ctx.indent());
1231 out.push_str("<span>");
1140 out.push_str("<span>");
@@ -1244,113 +1153,197 @@ fn generate_node(
1247−/// 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
1248−const HTML_PASSTHROUGH_ATTRS: &[&str] = &[
1157+/// with this layout (`None`: the top of the page): text flows, so its lines
1249− "type", "placeholder", "name", "value", "disabled", "required", "checked",
1158+/// and children are joined with a space; in HTML's own layout, and at the
1250− "for", "action", "method", "autocomplete",
1159+/// top of the page, two lines of text are separated by a line break (a
1251− "min", "max", "step", "pattern", "maxlength", "rows", "cols", "multiple",
1160+/// space, except where whitespace is kept, as in `@pre`).
1252− "alt", "role", "tabindex", "title", "autofocus",
1161+fn separator(layout: Option<Layout>, previous_is_text: bool, next: &Node) -> Option<char> {
1253− // Media
1162+ match layout {
1254− "controls", "autoplay", "loop", "muted", "poster", "preload",
1163+ Some(Layout::Text) => Some(' '),
1255− // Image optimization
1164+ Some(Layout::Native) | None if previous_is_text && matches!(next, Node::Text(_)) => {
1256− "loading", "decoding",
1165+ Some('\n')
1257− // Media src (explicit attribute form)
1166+ }
1258− "src",
1167+ _ => None,
1259− // New element attributes
1168+ }
1260− "datetime", "media", "sizes", "srcset", "list",
1169+}
1266− "low", "high", "optimum",
1268− "colspan", "rowspan", "scope",
1270− "popover", "popovertarget", "popovertargetaction",
1271− // Modern form/input hints
1272− "inputmode", "enterkeyhint",
1273− // Performance hints
1274− "fetchpriority", "blocking",
1276− "translate", "spellcheck",
1277− // ARIA live regions
1278− "aria-live", "aria-atomic", "aria-relevant",
1281−/// 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
1282−const BOOLEAN_HTML_ATTRS: &[&str] = &[
1172+/// element of its own) laid out as `layout` (`None`: the top of the page).
1283− "disabled", "required", "checked", "multiple",
1173+/// The first line of an element's text is its first child.
1284− "controls", "autoplay", "loop", "muted",
1174+fn generate_children(
1285− "open", "novalidate", "autofocus",
1175+ children: &[Node],
1286− "defer", "async", "nomodule",
1176+ layout: Option<Layout>,
1287− // Popover
1177+ out: &mut String,
1288− "popover",
1178+ styles: &mut StyleCollector,
1289−];
1179+ ctx: &mut GenContext,
1181+ generate_run(children, layout, &mut None, out, styles, ctx);
1291−fn emit_html_passthrough_attrs(out: &mut String, attrs: &[Attribute]) {
1184+/// [`generate_children`], with `previous` saying whether what was written
1292− for attr in attrs {
1185+/// last was a line of text (`None`: nothing yet). A `@fragment`'s children
1293− let key = attr.key.as_str();
1186+/// are written as if they stood in its place, so its lines are separated
1294− let is_passthrough = HTML_PASSTHROUGH_ATTRS.contains(&key)
1187+/// from the lines around it like any other lines.
1295− || key.starts_with("aria-")
1188+fn generate_run(
1296− || key.starts_with("data-");
1189+ children: &[Node],
1297− 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);
1298 continue;
1201 continue;
1300− if BOOLEAN_HTML_ATTRS.contains(&key) && attr.value.is_none() {
1203+ let start = out.len();
1301− out.push(' ');
1204+ if let Some(previous_is_text) = *previous
1302− out.push_str(key);
1205+ && let Some(sep) = separator(layout, previous_is_text, child)
1303− } else if let Some(val) = &attr.value {
1206+ {
1304− out.push(' ');
1207+ out.push(sep);
1305− out.push_str(key);
1208+ }
1306− out.push_str("=\"");
1209+ let body = out.len();
1307− out.push_str(&html_escape(val));
1210+ generate_node(child, layout, out, styles, ctx);
1308− 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(_)));
1221+/// Emit the element's leading argument as its attribute (`@iframe URL` →
1222+/// `src="URL"`, `@form /submit` → `action="/submit"`, `@link /a` →
1223+/// `href="/a"`), first, before the class. `@image [inline] photo.png` puts
1224+/// the file itself into the page.
1225+fn emit_argument_attr(out: &mut String, elem: &Element, in_picture: bool) {
1226+ let (Some(attr), Some(value)) = (elem.kind.leading_attribute(in_picture), &elem.argument)
1230+ // `@image [inline]`'s file is already a `data:` URI (see the parser)
1231+ let value = html_escape(value);
1233+ out.push_str(attr);
1234+ out.push_str("=\"");
1235+ out.push_str(&value);
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")
1313fn generate_element(
1313fn generate_element(
1314 elem: &Element,
1314 elem: &Element,
1315− parent_kind: Option<&ElementKind>,
1315+ parent: Option<Layout>,
1316 out: &mut String,
1316 out: &mut String,
1317 styles: &mut StyleCollector,
1317 styles: &mut StyleCollector,
1318 ctx: &mut GenContext,
1318 ctx: &mut GenContext,
1320 // Self-closing elements
1320 // Self-closing elements
1321− if matches!(elem.kind, ElementKind::Image | ElementKind::Input | ElementKind::HorizontalRule | ElementKind::Source | ElementKind::Spacer) {
1321+ if elem.kind.layout() == Layout::Void {
1322− generate_self_closing(elem, parent_kind, out, styles, ctx);
1322+ generate_self_closing(elem, parent, out, styles, ctx);
1325− // @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
1326− 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);
1327 out.push_str(&ctx.indent());
1329 out.push_str(&ctx.indent());
1328− out.push_str("<script");
1330+ out.push('<');
1329− // Pass through src, type, defer, async, etc.
1331+ out.push_str(tag);
1330− for attr in &elem.attrs {
1332+ emit_argument_attr(out, elem, false);
1331− let key = attr.key.as_str();
1333+ let (id, class) = extract_id_class(&elem.attrs);
1332− if matches!(key, "src" | "type" | "defer" | "async" | "crossorigin" | "integrity" | "nomodule" | "id") {
1334+ for (key, value) in [("id", id), ("class", class)] {
1333− if let Some(val) = &attr.value {
1335+ if let Some(value) = value {
1334− out.push(' ');
1336+ out.push_str(&format!(" {}=\"{}\"", key, html_escape(&value)));
1336− out.push_str("=\"");
1337− out.push_str(&html_escape(val));
1339+ emit_html_attrs(out, &elem.attrs);
1345 out.push('>');
1340 out.push('>');
1346− // Children are raw JS code, not HTML
1347 for child in &elem.children {
1341 for child in &elem.children {
1348 match child {
1342 match child {
1349 Node::Text(segments) => {
1343 Node::Text(segments) => {
1350 for seg in segments {
1344 for seg in segments {
1351− match seg {
1345+ if let TextSegment::Plain(text) = seg {
1352− TextSegment::Plain(text) => out.push_str(text),
1346+ out.push_str(text)
@@ -1358,46 +1351,10 @@ fn generate_element(
1361− out.push_str("</script>");
1354+ out.push_str("</");
1362− out.push_str(ctx.nl());
1355+ out.push_str(tag);
1365− // @breadcrumb generates semantic <nav aria-label="breadcrumb"><ol>...</ol></nav>
1366− if elem.kind == ElementKind::Breadcrumb {
1367− let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles);
1368− let (id, user_class) = extract_id_class(&elem.attrs);
1369− out.push_str(&ctx.indent());
1370− out.push_str("<nav aria-label=\"breadcrumb\"");
1371− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1372− if let Some(id) = id {
1373− out.push_str(" id=\"");
1374− out.push_str(&html_escape(&id));
1377 out.push('>');
1356 out.push('>');
1378 out.push_str(ctx.nl());
1357 out.push_str(ctx.nl());
1380− out.push_str(&ctx.indent());
1381− out.push_str("<ol>");
1382− out.push_str(ctx.nl());
1384− for child in &elem.children {
1385− out.push_str(&ctx.indent());
1386− out.push_str("<li>");
1387− let mut buf = String::new();
1388− generate_node(child, Some(&elem.kind), &mut buf, styles, ctx);
1389− out.push_str(buf.trim());
1390− out.push_str("</li>");
1391− out.push_str(ctx.nl());
1394− out.push_str(&ctx.indent());
1395− out.push_str("</ol>");
1396− out.push_str(ctx.nl());
1398− out.push_str(&ctx.indent());
1399− out.push_str("</nav>");
1400− out.push_str(ctx.nl());
1403 if elem.kind == ElementKind::Children {
1360 if elem.kind == ElementKind::Children {
@@ -1407,266 +1364,54 @@ fn generate_element(
1409 if elem.kind == ElementKind::Fragment {
1366 if elem.kind == ElementKind::Fragment {
1410− // Render children without a wrapper element
1367+ // Render children without a wrapper element, as if they were
1411− for child in &elem.children {
1368+ // written where the fragment is
1412− generate_node(child, parent_kind, out, styles, ctx);
1369+ generate_children(&elem.children, parent, out, styles, ctx);
1373+ let mut own = Flow::of(elem);
1417 let tag = match &elem.kind {
1374 let tag = match &elem.kind {
1418− ElementKind::Row | ElementKind::Column | ElementKind::El
1375+ ElementKind::Row | ElementKind::El => "div",
1419− | ElementKind::Grid | ElementKind::Stack => "div",
1420 ElementKind::Text => "span",
1376 ElementKind::Text => "span",
1421 ElementKind::Paragraph => "p",
1377 ElementKind::Paragraph => "p",
1422 ElementKind::Link => "a",
1378 ElementKind::Link => "a",
1423− ElementKind::Button => "button",
1379+ ElementKind::Tag(spec) => spec.html,
1424− ElementKind::Select => "select",
1425− ElementKind::Textarea => "textarea",
1426− ElementKind::Option => "option",
1427− ElementKind::Label => "label",
1428− // Semantic elements
1429− ElementKind::Nav => "nav",
1430− ElementKind::Header => "header",
1431− ElementKind::Footer => "footer",
1432− ElementKind::Main => "main",
1433− ElementKind::Section => "section",
1434− ElementKind::Article => "article",
1435− ElementKind::Aside => "aside",
1437− ElementKind::List => {
1438− if elem.attrs.iter().any(|a| a.key == "ordered") { "ol" } else { "ul" }
1440− ElementKind::ListItem => "li",
1442− ElementKind::Table => "table",
1443− ElementKind::TableHead => "thead",
1444− ElementKind::TableBody => "tbody",
1445− ElementKind::TableRow => "tr",
1446− ElementKind::TableCell => "td",
1447− ElementKind::TableHeaderCell => "th",
1449− ElementKind::Video => "video",
1450− ElementKind::Audio => "audio",
1451− // Additional semantic elements
1452− ElementKind::Form => "form",
1453− ElementKind::Details => "details",
1454− ElementKind::Summary => "summary",
1455− ElementKind::Blockquote => "blockquote",
1456− ElementKind::Cite => "cite",
1457− ElementKind::Code => "code",
1458− ElementKind::Pre => "pre",
1459− ElementKind::Figure => "figure",
1460− ElementKind::FigCaption => "figcaption",
1461− ElementKind::Progress => "progress",
1462− ElementKind::Meter => "meter",
1464− ElementKind::Dialog => "dialog",
1465− ElementKind::DefinitionList => "dl",
1466− ElementKind::DefinitionTerm => "dt",
1467− ElementKind::DefinitionDescription => "dd",
1468− ElementKind::Fieldset => "fieldset",
1469− ElementKind::Legend => "legend",
1470− ElementKind::Picture => "picture",
1471− ElementKind::Time => "time",
1472− ElementKind::Mark => "mark",
1473− ElementKind::Kbd => "kbd",
1474− ElementKind::Abbr => "abbr",
1475− ElementKind::Datalist => "datalist",
1476− ElementKind::Iframe => "iframe",
1477− ElementKind::Output => "output",
1478− ElementKind::Canvas => "canvas",
1479− ElementKind::Badge => "span",
1480− ElementKind::Tooltip => "span",
1481− ElementKind::Avatar => "div",
1482− ElementKind::Carousel => "div",
1483− ElementKind::Chip => "span",
1484− ElementKind::Tag => "span",
1485− ElementKind::Noscript => "noscript",
1486− ElementKind::Address => "address",
1487− ElementKind::Search => "search",
1488− ElementKind::Image | ElementKind::Input | ElementKind::HorizontalRule
1489− | ElementKind::Children | ElementKind::Slot(_) | ElementKind::Fragment
1490− | ElementKind::Source | ElementKind::Spacer
1491− | ElementKind::Script | ElementKind::Breadcrumb => unreachable!(),
1494− let kind_label = match elem.kind {
1495− ElementKind::Row => "row",
1496− ElementKind::Column => "column",
1497− ElementKind::El => "el",
1498− ElementKind::Text => "text",
1499− ElementKind::Paragraph => "paragraph",
1500− ElementKind::Link => "link",
1501− ElementKind::Button => "button",
1502− ElementKind::Select => "select",
1503− ElementKind::Textarea => "textarea",
1504− ElementKind::Option => "option",
1505− ElementKind::Label => "label",
1506− ElementKind::Nav => "nav",
1507− ElementKind::Header => "header",
1508− ElementKind::Footer => "footer",
1509− ElementKind::Main => "main",
1510− ElementKind::Section => "section",
1511− ElementKind::Article => "article",
1512− ElementKind::Aside => "aside",
1513− ElementKind::List => "list",
1514− ElementKind::ListItem => "item",
1515− ElementKind::Table => "table",
1516− ElementKind::TableHead => "thead",
1517− ElementKind::TableBody => "tbody",
1518− ElementKind::TableRow => "tr",
1519− ElementKind::TableCell => "td",
1520− ElementKind::TableHeaderCell => "th",
1521− ElementKind::Video => "video",
1522− ElementKind::Audio => "audio",
1523− ElementKind::Form => "form",
1524− ElementKind::Details => "details",
1525− ElementKind::Summary => "summary",
1526− ElementKind::Blockquote => "blockquote",
1527− ElementKind::Cite => "cite",
1528− ElementKind::Code => "code",
1529− ElementKind::Pre => "pre",
1530− ElementKind::Figure => "figure",
1531− ElementKind::FigCaption => "figcaption",
1532− ElementKind::Fragment => "fragment",
1533− ElementKind::Dialog => "dialog",
1534− ElementKind::DefinitionList => "dl",
1535− ElementKind::DefinitionTerm => "dt",
1536− ElementKind::DefinitionDescription => "dd",
1537− ElementKind::Fieldset => "fieldset",
1538− ElementKind::Legend => "legend",
1539− ElementKind::Picture => "picture",
1540− ElementKind::Time => "time",
1541− ElementKind::Mark => "mark",
1542− ElementKind::Kbd => "kbd",
1543− ElementKind::Abbr => "abbr",
1544− ElementKind::Datalist => "datalist",
1545− ElementKind::Iframe => "iframe",
1546− ElementKind::Output => "output",
1547− ElementKind::Canvas => "canvas",
1548− ElementKind::Grid => "grid",
1549− ElementKind::Stack => "stack",
1550− ElementKind::Badge => "badge",
1551− ElementKind::Tooltip => "tooltip",
1552− ElementKind::Avatar => "avatar",
1553− ElementKind::Carousel => "carousel",
1554− ElementKind::Chip => "chip",
1555− ElementKind::Tag => "tag",
1556− ElementKind::Noscript => "noscript",
1557− ElementKind::Address => "address",
1558− ElementKind::Search => "search",
1559 _ => "",
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();
1562 // Track interactive elements for focus-visible CSS
1389 // Track interactive elements for focus-visible CSS
1563− if matches!(elem.kind, ElementKind::Link | ElementKind::Button | ElementKind::Input
1390+ if elem.kind == ElementKind::Link
1564− | ElementKind::Select | ElementKind::Textarea) {
1391+ || matches!(kind_label, "button" | "input" | "select" | "textarea")
1565 ctx.has_interactive = true;
1393 ctx.has_interactive = true;
1568 // Compute CSS for each state and get a class name
1396 // Compute CSS for each state and get a class name
1569− 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();
1570 let (id, user_class) = extract_id_class(&elem.attrs);
1399 let (id, user_class) = extract_id_class(&elem.attrs);
1572 if ctx.dev && elem.line_num > 0 {
1401 if ctx.dev && elem.line_num > 0 {
1573 out.push_str(&ctx.indent());
1402 out.push_str(&ctx.indent());
1574− out.push_str(&format!("<!-- @{} line {} -->\n", kind_label, elem.line_num));
1403+ out.push_str(&format!(
1404+ "<!-- @{} line {} -->\n",
1405+ kind_label, elem.line_num
1576 out.push_str(&ctx.indent());
1408 out.push_str(&ctx.indent());
1577 out.push('<');
1409 out.push('<');
1578 out.push_str(tag);
1410 out.push_str(tag);
1580− // @main gets id="hl-main" for skip-to-content link (unless user set an id)
1412+ emit_argument_attr(out, elem, ctx.in_picture);
1581− if elem.kind == ElementKind::Main && id.is_none() {
1582− out.push_str(" id=\"hl-main\"");
1585− if elem.kind == ElementKind::Link {
1586− if let Some(url) = &elem.argument {
1587− out.push_str(" href=\"");
1588− out.push_str(&html_escape(url));
1590− // Auto rel="noopener noreferrer" and target="_blank" for external links
1591− let is_external = url.starts_with("http://") || url.starts_with("https://");
1593− let has_rel = elem.attrs.iter().any(|a| a.key == "rel");
1594− let has_target = elem.attrs.iter().any(|a| a.key == "target");
1596− out.push_str(" rel=\"noopener noreferrer\"");
1599− out.push_str(" target=\"_blank\"");
1606− if matches!(elem.kind, ElementKind::Video | ElementKind::Audio) {
1607− if let Some(src) = &elem.argument {
1608− out.push_str(" src=\"");
1609− out.push_str(&html_escape(src));
1615− if elem.kind == ElementKind::Form {
1616− if let Some(action) = &elem.argument {
1617− out.push_str(" action=\"");
1618− out.push_str(&html_escape(action));
1624− if elem.kind == ElementKind::Iframe {
1625− if let Some(src) = &elem.argument {
1626− out.push_str(" src=\"");
1627− out.push_str(&html_escape(src));
1633− if elem.kind == ElementKind::Tooltip {
1634− if let Some(text) = &elem.argument {
1635− out.push_str(" title=\"");
1636− out.push_str(&html_escape(text));
1642− if elem.kind == ElementKind::Time {
1643− if let Some(dt) = elem.attrs.iter().find(|a| a.key == "datetime") {
1644− if let Some(val) = &dt.value {
1645− out.push_str(" datetime=\"");
1646− out.push_str(&html_escape(val));
1652− // Critical CSS: inline styles directly instead of using a class
1414+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1653− let is_critical = elem.attrs.iter().any(|a| a.key == "critical");
1655− let inline_css = attrs_to_css(&elem.attrs, "", &elem.kind, parent_kind);
1656− if !inline_css.is_empty() {
1657− out.push_str(" style=\"");
1658− out.push_str(&html_escape(&inline_css));
1661− // Still use class for non-base styles (pseudo, responsive, etc.)
1662− if gen_class.as_deref().map_or(false, |c| !c.is_empty()) {
1663− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1664− } else if let Some(ref uc) = user_class {
1665− emit_class_attr(out, None, Some(uc));
1668− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1671 if let Some(id) = id {
1416 if let Some(id) = id {
1672 out.push_str(" id=\"");
1417 out.push_str(" id=\"");
@@ -1674,60 +1419,38 @@ fn generate_element(
1674 out.push('"');
1419 out.push('"');
1677− emit_html_passthrough_attrs(out, &elem.attrs);
1422+ emit_html_attrs(out, &elem.attrs);
1679 // Source map attributes in dev mode
1424 // Source map attributes in dev mode
1680 if ctx.dev && elem.line_num > 0 {
1425 if ctx.dev && elem.line_num > 0 {
1681− out.push_str(&format!(" data-hl-line=\"{}\" data-hl-el=\"{}\"", elem.line_num, kind_label));
1426+ out.push_str(&format!(
1427+ " data-hl-line=\"{}\" data-hl-el=\"{}\"",
1428+ elem.line_num, kind_label
1684 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");
1685 out.push_str(ctx.nl());
1438 out.push_str(ctx.nl());
1687− // Inline text argument
1440+ let layout = elem.kind.layout();
1691− | ElementKind::Button
1692− | ElementKind::Label
1693− | ElementKind::Option
1694− | ElementKind::Textarea
1695− | ElementKind::ListItem
1696− | ElementKind::TableCell
1697− | ElementKind::TableHeaderCell
1698− | ElementKind::Summary
1699− | ElementKind::Cite
1700− | ElementKind::Code
1701− | ElementKind::FigCaption
1702− | ElementKind::Legend
1703− | ElementKind::DefinitionTerm
1704− | ElementKind::Mark
1706− | ElementKind::Abbr
1707− | ElementKind::Time
1708− | ElementKind::DefinitionDescription
1709− | ElementKind::Badge
1710− | ElementKind::Tooltip
1711− | ElementKind::Chip
1714− if let Some(text) = &elem.argument {
1715− out.push_str(&html_escape(text));
1720 ctx.depth += 1;
1441 ctx.depth += 1;
1721− let is_paragraph = elem.kind == ElementKind::Paragraph;
1442+ let outer_in_text = ctx.in_text;
1722− for (i, child) in elem.children.iter().enumerate() {
1443+ ctx.in_text = in_text || layout == Layout::Text;
1723− generate_node(child, Some(&elem.kind), out, styles, ctx);
1444+ let outer_flow = std::mem::replace(&mut ctx.flow, own);
1724− if is_paragraph && i < elem.children.len() - 1 {
1445+ let outer_picture = std::mem::replace(&mut ctx.in_picture, elem.kind.is_tag("picture"));
1725− out.push(' ');
1446+ generate_children(&elem.children, Some(layout), out, styles, ctx);
1726− }
1447+ ctx.in_picture = outer_picture;
1727− }
1448+ ctx.flow = outer_flow;
1449+ ctx.in_text = outer_in_text;
1728 ctx.depth -= 1;
1450 ctx.depth -= 1;
1730 out.push_str(&ctx.indent());
1452 out.push_str(&ctx.indent());
1453+ ctx.dev = outer_dev;
1731 out.push_str("</");
1454 out.push_str("</");
1732 out.push_str(tag);
1455 out.push_str(tag);
1733 out.push('>');
1456 out.push('>');
@@ -1736,60 +1459,31 @@ fn generate_element(
1737fn generate_self_closing(
1460fn generate_self_closing(
1738 elem: &Element,
1461 elem: &Element,
1739− parent_kind: Option<&ElementKind>,
1462+ parent: Option<Layout>,
1740 out: &mut String,
1463 out: &mut String,
1741 styles: &mut StyleCollector,
1464 styles: &mut StyleCollector,
1742 ctx: &mut GenContext,
1465 ctx: &mut GenContext,
1744− 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);
1745 let (id, user_class) = extract_id_class(&elem.attrs);
1468 let (id, user_class) = extract_id_class(&elem.attrs);
1747− let (tag, kind_label) = match elem.kind {
1470+ let (tag, kind_label) = match &elem.kind {
1748 ElementKind::Image => ("img", "image"),
1471 ElementKind::Image => ("img", "image"),
1749− ElementKind::Input => ("input", "input"),
1472+ ElementKind::Tag(spec) => (spec.html, spec.name),
1750− ElementKind::HorizontalRule => ("hr", "hr"),
1473+ _ => unreachable!("not a void element: {:?}", elem.kind),
1751− ElementKind::Source => ("source", "source"),
1752− ElementKind::Spacer => ("div", "spacer"),
1753− _ => unreachable!(),
1756 if ctx.dev && elem.line_num > 0 {
1476 if ctx.dev && elem.line_num > 0 {
1757 out.push_str(&ctx.indent());
1477 out.push_str(&ctx.indent());
1758− out.push_str(&format!("<!-- @{} line {} -->\n", kind_label, elem.line_num));
1478+ out.push_str(&format!(
1479+ "<!-- @{} line {} -->\n",
1480+ kind_label, elem.line_num
1760 out.push_str(&ctx.indent());
1483 out.push_str(&ctx.indent());
1761 out.push('<');
1484 out.push('<');
1762 out.push_str(tag);
1485 out.push_str(tag);
1763−
1486+ emit_argument_attr(out, elem, ctx.in_picture);
1764− // Image src (with optional non-SVG base64 inlining)
1765− if elem.kind == ElementKind::Image {
1766− let src = elem.argument.as_deref().unwrap_or("");
1767− let is_inline = elem.attrs.iter().any(|a| a.key == "inline");
1768− if is_inline && !src.is_empty() && !src.ends_with(".svg") {
1769− let mime = if src.ends_with(".png") { "image/png" }
1770− else if src.ends_with(".jpg") || src.ends_with(".jpeg") { "image/jpeg" }
1771− else if src.ends_with(".gif") { "image/gif" }
1772− else if src.ends_with(".webp") { "image/webp" }
1773− else if src.ends_with(".avif") { "image/avif" }
1774− else { "application/octet-stream" };
1775− if let Ok(data) = std::fs::read(src) {
1776− let b64 = base64_encode(&data);
1777− out.push_str(" src=\"data:");
1778− out.push_str(mime);
1779− out.push_str(";base64,");
1780− out.push_str(&b64);
1783− out.push_str(" src=\"");
1784− out.push_str(&html_escape(src));
1788− out.push_str(" src=\"");
1789− out.push_str(&html_escape(src));
1794 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());
@@ -1799,97 +1493,14 @@ fn generate_self_closing(
1799 out.push('"');
1493 out.push('"');
1802− emit_html_passthrough_attrs(out, &elem.attrs);
1496+ emit_html_attrs(out, &elem.attrs);
1804 // Source map attributes in dev mode (self-closing)
1498 // Source map attributes in dev mode (self-closing)
1805 if ctx.dev && elem.line_num > 0 {
1499 if ctx.dev && elem.line_num > 0 {
1806− out.push_str(&format!(" data-hl-line=\"{}\" data-hl-el=\"{}\"", elem.line_num, kind_label));
1500+ out.push_str(&format!(
1807− }
1501+ " data-hl-line=\"{}\" data-hl-el=\"{}\"",
1808−
1502+ elem.line_num, kind_label
1809− // Image optimization: auto-add loading="lazy" and decoding="async"
1503+ ));
1810− if elem.kind == ElementKind::Image {
1811− // SVG inlining: @image [inline] logo.svg
1812− if elem.attrs.iter().any(|a| a.key == "inline") {
1813− if let Some(src) = &elem.argument {
1814− if src.ends_with(".svg") {
1815− if let Ok(svg_content) = std::fs::read_to_string(src) {
1816− // Close the tag we opened, then emit inline SVG instead
1817− out.truncate(out.rfind('<').unwrap_or(0));
1818− out.push_str(&ctx.indent());
1819− out.push_str(svg_content.trim());
1820− out.push_str(ctx.nl());
1826− // Responsive srcset: @image photo.jpg [responsive 400 800 1200]
1827− let responsive_attr = elem.attrs.iter().find(|a| a.key == "responsive");
1828− if let Some(resp) = responsive_attr {
1829− if let Some(ref sizes_str) = resp.value {
1830− let widths: Vec<&str> = sizes_str.split_whitespace().collect();
1831− if !widths.is_empty() {
1832− let src = elem.argument.as_deref().unwrap_or("");
1833− if !src.is_empty() {
1834− // Generate srcset with width descriptors
1835− // Convention: file-{width}.ext (e.g., photo-400.jpg)
1836− let dot_pos = src.rfind('.').unwrap_or(src.len());
1837− let base = &src[..dot_pos];
1838− let ext = &src[dot_pos..];
1839− let mut srcset_parts = Vec::new();
1841− srcset_parts.push(format!("{}-{}{} {}w", base, w, ext, w));
1843− out.push_str(" srcset=\"");
1844− out.push_str(&srcset_parts.join(", "));
1846− // Generate sizes attribute
1847− let max_width = widths.last().unwrap_or(&"100vw");
1848− out.push_str(&format!(" sizes=\"(max-width: {}px) 100vw, {}px\"", max_width, max_width));
1854− // Auto image dimensions: read local image file to inject width/height + aspect-ratio
1855− let has_width = elem.attrs.iter().any(|a| a.key == "width");
1856− let has_height = elem.attrs.iter().any(|a| a.key == "height");
1857− if !has_width || !has_height {
1858− if let Some(ref src) = elem.argument {
1859− if !src.starts_with("http://") && !src.starts_with("https://") && !src.starts_with("data:") {
1860− if let Some((w, h)) = read_image_dimensions(src) {
1862− out.push_str(&format!(" width=\"{}\"", w));
1865− out.push_str(&format!(" height=\"{}\"", h));
1867− // Auto aspect-ratio to prevent CLS
1868− if !elem.attrs.iter().any(|a| a.key == "aspect-ratio") {
1869− out.push_str(&format!(" style=\"aspect-ratio:{}/{}\"", w, h));
1876− // Smart image loading: first 3 images get fetchpriority="high" (above the fold),
1877− // subsequent images get loading="lazy" + decoding="async"
1878− ctx.image_count += 1;
1879− if ctx.image_count <= 3 {
1880− // Above-the-fold: eager loading with high priority
1881− if !elem.attrs.iter().any(|a| a.key == "fetchpriority") {
1882− out.push_str(" fetchpriority=\"high\"");
1885− // Below-the-fold: lazy loading
1886− if !elem.attrs.iter().any(|a| a.key == "loading") {
1887− out.push_str(" loading=\"lazy\"");
1889− if !elem.attrs.iter().any(|a| a.key == "decoding") {
1890− out.push_str(" decoding=\"async\"");
1895 out.push('>');
1506 out.push('>');
@@ -1907,7 +1518,10 @@ fn generate_text_segments(
1907 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
1518 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
1908 TextSegment::Inline(elem) => {
1519 TextSegment::Inline(elem) => {
1909 let mut buf = String::new();
1520 let mut buf = String::new();
1910− 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;
1911 out.push_str(buf.trim_end());
1525 out.push_str(buf.trim_end());
@@ -1920,97 +1534,183 @@ fn generate_text_segments(
1921fn compute_class(
1535fn compute_class(
1922 attrs: &[Attribute],
1536 attrs: &[Attribute],
1923− kind: &ElementKind,
1537+ site: &Site,
1924− parent_kind: Option<&ElementKind>,
1925 styles: &mut StyleCollector,
1538 styles: &mut StyleCollector,
1926) -> Option<String> {
1540) -> Option<String> {
1927− let base = attrs_to_css(attrs, "", kind, parent_kind);
1541+ // Every condition an attribute is under, and none
1542+ let mut conditions = vec![Condition::default()];
1543+ for attr in attrs.iter().filter(|a| !a.html) {
1544+ let (condition, _) = Condition::of(&attr.key);
1545+ if !conditions.contains(&condition) {
1546+ conditions.push(condition);
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)
1929− // Collect pseudo-state overrides
1573+/// The defaults of an element's kind where it is: an overlay's positioning
1930− let mut pseudo = Vec::new();
1574+/// context, its layout, and its kind's own CSS (a heading's `margin:0`).
1931− for &(prefix, selector) in PSEUDO_PREFIXES {
1575+fn default_css(site: &Site) -> String {
1932− let css = attrs_to_css(attrs, prefix, kind, parent_kind);
1576+ let mut css = String::new();
1933− if !css.is_empty() {
1577+ // Elements with @in-front / @behind children become positioning
1934− pseudo.push((selector.to_string(), css));
1578+ // contexts
1935− }
1579+ if site.has_overlay_children {
1580+ css.push_str("position:relative;isolation:isolate;");
1937−
1582+ if !site.root {
1938− // Auto-add ::-webkit-scrollbar pseudo for no-scrollbar attribute
1583+ css.push_str(layout_css(site.kind.layout(), site.inline));
1939− if attrs.iter().any(|a| a.key == "no-scrollbar") {
1940− pseudo.push(("::-webkit-scrollbar".to_string(), "display:none;".to_string()));
1585+ css.push_str(site.kind.css());
1943− // Collect nth:EXPR: dynamic pseudo selectors
1589+/// The declarations of a rule body, as (property, `property:value;`), for
1944− let mut nth_prefixes: Vec<String> = Vec::new();
1590+/// bodies htmlang wrote: every declaration ends in `;`, and a `;` inside
1945− for attr in attrs {
1591+/// quotes or parentheses doesn't end one.
1946− if attr.key.starts_with("nth:") {
1592+fn declarations(css: &str) -> impl Iterator<Item = (&str, &str)> {
1947− let rest = &attr.key[4..];
1593+ let mut rest = css;
1948− if let Some(colon_pos) = rest.find(':') {
1594+ std::iter::from_fn(move || {
1949− let prefix = format!("nth:{}:", &rest[..colon_pos]);
1595+ if rest.is_empty() {
1950− if !nth_prefixes.contains(&prefix) {
1596+ return None;
1951− nth_prefixes.push(prefix);
1597+ }
1598+ let (mut depth, mut quote, mut escaped) = (0i32, None, false);
1599+ let mut end = rest.len();
1600+ for (i, c) in rest.char_indices() {
1602+ _ if escaped => escaped = false,
1603+ '\\' => escaped = true,
1604+ c if Some(c) == quote => quote = None,
1605+ _ if quote.is_some() => {}
1606+ '"' | '\'' => quote = Some(c),
1609+ ';' if depth == 0 => {
1955− }
1616+ let (declaration, after) = rest.split_at(end);
1956− for prefix in &nth_prefixes {
1617+ rest = after;
1957− let expr = &prefix[4..prefix.len() - 1];
1618+ let name = declaration.split(':').next().unwrap_or("").trim();
1958− let selector = format!(":nth-child({})", expr);
1619+ Some((name, declaration))
1959− let css = attrs_to_css(attrs, prefix, kind, parent_kind);
1620+ })
1960− if !css.is_empty() {
1621+}
1961− pseudo.push((selector, css));
1965− // Collect has(...): dynamic pseudo selectors
1623+/// Dedupe CSS declarations within a single rule body: for any property
1966− let mut has_prefixes: Vec<String> = Vec::new();
1624+/// declared more than once, keep only the last occurrence. Unparseable
1967− for attr in attrs {
1625+/// segments (no `:`) are preserved as-is. Semicolons inside parentheses or
1968− if attr.key.starts_with("has(") {
1626+/// quoted strings are treated as part of a value, not as declaration
1969− if let Some(close) = attr.key.find("):") {
1627+/// separators.
1970− let prefix = format!("{}:", &attr.key[..close + 1]);
1628+fn dedupe_declarations(css: &str) -> String {
1971− if !has_prefixes.contains(&prefix) {
1629+ if css.is_empty() {
1972− has_prefixes.push(prefix);
1630+ return String::new();
1632+ // Quick path: no chance of duplicates if there's fewer than 2 declarations.
1633+ if css.matches(';').count() < 2 {
1634+ return css.to_string();
1637+ // Split into (property_name_opt, full_decl_with_semi) preserving whatever
1638+ // terminator the input used. We split on `;` at depth 0 (ignoring parens).
1639+ let mut decls: Vec<(Option<String>, String)> = Vec::new();
1640+ let mut current = String::new();
1641+ let mut depth: i32 = 0;
1642+ // A quoted string's `;` (`content "a;b"`) is text; a backslash escapes
1643+ // the character after it
1644+ let mut quote: Option<char> = None;
1645+ let mut escaped = false;
1646+ for ch in css.chars() {
1650+ } else if ch == '\\' {
1653+ } else if let Some(q) = quote {
1658+ } else if ch == '"' || ch == '\'' {
1661+ } else if ch == '(' {
1664+ } else if ch == ')' {
1667+ } else if ch == ';' && depth == 0 {
1669+ let trimmed = current.trim();
1670+ if !trimmed.is_empty() && trimmed != ";" {
1672+ .trim_end_matches(';')
1674+ .map(|(p, _)| p.trim().to_ascii_lowercase());
1675+ decls.push((prop, std::mem::take(&mut current)));
1977− for prefix in &has_prefixes {
1683+ if !current.trim().is_empty() {
1978− let inner = &prefix[4..prefix.len() - 2]; // extract selector from has(selector):
1684+ let prop = current
1979− let selector = format!(":has({})", inner);
1685+ .split_once(':')
1980− let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1686+ .map(|(p, _)| p.trim().to_ascii_lowercase());
1981− if !css.is_empty() {
1687+ decls.push((prop, std::mem::take(&mut current)));
1982− pseudo.push((selector, css));
1986− // Collect responsive overrides
1690+ if decls.len() < 2 {
1987− let mut responsive = Vec::new();
1691+ return css.to_string();
1988− for &(bp_name, _) in BREAKPOINTS {
1989− let prefix = format!("{}:", bp_name);
1990− let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1991− if !css.is_empty() {
1992− responsive.push((bp_name.to_string(), css));
1996− // Collect container query overrides
1694+ // Find index of last occurrence of each property.
1997− let mut container = Vec::new();
1695+ use std::collections::HashMap;
1998− for &(bp_name, _) in BREAKPOINTS {
1696+ let mut last: HashMap<String, usize> = HashMap::new();
1999− let prefix = format!("cq-{}:", bp_name);
1697+ for (i, (prop, _)) in decls.iter().enumerate() {
2000− let css = attrs_to_css(attrs, &prefix, kind, parent_kind);
1698+ if let Some(p) = prop {
2001− if !css.is_empty() {
1699+ last.insert(p.clone(), i);
2002− container.push((bp_name.to_string(), css));
2006− let dark = attrs_to_css(attrs, "dark:", kind, parent_kind);
1703+ let mut out = String::with_capacity(css.len());
2007− let print = attrs_to_css(attrs, "print:", kind, parent_kind);
1704+ for (i, (prop, raw)) in decls.iter().enumerate() {
2008− let motion_safe = attrs_to_css(attrs, "motion-safe:", kind, parent_kind);
1705+ let keep = match prop {
2009− let motion_reduce = attrs_to_css(attrs, "motion-reduce:", kind, parent_kind);
1706+ Some(p) => last.get(p) == Some(&i),
2010− let landscape = attrs_to_css(attrs, "landscape:", kind, parent_kind);
1707+ None => true,
2011− let portrait = attrs_to_css(attrs, "portrait:", kind, parent_kind);
1708+ };
2013− styles.get_class(base, pseudo, responsive, dark, print, motion_safe, motion_reduce, landscape, portrait, container)
1710+ out.push_str(raw);
2016fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option<&str>) {
1716fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option<&str>) {
@@ -2040,943 +1740,553 @@ fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option
2040// Attribute → CSS mapping
1740// Attribute → CSS mapping
2041// ---------------------------------------------------------------------------
1741// ---------------------------------------------------------------------------
2043−/// (htmlang prefix, CSS selector suffix)
1743+/// Where an element is written, which its CSS depends on.
2044−const PSEUDO_PREFIXES: &[(&str, &str)] = &[
1744+struct Site<'a> {
2045− ("hover:", ":hover"),
1745+ kind: &'a ElementKind,
2046− ("active:", ":active"),
1746+ /// How its parent lays out its children: its `width fill`, `height
2047− ("focus:", ":focus"),
1747+ /// fill` and `shrink` compile against it.
2048− ("focus-visible:", ":focus-visible"),
1748+ parent: &'a Flow,
2049− ("focus-within:", ":focus-within"),
1749+ /// It has `@in-front` / `@behind` children.
2050− ("disabled:", ":disabled"),
1750+ has_overlay_children: bool,
2051− ("checked:", ":checked"),
1751+ /// A row, column or grid inside text, laid out inline.
2052− ("placeholder:", "::placeholder"),
1752+ inline: bool,
2053− ("first:", ":first-child"),
1753+ /// The page's `<body>`, which the reset already makes a column.
2054− ("last:", ":last-child"),
1754+ root: bool,
2055− ("odd:", ":nth-child(odd)"),
2056− ("even:", ":nth-child(even)"),
2057− ("before:", "::before"),
2058− ("after:", "::after"),
2059− ("selection:", "::selection"),
2060− ("visited:", ":visited"),
2061− ("empty:", ":empty"),
2062− ("target:", ":target"),
2063− ("valid:", ":valid"),
2064− ("invalid:", ":invalid"),
2066−const RESPONSIVE_PREFIXES: &[&str] = &["sm:", "md:", "lg:", "xl:", "2xl:"];
2067−const MEDIA_PREFIXES: &[&str] = &["dark:", "print:", "motion-safe:", "motion-reduce:", "landscape:", "portrait:"];
2068−const CONTAINER_QUERY_PREFIXES: &[&str] = &["cq-sm:", "cq-md:", "cq-lg:", "cq-xl:", "cq-2xl:"];
2070−fn is_prefixed_attr(key: &str) -> bool {
2071− PSEUDO_PREFIXES.iter().any(|&(p, _)| key.starts_with(p))
2072− || RESPONSIVE_PREFIXES.iter().any(|p| key.starts_with(p))
2073− || MEDIA_PREFIXES.iter().any(|p| key.starts_with(p))
2074− || CONTAINER_QUERY_PREFIXES.iter().any(|p| key.starts_with(p))
2075− || key.starts_with("nth:")
2076− || key.starts_with("has(")
2079−fn attrs_to_css(
1757+impl Site<'_> {
2080− attrs: &[Attribute],
1758+ /// Where an element in a parent with the layout `layout` and the flow
2081− state_prefix: &str,
1759+ /// `parent` is.
2082− kind: &ElementKind,
1760+ fn new<'a>(elem: &'a Element, layout: Option<Layout>, parent: &'a Flow) -> Site<'a> {
2083− parent_kind: Option<&ElementKind>,
1761+ Site {
2084−) -> String {
1762+ kind: &elem.kind,
2085− let mut css = String::new();
1763+ parent,
2086−
1764+ has_overlay_children: has_overlay_children(elem),
2087− // Base element styles only for the default (non-state) pass
1765+ inline: layout == Some(Layout::Text) && elem.kind.layout().is_container(),
2088− if state_prefix.is_empty() {
1766+ root: false,
2090− ElementKind::Row => css.push_str("display:flex;flex-direction:row;"),
2091− ElementKind::Column => css.push_str("display:flex;flex-direction:column;"),
2092− ElementKind::El => css.push_str("display:flex;flex-direction:column;"),
2093− ElementKind::Paragraph => css.push_str("margin:0;"),
2094− // Semantic elements get flex column layout like @el
2095− ElementKind::Nav | ElementKind::Header | ElementKind::Footer
2096− | ElementKind::Main | ElementKind::Section | ElementKind::Article
2097− | ElementKind::Aside => css.push_str("display:flex;flex-direction:column;"),
2098− // Lists: reset browser defaults
2099− ElementKind::List => css.push_str("margin:0;padding-left:0;list-style:none;"),
2100− ElementKind::ListItem => css.push_str("display:flex;flex-direction:column;"),
2101− // Form: flex column like @el
2102− ElementKind::Form => css.push_str("display:flex;flex-direction:column;"),
2103− // Details: flex column
2104− ElementKind::Details => css.push_str("display:flex;flex-direction:column;"),
2105− // Figure: flex column
2106− ElementKind::Figure => css.push_str("display:flex;flex-direction:column;margin:0;"),
2107− // Blockquote: flex column, reset browser margin
2108− ElementKind::Blockquote => css.push_str("display:flex;flex-direction:column;margin:0;"),
2109− // Pre: preserve whitespace
2110− ElementKind::Pre => css.push_str("margin:0;white-space:pre;font-family:ui-monospace,monospace;"),
2111− // Code: monospace font
2112− ElementKind::Code => css.push_str("font-family:ui-monospace,monospace;"),
2114− ElementKind::Dialog => css.push_str("display:flex;flex-direction:column;"),
2115− ElementKind::DefinitionList => css.push_str("margin:0;"),
2116− ElementKind::DefinitionDescription => css.push_str("margin:0;display:flex;flex-direction:column;"),
2117− ElementKind::Fieldset => css.push_str("display:flex;flex-direction:column;border:1px solid currentColor;padding:0.5em;margin:0;"),
2118− ElementKind::Kbd => css.push_str("font-family:ui-monospace,monospace;"),
2119− ElementKind::Grid => css.push_str("display:grid;"),
2120− ElementKind::Stack => css.push_str("position:relative;"),
2121− ElementKind::Badge => css.push_str("display:inline-flex;align-items:center;justify-content:center;padding:2px 8px;border-radius:9999px;font-size:0.75rem;font-weight:600;line-height:1;"),
2122− ElementKind::Tooltip => css.push_str("position:relative;cursor:help;"),
2123− ElementKind::Spacer => css.push_str("flex:1;"),
2124− ElementKind::Avatar => css.push_str("display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;overflow:hidden;flex-shrink:0;"),
2125− 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;"),
2126− 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;"),
2127− ElementKind::Tag => css.push_str("display:inline-flex;align-items:center;padding:2px 8px;border-radius:4px;font-size:0.75rem;font-weight:600;"),
2130− // Children of @carousel get scroll-snap-align and flex-shrink
2131− if matches!(parent_kind, Some(ElementKind::Carousel)) {
2132− css.push_str("scroll-snap-align:start;flex-shrink:0;");
2136− for attr in attrs {
1771+// ---------------------------------------------------------------------------
2137− // Determine the effective key for this pass
1772+// Direction: what a child's `fill` and `shrink` compile against
2138− let effective_key = if state_prefix.is_empty() {
1773+// ---------------------------------------------------------------------------
2139− if is_prefixed_attr(&attr.key) {
2144− match attr.key.strip_prefix(state_prefix) {
2150− let val = attr.value.as_deref();
2152− match effective_key {
2154− "spacing" | "gap" => {
2155− if let Some(v) = val {
2156− push_css(&mut css, "gap", &css_px(v));
2160− if let Some(v) = val {
2161− push_css(&mut css, "padding", &css_px_multi(v));
2165− if let Some(v) = val {
2166− push_css(&mut css, "padding-left", &css_px(v));
2167− push_css(&mut css, "padding-right", &css_px(v));
2171− if let Some(v) = val {
2172− push_css(&mut css, "padding-top", &css_px(v));
2173− push_css(&mut css, "padding-bottom", &css_px(v));
2179− if let Some(v) = val {
2181− "fill" => match parent_kind {
2182− Some(ElementKind::Row) => {
2183− push_css(&mut css, "flex", "1");
2184− push_css(&mut css, "min-width", "0");
2186− _ => push_css(&mut css, "width", "100%"),
2188− "shrink" => push_css(&mut css, "flex-shrink", "0"),
2189− _ => push_css(&mut css, "width", &css_px(v)),
2194− if let Some(v) = val {
2196− "fill" => match parent_kind {
2197− Some(ElementKind::Column) => {
2198− push_css(&mut css, "flex", "1");
2199− push_css(&mut css, "min-height", "0");
2201− _ => push_css(&mut css, "height", "100%"),
2203− "shrink" => push_css(&mut css, "flex-shrink", "0"),
2204− _ => push_css(&mut css, "height", &css_px(v)),
2209− if let Some(v) = val {
2210− push_css(&mut css, "min-width", &css_px(v));
2214− if let Some(v) = val {
2215− push_css(&mut css, "max-width", &css_px(v));
2219− if let Some(v) = val {
2220− push_css(&mut css, "min-height", &css_px(v));
2224− if let Some(v) = val {
2225− push_css(&mut css, "max-height", &css_px(v));
2230− "center-x" => match parent_kind {
2231− Some(ElementKind::Column) | Some(ElementKind::El) => {
2232− push_css(&mut css, "align-self", "center");
2235− push_css(&mut css, "margin-left", "auto");
2236− push_css(&mut css, "margin-right", "auto");
2239− "center-y" => match parent_kind {
2240− Some(ElementKind::Row) => push_css(&mut css, "align-self", "center"),
2242− push_css(&mut css, "margin-top", "auto");
2243− push_css(&mut css, "margin-bottom", "auto");
2246− "align-left" => match parent_kind {
2247− Some(ElementKind::Column) | Some(ElementKind::El) => {
2248− push_css(&mut css, "align-self", "flex-start");
2250− _ => push_css(&mut css, "margin-right", "auto"),
2252− "align-right" => match parent_kind {
2253− Some(ElementKind::Column) | Some(ElementKind::El) => {
2254− push_css(&mut css, "align-self", "flex-end");
2256− _ => push_css(&mut css, "margin-left", "auto"),
2258− "align-top" => match parent_kind {
2259− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-start"),
2260− _ => push_css(&mut css, "margin-bottom", "auto"),
2262− "align-bottom" => match parent_kind {
2263− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-end"),
2264− _ => push_css(&mut css, "margin-top", "auto"),
2269− if let Some(v) = val {
2270− push_css(&mut css, "background", v);
2274− if let Some(v) = val {
2275− push_css(&mut css, "color", v);
2279− if let Some(v) = val {
2280− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2281− if parts.len() == 2 {
2285− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2291− &format!("{} solid currentColor", css_px(parts[0])),
2296− "border-top" | "border-bottom" | "border-left" | "border-right" => {
2297− if let Some(v) = val {
2298− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2299− if parts.len() == 2 {
2303− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2309− &format!("{} solid currentColor", css_px(parts[0])),
2315− if let Some(v) = val {
2316− push_css(&mut css, "border-radius", &css_px(v));
2319− "bold" => push_css(&mut css, "font-weight", "bold"),
2320− "italic" => push_css(&mut css, "font-style", "italic"),
2321− "underline" => push_css(&mut css, "text-decoration", "underline"),
2323− if let Some(v) = val {
2324− push_css(&mut css, "font-size", &css_px(v));
2328− if let Some(v) = val {
2329− push_css(&mut css, "font-family", v);
2333− if let Some(v) = val {
2334− push_css(&mut css, "transition", v);
2338− if let Some(v) = val {
2339− push_css(&mut css, "cursor", v);
2343− if let Some(v) = val {
2344− push_css(&mut css, "opacity", v);
2350− if let Some(v) = val {
2351− push_css(&mut css, "text-align", v);
2355− if let Some(v) = val {
2356− push_css(&mut css, "line-height", v);
2359− "letter-spacing" => {
2360− if let Some(v) = val {
2361− push_css(&mut css, "letter-spacing", &css_px(v));
2364− "text-transform" => {
2365− if let Some(v) = val {
2366− push_css(&mut css, "text-transform", v);
2370− if let Some(v) = val {
2371− push_css(&mut css, "white-space", v);
2375− // Overflow & positioning
2377− if let Some(v) = val {
2378− push_css(&mut css, "overflow", v);
2382− if let Some(v) = val {
2383− push_css(&mut css, "position", v);
2387− if let Some(v) = val {
2388− push_css(&mut css, "top", &css_px(v));
2392− if let Some(v) = val {
2393− push_css(&mut css, "right", &css_px(v));
2397− if let Some(v) = val {
2398− push_css(&mut css, "bottom", &css_px(v));
2402− if let Some(v) = val {
2403− push_css(&mut css, "left", &css_px(v));
2407− if let Some(v) = val {
2408− push_css(&mut css, "z-index", v);
2412− // Display & visibility
2414− if let Some(v) = val {
2415− push_css(&mut css, "display", v);
2419− if let Some(v) = val {
2420− push_css(&mut css, "visibility", v);
2423− "hidden" => push_css(&mut css, "display", "none"),
2425− // Transform & filters
2427− if let Some(v) = val {
2428− push_css(&mut css, "transform", v);
2431− "backdrop-filter" => {
2432− if let Some(v) = val {
2433− push_css(&mut css, "backdrop-filter", v);
2439− if let Some(v) = val {
2440− push_css(&mut css, "box-shadow", v);
2445− "wrap" => push_css(&mut css, "flex-wrap", "wrap"),
2447− if let Some(v) = val {
2448− push_css(&mut css, "column-gap", &css_px(v));
2452− if let Some(v) = val {
2453− push_css(&mut css, "row-gap", &css_px(v));
2459− push_css(&mut css, "display", "grid");
2462− if let Some(v) = val {
2463− if let Ok(n) = v.parse::<u32>() {
2464− push_css(&mut css, "grid-template-columns", &format!("repeat({},1fr)", n));
2466− push_css(&mut css, "grid-template-columns", v);
2471− if let Some(v) = val {
2472− if let Ok(n) = v.parse::<u32>() {
2473− push_css(&mut css, "grid-template-rows", &format!("repeat({},1fr)", n));
2475− push_css(&mut css, "grid-template-rows", v);
2480− if let Some(v) = val {
2481− push_css(&mut css, "grid-column", &format!("span {}", v));
2485− if let Some(v) = val {
2486− push_css(&mut css, "grid-row", &format!("span {}", v));
2492− if let Some(v) = val {
2493− push_css(&mut css, "animation", v);
2498− "aspect-ratio" => {
2499− if let Some(v) = val {
2500− push_css(&mut css, "aspect-ratio", v);
2504− // CSS containment for rendering performance
2506− if let Some(v) = val {
2507− push_css(&mut css, "contain", v);
2509− push_css(&mut css, "contain", "layout style paint");
2512− "content-visibility" => {
2513− if let Some(v) = val {
2514− push_css(&mut css, "content-visibility", v);
2516− push_css(&mut css, "content-visibility", "auto");
2520− // Outline (like border but doesn't affect layout)
2522− if let Some(v) = val {
2523− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2524− if parts.len() == 2 {
2528− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2534− &format!("{} solid currentColor", css_px(parts[0])),
2540− // Logical properties (i18n-aware)
2541− "padding-inline" => {
2542− if let Some(v) = val {
2543− push_css(&mut css, "padding-inline", &css_px_multi(v));
2546− "padding-block" => {
2547− if let Some(v) = val {
2548− push_css(&mut css, "padding-block", &css_px_multi(v));
2551− "margin-inline" => {
2552− if let Some(v) = val {
2553− push_css(&mut css, "margin-inline", &css_px_multi(v));
2556− "margin-block" => {
2557− if let Some(v) = val {
2558− push_css(&mut css, "margin-block", &css_px_multi(v));
2562− // Logical property start/end variants
2563− "padding-inline-start" | "padding-inline-end" |
2564− "padding-block-start" | "padding-block-end" |
2565− "margin-inline-start" | "margin-inline-end" |
2566− "margin-block-start" | "margin-block-end" => {
2567− if let Some(v) = val {
2568− push_css(&mut css, effective_key, &css_px(v));
2573− "inset-inline" | "inset-block" => {
2574− if let Some(v) = val {
2575− push_css(&mut css, effective_key, &css_px_multi(v));
2578− "inset-inline-start" | "inset-inline-end" |
2579− "inset-block-start" | "inset-block-end" => {
2580− if let Some(v) = val {
2581− push_css(&mut css, effective_key, &css_px(v));
2586− "border-inline" | "border-block" |
2587− "border-inline-start" | "border-inline-end" |
2588− "border-block-start" | "border-block-end" => {
2589− if let Some(v) = val {
2590− push_css(&mut css, effective_key, v);
2594− // Logical border-radius
2595− "border-start-start-radius" | "border-start-end-radius" |
2596− "border-end-start-radius" | "border-end-end-radius" => {
2597− if let Some(v) = val {
2598− push_css(&mut css, effective_key, &css_px(v));
2602− // Logical scroll margins & padding
1775+/// The way a flex row or column lays out its children.
2603− "scroll-margin-inline" | "scroll-margin-block" |
1776+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2604− "scroll-padding-inline" | "scroll-padding-block" => {
1777+enum Axis {
2605− if let Some(v) = val {
1778+ Row,
2606− push_css(&mut css, effective_key, &css_px_multi(v));
1779+ Column,
2610− // Logical sizing
1782+impl Axis {
2611− "inline-size" | "block-size" |
1783+ /// The direction a `flex-direction` or `flex-flow` value sets, if it
2612− "min-inline-size" | "max-inline-size" |
1784+ /// names one (not `var(--dir)`, which only the browser knows).
2613− "min-block-size" | "max-block-size" => {
1785+ fn of_value(value: &str) -> Option<Axis> {
2614− if let Some(v) = val {
1786+ value.split_whitespace().find_map(|word| match word {
2615− push_css(&mut css, effective_key, &css_px(v));
1787+ "row" | "row-reverse" => Some(Axis::Row),
2616− }
1788+ "column" | "column-reverse" => Some(Axis::Column),
2619− // Scroll snap
1794+/// How an element lays out its children, as its CSS sets it: the
2620− "scroll-snap-type" => {
1795+/// direction its children's `width`/`height` `fill` and `shrink` compile
2621− if let Some(v) = val {
1796+/// against. That is the direction of `@row` or of a column, or the one its
2622− push_css(&mut css, "scroll-snap-type", v);
1797+/// own `flex-direction` (or `flex-flow`) sets, with or without media or
2623− }
1798+/// container prefixes. Like elm-ui's `.r > .wf`, the rules for a direction
2624− }
1799+/// set under a prefix are keyed on the element's class: `@media (...) {
2625− "scroll-snap-align" => {
1800+/// :where(.a)>.b {...} }`.
2626− if let Some(v) = val {
1801+#[derive(Clone, Default)]
2627− push_css(&mut css, "scroll-snap-align", v);
1802+struct Flow {
2628− }
1803+ /// Without a prefix; `None` when the element isn't a flex row or column
2629− }
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>,
2631− // Margin
1814+impl Flow {
2632− "margin" => {
1815+ fn of(elem: &Element) -> Flow {
2633− if let Some(v) = val {
1816+ let mut base = match elem.kind.layout() {
2634− push_css(&mut css, "margin", &css_px_multi(v));
1817+ Layout::Row => Axis::Row,
2635− }
1818+ Layout::Column => Axis::Column,
2636− }
1819+ _ => return Flow::default(),
2637− "margin-x" => {
1820+ };
2638− if let Some(v) = val {
1821+ let mut changes: Vec<(Vec<usize>, Axis)> = Vec::new();
2639− push_css(&mut css, "margin-left", &css_px(v));
1822+ for attr in elem.attrs.iter().filter(|a| !a.html) {
2640− push_css(&mut css, "margin-right", &css_px(v));
1823+ let (condition, name) = Condition::of(&attr.key);
2641− }
1824+ if !matches!(name, "flex-direction" | "flex-flow") || !condition.selector.is_empty() {
2644− if let Some(v) = val {
2645− push_css(&mut css, "margin-top", &css_px(v));
2646− push_css(&mut css, "margin-bottom", &css_px(v));
2649−
1827+ let Some(axis) = attr.value.as_deref().and_then(Axis::of_value) else {
2650− // Filter
1828+ continue;
2651− "filter" => {
1829+ };
2652− if let Some(v) = val {
1830+ if condition.at.is_empty() {
2653− push_css(&mut css, "filter", v);
1831+ base = axis;
1833+ // The later one wins, as in the CSS
1834+ changes.retain(|(at, _)| *at != condition.at);
1835+ changes.push((condition.at, axis));
1838+ changes.sort_by_key(|(at, _)| at_order(at));
2657− // Object fit/position (for images)
1846+ /// The direction under the at-rules `at`: the latest one set among
2658− "object-fit" => {
1847+ /// the conditions that hold there (`md:` holds at `lg:`), else the one
2659− if let Some(v) = val {
1848+ /// without a prefix.
2660− push_css(&mut css, "object-fit", v);
1849+ fn at(&self, at: &[usize]) -> Option<Axis> {
2661− }
1850+ let base = self.base?;
2662− }
1851+ let here = Condition::at_only(at);
2663− "object-position" => {
1852+ let changed = self
2664− if let Some(v) = val {
1853+ .changes
2665− push_css(&mut css, "object-position", v);
1854+ .iter()
2667− }
1856+ .find(|(chain, _)| Condition::at_only(chain).holds_at(&here))
1857+ .map(|&(_, axis)| axis);
1858+ Some(changed.unwrap_or(base))
2669− // Text shadow
1862+/// `width` or `height`.
2670− "text-shadow" => {
1863+#[derive(Clone, Copy, PartialEq, Eq)]
2671− if let Some(v) = val {
1864+enum Dim {
2672− push_css(&mut css, "text-shadow", v);
1865+ Width,
2676− // Text overflow
1869+/// What a `width` or `height` says.
2677− "text-overflow" => {
1870+#[derive(Clone, Copy, PartialEq, Eq)]
2678− if let Some(v) = val {
1871+enum Size {
2679− push_css(&mut css, "text-overflow", v);
1872+ Fill,
2681− }
1874+ /// A size of its own (`width 300`)
2683− // Interaction
1878+impl Size {
2684− "pointer-events" => {
1879+ fn of(value: &str) -> Size {
2685− if let Some(v) = val {
1880+ match value.trim() {
2686− push_css(&mut css, "pointer-events", v);
1881+ "fill" => Size::Fill,
2687− }
1882+ "shrink" => Size::Shrink,
2688− }
1883+ _ => Size::Set,
2689− "user-select" => {
1884+ }
2690− if let Some(v) = val {
1885+ }
2691− push_css(&mut css, "user-select", v);
1886+}
2695− // Flexbox/grid alignment
1888+/// The declarations `fill` and `shrink` make in a parent laid out along
2696− "justify-content" => {
1889+/// `axis` (`None`: not a flex row or column). Along the parent's direction,
2697− if let Some(v) = val {
1890+/// `fill` takes the remaining space and `shrink` keeps the content's size;
2698− push_css(&mut css, "justify-content", v);
1891+/// across it (or outside flex), `fill` is the full size and `shrink` fits
2699− }
1892+/// the content.
2700− }
1893+fn sizing(dim: Dim, size: Size, axis: Option<Axis>) -> &'static [(&'static str, &'static str)] {
2701− "align-items" => {
1894+ match (dim, size, axis) {
2702− if let Some(v) = val {
1895+ (_, Size::Set, _) => &[],
2703− push_css(&mut css, "align-items", v);
1896+ (Dim::Width, Size::Fill, Some(Axis::Row)) => &[("flex", "1"), ("min-width", "0")],
2704− }
1897+ (Dim::Width, Size::Fill, _) => &[("width", "100%")],
2705− }
1898+ (Dim::Width, Size::Shrink, Some(Axis::Row)) => &[("flex-shrink", "0")],
1899+ (Dim::Width, Size::Shrink, _) => &[("width", "fit-content")],
1900+ (Dim::Height, Size::Fill, Some(Axis::Column)) => &[("flex", "1"), ("min-height", "0")],
1901+ (Dim::Height, Size::Fill, _) => &[("height", "100%")],
1902+ (Dim::Height, Size::Shrink, Some(Axis::Column)) => &[("flex-shrink", "0")],
1903+ (Dim::Height, Size::Shrink, _) => &[("height", "fit-content")],
2707− // Flex item order
1907+/// Every property `fill` and `shrink` of `dim` can set, with its initial
2708− "order" => {
1908+/// value (`flex` covers `flex-shrink`).
2709− if let Some(v) = val {
1909+fn sizing_properties(dim: Dim) -> [(&'static str, &'static str); 3] {
2710− push_css(&mut css, "order", v);
1910+ match dim {
2711− }
1911+ Dim::Width => [
2712− }
1912+ ("flex", "0 1 auto"),
1913+ ("min-width", "auto"),
1917+ ("flex", "0 1 auto"),
1918+ ("min-height", "auto"),
1919+ ("height", "auto"),
2714− // Background extras
1924+/// What an element's attributes under some prefixes say about its size.
2715− "background-size" => {
1925+#[derive(Default)]
2716− if let Some(v) = val {
1926+struct Sizes {
2717− push_css(&mut css, "background-size", v);
1927+ /// The last `width` and `height`
2718− }
1928+ width: Option<Size>,
2719− }
1929+ height: Option<Size>,
2720− "background-position" => {
1930+ /// A `fill` or `shrink` for the width / height is among them (a later
2721− if let Some(v) = val {
1931+ /// size may replace it)
2722− push_css(&mut css, "background-position", v);
1932+ width_word: bool,
2723− }
1933+ height_word: bool,
2724− }
1934+ /// It writes `flex`, one of its longhands (`flex-grow`, `flex-shrink`,
2725− "background-repeat" => {
1935+ /// `flex-basis`), `min-width` or `min-height` itself
2726− if let Some(v) = val {
1936+ flex: bool,
2727− push_css(&mut css, "background-repeat", v);
1937+ flex_grow: bool,
2728− }
1938+ flex_shrink: bool,
2729− }
1939+ flex_basis: bool,
2731− // Text wrapping
1944+impl Sizes {
2732− "word-break" => {
1945+ /// Read the attributes under the conditions that hold wherever `at`
2733− if let Some(v) = val {
1946+ /// does, a later condition over an earlier one.
2734− push_css(&mut css, "word-break", v);
1947+ fn of(attrs: &[Attribute], at: &Condition) -> Sizes {
2735− }
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 {
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,
2737− "overflow-wrap" => {
1980+ }
2738− if let Some(v) = val {
1981+ sizes
2739− push_css(&mut css, "overflow-wrap", v);
1982+ }
1984+ /// The element writes `property` itself: a layout word leaves it alone.
1985+ fn writes(&self, property: &str) -> bool {
1987+ "flex" => self.flex,
1988+ "flex-grow" => self.flex || self.flex_grow,
1989+ "flex-shrink" => self.flex || self.flex_shrink,
1990+ "flex-basis" => self.flex || self.flex_basis,
1991+ "min-width" => self.min_width,
1992+ "min-height" => self.min_height,
1993+ "width" => self.width == Some(Size::Set),
1994+ "height" => self.height == Some(Size::Set),
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);
2027+ if !self.writes(property) {
2028+ push_css(css, property, value);
2743− // Container queries
2033+/// The rule that gives an element's `fill` and `shrink`, as its attributes
2744− "container" => {
2034+/// under the at-rules `at` set them, their meaning in a parent laid out
2745− push_css(&mut css, "container-type", "inline-size");
2035+/// along `axis`. Every other property a layout word could have set is put
2746− }
2036+/// back to its initial value, so the rule is right whichever earlier rule
2747− "container-name" => {
2037+/// it overrides. Properties the element writes itself are left alone.
2748− if let Some(v) = val {
2038+fn sizing_rule(attrs: &[Attribute], at: &[usize], axis: Axis) -> String {
2749− push_css(&mut css, "container-name", v);
2039+ let sizes = Sizes::of(attrs, &Condition::at_only(at));
2750− }
2040+ let mut sets: Vec<(&str, &str)> = Vec::new();
2751− }
2041+ let mut resets: Vec<(&str, &str)> = Vec::new();
2752− "container-type" => {
2042+ for (dim, size, word) in [
2753− if let Some(v) = val {
2043+ (Dim::Width, sizes.width, sizes.width_word),
2754− push_css(&mut css, "container-type", v);
2044+ (Dim::Height, sizes.height, sizes.height_word),
2049+ if let Some(size) = size {
2050+ sets.extend_from_slice(sizing(dim, size, Some(axis)));
2052+ resets.extend_from_slice(&sizing_properties(dim));
2054+ let mut css = String::new();
2055+ let mut written: Vec<&str> = Vec::new();
2056+ for &(property, value) in &resets {
2057+ if sets.iter().any(|&(p, _)| p == property) || written.contains(&property) {
2060+ written.push(property);
2061+ sizes.push(&mut css, property, value);
2063+ for &(property, value) in &sets {
2064+ sizes.push(&mut css, property, value);
2758− // Overflow axis
2069+/// The rules an element's `fill` and `shrink` need under each chain of
2759− "overflow-x" => {
2070+/// at-rules where the direction of `flow` (its parent's) changes: `(at,
2760− if let Some(v) = val {
2071+/// body)`.
2761− push_css(&mut css, "overflow-x", v);
2072+fn sizing_changes(attrs: &[Attribute], flow: &Flow) -> Vec<(Vec<usize>, String)> {
2762− }
2073+ flow.changes
2764− "overflow-y" => {
2075+ .map(|(at, axis)| (at.clone(), sizing_rule(attrs, at, *axis)))
2765− if let Some(v) = val {
2076+ .filter(|(_, body)| !body.is_empty())
2766− push_css(&mut css, "overflow-y", v);
2077+ .collect()
2770− // Inset (shorthand for top/right/bottom/left)
2080+/// An element's generated class, with the rules keyed on its parent's
2771− "inset" => {
2081+/// class that its `fill` and `shrink` need where the parent's direction
2772− if let Some(v) = val {
2082+/// changes under a prefix (see [`Flow`]): `:where(.a)>.b`, one class of
2773− push_css(&mut css, "inset", &css_px(v));
2083+/// specificity like any class rule.
2774− }
2084+fn element_class(elem: &Element, site: &Site, styles: &mut StyleCollector) -> Option<String> {
2775− }
2085+ let as_child = match site.parent.class {
2086+ Some(_) => sizing_changes(&elem.attrs, site.parent),
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);
2777− // Accent & caret colors
2104+/// The `display` of a layout (nothing for text, native and void elements,
2778− "accent-color" => {
2105+/// which keep HTML's own).
2779− if let Some(v) = val {
2106+fn layout_css(layout: Layout, inline: bool) -> &'static str {
2780− push_css(&mut css, "accent-color", v);
2107+ match (layout, inline) {
2781− }
2108+ (Layout::Column, false) => "display:flex;flex-direction:column;",
2782− }
2109+ (Layout::Column, true) => "display:inline-flex;flex-direction:column;",
2783− "caret-color" => {
2110+ (Layout::Row, false) => "display:flex;flex-direction:row;",
2784− if let Some(v) = val {
2111+ (Layout::Row, true) => "display:inline-flex;flex-direction:row;",
2785− push_css(&mut css, "caret-color", v);
2112+ (Layout::Grid, false) => "display:grid;",
2786− }
2113+ (Layout::Grid, true) => "display:inline-grid;",
2789− // Color scheme & appearance
2118+/// The declarations of the attributes under `condition` (the defaults of
2790− "color-scheme" => {
2119+/// the element's kind are [`default_css`]'s).
2791− if let Some(v) = val {
2120+fn attrs_to_css(attrs: &[Attribute], condition: &Condition, site: &Site) -> String {
2792− push_css(&mut css, "color-scheme", v);
2121+ let mut css = String::new();
2793− }
2122+ // The auto margins of `center-x`, `align-left`, ..., written at the end
2794− }
2123+ let mut aligned = String::new();
2795− "appearance" => {
2124+ let kind = site.kind;
2796− if let Some(v) = val {
2125+ // Under `children:` the styles go on the children, whose parent is this
2797− push_css(&mut css, "appearance", v);
2126+ // element: htmlang's words that place an element in its parent are an
2798− }
2127+ // error there (the parser reports them), and left out
2799− }
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()) {
2801− // List style
2160+ let val = attr.value.as_deref();
2802− "list-style" => {
2161+ // A style whose value came out empty (a field a record doesn't
2803− if let Some(v) = val {
2162+ // have, `${if()}` without its other branch) is left out
2804− push_css(&mut css, "list-style", v);
2163+ if val.is_some_and(|v| v.trim().is_empty()) {
2808− // Table
2167+ match effective_key {
2809− "border-collapse" => {
2168+ // htmlang's own words: they lay out children or place the
2810− if let Some(v) = val {
2169+ // element in its parent, and mean more than one CSS property
2811− push_css(&mut css, "border-collapse", v);
2170+ "spacing" if !lays_out_children => {}
2812− }
2171+ "spacing" => {
2814− "border-spacing" => {
2815 if let Some(v) = val {
2172 if let Some(v) = val {
2816− push_css(&mut css, "border-spacing", &css_px(v));
2173+ push_css(&mut css, "gap", &with_px("gap", v));
2820− // Text decoration
2177+ // Sizing: `fill` and `shrink` compile against the parent's
2821− "text-decoration" => {
2178+ // direction. Only the last `width` (`height`) counts, as for
2822− if let Some(v) = val {
2179+ // any style written twice.
2823− push_css(&mut css, "text-decoration", v);
2180+ "width" | "height" if val.is_some_and(|v| Size::of(v) != Size::Set) => {
2824− }
2181+ let later = attrs[index + 1..].iter().any(|a| {
2826− "text-decoration-color" => {
2183+ && under(&a.key, condition) == Some(effective_key)
2827− if let Some(v) = val {
2184+ && a.value.as_deref().is_some_and(|v| !v.trim().is_empty())
2828− push_css(&mut css, "text-decoration-color", v);
2185+ });
2831− "text-decoration-thickness" => {
2832− if let Some(v) = val {
2833− push_css(&mut css, "text-decoration-thickness", &css_px(v));
2836− "text-decoration-style" => {
2837− if let Some(v) = val {
2838− push_css(&mut css, "text-decoration-style", v);
2841− "text-underline-offset" => {
2842− if let Some(v) = val {
2843− push_css(&mut css, "text-underline-offset", &css_px(v));
2845− }
2189+ let dim = if effective_key == "width" {
2847− // Multi-column
2191+ } else {
2848− "column-width" => {
2192+ Dim::Height
2849− if let Some(v) = val {
2193+ };
2850− push_css(&mut css, "column-width", &css_px(v));
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);
2854 if let Some(v) = val {
2238 if let Some(v) = val {
2855− push_css(&mut css, "column-rule", v);
2239+ push_css(&mut css, effective_key, &with_px(effective_key, v));
2859− // Place items/self
2243+ // Alignment: auto margins, which work along either direction.
2860− "place-items" => {
2244+ // They are written last, so a `margin` on the same element
2861− if let Some(v) = val {
2245+ // keeps its other sides (`center-x, margin 20`)
2862− push_css(&mut css, "place-items", v);
2246+ "center-x" => {
2863− }
2247+ push_css(&mut aligned, "margin-left", "auto");
2248+ push_css(&mut aligned, "margin-right", "auto");
2865− "place-self" => {
2250+ "center-y" => {
2866− if let Some(v) = val {
2251+ push_css(&mut aligned, "margin-top", "auto");
2867− push_css(&mut css, "place-self", v);
2252+ push_css(&mut aligned, "margin-bottom", "auto");
2254+ "align-left" => push_css(&mut aligned, "margin-right", "auto"),
2255+ "align-right" => push_css(&mut aligned, "margin-left", "auto"),
2256+ "align-top" => push_css(&mut aligned, "margin-bottom", "auto"),
2257+ "align-bottom" => push_css(&mut aligned, "margin-top", "auto"),
2871− // Scroll behavior
2259+ "wrap" if lays_out_children => push_css(&mut css, "flex-wrap", "wrap"),
2872− "scroll-behavior" => {
2260+ "wrap" => {}
2873− if let Some(v) = val {
2874− push_css(&mut css, "scroll-behavior", v);
2878− // Resize
2262+ // Grid
2879− "resize" => {
2263+ "grid-cols" | "grid-rows" if !lays_out_children => {}
2264+ "grid-cols" | "grid-rows" => {
2880 if let Some(v) = val {
2265 if let Some(v) = val {
2881− push_css(&mut css, "resize", v);
2266+ let property = if effective_key == "grid-cols" {
2267+ "grid-template-columns"
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)),
2884−
2277+ "col-span" | "row-span" => {
2885− // New CSS properties
2887− if let Some(v) = val { push_css(&mut css, "clip-path", v); }
2889− "mix-blend-mode" => {
2890− if let Some(v) = val { push_css(&mut css, "mix-blend-mode", v); }
2892− "background-blend-mode" => {
2893− if let Some(v) = val { push_css(&mut css, "background-blend-mode", v); }
2895− "writing-mode" => {
2896− if let Some(v) = val { push_css(&mut css, "writing-mode", v); }
2898− "column-count" => {
2899− if let Some(v) = val { push_css(&mut css, "column-count", v); }
2902− if let Some(v) = val { push_css(&mut css, "column-gap", &css_px(v)); }
2905− if let Some(v) = val { push_css(&mut css, "text-indent", &css_px(v)); }
2908− if let Some(v) = val { push_css(&mut css, "hyphens", v); }
2911− if let Some(v) = val { push_css(&mut css, "flex-grow", v); }
2914− if let Some(v) = val { push_css(&mut css, "flex-shrink", v); }
2917− if let Some(v) = val { push_css(&mut css, "flex-basis", &css_px(v)); }
2920− if let Some(v) = val { push_css(&mut css, "isolation", v); }
2922− "place-content" => {
2923− if let Some(v) = val { push_css(&mut css, "place-content", v); }
2925− "background-image" => {
2926− if let Some(v) = val { push_css(&mut css, "background-image", v); }
2929− if let Some(v) = val { push_css(&mut css, "font-weight", v); }
2932− if let Some(v) = val { push_css(&mut css, "font-style", v); }
2935− if let Some(v) = val { push_css(&mut css, "text-wrap", v); }
2938− if let Some(v) = val { push_css(&mut css, "will-change", v); }
2940− "touch-action" => {
2941− if let Some(v) = val { push_css(&mut css, "touch-action", v); }
2943− "vertical-align" => {
2944− if let Some(v) = val { push_css(&mut css, "vertical-align", v); }
2946− "scroll-margin" => {
2947− if let Some(v) = val { push_css(&mut css, "scroll-margin", &css_px(v)); }
2949− "scroll-margin-top" | "scroll-margin-bottom" | "scroll-margin-left" | "scroll-margin-right" => {
2950− if let Some(v) = val { push_css(&mut css, effective_key, &css_px(v)); }
2952− "scroll-padding" => {
2953− if let Some(v) = val { push_css(&mut css, "scroll-padding", &css_px(v)); }
2955− "scroll-padding-top" | "scroll-padding-bottom" | "scroll-padding-left" | "scroll-padding-right" => {
2956− if let Some(v) = val { push_css(&mut css, effective_key, &css_px(v)); }
2959− if let Some(v) = val { push_css(&mut css, "direction", v); }
2963 if let Some(v) = val {
2278 if let Some(v) = val {
2964− // Wrap in quotes if not already quoted and not a CSS keyword
2279+ let property = if effective_key == "col-span" {
2965− if v.starts_with('"') || v.starts_with('\'') || v == "none" || v == "normal" || v.starts_with("attr(") || v.starts_with("counter(") {
2280+ "grid-column"
2966− push_css(&mut css, "content", v);
2967 } else {
2281 } else {
2968− push_css(&mut css, "content", &format!("\"{}\"", v));
2282+ "grid-row"
2284+ push_css(&mut css, property, &format!("span {}", v));
2973− // --- CSS Shorthands ---
2288+ // CSS's `line-clamp` has no support yet without its
2974−
2289+ // `-webkit-` fallback, which needs a box to clamp
2976− push_css(&mut css, "overflow", "hidden");
2977− push_css(&mut css, "text-overflow", "ellipsis");
2978− push_css(&mut css, "white-space", "nowrap");
2980 "line-clamp" => {
2290 "line-clamp" => {
2981 if let Some(v) = val {
2291 if let Some(v) = val {
2982 push_css(&mut css, "display", "-webkit-box");
2292 push_css(&mut css, "display", "-webkit-box");
@@ -2985,128 +2295,23 @@ fn attrs_to_css(
2985 push_css(&mut css, "overflow", "hidden");
2295 push_css(&mut css, "overflow", "hidden");
2989− if let Some(v) = val {
2299+ // Every other name is a CSS property (standard, custom,
2990− push_css(&mut css, "filter", &format!("blur({})", css_px(v)));
2300+ // vendor-prefixed, or one htmlang doesn't know, which the
2991− }
2301+ // parser warned about), written under its own name with the
2992− }
2302+ // value as written, except for `px` after a bare number where
2993− "backdrop-blur" => {
2303+ // the property takes a length
2994− if let Some(v) = val {
2304+ key if crate::vocab::is_property_name(key) => {
2995− push_css(&mut css, "backdrop-filter", &format!("blur({})", css_px(v)));
2998− "no-scrollbar" => {
2999− push_css(&mut css, "scrollbar-width", "none");
3000− push_css(&mut css, "-ms-overflow-style", "none");
3003− push_css(&mut css, "background", "linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%)");
3004− push_css(&mut css, "background-size", "200% 100%");
3005− push_css(&mut css, "animation", "hl-skeleton 1.5s ease-in-out infinite");
3008 if let Some(v) = val {
2305 if let Some(v) = val {
3009− // Parse: "from to [angle]" or "color1 color2 [angle]"
2306+ push_css(&mut css, key, &with_px(key, v));
3010− let parts: Vec<&str> = v.split_whitespace().collect();
3011− let bg = if parts.len() >= 3 && (parts[2].ends_with("deg") || parts[2].ends_with("turn") || parts[2].ends_with("rad")) {
3012− format!("linear-gradient({},{},{})", parts[2], parts[0], parts[1])
3013− } else if parts.len() >= 2 {
3014− format!("linear-gradient({},{})", parts[0], parts[1])
3016− format!("linear-gradient({},transparent)", parts[0])
3018− push_css(&mut css, "background", &bg);
3023− "grid-template-areas" => {
3024− if let Some(v) = val { push_css(&mut css, "grid-template-areas", v); }
3027− if let Some(v) = val { push_css(&mut css, "grid-area", v); }
3030− // View transitions
3031− "view-transition-name" => {
3032− if let Some(v) = val { push_css(&mut css, "view-transition-name", v); }
3035− // Animate shorthand (alias for animation)
3037− if let Some(v) = val { push_css(&mut css, "animation", v); }
3041− "grid-template-columns" => {
3042− if let Some(v) = val { push_css(&mut css, "grid-template-columns", v); }
3044− "grid-template-rows" => {
3045− if let Some(v) = val { push_css(&mut css, "grid-template-rows", v); }
3048− // Scroll-driven animations
3049− "animation-timeline" => {
3050− if let Some(v) = val { push_css(&mut css, "animation-timeline", v); }
3052− "animation-range" => {
3053− if let Some(v) = val { push_css(&mut css, "animation-range", v); }
3055− "view-timeline-name" => {
3056− if let Some(v) = val { push_css(&mut css, "view-timeline-name", v); }
3058− "view-timeline-axis" => {
3059− if let Some(v) = val { push_css(&mut css, "view-timeline-axis", v); }
3061− "scroll-timeline-name" => {
3062− if let Some(v) = val { push_css(&mut css, "scroll-timeline-name", v); }
3064− "scroll-timeline-axis" => {
3065− if let Some(v) = val { push_css(&mut css, "scroll-timeline-axis", v); }
3068− // Anchor positioning
3070− if let Some(v) = val { push_css(&mut css, "anchor-name", v); }
3072− "position-anchor" => {
3073− if let Some(v) = val { push_css(&mut css, "position-anchor", v); }
3075− "position-area" => {
3076− if let Some(v) = val { push_css(&mut css, "position-area", v); }
3079− // Legacy alias for position-area
3080− if let Some(v) = val { push_css(&mut css, "position-area", v); }
3083− // initial-letter (drop caps)
3084− "initial-letter" => {
3085− if let Some(v) = val { push_css(&mut css, "initial-letter", v); }
3088− // Critical CSS hint — not CSS, handled elsewhere
3091− // Identity and HTML passthrough — not CSS
3092− "id" | "class" => {}
3093− "type" | "placeholder" | "name" | "value" | "disabled" | "required"
3094− | "checked" | "for" | "action" | "method" | "autocomplete" | "min"
3095− | "max" | "step" | "pattern" | "maxlength" | "rows" | "cols"
3096− | "multiple" | "alt" | "role" | "tabindex" | "title"
3097− | "controls" | "autoplay" | "loop" | "muted" | "poster" | "preload"
3098− | "loading" | "decoding" | "ordered" | "src"
3099− | "open" | "novalidate" | "low" | "high" | "optimum"
3100− | "colspan" | "rowspan" | "scope" | "inline" | "responsive"
3101− | "datetime" | "media" | "sizes" | "srcset" | "cite" | "list"
3102− | "sandbox" | "allow" | "allowfullscreen" | "referrerpolicy"
3103− | "formaction" | "formmethod" | "formtarget" | "target"
3104− | "autofocus" => {}
2314+ css.push_str(&aligned);
@@ -3117,41 +2322,10 @@ fn push_css(css: &mut String, prop: &str, value: &str) {
3117 css.push(';');
2322 css.push(';');
3120−/// Known CSS units — if a value ends with one, skip appending `px`.
3121−const CSS_UNITS: &[&str] = &[
3122− "%", "rem", "em", "vh", "vw", "vmin", "vmax", "dvh", "svh", "lvh",
3123− "ch", "ex", "cm", "mm", "in", "pt", "pc", "fr",
3126−/// Format a numeric value: if it already has a CSS unit, pass through as-is;
3127−/// otherwise append `px`.
3128−fn css_px(value: &str) -> String {
3129− let v = value.trim();
3131− return "0".to_string();
3133− if CSS_UNITS.iter().any(|u| v.ends_with(u)) {
3134− return v.to_string();
3136− if v.starts_with("var(") || v.starts_with("calc(") || v.starts_with("clamp(") || v.starts_with("min(") || v.starts_with("max(") {
3137− return v.to_string();
3142−/// Format multiple space-separated values, each getting px if needed.
3143−fn css_px_multi(value: &str) -> String {
3145− .split_whitespace()
3146− .map(|p| css_px(p))
3147− .collect::<Vec<_>>()
3151fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
2325fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
3152 let mut id = None;
2326 let mut id = None;
3153 let mut class = None;
2327 let mut class = None;
3154− for attr in attrs {
2328+ for attr in attrs.iter().filter(|a| a.html) {
3155 match attr.key.as_str() {
2329 match attr.key.as_str() {
3156 "id" => id = attr.value.clone(),
2330 "id" => id = attr.value.clone(),
3157 "class" => class = attr.value.clone(),
2331 "class" => class = attr.value.clone(),
@@ -3161,149 +2335,6 @@ fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
3161 (id, class)
2335 (id, class)
3164−/// Read image dimensions from a local file by parsing the header bytes.
3165−/// Supports PNG, JPEG, GIF, WebP, AVIF, and SVG.
3166−fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
3167− // SVG: parse as text for viewBox/width/height attributes
3168− if path.ends_with(".svg") || path.ends_with(".SVG") {
3169− let text = std::fs::read_to_string(path).ok()?;
3170− return read_svg_dimensions(&text);
3173− let data = std::fs::read(path).ok()?;
3174− if data.len() < 12 {
3178− // PNG: 8-byte signature, then IHDR chunk with width/height at bytes 16-23
3179− if data.len() >= 24 && data.starts_with(b"\x89PNG\r\n\x1a\n") {
3180− let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
3181− let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
3182− return Some((w, h));
3185− // GIF: "GIF87a" or "GIF89a", width/height at bytes 6-9 (little-endian)
3186− if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
3187− let w = u16::from_le_bytes([data[6], data[7]]) as u32;
3188− let h = u16::from_le_bytes([data[8], data[9]]) as u32;
3189− return Some((w, h));
3192− // JPEG: scan for SOF0/SOF2 marker (0xFF 0xC0 or 0xFF 0xC2)
3193− if data.starts_with(b"\xff\xd8") {
3195− while i + 9 < data.len() {
3196− if data[i] != 0xFF {
3200− let marker = data[i + 1];
3201− if marker == 0xC0 || marker == 0xC2 {
3202− let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
3203− let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
3204− return Some((w, h));
3206− if i + 3 < data.len() {
3207− let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
3215− // WebP: "RIFF" ... "WEBP", VP8 header at byte 20
3216− if data.len() >= 30 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
3217− if &data[12..16] == b"VP8 " && data.len() >= 30 {
3218− let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
3219− let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
3220− return Some((w, h));
3222− if &data[12..16] == b"VP8L" && data.len() >= 25 && data[21] == 0x2F {
3223− let bits = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
3224− let w = (bits & 0x3FFF) + 1;
3225− let h = ((bits >> 14) & 0x3FFF) + 1;
3226− return Some((w, h));
3230− // AVIF: ISOBMFF container with "ftyp" box containing "avif"/"avis" brand,
3231− // then "ispe" box with width/height
3232− if data.len() >= 12 && &data[4..8] == b"ftyp" {
3233− let brand = &data[8..12];
3234− if brand == b"avif" || brand == b"avis" || brand == b"mif1" {
3235− return read_avif_dimensions(&data);
3242−/// Parse SVG viewBox or width/height attributes to get dimensions.
3243−fn read_svg_dimensions(text: &str) -> Option<(u32, u32)> {
3244− // Try viewBox first: viewBox="minX minY width height"
3245− if let Some(vb_start) = text.find("viewBox=\"") {
3246− let rest = &text[vb_start + 9..];
3247− if let Some(end) = rest.find('"') {
3248− let parts: Vec<&str> = rest[..end].split_whitespace().collect();
3249− if parts.len() == 4 {
3250− if let (Ok(w), Ok(h)) = (parts[2].parse::<f64>(), parts[3].parse::<f64>()) {
3251− if w > 0.0 && h > 0.0 {
3252− return Some((w.round() as u32, h.round() as u32));
3258− // Fall back to width/height attributes on <svg>
3259− let svg_tag = text.find("<svg")?;
3260− let tag_end = text[svg_tag..].find('>')? + svg_tag;
3261− let tag = &text[svg_tag..tag_end];
3262− let w = extract_svg_attr(tag, "width")?;
3263− let h = extract_svg_attr(tag, "height")?;
3267−fn extract_svg_attr(tag: &str, attr: &str) -> Option<u32> {
3268− let needle = format!("{}=\"", attr);
3269− let start = tag.find(&needle)? + needle.len();
3270− let rest = &tag[start..];
3271− let end = rest.find('"')?;
3272− let val = rest[..end].trim_end_matches("px");
3273− val.parse::<f64>().ok().map(|v| v.round() as u32)
3276−/// Parse AVIF (ISOBMFF) container to find ispe box with image dimensions.
3277−fn read_avif_dimensions(data: &[u8]) -> Option<(u32, u32)> {
3278− // Walk ISOBMFF boxes looking for "ispe" (image spatial extents)
3280− while i + 8 <= data.len() {
3281− let box_size = u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as usize;
3282− let box_type = &data[i + 4..i + 8];
3286− let box_end = (i + box_size).min(data.len());
3287− // ispe box: 4 bytes version/flags + 4 bytes width + 4 bytes height
3288− if box_type == b"ispe" && box_end >= i + 20 {
3289− let w = u32::from_be_bytes([data[i + 12], data[i + 13], data[i + 14], data[i + 15]]);
3290− let h = u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
3291− return Some((w, h));
3293− // Recurse into container boxes (meta, iprp, ipco)
3294− if matches!(box_type, b"meta" | b"iprp" | b"ipco" | b"moov" | b"trak" | b"mdia") {
3295− let header_size = if box_type == b"meta" { 12 } else { 8 };
3296− if i + header_size < box_end {
3297− if let Some(dims) = read_avif_dimensions(&data[i + header_size..box_end]) {
3307fn html_escape(s: &str) -> String {
2338fn html_escape(s: &str) -> String {
3308 s.replace('&', "&")
2339 s.replace('&', "&")
3309 .replace('<', "<")
2340 .replace('<', "<")
@@ -3342,10 +2373,24 @@ fn base64_encode(data: &[u8]) -> String {
3342/// Generate a standard v3 source map with VLQ-encoded mappings.
2373/// Generate a standard v3 source map with VLQ-encoded mappings.
3343/// Compatible with browser devtools and source map tooling.
2374/// Compatible with browser devtools and source map tooling.
3344pub 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 {
3345 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)
3346− collect_source_lines(&doc.nodes, &mut mappings);
2383+ for (idx, line) in html.lines().enumerate() {
3347− mappings.sort_by_key(|m| m.0);
2384+ if let Some(pos) = line.find("data-hl-line=\"") {
3348− 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));
3350 // Build VLQ-encoded mappings string.
2395 // Build VLQ-encoded mappings string.
3351 // 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
@@ -3363,16 +2408,19 @@ pub fn generate_source_map(doc: &Document, source_file: &str) -> String {
3363 if mapping_idx < mappings.len() && mappings[mapping_idx].0 == gen_line {
2408 if mapping_idx < mappings.len() && mappings[mapping_idx].0 == gen_line {
3364 let source_line = mappings[mapping_idx].1 as i64 - 1; // 0-based
2409 let source_line = mappings[mapping_idx].1 as i64 - 1; // 0-based
3365 // Segment: gen_col=0, source_idx=0, source_line=delta, source_col=0
2410 // Segment: gen_col=0, source_idx=0, source_line=delta, source_col=0
3366− vlq_encode(0, &mut vlq); // generated column (always 0)
2411+ vlq_encode(0, &mut vlq); // generated column (always 0)
3367− vlq_encode(0, &mut vlq); // source file index (always 0)
2412+ vlq_encode(0, &mut vlq); // source file index (always 0)
3368 vlq_encode(source_line - prev_source_line, &mut vlq); // source line delta
2413 vlq_encode(source_line - prev_source_line, &mut vlq); // source line delta
3369− vlq_encode(0, &mut vlq); // source column (always 0)
2414+ vlq_encode(0, &mut vlq); // source column (always 0)
3370 prev_source_line = source_line;
2415 prev_source_line = source_line;
3371 mapping_idx += 1;
2416 mapping_idx += 1;
3375− let escaped_file = source_file.replace(".hl", ".html").replace('\\', "\\\\").replace('"', "\\\"");
2420+ let escaped_file = source_file
2421+ .replace(".hl", ".html")
2422+ .replace('\\', "\\\\")
2423+ .replace('"', "\\\"");
3376 let escaped_source = source_file.replace('\\', "\\\\").replace('"', "\\\"");
2424 let escaped_source = source_file.replace('\\', "\\\\").replace('"', "\\\"");
3378 format!(
2426 format!(
@@ -3402,52 +2450,30 @@ fn vlq_encode(value: i64, out: &mut String) {
3405−fn collect_source_lines(nodes: &[Node], mappings: &mut Vec<(usize, usize)>) {
2453+#[cfg(test)]
3406− for node in nodes {
2454+mod tests {
3407− if let Node::Element(elem) = node {
2455+ use super::*;
3408− if elem.line_num > 0 {
2456+
3409− mappings.push((mappings.len() + 1, elem.line_num));
2457+ #[test]
3410− }
2458+ fn a_name_is_a_stable_hash_of_the_style() {
3411− collect_source_lines(&elem.children, mappings);
2459+ // The same in every build and on every platform
3412− }
2460+ assert_eq!(stable_hash(""), 0xf52a_15e9_a9b5_e89b);
3413− }
2461+ assert_eq!(hash_digits(35, 3), "z00");
3414−}
2462+ assert_eq!(hash_digits(u64::MAX, 13), "fsgs46211e5w3");
3416−/// Check if a specific element kind exists anywhere in the node tree.
2464+
3417−fn has_element_kind(nodes: &[Node], target: &ElementKind) -> bool {
2465+ #[test]
3418− for node in nodes {
2466+ fn a_name_taken_in_the_file_takes_more_digits() {
3419− if let Node::Element(elem) = node {
2467+ // These two styles' hashes end in the same 7 digits
3420− if elem.kind == *target {
2468+ let mut styles = StyleCollector::new();
3421− return true;
2469+ let first = styles.get_class("width:129555px;".into(), Vec::new(), String::new());
3422− }
2470+ let second = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
3423− if has_element_kind(&elem.children, target) {
2471+ let (first, second) = (first.unwrap(), second.unwrap());
3424− return true;
2472+ assert_eq!(first.len(), 3 + CLASS_DIGITS, "{first}");
3425− }
2473+ assert_eq!(second.len(), 3 + CLASS_DIGITS + 1, "{second}");
3426− }
2474+ assert!(second.starts_with(&first), "{first} {second}");
3427− }
2475+ // The same style gets the name it got before
3428− false
2476+ let again = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
3429−}
2477+ assert_eq!(again.as_deref(), Some(second.as_str()));
3431−/// Collect unique external domains from generated HTML for DNS prefetch hints.
3432−fn collect_dns_prefetch(html: &str, dev: bool) -> String {
3433− let mut domains = Vec::new();
3434− let mut rest = html;
3435− while let Some(pos) = rest.find("https://") {
3436− let start = pos + 8; // skip "https://"
3437− rest = &rest[start..];
3438− let end = rest.find(|c: char| c == '/' || c == '"' || c == '\'' || c == ' ' || c == '>' || c == ')').unwrap_or(rest.len());
3439− let domain = &rest[..end];
3440− if !domain.is_empty() && domain.contains('.') && !domains.contains(&domain.to_string()) {
3441− domains.push(domain.to_string());
3444− let mut out = String::new();
3445− for domain in &domains {
3447− out.push_str(&format!("<link rel=\"dns-prefetch\" href=\"//{}\">\n", domain));
3449− out.push_str(&format!("<link rel=\"dns-prefetch\" href=\"//{}\">", domain));