@@ -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,56 +17,315 @@ const BREAKPOINTS: &[(&str, &str)] = &[
16 ("2xl", "1536px"),
17 ("2xl", "1536px"),
19−/// Generate short CSS class names: a..z, then aa..a9, ba..b9, ..., z9, then
20+/// The prefix of every generated class (`hl-2k9xq0m`), which keeps them
20−/// aaa, ... The first character is always a letter; later ones are drawn from
21+/// out of the author's own class names.
21−/// [a-z0-9]. The mapping is a bijection, so distinct indices never collide.
22+pub const CLASS_PREFIX: &str = "hl-";
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.
22−pub(crate) fn short_class_name(idx: usize) -> String {
46+pub fn hash_digits(hash: u64, digits: usize) -> String {
23− const REST: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
47+ const DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
24− // Find the name length: 26 names of length 1, 26*36 of length 2, ...
25− let mut n = idx;
48+ let mut n = hash;
26− let mut len = 1;
49+ (0..digits)
27− let mut count = 26usize;
50+ .map(|_| {
28− while n >= count {
51+ let digit = DIGITS[(n % 36) as usize] as char;
31− count = count.saturating_mul(36);
33− let mut tail = Vec::with_capacity(len - 1);
35− tail.push(REST[n % 36]);
38− let mut name = String::with_capacity(len);
54+ })
39− name.push((b'a' + n as u8) as char);
55+ .collect()
40− name.extend(tail.iter().rev().map(|&b| b as char));
56+}
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();
94+ /// Only the at-rule part: a direction under `hover:` is the one without
96+ fn at_only(at: &[usize]) -> Condition {
99+ selector: Vec::new(),
103+ /// The styles go on the element's children (`children:`).
104+ fn on_children(&self) -> bool {
105+ self.selector.iter().any(|p| p == crate::vocab::CHILDREN)
108+ /// The styles go on the elements of one kind inside the element
109+ /// (`@td:`): where the element prefix is in the selector chain.
110+ fn inside(&self) -> Option<usize> {
113+ .position(|p| crate::vocab::element_prefix(p).is_some())
116+ /// Whether this condition holds wherever `other` does: its at-rules
117+ /// are implied by `other`'s, and it has no selector or `other`'s.
118+ fn holds_at(&self, other: &Condition) -> bool {
119+ (self.selector.is_empty() || self.selector == other.selector)
120+ && self.at.iter().all(|&a| {
124+ .any(|&b| crate::vocab::at_rule_implied(a, b))
128+ /// The order the rules of each condition are written in, which the
129+ /// cascade follows: no prefix, then selectors, then each at-rule
130+ /// block (see [`at_order`]), with its selectors inside it.
131+ fn order(&self) -> (AtOrder, SelectorOrder) {
132+ (at_order(&self.at), selector_order(&self.selector))
136+/// Where a block of at-rules is written: after the rules without one; by
137+/// its last (innermost) prefix in the order of
138+/// [`crate::vocab::at_rule_prefixes`] (widths, media, container widths), so
139+/// `md:dark:` comes with `dark:`, after it; then by length.
140+type AtOrder = (bool, usize, usize, Vec<usize>);
142+fn at_order(at: &[usize]) -> AtOrder {
145+ at.last().copied().unwrap_or(0),
151+/// Selector chains in the order of [`crate::vocab::PSEUDOS`] (position,
152+/// then form state, then `hover:`, `focus:`, `active:`, `disabled:`), and
153+/// by their argument's text for the same pseudo-class; a chain before the
154+/// longer ones it starts. A chain through `children:` comes after the
155+/// others, ordered by what follows its last `children:` and then by what
156+/// comes before it: only that tail counts toward its specificity (see
157+/// [`selector`]), so `hover:children:` follows `children:` and wins over it
159+type SelectorOrder = (bool, Vec<(usize, String)>, Vec<(usize, String)>);
161+fn selector_order(selector: &[String]) -> SelectorOrder {
162+ let table = crate::vocab::PSEUDOS;
163+ let ranked = |chain: &[String]| -> Vec<(usize, String)> {
167+ let name = crate::vocab::pseudo_name(p);
170+ .position(|(q, _)| *q == name)
171+ .unwrap_or(table.len());
176+ match selector.iter().rposition(|p| p == crate::vocab::CHILDREN) {
177+ None => (false, ranked(selector), Vec::new()),
178+ Some(i) => (true, ranked(&selector[i + 1..]), ranked(&selector[..i])),
182+/// The order of the chains through an element prefix (`@td:`, see
183+/// [`scoped_selector`]): by the prefixes before it, which select the root
184+/// of the scope and add nothing to the specificity, so `hover:@td:` comes
185+/// after `@td:` and wins on hover; then by the element; then by the
186+/// prefixes after it.
187+fn inside_order(chain: &[String]) -> (SelectorOrder, String, SelectorOrder) {
190+ .position(|p| crate::vocab::element_prefix(p).is_some())
191+ .unwrap_or(chain.len());
193+ selector_order(&chain[..at]),
194+ chain.get(at).cloned().unwrap_or_default(),
195+ selector_order(chain.get(at + 1..).unwrap_or_default()),
199+/// The selector for `class` under a chain of selector prefixes, read left
200+/// to right. Everything before the last `children:` goes in `:where()`, so
201+/// a parent's `children:` styles have no specificity, and a child's own
202+/// attributes win over them: `children:hover:` is `:where(.a)>*:hover`,
203+/// `hover:children:` is `:where(.a:hover)>*`.
204+fn selector(class: &str, chain: &[String]) -> String {
205+ let last_children = chain.iter().rposition(|p| p == crate::vocab::CHILDREN);
206+ let mut out = format!(".{}", class);
207+ for (i, prefix) in chain.iter().enumerate() {
208+ if prefix == crate::vocab::CHILDREN {
209+ if Some(i) == last_children {
210+ out = format!(":where({})>*", out);
214+ } else if let Some(pseudo) = crate::vocab::pseudo_selector(prefix) {
215+ out.push_str(&pseudo);
221+/// The rule for the elements an element prefix picks out inside the
222+/// element with the class `class` (see [`Condition::inside`]): the scope's
223+/// root, from the selector prefixes before it (`hover:@td:` is inside a
224+/// hovered element), and the selector for the elements, from those after
225+/// it (`@td:hover:` is a hovered cell). `:scope td` leaves out the root
226+/// itself, so `@ul [@ul:...]` styles the lists inside, not its own. `None`
227+/// when the name has no tag of its own (the parser reports it).
228+fn scoped_selector(class: &str, chain: &[String], at: usize) -> Option<(String, String)> {
229+ let name = crate::vocab::element_prefix(&chain[at])?;
230+ let tag = ElementKind::from_name(name)?.own_tag()?;
231+ let root = selector(class, &chain[..at]);
232+ let mut target = format!(":scope {}", tag);
233+ for prefix in &chain[at + 1..] {
234+ if let Some(pseudo) = crate::vocab::pseudo_selector(prefix) {
235+ target.push_str(&pseudo);
238+ Some((root, target))
241+/// The `@media` or `@container` rule an at-rule prefix stands for, as
242+/// written in readable and in compact output.
243+fn at_rule(rank: usize, dev: bool) -> String {
244+ let prefix = crate::vocab::at_rule_prefixes()
246+ .unwrap_or_default();
247+ let name = prefix.trim_end_matches(':');
248+ let width = |name: &str| {
251+ .find(|(n, _)| *n == name)
252+ .map_or("0", |(_, w)| *w)
254+ let (kind, feature, value) = if let Some(size) = name.strip_prefix("cq-") {
255+ ("@container", "min-width", width(size))
259+ return "@media print".to_string();
261+ "dark" => ("@media", "prefers-color-scheme", "dark"),
262+ "motion-safe" => ("@media", "prefers-reduced-motion", "no-preference"),
263+ "motion-reduce" => ("@media", "prefers-reduced-motion", "reduce"),
264+ "landscape" | "portrait" => ("@media", "orientation", name),
265+ _ => ("@media", "min-width", width(name)),
269+ format!("{} ({}: {})", kind, feature, value)
271+ format!("{}({}:{})", kind, feature, value)
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);
44struct StyleEntry {
298struct StyleEntry {
45 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.
46− base: String,
307+ defaults: String,
47− /// (CSS selector suffix, css_rules) — e.g. (":hover", "color:red;")
308+ /// The element's rules: under each condition, its declarations, in the
48− pseudo: Vec<(String, String)>,
309+ /// order they are written
49− /// Responsive overrides: (breakpoint_prefix, css)
310+ rules: Vec<(Condition, String)>,
50− responsive: Vec<(String, String)>,
311+ /// What else tells two elements with the same CSS apart: the rules
51− /// Dark mode overrides
312+ /// keyed on this class (see [`StyleCollector::keyed`]). Not written.
52− dark: String,
313+ distinct: String,
56− motion_reduce: String,
59− /// Container query overrides: (breakpoint_prefix, css)
60− container: Vec<(String, String)>,
63struct StyleCollector {
316struct StyleCollector {
64 entries: Vec<StyleEntry>,
317 entries: Vec<StyleEntry>,
65− /// 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
66− /// Using u64 as the key keeps lookups allocation-free; on the rare case of
319+ /// styles hash alike, which the full comparison tells apart).
67− /// a hash collision we fall back to a full equality check against the entry.
68 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)>,
71impl StyleCollector {
331impl StyleCollector {
@@ -73,313 +333,282 @@ impl StyleCollector {
73 StyleCollector {
333 StyleCollector {
74 entries: Vec::new(),
334 entries: Vec::new(),
75 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);
79 /// 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.
80− #[allow(clippy::too_many_arguments)]
81 fn get_class(
351 fn get_class(
82 &mut self,
352 &mut self,
83− base: String,
353+ defaults: String,
84− pseudo: Vec<(String, String)>,
354+ mut rules: Vec<(Condition, String)>,
85− responsive: Vec<(String, String)>,
355+ distinct: String,
89− motion_reduce: String,
92− container: Vec<(String, String)>,
93 ) -> Option<String> {
356 ) -> Option<String> {
357+ rules.retain(|(_, body)| !body.is_empty());
94− if base.is_empty()
358+ if defaults.is_empty() && rules.is_empty() {
96− && responsive.is_empty()
99− && motion_safe.is_empty()
100− && motion_reduce.is_empty()
101− && landscape.is_empty()
102− && portrait.is_empty()
103− && container.is_empty()
105 return None;
359 return None;
107− use std::collections::hash_map::DefaultHasher;
361+ rules.sort_by_cached_key(|(condition, _)| condition.order());
108− let mut h = DefaultHasher::new();
362+ let style = stable_hash(&style_text(&defaults, &rules, &distinct));
109− base.hash(&mut h);
363+
110− pseudo.hash(&mut h);
111− responsive.hash(&mut h);
114− motion_safe.hash(&mut h);
115− motion_reduce.hash(&mut h);
116− landscape.hash(&mut h);
117− portrait.hash(&mut h);
118− container.hash(&mut h);
119− let sig = h.finish();
121− if let Some(indices) = self.index.get(&sig) {
364+ if let Some(indices) = self.index.get(&style) {
122 for &idx in indices {
365 for &idx in indices {
123 let e = &self.entries[idx];
366 let e = &self.entries[idx];
124− if e.base == base
367+ if e.defaults == defaults && e.rules == rules && e.distinct == distinct {
125− && e.pseudo == pseudo
126− && e.responsive == responsive
129− && e.motion_safe == motion_safe
130− && e.motion_reduce == motion_reduce
131− && e.landscape == landscape
132− && e.portrait == portrait
133− && e.container == container
135 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
139 let idx = self.entries.len();
375 let idx = self.entries.len();
140− 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());
141 self.entries.push(StyleEntry {
381 self.entries.push(StyleEntry {
142 class_name: name.clone(),
382 class_name: name.clone(),
144− pseudo,
384+ defaults,
145− responsive,
385+ rules,
154− self.index.entry(sig).or_default().push(idx);
388+ self.index.entry(style).or_default().push(idx);
155 Some(name)
389 Some(name)
158− /// All generated rules, wrapped in `@layer htmlang`.
392+ /// The classes given, in the order they were
393+ fn classes(&self) -> impl Iterator<Item = Class> + '_ {
394+ self.entries.iter().map(|e| Class {
395+ name: e.class_name.clone(),
400+ /// All generated rules, in three layers (see [`LAYERS`]): the element
401+ /// kinds' defaults in `hl-kind` (`:where(.hl-a)`), the rules for the
402+ /// elements an element prefix picks out inside an element (`@td:`), and
403+ /// a function's scoped `@style`, in `hl-inside`, and the elements' own
404+ /// rules in `htmlang`. They are written in a fixed order, so which rule
405+ /// wins never depends on where in the page an element is: the rules
406+ /// without a prefix, then those under selector prefixes, then each block
407+ /// of at-rules (see [`at_order`]), in which the rules keyed on a parent
408+ /// come first, then the element's own, then its selectors (see
409+ /// [`selector_order`]).
159− fn to_css_formatted(&self, dev: bool) -> String {
410+ fn to_css_formatted(&self, dev: bool, scoped: &[String]) -> String {
411+ // The defaults: `:where(.hl-a,.hl-b){...}`
160− let mut css = String::new();
412+ let mut kind = String::new();
161− let inner_indent = if dev { " " } else { "" };
413+ let mut defaults: Vec<(&str, Vec<&str>)> = Vec::new();
162− css.push_str(if dev { "@layer htmlang {\n" } else { "@layer htmlang{" });
414+ for e in self.entries.iter().filter(|e| !e.defaults.is_empty()) {
163−
415+ match defaults.iter_mut().find(|(body, _)| *body == e.defaults) {
164− // Non-responsive rules. Base and pseudo rules are merged separately by
416+ Some((_, classes)) => classes.push(&e.class_name),
165− // identical body so that e.g. `.a,.b{display:flex;flex-direction:column;}`
417+ None => defaults.push((&e.defaults, vec![&e.class_name])),
166− // replaces two identical rules. Pseudo variants are grouped per selector
418+ }
167− // suffix (`:hover` with `:hover`, etc.) to keep each pseudo's cascade
419+ }
168− // position independent of others.
420+ for (body, classes) in defaults {
169− let mut base_pairs: Vec<(&str, &str)> = Vec::with_capacity(self.entries.len());
421+ let classes: Vec<String> = classes.iter().map(|c| format!(".{}", c)).collect();
170− for e in &self.entries {
422+ let selector = format!(":where({})", classes.join(","));
171− if !e.base.is_empty() {
423+ if dev {
172− base_pairs.push((e.class_name.as_str(), e.base.as_str()));
424+ kind.push_str(&format!(" {} {{{}}}\n", selector, body));
426+ kind.push_str(&format!("{}{{{}}}", selector, body));
175− emit_grouped_rules(&mut css, &base_pairs, "", inner_indent, dev);
177− // Collect pseudo rules grouped by selector suffix, preserving the order
430+ let mut inside = self.blocks(true, dev);
178− // in which suffixes first appear across entries.
431+ // A function's scoped `@style`, nested under its class
179− let mut pseudo_order: Vec<&str> = Vec::new();
432+ for block in scoped {
180− let mut pseudo_buckets: HashMap<&str, Vec<(&str, &str)>> = HashMap::new();
433+ if dev {
181− for e in &self.entries {
434+ inside.push_str(block);
182− for (selector, body) in &e.pseudo {
435+ inside.push('\n');
183− if body.is_empty() {
436+ } else {
184− continue;
437+ inside.push_str(&compact_css(block));
186− let key = selector.as_str();
187− if !pseudo_buckets.contains_key(key) {
188− pseudo_order.push(key);
193− .push((e.class_name.as_str(), body.as_str()));
196− for selector in &pseudo_order {
440+
197− if let Some(pairs) = pseudo_buckets.get(selector) {
441+ let mut css = String::new();
198− emit_grouped_rules(&mut css, pairs, selector, inner_indent, dev);
442+ for (name, rules) in [
444+ ("hl-inside", inside),
445+ ("htmlang", self.blocks(false, dev)),
447+ if rules.is_empty() {
451+ css.push_str(&format!("@layer {} {{\n{}}}\n", name, rules));
453+ css.push_str(&format!("@layer {}{{{}}}", name, rules));
202− // Responsive rules grouped by breakpoint
459+ /// The rules of every block of at-rules, in order: those for the
203− for &(bp_name, bp_width) in BREAKPOINTS {
460+ /// elements inside (`inside`: rules under an element prefix, each in
204− let mut bp_pairs: Vec<(&str, &str)> = Vec::new();
461+ /// an `@scope` on its element's class), or the elements' own.
462+ fn blocks(&self, inside: bool, dev: bool) -> String {
463+ let mut css = String::new();
205− for e in &self.entries {
465+ self.entries.iter().flat_map(move |e| {
206− for (bp, rule_css) in &e.responsive {
466+ e.rules
207− if bp == bp_name && !rule_css.is_empty() {
467+ .iter()
208− bp_pairs.push((e.class_name.as_str(), rule_css.as_str()));
468+ .filter(move |(c, _)| c.inside().is_some() == inside)
469+ .map(move |(c, body)| (e, c, body))
472+ let mut blocks: Vec<&[usize]> = vec![&[]];
473+ let keyed = self.keyed.iter().filter(|_| !inside);
475+ .map(|(_, c, _)| c.at.as_slice())
476+ .chain(keyed.map(|(at, _, _)| at.as_slice()));
478+ if !blocks.contains(&at) {
482+ blocks.sort_by_key(|at| at_order(at));
485+ let depth = at.len();
486+ // Readable output indents a rule inside `@layer` and inside
487+ // each at-rule but the first
488+ let indent = if dev {
489+ " ".repeat(depth.max(1))
493+ let mut inner = String::new();
494+ // Rules keyed on a parent's class come first: they have the
495+ // specificity of one class, like a class rule, so the child's
496+ // own rules in the block still win
498+ let keyed: Vec<(&str, &str)> = self
501+ .filter(|(a, _, _)| a.as_slice() == at)
502+ .map(|(_, selector, body)| (selector.as_str(), body.as_str()))
504+ emit_selector_rules(&mut inner, &keyed, &indent, dev);
506+ // The selector chains of this block, in order
507+ let mut chains: Vec<&[String]> = Vec::new();
508+ for (_, condition, _) in rules() {
509+ if condition.at == at && !chains.contains(&condition.selector.as_slice()) {
510+ chains.push(&condition.selector);
514+ chains.sort_by_cached_key(|chain| inside_order(chain));
515+ // One `@scope` for each root, its rules in the order of
516+ // the chains: rules for one element under two roots (`.a`
517+ // and `.a:hover`) tie on specificity and proximity, so the
519+ let mut scopes: Vec<(String, Vec<(String, &str)>)> = Vec::new();
520+ for chain in chains {
521+ let Some(element) = chain
523+ .position(|p| crate::vocab::element_prefix(p).is_some())
528+ rules().filter(|(_, c, _)| c.at == at && c.selector == chain)
530+ let Some((root, target)) = scoped_selector(&e.class_name, chain, element)
534+ match scopes.iter_mut().find(|(r, _)| *r == root) {
535+ Some((_, targets)) => targets.push((target, body)),
536+ None => scopes.push((root, vec![(target, body)])),
211− }
540+ let inner_indent = if dev {
212− emit_media_block(
541+ format!("{} ", indent)
213− &mut css,
542+ } else {
214− &format!("@media (min-width: {})", bp_width),
543+ String::new()
215− &format!("@media(min-width:{})", bp_width),
544+ };
216− &bp_pairs,
545+ for (root, targets) in scopes {
217− "",
546+ let targets: Vec<(&str, &str)> =
218− dev,
547+ targets.iter().map(|(t, b)| (t.as_str(), *b)).collect();
219− );
548+ inner.push_str(&indent);
220− }
549+ inner.push_str(&format!("@scope ({})", root));
221−
550+ inner.push_str(if dev { " {\n" } else { "{" });
222− // Dark mode rules
551+ emit_selector_rules(&mut inner, &targets, &inner_indent, dev);
223− let dark_pairs: Vec<(&str, &str)> = self
552+ inner.push_str(&indent);
224− .entries
553+ inner.push_str(if dev { "}\n" } else { "}" });
226− .filter(|e| !e.dark.is_empty())
227− .map(|e| (e.class_name.as_str(), e.dark.as_str()))
231− "@media (prefers-color-scheme: dark)",
232− "@media(prefers-color-scheme:dark)",
239− let print_pairs: Vec<(&str, &str)> = self
242− .filter(|e| !e.print.is_empty())
243− .map(|e| (e.class_name.as_str(), e.print.as_str()))
254− // Motion safe rules
255− let motion_safe_pairs: Vec<(&str, &str)> = self
258− .filter(|e| !e.motion_safe.is_empty())
259− .map(|e| (e.class_name.as_str(), e.motion_safe.as_str()))
263− "@media (prefers-reduced-motion: no-preference)",
264− "@media(prefers-reduced-motion:no-preference)",
270− // Motion reduce rules
271− let motion_reduce_pairs: Vec<(&str, &str)> = self
274− .filter(|e| !e.motion_reduce.is_empty())
275− .map(|e| (e.class_name.as_str(), e.motion_reduce.as_str()))
279− "@media (prefers-reduced-motion: reduce)",
280− "@media(prefers-reduced-motion:reduce)",
281− &motion_reduce_pairs,
287− let landscape_pairs: Vec<(&str, &str)> = self
290− .filter(|e| !e.landscape.is_empty())
291− .map(|e| (e.class_name.as_str(), e.landscape.as_str()))
295− "@media (orientation: landscape)",
296− "@media(orientation:landscape)",
303− let portrait_pairs: Vec<(&str, &str)> = self
306− .filter(|e| !e.portrait.is_empty())
307− .map(|e| (e.class_name.as_str(), e.portrait.as_str()))
311− "@media (orientation: portrait)",
312− "@media(orientation:portrait)",
318− // Container query rules grouped by breakpoint
319− for &(bp_name, bp_width) in BREAKPOINTS {
320− let mut cq_pairs: Vec<(&str, &str)> = Vec::new();
321− for e in &self.entries {
322− for (bp, rule_css) in &e.container {
323− if bp == bp_name && !rule_css.is_empty() {
324− cq_pairs.push((e.class_name.as_str(), rule_css.as_str()));
556+ chains.sort_by_cached_key(|chain| selector_order(chain));
557+ for chain in chains {
558+ let pairs: Vec<(String, &str)> = rules()
559+ .filter(|(_, c, _)| c.at == at && c.selector == chain)
560+ .map(|(e, _, body)| (selector(&e.class_name, chain), body.as_str()))
562+ emit_grouped_rules(&mut inner, &pairs, &indent, dev);
565+ if inner.is_empty() {
328− emit_media_block(
568+ // Each at-rule wraps the next, outermost first
329− &mut css,
569+ for (level, &rank) in at.iter().enumerate().rev() {
330− &format!("@container (min-width: {})", bp_width),
570+ let pad = if dev {
331− &format!("@container(min-width:{})", bp_width),
571+ " ".repeat(level)
332− &cq_pairs,
572+ } else {
333− "",
573+ String::new()
335− );
575+ inner = if dev {
576+ format!("{pad}{} {{\n{inner}{pad}}}\n", at_rule(rank, true))
578+ format!("{}{{{inner}}}", at_rule(rank, false))
581+ css.push_str(&inner);
338− css.push_str(if dev { "}\n" } else { "}" });
343−/// Emit CSS rules from `(class_name, body)` pairs, merging identical bodies
587+/// Emit CSS rules from `(selector, body)` pairs, merging identical bodies
344/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
588/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
345/// of each distinct body determines ordering, so output stays deterministic
589/// of each distinct body determines ordering, so output stays deterministic
346−/// across runs. `selector_suffix` is appended to each class (e.g. `":hover"`,
347−/// or `""` for plain class rules). `indent` is prepended to each rule line.
590+/// across runs. `indent` is prepended to each rule line.
348−fn emit_grouped_rules(
591+fn emit_grouped_rules(out: &mut String, pairs: &[(String, &str)], indent: &str, dev: bool) {
350− pairs: &[(&str, &str)],
351− selector_suffix: &str,
355 if pairs.is_empty() {
592 if pairs.is_empty() {
358 // Group in first-occurrence order.
595 // Group in first-occurrence order.
359 let mut order: Vec<&str> = Vec::new();
596 let mut order: Vec<&str> = Vec::new();
360 let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
597 let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
361− for &(name, body) in pairs {
598+ for (selector, body) in pairs {
362 if body.is_empty() {
599 if body.is_empty() {
363 continue;
600 continue;
365 if !groups.contains_key(body) {
602 if !groups.contains_key(body) {
366 order.push(body);
603 order.push(body);
368− groups.entry(body).or_default().push(name);
605+ groups.entry(body).or_default().push(selector);
370 let sp = if dev { " " } else { "" };
607 let sp = if dev { " " } else { "" };
371 let nl = if dev { "\n" } else { "" };
608 let nl = if dev { "\n" } else { "" };
372 for body in &order {
609 for body in &order {
373− let names = &groups[body];
374 out.push_str(indent);
610 out.push_str(indent);
375− for (i, n) in names.iter().enumerate() {
611+ out.push_str(&groups[body].join(","));
381− out.push_str(selector_suffix);
383 out.push_str(sp);
612 out.push_str(sp);
384 out.push('{');
613 out.push('{');
385 out.push_str(body);
614 out.push_str(body);
@@ -388,37 +617,44 @@ fn emit_grouped_rules(
391−/// Emit an `@media` / `@container` block containing grouped class rules.
620+/// Emit `(selector, body)` rules in their order, merging a run of rules
392−/// Skips the block entirely if no non-empty bodies are present.
621+/// with the same body into one rule with a selector list (the order
393−fn emit_media_block(
622+/// matters: two rules may apply to one element).
394− out: &mut String,
623+fn emit_selector_rules(out: &mut String, rules: &[(&str, &str)], indent: &str, dev: bool) {
395− header_dev: &str,
624+ let mut i = 0;
396− header_min: &str,
625+ while i < rules.len() {
397− pairs: &[(&str, &str)],
626+ let body = rules[i].1;
398− selector_suffix: &str,
627+ let run = rules[i..].iter().take_while(|(_, b)| *b == body).count();
399− dev: bool,
628+ if !body.is_empty() {
400−) {
629+ let selectors: Vec<&str> = rules[i..i + run].iter().map(|(s, _)| *s).collect();
401− if pairs.iter().all(|(_, body)| body.is_empty()) {
630+ out.push_str(indent);
402− return;
631+ out.push_str(&selectors.join(","));
404− let mut inner = String::new();
633+ out.push(' ');
405− let inner_indent = if dev { " " } else { "" };
634+ }
406− emit_grouped_rules(&mut inner, pairs, selector_suffix, inner_indent, dev);
635+ out.push('{');
407− if inner.is_empty() {
636+ out.push_str(body);
408− return;
637+ out.push('}');
410− if dev {
638+ if dev {
411− out.push_str(&format!("{} {{\n{}}}\n", header_dev, inner));
639+ out.push('\n');
413− out.push_str(&format!("{}{{{}}}", header_min, inner));
641+ }
417struct GenContext {
646struct GenContext {
418 dev: bool,
647 dev: bool,
419 depth: usize,
648 depth: usize,
421 has_interactive: bool,
649 has_interactive: bool,
650+ /// Writing inside a text element, at any depth: htmlang's own `<div>`s
651+ /// are `<span>`s there, which text can hold.
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`
424impl GenContext {
660impl GenContext {
@@ -444,23 +680,26 @@ pub struct CodegenOptions {
444 pub dev: bool,
680 pub dev: bool,
445 pub partial: bool,
681 pub partial: bool,
446 pub minify: bool,
682 pub minify: bool,
450/// Generate HTML from a parsed document using the given options.
685/// Generate HTML from a parsed document using the given options.
451pub 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();
452 let mut html = if opts.partial {
694 let mut html = if opts.partial {
453− generate_partial_inner(doc, opts.dev)
695+ generate_partial_inner(doc, opts.dev, &mut classes)
455− generate_full_inner(doc, opts.dev)
697+ generate_full_inner(doc, opts.dev, &mut classes)
457 if opts.minify {
699 if opts.minify {
458 html = minify_html(&html);
700 html = minify_html(&html);
460− if opts.compat {
702+ (html, classes)
461− html = add_vendor_prefixes(&html);
466pub fn generate(doc: &Document) -> String {
705pub fn generate(doc: &Document) -> String {
@@ -508,38 +747,6 @@ pub fn generate_minified(doc: &Document) -> String {
511−pub fn generate_compat(doc: &Document) -> String {
516− ..Default::default()
521−pub fn generate_dev_compat(doc: &Document) -> String {
527− ..Default::default()
532−pub fn generate_minified_compat(doc: &Document) -> String {
538− ..Default::default()
543fn minify_html(html: &str) -> String {
750fn minify_html(html: &str) -> String {
544 let mut result = String::with_capacity(html.len());
751 let mut result = String::with_capacity(html.len());
545 let mut in_pre = false;
752 let mut in_pre = false;
@@ -618,499 +825,132 @@ fn minify_html(html: &str) -> String {
621−/// Add vendor prefixes to CSS within <style> tags for broader browser compatibility.
622−fn add_vendor_prefixes(html: &str) -> String {
623− // Find CSS within <style>...</style> and add vendor prefixes
624− let mut result = String::with_capacity(html.len() + 512);
625− let mut rest = html;
626− while let Some(start) = rest.find("<style>") {
627− let after_tag = start + 7;
628− result.push_str(&rest[..after_tag]);
629− rest = &rest[after_tag..];
630− if let Some(end) = rest.find("</style>") {
631− let css = &rest[..end];
632− result.push_str(&prefix_css(css));
633− result.push_str("</style>");
634− rest = &rest[end + 8..];
639− result.push_str(rest);
643−fn prefix_css(css: &str) -> String {
644− let mut out = String::with_capacity(css.len() + 256);
646− let bytes = css.as_bytes();
647− while i < bytes.len() {
648− // Find property declarations
649− if let Some(pos) = css[i..].find('{') {
650− let brace = i + pos;
651− out.push_str(&css[i..=brace]);
653− // Process declarations within this block
654− if let Some(close) = css[i..].find('}') {
655− let block = &css[i..i + close];
656− out.push_str(&prefix_declarations(block));
661− out.push_str(&css[i..]);
668−fn prefix_declarations(block: &str) -> String {
669− let mut out = String::with_capacity(block.len() + 128);
670− for decl in block.split(';') {
671− let decl = decl.trim();
672− if decl.is_empty() {
675− if let Some((prop, val)) = decl.split_once(':') {
676− let prop = prop.trim();
677− let val = val.trim();
679− "backdrop-filter" => {
680− out.push_str(&format!("-webkit-backdrop-filter:{};", val));
681− out.push_str(&format!("backdrop-filter:{};", val));
684− out.push_str(&format!("-webkit-user-select:{};", val));
685− out.push_str(&format!("-moz-user-select:{};", val));
686− out.push_str(&format!("user-select:{};", val));
689− out.push_str(&format!("-webkit-appearance:{};", val));
690− out.push_str(&format!("-moz-appearance:{};", val));
691− out.push_str(&format!("appearance:{};", val));
693− "background-clip" if val.contains("text") => {
694− out.push_str(&format!("-webkit-background-clip:{};", val));
695− out.push_str(&format!("background-clip:{};", val));
698− out.push_str(&format!("-webkit-hyphens:{};", val));
699− out.push_str(&format!("-ms-hyphens:{};", val));
700− out.push_str(&format!("hyphens:{};", val));
702− "text-size-adjust" => {
703− out.push_str(&format!("-webkit-text-size-adjust:{};", val));
704− out.push_str(&format!("-ms-text-size-adjust:{};", val));
705− out.push_str(&format!("text-size-adjust:{};", val));
707− "mask-image" | "mask-size" | "mask-repeat" | "mask-position" => {
708− out.push_str(&format!("-webkit-{}:{};", prop, val));
709− out.push_str(&format!("{}:{};", prop, val));
724−fn generate_full_inner(doc: &Document, dev: bool) -> String {
828+fn generate_full_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
829+ // Without `@page` the output is a fragment
830+ let Some(page) = &doc.page else {
831+ return generate_partial_inner(doc, dev, classes);
725 let mut styles = StyleCollector::new();
833 let mut styles = StyleCollector::new();
726 let mut ctx = GenContext {
834 let mut ctx = GenContext {
728 depth: 0,
836 depth: 0,
730 has_interactive: false,
837 has_interactive: false,
839+ flow: Flow::default(),
733− // Check if document has @main for skip-to-content link
843+ // The page is the root element: `<body>` is a column (the reset makes
734− let has_main = has_tag(&doc.nodes, "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();
736 let mut body = String::new();
867 let mut body = String::new();
870+ Some(Layout::Column),
738− // Skip-to-content link for accessibility (only when @main exists)
876+ let element_css = build_element_css(doc, &styles, dev);
740− if dev {
877+ let nl = if dev { "\n" } else { "" };
741− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>\n");
743− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>");
747− for node in &doc.nodes {
879+ let mut meta_html = String::new();
748− generate_node(node, None, &mut body, &mut styles, &mut ctx);
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);
751− // Collect external domains for DNS prefetch
920+ // `@page`'s HTML attributes go on `<html>`
752− let dns_prefetch_html = collect_dns_prefetch(&body, dev);
921+ let mut root_attrs = String::new();
753−
922+ for attr in html_attrs(&page.html_attrs) {
754− let element_css = build_element_css(doc, &styles, dev);
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);
756− // Build meta tags string
928+ // Focus-visible CSS for interactive elements (accessibility)
757− let meta_html = if doc.meta_tags.is_empty() {
929+ let focus_visible_css = if ctx.has_interactive {
758− String::new()
930+ let focusable = ":where(a,button,input,select,textarea):focus-visible";
760− let mut m = String::new();
761− for (name, content) in &doc.meta_tags {
762− if dev {
931+ if dev {
763− m.push_str(&format!(
932+ format!(
764− "<meta name=\"{}\" content=\"{}\">\n",
933+ "{}{} {{ outline: 2px solid currentColor; outline-offset: 2px; }}\n",
765− html_escape(name),
934+ OWN_ELEMENTS, focusable
766− html_escape(content)
935+ )
768− } else {
936+ } else {
769− m.push_str(&format!(
937+ format!(
770− "<meta name=\"{}\" content=\"{}\">",
938+ "{}{}{{outline:2px solid currentColor;outline-offset:2px}}",
771− html_escape(name),
939+ OWN_ELEMENTS, focusable
772− html_escape(content)
940+ )
779− // Build OG meta tags
780− let og_html = if doc.og_tags.is_empty() {
783− let mut o = String::new();
784− for (property, content) in &doc.og_tags {
786− o.push_str(&format!(
787− "<meta property=\"og:{}\" content=\"{}\">\n",
788− html_escape(property),
789− html_escape(content)
792− o.push_str(&format!(
793− "<meta property=\"og:{}\" content=\"{}\">",
794− html_escape(property),
795− html_escape(content)
802− // Build head blocks string
803− let head_html = if doc.head_blocks.is_empty() {
804 String::new()
943 String::new()
806− let mut h = String::new();
807− for block in &doc.head_blocks {
816− let lang_attr = match &doc.lang {
817− Some(lang) => format!(" lang=\"{}\"", html_escape(lang)),
818− None => String::new(),
945+ let reset_css = reset_css(dev, true, &focus_visible_css);
946+ classes.extend(styles.classes());
821− let favicon_html = match &doc.favicon {
948+ format!(
822− Some(path) => {
949+ "<!DOCTYPE html>{nl}<html{root_attrs}>{nl}<head>{nl}<meta charset=\"utf-8\">{nl}\
823− // Try to read and inline the favicon
950+ {meta_html}<style>{nl}{reset_css}{element_css}</style>{nl}</head>{nl}\
824− if let Ok(data) = std::fs::read(path) {
951+ <body{body_attrs}>{nl}{body}</body>{nl}</html>{nl}",
825− let mime = if path.ends_with(".ico") {
952+ )
827− } else if path.ends_with(".png") {
829− } else if path.ends_with(".svg") {
834− let b64 = base64_encode(&data);
837− "<link rel=\"icon\" href=\"data:{};base64,{}\">\n",
841− format!("<link rel=\"icon\" href=\"data:{};base64,{}\">", mime, b64)
844− // Fall back to href
846− format!("<link rel=\"icon\" href=\"{}\">\n", html_escape(path))
848− format!("<link rel=\"icon\" href=\"{}\">", html_escape(path))
852− None => String::new(),
856− let canonical_html = match &doc.canonical {
859− format!("<link rel=\"canonical\" href=\"{}\">\n", html_escape(url))
861− format!("<link rel=\"canonical\" href=\"{}\">", html_escape(url))
864− None => String::new(),
868− let base_html = match &doc.base_url {
871− format!("<base href=\"{}\">\n", html_escape(url))
873− format!("<base href=\"{}\">", html_escape(url))
876− None => String::new(),
880− let json_ld_html: String = doc
886− "<script type=\"application/ld+json\">\n{}\n</script>\n",
890− format!("<script type=\"application/ld+json\">{}</script>", block)
896− let manifest_html = if let Some(ref manifest) = doc.manifest {
897− let mut json = String::from("{");
898− json.push_str(&format!("\"name\":{},", json_str(&manifest.name)));
899− if let Some(ref short) = manifest.short_name {
900− json.push_str(&format!("\"short_name\":{},", json_str(short)));
902− json.push_str(&format!("\"start_url\":{},", json_str(&manifest.start_url)));
903− json.push_str(&format!("\"display\":{}", json_str(&manifest.display)));
904− if let Some(ref bg) = manifest.background_color {
905− json.push_str(&format!(",\"background_color\":{}", json_str(bg)));
907− if let Some(ref tc) = manifest.theme_color {
908− json.push_str(&format!(",\"theme_color\":{}", json_str(tc)));
910− if let Some(ref desc) = manifest.description {
911− json.push_str(&format!(",\"description\":{}", json_str(desc)));
913− if !manifest.icons.is_empty() {
914− json.push_str(",\"icons\":[");
915− for (i, (src, sizes)) in manifest.icons.iter().enumerate() {
919− json.push_str(&format!(
920− "{{\"src\":{},\"sizes\":{},\"type\":\"image/png\"}}",
929− // Inline the manifest as a data URI
930− let encoded = base64_encode(json.as_bytes());
933− "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">\n",
938− "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">",
946− // Preload hints (auto-detect fonts from @font-face)
947− let mut preload_html = String::new();
948− for (_, url) in &doc.font_faces {
950− preload_html.push_str(&format!(
951− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>\n",
955− preload_html.push_str(&format!(
956− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>",
961− // Explicit preload hints from the document
962− for hint in &doc.preload_hints {
964− preload_html.push_str(&format!(
965− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>\n",
966− html_escape(&hint.href),
968− if hint.crossorigin { " crossorigin" } else { "" }
971− preload_html.push_str(&format!(
972− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>",
973− html_escape(&hint.href),
975− if hint.crossorigin { " crossorigin" } else { "" }
980− // Auto theme-color meta from @theme primary token
981− let theme_color_html = doc
984− .find(|(name, _)| name == "primary" || name == "theme-color")
988− "<meta name=\"theme-color\" content=\"{}\">\n",
993− "<meta name=\"theme-color\" content=\"{}\">",
998− .unwrap_or_default();
1000− // Focus-visible CSS for interactive elements (accessibility)
1001− let focus_visible_css = if ctx.has_interactive {
1003− "a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }\n"
1005− "a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid currentColor;outline-offset:2px}"
1011− // Skip-to-content CSS (visually hidden but accessible)
1012− let skip_link_css = if has_main {
1014− ".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"
1016− ".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}"
1022− let reset_css = reset_css(dev, focus_visible_css, skip_link_css);
1024− match &doc.page_title {
1032−<meta charset=\"utf-8\">
1033−<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
1034−<title>{title}</title>
1035−{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}\
1037−{reset_css}{element_css}\
1045− title = html_escape(title),
1046− lang_attr = lang_attr,
1047− theme_color_html = theme_color_html,
1048− base_html = base_html,
1049− canonical_html = canonical_html,
1050− manifest_html = manifest_html,
1051− preload_html = preload_html,
1052− dns_prefetch_html = dns_prefetch_html,
1053− meta_html = meta_html,
1054− favicon_html = favicon_html,
1055− json_ld_html = json_ld_html,
1056− head_html = head_html,
1058− reset_css = reset_css,
1059− element_css = element_css,
1064− "<!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>{reset_css}{element_css}</style></head><body>{body}</body></html>",
1065− title = html_escape(title),
1066− lang_attr = lang_attr,
1067− theme_color_html = theme_color_html,
1068− base_html = base_html,
1069− canonical_html = canonical_html,
1070− manifest_html = manifest_html,
1071− preload_html = preload_html,
1072− dns_prefetch_html = dns_prefetch_html,
1073− meta_html = meta_html,
1075− favicon_html = favicon_html,
1076− json_ld_html = json_ld_html,
1077− head_html = head_html,
1078− reset_css = reset_css,
1079− element_css = element_css,
1085− if element_css.is_empty() {
1088− format!("<style>\n{}</style>\n{}", element_css, body)
1090− format!("<style>{}</style>{}", element_css, body)
1096−/// Encode `s` as a JSON string literal (with surrounding quotes).
1097−pub(crate) fn json_str(s: &str) -> String {
1098− let mut out = String::with_capacity(s.len() + 2);
1100− for c in s.chars() {
1102− '"' => out.push_str("\\\""),
1103− '\\' => out.push_str("\\\\"),
1104− '\n' => out.push_str("\\n"),
1105− '\r' => out.push_str("\\r"),
1106− '\t' => out.push_str("\\t"),
1107− c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1115/// Assemble every CSS block the document needs (font faces, custom
955/// Assemble every CSS block the document needs (font faces, custom
1116/// properties, generated class rules, keyframes, and user CSS). Shared by
956/// properties, generated class rules, keyframes, and user CSS). Shared by
@@ -1118,63 +958,16 @@ pub(crate) fn json_str(s: &str) -> String {
1118fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> String {
958fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> String {
1119 let mut element_css = String::new();
959 let mut element_css = String::new();
1121− // @font-face rules, in declaration order
1122− for (name, url) in &doc.font_faces {
1123− let format_hint = if url.ends_with(".woff2") {
1125− } else if url.ends_with(".woff") {
1127− } else if url.ends_with(".ttf") {
1128− " format('truetype')"
1129− } else if url.ends_with(".otf") {
1130− " format('opentype')"
1135− element_css.push_str(&format!(
1136− "@font-face {{\n font-family: '{}';\n src: url('{}'){};\n font-display: swap;\n}}\n",
1137− name, url, format_hint
1140− element_css.push_str(&format!(
1141− "@font-face{{font-family:'{}';src:url('{}'){};font-display:swap}}",
1142− name, url, format_hint
1147− // Collect all CSS custom properties (explicit `@let --name` / `@theme`
961+ // Collect the CSS custom properties declared with `@let --name` so they
1148− // tokens, plus any auto-extracted repeats) so they can be emitted in a
1149− // single `:root` block below.
962+ // can be emitted in a single `:root` block below.
1150 let mut root_vars: Vec<(String, String)> = Vec::new();
963 let mut root_vars: Vec<(String, String)> = Vec::new();
1151 for (name, value) in &doc.css_vars {
964 for (name, value) in &doc.css_vars {
1152 root_vars.push((name.clone(), value.clone()));
965 root_vars.push((name.clone(), value.clone()));
1154− for (name, value) in &doc.theme_tokens {
1155− let css_name = format!("--{}", name);
1156− if !root_vars.iter().any(|(n, _)| *n == css_name) {
1157− root_vars.push((css_name, value.clone()));
1161− // Generated rules always go in `@layer htmlang`, so unlayered user CSS
968+ // Generated rules always go in htmlang's layers, so unlayered user CSS
1162 // (`@style`, `@raw`) overrides them regardless of specificity.
969 // (`@style`, `@raw`) overrides them regardless of specificity.
1163− let styles_css = styles.to_css_formatted(dev);
970+ let styles_css = styles.to_css_formatted(dev, &doc.scoped_css);
1164− // Fold literal values declared via `@theme` / `@let --name` back into
1165− // `var(--name)` references so the generated CSS actually uses the
1166− // custom properties emitted in `:root`.
1167− let styles_css = substitute_css_vars(&styles_css, &root_vars);
1168− // Further compress the CSS by auto-extracting any remaining literal
1169− // values that appear often enough for `var(--hN)` references to come out
1170− // shorter overall. Disabled in dev mode to keep the CSS readable.
1171− let styles_css = if dev {
1174− let (new_css, auto_vars) = auto_extract_repeats(&styles_css, &root_vars);
1175− root_vars.extend(auto_vars);
1179 // Emit the :root block first so the cascade picks up the custom
972 // Emit the :root block first so the cascade picks up the custom
1180 // properties before the class rules consume them.
973 // properties before the class rules consume them.
@@ -1199,71 +992,121 @@ fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> Stri
1200 element_css.push_str(&styles_css);
993 element_css.push_str(&styles_css);
1203− for (name, kf_body) in &doc.keyframes {
1205− element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1207− element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1211− // Keyframes for the standard library's `$skeleton` bundle, when used
1212− if element_css.contains("hl-skeleton") {
1214− element_css.push_str("@keyframes hl-skeleton {\n 0% { background-position: 200% 0; }\n 100% { background-position: -200% 0; }\n}\n");
1216− element_css.push_str("@keyframes hl-skeleton{0%{background-position:200% 0}100%{background-position:-200% 0}}");
1220 // @style blocks (custom CSS)
995 // @style blocks (custom CSS)
1221 for block in &doc.custom_css {
996 for block in &doc.custom_css {
1222 if dev {
997 if dev {
1223 element_css.push_str(block);
998 element_css.push_str(block);
1224 element_css.push('\n');
999 element_css.push('\n');
1225 } else {
1000 } else {
1226− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1227− element_css.push_str(&minified);
1001+ element_css.push_str(&compact_css(block));
1231 element_css
1005 element_css
1008+/// An `@style` body on one line: each line trimmed, and the lines joined with
1009+/// a space, so a value that goes on over two lines (`margin: 0` then `auto;`)
1010+/// keeps its words apart.
1011+fn compact_css(block: &str) -> String {
1015+ .filter(|l| !l.is_empty())
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"];
1234/// Built-in reset rules, in a layer before `htmlang`: unlayered CSS beats
1036/// Built-in reset rules, in a layer before `htmlang`: unlayered CSS beats
1235−/// every layer, so an unlayered `a{color:inherit}` would override
1037+/// every layer, so an unlayered rule here would override the generated
1236−/// `@link [color red]`.
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`.
1237−fn reset_css(dev: bool, focus_visible_css: &str, skip_link_css: &str) -> String {
1044+fn reset_css(dev: bool, page: bool, focus_visible_css: &str) -> String {
1238− let base = if dev {
1045+ let own = OWN_ELEMENTS;
1239− "*, *::before, *::after { box-sizing: border-box; }\nbody { margin: 0; font-family: system-ui, -apple-system, sans-serif; }\nimg { display: block; }\na { text-decoration: none; color: inherit; }\n"
1046+ let mut rules = Vec::new();
1048+ rules.push(if dev {
1049+ "*, *::before, *::after { box-sizing: border-box; }".to_string()
1051+ "*,*::before,*::after{box-sizing:border-box}".to_string()
1053+ rules.push(if dev {
1054+ "body { margin: 0; font-family: system-ui, -apple-system, sans-serif; display: flex; flex-direction: column; min-height: 100dvh; }".to_string()
1056+ "body{margin:0;font-family:system-ui,-apple-system,sans-serif;display:flex;flex-direction:column;min-height:100dvh}".to_string()
1240 } else {
1058 } else {
1241− "*,*::before,*::after{box-sizing:border-box}body{margin:0;font-family:system-ui,-apple-system,sans-serif}img{display:block}a{text-decoration:none;color:inherit}"
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}}")
1065+ let hidden = "[hidden]:not([hidden=\"until-found\"]),dialog:not([open]):not(:popover-open),\
1066+ [popover]:not(:popover-open):not(dialog[open])";
1067+ rules.push(if dev {
1068+ format!("{own}:where({hidden}) {{ display: none !important; }}")
1070+ format!("{own}:where({hidden}){{display:none!important}}")
1072+ let mut rules = rules.join(if dev { "\n" } else { "" });
1243− let rules = format!("{}{}{}", base, focus_visible_css, skip_link_css);
1076+ rules.push_str(focus_visible_css);
1244 if dev {
1077 if dev {
1245− format!("@layer hl-reset, htmlang;\n@layer hl-reset {{\n{}}}\n", rules)
1079+ "@layer {};\n@layer hl-reset {{\n{}}}\n",
1246 } else {
1083 } else {
1247− format!("@layer hl-reset,htmlang;@layer hl-reset{{{}}}", rules)
1084+ format!("@layer {};@layer hl-reset{{{}}}", LAYERS.join(","), rules)
1251/// 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.
1252−fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1089+fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
1253 let mut styles = StyleCollector::new();
1090 let mut styles = StyleCollector::new();
1254 let mut ctx = GenContext {
1091 let mut ctx = GenContext {
1256 depth: 0,
1093 depth: 0,
1258 has_interactive: false,
1094 has_interactive: false,
1096+ flow: Flow::default(),
1260 let mut body = String::new();
1099 let mut body = String::new();
1262− for node in &doc.nodes {
1263− generate_node(node, None, &mut body, &mut styles, &mut ctx);
1101+ generate_children(&doc.nodes, None, &mut body, &mut styles, &mut ctx);
1266− let element_css = build_element_css(doc, &styles, dev);
1103+ let mut element_css = build_element_css(doc, &styles, dev);
1104+ // htmlang's own elements get the reset's rules for elements (which
1105+ // also puts htmlang's layers in order)
1106+ if !styles.entries.is_empty() || !doc.scoped_css.is_empty() {
1107+ element_css.insert_str(0, &reset_css(dev, false, ""));
1109+ classes.extend(styles.classes());
1268 if element_css.is_empty() {
1111 if element_css.is_empty() {
@@ -1278,22 +1121,20 @@ fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1278// Node generation
1121// Node generation
1279// ---------------------------------------------------------------------------
1122// ---------------------------------------------------------------------------
1124+/// Write `node`, which is inside an element with the layout `parent`
1125+/// (`None` at the top of the page).
1281fn generate_node(
1126fn generate_node(
1282 node: &Node,
1127 node: &Node,
1283− parent_kind: Option<&ElementKind>,
1128+ parent: Option<Layout>,
1284 out: &mut String,
1129 out: &mut String,
1285 styles: &mut StyleCollector,
1130 styles: &mut StyleCollector,
1286 ctx: &mut GenContext,
1131 ctx: &mut GenContext,
1288 match node {
1133 match node {
1289− Node::Element(elem) => generate_element(elem, parent_kind, out, styles, ctx),
1134+ Node::Element(elem) => generate_element(elem, parent, out, styles, ctx),
1290 Node::Text(segments) => {
1135 Node::Text(segments) => {
1291− let needs_wrap = matches!(
1136+ // In a row, column or grid each line of text is a child
1292− parent_kind,
1137+ let needs_wrap = parent.is_some_and(Layout::is_container);
1293− Some(ElementKind::Row | ElementKind::Column | ElementKind::El)
1295− .and_then(ElementKind::spec)
1296− .is_some_and(|spec| spec.wraps_text);
1297 if needs_wrap {
1138 if needs_wrap {
1298 out.push_str(&ctx.indent());
1139 out.push_str(&ctx.indent());
1299 out.push_str("<span>");
1140 out.push_str("<span>");
@@ -1312,73 +1153,156 @@ fn generate_node(
1156+/// What goes between two things written one after the other in an element
1157+/// with this layout (`None`: the top of the page): text flows, so its lines
1158+/// and children are joined with a space; in HTML's own layout, and at the
1159+/// top of the page, two lines of text are separated by a line break (a
1160+/// space, except where whitespace is kept, as in `@pre`).
1161+fn separator(layout: Option<Layout>, previous_is_text: bool, next: &Node) -> Option<char> {
1163+ Some(Layout::Text) => Some(' '),
1164+ Some(Layout::Native) | None if previous_is_text && matches!(next, Node::Text(_)) => {
1316−/// Emit the argument of an element whose argument is an HTML attribute
1171+/// Write the children of an element (or of a `@fragment`, which has no
1317−/// (`@iframe URL` → `src="URL"`, `@form /submit` → `action="/submit"`).
1172+/// element of its own) laid out as `layout` (`None`: the top of the page).
1173+/// The first line of an element's text is its first child.
1174+fn generate_children(
1176+ layout: Option<Layout>,
1178+ styles: &mut StyleCollector,
1179+ ctx: &mut GenContext,
1181+ generate_run(children, layout, &mut None, out, styles, ctx);
1184+/// [`generate_children`], with `previous` saying whether what was written
1185+/// last was a line of text (`None`: nothing yet). A `@fragment`'s children
1186+/// are written as if they stood in its place, so its lines are separated
1187+/// from the lines around it like any other lines.
1190+ layout: Option<Layout>,
1191+ previous: &mut Option<bool>,
1318−fn emit_argument_attr(out: &mut String, elem: &Element) {
1192+ out: &mut String,
1319− if let Some(TagSpec {
1193+ styles: &mut StyleCollector,
1320− arg: TagArg::Attr(attr),
1194+ ctx: &mut GenContext,
1196+ for child in children {
1197+ if let Node::Element(elem) = child
1322− }) = elem.kind.spec()
1198+ && elem.kind == ElementKind::Fragment
1323− && let Some(value) = &elem.argument
1199+ {
1200+ generate_run(&elem.children, layout, previous, out, styles, ctx);
1203+ let start = out.len();
1204+ if let Some(previous_is_text) = *previous
1205+ && let Some(sep) = separator(layout, previous_is_text, child)
1325− out.push(' ');
1207+ out.push(sep);
1326− out.push_str(attr);
1208+ }
1327− out.push_str("=\"");
1209+ let body = out.len();
1328− out.push_str(&html_escape(value));
1210+ generate_node(child, layout, out, styles, ctx);
1329− 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))
1333/// Emit HTML attributes: `key=value` ones (except `id` / `class`, which
1259/// Emit HTML attributes: `key=value` ones (except `id` / `class`, which
1334−/// are emitted with the generated class) and bare booleans like `required`.
1260+/// are emitted with the generated class) and flags like `required`.
1335fn emit_html_attrs(out: &mut String, attrs: &[Attribute]) {
1261fn emit_html_attrs(out: &mut String, attrs: &[Attribute]) {
1336− for attr in attrs {
1262+ for attr in html_attrs(attrs) {
1337 let key = attr.key.as_str();
1263 let key = attr.key.as_str();
1338− if attr.html && key != "id" && key != "class" {
1264+ if key != "id" && key != "class" {
1339− out.push(' ');
1265+ push_html_attr(out, attr);
1341− out.push_str("=\"");
1342− out.push_str(&html_escape(strip_string_quotes(
1343− attr.value.as_deref().unwrap_or(""),
1346− } else if !attr.html
1347− && attr.value.is_none()
1348− && crate::vocab::BOOLEAN_HTML_ATTRS.contains(&key)
1356−/// If the value is wrapped in a single pair of matching quotes (e.g.
1270+/// The HTML attributes of `attrs`, `key=value` ones and flags, each name
1357−/// `"Avatar"`), return the inner content. Quotes act as source-level
1271+/// once: the later one wins, as a style does. (Of two attributes with one
1358−/// delimiters in the `.hl` syntax and shouldn't leak into HTML attribute
1272+/// name, the browser keeps the first, so a bundle's attribute or a
1359−/// values. Multi-quoted values like `"h h" "s m"` are left unchanged —
1273+/// function's own would win over one written after it.)
1360−/// those are real string tokens (used e.g. by CSS `grid-template-areas`).
1274+fn html_attrs(attrs: &[Attribute]) -> impl Iterator<Item = &Attribute> {
1361−fn strip_string_quotes(val: &str) -> &str {
1275+ let is_html =
1362− let bytes = val.as_bytes();
1276+ |a: &Attribute| a.html || (a.value.is_none() && crate::vocab::is_html_flag(&a.key));
1363− if bytes.len() < 2 {
1277+ attrs.iter().enumerate().filter_map(move |(i, attr)| {
1364− return val;
1278+ let later = attrs[i + 1..]
1366− let first = bytes[0];
1280+ .any(|other| is_html(other) && other.key == attr.key);
1367− let last = bytes[bytes.len() - 1];
1281+ (is_html(attr) && !later).then_some(attr)
1368− if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
1282+ })
1369− let inner = &val[1..val.len() - 1];
1283+}
1370− if !inner.as_bytes().contains(&first) {
1284+
1371− return inner;
1285+/// ` key="value"`, or ` key` for a flag.
1372− }
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("")));
1377// True if any direct child is `@in-front` or `@behind`. Such children render
1297// True if any direct child is `@in-front` or `@behind`. Such children render
1378// as absolutely positioned overlays, so the parent automatically becomes a
1298// as absolutely positioned overlays, so the parent automatically becomes a
1379// positioning context (position:relative + isolation:isolate).
1299// positioning context (position:relative + isolation:isolate).
1380fn has_overlay_children(elem: &Element) -> bool {
1300fn has_overlay_children(elem: &Element) -> bool {
1301+ holds_overlays(&elem.children)
1304+fn holds_overlays(children: &[Node]) -> bool {
1381− elem.children.iter().any(|child| {
1305+ children.iter().any(|child| {
1382 matches!(
1306 matches!(
1384 Node::Element(e) if e.kind.is_tag("in-front") || e.kind.is_tag("behind")
1308 Node::Element(e) if e.kind.is_tag("in-front") || e.kind.is_tag("behind")
@@ -1388,48 +1312,32 @@ fn has_overlay_children(elem: &Element) -> bool {
1389fn generate_element(
1313fn generate_element(
1390 elem: &Element,
1314 elem: &Element,
1391− parent_kind: Option<&ElementKind>,
1315+ parent: Option<Layout>,
1392 out: &mut String,
1316 out: &mut String,
1393 styles: &mut StyleCollector,
1317 styles: &mut StyleCollector,
1394 ctx: &mut GenContext,
1318 ctx: &mut GenContext,
1396 // Self-closing elements
1320 // Self-closing elements
1397− if elem.kind == ElementKind::Image || elem.kind.spec().is_some_and(|spec| spec.void) {
1321+ if elem.kind.layout() == Layout::Void {
1398− generate_self_closing(elem, parent_kind, out, styles, ctx);
1322+ generate_self_closing(elem, parent, out, styles, ctx);
1401− // @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+ // escaping; it isn't shown, so it has no class (its styles are an error)
1402− if elem.kind == ElementKind::Script {
1327+ if elem.kind.is_verbatim() {
1328+ let tag = elem.kind.spec().map_or("script", |spec| spec.html);
1403 out.push_str(&ctx.indent());
1329 out.push_str(&ctx.indent());
1404− out.push_str("<script");
1330+ out.push('<');
1405− // Pass through src, type, defer, async, etc.
1331+ out.push_str(tag);
1406− for attr in &elem.attrs {
1332+ emit_argument_attr(out, elem, false);
1407− let key = attr.key.as_str();
1333+ let (id, class) = extract_id_class(&elem.attrs);
1408− if matches!(
1334+ for (key, value) in [("id", id), ("class", class)] {
1419− if let Some(val) = &attr.value {
1335+ if let Some(value) = value {
1421− out.push_str(key);
1336+ out.push_str(&format!(" {}=\"{}\"", key, html_escape(&value)));
1422− out.push_str("=\"");
1423− out.push_str(&html_escape(val));
1339+ emit_html_attrs(out, &elem.attrs);
1431 out.push('>');
1340 out.push('>');
1432− // Children are raw JS code, not HTML
1433 for child in &elem.children {
1341 for child in &elem.children {
1434 match child {
1342 match child {
1435 Node::Text(segments) => {
1343 Node::Text(segments) => {
@@ -1443,7 +1351,9 @@ fn generate_element(
1446− out.push_str("</script>");
1354+ out.push_str("</");
1447 out.push_str(ctx.nl());
1357 out.push_str(ctx.nl());
@@ -1454,26 +1364,26 @@ fn generate_element(
1456 if elem.kind == ElementKind::Fragment {
1366 if elem.kind == ElementKind::Fragment {
1457− // Render children without a wrapper element
1367+ // Render children without a wrapper element, as if they were
1458− for child in &elem.children {
1368+ // written where the fragment is
1459− generate_node(child, parent_kind, out, styles, ctx);
1369+ generate_children(&elem.children, parent, out, styles, ctx);
1373+ let mut own = Flow::of(elem);
1464 let tag = match &elem.kind {
1374 let tag = match &elem.kind {
1465− ElementKind::Row | ElementKind::Column | ElementKind::El => "div",
1375+ ElementKind::Row | ElementKind::El => "div",
1466 ElementKind::Text => "span",
1376 ElementKind::Text => "span",
1467 ElementKind::Paragraph => "p",
1377 ElementKind::Paragraph => "p",
1468 ElementKind::Link => "a",
1378 ElementKind::Link => "a",
1469− ElementKind::Tag(spec)
1470− if spec.name == "list" && elem.attrs.iter().any(|a| a.key == "ordered") =>
1474 ElementKind::Tag(spec) => spec.html,
1379 ElementKind::Tag(spec) => spec.html,
1475 _ => "",
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 };
1477 let kind_label = elem.kind.name();
1387 let kind_label = elem.kind.name();
1479 // Track interactive elements for focus-visible CSS
1389 // Track interactive elements for focus-visible CSS
@@ -1484,14 +1394,8 @@ fn generate_element(
1486 // Compute CSS for each state and get a class name
1396 // Compute CSS for each state and get a class name
1487− let overlay_children = has_overlay_children(elem);
1397+ let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
1488− let gen_class = compute_class(
1398+ own.class = gen_class.clone();
1495 let (id, user_class) = extract_id_class(&elem.attrs);
1399 let (id, user_class) = extract_id_class(&elem.attrs);
1497 if ctx.dev && elem.line_num > 0 {
1401 if ctx.dev && elem.line_num > 0 {
@@ -1505,32 +1409,7 @@ fn generate_element(
1505 out.push('<');
1409 out.push('<');
1506 out.push_str(tag);
1410 out.push_str(tag);
1508− // @main gets id="hl-main" for skip-to-content link (unless user set an id)
1509− if elem.kind.is_tag("main") && id.is_none() {
1510− out.push_str(" id=\"hl-main\"");
1513− if elem.kind == ElementKind::Link
1514− && let Some(url) = &elem.argument
1516− out.push_str(" href=\"");
1517− out.push_str(&html_escape(url));
1519− // Auto rel="noopener noreferrer" and target="_blank" for external links
1520− let is_external = url.starts_with("http://") || url.starts_with("https://");
1522− let has_rel = elem.attrs.iter().any(|a| a.key == "rel");
1523− let has_target = elem.attrs.iter().any(|a| a.key == "target");
1525− out.push_str(" rel=\"noopener noreferrer\"");
1528− out.push_str(" target=\"_blank\"");
1533− emit_argument_attr(out, elem);
1412+ emit_argument_attr(out, elem, ctx.in_picture);
1535 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1414 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
@@ -1551,28 +1430,27 @@ fn generate_element(
1553 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");
1554 out.push_str(ctx.nl());
1438 out.push_str(ctx.nl());
1556− // Inline text argument
1440+ let layout = elem.kind.layout();
1557− if renders_argument_as_text(&elem.kind)
1558− && let Some(text) = &elem.argument
1560− out.push_str(&html_escape(text));
1564 ctx.depth += 1;
1441 ctx.depth += 1;
1565− let is_paragraph = elem.kind == ElementKind::Paragraph
1442+ let outer_in_text = ctx.in_text;
1566− || elem.kind.spec().is_some_and(|spec| spec.inline);
1443+ ctx.in_text = in_text || layout == Layout::Text;
1567− for (i, child) in elem.children.iter().enumerate() {
1444+ let outer_flow = std::mem::replace(&mut ctx.flow, own);
1568− generate_node(child, Some(&elem.kind), out, styles, ctx);
1445+ let outer_picture = std::mem::replace(&mut ctx.in_picture, elem.kind.is_tag("picture"));
1569− if is_paragraph && i < elem.children.len() - 1 {
1446+ generate_children(&elem.children, Some(layout), out, styles, ctx);
1570− out.push(' ');
1447+ ctx.in_picture = outer_picture;
1571− }
1448+ ctx.flow = outer_flow;
1572− }
1449+ ctx.in_text = outer_in_text;
1573 ctx.depth -= 1;
1450 ctx.depth -= 1;
1575 out.push_str(&ctx.indent());
1452 out.push_str(&ctx.indent());
1453+ ctx.dev = outer_dev;
1576 out.push_str("</");
1454 out.push_str("</");
1577 out.push_str(tag);
1455 out.push_str(tag);
1578 out.push('>');
1456 out.push('>');
@@ -1581,12 +1459,12 @@ fn generate_element(
1582fn generate_self_closing(
1460fn generate_self_closing(
1583 elem: &Element,
1461 elem: &Element,
1584− parent_kind: Option<&ElementKind>,
1462+ parent: Option<Layout>,
1585 out: &mut String,
1463 out: &mut String,
1586 styles: &mut StyleCollector,
1464 styles: &mut StyleCollector,
1587 ctx: &mut GenContext,
1465 ctx: &mut GenContext,
1589− let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles, false);
1467+ let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
1590 let (id, user_class) = extract_id_class(&elem.attrs);
1468 let (id, user_class) = extract_id_class(&elem.attrs);
1592 let (tag, kind_label) = match &elem.kind {
1470 let (tag, kind_label) = match &elem.kind {
@@ -1605,44 +1483,7 @@ fn generate_self_closing(
1605 out.push_str(&ctx.indent());
1483 out.push_str(&ctx.indent());
1606 out.push('<');
1484 out.push('<');
1607 out.push_str(tag);
1485 out.push_str(tag);
1608− emit_argument_attr(out, elem);
1486+ emit_argument_attr(out, elem, ctx.in_picture);
1610− // Image src (with optional non-SVG base64 inlining)
1611− if elem.kind == ElementKind::Image {
1612− let src = elem.argument.as_deref().unwrap_or("");
1613− let is_inline = elem.attrs.iter().any(|a| a.key == "inline");
1614− if is_inline && !src.is_empty() && !src.ends_with(".svg") {
1615− let mime = if src.ends_with(".png") {
1617− } else if src.ends_with(".jpg") || src.ends_with(".jpeg") {
1619− } else if src.ends_with(".gif") {
1621− } else if src.ends_with(".webp") {
1623− } else if src.ends_with(".avif") {
1626− "application/octet-stream"
1628− if let Ok(data) = std::fs::read(src) {
1629− let b64 = base64_encode(&data);
1630− out.push_str(" src=\"data:");
1631− out.push_str(mime);
1632− out.push_str(";base64,");
1633− out.push_str(&b64);
1636− out.push_str(" src=\"");
1637− out.push_str(&html_escape(src));
1641− out.push_str(" src=\"");
1642− out.push_str(&html_escape(src));
1647 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());
@@ -1662,93 +1503,6 @@ fn generate_self_closing(
1665− // Image optimization: auto-add loading="lazy" and decoding="async"
1666− if elem.kind == ElementKind::Image {
1667− // SVG inlining: @image [inline] logo.svg
1668− if elem.attrs.iter().any(|a| a.key == "inline")
1669− && let Some(src) = &elem.argument
1670− && src.ends_with(".svg")
1671− && let Ok(svg_content) = std::fs::read_to_string(src)
1673− // Close the tag we opened, then emit inline SVG instead
1674− out.truncate(out.rfind('<').unwrap_or(0));
1675− out.push_str(&ctx.indent());
1676− out.push_str(svg_content.trim());
1677− out.push_str(ctx.nl());
1680− // Responsive srcset: @image photo.jpg [responsive 400 800 1200]
1681− let responsive_attr = elem.attrs.iter().find(|a| a.key == "responsive");
1682− if let Some(resp) = responsive_attr
1683− && let Some(ref sizes_str) = resp.value
1685− let widths: Vec<&str> = sizes_str.split_whitespace().collect();
1686− if !widths.is_empty() {
1687− let src = elem.argument.as_deref().unwrap_or("");
1688− if !src.is_empty() {
1689− // Generate srcset with width descriptors
1690− // Convention: file-{width}.ext (e.g., photo-400.jpg)
1691− let dot_pos = src.rfind('.').unwrap_or(src.len());
1692− let base = &src[..dot_pos];
1693− let ext = &src[dot_pos..];
1694− let mut srcset_parts = Vec::new();
1696− srcset_parts.push(format!("{}-{}{} {}w", base, w, ext, w));
1698− out.push_str(" srcset=\"");
1699− out.push_str(&srcset_parts.join(", "));
1701− // Generate sizes attribute
1702− let max_width = widths.last().unwrap_or(&"100vw");
1703− out.push_str(&format!(
1704− " sizes=\"(max-width: {}px) 100vw, {}px\"",
1705− max_width, max_width
1711− // Auto image dimensions: read local image file to inject width/height + aspect-ratio
1712− let has_width = elem.attrs.iter().any(|a| a.key == "width");
1713− let has_height = elem.attrs.iter().any(|a| a.key == "height");
1714− if (!has_width || !has_height)
1715− && let Some(ref src) = elem.argument
1716− && !src.starts_with("http://")
1717− && !src.starts_with("https://")
1718− && !src.starts_with("data:")
1719− && let Some((w, h)) = read_image_dimensions(src)
1721− // Intrinsic size attributes only when neither dimension is set in
1722− // CSS; with one CSS dimension, a leftover intrinsic attribute for
1723− // the other would distort the image (200 wide but 1000 tall).
1724− if !has_width && !has_height {
1725− out.push_str(&format!(" width=\"{}\" height=\"{}\"", w, h));
1727− // Auto aspect-ratio to prevent CLS
1728− if !elem.attrs.iter().any(|a| a.key == "aspect-ratio") {
1729− out.push_str(&format!(" style=\"aspect-ratio:{}/{}\"", w, h));
1733− // Smart image loading: first 3 images get fetchpriority="high" (above the fold),
1734− // subsequent images get loading="lazy" + decoding="async"
1735− ctx.image_count += 1;
1736− if ctx.image_count <= 3 {
1737− // Above-the-fold: eager loading with high priority
1738− if !elem.attrs.iter().any(|a| a.key == "fetchpriority") {
1739− out.push_str(" fetchpriority=\"high\"");
1742− // Below-the-fold: lazy loading
1743− if !elem.attrs.iter().any(|a| a.key == "loading") {
1744− out.push_str(" loading=\"lazy\"");
1746− if !elem.attrs.iter().any(|a| a.key == "decoding") {
1747− out.push_str(" decoding=\"async\"");
1752 out.push('>');
1506 out.push('>');
1753 out.push_str(ctx.nl());
1507 out.push_str(ctx.nl());
@@ -1764,7 +1518,10 @@ fn generate_text_segments(
1764 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
1518 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
1765 TextSegment::Inline(elem) => {
1519 TextSegment::Inline(elem) => {
1766 let mut buf = String::new();
1520 let mut buf = String::new();
1521+ // An element inside a line of text is in text
1522+ let outer_flow = std::mem::take(&mut ctx.flow);
1767− generate_element(elem, None, &mut buf, styles, ctx);
1523+ generate_element(elem, Some(Layout::Text), &mut buf, styles, ctx);
1524+ ctx.flow = outer_flow;
1768 out.push_str(buf.trim_end());
1525 out.push_str(buf.trim_end());
@@ -1777,142 +1534,104 @@ fn generate_text_segments(
1778fn compute_class(
1535fn compute_class(
1779 attrs: &[Attribute],
1536 attrs: &[Attribute],
1780− kind: &ElementKind,
1537+ site: &Site,
1781− parent_kind: Option<&ElementKind>,
1782 styles: &mut StyleCollector,
1538 styles: &mut StyleCollector,
1783− has_overlay_children: bool,
1539+ distinct: String,
1784) -> Option<String> {
1540) -> Option<String> {
1785− let base = attrs_to_css(attrs, "", kind, parent_kind, has_overlay_children);
1541+ // Every condition an attribute is under, and none
1786−
1542+ let mut conditions = vec![Condition::default()];
1787− // Collect pseudo-state overrides
1543+ for attr in attrs.iter().filter(|a| !a.html) {
1788− let mut pseudo = Vec::new();
1544+ let (condition, _) = Condition::of(&attr.key);
1789− for &(prefix, selector) in crate::vocab::PSEUDO_PREFIXES {
1545+ if !conditions.contains(&condition) {
1790− let css = attrs_to_css(attrs, prefix, kind, parent_kind, has_overlay_children);
1546+ conditions.push(condition);
1791− if !css.is_empty() {
1792− pseudo.push((selector.to_string(), css));
1796− // Collect nth:EXPR: dynamic pseudo selectors
1797− let mut nth_prefixes: Vec<String> = Vec::new();
1798− for attr in attrs {
1799− if attr.key.starts_with("nth:") {
1800− let rest = &attr.key[4..];
1801− if let Some(colon_pos) = rest.find(':') {
1802− let prefix = format!("nth:{}:", &rest[..colon_pos]);
1803− if !nth_prefixes.contains(&prefix) {
1804− nth_prefixes.push(prefix);
1809− for prefix in &nth_prefixes {
1810− let expr = &prefix[4..prefix.len() - 1];
1811− let selector = format!(":nth-child({})", expr);
1812− let css = attrs_to_css(attrs, prefix, kind, parent_kind, has_overlay_children);
1813− if !css.is_empty() {
1814− pseudo.push((selector, css));
1818− // Collect has(...): dynamic pseudo selectors
1819− let mut has_prefixes: Vec<String> = Vec::new();
1820− for attr in attrs {
1821− if attr.key.starts_with("has(")
1822− && let Some(close) = attr.key.find("):")
1824− let prefix = format!("{}:", &attr.key[..close + 1]);
1825− if !has_prefixes.contains(&prefix) {
1826− has_prefixes.push(prefix);
1830− for prefix in &has_prefixes {
1831− let inner = &prefix[4..prefix.len() - 2]; // extract selector from has(selector):
1832− let selector = format!(":has({})", inner);
1833− let css = attrs_to_css(attrs, prefix, kind, parent_kind, has_overlay_children);
1834− if !css.is_empty() {
1835− pseudo.push((selector, css));
1839− // Collect responsive overrides
1840− let mut responsive = Vec::new();
1841− for &(bp_name, _) in BREAKPOINTS {
1842− let prefix = format!("{}:", bp_name);
1843− let css = attrs_to_css(attrs, &prefix, kind, parent_kind, has_overlay_children);
1844− if !css.is_empty() {
1845− responsive.push((bp_name.to_string(), css));
1849− // Collect container query overrides
1850− let mut container = Vec::new();
1851− for &(bp_name, _) in BREAKPOINTS {
1852− let prefix = format!("cq-{}:", bp_name);
1853− let css = attrs_to_css(attrs, &prefix, kind, parent_kind, has_overlay_children);
1854− if !css.is_empty() {
1855− container.push((bp_name.to_string(), css));
1859− let dark = attrs_to_css(attrs, "dark:", kind, parent_kind, has_overlay_children);
1860− let print = attrs_to_css(attrs, "print:", kind, parent_kind, has_overlay_children);
1861− let motion_safe = attrs_to_css(attrs, "motion-safe:", kind, parent_kind, has_overlay_children);
1862− let motion_reduce =
1863− attrs_to_css(attrs, "motion-reduce:", kind, parent_kind, has_overlay_children);
1864− let landscape = attrs_to_css(attrs, "landscape:", kind, parent_kind, has_overlay_children);
1865− let portrait = attrs_to_css(attrs, "portrait:", kind, parent_kind, has_overlay_children);
1867 // Dedupe: if a property is declared twice within a single rule, keep only
1549 // Dedupe: if a property is declared twice within a single rule, keep only
1868− // the last occurrence (element-kind defaults are written before
1550+ // the last occurrence.
1869− // user attributes, so a user [list-style disc] correctly overrides the
1551+ let rules: Vec<(Condition, String)> = conditions
1870− // default list-style:none, and we don't need to ship both).
1871− let base = dedupe_declarations(&base);
1872− let pseudo: Vec<(String, String)> = pseudo
1873 .into_iter()
1552 .into_iter()
1874− .map(|(sel, css)| (sel, dedupe_declarations(&css)))
1553+ .map(|condition| {
1875− .collect();
1554+ let css = dedupe_declarations(&attrs_to_css(attrs, &condition, site));
1876− let responsive: Vec<(String, String)> = responsive
1555+ (condition, css)
1877− .into_iter()
1556+ })
1878− .map(|(bp, css)| (bp, dedupe_declarations(&css)))
1879 .collect();
1557 .collect();
1880− let dark = dedupe_declarations(&dark);
1558+ // The kind's defaults, less what the element sets itself (a user
1881− let print = dedupe_declarations(&print);
1559+ // `[list-style disc]` wins over the default `list-style:none` anyway,
1882− let motion_safe = dedupe_declarations(&motion_safe);
1560+ // so there is no need to ship both)
1883− let motion_reduce = dedupe_declarations(&motion_reduce);
1561+ let own = rules
1884− let landscape = dedupe_declarations(&landscape);
1562+ .iter()
1885− let portrait = dedupe_declarations(&portrait);
1563+ .find(|(condition, _)| *condition == Condition::default())
1886− let container: Vec<(String, String)> = container
1564+ .map_or("", |(_, css)| css.as_str());
1887− .into_iter()
1565+ let own: Vec<&str> = declarations(own).map(|(name, _)| name).collect();
1888− .map(|(bp, css)| (bp, dedupe_declarations(&css)))
1566+ let defaults: String = declarations(&dedupe_declarations(&default_css(site)))
1567+ .filter(|(name, _)| !own.contains(name))
1568+ .map(|(_, declaration)| declaration)
1889 .collect();
1569 .collect();
1890−
1570+ styles.get_class(defaults, rules, distinct)
1905−/// Dedupe CSS declarations within a single rule body: for any property
1573+/// The defaults of an element's kind where it is: an overlay's positioning
1906−/// declared more than once, keep only the last occurrence. Unparseable
1574+/// context, its layout, and its kind's own CSS (a heading's `margin:0`).
1907−/// segments (no `:`) are preserved as-is. Semicolons inside parentheses are
1575+fn default_css(site: &Site) -> String {
1908−/// treated as part of a value, not as declaration separators.
1576+ let mut css = String::new();
1909−fn dedupe_declarations(css: &str) -> String {
1577+ // Elements with @in-front / @behind children become positioning
1910− if css.is_empty() {
1578+ // contexts
1911− return String::new();
1579+ if site.has_overlay_children {
1580+ css.push_str("position:relative;isolation:isolate;");
1913− // Quick path: no chance of duplicates if there's fewer than 2 declarations.
1582+ if !site.root {
1914− if css.matches(';').count() < 2 {
1583+ css.push_str(layout_css(site.kind.layout(), site.inline));
1915− return css.to_string();
1584+ }
1585+ css.push_str(site.kind.css());
1589+/// The declarations of a rule body, as (property, `property:value;`), for
1590+/// bodies htmlang wrote: every declaration ends in `;`, and a `;` inside
1591+/// quotes or parentheses doesn't end one.
1592+fn declarations(css: &str) -> impl Iterator<Item = (&str, &str)> {
1593+ let mut rest = css;
1594+ std::iter::from_fn(move || {
1595+ if rest.is_empty() {
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 => {
1616+ let (declaration, after) = rest.split_at(end);
1618+ let name = declaration.split(':').next().unwrap_or("").trim();
1619+ Some((name, declaration))
1623+/// Dedupe CSS declarations within a single rule body: for any property
1624+/// declared more than once, keep only the last occurrence. Unparseable
1625+/// segments (no `:`) are preserved as-is. Semicolons inside parentheses or
1626+/// quoted strings are treated as part of a value, not as declaration
1628+fn dedupe_declarations(css: &str) -> String {
1629+ if css.is_empty() {
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();
1918 // Split into (property_name_opt, full_decl_with_semi) preserving whatever
1637 // Split into (property_name_opt, full_decl_with_semi) preserving whatever
@@ -1920,8 +1639,26 @@ fn dedupe_declarations(css: &str) -> String {
1920 let mut decls: Vec<(Option<String>, String)> = Vec::new();
1639 let mut decls: Vec<(Option<String>, String)> = Vec::new();
1921 let mut current = String::new();
1640 let mut current = String::new();
1922 let mut depth: i32 = 0;
1641 let mut depth: i32 = 0;
1642+ // A quoted string's `;` (`content "a;b"`) is text; a backslash escapes
1643+ // the character after it
1644+ let mut quote: Option<char> = None;
1645+ let mut escaped = false;
1923 for ch in css.chars() {
1646 for ch in css.chars() {
1924− if ch == '(' {
1647+ if escaped {
1650+ } else if ch == '\\' {
1653+ } else if let Some(q) = quote {
1658+ } else if ch == '"' || ch == '\'' {
1661+ } else if ch == '(' {
1925 depth += 1;
1662 depth += 1;
1926 current.push(ch);
1663 current.push(ch);
1927 } else if ch == ')' {
1664 } else if ch == ')' {
@@ -2003,579 +1740,553 @@ fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option
2003// Attribute → CSS mapping
1740// Attribute → CSS mapping
2004// ---------------------------------------------------------------------------
1741// ---------------------------------------------------------------------------
2006−/// (htmlang prefix, CSS selector suffix)
1743+/// Where an element is written, which its CSS depends on.
2007−/// `display:flex;flex-direction:column;` — base layout for `@el` and every
1744+struct Site<'a> {
2008−/// semantic wrapper that behaves like a column.
1745+ kind: &'a ElementKind,
2009−const FLEX_COLUMN: &str = "display:flex;flex-direction:column;";
1746+ /// How its parent lays out its children: its `width fill`, `height
2010−
1747+ /// fill` and `shrink` compile against it.
2011−
1748+ parent: &'a Flow,
2012−
1749+ /// It has `@in-front` / `@behind` children.
2014− attrs: &[Attribute],
2015− state_prefix: &str,
2016− kind: &ElementKind,
2017− parent_kind: Option<&ElementKind>,
2018 has_overlay_children: bool,
1750 has_overlay_children: bool,
2019−) -> String {
1751+ /// A row, column or grid inside text, laid out inline.
2020− let mut css = String::new();
1752+ inline: bool,
1753+ /// The page's `<body>`, which the reset already makes a column.
2022− // Base element styles only for the default (non-state) pass
1757+impl Site<'_> {
2023− if state_prefix.is_empty() {
1758+ /// Where an element in a parent with the layout `layout` and the flow
2024− // Elements with @in-front / @behind children become positioning
1759+ /// `parent` is.
2025− // contexts. Pushed before user attrs so an explicit `position` wins
1760+ fn new<'a>(elem: &'a Element, layout: Option<Layout>, parent: &'a Flow) -> Site<'a> {
2026− // via dedupe (only the last declaration of a property is kept).
1761+ Site {
2027− if has_overlay_children {
1762+ kind: &elem.kind,
2028− css.push_str("position:relative;isolation:isolate;");
1763+ parent,
2029− }
1764+ has_overlay_children: has_overlay_children(elem),
2030− match kind {
1765+ inline: layout == Some(Layout::Text) && elem.kind.layout().is_container(),
2031− ElementKind::Row => css.push_str("display:flex;flex-direction:row;"),
1766+ root: false,
2032− ElementKind::Column | ElementKind::El => css.push_str(FLEX_COLUMN),
2033− ElementKind::Paragraph => css.push_str("margin:0;"),
2034− ElementKind::Tag(spec) => css.push_str(spec.css),
2039− for attr in attrs {
1771+// ---------------------------------------------------------------------------
2040− if attr.html {
1772+// Direction: what a child's `fill` and `shrink` compile against
2041− continue;
1773+// ---------------------------------------------------------------------------
2043− // Determine the effective key for this pass
2044− let effective_key = if state_prefix.is_empty() {
2045− if crate::vocab::is_prefixed(&attr.key) {
2050− match attr.key.strip_prefix(state_prefix) {
2056− let val = attr.value.as_deref();
1775+/// The way a flex row or column lays out its children.
1776+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2058− match effective_key {
1782+impl Axis {
2059− // Layout
1783+ /// The direction a `flex-direction` or `flex-flow` value sets, if it
2060− "spacing" | "gap" => {
1784+ /// names one (not `var(--dir)`, which only the browser knows).
2061− if let Some(v) = val {
1785+ fn of_value(value: &str) -> Option<Axis> {
2062− push_css(&mut css, "gap", &css_px(v));
1786+ value.split_whitespace().find_map(|word| match word {
2063− }
1787+ "row" | "row-reverse" => Some(Axis::Row),
2064− }
1788+ "column" | "column-reverse" => Some(Axis::Column),
2065− "padding" => {
1789+ _ => None,
2066− if let Some(v) = val {
1790+ })
2067− push_css(&mut css, "padding", &css_px_multi(v));
1791+ }
2071− if let Some(v) = val {
2072− // Logical property covers both inline sides in one
2073− // declaration; for symmetric values this is visually
2074− // identical to padding-left/right in LTR and RTL.
2075− push_css(&mut css, "padding-inline", &css_px(v));
2079− if let Some(v) = val {
2080− push_css(&mut css, "padding-block", &css_px(v));
2084− if let Some(v) = val {
2085− push_css(&mut css, "padding-top", &css_px(v));
2088− "padding-bottom" => {
2089− if let Some(v) = val {
2090− push_css(&mut css, "padding-bottom", &css_px(v));
2093− "padding-left" => {
2094− if let Some(v) = val {
2095− push_css(&mut css, "padding-left", &css_px(v));
2098− "padding-right" => {
2099− if let Some(v) = val {
2100− push_css(&mut css, "padding-right", &css_px(v));
2104− // Sizing
1794+/// How an element lays out its children, as its CSS sets it: the
2105− "width" => {
1795+/// direction its children's `width`/`height` `fill` and `shrink` compile
2106− if let Some(v) = val {
1796+/// against. That is the direction of `@row` or of a column, or the one its
2107− match v {
1797+/// own `flex-direction` (or `flex-flow`) sets, with or without media or
2108− "fill" => match parent_kind {
1798+/// container prefixes. Like elm-ui's `.r > .wf`, the rules for a direction
2109− Some(ElementKind::Row) => {
1799+/// set under a prefix are keyed on the element's class: `@media (...) {
2110− push_css(&mut css, "flex", "1");
1800+/// :where(.a)>.b {...} }`.
2111− push_css(&mut css, "min-width", "0");
1801+#[derive(Clone, Default)]
2112− }
1802+struct Flow {
2113− _ => push_css(&mut css, "width", "100%"),
1803+ /// Without a prefix; `None` when the element isn't a flex row or column
2114− },
1804+ /// (a grid, text, HTML's own layout, the top of the page)
2115− "shrink" => push_css(&mut css, "flex-shrink", "0"),
1805+ base: Option<Axis>,
2116− _ => push_css(&mut css, "width", &css_px(v)),
1806+ /// The direction under each chain of at-rule prefixes that sets one, in
2117− }
1807+ /// the order their blocks are written
2118− }
1808+ changes: Vec<(Vec<usize>, Axis)>,
2119− }
1809+ /// The element's generated class, which the rules for the changes are
2120− "height" => {
1810+ /// keyed on
2121− if let Some(v) = val {
1811+ class: Option<String>,
2123− "fill" => match parent_kind {
2124− Some(ElementKind::Column) => {
2125− push_css(&mut css, "flex", "1");
2126− push_css(&mut css, "min-height", "0");
2128− _ => push_css(&mut css, "height", "100%"),
2130− "shrink" => push_css(&mut css, "flex-shrink", "0"),
2131− _ => push_css(&mut css, "height", &css_px(v)),
2136− if let Some(v) = val {
2137− push_css(&mut css, "min-width", &css_px(v));
2141− if let Some(v) = val {
2142− push_css(&mut css, "max-width", &css_px(v));
2146− if let Some(v) = val {
2147− push_css(&mut css, "min-height", &css_px(v));
2151− if let Some(v) = val {
2152− push_css(&mut css, "max-height", &css_px(v));
2156− // Alignment
1814+impl Flow {
2157− "center-x" => match parent_kind {
1815+ fn of(elem: &Element) -> Flow {
2158− Some(ElementKind::Column) | Some(ElementKind::El) => {
1816+ let mut base = match elem.kind.layout() {
2159− push_css(&mut css, "align-self", "center");
1817+ Layout::Row => Axis::Row,
2160− }
1818+ Layout::Column => Axis::Column,
2161− _ => {
1819+ _ => return Flow::default(),
2162− push_css(&mut css, "margin-left", "auto");
1820+ };
2163− push_css(&mut css, "margin-right", "auto");
1821+ let mut changes: Vec<(Vec<usize>, Axis)> = Vec::new();
2164− }
1822+ for attr in elem.attrs.iter().filter(|a| !a.html) {
2165− },
1823+ let (condition, name) = Condition::of(&attr.key);
2166− "center-y" => match parent_kind {
1824+ if !matches!(name, "flex-direction" | "flex-flow") || !condition.selector.is_empty() {
2167− Some(ElementKind::Row) => push_css(&mut css, "align-self", "center"),
1825+ continue;
2169− push_css(&mut css, "margin-top", "auto");
2170− push_css(&mut css, "margin-bottom", "auto");
2173− "align-left" => match parent_kind {
2174− Some(ElementKind::Column) | Some(ElementKind::El) => {
2175− push_css(&mut css, "align-self", "flex-start");
2177− _ => push_css(&mut css, "margin-right", "auto"),
2179− "align-right" => match parent_kind {
2180− Some(ElementKind::Column) | Some(ElementKind::El) => {
2181− push_css(&mut css, "align-self", "flex-end");
2183− _ => push_css(&mut css, "margin-left", "auto"),
2185− "align-top" => match parent_kind {
2186− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-start"),
2187− _ => push_css(&mut css, "margin-bottom", "auto"),
2189− "align-bottom" => match parent_kind {
2190− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-end"),
2191− _ => push_css(&mut css, "margin-top", "auto"),
2196− if let Some(v) = val {
2197− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2198− if parts.len() == 2 {
2202− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2208− &format!("{} solid currentColor", css_px(parts[0])),
2213− "border-top" | "border-bottom" | "border-left" | "border-right" => {
2214− if let Some(v) = val {
2215− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2216− if parts.len() == 2 {
2220− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2226− &format!("{} solid currentColor", css_px(parts[0])),
2232− if let Some(v) = val {
2233− push_css(&mut css, "border-radius", &css_px(v));
2236− "bold" => push_css(&mut css, "font-weight", "bold"),
2237− "italic" => push_css(&mut css, "font-style", "italic"),
2238− "underline" => push_css(&mut css, "text-decoration", "underline"),
2240− if let Some(v) = val {
2241− push_css(&mut css, "font-size", &css_px(v));
2244− "font" => {
1827+ let Some(axis) = attr.value.as_deref().and_then(Axis::of_value) else {
2245− if let Some(v) = val {
1828+ continue;
2246− // `font "Inter, sans-serif"` quotes a whole font stack so
1829+ };
2247− // its commas don't split the attribute list.
1830+ if condition.at.is_empty() {
2248− let v = match v.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
1831+ base = axis;
2249− Some(stack) if stack.contains(',') => stack,
1832+ } else {
2250− _ => v,
1833+ // The later one wins, as in the CSS
2251− };
1834+ changes.retain(|(at, _)| *at != condition.at);
2252− push_css(&mut css, "font-family", v);
1835+ changes.push((condition.at, axis));
1838+ changes.sort_by_key(|(at, _)| at_order(at));
2256− // Typography
1846+ /// The direction under the at-rules `at`: the latest one set among
2257− "line-height" => {
1847+ /// the conditions that hold there (`md:` holds at `lg:`), else the one
2258− if let Some(v) = val {
1848+ /// without a prefix.
2259− push_css(&mut css, "line-height", &css_line_height(v));
1849+ fn at(&self, at: &[usize]) -> Option<Axis> {
2260− }
1850+ let base = self.base?;
2261− }
1851+ let here = Condition::at_only(at);
2262− "letter-spacing" => {
1852+ let changed = self
2263− if let Some(v) = val {
1853+ .changes
2264− push_css(&mut css, "letter-spacing", &css_px(v));
1854+ .iter()
2266− }
1856+ .find(|(chain, _)| Condition::at_only(chain).holds_at(&here))
1857+ .map(|&(_, axis)| axis);
1858+ Some(changed.unwrap_or(base))
2268− // Overflow & positioning
1862+/// `width` or `height`.
2269− "top" => {
1863+#[derive(Clone, Copy, PartialEq, Eq)]
2270− if let Some(v) = val {
1864+enum Dim {
2271− push_css(&mut css, "top", &css_px(v));
1865+ Width,
2275− if let Some(v) = val {
2276− push_css(&mut css, "right", &css_px(v));
2280− if let Some(v) = val {
2281− push_css(&mut css, "bottom", &css_px(v));
2285− if let Some(v) = val {
2286− push_css(&mut css, "left", &css_px(v));
2290− // Display & visibility
1869+/// What a `width` or `height` says.
2291− "hidden" => push_css(&mut css, "display", "none"),
1870+#[derive(Clone, Copy, PartialEq, Eq)]
1874+ /// A size of its own (`width 300`)
2293− // Effects
1878+impl Size {
1879+ fn of(value: &str) -> Size {
1880+ match value.trim() {
1881+ "fill" => Size::Fill,
1882+ "shrink" => Size::Shrink,
2295− // Flow
1888+/// The declarations `fill` and `shrink` make in a parent laid out along
2296− "wrap" => push_css(&mut css, "flex-wrap", "wrap"),
1889+/// `axis` (`None`: not a flex row or column). Along the parent's direction,
1890+/// `fill` takes the remaining space and `shrink` keeps the content's size;
1891+/// across it (or outside flex), `fill` is the full size and `shrink` fits
1893+fn sizing(dim: Dim, size: Size, axis: Option<Axis>) -> &'static [(&'static str, &'static str)] {
1894+ match (dim, size, axis) {
1895+ (_, Size::Set, _) => &[],
1896+ (Dim::Width, Size::Fill, Some(Axis::Row)) => &[("flex", "1"), ("min-width", "0")],
1897+ (Dim::Width, Size::Fill, _) => &[("width", "100%")],
1898+ (Dim::Width, Size::Shrink, Some(Axis::Row)) => &[("flex-shrink", "0")],
1899+ (Dim::Width, Size::Shrink, _) => &[("width", "fit-content")],
1900+ (Dim::Height, Size::Fill, Some(Axis::Column)) => &[("flex", "1"), ("min-height", "0")],
1901+ (Dim::Height, Size::Fill, _) => &[("height", "100%")],
1902+ (Dim::Height, Size::Shrink, Some(Axis::Column)) => &[("flex-shrink", "0")],
1903+ (Dim::Height, Size::Shrink, _) => &[("height", "fit-content")],
2298− // Grid
1907+/// Every property `fill` and `shrink` of `dim` can set, with its initial
2299− "grid" => {
1908+/// value (`flex` covers `flex-shrink`).
2300− push_css(&mut css, "display", "grid");
1909+fn sizing_properties(dim: Dim) -> [(&'static str, &'static str); 3] {
2302− "grid-cols" => {
1911+ Dim::Width => [
2303− if let Some(v) = val {
1912+ ("flex", "0 1 auto"),
2304− if let Ok(n) = v.parse::<u32>() {
1913+ ("min-width", "auto"),
2305− push_css(
1914+ ("width", "auto"),
2307− "grid-template-columns",
1916+ Dim::Height => [
2308− &format!("repeat({},1fr)", n),
1917+ ("flex", "0 1 auto"),
2309− );
1918+ ("min-height", "auto"),
2310− } else {
1919+ ("height", "auto"),
2311− push_css(&mut css, "grid-template-columns", v);
1920+ ],
2316− if let Some(v) = val {
2317− if let Ok(n) = v.parse::<u32>() {
2320− "grid-template-rows",
2321− &format!("repeat({},1fr)", n),
2324− push_css(&mut css, "grid-template-rows", v);
2329− if let Some(v) = val {
2330− push_css(&mut css, "grid-column", &format!("span {}", v));
2334− if let Some(v) = val {
2335− push_css(&mut css, "grid-row", &format!("span {}", v));
2339− // CSS containment for rendering performance
1924+/// What an element's attributes under some prefixes say about its size.
2340− "contain" => {
1925+#[derive(Default)]
2341− if let Some(v) = val {
1926+struct Sizes {
2342− push_css(&mut css, "contain", v);
1927+ /// The last `width` and `height`
2343− } else {
1928+ width: Option<Size>,
2344− push_css(&mut css, "contain", "layout style paint");
1929+ height: Option<Size>,
2345− }
1930+ /// A `fill` or `shrink` for the width / height is among them (a later
2346− }
1931+ /// size may replace it)
2347− "content-visibility" => {
1932+ width_word: bool,
2348− if let Some(v) = val {
1933+ height_word: bool,
2349− push_css(&mut css, "content-visibility", v);
1934+ /// It writes `flex`, one of its longhands (`flex-grow`, `flex-shrink`,
2350− } else {
1935+ /// `flex-basis`), `min-width` or `min-height` itself
2351− push_css(&mut css, "content-visibility", "auto");
1936+ flex: bool,
2352− }
1937+ flex_grow: bool,
2353− }
1938+ flex_shrink: bool,
2355− // Outline (like border but doesn't affect layout)
1944+impl Sizes {
2356− "outline" => {
1945+ /// Read the attributes under the conditions that hold wherever `at`
2357− if let Some(v) = val {
1946+ /// does, a later condition over an earlier one.
2358− let parts: Vec<&str> = v.splitn(2, ' ').collect();
1947+ fn of(attrs: &[Attribute], at: &Condition) -> Sizes {
2359− if parts.len() == 2 {
1948+ let mut sizes = Sizes::default();
2360− push_css(
1949+ let mut read: Vec<(Condition, &str, &str)> = Vec::new();
2361− &mut css,
1950+ for attr in attrs.iter().filter(|a| !a.html) {
2362− "outline",
1951+ let (condition, name) = Condition::of(&attr.key);
2363− &format!("{} solid {}", css_px(parts[0]), parts[1]),
1952+ let Some(value) = attr.value.as_deref().filter(|v| !v.trim().is_empty()) else {
2366− push_css(
1955+ if condition.holds_at(at) {
2367− &mut css,
1956+ read.push((condition, name, value));
2369− &format!("{} solid currentColor", css_px(parts[0])),
1958+ }
2370− );
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,
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);
2375− // Logical properties (i18n-aware)
2033+/// The rule that gives an element's `fill` and `shrink`, as its attributes
2376− "padding-inline" => {
2034+/// under the at-rules `at` set them, their meaning in a parent laid out
2377− if let Some(v) = val {
2035+/// along `axis`. Every other property a layout word could have set is put
2378− push_css(&mut css, "padding-inline", &css_px_multi(v));
2036+/// back to its initial value, so the rule is right whichever earlier rule
2379− }
2037+/// it overrides. Properties the element writes itself are left alone.
2380− }
2038+fn sizing_rule(attrs: &[Attribute], at: &[usize], axis: Axis) -> String {
2381− "padding-block" => {
2039+ let sizes = Sizes::of(attrs, &Condition::at_only(at));
2382− if let Some(v) = val {
2040+ let mut sets: Vec<(&str, &str)> = Vec::new();
2383− push_css(&mut css, "padding-block", &css_px_multi(v));
2041+ let mut resets: Vec<(&str, &str)> = Vec::new();
2384− }
2042+ for (dim, size, word) in [
2385− }
2043+ (Dim::Width, sizes.width, sizes.width_word),
2386− "margin-inline" => {
2044+ (Dim::Height, sizes.height, sizes.height_word),
2387− if let Some(v) = val {
2045+ ] {
2388− push_css(&mut css, "margin-inline", &css_px_multi(v));
2046+ if !word {
2391− "margin-block" => {
2049+ if let Some(size) = size {
2392− if let Some(v) = val {
2050+ sets.extend_from_slice(sizing(dim, size, Some(axis)));
2393− push_css(&mut css, "margin-block", &css_px_multi(v));
2051+ }
2394− }
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);
2397− // Logical property start/end variants
2069+/// The rules an element's `fill` and `shrink` need under each chain of
2398− "padding-inline-start"
2070+/// at-rules where the direction of `flow` (its parent's) changes: `(at,
2399− | "padding-inline-end"
2071+/// body)`.
2400− | "padding-block-start"
2072+fn sizing_changes(attrs: &[Attribute], flow: &Flow) -> Vec<(Vec<usize>, String)> {
2401− | "padding-block-end"
2073+ flow.changes
2402− | "margin-inline-start"
2074+ .iter()
2403− | "margin-inline-end"
2075+ .map(|(at, axis)| (at.clone(), sizing_rule(attrs, at, *axis)))
2404− | "margin-block-start"
2076+ .filter(|(_, body)| !body.is_empty())
2405− | "margin-block-end" => {
2077+ .collect()
2406− if let Some(v) = val {
2078+}
2407− push_css(&mut css, effective_key, &css_px(v));
2411− // Logical inset
2080+/// An element's generated class, with the rules keyed on its parent's
2412− "inset-inline" | "inset-block" => {
2081+/// class that its `fill` and `shrink` need where the parent's direction
2413− if let Some(v) = val {
2082+/// changes under a prefix (see [`Flow`]): `:where(.a)>.b`, one class of
2414− push_css(&mut css, effective_key, &css_px_multi(v));
2083+/// specificity like any class rule.
2415− }
2084+fn element_class(elem: &Element, site: &Site, styles: &mut StyleCollector) -> Option<String> {
2416− }
2085+ let as_child = match site.parent.class {
2417− "inset-inline-start" | "inset-inline-end" | "inset-block-start" | "inset-block-end" => {
2086+ Some(_) => sizing_changes(&elem.attrs, site.parent),
2418− if let Some(v) = val {
2087+ None => Vec::new(),
2419− push_css(&mut css, effective_key, &css_px(v));
2088+ };
2420− }
2089+ // Two elements with the same CSS but different rules keyed on them
2421− }
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);
2423− // Logical border
2104+/// The `display` of a layout (nothing for text, native and void elements,
2424− "border-inline"
2105+/// which keep HTML's own).
2425− | "border-block"
2106+fn layout_css(layout: Layout, inline: bool) -> &'static str {
2426− | "border-inline-start"
2107+ match (layout, inline) {
2427− | "border-inline-end"
2108+ (Layout::Column, false) => "display:flex;flex-direction:column;",
2428− | "border-block-start"
2109+ (Layout::Column, true) => "display:inline-flex;flex-direction:column;",
2429− | "border-block-end" => {
2110+ (Layout::Row, false) => "display:flex;flex-direction:row;",
2430− if let Some(v) = val {
2111+ (Layout::Row, true) => "display:inline-flex;flex-direction:row;",
2431− push_css(&mut css, effective_key, v);
2112+ (Layout::Grid, false) => "display:grid;",
2432− }
2113+ (Layout::Grid, true) => "display:inline-grid;",
2435− // Logical border-radius
2118+/// The declarations of the attributes under `condition` (the defaults of
2436− "border-start-start-radius"
2119+/// the element's kind are [`default_css`]'s).
2437− | "border-start-end-radius"
2120+fn attrs_to_css(attrs: &[Attribute], condition: &Condition, site: &Site) -> String {
2438− | "border-end-start-radius"
2121+ let mut css = String::new();
2439− | "border-end-end-radius" => {
2122+ // The auto margins of `center-x`, `align-left`, ..., written at the end
2440− if let Some(v) = val {
2123+ let mut aligned = String::new();
2441− push_css(&mut css, effective_key, &css_px(v));
2124+ let kind = site.kind;
2442− }
2125+ // Under `children:` the styles go on the children, whose parent is this
2443− }
2126+ // element: htmlang's words that place an element in its parent are an
2127+ // error there (the parser reports them), and left out
2128+ let on_children = condition.on_children();
2129+ let inside = condition.inside().is_some();
2130+ // The direction `fill` and `shrink` compile against
2131+ let axis = site.parent.at(&condition.at);
2133+ // htmlang's words for laying out children (`spacing`, `wrap`,
2134+ // `grid-cols`) mean nothing on an element that doesn't lay out its
2135+ // children, which the parser reports; they are left out. Under
2136+ // `children:` they go on the children, whose layout isn't known here.
2137+ let lays_out_children = kind.layout().is_container() || on_children;
2138+ fn under<'k>(key: &'k str, condition: &Condition) -> Option<&'k str> {
2139+ let (c, name) = Condition::of(key);
2140+ (c == *condition).then_some(name)
2143+ for (index, attr) in attrs.iter().enumerate() {
2147+ let Some(effective_key) = under(&attr.key, condition) else {
2150+ if on_children && crate::vocab::places_in_parent(effective_key, attr.value.as_deref()) {
2153+ // Under an element prefix (`@td:`) the styles go on elements whose
2154+ // layout and parent aren't known here: htmlang's own words are an
2155+ // error there (the parser reports them), and left out
2156+ if inside && crate::vocab::is_htmlang_word(effective_key, attr.value.as_deref()) {
2445− // Logical scroll margins & padding
2160+ let val = attr.value.as_deref();
2446− "scroll-margin-inline"
2161+ // A style whose value came out empty (a field a record doesn't
2447− | "scroll-margin-block"
2162+ // have, `${if()}` without its other branch) is left out
2448− | "scroll-padding-inline"
2163+ if val.is_some_and(|v| v.trim().is_empty()) {
2449− | "scroll-padding-block" => {
2164+ continue;
2450− if let Some(v) = val {
2165+ }
2451− push_css(&mut css, effective_key, &css_px_multi(v));
2455− // Logical sizing
2167+ match effective_key {
2456− "inline-size" | "block-size" | "min-inline-size" | "max-inline-size"
2168+ // htmlang's own words: they lay out children or place the
2457− | "min-block-size" | "max-block-size" => {
2169+ // element in its parent, and mean more than one CSS property
2170+ "spacing" if !lays_out_children => {}
2458 if let Some(v) = val {
2172 if let Some(v) = val {
2459− push_css(&mut css, effective_key, &css_px(v));
2173+ push_css(&mut css, "gap", &with_px("gap", v));
2463− // Margin
2177+ // Sizing: `fill` and `shrink` compile against the parent's
2464− "margin" => {
2178+ // direction. Only the last `width` (`height`) counts, as for
2465− if let Some(v) = val {
2179+ // any style written twice.
2466− push_css(&mut css, "margin", &css_px_multi(v));
2180+ "width" | "height" if val.is_some_and(|v| Size::of(v) != Size::Set) => {
2467− }
2181+ let later = attrs[index + 1..].iter().any(|a| {
2469− "margin-x" => {
2183+ && under(&a.key, condition) == Some(effective_key)
2470− if let Some(v) = val {
2184+ && a.value.as_deref().is_some_and(|v| !v.trim().is_empty())
2471− push_css(&mut css, "margin-inline", &css_px(v));
2185+ });
2475− if let Some(v) = val {
2476− push_css(&mut css, "margin-block", &css_px(v));
2478− }
2189+ let dim = if effective_key == "width" {
2480− // Container queries
2191+ } else {
2481− "container" => {
2192+ Dim::Height
2482− push_css(&mut css, "container-type", "inline-size");
2193+ };
2483− }
2194+ let size = Size::of(val.unwrap_or_default());
2484−
2195+ // What the element writes itself, which a layout word
2485− // Inset (shorthand for top/right/bottom/left)
2196+ // leaves alone
2486− "inset" => {
2197+ let sizes = Sizes::of(attrs, condition);
2487− if let Some(v) = val {
2198+ for &(property, value) in sizing(dim, size, axis) {
2488− push_css(&mut css, "inset", &css_px(v));
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);
2493− "border-spacing" => {
2494 if let Some(v) = val {
2238 if let Some(v) = val {
2495− push_css(&mut css, "border-spacing", &css_px(v));
2239+ push_css(&mut css, effective_key, &with_px(effective_key, v));
2499− // Text decoration
2243+ // Alignment: auto margins, which work along either direction.
2500− "text-decoration-thickness" => {
2244+ // They are written last, so a `margin` on the same element
2501− if let Some(v) = val {
2245+ // keeps its other sides (`center-x, margin 20`)
2502− push_css(&mut css, "text-decoration-thickness", &css_px(v));
2246+ "center-x" => {
2503− }
2247+ push_css(&mut aligned, "margin-left", "auto");
2248+ push_css(&mut aligned, "margin-right", "auto");
2505− "text-underline-offset" => {
2250+ "center-y" => {
2506− if let Some(v) = val {
2251+ push_css(&mut aligned, "margin-top", "auto");
2507− push_css(&mut css, "text-underline-offset", &css_px(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"),
2511− // Multi-column
2259+ "wrap" if lays_out_children => push_css(&mut css, "flex-wrap", "wrap"),
2512− "column-width" => {
2260+ "wrap" => {}
2513− if let Some(v) = val {
2514− push_css(&mut css, "column-width", &css_px(v));
2518− // New CSS properties
2262+ // Grid
2519− "column-gap" => {
2263+ "grid-cols" | "grid-rows" if !lays_out_children => {}
2520− if let Some(v) = val {
2264+ "grid-cols" | "grid-rows" => {
2521− push_css(&mut css, "column-gap", &css_px(v));
2525− if let Some(v) = val {
2526− push_css(&mut css, "text-indent", &css_px(v));
2530− if let Some(v) = val {
2531− push_css(&mut css, "flex-basis", &css_px(v));
2534− "scroll-margin" => {
2535− if let Some(v) = val {
2536− push_css(&mut css, "scroll-margin", &css_px(v));
2539− "scroll-margin-top"
2540− | "scroll-margin-bottom"
2541− | "scroll-margin-left"
2542− | "scroll-margin-right" => {
2543− if let Some(v) = val {
2544− push_css(&mut css, effective_key, &css_px(v));
2547− "scroll-padding" => {
2548− if let Some(v) = val {
2549− push_css(&mut css, "scroll-padding", &css_px(v));
2552− "scroll-padding-top"
2553− | "scroll-padding-bottom"
2554− | "scroll-padding-left"
2555− | "scroll-padding-right" => {
2556 if let Some(v) = val {
2265 if let Some(v) = val {
2557− push_css(&mut css, effective_key, &css_px(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)),
2560−
2277+ "col-span" | "row-span" => {
2562 if let Some(v) = val {
2278 if let Some(v) = val {
2563− // Wrap in quotes if not already quoted and not a CSS keyword
2279+ let property = if effective_key == "col-span" {
2564− if v.starts_with('"')
2280+ "grid-column"
2565− || v.starts_with('\'')
2568− || v.starts_with("attr(")
2569− || v.starts_with("counter(")
2571− push_css(&mut css, "content", v);
2572 } else {
2281 } else {
2573− push_css(&mut css, "content", &format!("\"{}\"", v));
2282+ "grid-row"
2284+ push_css(&mut css, property, &format!("span {}", v));
2578− // --- CSS Shorthands ---
2288+ // CSS's `line-clamp` has no support yet without its
2289+ // `-webkit-` fallback, which needs a box to clamp
2579 "line-clamp" => {
2290 "line-clamp" => {
2580 if let Some(v) = val {
2291 if let Some(v) = val {
2581 push_css(&mut css, "display", "-webkit-box");
2292 push_css(&mut css, "display", "-webkit-box");
@@ -2585,15 +2296,14 @@ fn attrs_to_css(
2588− // Any other standard CSS property is copied through, with `px`
2299+ // Every other name is a CSS property (standard, custom,
2589− // added to bare numbers where the property takes a length.
2300+ // vendor-prefixed, or one htmlang doesn't know, which the
2590− key if crate::vocab::is_css_property(key) => {
2301+ // parser warned about), written under its own name with the
2302+ // value as written, except for `px` after a bare number where
2303+ // the property takes a length
2304+ key if crate::vocab::is_property_name(key) => {
2591 if let Some(v) = val {
2305 if let Some(v) = val {
2592− if crate::vocab::is_length_property(key) {
2306+ push_css(&mut css, key, &with_px(key, v));
2593− push_css(&mut css, key, &css_px_multi(v));
2595− push_css(&mut css, key, v);
@@ -2601,6 +2311,7 @@ fn attrs_to_css(
2314+ css.push_str(&aligned);
@@ -2611,258 +2322,6 @@ fn push_css(css: &mut String, prop: &str, value: &str) {
2611 css.push(';');
2322 css.push(';');
2614−/// Known CSS units — if a value ends with one, skip appending `px`.
2615−/// Format a length value: a bare number gets `px` appended; anything else
2616−/// (values with units, keywords like `auto`, functions like `calc(...)`) is
2617−/// passed through unchanged.
2618−fn css_px(value: &str) -> String {
2619− let v = value.trim();
2621− return "0".to_string();
2623− let is_bare_number = !v.is_empty()
2624− && v.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'-' | b'+'))
2625− && v.parse::<f64>().is_ok();
2626− if is_bare_number {
2633−/// Rewrite literal values that match a declared CSS custom property (from
2634−/// `@theme` or `@let --name value`) to `var(--name)` references. Matches are
2635−/// anchored to CSS value boundaries so e.g. `#3b82f6` inside a longer hex or
2636−/// inside an identifier is not replaced. The `:root` block is emitted before
2637−/// this call runs, so its declarations are not affected.
2638−fn substitute_css_vars(css: &str, vars: &[(String, String)]) -> String {
2639− if css.is_empty() || vars.is_empty() {
2640− return css.to_string();
2642− // Prefer longer values first so that if two vars share a prefix, the
2643− // longer (more specific) match wins.
2644− let mut pairs: Vec<(&str, String)> = vars
2646− .filter(|(name, value)| name.starts_with("--") && !value.is_empty())
2647− .map(|(name, value)| (value.as_str(), format!("var({})", name)))
2649− pairs.sort_by_key(|(v, _)| std::cmp::Reverse(v.len()));
2650− if pairs.is_empty() {
2651− return css.to_string();
2654− let is_boundary_before = |b: Option<u8>| match b {
2656− Some(c) => matches!(c, b':' | b' ' | b',' | b'(' | b';' | b'{' | b'\n' | b'\t'),
2658− let is_boundary_after = |b: Option<u8>| match b {
2660− Some(c) => matches!(c, b';' | b'}' | b',' | b' ' | b')' | b'\n' | b'\t'),
2663− let bytes = css.as_bytes();
2664− let mut out = String::with_capacity(css.len());
2666− let mut prev: Option<u8> = None;
2667− // Only declaration values are rewritten — never selectors or at-rule
2668− // preludes such as `@media (min-width:768px)`. `blocks` records, for
2669− // each open `{`, whether it holds declarations (a style rule) or nested
2670− // rules (an at-rule like `@media` / `@layer`).
2671− let mut blocks: Vec<bool> = Vec::new();
2672− let mut prelude_start = 0;
2673− let mut in_value = false;
2674− while i < bytes.len() {
2677− let prelude = css[prelude_start..i].trim_start();
2678− blocks.push(!prelude.starts_with('@'));
2680− prelude_start = i + 1;
2685− prelude_start = i + 1;
2689− prelude_start = i + 1;
2691− b':' if blocks.last() == Some(&true) => in_value = true,
2694− if in_value && is_boundary_before(prev) {
2695− let mut matched = false;
2696− for (val, repl) in &pairs {
2697− let vb = val.as_bytes();
2698− if i + vb.len() <= bytes.len() && &bytes[i..i + vb.len()] == vb {
2699− let next = bytes.get(i + vb.len()).copied();
2700− if is_boundary_after(next) {
2701− out.push_str(repl);
2702− prev = repl.as_bytes().last().copied();
2713− // Advance by one UTF-8 code point.
2716− while i < bytes.len() && (bytes[i] & 0xC0) == 0x80 {
2719− out.push_str(&css[start..i]);
2720− prev = bytes.get(i - 1).copied();
2725−/// Scan generated CSS for literal property values that repeat often enough
2726−/// that substituting them with an auto-named custom property would reduce
2727−/// total byte count. Returns the rewritten CSS and any new vars that should
2728−/// be appended to `:root`.
2730−/// The algorithm only promotes a value if it strictly saves bytes after
2731−/// accounting for the `--xN:value;` declaration overhead plus the
2732−/// `var(--xN)` reference cost at each call site. Values that are already
2733−/// `var(...)` references or contain `var(` calls are skipped so we never
2734−/// nest references. Names avoid collisions with `existing_vars`.
2735−fn auto_extract_repeats(
2737− existing_vars: &[(String, String)],
2738−) -> (String, Vec<(String, String)>) {
2739− if css.is_empty() {
2740− return (css.to_string(), Vec::new());
2742− // Count occurrences of each distinct property value (the text between
2743− // `:` and the next `;` or `}` at the top level of a declaration block,
2744− // ignoring balanced parentheses so that e.g. `rgba(...)` stays intact).
2745− let bytes = css.as_bytes();
2746− let mut counts: HashMap<String, usize> = HashMap::new();
2747− let mut depth: i32 = 0;
2749− while i < bytes.len() {
2765− if depth > 0 && bytes[i] == b':' {
2766− // Skip past `:` then walk to the terminator.
2768− let mut end = start;
2769− let mut pdepth = 0i32;
2770− while end < bytes.len() {
2772− b'(' => pdepth += 1,
2773− b')' if pdepth > 0 => pdepth -= 1,
2774− b';' | b'}' if pdepth == 0 => break,
2775− b'{' if pdepth == 0 => break,
2780− let val = css[start..end].trim();
2781− if !val.is_empty() && !val.starts_with("var(") && !val.contains("var(") {
2782− *counts.entry(val.to_string()).or_default() += 1;
2790− // Decide which values are worth extracting. A value of length L appearing
2791− // N times costs N*L bytes inline; promoting it costs (L + 6) for the
2792− // `--hK:V;` declaration plus N * ref_len for the call sites. We estimate
2793− // ref_len optimistically as `var(--h0)` (9 bytes) and fall back to 10 for
2794− // two-digit indices, which only affects very large extraction counts.
2795− let existing: std::collections::HashSet<&str> =
2796− existing_vars.iter().map(|(n, _)| n.as_str()).collect();
2797− let mut candidates: Vec<(String, usize)> =
2798− counts.into_iter().filter(|(_, n)| *n >= 2).collect();
2799− // Stable, deterministic ordering — longest values first, tiebreak by text.
2800− candidates.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
2802− let mut extracted: Vec<(String, String)> = Vec::new();
2803− let mut next_idx: usize = 0;
2804− for (value, n) in candidates {
2805− let l = value.len();
2806− // Allocate the next unused `--hN` name.
2807− let (name, ref_len) = loop {
2808− let candidate = format!("--h{}", next_idx);
2810− let rl = candidate.len() + 6; // `var(` + name + `)`
2811− if !existing.contains(candidate.as_str())
2812− && !extracted.iter().any(|(n, _)| *n == candidate)
2814− break (candidate, rl);
2817− // Skip if promotion would not strictly reduce byte count.
2818− // Before: n * l bytes. After: (l + name.len() + 2) for the :root
2819− // declaration (`<name>:<value>;`) plus n * ref_len for the sites.
2820− let decl_overhead = l + name.len() + 2;
2821− let before = n * l;
2822− let after = decl_overhead + n * ref_len;
2823− if after < before {
2824− extracted.push((name, value));
2826− // Rewind the index so the next value can reuse this slot.
2831− if extracted.is_empty() {
2832− return (css.to_string(), Vec::new());
2834− let new_css = substitute_css_vars(css, &extracted);
2835− (new_css, extracted)
2838−/// Format a `line-height` value. CSS accepts either a unitless multiplier
2839−/// (e.g. `1.5`) or a length (e.g. `24px`). Plain integers in htmlang source
2840−/// are ambiguous: `[line-height 24]` was historically emitted as `24` (which
2841−/// CSS interprets as 24× font-size — almost never what anyone wants). Treat
2842−/// integers ≥ 2 as pixel lengths; anything with a decimal, an existing unit,
2843−/// or the value `0`/`1` passes through unchanged.
2844−fn css_line_height(value: &str) -> String {
2845− let v = value.trim();
2846− if v == "0" || v == "1" {
2847− return v.to_string();
2849− // Plain integer — treat as pixel length. Decimals, units, keywords and
2850− // functions pass through.
2851− if !v.is_empty() && v.chars().all(|c| c.is_ascii_digit()) {
2852− return format!("{}px", v);
2857−/// Format multiple space-separated values, each getting px if needed.
2858−fn css_px_multi(value: &str) -> String {
2860− .split_whitespace()
2862− .collect::<Vec<_>>()
2866fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
2325fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
2867 let mut id = None;
2326 let mut id = None;
2868 let mut class = None;
2327 let mut class = None;
@@ -2876,153 +2335,6 @@ fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
2876 (id, class)
2335 (id, class)
2879−/// Read image dimensions from a local file by parsing the header bytes.
2880−/// Supports PNG, JPEG, GIF, WebP, AVIF, and SVG.
2881−fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
2882− // SVG: parse as text for viewBox/width/height attributes
2883− if path.ends_with(".svg") || path.ends_with(".SVG") {
2884− let text = std::fs::read_to_string(path).ok()?;
2885− return read_svg_dimensions(&text);
2888− let data = std::fs::read(path).ok()?;
2889− if data.len() < 12 {
2893− // PNG: 8-byte signature, then IHDR chunk with width/height at bytes 16-23
2894− if data.len() >= 24 && data.starts_with(b"\x89PNG\r\n\x1a\n") {
2895− let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
2896− let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
2897− return Some((w, h));
2900− // GIF: "GIF87a" or "GIF89a", width/height at bytes 6-9 (little-endian)
2901− if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
2902− let w = u16::from_le_bytes([data[6], data[7]]) as u32;
2903− let h = u16::from_le_bytes([data[8], data[9]]) as u32;
2904− return Some((w, h));
2907− // JPEG: scan for SOF0/SOF2 marker (0xFF 0xC0 or 0xFF 0xC2)
2908− if data.starts_with(b"\xff\xd8") {
2910− while i + 9 < data.len() {
2911− if data[i] != 0xFF {
2915− let marker = data[i + 1];
2916− if marker == 0xC0 || marker == 0xC2 {
2917− let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
2918− let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
2919− return Some((w, h));
2921− if i + 3 < data.len() {
2922− let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
2930− // WebP: "RIFF" ... "WEBP", VP8 header at byte 20
2931− if data.len() >= 30 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
2932− if &data[12..16] == b"VP8 " && data.len() >= 30 {
2933− let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
2934− let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
2935− return Some((w, h));
2937− if &data[12..16] == b"VP8L" && data.len() >= 25 && data[21] == 0x2F {
2938− let bits = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
2939− let w = (bits & 0x3FFF) + 1;
2940− let h = ((bits >> 14) & 0x3FFF) + 1;
2941− return Some((w, h));
2945− // AVIF: ISOBMFF container with "ftyp" box containing "avif"/"avis" brand,
2946− // then "ispe" box with width/height
2947− if data.len() >= 12 && &data[4..8] == b"ftyp" {
2948− let brand = &data[8..12];
2949− if brand == b"avif" || brand == b"avis" || brand == b"mif1" {
2950− return read_avif_dimensions(&data);
2957−/// Parse SVG viewBox or width/height attributes to get dimensions.
2958−fn read_svg_dimensions(text: &str) -> Option<(u32, u32)> {
2959− // Try viewBox first: viewBox="minX minY width height"
2960− if let Some(vb_start) = text.find("viewBox=\"") {
2961− let rest = &text[vb_start + 9..];
2962− if let Some(end) = rest.find('"') {
2963− let parts: Vec<&str> = rest[..end].split_whitespace().collect();
2964− if parts.len() == 4
2965− && let (Ok(w), Ok(h)) = (parts[2].parse::<f64>(), parts[3].parse::<f64>())
2969− return Some((w.round() as u32, h.round() as u32));
2973− // Fall back to width/height attributes on <svg>
2974− let svg_tag = text.find("<svg")?;
2975− let tag_end = text[svg_tag..].find('>')? + svg_tag;
2976− let tag = &text[svg_tag..tag_end];
2977− let w = extract_svg_attr(tag, "width")?;
2978− let h = extract_svg_attr(tag, "height")?;
2982−fn extract_svg_attr(tag: &str, attr: &str) -> Option<u32> {
2983− let needle = format!("{}=\"", attr);
2984− let start = tag.find(&needle)? + needle.len();
2985− let rest = &tag[start..];
2986− let end = rest.find('"')?;
2987− let val = rest[..end].trim_end_matches("px");
2988− val.parse::<f64>().ok().map(|v| v.round() as u32)
2991−/// Parse AVIF (ISOBMFF) container to find ispe box with image dimensions.
2992−fn read_avif_dimensions(data: &[u8]) -> Option<(u32, u32)> {
2993− // Walk ISOBMFF boxes looking for "ispe" (image spatial extents)
2995− while i + 8 <= data.len() {
2997− u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as usize;
2998− let box_type = &data[i + 4..i + 8];
3002− let box_end = (i + box_size).min(data.len());
3003− // ispe box: 4 bytes version/flags + 4 bytes width + 4 bytes height
3004− if box_type == b"ispe" && box_end >= i + 20 {
3005− let w = u32::from_be_bytes([data[i + 12], data[i + 13], data[i + 14], data[i + 15]]);
3006− let h = u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
3007− return Some((w, h));
3009− // Recurse into container boxes (meta, iprp, ipco)
3012− b"meta" | b"iprp" | b"ipco" | b"moov" | b"trak" | b"mdia"
3014− let header_size = if box_type == b"meta" { 12 } else { 8 };
3015− if i + header_size < box_end
3016− && let Some(dims) = read_avif_dimensions(&data[i + header_size..box_end])
3026fn html_escape(s: &str) -> String {
2338fn html_escape(s: &str) -> String {
3027 s.replace('&', "&")
2339 s.replace('&', "&")
3028 .replace('<', "<")
2340 .replace('<', "<")
@@ -3138,43 +2450,30 @@ fn vlq_encode(value: i64, out: &mut String) {
3142−/// Does the tree contain the table element `name` (e.g. `"main"`)?
2454+mod tests {
3143−fn has_tag(nodes: &[Node], name: &str) -> bool {
2455+ use super::*;
3144− nodes.iter().any(|node| match node {
2456+
3145− Node::Element(elem) => elem.kind.is_tag(name) || has_tag(&elem.children, name),
2457+ #[test]
3146− _ => false,
2458+ fn a_name_is_a_stable_hash_of_the_style() {
3147− })
2459+ // The same in every build and on every platform
3148−}
2460+ assert_eq!(stable_hash(""), 0xf52a_15e9_a9b5_e89b);
3149−
2461+ assert_eq!(hash_digits(35, 3), "z00");
3150−/// Collect unique external domains from generated HTML for DNS prefetch hints.
2462+ assert_eq!(hash_digits(u64::MAX, 13), "fsgs46211e5w3");
3151−fn collect_dns_prefetch(html: &str, dev: bool) -> String {
2463+ }
3152− let mut domains = Vec::new();
2464+
3153− let mut rest = html;
2465+ #[test]
3154− while let Some(pos) = rest.find("https://") {
2466+ fn a_name_taken_in_the_file_takes_more_digits() {
3155− let start = pos + 8; // skip "https://"
2467+ // These two styles' hashes end in the same 7 digits
3156− rest = &rest[start..];
2468+ let mut styles = StyleCollector::new();
3157− let end = rest
2469+ let first = styles.get_class("width:129555px;".into(), Vec::new(), String::new());
3158− .find(['/', '"', '\'', ' ', '>', ')'])
2470+ let second = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
3159− .unwrap_or(rest.len());
2471+ let (first, second) = (first.unwrap(), second.unwrap());
3160− let domain = &rest[..end];
2472+ assert_eq!(first.len(), 3 + CLASS_DIGITS, "{first}");
3161− if !domain.is_empty() && domain.contains('.') && !domains.contains(&domain.to_string()) {
2473+ assert_eq!(second.len(), 3 + CLASS_DIGITS + 1, "{second}");
3162− domains.push(domain.to_string());
2474+ assert!(second.starts_with(&first), "{first} {second}");
3163− }
2475+ // The same style gets the name it got before
3164− }
2476+ let again = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
3165− let mut out = String::new();
2477+ assert_eq!(again.as_deref(), Some(second.as_str()));
3166− for domain in &domains {
3168− out.push_str(&format!(
3169− "<link rel=\"dns-prefetch\" href=\"//{}\">\n",
3173− out.push_str(&format!(
3174− "<link rel=\"dns-prefetch\" href=\"//{}\">",