@@ -1,7 +1,8 @@
11use std::collections::HashMap;
2−use std::hash::{Hash, Hasher};
2+use std::hash::Hash;
33
44use crate::ast::*;
5+use crate::vocab::with_px;
56
67// ---------------------------------------------------------------------------
78// Style collector: deduplicates CSS and assigns class names
@@ -16,56 +17,315 @@ const BREAKPOINTS: &[(&str, &str)] = &[
1617 ("2xl", "1536px"),
1718];
1819
19−/// Generate short CSS class names: a..z, then aa..a9, ba..b9, ..., z9, then
20−/// aaa, ... The first character is always a letter; later ones are drawn from
21−/// [a-z0-9]. The mapping is a bijection, so distinct indices never collide.
22−pub(crate) fn short_class_name(idx: usize) -> String {
23− const REST: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
24− // Find the name length: 26 names of length 1, 26*36 of length 2, ...
25− let mut n = idx;
26− let mut len = 1;
27− let mut count = 26usize;
28− while n >= count {
29− n -= count;
30− len += 1;
31− count = count.saturating_mul(36);
20+/// The prefix of every generated class (`hl-2k9xq0m`), which keeps them
21+/// out of the author's own class names.
22+pub const CLASS_PREFIX: &str = "hl-";
23+
24+/// How many base-36 digits a class's name has after `hl-`: 7, about 36
25+/// bits of its style's hash, so a site with 10,000 different styles has
26+/// odds of about 6 in 10,000 that two of them share a name, which
27+/// `htmlang build` reports (`class-collision`). Within one file, a style
28+/// whose name is taken takes more digits.
29+pub const CLASS_DIGITS: usize = 7;
30+
31+/// A stable hash of `text`: FNV-1a, then SplitMix64's finalizer, so every
32+/// digit of a name depends on all of the text. It is the same on every
33+/// platform and in every build, unlike `std`'s hasher.
34+pub fn stable_hash(text: &str) -> u64 {
35+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
36+ for byte in text.bytes() {
37+ hash ^= u64::from(byte);
38+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
39+ }
40+ hash = (hash ^ (hash >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
41+ hash = (hash ^ (hash >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
42+ hash ^ (hash >> 31)
43+}
44+
45+/// `digits` base-36 digits of `hash`: `2k9xq0m`. With 13, all of it.
46+pub fn hash_digits(hash: u64, digits: usize) -> String {
47+ const DIGITS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
48+ let mut n = hash;
49+ (0..digits)
50+ .map(|_| {
51+ let digit = DIGITS[(n % 36) as usize] as char;
52+ n /= 36;
53+ digit
54+ })
55+ .collect()
56+}
57+
58+/// A class htmlang generated: its name, and the hash of the style it
59+/// stands for. One style has one name in every file, so a fragment's
60+/// classes mean the same in any page it goes into.
61+#[derive(Clone, Debug, PartialEq, Eq)]
62+pub struct Class {
63+ pub name: String,
64+ pub style: u64,
65+}
66+
67+/// When a style applies: the at-rule prefixes it is under (their ranks,
68+/// see [`crate::vocab::at_rule_rank`], sorted, so `dark:md:` and `md:dark:`
69+/// are one condition) and its selector prefixes, left to right as the
70+/// selector reads (`hover:children:` is `.a:hover > *`).
71+#[derive(Clone, Default, PartialEq, Eq, Hash, Debug)]
72+struct Condition {
73+ at: Vec<usize>,
74+ selector: Vec<String>,
75+}
76+
77+impl Condition {
78+ /// The condition of an attribute's key, and the name after its
79+ /// prefixes.
80+ fn of(key: &str) -> (Condition, &str) {
81+ let (prefixes, name) = crate::vocab::split_prefixes(key);
82+ let mut condition = Condition::default();
83+ for prefix in prefixes {
84+ match crate::vocab::at_rule_rank(prefix) {
85+ Some(rank) => condition.at.push(rank),
86+ None => condition.selector.push(prefix.to_string()),
87+ }
88+ }
89+ condition.at.sort_unstable();
90+ condition.at.dedup();
91+ (condition, name)
92+ }
93+
94+ /// Only the at-rule part: a direction under `hover:` is the one without
95+ /// it.
96+ fn at_only(at: &[usize]) -> Condition {
97+ Condition {
98+ at: at.to_vec(),
99+ selector: Vec::new(),
100+ }
101+ }
102+
103+ /// The styles go on the element's children (`children:`).
104+ fn on_children(&self) -> bool {
105+ self.selector.iter().any(|p| p == crate::vocab::CHILDREN)
106+ }
107+
108+ /// The styles go on the elements of one kind inside the element
109+ /// (`@td:`): where the element prefix is in the selector chain.
110+ fn inside(&self) -> Option<usize> {
111+ self.selector
112+ .iter()
113+ .position(|p| crate::vocab::element_prefix(p).is_some())
114+ }
115+
116+ /// Whether this condition holds wherever `other` does: its at-rules
117+ /// are implied by `other`'s, and it has no selector or `other`'s.
118+ fn holds_at(&self, other: &Condition) -> bool {
119+ (self.selector.is_empty() || self.selector == other.selector)
120+ && self.at.iter().all(|&a| {
121+ other
122+ .at
123+ .iter()
124+ .any(|&b| crate::vocab::at_rule_implied(a, b))
125+ })
126+ }
127+
128+ /// The order the rules of each condition are written in, which the
129+ /// cascade follows: no prefix, then selectors, then each at-rule
130+ /// block (see [`at_order`]), with its selectors inside it.
131+ fn order(&self) -> (AtOrder, SelectorOrder) {
132+ (at_order(&self.at), selector_order(&self.selector))
133+ }
134+}
135+
136+/// Where a block of at-rules is written: after the rules without one; by
137+/// its last (innermost) prefix in the order of
138+/// [`crate::vocab::at_rule_prefixes`] (widths, media, container widths), so
139+/// `md:dark:` comes with `dark:`, after it; then by length.
140+type AtOrder = (bool, usize, usize, Vec<usize>);
141+
142+fn at_order(at: &[usize]) -> AtOrder {
143+ (
144+ !at.is_empty(),
145+ at.last().copied().unwrap_or(0),
146+ at.len(),
147+ at.to_vec(),
148+ )
149+}
150+
151+/// Selector chains in the order of [`crate::vocab::PSEUDOS`] (position,
152+/// then form state, then `hover:`, `focus:`, `active:`, `disabled:`), and
153+/// by their argument's text for the same pseudo-class; a chain before the
154+/// longer ones it starts. A chain through `children:` comes after the
155+/// others, ordered by what follows its last `children:` and then by what
156+/// comes before it: only that tail counts toward its specificity (see
157+/// [`selector`]), so `hover:children:` follows `children:` and wins over it
158+/// on hover.
159+type SelectorOrder = (bool, Vec<(usize, String)>, Vec<(usize, String)>);
160+
161+fn selector_order(selector: &[String]) -> SelectorOrder {
162+ let table = crate::vocab::PSEUDOS;
163+ let ranked = |chain: &[String]| -> Vec<(usize, String)> {
164+ chain
165+ .iter()
166+ .map(|p| {
167+ let name = crate::vocab::pseudo_name(p);
168+ let rank = table
169+ .iter()
170+ .position(|(q, _)| *q == name)
171+ .unwrap_or(table.len());
172+ (rank, p.clone())
173+ })
174+ .collect()
175+ };
176+ match selector.iter().rposition(|p| p == crate::vocab::CHILDREN) {
177+ None => (false, ranked(selector), Vec::new()),
178+ Some(i) => (true, ranked(&selector[i + 1..]), ranked(&selector[..i])),
179+ }
180+}
181+
182+/// The order of the chains through an element prefix (`@td:`, see
183+/// [`scoped_selector`]): by the prefixes before it, which select the root
184+/// of the scope and add nothing to the specificity, so `hover:@td:` comes
185+/// after `@td:` and wins on hover; then by the element; then by the
186+/// prefixes after it.
187+fn inside_order(chain: &[String]) -> (SelectorOrder, String, SelectorOrder) {
188+ let at = chain
189+ .iter()
190+ .position(|p| crate::vocab::element_prefix(p).is_some())
191+ .unwrap_or(chain.len());
192+ (
193+ selector_order(&chain[..at]),
194+ chain.get(at).cloned().unwrap_or_default(),
195+ selector_order(chain.get(at + 1..).unwrap_or_default()),
196+ )
197+}
198+
199+/// The selector for `class` under a chain of selector prefixes, read left
200+/// to right. Everything before the last `children:` goes in `:where()`, so
201+/// a parent's `children:` styles have no specificity, and a child's own
202+/// attributes win over them: `children:hover:` is `:where(.a)>*:hover`,
203+/// `hover:children:` is `:where(.a:hover)>*`.
204+fn selector(class: &str, chain: &[String]) -> String {
205+ let last_children = chain.iter().rposition(|p| p == crate::vocab::CHILDREN);
206+ let mut out = format!(".{}", class);
207+ for (i, prefix) in chain.iter().enumerate() {
208+ if prefix == crate::vocab::CHILDREN {
209+ if Some(i) == last_children {
210+ out = format!(":where({})>*", out);
211+ } else {
212+ out.push_str(">*");
213+ }
214+ } else if let Some(pseudo) = crate::vocab::pseudo_selector(prefix) {
215+ out.push_str(&pseudo);
216+ }
32217 }
33− let mut tail = Vec::with_capacity(len - 1);
34− for _ in 1..len {
35− tail.push(REST[n % 36]);
36− n /= 36;
218+ out
219+}
220+
221+/// The rule for the elements an element prefix picks out inside the
222+/// element with the class `class` (see [`Condition::inside`]): the scope's
223+/// root, from the selector prefixes before it (`hover:@td:` is inside a
224+/// hovered element), and the selector for the elements, from those after
225+/// it (`@td:hover:` is a hovered cell). `:scope td` leaves out the root
226+/// itself, so `@ul [@ul:...]` styles the lists inside, not its own. `None`
227+/// when the name has no tag of its own (the parser reports it).
228+fn scoped_selector(class: &str, chain: &[String], at: usize) -> Option<(String, String)> {
229+ let name = crate::vocab::element_prefix(&chain[at])?;
230+ let tag = ElementKind::from_name(name)?.own_tag()?;
231+ let root = selector(class, &chain[..at]);
232+ let mut target = format!(":scope {}", tag);
233+ for prefix in &chain[at + 1..] {
234+ if let Some(pseudo) = crate::vocab::pseudo_selector(prefix) {
235+ target.push_str(&pseudo);
236+ }
237+ }
238+ Some((root, target))
239+}
240+
241+/// The `@media` or `@container` rule an at-rule prefix stands for, as
242+/// written in readable and in compact output.
243+fn at_rule(rank: usize, dev: bool) -> String {
244+ let prefix = crate::vocab::at_rule_prefixes()
245+ .nth(rank)
246+ .unwrap_or_default();
247+ let name = prefix.trim_end_matches(':');
248+ let width = |name: &str| {
249+ BREAKPOINTS
250+ .iter()
251+ .find(|(n, _)| *n == name)
252+ .map_or("0", |(_, w)| *w)
253+ };
254+ let (kind, feature, value) = if let Some(size) = name.strip_prefix("cq-") {
255+ ("@container", "min-width", width(size))
256+ } else {
257+ match name {
258+ "print" => {
259+ return "@media print".to_string();
260+ }
261+ "dark" => ("@media", "prefers-color-scheme", "dark"),
262+ "motion-safe" => ("@media", "prefers-reduced-motion", "no-preference"),
263+ "motion-reduce" => ("@media", "prefers-reduced-motion", "reduce"),
264+ "landscape" | "portrait" => ("@media", "orientation", name),
265+ _ => ("@media", "min-width", width(name)),
266+ }
267+ };
268+ if dev {
269+ format!("{} ({}: {})", kind, feature, value)
270+ } else {
271+ format!("{}({}:{})", kind, feature, value)
37272 }
38− let mut name = String::with_capacity(len);
39− name.push((b'a' + n as u8) as char);
40− name.extend(tail.iter().rev().map(|&b| b as char));
41− name
273+}
274+
275+/// A style as text, for its hash: the defaults of its element's kind, its
276+/// rules (the at-rules' ranks, the selector prefixes and the declarations
277+/// of each) and the rules keyed on it, each part ended by a character CSS
278+/// doesn't have.
279+fn style_text(defaults: &str, rules: &[(Condition, String)], distinct: &str) -> String {
280+ let mut text = format!("{defaults}\u{1}");
281+ for (condition, body) in rules {
282+ for rank in &condition.at {
283+ text.push_str(&format!("{rank}\u{2}"));
284+ }
285+ text.push('\u{3}');
286+ for prefix in &condition.selector {
287+ text.push_str(prefix);
288+ text.push('\u{2}');
289+ }
290+ text.push('\u{3}');
291+ text.push_str(body);
292+ text.push('\u{1}');
293+ }
294+ text.push_str(distinct);
295+ text
42296}
43297
44298struct StyleEntry {
45299 class_name: String,
46− base: String,
47− /// (CSS selector suffix, css_rules) — e.g. (":hover", "color:red;")
48− pseudo: Vec<(String, String)>,
49− /// Responsive overrides: (breakpoint_prefix, css)
50− responsive: Vec<(String, String)>,
51− /// Dark mode overrides
52− dark: String,
53− /// Print overrides
54− print: String,
55− motion_safe: String,
56− motion_reduce: String,
57− landscape: String,
58− portrait: String,
59− /// Container query overrides: (breakpoint_prefix, css)
60− container: Vec<(String, String)>,
300+ /// The hash of the style, which names the class
301+ style: u64,
302+ /// The defaults of the element's kind (its layout, a heading's
303+ /// `margin:0`, ...), less what its own attributes set. They are written
304+ /// as `:where(.hl-a)` in the layer `hl-kind`, so an element prefix
305+ /// around it (`@h2:`), its parent's `children:` styles and its own
306+ /// attributes, all in later layers, win over them.
307+ defaults: String,
308+ /// The element's rules: under each condition, its declarations, in the
309+ /// order they are written
310+ rules: Vec<(Condition, String)>,
311+ /// What else tells two elements with the same CSS apart: the rules
312+ /// keyed on this class (see [`StyleCollector::keyed`]). Not written.
313+ distinct: String,
61314}
62315
63316struct StyleCollector {
64317 entries: Vec<StyleEntry>,
65− /// Maps a pre-hashed style signature to an index into `entries`.
66− /// Using u64 as the key keeps lookups allocation-free; on the rare case of
67− /// a hash collision we fall back to a full equality check against the entry.
318+ /// Maps a style's hash to its entries (more than one only when two
319+ /// styles hash alike, which the full comparison tells apart).
68320 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)>,
69329}
70330
71331impl StyleCollector {
@@ -73,313 +333,282 @@ impl StyleCollector {
73333 StyleCollector {
74334 entries: Vec::new(),
75335 index: HashMap::new(),
336+ names: std::collections::HashSet::new(),
337+ keyed: Vec::new(),
338+ keyed_seen: std::collections::HashSet::new(),
339+ }
340+ }
341+
342+ /// Add a rule for `selector` under the at-rules `at`, once.
343+ fn add_keyed(&mut self, at: Vec<usize>, selector: String, body: String) {
344+ let rule = (at, selector, body);
345+ if self.keyed_seen.insert(rule.clone()) {
346+ self.keyed.push(rule);
76347 }
77348 }
78349
79350 /// Returns a class name for this style combination, or None if all empty.
80− #[allow(clippy::too_many_arguments)]
81351 fn get_class(
82352 &mut self,
83− base: String,
84− pseudo: Vec<(String, String)>,
85− responsive: Vec<(String, String)>,
86− dark: String,
87− print: String,
88− motion_safe: String,
89− motion_reduce: String,
90− landscape: String,
91− portrait: String,
92− container: Vec<(String, String)>,
353+ defaults: String,
354+ mut rules: Vec<(Condition, String)>,
355+ distinct: String,
93356 ) -> Option<String> {
94− if base.is_empty()
95− && pseudo.is_empty()
96− && responsive.is_empty()
97− && dark.is_empty()
98− && print.is_empty()
99− && motion_safe.is_empty()
100− && motion_reduce.is_empty()
101− && landscape.is_empty()
102− && portrait.is_empty()
103− && container.is_empty()
104− {
357+ rules.retain(|(_, body)| !body.is_empty());
358+ if defaults.is_empty() && rules.is_empty() {
105359 return None;
106360 }
107− use std::collections::hash_map::DefaultHasher;
108− let mut h = DefaultHasher::new();
109− base.hash(&mut h);
110− pseudo.hash(&mut h);
111− responsive.hash(&mut h);
112− dark.hash(&mut h);
113− print.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();
120−
121− if let Some(indices) = self.index.get(&sig) {
361+ rules.sort_by_cached_key(|(condition, _)| condition.order());
362+ let style = stable_hash(&style_text(&defaults, &rules, &distinct));
363+
364+ if let Some(indices) = self.index.get(&style) {
122365 for &idx in indices {
123366 let e = &self.entries[idx];
124− if e.base == base
125− && e.pseudo == pseudo
126− && e.responsive == responsive
127− && e.dark == dark
128− && e.print == print
129− && e.motion_safe == motion_safe
130− && e.motion_reduce == motion_reduce
131− && e.landscape == landscape
132− && e.portrait == portrait
133− && e.container == container
134− {
367+ if e.defaults == defaults && e.rules == rules && e.distinct == distinct {
135368 return Some(e.class_name.clone());
136369 }
137370 }
138371 }
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
139375 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());
141381 self.entries.push(StyleEntry {
142382 class_name: name.clone(),
143− base,
144− pseudo,
145− responsive,
146− dark,
147− print,
148− motion_safe,
149− motion_reduce,
150− landscape,
151− portrait,
152− container,
383+ style,
384+ defaults,
385+ rules,
386+ distinct,
153387 });
154− self.index.entry(sig).or_default().push(idx);
388+ self.index.entry(style).or_default().push(idx);
155389 Some(name)
156390 }
157391
158− /// All generated rules, wrapped in `@layer htmlang`.
159− fn to_css_formatted(&self, dev: bool) -> String {
160− let mut css = String::new();
161− let inner_indent = if dev { " " } else { "" };
162− css.push_str(if dev { "@layer htmlang {\n" } else { "@layer htmlang{" });
163−
164− // Non-responsive rules. Base and pseudo rules are merged separately by
165− // identical body so that e.g. `.a,.b{display:flex;flex-direction:column;}`
166− // replaces two identical rules. Pseudo variants are grouped per selector
167− // suffix (`:hover` with `:hover`, etc.) to keep each pseudo's cascade
168− // position independent of others.
169− let mut base_pairs: Vec<(&str, &str)> = Vec::with_capacity(self.entries.len());
170− for e in &self.entries {
171− if !e.base.is_empty() {
172− base_pairs.push((e.class_name.as_str(), e.base.as_str()));
173− }
174− }
175− emit_grouped_rules(&mut css, &base_pairs, "", inner_indent, dev);
176−
177− // Collect pseudo rules grouped by selector suffix, preserving the order
178− // in which suffixes first appear across entries.
179− let mut pseudo_order: Vec<&str> = Vec::new();
180− let mut pseudo_buckets: HashMap<&str, Vec<(&str, &str)>> = HashMap::new();
181− for e in &self.entries {
182− for (selector, body) in &e.pseudo {
183− if body.is_empty() {
184− continue;
185− }
186− let key = selector.as_str();
187− if !pseudo_buckets.contains_key(key) {
188− pseudo_order.push(key);
189− }
190− pseudo_buckets
191− .entry(key)
192− .or_default()
193− .push((e.class_name.as_str(), body.as_str()));
392+ /// The classes given, in the order they were
393+ fn classes(&self) -> impl Iterator<Item = Class> + '_ {
394+ self.entries.iter().map(|e| Class {
395+ name: e.class_name.clone(),
396+ style: e.style,
397+ })
398+ }
399+
400+ /// All generated rules, in three layers (see [`LAYERS`]): the element
401+ /// kinds' defaults in `hl-kind` (`:where(.hl-a)`), the rules for the
402+ /// elements an element prefix picks out inside an element (`@td:`), and
403+ /// a function's scoped `@style`, in `hl-inside`, and the elements' own
404+ /// rules in `htmlang`. They are written in a fixed order, so which rule
405+ /// wins never depends on where in the page an element is: the rules
406+ /// without a prefix, then those under selector prefixes, then each block
407+ /// of at-rules (see [`at_order`]), in which the rules keyed on a parent
408+ /// come first, then the element's own, then its selectors (see
409+ /// [`selector_order`]).
410+ fn to_css_formatted(&self, dev: bool, scoped: &[String]) -> String {
411+ // The defaults: `:where(.hl-a,.hl-b){...}`
412+ let mut kind = String::new();
413+ let mut defaults: Vec<(&str, Vec<&str>)> = Vec::new();
414+ for e in self.entries.iter().filter(|e| !e.defaults.is_empty()) {
415+ match defaults.iter_mut().find(|(body, _)| *body == e.defaults) {
416+ Some((_, classes)) => classes.push(&e.class_name),
417+ None => defaults.push((&e.defaults, vec![&e.class_name])),
418+ }
419+ }
420+ for (body, classes) in defaults {
421+ let classes: Vec<String> = classes.iter().map(|c| format!(".{}", c)).collect();
422+ let selector = format!(":where({})", classes.join(","));
423+ if dev {
424+ kind.push_str(&format!(" {} {{{}}}\n", selector, body));
425+ } else {
426+ kind.push_str(&format!("{}{{{}}}", selector, body));
194427 }
195428 }
196− for selector in &pseudo_order {
197− if let Some(pairs) = pseudo_buckets.get(selector) {
198− emit_grouped_rules(&mut css, pairs, selector, inner_indent, dev);
429+
430+ let mut inside = self.blocks(true, dev);
431+ // A function's scoped `@style`, nested under its class
432+ for block in scoped {
433+ if dev {
434+ inside.push_str(block);
435+ inside.push('\n');
436+ } else {
437+ inside.push_str(&compact_css(block));
199438 }
200439 }
201440
202− // Responsive rules grouped by breakpoint
203− for &(bp_name, bp_width) in BREAKPOINTS {
204− let mut bp_pairs: Vec<(&str, &str)> = Vec::new();
205− for e in &self.entries {
206− for (bp, rule_css) in &e.responsive {
207− if bp == bp_name && !rule_css.is_empty() {
208− bp_pairs.push((e.class_name.as_str(), rule_css.as_str()));
209− }
210− }
441+ let mut css = String::new();
442+ for (name, rules) in [
443+ ("hl-kind", kind),
444+ ("hl-inside", inside),
445+ ("htmlang", self.blocks(false, dev)),
446+ ] {
447+ if rules.is_empty() {
448+ continue;
449+ }
450+ if dev {
451+ css.push_str(&format!("@layer {} {{\n{}}}\n", name, rules));
452+ } else {
453+ css.push_str(&format!("@layer {}{{{}}}", name, rules));
211454 }
212− emit_media_block(
213− &mut css,
214− &format!("@media (min-width: {})", bp_width),
215− &format!("@media(min-width:{})", bp_width),
216− &bp_pairs,
217− "",
218− dev,
219− );
220455 }
456+ css
457+ }
221458
222− // Dark mode rules
223− let dark_pairs: Vec<(&str, &str)> = self
224− .entries
225− .iter()
226− .filter(|e| !e.dark.is_empty())
227− .map(|e| (e.class_name.as_str(), e.dark.as_str()))
228− .collect();
229− emit_media_block(
230− &mut css,
231− "@media (prefers-color-scheme: dark)",
232− "@media(prefers-color-scheme:dark)",
233− &dark_pairs,
234− "",
235− dev,
236− );
237−
238− // Print rules
239− let print_pairs: Vec<(&str, &str)> = self
240− .entries
241− .iter()
242− .filter(|e| !e.print.is_empty())
243− .map(|e| (e.class_name.as_str(), e.print.as_str()))
244− .collect();
245− emit_media_block(
246− &mut css,
247− "@media print",
248− "@media print",
249− &print_pairs,
250− "",
251− dev,
252− );
253−
254− // Motion safe rules
255− let motion_safe_pairs: Vec<(&str, &str)> = self
256− .entries
257− .iter()
258− .filter(|e| !e.motion_safe.is_empty())
259− .map(|e| (e.class_name.as_str(), e.motion_safe.as_str()))
260− .collect();
261− emit_media_block(
262− &mut css,
263− "@media (prefers-reduced-motion: no-preference)",
264− "@media(prefers-reduced-motion:no-preference)",
265− &motion_safe_pairs,
266− "",
267− dev,
268− );
269−
270− // Motion reduce rules
271− let motion_reduce_pairs: Vec<(&str, &str)> = self
272− .entries
273− .iter()
274− .filter(|e| !e.motion_reduce.is_empty())
275− .map(|e| (e.class_name.as_str(), e.motion_reduce.as_str()))
276− .collect();
277− emit_media_block(
278− &mut css,
279− "@media (prefers-reduced-motion: reduce)",
280− "@media(prefers-reduced-motion:reduce)",
281− &motion_reduce_pairs,
282− "",
283− dev,
284− );
285−
286− // Landscape rules
287− let landscape_pairs: Vec<(&str, &str)> = self
288− .entries
289− .iter()
290− .filter(|e| !e.landscape.is_empty())
291− .map(|e| (e.class_name.as_str(), e.landscape.as_str()))
292− .collect();
293− emit_media_block(
294− &mut css,
295− "@media (orientation: landscape)",
296− "@media(orientation:landscape)",
297− &landscape_pairs,
298− "",
299− dev,
300− );
301−
302− // Portrait rules
303− let portrait_pairs: Vec<(&str, &str)> = self
304− .entries
305− .iter()
306− .filter(|e| !e.portrait.is_empty())
307− .map(|e| (e.class_name.as_str(), e.portrait.as_str()))
308− .collect();
309− emit_media_block(
310− &mut css,
311− "@media (orientation: portrait)",
312− "@media(orientation:portrait)",
313− &portrait_pairs,
314− "",
315− dev,
316− );
317−
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()));
459+ /// The rules of every block of at-rules, in order: those for the
460+ /// elements inside (`inside`: rules under an element prefix, each in
461+ /// an `@scope` on its element's class), or the elements' own.
462+ fn blocks(&self, inside: bool, dev: bool) -> String {
463+ let mut css = String::new();
464+ let rules = || {
465+ self.entries.iter().flat_map(move |e| {
466+ e.rules
467+ .iter()
468+ .filter(move |(c, _)| c.inside().is_some() == inside)
469+ .map(move |(c, body)| (e, c, body))
470+ })
471+ };
472+ let mut blocks: Vec<&[usize]> = vec![&[]];
473+ let keyed = self.keyed.iter().filter(|_| !inside);
474+ let every = rules()
475+ .map(|(_, c, _)| c.at.as_slice())
476+ .chain(keyed.map(|(at, _, _)| at.as_slice()));
477+ for at in every {
478+ if !blocks.contains(&at) {
479+ blocks.push(at);
480+ }
481+ }
482+ blocks.sort_by_key(|at| at_order(at));
483+
484+ for at in blocks {
485+ let depth = at.len();
486+ // Readable output indents a rule inside `@layer` and inside
487+ // each at-rule but the first
488+ let indent = if dev {
489+ " ".repeat(depth.max(1))
490+ } else {
491+ String::new()
492+ };
493+ let mut inner = String::new();
494+ // Rules keyed on a parent's class come first: they have the
495+ // specificity of one class, like a class rule, so the child's
496+ // own rules in the block still win
497+ if !inside {
498+ let keyed: Vec<(&str, &str)> = self
499+ .keyed
500+ .iter()
501+ .filter(|(a, _, _)| a.as_slice() == at)
502+ .map(|(_, selector, body)| (selector.as_str(), body.as_str()))
503+ .collect();
504+ emit_selector_rules(&mut inner, &keyed, &indent, dev);
505+ }
506+ // The selector chains of this block, in order
507+ let mut chains: Vec<&[String]> = Vec::new();
508+ for (_, condition, _) in rules() {
509+ if condition.at == at && !chains.contains(&condition.selector.as_slice()) {
510+ chains.push(&condition.selector);
511+ }
512+ }
513+ if inside {
514+ chains.sort_by_cached_key(|chain| inside_order(chain));
515+ // One `@scope` for each root, its rules in the order of
516+ // the chains: rules for one element under two roots (`.a`
517+ // and `.a:hover`) tie on specificity and proximity, so the
518+ // later one wins
519+ let mut scopes: Vec<(String, Vec<(String, &str)>)> = Vec::new();
520+ for chain in chains {
521+ let Some(element) = chain
522+ .iter()
523+ .position(|p| crate::vocab::element_prefix(p).is_some())
524+ else {
525+ continue;
526+ };
527+ for (e, _, body) in
528+ rules().filter(|(_, c, _)| c.at == at && c.selector == chain)
529+ {
530+ let Some((root, target)) = scoped_selector(&e.class_name, chain, element)
531+ else {
532+ continue;
533+ };
534+ match scopes.iter_mut().find(|(r, _)| *r == root) {
535+ Some((_, targets)) => targets.push((target, body)),
536+ None => scopes.push((root, vec![(target, body)])),
537+ }
325538 }
326539 }
540+ let inner_indent = if dev {
541+ format!("{} ", indent)
542+ } else {
543+ String::new()
544+ };
545+ for (root, targets) in scopes {
546+ let targets: Vec<(&str, &str)> =
547+ targets.iter().map(|(t, b)| (t.as_str(), *b)).collect();
548+ inner.push_str(&indent);
549+ inner.push_str(&format!("@scope ({})", root));
550+ inner.push_str(if dev { " {\n" } else { "{" });
551+ emit_selector_rules(&mut inner, &targets, &inner_indent, dev);
552+ inner.push_str(&indent);
553+ inner.push_str(if dev { "}\n" } else { "}" });
554+ }
555+ } else {
556+ chains.sort_by_cached_key(|chain| selector_order(chain));
557+ for chain in chains {
558+ let pairs: Vec<(String, &str)> = rules()
559+ .filter(|(_, c, _)| c.at == at && c.selector == chain)
560+ .map(|(e, _, body)| (selector(&e.class_name, chain), body.as_str()))
561+ .collect();
562+ emit_grouped_rules(&mut inner, &pairs, &indent, dev);
563+ }
564+ }
565+ if inner.is_empty() {
566+ continue;
567+ }
568+ // Each at-rule wraps the next, outermost first
569+ for (level, &rank) in at.iter().enumerate().rev() {
570+ let pad = if dev {
571+ " ".repeat(level)
572+ } else {
573+ String::new()
574+ };
575+ inner = if dev {
576+ format!("{pad}{} {{\n{inner}{pad}}}\n", at_rule(rank, true))
577+ } else {
578+ format!("{}{{{inner}}}", at_rule(rank, false))
579+ };
327580 }
328− emit_media_block(
329− &mut css,
330− &format!("@container (min-width: {})", bp_width),
331− &format!("@container(min-width:{})", bp_width),
332− &cq_pairs,
333− "",
334− dev,
335− );
581+ css.push_str(&inner);
336582 }
337−
338− css.push_str(if dev { "}\n" } else { "}" });
339583 css
340584 }
341585}
342586
343−/// Emit CSS rules from `(class_name, body)` pairs, merging identical bodies
587+/// Emit CSS rules from `(selector, body)` pairs, merging identical bodies
344588/// into a single selector-list rule (e.g. `.a,.b{body}`). The first occurrence
345589/// 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.
348−fn emit_grouped_rules(
349− out: &mut String,
350− pairs: &[(&str, &str)],
351− selector_suffix: &str,
352− indent: &str,
353− dev: bool,
354−) {
590+/// across runs. `indent` is prepended to each rule line.
591+fn emit_grouped_rules(out: &mut String, pairs: &[(String, &str)], indent: &str, dev: bool) {
355592 if pairs.is_empty() {
356593 return;
357594 }
358595 // Group in first-occurrence order.
359596 let mut order: Vec<&str> = Vec::new();
360597 let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
361− for &(name, body) in pairs {
598+ for (selector, body) in pairs {
362599 if body.is_empty() {
363600 continue;
364601 }
365602 if !groups.contains_key(body) {
366603 order.push(body);
367604 }
368− groups.entry(body).or_default().push(name);
605+ groups.entry(body).or_default().push(selector);
369606 }
370607 let sp = if dev { " " } else { "" };
371608 let nl = if dev { "\n" } else { "" };
372609 for body in &order {
373− let names = &groups[body];
374610 out.push_str(indent);
375− for (i, n) in names.iter().enumerate() {
376− if i > 0 {
377− out.push(',');
378− }
379− out.push('.');
380− out.push_str(n);
381− out.push_str(selector_suffix);
382− }
611+ out.push_str(&groups[body].join(","));
383612 out.push_str(sp);
384613 out.push('{');
385614 out.push_str(body);
@@ -388,38 +617,44 @@ fn emit_grouped_rules(
388617 }
389618}
390619
391−/// Emit an `@media` / `@container` block containing grouped class rules.
392−/// Skips the block entirely if no non-empty bodies are present.
393−fn emit_media_block(
394− out: &mut String,
395− header_dev: &str,
396− header_min: &str,
397− pairs: &[(&str, &str)],
398− selector_suffix: &str,
399− dev: bool,
400−) {
401− if pairs.iter().all(|(_, body)| body.is_empty()) {
402− return;
403− }
404− let mut inner = String::new();
405− let inner_indent = if dev { " " } else { "" };
406− emit_grouped_rules(&mut inner, pairs, selector_suffix, inner_indent, dev);
407− if inner.is_empty() {
408− return;
409− }
410− if dev {
411− out.push_str(&format!("{} {{\n{}}}\n", header_dev, inner));
412− } else {
413− out.push_str(&format!("{}{{{}}}", header_min, inner));
620+/// Emit `(selector, body)` rules in their order, merging a run of rules
621+/// with the same body into one rule with a selector list (the order
622+/// matters: two rules may apply to one element).
623+fn emit_selector_rules(out: &mut String, rules: &[(&str, &str)], indent: &str, dev: bool) {
624+ let mut i = 0;
625+ while i < rules.len() {
626+ let body = rules[i].1;
627+ let run = rules[i..].iter().take_while(|(_, b)| *b == body).count();
628+ if !body.is_empty() {
629+ let selectors: Vec<&str> = rules[i..i + run].iter().map(|(s, _)| *s).collect();
630+ out.push_str(indent);
631+ out.push_str(&selectors.join(","));
632+ if dev {
633+ out.push(' ');
634+ }
635+ out.push('{');
636+ out.push_str(body);
637+ out.push('}');
638+ if dev {
639+ out.push('\n');
640+ }
641+ }
642+ i += run;
414643 }
415644}
416645
417646struct GenContext {
418647 dev: bool,
419648 depth: usize,
420− image_count: usize,
421649 has_interactive: bool,
422− has_defer: bool,
650+ /// Writing inside a text element, at any depth: htmlang's own `<div>`s
651+ /// are `<span>`s there, which text can hold.
652+ in_text: bool,
653+ /// How the element whose children are being written lays them out
654+ flow: Flow,
655+ /// Writing the children of a `@picture`, where `@source`'s leading
656+ /// argument is its `srcset`
657+ in_picture: bool,
423658}
424659
425660impl GenContext {
@@ -445,23 +680,26 @@ pub struct CodegenOptions {
445680 pub dev: bool,
446681 pub partial: bool,
447682 pub minify: bool,
448− pub compat: bool,
449683}
450684
451685/// Generate HTML from a parsed document using the given options.
452686pub fn generate_with(doc: &Document, opts: &CodegenOptions) -> String {
687+ generate_with_classes(doc, opts).0
688+}
689+
690+/// [`generate_with`], and the classes the document's styles were given,
691+/// for a check across files that no name stands for two styles.
692+pub fn generate_with_classes(doc: &Document, opts: &CodegenOptions) -> (String, Vec<Class>) {
693+ let mut classes = Vec::new();
453694 let mut html = if opts.partial {
454− generate_partial_inner(doc, opts.dev)
695+ generate_partial_inner(doc, opts.dev, &mut classes)
455696 } else {
456− generate_full_inner(doc, opts.dev)
697+ generate_full_inner(doc, opts.dev, &mut classes)
457698 };
458699 if opts.minify {
459700 html = minify_html(&html);
460701 }
461− if opts.compat {
462− html = add_vendor_prefixes(&html);
463− }
464− html
702+ (html, classes)
465703}
466704
467705pub fn generate(doc: &Document) -> String {
@@ -509,38 +747,6 @@ pub fn generate_minified(doc: &Document) -> String {
509747 )
510748}
511749
512−pub fn generate_compat(doc: &Document) -> String {
513− generate_with(
514− doc,
515− &CodegenOptions {
516− compat: true,
517− ..Default::default()
518− },
519− )
520−}
521−
522−pub fn generate_dev_compat(doc: &Document) -> String {
523− generate_with(
524− doc,
525− &CodegenOptions {
526− dev: true,
527− compat: true,
528− ..Default::default()
529− },
530− )
531−}
532−
533−pub fn generate_minified_compat(doc: &Document) -> String {
534− generate_with(
535− doc,
536− &CodegenOptions {
537− minify: true,
538− compat: true,
539− ..Default::default()
540− },
541− )
542−}
543−
544750fn minify_html(html: &str) -> String {
545751 let mut result = String::with_capacity(html.len());
546752 let mut in_pre = false;
@@ -619,514 +825,132 @@ fn minify_html(html: &str) -> String {
619825 result
620826}
621827
622−/// Add vendor prefixes to CSS within <style> tags for broader browser compatibility.
623−fn add_vendor_prefixes(html: &str) -> String {
624− // Find CSS within <style>...</style> and add vendor prefixes
625− let mut result = String::with_capacity(html.len() + 512);
626− let mut rest = html;
627− while let Some(start) = rest.find("<style>") {
628− let after_tag = start + 7;
629− result.push_str(&rest[..after_tag]);
630− rest = &rest[after_tag..];
631− if let Some(end) = rest.find("</style>") {
632− let css = &rest[..end];
633− result.push_str(&prefix_css(css));
634− result.push_str("</style>");
635− rest = &rest[end + 8..];
636− } else {
637− break;
638− }
639− }
640− result.push_str(rest);
641− result
642−}
643−
644−fn prefix_css(css: &str) -> String {
645− let mut out = String::with_capacity(css.len() + 256);
646− let mut i = 0;
647− let bytes = css.as_bytes();
648− while i < bytes.len() {
649− // Find property declarations
650− if let Some(pos) = css[i..].find('{') {
651− let brace = i + pos;
652− out.push_str(&css[i..=brace]);
653− i = brace + 1;
654− // Process declarations within this block
655− if let Some(close) = css[i..].find('}') {
656− let block = &css[i..i + close];
657− out.push_str(&prefix_declarations(block));
658− out.push('}');
659− i = i + close + 1;
660− }
661− } else {
662− out.push_str(&css[i..]);
663− break;
664− }
665− }
666− out
667−}
668−
669−fn prefix_declarations(block: &str) -> String {
670− let mut out = String::with_capacity(block.len() + 128);
671− for decl in block.split(';') {
672− let decl = decl.trim();
673− if decl.is_empty() {
674− continue;
675− }
676− if let Some((prop, val)) = decl.split_once(':') {
677− let prop = prop.trim();
678− let val = val.trim();
679− match prop {
680− "backdrop-filter" => {
681− out.push_str(&format!("-webkit-backdrop-filter:{};", val));
682− out.push_str(&format!("backdrop-filter:{};", val));
683− }
684− "user-select" => {
685− out.push_str(&format!("-webkit-user-select:{};", val));
686− out.push_str(&format!("-moz-user-select:{};", val));
687− out.push_str(&format!("user-select:{};", val));
688− }
689− "appearance" => {
690− out.push_str(&format!("-webkit-appearance:{};", val));
691− out.push_str(&format!("-moz-appearance:{};", val));
692− out.push_str(&format!("appearance:{};", val));
693− }
694− "background-clip" if val.contains("text") => {
695− out.push_str(&format!("-webkit-background-clip:{};", val));
696− out.push_str(&format!("background-clip:{};", val));
697− }
698− "hyphens" => {
699− out.push_str(&format!("-webkit-hyphens:{};", val));
700− out.push_str(&format!("-ms-hyphens:{};", val));
701− out.push_str(&format!("hyphens:{};", val));
702− }
703− "text-size-adjust" => {
704− out.push_str(&format!("-webkit-text-size-adjust:{};", val));
705− out.push_str(&format!("-ms-text-size-adjust:{};", val));
706− out.push_str(&format!("text-size-adjust:{};", val));
707− }
708− "mask-image" | "mask-size" | "mask-repeat" | "mask-position" => {
709− out.push_str(&format!("-webkit-{}:{};", prop, val));
710− out.push_str(&format!("{}:{};", prop, val));
711− }
712− _ => {
713− out.push_str(decl);
714− out.push(';');
715− }
716− }
717− } else {
718− out.push_str(decl);
719− out.push(';');
720− }
721− }
722− out
723−}
724−
725−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);
832+ };
726833 let mut styles = StyleCollector::new();
727834 let mut ctx = GenContext {
728835 dev,
729836 depth: 0,
730− image_count: 0,
731837 has_interactive: false,
732− has_defer: false,
838+ in_text: false,
839+ flow: Flow::default(),
840+ in_picture: false,
733841 };
734842
735− // Check if document has @main for skip-to-content link
736− let has_main = has_element_kind(&doc.nodes, &ElementKind::Main);
843+ // The page is the root element: `<body>` is a column (the reset makes
844+ // it one, filling the viewport), `@page`'s styles are its class, and
845+ // the page's top-level elements are its children
846+ let root = Element {
847+ kind: ElementKind::El,
848+ attrs: page.styles.clone(),
849+ argument: None,
850+ children: Vec::new(),
851+ line_num: 0,
852+ function: None,
853+ };
854+ let mut own = Flow::of(&root);
855+ let top = Flow::default();
856+ let site = Site {
857+ kind: &root.kind,
858+ parent: &top,
859+ has_overlay_children: holds_overlays(&doc.nodes),
860+ inline: false,
861+ root: true,
862+ };
863+ let body_class = element_class(&root, &site, &mut styles);
864+ own.class = body_class.clone();
865+ ctx.flow = own;
737866
738867 let mut body = String::new();
868+ generate_children(
869+ &doc.nodes,
870+ Some(Layout::Column),
871+ &mut body,
872+ &mut styles,
873+ &mut ctx,
874+ );
739875
740− // Skip-to-content link for accessibility (only when @main exists)
741− if has_main {
742− if dev {
743− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>\n");
744− } else {
745− body.push_str("<a href=\"#hl-main\" class=\"hl-skip\">Skip to content</a>");
746− }
747− }
876+ let element_css = build_element_css(doc, &styles, dev);
877+ let nl = if dev { "\n" } else { "" };
748878
749− for node in &doc.nodes {
750− generate_node(node, None, &mut body, &mut styles, &mut ctx);
879+ let mut meta_html = String::new();
880+ // A `@meta viewport` of the page's own replaces the usual one
881+ if !doc.meta_tags.iter().any(|(name, _)| name == "viewport") {
882+ meta_html.push_str(&format!(
883+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">{}",
884+ nl
885+ ));
886+ }
887+ meta_html.push_str(&format!(
888+ "<title>{}</title>{}",
889+ html_escape(&page.title),
890+ nl
891+ ));
892+ for (name, content) in &doc.meta_tags {
893+ meta_html.push_str(&format!(
894+ "<meta name=\"{}\" content=\"{}\">{}",
895+ html_escape(name),
896+ html_escape(content),
897+ nl
898+ ));
899+ }
900+ for (property, content) in &doc.og_tags {
901+ meta_html.push_str(&format!(
902+ "<meta property=\"og:{}\" content=\"{}\">{}",
903+ html_escape(property),
904+ html_escape(content),
905+ nl
906+ ));
907+ }
908+ if let Some(path) = &page.favicon {
909+ meta_html.push_str(&format!(
910+ "<link rel=\"icon\" href=\"{}\">{}",
911+ html_escape(path),
912+ nl
913+ ));
914+ }
915+ for block in &doc.head_blocks {
916+ meta_html.push_str(block);
917+ meta_html.push_str(nl);
751918 }
752919
753− // Collect external domains for DNS prefetch
754− let dns_prefetch_html = collect_dns_prefetch(&body, dev);
755−
756− let element_css = build_element_css(doc, &styles, dev);
920+ // `@page`'s HTML attributes go on `<html>`
921+ let mut root_attrs = String::new();
922+ for attr in html_attrs(&page.html_attrs) {
923+ push_html_attr(&mut root_attrs, attr);
924+ }
925+ let mut body_attrs = String::new();
926+ emit_class_attr(&mut body_attrs, body_class.as_deref(), None);
757927
758− // Build meta tags string
759− let meta_html = if doc.meta_tags.is_empty() {
760− String::new()
761− } else {
762− let mut m = String::new();
763− for (name, content) in &doc.meta_tags {
764− if dev {
765− m.push_str(&format!(
766− "<meta name=\"{}\" content=\"{}\">\n",
767− html_escape(name),
768− html_escape(content)
769− ));
770− } else {
771− m.push_str(&format!(
772− "<meta name=\"{}\" content=\"{}\">",
773− html_escape(name),
774− html_escape(content)
775− ));
776− }
928+ // Focus-visible CSS for interactive elements (accessibility)
929+ let focus_visible_css = if ctx.has_interactive {
930+ let focusable = ":where(a,button,input,select,textarea):focus-visible";
931+ if dev {
932+ format!(
933+ "{}{} {{ outline: 2px solid currentColor; outline-offset: 2px; }}\n",
934+ OWN_ELEMENTS, focusable
935+ )
936+ } else {
937+ format!(
938+ "{}{}{{outline:2px solid currentColor;outline-offset:2px}}",
939+ OWN_ELEMENTS, focusable
940+ )
777941 }
778− m
779− };
780−
781− // Build OG meta tags
782− let og_html = if doc.og_tags.is_empty() {
783− String::new()
784942 } else {
785− let mut o = String::new();
786− for (property, content) in &doc.og_tags {
787− if dev {
788− o.push_str(&format!(
789− "<meta property=\"og:{}\" content=\"{}\">\n",
790− html_escape(property),
791− html_escape(content)
792− ));
793− } else {
794− o.push_str(&format!(
795− "<meta property=\"og:{}\" content=\"{}\">",
796− html_escape(property),
797− html_escape(content)
798− ));
799− }
800− }
801− o
802− };
803−
804− // Build head blocks string
805− let head_html = if doc.head_blocks.is_empty() {
806943 String::new()
807− } else {
808− let mut h = String::new();
809− for block in &doc.head_blocks {
810− h.push_str(block);
811− if dev {
812− h.push('\n');
813− }
814− }
815− h
816944 };
945+ let reset_css = reset_css(dev, true, &focus_visible_css);
946+ classes.extend(styles.classes());
817947
818− let lang_attr = match &doc.lang {
819− Some(lang) => format!(" lang=\"{}\"", html_escape(lang)),
820− None => String::new(),
821− };
822−
823− let favicon_html = match &doc.favicon {
824− Some(path) => {
825− // Try to read and inline the favicon
826− if let Ok(data) = std::fs::read(path) {
827− let mime = if path.ends_with(".ico") {
828− "image/x-icon"
829− } else if path.ends_with(".png") {
830− "image/png"
831− } else if path.ends_with(".svg") {
832− "image/svg+xml"
833− } else {
834− "image/x-icon"
835− };
836− let b64 = base64_encode(&data);
837− if dev {
838− format!(
839− "<link rel=\"icon\" href=\"data:{};base64,{}\">\n",
840− mime, b64
841− )
842− } else {
843− format!("<link rel=\"icon\" href=\"data:{};base64,{}\">", mime, b64)
844− }
845− } else {
846− // Fall back to href
847− if dev {
848− format!("<link rel=\"icon\" href=\"{}\">\n", html_escape(path))
849− } else {
850− format!("<link rel=\"icon\" href=\"{}\">", html_escape(path))
851− }
852− }
853− }
854− None => String::new(),
855− };
856−
857− // Canonical URL
858− let canonical_html = match &doc.canonical {
859− Some(url) => {
860− if dev {
861− format!("<link rel=\"canonical\" href=\"{}\">\n", html_escape(url))
862− } else {
863− format!("<link rel=\"canonical\" href=\"{}\">", html_escape(url))
864− }
865− }
866− None => String::new(),
867− };
868−
869− // Base URL
870− let base_html = match &doc.base_url {
871− Some(url) => {
872− if dev {
873− format!("<base href=\"{}\">\n", html_escape(url))
874− } else {
875− format!("<base href=\"{}\">", html_escape(url))
876− }
877− }
878− None => String::new(),
879− };
880−
881− // JSON-LD blocks
882− let json_ld_html: String = doc
883− .json_ld_blocks
884− .iter()
885− .map(|block| {
886− if dev {
887− format!(
888− "<script type=\"application/ld+json\">\n{}\n</script>\n",
889− block
890− )
891− } else {
892− format!("<script type=\"application/ld+json\">{}</script>", block)
893− }
894− })
895− .collect();
896−
897− // Manifest link
898− let manifest_html = if let Some(ref manifest) = doc.manifest {
899− let mut json = String::from("{");
900− json.push_str(&format!("\"name\":{},", json_str(&manifest.name)));
901− if let Some(ref short) = manifest.short_name {
902− json.push_str(&format!("\"short_name\":{},", json_str(short)));
903− }
904− json.push_str(&format!("\"start_url\":{},", json_str(&manifest.start_url)));
905− json.push_str(&format!("\"display\":{}", json_str(&manifest.display)));
906− if let Some(ref bg) = manifest.background_color {
907− json.push_str(&format!(",\"background_color\":{}", json_str(bg)));
908− }
909− if let Some(ref tc) = manifest.theme_color {
910− json.push_str(&format!(",\"theme_color\":{}", json_str(tc)));
911− }
912− if let Some(ref desc) = manifest.description {
913− json.push_str(&format!(",\"description\":{}", json_str(desc)));
914− }
915− if !manifest.icons.is_empty() {
916− json.push_str(",\"icons\":[");
917− for (i, (src, sizes)) in manifest.icons.iter().enumerate() {
918− if i > 0 {
919− json.push(',');
920− }
921− json.push_str(&format!(
922− "{{\"src\":{},\"sizes\":{},\"type\":\"image/png\"}}",
923− json_str(src),
924− json_str(sizes)
925− ));
926− }
927− json.push(']');
928− }
929− json.push('}');
930−
931− // Inline the manifest as a data URI
932− let encoded = base64_encode(json.as_bytes());
933− if dev {
934− format!(
935− "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">\n",
936− encoded
937− )
938− } else {
939− format!(
940− "<link rel=\"manifest\" href=\"data:application/manifest+json;base64,{}\">",
941− encoded
942− )
943− }
944− } else {
945− String::new()
946− };
947−
948− // Preload hints (auto-detect fonts from @font-face)
949− let mut preload_html = String::new();
950− for (_, url) in &doc.font_faces {
951− if dev {
952− preload_html.push_str(&format!(
953− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>\n",
954− url
955− ));
956− } else {
957− preload_html.push_str(&format!(
958− "<link rel=\"preload\" href=\"{}\" as=\"font\" type=\"font/woff2\" crossorigin>",
959− url
960− ));
961− }
962− }
963− // Explicit preload hints from the document
964− for hint in &doc.preload_hints {
965− if dev {
966− preload_html.push_str(&format!(
967− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>\n",
968− html_escape(&hint.href),
969− hint.as_type,
970− if hint.crossorigin { " crossorigin" } else { "" }
971− ));
972− } else {
973− preload_html.push_str(&format!(
974− "<link rel=\"preload\" href=\"{}\" as=\"{}\"{}>",
975− html_escape(&hint.href),
976− hint.as_type,
977− if hint.crossorigin { " crossorigin" } else { "" }
978− ));
979− }
980− }
981−
982− // Auto theme-color meta from @theme primary token
983− let theme_color_html = doc
984− .theme_tokens
985− .iter()
986− .find(|(name, _)| name == "primary" || name == "theme-color")
987− .map(|(_, value)| {
988− if dev {
989− format!(
990− "<meta name=\"theme-color\" content=\"{}\">\n",
991− html_escape(value)
992− )
993− } else {
994− format!(
995− "<meta name=\"theme-color\" content=\"{}\">",
996− html_escape(value)
997− )
998− }
999− })
1000− .unwrap_or_default();
1001−
1002− // Focus-visible CSS for interactive elements (accessibility)
1003− let focus_visible_css = if ctx.has_interactive {
1004− if dev {
1005− "a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }\n"
1006− } else {
1007− "a:focus-visible,button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid currentColor;outline-offset:2px}"
1008− }
1009− } else {
1010− ""
1011− };
1012−
1013− // Skip-to-content CSS (visually hidden but accessible)
1014− let skip_link_css = if has_main {
1015− if dev {
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; }\n.hl-skip:focus { left: 8px; top: 8px; width: auto; height: auto; overflow: visible; }\n"
1017− } else {
1018− ".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}"
1019− }
1020− } else {
1021− ""
1022− };
1023−
1024− // Noscript fallback: show deferred content if JS is disabled
1025− let noscript_html = if ctx.has_defer {
1026− if dev {
1027− "<noscript><style>.hl-defer-placeholder { display: none; }</style></noscript>\n"
1028− } else {
1029− "<noscript><style>.hl-defer-placeholder{display:none}</style></noscript>"
1030− }
1031− } else {
1032− ""
1033− };
1034−
1035− let reset_css = reset_css(dev, focus_visible_css, skip_link_css);
1036−
1037− match &doc.page_title {
1038− Some(title) => {
1039− if dev {
1040− format!(
1041− "\
1042−<!DOCTYPE html>
1043−<html{lang_attr}>
1044−<head>
1045−<meta charset=\"utf-8\">
1046−<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
1047−<title>{title}</title>
1048−{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}\
1049−<style>
1050−{reset_css}{element_css}\
1051−</style>
1052−{noscript_html}\
1053−</head>
1054−<body>
1055−{body}\
1056−</body>
1057−</html>
1058−",
1059− title = html_escape(title),
1060− lang_attr = lang_attr,
1061− theme_color_html = theme_color_html,
1062− base_html = base_html,
1063− canonical_html = canonical_html,
1064− manifest_html = manifest_html,
1065− preload_html = preload_html,
1066− dns_prefetch_html = dns_prefetch_html,
1067− meta_html = meta_html,
1068− favicon_html = favicon_html,
1069− json_ld_html = json_ld_html,
1070− head_html = head_html,
1071− og_html = og_html,
1072− reset_css = reset_css,
1073− noscript_html = noscript_html,
1074− element_css = element_css,
1075− body = body,
1076− )
1077− } else {
1078− format!(
1079− "<!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>{noscript_html}</head><body>{body}</body></html>",
1080− title = html_escape(title),
1081− lang_attr = lang_attr,
1082− theme_color_html = theme_color_html,
1083− base_html = base_html,
1084− canonical_html = canonical_html,
1085− manifest_html = manifest_html,
1086− preload_html = preload_html,
1087− dns_prefetch_html = dns_prefetch_html,
1088− meta_html = meta_html,
1089− og_html = og_html,
1090− favicon_html = favicon_html,
1091− json_ld_html = json_ld_html,
1092− head_html = head_html,
1093− reset_css = reset_css,
1094− noscript_html = noscript_html,
1095− element_css = element_css,
1096− body = body,
1097− )
1098− }
1099− }
1100− None => {
1101− if element_css.is_empty() {
1102− body
1103− } else if dev {
1104− format!("<style>\n{}</style>\n{}", element_css, body)
1105− } else {
1106− format!("<style>{}</style>{}", element_css, body)
1107− }
1108− }
1109− }
1110−}
1111−
1112−/// Encode `s` as a JSON string literal (with surrounding quotes).
1113−pub(crate) fn json_str(s: &str) -> String {
1114− let mut out = String::with_capacity(s.len() + 2);
1115− out.push('"');
1116− for c in s.chars() {
1117− match c {
1118− '"' => out.push_str("\\\""),
1119− '\\' => out.push_str("\\\\"),
1120− '\n' => out.push_str("\\n"),
1121− '\r' => out.push_str("\\r"),
1122− '\t' => out.push_str("\\t"),
1123− c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1124− c => out.push(c),
1125− }
1126− }
1127− out.push('"');
1128− out
1129−}
948+ format!(
949+ "<!DOCTYPE html>{nl}<html{root_attrs}>{nl}<head>{nl}<meta charset=\"utf-8\">{nl}\
950+ {meta_html}<style>{nl}{reset_css}{element_css}</style>{nl}</head>{nl}\
951+ <body{body_attrs}>{nl}{body}</body>{nl}</html>{nl}",
952+ )
953+}
1130954
1131955/// Assemble every CSS block the document needs (font faces, custom
1132956/// properties, generated class rules, keyframes, and user CSS). Shared by
@@ -1134,63 +958,16 @@ pub(crate) fn json_str(s: &str) -> String {
1134958fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> String {
1135959 let mut element_css = String::new();
1136960
1137− // @font-face rules, in declaration order
1138− for (name, url) in &doc.font_faces {
1139− let format_hint = if url.ends_with(".woff2") {
1140− " format('woff2')"
1141− } else if url.ends_with(".woff") {
1142− " format('woff')"
1143− } else if url.ends_with(".ttf") {
1144− " format('truetype')"
1145− } else if url.ends_with(".otf") {
1146− " format('opentype')"
1147− } else {
1148− ""
1149− };
1150− if dev {
1151− element_css.push_str(&format!(
1152− "@font-face {{\n font-family: '{}';\n src: url('{}'){};\n font-display: swap;\n}}\n",
1153− name, url, format_hint
1154− ));
1155− } else {
1156− element_css.push_str(&format!(
1157− "@font-face{{font-family:'{}';src:url('{}'){};font-display:swap}}",
1158− name, url, format_hint
1159− ));
1160− }
1161− }
1162−
1163− // Collect all CSS custom properties (explicit `@let --name` / `@theme`
1164− // tokens, plus any auto-extracted repeats) so they can be emitted in a
1165− // single `:root` block below.
961+ // Collect the CSS custom properties declared with `@let --name` so they
962+ // can be emitted in a single `:root` block below.
1166963 let mut root_vars: Vec<(String, String)> = Vec::new();
1167964 for (name, value) in &doc.css_vars {
1168965 root_vars.push((name.clone(), value.clone()));
1169966 }
1170− for (name, value) in &doc.theme_tokens {
1171− let css_name = format!("--{}", name);
1172− if !root_vars.iter().any(|(n, _)| *n == css_name) {
1173− root_vars.push((css_name, value.clone()));
1174− }
1175− }
1176967
1177− // Generated rules always go in `@layer htmlang`, so unlayered user CSS
968+ // Generated rules always go in htmlang's layers, so unlayered user CSS
1178969 // (`@style`, `@raw`) overrides them regardless of specificity.
1179− let styles_css = styles.to_css_formatted(dev);
1180− // Fold literal values declared via `@theme` / `@let --name` back into
1181− // `var(--name)` references so the generated CSS actually uses the
1182− // custom properties emitted in `:root`.
1183− let styles_css = substitute_css_vars(&styles_css, &root_vars);
1184− // Further compress the CSS by auto-extracting any remaining literal
1185− // values that appear often enough for `var(--hN)` references to come out
1186− // shorter overall. Disabled in dev mode to keep the CSS readable.
1187− let styles_css = if dev {
1188− styles_css
1189− } else {
1190− let (new_css, auto_vars) = auto_extract_repeats(&styles_css, &root_vars);
1191− root_vars.extend(auto_vars);
1192− new_css
1193− };
970+ let styles_css = styles.to_css_formatted(dev, &doc.scoped_css);
1194971
1195972 // Emit the :root block first so the cascade picks up the custom
1196973 // properties before the class rules consume them.
@@ -1215,72 +992,121 @@ fn build_element_css(doc: &Document, styles: &StyleCollector, dev: bool) -> Stri
1215992
1216993 element_css.push_str(&styles_css);
1217994
1218− // @keyframes
1219− for (name, kf_body) in &doc.keyframes {
1220− if dev {
1221− element_css.push_str(&format!("@keyframes {} {{\n{}\n}}\n", name, kf_body));
1222− } else {
1223− element_css.push_str(&format!("@keyframes {}{{{}}}", name, kf_body));
1224− }
1225− }
1226−
1227− // Auto-inject skeleton keyframe if skeleton attribute is used
1228− if element_css.contains("hl-skeleton") {
1229− if dev {
1230− element_css.push_str("@keyframes hl-skeleton {\n 0% { background-position: 200% 0; }\n 100% { background-position: -200% 0; }\n}\n");
1231− } else {
1232− element_css.push_str("@keyframes hl-skeleton{0%{background-position:200% 0}100%{background-position:-200% 0}}");
1233− }
1234− }
1235−
1236995 // @style blocks (custom CSS)
1237996 for block in &doc.custom_css {
1238997 if dev {
1239998 element_css.push_str(block);
1240999 element_css.push('\n');
12411000 } else {
1242− let minified: String = block.lines().map(|l| l.trim()).collect::<Vec<_>>().join("");
1243− element_css.push_str(&minified);
1001+ element_css.push_str(&compact_css(block));
12441002 }
12451003 }
12461004
12471005 element_css
12481006}
12491007
1008+/// An `@style` body on one line: each line trimmed, and the lines joined with
1009+/// a space, so a value that goes on over two lines (`margin: 0` then `auto;`)
1010+/// keeps its words apart.
1011+fn compact_css(block: &str) -> String {
1012+ block
1013+ .lines()
1014+ .map(str::trim)
1015+ .filter(|l| !l.is_empty())
1016+ .collect::<Vec<_>>()
1017+ .join(" ")
1018+}
1019+
1020+/// htmlang's own elements: those with a generated class, or the class of a
1021+/// function's scoped `@style`. The reset's rules for elements are kept to
1022+/// them, so `@raw` and `@markdown` content, and the page a fragment is put
1023+/// into, keep their own.
1024+const OWN_ELEMENTS: &str = ":where([class^=\"hl-\"],[class*=\" hl-\"])";
1025+
1026+/// htmlang's cascade layers, from the one that loses to the one that wins:
1027+/// the reset; the defaults of each element's kind (a heading's `margin:0`,
1028+/// a column's `display:flex`); the styles an element gets from an
1029+/// element prefix on an element around it (`@td:padding 8`) and from a
1030+/// function's scoped `@style`; and the element's own styles. So a
1031+/// scope's styles win over the defaults, and what an element says about
1032+/// itself wins over both. CSS outside any layer (`@style`, `@raw`) wins
1033+/// over all of them.
1034+const LAYERS: [&str; 4] = ["hl-reset", "hl-kind", "hl-inside", "htmlang"];
1035+
12501036/// Built-in reset rules, in a layer before `htmlang`: unlayered CSS beats
1251−/// every layer, so an unlayered `a{color:inherit}` would override
1252−/// `@link [color red]`.
1253−fn reset_css(dev: bool, focus_visible_css: &str, skip_link_css: &str) -> String {
1254− let base = if dev {
1255− "*, *::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"
1037+/// every layer, so an unlayered rule here would override the generated
1038+/// ones. A page resets `box-sizing` everywhere and makes `<body>` a column
1039+/// that fills the window; a fragment, which goes into a page it doesn't
1040+/// own, touches only htmlang's own elements. In both, an element htmlang
1041+/// lays out stays hidden while it is `hidden`, a closed `<dialog>` or a
1042+/// popover that isn't showing: its generated `display` would otherwise
1043+/// beat the browser's `display: none`.
1044+fn reset_css(dev: bool, page: bool, focus_visible_css: &str) -> String {
1045+ let own = OWN_ELEMENTS;
1046+ let mut rules = Vec::new();
1047+ if page {
1048+ rules.push(if dev {
1049+ "*, *::before, *::after { box-sizing: border-box; }".to_string()
1050+ } else {
1051+ "*,*::before,*::after{box-sizing:border-box}".to_string()
1052+ });
1053+ rules.push(if dev {
1054+ "body { margin: 0; font-family: system-ui, -apple-system, sans-serif; display: flex; flex-direction: column; min-height: 100dvh; }".to_string()
1055+ } else {
1056+ "body{margin:0;font-family:system-ui,-apple-system,sans-serif;display:flex;flex-direction:column;min-height:100dvh}".to_string()
1057+ });
12561058 } else {
1257− "*,*::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}"
1258− };
1259− let rules = format!("{}{}{}", base, focus_visible_css, skip_link_css);
1059+ rules.push(if dev {
1060+ format!("{own}, {own}::before, {own}::after {{ box-sizing: border-box; }}")
1061+ } else {
1062+ format!("{own},{own}::before,{own}::after{{box-sizing:border-box}}")
1063+ });
1064+ }
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; }}")
1069+ } else {
1070+ format!("{own}:where({hidden}){{display:none!important}}")
1071+ });
1072+ let mut rules = rules.join(if dev { "\n" } else { "" });
1073+ if dev {
1074+ rules.push('\n');
1075+ }
1076+ rules.push_str(focus_visible_css);
12601077 if dev {
1261− format!("@layer hl-reset, htmlang;\n@layer hl-reset {{\n{}}}\n", rules)
1078+ format!(
1079+ "@layer {};\n@layer hl-reset {{\n{}}}\n",
1080+ LAYERS.join(", "),
1081+ rules
1082+ )
12621083 } else {
1263− format!("@layer hl-reset,htmlang;@layer hl-reset{{{}}}", rules)
1084+ format!("@layer {};@layer hl-reset{{{}}}", LAYERS.join(","), rules)
12641085 }
12651086}
12661087
12671088/// Generate an HTML fragment: body + optional <style>, no <html>/<head>/<body> wrapper.
1268−fn generate_partial_inner(doc: &Document, dev: bool) -> String {
1089+fn generate_partial_inner(doc: &Document, dev: bool, classes: &mut Vec<Class>) -> String {
12691090 let mut styles = StyleCollector::new();
12701091 let mut ctx = GenContext {
12711092 dev,
12721093 depth: 0,
1273− image_count: 0,
12741094 has_interactive: false,
1275− has_defer: false,
1095+ in_text: false,
1096+ flow: Flow::default(),
1097+ in_picture: false,
12761098 };
12771099 let mut body = String::new();
12781100
1279− for node in &doc.nodes {
1280− generate_node(node, None, &mut body, &mut styles, &mut ctx);
1281− }
1101+ generate_children(&doc.nodes, None, &mut body, &mut styles, &mut ctx);
12821102
1283− 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, ""));
1108+ }
1109+ classes.extend(styles.classes());
12841110
12851111 if element_css.is_empty() {
12861112 body
@@ -1295,44 +1121,20 @@ fn generate_partial_inner(doc: &Document, dev: bool) -> String {
12951121// Node generation
12961122// ---------------------------------------------------------------------------
12971123
1124+/// Write `node`, which is inside an element with the layout `parent`
1125+/// (`None` at the top of the page).
12981126fn generate_node(
12991127 node: &Node,
1300− parent_kind: Option<&ElementKind>,
1128+ parent: Option<Layout>,
13011129 out: &mut String,
13021130 styles: &mut StyleCollector,
13031131 ctx: &mut GenContext,
13041132) {
13051133 match node {
1306− Node::Element(elem) => generate_element(elem, parent_kind, out, styles, ctx),
1134+ Node::Element(elem) => generate_element(elem, parent, out, styles, ctx),
13071135 Node::Text(segments) => {
1308− let needs_wrap = matches!(
1309− parent_kind,
1310− Some(ElementKind::Row)
1311− | Some(ElementKind::Column)
1312− | Some(ElementKind::El)
1313− | Some(ElementKind::Nav)
1314− | Some(ElementKind::Header)
1315− | Some(ElementKind::Footer)
1316− | Some(ElementKind::Main)
1317− | Some(ElementKind::Section)
1318− | Some(ElementKind::Article)
1319− | Some(ElementKind::Aside)
1320− | Some(ElementKind::ListItem)
1321− | Some(ElementKind::Form)
1322− | Some(ElementKind::Details)
1323− | Some(ElementKind::Figure)
1324− | Some(ElementKind::Blockquote)
1325− | Some(ElementKind::Dialog)
1326− | Some(ElementKind::DefinitionList)
1327− | Some(ElementKind::DefinitionDescription)
1328− | Some(ElementKind::Fieldset)
1329− | Some(ElementKind::Datalist)
1330− | Some(ElementKind::Grid)
1331− | Some(ElementKind::Stack)
1332− | Some(ElementKind::Noscript)
1333− | Some(ElementKind::Address)
1334− | Some(ElementKind::Search)
1335− );
1136+ // In a row, column or grid each line of text is a child
1137+ let needs_wrap = parent.is_some_and(Layout::is_container);
13361138 if needs_wrap {
13371139 out.push_str(&ctx.indent());
13381140 out.push_str("<span>");
@@ -1351,209 +1153,191 @@ fn generate_node(
13511153 }
13521154}
13531155
1354−/// HTML attributes that are passed through to the HTML tag rather than converted to CSS.
1355−const HTML_PASSTHROUGH_ATTRS: &[&str] = &[
1356− "type",
1357− "placeholder",
1358− "name",
1359− "value",
1360− "disabled",
1361− "required",
1362− "checked",
1363− "for",
1364− "action",
1365− "method",
1366− "autocomplete",
1367− "min",
1368− "max",
1369− "step",
1370− "pattern",
1371− "maxlength",
1372− "rows",
1373− "cols",
1374− "multiple",
1375− "alt",
1376− "role",
1377− "tabindex",
1378− "title",
1379− "autofocus",
1380− // Media
1381− "controls",
1382− "autoplay",
1383− "loop",
1384− "muted",
1385− "playsinline",
1386− "poster",
1387− "preload",
1388− // Image optimization
1389− "loading",
1390− "decoding",
1391− // Media src (explicit attribute form)
1392− "src",
1393− // New element attributes
1394− "datetime",
1395− "media",
1396− "sizes",
1397− "srcset",
1398− "list",
1399− // Details
1400− "open",
1401− // Form
1402− "novalidate",
1403− // Progress/Meter
1404− "low",
1405− "high",
1406− "optimum",
1407− // Table
1408− "colspan",
1409− "rowspan",
1410− "scope",
1411− // Popover API
1412− "popover",
1413− "popovertarget",
1414− "popovertargetaction",
1415− // Modern form/input hints
1416− "inputmode",
1417− "enterkeyhint",
1418− // Performance hints
1419− "fetchpriority",
1420− "blocking",
1421− // Global attrs
1422− "translate",
1423− "spellcheck",
1424− // ARIA live regions
1425− "aria-live",
1426− "aria-atomic",
1427− "aria-relevant",
1428−];
1156+/// What goes between two things written one after the other in an element
1157+/// with this layout (`None`: the top of the page): text flows, so its lines
1158+/// and children are joined with a space; in HTML's own layout, and at the
1159+/// top of the page, two lines of text are separated by a line break (a
1160+/// space, except where whitespace is kept, as in `@pre`).
1161+fn separator(layout: Option<Layout>, previous_is_text: bool, next: &Node) -> Option<char> {
1162+ match layout {
1163+ Some(Layout::Text) => Some(' '),
1164+ Some(Layout::Native) | None if previous_is_text && matches!(next, Node::Text(_)) => {
1165+ Some('\n')
1166+ }
1167+ _ => None,
1168+ }
1169+}
14291170
1430−/// Boolean HTML attributes (rendered without a value, e.g., `<input disabled>`).
1431−const BOOLEAN_HTML_ATTRS: &[&str] = &[
1432− "disabled",
1433− "required",
1434− "checked",
1435− "multiple",
1436− "controls",
1437− "autoplay",
1438− "loop",
1439− "muted",
1440− "playsinline",
1441− "open",
1442− "novalidate",
1443− "autofocus",
1444− "defer",
1445− "async",
1446− "nomodule",
1447− // Popover
1448− "popover",
1449−];
1171+/// Write the children of an element (or of a `@fragment`, which has no
1172+/// element of its own) laid out as `layout` (`None`: the top of the page).
1173+/// The first line of an element's text is its first child.
1174+fn generate_children(
1175+ children: &[Node],
1176+ layout: Option<Layout>,
1177+ out: &mut String,
1178+ styles: &mut StyleCollector,
1179+ ctx: &mut GenContext,
1180+) {
1181+ generate_run(children, layout, &mut None, out, styles, ctx);
1182+}
14501183
1451−fn emit_html_passthrough_attrs(out: &mut String, attrs: &[Attribute]) {
1452− for attr in attrs {
1453− let key = attr.key.as_str();
1454− let is_passthrough = HTML_PASSTHROUGH_ATTRS.contains(&key)
1455− || key.starts_with("aria-")
1456− || key.starts_with("data-");
1457− if !is_passthrough {
1184+/// [`generate_children`], with `previous` saying whether what was written
1185+/// last was a line of text (`None`: nothing yet). A `@fragment`'s children
1186+/// are written as if they stood in its place, so its lines are separated
1187+/// from the lines around it like any other lines.
1188+fn generate_run(
1189+ children: &[Node],
1190+ layout: Option<Layout>,
1191+ previous: &mut Option<bool>,
1192+ out: &mut String,
1193+ styles: &mut StyleCollector,
1194+ ctx: &mut GenContext,
1195+) {
1196+ for child in children {
1197+ if let Node::Element(elem) = child
1198+ && elem.kind == ElementKind::Fragment
1199+ {
1200+ generate_run(&elem.children, layout, previous, out, styles, ctx);
14581201 continue;
14591202 }
1460− if BOOLEAN_HTML_ATTRS.contains(&key) && attr.value.is_none() {
1461− out.push(' ');
1462− out.push_str(key);
1463− } else if let Some(val) = &attr.value {
1464− out.push(' ');
1465− out.push_str(key);
1466− out.push_str("=\"");
1467− out.push_str(&html_escape(strip_string_quotes(val)));
1468− out.push('"');
1203+ let start = out.len();
1204+ if let Some(previous_is_text) = *previous
1205+ && let Some(sep) = separator(layout, previous_is_text, child)
1206+ {
1207+ out.push(sep);
1208+ }
1209+ let body = out.len();
1210+ generate_node(child, layout, out, styles, ctx);
1211+ // A child that writes nothing (an empty `@fragment`) takes no
1212+ // separator either, so text never gets two spaces in a row
1213+ if out.len() == body {
1214+ out.truncate(start);
1215+ continue;
14691216 }
1217+ *previous = Some(matches!(child, Node::Text(_)));
14701218 }
14711219}
14721220
1473−/// If the value is wrapped in a single pair of matching quotes (e.g.
1474−/// `"Avatar"`), return the inner content. Quotes act as source-level
1475−/// delimiters in the `.hl` syntax and shouldn't leak into HTML attribute
1476−/// values. Multi-quoted values like `"h h" "s m"` are left unchanged —
1477−/// those are real string tokens (used e.g. by CSS `grid-template-areas`).
1478−fn strip_string_quotes(val: &str) -> &str {
1479− let bytes = val.as_bytes();
1480− if bytes.len() < 2 {
1481− return val;
1482− }
1483− let first = bytes[0];
1484− let last = bytes[bytes.len() - 1];
1485− if (first == b'"' && last == b'"') || (first == b'\'' && last == b'\'') {
1486− let inner = &val[1..val.len() - 1];
1487− if !inner.as_bytes().contains(&first) {
1488− return inner;
1221+/// Emit the element's leading argument as its attribute (`@iframe URL` →
1222+/// `src="URL"`, `@form /submit` → `action="/submit"`, `@link /a` →
1223+/// `href="/a"`), first, before the class. `@image [inline] photo.png` puts
1224+/// the file itself into the page.
1225+fn emit_argument_attr(out: &mut String, elem: &Element, in_picture: bool) {
1226+ let (Some(attr), Some(value)) = (elem.kind.leading_attribute(in_picture), &elem.argument)
1227+ else {
1228+ return;
1229+ };
1230+ // `@image [inline]`'s file is already a `data:` URI (see the parser)
1231+ let value = html_escape(value);
1232+ out.push(' ');
1233+ out.push_str(attr);
1234+ out.push_str("=\"");
1235+ out.push_str(&value);
1236+ out.push('"');
1237+}
1238+
1239+/// A file's bytes as a `data:` URI, its type from its extension.
1240+pub(crate) fn data_uri(path: &str, data: &[u8]) -> String {
1241+ let mime = match path
1242+ .rsplit('.')
1243+ .next()
1244+ .map(str::to_ascii_lowercase)
1245+ .as_deref()
1246+ {
1247+ Some("png") => "image/png",
1248+ Some("jpg" | "jpeg") => "image/jpeg",
1249+ Some("gif") => "image/gif",
1250+ Some("webp") => "image/webp",
1251+ Some("avif") => "image/avif",
1252+ Some("svg") => "image/svg+xml",
1253+ Some("ico") => "image/x-icon",
1254+ _ => "application/octet-stream",
1255+ };
1256+ format!("data:{};base64,{}", mime, base64_encode(data))
1257+}
1258+
1259+/// Emit HTML attributes: `key=value` ones (except `id` / `class`, which
1260+/// are emitted with the generated class) and flags like `required`.
1261+fn emit_html_attrs(out: &mut String, attrs: &[Attribute]) {
1262+ for attr in html_attrs(attrs) {
1263+ let key = attr.key.as_str();
1264+ if key != "id" && key != "class" {
1265+ push_html_attr(out, attr);
14891266 }
14901267 }
1491− val
1268+}
1269+
1270+/// The HTML attributes of `attrs`, `key=value` ones and flags, each name
1271+/// once: the later one wins, as a style does. (Of two attributes with one
1272+/// name, the browser keeps the first, so a bundle's attribute or a
1273+/// function's own would win over one written after it.)
1274+fn html_attrs(attrs: &[Attribute]) -> impl Iterator<Item = &Attribute> {
1275+ let is_html =
1276+ |a: &Attribute| a.html || (a.value.is_none() && crate::vocab::is_html_flag(&a.key));
1277+ attrs.iter().enumerate().filter_map(move |(i, attr)| {
1278+ let later = attrs[i + 1..]
1279+ .iter()
1280+ .any(|other| is_html(other) && other.key == attr.key);
1281+ (is_html(attr) && !later).then_some(attr)
1282+ })
1283+}
1284+
1285+/// ` key="value"`, or ` key` for a flag.
1286+fn push_html_attr(out: &mut String, attr: &Attribute) {
1287+ out.push(' ');
1288+ out.push_str(&attr.key);
1289+ if attr.html {
1290+ out.push_str("=\"");
1291+ // Quoted text has already lost its quotes (see parser.rs)
1292+ out.push_str(&html_escape(attr.value.as_deref().unwrap_or("")));
1293+ out.push('"');
1294+ }
14921295}
14931296
14941297// True if any direct child is `@in-front` or `@behind`. Such children render
14951298// as absolutely positioned overlays, so the parent automatically becomes a
14961299// positioning context (position:relative + isolation:isolate).
14971300fn has_overlay_children(elem: &Element) -> bool {
1498− elem.children.iter().any(|child| {
1301+ holds_overlays(&elem.children)
1302+}
1303+
1304+fn holds_overlays(children: &[Node]) -> bool {
1305+ children.iter().any(|child| {
14991306 matches!(
15001307 child,
1501− Node::Element(e) if matches!(e.kind, ElementKind::InFront | ElementKind::Behind)
1308+ Node::Element(e) if e.kind.is_tag("in-front") || e.kind.is_tag("behind")
15021309 )
15031310 })
15041311}
15051312
15061313fn generate_element(
15071314 elem: &Element,
1508− parent_kind: Option<&ElementKind>,
1315+ parent: Option<Layout>,
15091316 out: &mut String,
15101317 styles: &mut StyleCollector,
15111318 ctx: &mut GenContext,
15121319) {
15131320 // Self-closing elements
1514− if matches!(
1515− elem.kind,
1516− ElementKind::Image
1517− | ElementKind::Input
1518− | ElementKind::HorizontalRule
1519− | ElementKind::Source
1520− | ElementKind::Spacer
1521− ) {
1522− generate_self_closing(elem, parent_kind, out, styles, ctx);
1321+ if elem.kind.layout() == Layout::Void {
1322+ generate_self_closing(elem, parent, out, styles, ctx);
15231323 return;
15241324 }
1525− // @script renders as <script> with raw body content (no HTML escaping)
1526− if elem.kind == ElementKind::Script {
1325+ // A verbatim element (@script) writes its body as it is, with no HTML
1326+ // escaping; it isn't shown, so it has no class (its styles are an error)
1327+ if elem.kind.is_verbatim() {
1328+ let tag = elem.kind.spec().map_or("script", |spec| spec.html);
15271329 out.push_str(&ctx.indent());
1528− out.push_str("<script");
1529− // Pass through src, type, defer, async, etc.
1530− for attr in &elem.attrs {
1531− let key = attr.key.as_str();
1532− if matches!(
1533− key,
1534− "src"
1535− | "type"
1536− | "defer"
1537− | "async"
1538− | "crossorigin"
1539− | "integrity"
1540− | "nomodule"
1541− | "id"
1542− ) {
1543− if let Some(val) = &attr.value {
1544− out.push(' ');
1545− out.push_str(key);
1546− out.push_str("=\"");
1547− out.push_str(&html_escape(val));
1548− out.push('"');
1549− } else {
1550− out.push(' ');
1551− out.push_str(key);
1552− }
1330+ out.push('<');
1331+ out.push_str(tag);
1332+ emit_argument_attr(out, elem, false);
1333+ let (id, class) = extract_id_class(&elem.attrs);
1334+ for (key, value) in [("id", id), ("class", class)] {
1335+ if let Some(value) = value {
1336+ out.push_str(&format!(" {}=\"{}\"", key, html_escape(&value)));
15531337 }
15541338 }
1339+ emit_html_attrs(out, &elem.attrs);
15551340 out.push('>');
1556− // Children are raw JS code, not HTML
15571341 for child in &elem.children {
15581342 match child {
15591343 Node::Text(segments) => {
@@ -1567,46 +1351,10 @@ fn generate_element(
15671351 _ => {}
15681352 }
15691353 }
1570− out.push_str("</script>");
1571− out.push_str(ctx.nl());
1572− return;
1573− }
1574− // @breadcrumb generates semantic <nav aria-label="breadcrumb"><ol>...</ol></nav>
1575− if elem.kind == ElementKind::Breadcrumb {
1576− let gen_class = compute_class(&elem.attrs, &elem.kind, parent_kind, styles, false);
1577− let (id, user_class) = extract_id_class(&elem.attrs);
1578− out.push_str(&ctx.indent());
1579− out.push_str("<nav aria-label=\"breadcrumb\"");
1580− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1581− if let Some(id) = id {
1582− out.push_str(" id=\"");
1583− out.push_str(&html_escape(&id));
1584− out.push('"');
1585− }
1354+ out.push_str("</");
1355+ out.push_str(tag);
15861356 out.push('>');
15871357 out.push_str(ctx.nl());
1588− ctx.depth += 1;
1589− out.push_str(&ctx.indent());
1590− out.push_str("<ol>");
1591− out.push_str(ctx.nl());
1592− ctx.depth += 1;
1593− for child in &elem.children {
1594− out.push_str(&ctx.indent());
1595− out.push_str("<li>");
1596− let mut buf = String::new();
1597− generate_node(child, Some(&elem.kind), &mut buf, styles, ctx);
1598− out.push_str(buf.trim());
1599− out.push_str("</li>");
1600− out.push_str(ctx.nl());
1601− }
1602− ctx.depth -= 1;
1603− out.push_str(&ctx.indent());
1604− out.push_str("</ol>");
1605− out.push_str(ctx.nl());
1606− ctx.depth -= 1;
1607− out.push_str(&ctx.indent());
1608− out.push_str("</nav>");
1609− out.push_str(ctx.nl());
16101358 return;
16111359 }
16121360 if elem.kind == ElementKind::Children {
@@ -1616,209 +1364,38 @@ fn generate_element(
16161364 return;
16171365 }
16181366 if elem.kind == ElementKind::Fragment {
1619− // Render children without a wrapper element
1620− for child in &elem.children {
1621− generate_node(child, parent_kind, out, styles, ctx);
1622− }
1367+ // Render children without a wrapper element, as if they were
1368+ // written where the fragment is
1369+ generate_children(&elem.children, parent, out, styles, ctx);
16231370 return;
16241371 }
16251372
1373+ let mut own = Flow::of(elem);
16261374 let tag = match &elem.kind {
1627− ElementKind::Row
1628− | ElementKind::Column
1629− | ElementKind::El
1630− | ElementKind::Grid
1631− | ElementKind::Stack
1632− | ElementKind::InFront
1633− | ElementKind::Behind => "div",
1375+ ElementKind::Row | ElementKind::El => "div",
16341376 ElementKind::Text => "span",
16351377 ElementKind::Paragraph => "p",
16361378 ElementKind::Link => "a",
1637− ElementKind::Button => "button",
1638− ElementKind::Select => "select",
1639− ElementKind::Textarea => "textarea",
1640− ElementKind::Option => "option",
1641− ElementKind::Label => "label",
1642− // Semantic elements
1643− ElementKind::Nav => "nav",
1644− ElementKind::Header => "header",
1645− ElementKind::Footer => "footer",
1646− ElementKind::Main => "main",
1647− ElementKind::Section => "section",
1648− ElementKind::Article => "article",
1649− ElementKind::Aside => "aside",
1650− // List
1651− ElementKind::List => {
1652− if elem.attrs.iter().any(|a| a.key == "ordered") {
1653− "ol"
1654− } else {
1655− "ul"
1656− }
1657− }
1658− ElementKind::ListItem => "li",
1659− // Table
1660− ElementKind::Table => "table",
1661− ElementKind::TableHead => "thead",
1662− ElementKind::TableBody => "tbody",
1663− ElementKind::TableRow => "tr",
1664− ElementKind::TableCell => "td",
1665− ElementKind::TableHeaderCell => "th",
1666− // Media
1667− ElementKind::Video => "video",
1668− ElementKind::Audio => "audio",
1669− // Additional semantic elements
1670− ElementKind::Form => "form",
1671− ElementKind::Details => "details",
1672− ElementKind::Summary => "summary",
1673− ElementKind::Blockquote => "blockquote",
1674− ElementKind::Cite => "cite",
1675− ElementKind::Code => "code",
1676− ElementKind::Pre => "pre",
1677− ElementKind::Figure => "figure",
1678− ElementKind::FigCaption => "figcaption",
1679− ElementKind::Progress => "progress",
1680− ElementKind::Meter => "meter",
1681− // New elements
1682− ElementKind::Dialog => "dialog",
1683− ElementKind::DefinitionList => "dl",
1684− ElementKind::DefinitionTerm => "dt",
1685− ElementKind::DefinitionDescription => "dd",
1686− ElementKind::Fieldset => "fieldset",
1687− ElementKind::Legend => "legend",
1688− ElementKind::Picture => "picture",
1689− ElementKind::Time => "time",
1690− ElementKind::Mark => "mark",
1691− ElementKind::Kbd => "kbd",
1692− ElementKind::Abbr => "abbr",
1693− ElementKind::Datalist => "datalist",
1694− ElementKind::Iframe => "iframe",
1695− ElementKind::Output => "output",
1696− ElementKind::Canvas => "canvas",
1697− ElementKind::Badge => "span",
1698− ElementKind::Tooltip => "span",
1699− ElementKind::Avatar => "div",
1700− ElementKind::Carousel => "div",
1701− ElementKind::Chip => "span",
1702− ElementKind::Tag => "span",
1703− ElementKind::Noscript => "noscript",
1704− ElementKind::Address => "address",
1705− ElementKind::Search => "search",
1706− // Heading elements
1707− ElementKind::H1 => "h1",
1708− ElementKind::H2 => "h2",
1709− ElementKind::H3 => "h3",
1710− ElementKind::H4 => "h4",
1711− ElementKind::H5 => "h5",
1712− ElementKind::H6 => "h6",
1713− ElementKind::Image
1714− | ElementKind::Input
1715− | ElementKind::HorizontalRule
1716− | ElementKind::Children
1717− | ElementKind::Slot(_)
1718− | ElementKind::Fragment
1719− | ElementKind::Source
1720− | ElementKind::Spacer
1721− | ElementKind::Script
1722− | ElementKind::Breadcrumb => unreachable!(),
1723− };
1724−
1725− let kind_label = match elem.kind {
1726− ElementKind::Row => "row",
1727− ElementKind::Column => "column",
1728− ElementKind::El => "el",
1729− ElementKind::Text => "text",
1730− ElementKind::Paragraph => "paragraph",
1731− ElementKind::Link => "link",
1732− ElementKind::Button => "button",
1733− ElementKind::Select => "select",
1734− ElementKind::Textarea => "textarea",
1735− ElementKind::Option => "option",
1736− ElementKind::Label => "label",
1737− ElementKind::Nav => "nav",
1738− ElementKind::Header => "header",
1739− ElementKind::Footer => "footer",
1740− ElementKind::Main => "main",
1741− ElementKind::Section => "section",
1742− ElementKind::Article => "article",
1743− ElementKind::Aside => "aside",
1744− ElementKind::List => "list",
1745− ElementKind::ListItem => "item",
1746− ElementKind::Table => "table",
1747− ElementKind::TableHead => "thead",
1748− ElementKind::TableBody => "tbody",
1749− ElementKind::TableRow => "tr",
1750− ElementKind::TableCell => "td",
1751− ElementKind::TableHeaderCell => "th",
1752− ElementKind::Video => "video",
1753− ElementKind::Audio => "audio",
1754− ElementKind::Form => "form",
1755− ElementKind::Details => "details",
1756− ElementKind::Summary => "summary",
1757− ElementKind::Blockquote => "blockquote",
1758− ElementKind::Cite => "cite",
1759− ElementKind::Code => "code",
1760− ElementKind::Pre => "pre",
1761− ElementKind::Figure => "figure",
1762− ElementKind::FigCaption => "figcaption",
1763− ElementKind::Fragment => "fragment",
1764− ElementKind::Dialog => "dialog",
1765− ElementKind::DefinitionList => "dl",
1766− ElementKind::DefinitionTerm => "dt",
1767− ElementKind::DefinitionDescription => "dd",
1768− ElementKind::Fieldset => "fieldset",
1769− ElementKind::Legend => "legend",
1770− ElementKind::Picture => "picture",
1771− ElementKind::Time => "time",
1772− ElementKind::Mark => "mark",
1773− ElementKind::Kbd => "kbd",
1774− ElementKind::Abbr => "abbr",
1775− ElementKind::Datalist => "datalist",
1776− ElementKind::Iframe => "iframe",
1777− ElementKind::Output => "output",
1778− ElementKind::Canvas => "canvas",
1779− ElementKind::Grid => "grid",
1780− ElementKind::Stack => "stack",
1781− ElementKind::Badge => "badge",
1782− ElementKind::Tooltip => "tooltip",
1783− ElementKind::Avatar => "avatar",
1784− ElementKind::Carousel => "carousel",
1785− ElementKind::Chip => "chip",
1786− ElementKind::Tag => "tag",
1787− ElementKind::Noscript => "noscript",
1788− ElementKind::Address => "address",
1789− ElementKind::Search => "search",
1790− ElementKind::InFront => "in-front",
1791− ElementKind::Behind => "behind",
1792− ElementKind::H1 => "h1",
1793− ElementKind::H2 => "h2",
1794− ElementKind::H3 => "h3",
1795− ElementKind::H4 => "h4",
1796− ElementKind::H5 => "h5",
1797− ElementKind::H6 => "h6",
1379+ ElementKind::Tag(spec) => spec.html,
17981380 _ => "",
17991381 };
1382+ // Inside text, htmlang's own `<div>` is a `<span>`, which text can
1383+ // hold (directly in text, a row, column or grid is also laid out
1384+ // inline: see `Site::inline`)
1385+ let in_text = ctx.in_text || parent == Some(Layout::Text);
1386+ let tag = if in_text && tag == "div" { "span" } else { tag };
1387+ let kind_label = elem.kind.name();
18001388
18011389 // Track interactive elements for focus-visible CSS
1802− if matches!(
1803− elem.kind,
1804− ElementKind::Link
1805− | ElementKind::Button
1806− | ElementKind::Input
1807− | ElementKind::Select
1808− | ElementKind::Textarea
1809− ) {
1390+ if elem.kind == ElementKind::Link
1391+ || matches!(kind_label, "button" | "input" | "select" | "textarea")
1392+ {
18101393 ctx.has_interactive = true;
18111394 }
18121395
18131396 // Compute CSS for each state and get a class name
1814− let overlay_children = has_overlay_children(elem);
1815− let gen_class = compute_class(
1816− &elem.attrs,
1817− &elem.kind,
1818− parent_kind,
1819− styles,
1820− overlay_children,
1821− );
1397+ let gen_class = element_class(elem, &Site::new(elem, parent, &ctx.flow), styles);
1398+ own.class = gen_class.clone();
18221399 let (id, user_class) = extract_id_class(&elem.attrs);
18231400
18241401 if ctx.dev && elem.line_num > 0 {
@@ -1832,85 +1409,9 @@ fn generate_element(
18321409 out.push('<');
18331410 out.push_str(tag);
18341411
1835− // @main gets id="hl-main" for skip-to-content link (unless user set an id)
1836− if elem.kind == ElementKind::Main && id.is_none() {
1837− out.push_str(" id=\"hl-main\"");
1838− }
1839−
1840− if elem.kind == ElementKind::Link
1841− && let Some(url) = &elem.argument
1842− {
1843− out.push_str(" href=\"");
1844− out.push_str(&html_escape(url));
1845− out.push('"');
1846− // Auto rel="noopener noreferrer" and target="_blank" for external links
1847− let is_external = url.starts_with("http://") || url.starts_with("https://");
1848− if is_external {
1849− let has_rel = elem.attrs.iter().any(|a| a.key == "rel");
1850− let has_target = elem.attrs.iter().any(|a| a.key == "target");
1851− if !has_rel {
1852− out.push_str(" rel=\"noopener noreferrer\"");
1853− }
1854− if !has_target {
1855− out.push_str(" target=\"_blank\"");
1856− }
1857− }
1858− }
1859−
1860− // Video/Audio src
1861− if matches!(elem.kind, ElementKind::Video | ElementKind::Audio)
1862− && let Some(src) = &elem.argument
1863− {
1864− out.push_str(" src=\"");
1865− out.push_str(&html_escape(src));
1866− out.push('"');
1867− }
1868−
1869− // Form action
1870− if elem.kind == ElementKind::Form
1871− && let Some(action) = &elem.argument
1872− {
1873− out.push_str(" action=\"");
1874− out.push_str(&html_escape(action));
1875− out.push('"');
1876− }
1877−
1878− // Iframe src
1879− if elem.kind == ElementKind::Iframe
1880− && let Some(src) = &elem.argument
1881− {
1882− out.push_str(" src=\"");
1883− out.push_str(&html_escape(src));
1884− out.push('"');
1885− }
1886−
1887− // Tooltip title
1888− if elem.kind == ElementKind::Tooltip
1889− && let Some(text) = &elem.argument
1890− {
1891− out.push_str(" title=\"");
1892− out.push_str(&html_escape(text));
1893− out.push('"');
1894− }
1412+ emit_argument_attr(out, elem, ctx.in_picture);
18951413
1896− // Critical CSS: inline styles directly instead of using a class
1897− let is_critical = elem.attrs.iter().any(|a| a.key == "critical");
1898− if is_critical {
1899− let inline_css = attrs_to_css(&elem.attrs, "", &elem.kind, parent_kind, overlay_children);
1900− if !inline_css.is_empty() {
1901− out.push_str(" style=\"");
1902− out.push_str(&html_escape(&inline_css));
1903− out.push('"');
1904− }
1905− // Still use class for non-base styles (pseudo, responsive, etc.)
1906− if gen_class.as_deref().is_some_and(|c| !c.is_empty()) {
1907− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1908− } else if let Some(ref uc) = user_class {
1909− emit_class_attr(out, None, Some(uc));
1910− }
1911− } else {
1912− emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
1913− }
1414+ emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
19141415
19151416 if let Some(id) = id {
19161417 out.push_str(" id=\"");
@@ -1918,7 +1419,7 @@ fn generate_element(
19181419 out.push('"');
19191420 }
19201421
1921− emit_html_passthrough_attrs(out, &elem.attrs);
1422+ emit_html_attrs(out, &elem.attrs);
19221423
19231424 // Source map attributes in dev mode
19241425 if ctx.dev && elem.line_num > 0 {
@@ -1929,36 +1430,27 @@ fn generate_element(
19291430 }
19301431
19311432 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");
19321438 out.push_str(ctx.nl());
19331439
1934− // Inline text argument
1935− if renders_argument_as_text(&elem.kind)
1936− && let Some(text) = &elem.argument
1937− {
1938− out.push_str(&html_escape(text));
1939− }
1940−
1941− // Children
1440+ let layout = elem.kind.layout();
19421441 ctx.depth += 1;
1943− let is_paragraph = matches!(
1944− elem.kind,
1945− ElementKind::Paragraph
1946− | ElementKind::H1
1947− | ElementKind::H2
1948− | ElementKind::H3
1949− | ElementKind::H4
1950− | ElementKind::H5
1951− | ElementKind::H6
1952− );
1953− for (i, child) in elem.children.iter().enumerate() {
1954− generate_node(child, Some(&elem.kind), out, styles, ctx);
1955− if is_paragraph && i < elem.children.len() - 1 {
1956− out.push(' ');
1957− }
1958− }
1442+ let outer_in_text = ctx.in_text;
1443+ ctx.in_text = in_text || layout == Layout::Text;
1444+ let outer_flow = std::mem::replace(&mut ctx.flow, own);
1445+ let outer_picture = std::mem::replace(&mut ctx.in_picture, elem.kind.is_tag("picture"));
1446+ generate_children(&elem.children, Some(layout), out, styles, ctx);
1447+ ctx.in_picture = outer_picture;
1448+ ctx.flow = outer_flow;
1449+ ctx.in_text = outer_in_text;
19591450 ctx.depth -= 1;
19601451
19611452 out.push_str(&ctx.indent());
1453+ ctx.dev = outer_dev;
19621454 out.push_str("</");
19631455 out.push_str(tag);
19641456 out.push('>');
@@ -1967,21 +1459,18 @@ fn generate_element(
19671459
19681460fn generate_self_closing(
19691461 elem: &Element,
1970− parent_kind: Option<&ElementKind>,
1462+ parent: Option<Layout>,
19711463 out: &mut String,
19721464 styles: &mut StyleCollector,
19731465 ctx: &mut GenContext,
19741466) {
1975− 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);
19761468 let (id, user_class) = extract_id_class(&elem.attrs);
19771469
1978− let (tag, kind_label) = match elem.kind {
1470+ let (tag, kind_label) = match &elem.kind {
19791471 ElementKind::Image => ("img", "image"),
1980− ElementKind::Input => ("input", "input"),
1981− ElementKind::HorizontalRule => ("hr", "hr"),
1982− ElementKind::Source => ("source", "source"),
1983− ElementKind::Spacer => ("div", "spacer"),
1984− _ => unreachable!(),
1472+ ElementKind::Tag(spec) => (spec.html, spec.name),
1473+ _ => unreachable!("not a void element: {:?}", elem.kind),
19851474 };
19861475
19871476 if ctx.dev && elem.line_num > 0 {
@@ -1994,43 +1483,7 @@ fn generate_self_closing(
19941483 out.push_str(&ctx.indent());
19951484 out.push('<');
19961485 out.push_str(tag);
1997−
1998− // Image src (with optional non-SVG base64 inlining)
1999− if elem.kind == ElementKind::Image {
2000− let src = elem.argument.as_deref().unwrap_or("");
2001− let is_inline = elem.attrs.iter().any(|a| a.key == "inline");
2002− if is_inline && !src.is_empty() && !src.ends_with(".svg") {
2003− let mime = if src.ends_with(".png") {
2004− "image/png"
2005− } else if src.ends_with(".jpg") || src.ends_with(".jpeg") {
2006− "image/jpeg"
2007− } else if src.ends_with(".gif") {
2008− "image/gif"
2009− } else if src.ends_with(".webp") {
2010− "image/webp"
2011− } else if src.ends_with(".avif") {
2012− "image/avif"
2013− } else {
2014− "application/octet-stream"
2015− };
2016− if let Ok(data) = std::fs::read(src) {
2017− let b64 = base64_encode(&data);
2018− out.push_str(" src=\"data:");
2019− out.push_str(mime);
2020− out.push_str(";base64,");
2021− out.push_str(&b64);
2022− out.push('"');
2023− } else {
2024− out.push_str(" src=\"");
2025− out.push_str(&html_escape(src));
2026− out.push('"');
2027− }
2028− } else {
2029− out.push_str(" src=\"");
2030− out.push_str(&html_escape(src));
2031− out.push('"');
2032− }
2033− }
1486+ emit_argument_attr(out, elem, ctx.in_picture);
20341487
20351488 emit_class_attr(out, gen_class.as_deref(), user_class.as_deref());
20361489
@@ -2040,7 +1493,7 @@ fn generate_self_closing(
20401493 out.push('"');
20411494 }
20421495
2043− emit_html_passthrough_attrs(out, &elem.attrs);
1496+ emit_html_attrs(out, &elem.attrs);
20441497
20451498 // Source map attributes in dev mode (self-closing)
20461499 if ctx.dev && elem.line_num > 0 {
@@ -2050,93 +1503,6 @@ fn generate_self_closing(
20501503 ));
20511504 }
20521505
2053− // Image optimization: auto-add loading="lazy" and decoding="async"
2054− if elem.kind == ElementKind::Image {
2055− // SVG inlining: @image [inline] logo.svg
2056− if elem.attrs.iter().any(|a| a.key == "inline")
2057− && let Some(src) = &elem.argument
2058− && src.ends_with(".svg")
2059− && let Ok(svg_content) = std::fs::read_to_string(src)
2060− {
2061− // Close the tag we opened, then emit inline SVG instead
2062− out.truncate(out.rfind('<').unwrap_or(0));
2063− out.push_str(&ctx.indent());
2064− out.push_str(svg_content.trim());
2065− out.push_str(ctx.nl());
2066− return;
2067− }
2068− // Responsive srcset: @image photo.jpg [responsive 400 800 1200]
2069− let responsive_attr = elem.attrs.iter().find(|a| a.key == "responsive");
2070− if let Some(resp) = responsive_attr
2071− && let Some(ref sizes_str) = resp.value
2072− {
2073− let widths: Vec<&str> = sizes_str.split_whitespace().collect();
2074− if !widths.is_empty() {
2075− let src = elem.argument.as_deref().unwrap_or("");
2076− if !src.is_empty() {
2077− // Generate srcset with width descriptors
2078− // Convention: file-{width}.ext (e.g., photo-400.jpg)
2079− let dot_pos = src.rfind('.').unwrap_or(src.len());
2080− let base = &src[..dot_pos];
2081− let ext = &src[dot_pos..];
2082− let mut srcset_parts = Vec::new();
2083− for w in &widths {
2084− srcset_parts.push(format!("{}-{}{} {}w", base, w, ext, w));
2085− }
2086− out.push_str(" srcset=\"");
2087− out.push_str(&srcset_parts.join(", "));
2088− out.push('"');
2089− // Generate sizes attribute
2090− let max_width = widths.last().unwrap_or(&"100vw");
2091− out.push_str(&format!(
2092− " sizes=\"(max-width: {}px) 100vw, {}px\"",
2093− max_width, max_width
2094− ));
2095− }
2096− }
2097− }
2098−
2099− // Auto image dimensions: read local image file to inject width/height + aspect-ratio
2100− let has_width = elem.attrs.iter().any(|a| a.key == "width");
2101− let has_height = elem.attrs.iter().any(|a| a.key == "height");
2102− if (!has_width || !has_height)
2103− && let Some(ref src) = elem.argument
2104− && !src.starts_with("http://")
2105− && !src.starts_with("https://")
2106− && !src.starts_with("data:")
2107− && let Some((w, h)) = read_image_dimensions(src)
2108− {
2109− // Intrinsic size attributes only when neither dimension is set in
2110− // CSS; with one CSS dimension, a leftover intrinsic attribute for
2111− // the other would distort the image (200 wide but 1000 tall).
2112− if !has_width && !has_height {
2113− out.push_str(&format!(" width=\"{}\" height=\"{}\"", w, h));
2114− }
2115− // Auto aspect-ratio to prevent CLS
2116− if !elem.attrs.iter().any(|a| a.key == "aspect-ratio") {
2117− out.push_str(&format!(" style=\"aspect-ratio:{}/{}\"", w, h));
2118− }
2119− }
2120−
2121− // Smart image loading: first 3 images get fetchpriority="high" (above the fold),
2122− // subsequent images get loading="lazy" + decoding="async"
2123− ctx.image_count += 1;
2124− if ctx.image_count <= 3 {
2125− // Above-the-fold: eager loading with high priority
2126− if !elem.attrs.iter().any(|a| a.key == "fetchpriority") {
2127− out.push_str(" fetchpriority=\"high\"");
2128− }
2129− } else {
2130− // Below-the-fold: lazy loading
2131− if !elem.attrs.iter().any(|a| a.key == "loading") {
2132− out.push_str(" loading=\"lazy\"");
2133− }
2134− if !elem.attrs.iter().any(|a| a.key == "decoding") {
2135− out.push_str(" decoding=\"async\"");
2136− }
2137− }
2138− }
2139−
21401506 out.push('>');
21411507 out.push_str(ctx.nl());
21421508}
@@ -2152,7 +1518,10 @@ fn generate_text_segments(
21521518 TextSegment::Plain(text) => out.push_str(&html_escape(text)),
21531519 TextSegment::Inline(elem) => {
21541520 let mut buf = String::new();
2155− generate_element(elem, None, &mut buf, styles, ctx);
1521+ // An element inside a line of text is in text
1522+ let outer_flow = std::mem::take(&mut ctx.flow);
1523+ generate_element(elem, Some(Layout::Text), &mut buf, styles, ctx);
1524+ ctx.flow = outer_flow;
21561525 out.push_str(buf.trim_end());
21571526 }
21581527 }
@@ -2165,143 +1534,97 @@ fn generate_text_segments(
21651534
21661535fn compute_class(
21671536 attrs: &[Attribute],
2168− kind: &ElementKind,
2169− parent_kind: Option<&ElementKind>,
1537+ site: &Site,
21701538 styles: &mut StyleCollector,
2171− has_overlay_children: bool,
1539+ distinct: String,
21721540) -> Option<String> {
2173− let base = attrs_to_css(attrs, "", kind, parent_kind, has_overlay_children);
2174−
2175− // Collect pseudo-state overrides
2176− let mut pseudo = Vec::new();
2177− for &(prefix, selector) in PSEUDO_PREFIXES {
2178− let css = attrs_to_css(attrs, prefix, kind, parent_kind, has_overlay_children);
2179− if !css.is_empty() {
2180− pseudo.push((selector.to_string(), css));
2181− }
2182− }
2183−
2184− // Auto-add ::-webkit-scrollbar pseudo for no-scrollbar attribute
2185− if attrs.iter().any(|a| a.key == "no-scrollbar") {
2186− pseudo.push((
2187− "::-webkit-scrollbar".to_string(),
2188− "display:none;".to_string(),
2189− ));
2190− }
2191−
2192− // Collect nth:EXPR: dynamic pseudo selectors
2193− let mut nth_prefixes: Vec<String> = Vec::new();
2194− for attr in attrs {
2195− if attr.key.starts_with("nth:") {
2196− let rest = &attr.key[4..];
2197− if let Some(colon_pos) = rest.find(':') {
2198− let prefix = format!("nth:{}:", &rest[..colon_pos]);
2199− if !nth_prefixes.contains(&prefix) {
2200− nth_prefixes.push(prefix);
2201− }
2202− }
2203− }
2204− }
2205− for prefix in &nth_prefixes {
2206− let expr = &prefix[4..prefix.len() - 1];
2207− let selector = format!(":nth-child({})", expr);
2208− let css = attrs_to_css(attrs, prefix, kind, parent_kind, has_overlay_children);
2209− if !css.is_empty() {
2210− pseudo.push((selector, css));
1541+ // Every condition an attribute is under, and none
1542+ let mut conditions = vec![Condition::default()];
1543+ for attr in attrs.iter().filter(|a| !a.html) {
1544+ let (condition, _) = Condition::of(&attr.key);
1545+ if !conditions.contains(&condition) {
1546+ conditions.push(condition);
22111547 }
22121548 }
1549+ // Dedupe: if a property is declared twice within a single rule, keep only
1550+ // the last occurrence.
1551+ let rules: Vec<(Condition, String)> = conditions
1552+ .into_iter()
1553+ .map(|condition| {
1554+ let css = dedupe_declarations(&attrs_to_css(attrs, &condition, site));
1555+ (condition, css)
1556+ })
1557+ .collect();
1558+ // The kind's defaults, less what the element sets itself (a user
1559+ // `[list-style disc]` wins over the default `list-style:none` anyway,
1560+ // so there is no need to ship both)
1561+ let own = rules
1562+ .iter()
1563+ .find(|(condition, _)| *condition == Condition::default())
1564+ .map_or("", |(_, css)| css.as_str());
1565+ let own: Vec<&str> = declarations(own).map(|(name, _)| name).collect();
1566+ let defaults: String = declarations(&dedupe_declarations(&default_css(site)))
1567+ .filter(|(name, _)| !own.contains(name))
1568+ .map(|(_, declaration)| declaration)
1569+ .collect();
1570+ styles.get_class(defaults, rules, distinct)
1571+}
22131572
2214− // Collect has(...): dynamic pseudo selectors
2215− let mut has_prefixes: Vec<String> = Vec::new();
2216− for attr in attrs {
2217− if attr.key.starts_with("has(")
2218− && let Some(close) = attr.key.find("):")
2219− {
2220− let prefix = format!("{}:", &attr.key[..close + 1]);
2221− if !has_prefixes.contains(&prefix) {
2222− has_prefixes.push(prefix);
2223− }
2224− }
1573+/// The defaults of an element's kind where it is: an overlay's positioning
1574+/// context, its layout, and its kind's own CSS (a heading's `margin:0`).
1575+fn default_css(site: &Site) -> String {
1576+ let mut css = String::new();
1577+ // Elements with @in-front / @behind children become positioning
1578+ // contexts
1579+ if site.has_overlay_children {
1580+ css.push_str("position:relative;isolation:isolate;");
22251581 }
2226− for prefix in &has_prefixes {
2227− let inner = &prefix[4..prefix.len() - 2]; // extract selector from has(selector):
2228− let selector = format!(":has({})", inner);
2229− let css = attrs_to_css(attrs, prefix, kind, parent_kind, has_overlay_children);
2230− if !css.is_empty() {
2231− pseudo.push((selector, css));
2232− }
1582+ if !site.root {
1583+ css.push_str(layout_css(site.kind.layout(), site.inline));
22331584 }
1585+ css.push_str(site.kind.css());
1586+ css
1587+}
22341588
2235− // Collect responsive overrides
2236− let mut responsive = Vec::new();
2237− for &(bp_name, _) in BREAKPOINTS {
2238− let prefix = format!("{}:", bp_name);
2239− let css = attrs_to_css(attrs, &prefix, kind, parent_kind, has_overlay_children);
2240− if !css.is_empty() {
2241− responsive.push((bp_name.to_string(), 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() {
1596+ return None;
22421597 }
2243− }
2244−
2245− // Collect container query overrides
2246− let mut container = Vec::new();
2247− for &(bp_name, _) in BREAKPOINTS {
2248− let prefix = format!("cq-{}:", bp_name);
2249− let css = attrs_to_css(attrs, &prefix, kind, parent_kind, has_overlay_children);
2250− if !css.is_empty() {
2251− container.push((bp_name.to_string(), css));
1598+ let (mut depth, mut quote, mut escaped) = (0i32, None, false);
1599+ let mut end = rest.len();
1600+ for (i, c) in rest.char_indices() {
1601+ match c {
1602+ _ if escaped => escaped = false,
1603+ '\\' => escaped = true,
1604+ c if Some(c) == quote => quote = None,
1605+ _ if quote.is_some() => {}
1606+ '"' | '\'' => quote = Some(c),
1607+ '(' => depth += 1,
1608+ ')' => depth -= 1,
1609+ ';' if depth == 0 => {
1610+ end = i + 1;
1611+ break;
1612+ }
1613+ _ => {}
1614+ }
22521615 }
2253− }
2254−
2255− let dark = attrs_to_css(attrs, "dark:", kind, parent_kind, has_overlay_children);
2256− let print = attrs_to_css(attrs, "print:", kind, parent_kind, has_overlay_children);
2257− let motion_safe = attrs_to_css(attrs, "motion-safe:", kind, parent_kind, has_overlay_children);
2258− let motion_reduce =
2259− attrs_to_css(attrs, "motion-reduce:", kind, parent_kind, has_overlay_children);
2260− let landscape = attrs_to_css(attrs, "landscape:", kind, parent_kind, has_overlay_children);
2261− let portrait = attrs_to_css(attrs, "portrait:", kind, parent_kind, has_overlay_children);
2262−
2263− // Dedupe: if a property is declared twice within a single rule, keep only
2264− // the last occurrence (element-kind defaults are written before
2265− // user attributes, so a user [list-style disc] correctly overrides the
2266− // default list-style:none, and we don't need to ship both).
2267− let base = dedupe_declarations(&base);
2268− let pseudo: Vec<(String, String)> = pseudo
2269− .into_iter()
2270− .map(|(sel, css)| (sel, dedupe_declarations(&css)))
2271− .collect();
2272− let responsive: Vec<(String, String)> = responsive
2273− .into_iter()
2274− .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2275− .collect();
2276− let dark = dedupe_declarations(&dark);
2277− let print = dedupe_declarations(&print);
2278− let motion_safe = dedupe_declarations(&motion_safe);
2279− let motion_reduce = dedupe_declarations(&motion_reduce);
2280− let landscape = dedupe_declarations(&landscape);
2281− let portrait = dedupe_declarations(&portrait);
2282− let container: Vec<(String, String)> = container
2283− .into_iter()
2284− .map(|(bp, css)| (bp, dedupe_declarations(&css)))
2285− .collect();
2286−
2287− styles.get_class(
2288− base,
2289− pseudo,
2290− responsive,
2291− dark,
2292− print,
2293− motion_safe,
2294− motion_reduce,
2295− landscape,
2296− portrait,
2297− container,
2298− )
1616+ let (declaration, after) = rest.split_at(end);
1617+ rest = after;
1618+ let name = declaration.split(':').next().unwrap_or("").trim();
1619+ Some((name, declaration))
1620+ })
22991621}
23001622
23011623/// Dedupe CSS declarations within a single rule body: for any property
23021624/// declared more than once, keep only the last occurrence. Unparseable
2303−/// segments (no `:`) are preserved as-is. Semicolons inside parentheses are
2304−/// treated as part of a value, not as declaration separators.
1625+/// segments (no `:`) are preserved as-is. Semicolons inside parentheses or
1626+/// quoted strings are treated as part of a value, not as declaration
1627+/// separators.
23051628fn dedupe_declarations(css: &str) -> String {
23061629 if css.is_empty() {
23071630 return String::new();
@@ -2316,8 +1639,26 @@ fn dedupe_declarations(css: &str) -> String {
23161639 let mut decls: Vec<(Option<String>, String)> = Vec::new();
23171640 let mut current = String::new();
23181641 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;
23191646 for ch in css.chars() {
2320− if ch == '(' {
1647+ if escaped {
1648+ escaped = false;
1649+ current.push(ch);
1650+ } else if ch == '\\' {
1651+ escaped = true;
1652+ current.push(ch);
1653+ } else if let Some(q) = quote {
1654+ if ch == q {
1655+ quote = None;
1656+ }
1657+ current.push(ch);
1658+ } else if ch == '"' || ch == '\'' {
1659+ quote = Some(ch);
1660+ current.push(ch);
1661+ } else if ch == '(' {
23211662 depth += 1;
23221663 current.push(ch);
23231664 } else if ch == ')' {
@@ -2399,1268 +1740,578 @@ fn emit_class_attr(out: &mut String, gen_class: Option<&str>, user_class: Option
23991740// Attribute → CSS mapping
24001741// ---------------------------------------------------------------------------
24011742
2402−/// (htmlang prefix, CSS selector suffix)
2403−const PSEUDO_PREFIXES: &[(&str, &str)] = &[
2404− ("hover:", ":hover"),
2405− ("active:", ":active"),
2406− ("focus:", ":focus"),
2407− ("focus-visible:", ":focus-visible"),
2408− ("focus-within:", ":focus-within"),
2409− ("disabled:", ":disabled"),
2410− ("checked:", ":checked"),
2411− ("placeholder:", "::placeholder"),
2412− ("first:", ":first-child"),
2413− ("last:", ":last-child"),
2414− ("odd:", ":nth-child(odd)"),
2415− ("even:", ":nth-child(even)"),
2416− ("before:", "::before"),
2417− ("after:", "::after"),
2418− ("selection:", "::selection"),
2419− ("visited:", ":visited"),
2420− ("empty:", ":empty"),
2421− ("target:", ":target"),
2422− ("valid:", ":valid"),
2423− ("invalid:", ":invalid"),
2424−];
2425−const RESPONSIVE_PREFIXES: &[&str] = &["sm:", "md:", "lg:", "xl:", "2xl:"];
2426−const MEDIA_PREFIXES: &[&str] = &[
2427− "dark:",
2428− "print:",
2429− "motion-safe:",
2430− "motion-reduce:",
2431− "landscape:",
2432− "portrait:",
2433−];
2434−const CONTAINER_QUERY_PREFIXES: &[&str] = &["cq-sm:", "cq-md:", "cq-lg:", "cq-xl:", "cq-2xl:"];
2435−
2436−fn is_prefixed_attr(key: &str) -> bool {
2437− PSEUDO_PREFIXES.iter().any(|&(p, _)| key.starts_with(p))
2438− || RESPONSIVE_PREFIXES.iter().any(|p| key.starts_with(p))
2439− || MEDIA_PREFIXES.iter().any(|p| key.starts_with(p))
2440− || CONTAINER_QUERY_PREFIXES.iter().any(|p| key.starts_with(p))
2441− || key.starts_with("nth:")
2442− || key.starts_with("has(")
1743+/// Where an element is written, which its CSS depends on.
1744+struct Site<'a> {
1745+ kind: &'a ElementKind,
1746+ /// How its parent lays out its children: its `width fill`, `height
1747+ /// fill` and `shrink` compile against it.
1748+ parent: &'a Flow,
1749+ /// It has `@in-front` / `@behind` children.
1750+ has_overlay_children: bool,
1751+ /// A row, column or grid inside text, laid out inline.
1752+ inline: bool,
1753+ /// The page's `<body>`, which the reset already makes a column.
1754+ root: bool,
24431755}
24441756
2445−/// `display:flex;flex-direction:column;` — base layout for `@el` and every
2446−/// semantic wrapper that behaves like a column.
2447−const FLEX_COLUMN: &str = "display:flex;flex-direction:column;";
1757+impl Site<'_> {
1758+ /// Where an element in a parent with the layout `layout` and the flow
1759+ /// `parent` is.
1760+ fn new<'a>(elem: &'a Element, layout: Option<Layout>, parent: &'a Flow) -> Site<'a> {
1761+ Site {
1762+ kind: &elem.kind,
1763+ parent,
1764+ has_overlay_children: has_overlay_children(elem),
1765+ inline: layout == Some(Layout::Text) && elem.kind.layout().is_container(),
1766+ root: false,
1767+ }
1768+ }
1769+}
24481770
2449−/// Font stack shared by `@pre`, `@code`, `@kbd`.
2450−const MONOSPACE_STACK: &str = "font-family:ui-monospace,monospace;";
1771+// ---------------------------------------------------------------------------
1772+// Direction: what a child's `fill` and `shrink` compile against
1773+// ---------------------------------------------------------------------------
24511774
2452−/// Declarations common to `@badge` and `@tag`. They differ only in
2453−/// `border-radius` (and `@badge` additionally centers content / pins
2454−/// line-height:1), so keeping the shared base here avoids drift.
2455−const PILL_BASE: &str =
2456− "display:inline-flex;align-items:center;padding:2px 8px;font-size:0.75rem;font-weight:600;";
1775+/// The way a flex row or column lays out its children.
1776+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1777+enum Axis {
1778+ Row,
1779+ Column,
1780+}
24571781
2458−fn attrs_to_css(
2459− attrs: &[Attribute],
2460− state_prefix: &str,
2461− kind: &ElementKind,
2462− parent_kind: Option<&ElementKind>,
2463− has_overlay_children: bool,
2464−) -> String {
2465− let mut css = String::new();
1782+impl Axis {
1783+ /// The direction a `flex-direction` or `flex-flow` value sets, if it
1784+ /// names one (not `var(--dir)`, which only the browser knows).
1785+ fn of_value(value: &str) -> Option<Axis> {
1786+ value.split_whitespace().find_map(|word| match word {
1787+ "row" | "row-reverse" => Some(Axis::Row),
1788+ "column" | "column-reverse" => Some(Axis::Column),
1789+ _ => None,
1790+ })
1791+ }
1792+}
24661793
2467− // Base element styles only for the default (non-state) pass
2468− if state_prefix.is_empty() {
2469− // Elements with @in-front / @behind children become positioning
2470− // contexts. Pushed before user attrs so an explicit `position` wins
2471− // via dedupe (only the last declaration of a property is kept).
2472− if has_overlay_children {
2473− css.push_str("position:relative;isolation:isolate;");
2474− }
2475− match kind {
2476− ElementKind::Row => css.push_str("display:flex;flex-direction:row;"),
2477− ElementKind::Column
2478− | ElementKind::El
2479− // Semantic elements get flex column layout like @el
2480− | ElementKind::Nav
2481− | ElementKind::Header
2482− | ElementKind::Footer
2483− | ElementKind::Main
2484− | ElementKind::Section
2485− | ElementKind::Article
2486− | ElementKind::Aside
2487− | ElementKind::ListItem
2488− | ElementKind::Form
2489− | ElementKind::Details
2490− | ElementKind::Dialog => css.push_str(FLEX_COLUMN),
2491− ElementKind::Paragraph
2492− | ElementKind::H1
2493− | ElementKind::H2
2494− | ElementKind::H3
2495− | ElementKind::H4
2496− | ElementKind::H5
2497− | ElementKind::H6 => css.push_str("margin:0;"),
2498− // Lists: reset browser defaults
2499− ElementKind::List => css.push_str("margin:0;padding-left:0;list-style:none;"),
2500− // Figure / Blockquote: flex column with browser margin reset
2501− ElementKind::Figure | ElementKind::Blockquote => {
2502− css.push_str(FLEX_COLUMN);
2503− css.push_str("margin:0;");
2504− }
2505− // Pre: preserve whitespace
2506− ElementKind::Pre => {
2507− css.push_str("margin:0;white-space:pre;");
2508− css.push_str(MONOSPACE_STACK);
2509− }
2510− // Code / Kbd: monospace font
2511− ElementKind::Code | ElementKind::Kbd => css.push_str(MONOSPACE_STACK),
2512− ElementKind::DefinitionList => css.push_str("margin:0;"),
2513− ElementKind::DefinitionDescription => {
2514− css.push_str("margin:0;");
2515− css.push_str(FLEX_COLUMN);
2516− }
2517− ElementKind::Fieldset => {
2518− css.push_str(FLEX_COLUMN);
2519− // Align padding to the px-based scale used by Badge/Tag/Chip
2520− // rather than the old 0.5em (which depended on font-size).
2521− css.push_str("border:1px solid currentColor;padding:8px;margin:0;");
2522− }
2523− ElementKind::Grid => css.push_str("display:grid;"),
2524− ElementKind::Stack => css.push_str("position:relative;"),
2525− ElementKind::Badge => {
2526− css.push_str(PILL_BASE);
2527− css.push_str("justify-content:center;border-radius:9999px;line-height:1;");
2528− }
2529− ElementKind::Tag => {
2530− css.push_str(PILL_BASE);
2531− css.push_str("border-radius:4px;");
2532− }
2533− ElementKind::Tooltip => css.push_str("position:relative;cursor:help;"),
2534− ElementKind::Spacer => css.push_str("flex:1;"),
2535− ElementKind::Avatar => css.push_str("display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;overflow:hidden;flex-shrink:0;"),
2536− ElementKind::Carousel => css.push_str("display:flex;flex-direction:row;overflow-x:auto;scroll-snap-type:x mandatory;-webkit-overflow-scrolling:touch;scrollbar-width:none;"),
2537− ElementKind::Chip => css.push_str("display:inline-flex;align-items:center;gap:4px;padding:4px 12px;border-radius:9999px;font-size:0.875rem;border:1px solid currentColor;"),
2538− // Overlay layers fill the parent. Parent gets position:relative
2539− // applied automatically (see has_overlay_children check below).
2540− ElementKind::InFront => {
2541− css.push_str(FLEX_COLUMN);
2542− css.push_str("position:absolute;inset:0;");
1794+/// How an element lays out its children, as its CSS sets it: the
1795+/// direction its children's `width`/`height` `fill` and `shrink` compile
1796+/// against. That is the direction of `@row` or of a column, or the one its
1797+/// own `flex-direction` (or `flex-flow`) sets, with or without media or
1798+/// container prefixes. Like elm-ui's `.r > .wf`, the rules for a direction
1799+/// set under a prefix are keyed on the element's class: `@media (...) {
1800+/// :where(.a)>.b {...} }`.
1801+#[derive(Clone, Default)]
1802+struct Flow {
1803+ /// Without a prefix; `None` when the element isn't a flex row or column
1804+ /// (a grid, text, HTML's own layout, the top of the page)
1805+ base: Option<Axis>,
1806+ /// The direction under each chain of at-rule prefixes that sets one, in
1807+ /// the order their blocks are written
1808+ changes: Vec<(Vec<usize>, Axis)>,
1809+ /// The element's generated class, which the rules for the changes are
1810+ /// keyed on
1811+ class: Option<String>,
1812+}
1813+
1814+impl Flow {
1815+ fn of(elem: &Element) -> Flow {
1816+ let mut base = match elem.kind.layout() {
1817+ Layout::Row => Axis::Row,
1818+ Layout::Column => Axis::Column,
1819+ _ => return Flow::default(),
1820+ };
1821+ let mut changes: Vec<(Vec<usize>, Axis)> = Vec::new();
1822+ for attr in elem.attrs.iter().filter(|a| !a.html) {
1823+ let (condition, name) = Condition::of(&attr.key);
1824+ if !matches!(name, "flex-direction" | "flex-flow") || !condition.selector.is_empty() {
1825+ continue;
25431826 }
2544− ElementKind::Behind => {
2545− css.push_str(FLEX_COLUMN);
2546− css.push_str("position:absolute;inset:0;z-index:-1;");
1827+ let Some(axis) = attr.value.as_deref().and_then(Axis::of_value) else {
1828+ continue;
1829+ };
1830+ if condition.at.is_empty() {
1831+ base = axis;
1832+ } else {
1833+ // The later one wins, as in the CSS
1834+ changes.retain(|(at, _)| *at != condition.at);
1835+ changes.push((condition.at, axis));
25471836 }
2548− _ => {}
25491837 }
2550− // Children of @carousel get scroll-snap-align and flex-shrink
2551− if matches!(parent_kind, Some(ElementKind::Carousel)) {
2552− css.push_str("scroll-snap-align:start;flex-shrink:0;");
1838+ changes.sort_by_key(|(at, _)| at_order(at));
1839+ Flow {
1840+ base: Some(base),
1841+ changes,
1842+ class: None,
1843+ }
1844+ }
1845+
1846+ /// The direction under the at-rules `at`: the latest one set among
1847+ /// the conditions that hold there (`md:` holds at `lg:`), else the one
1848+ /// without a prefix.
1849+ fn at(&self, at: &[usize]) -> Option<Axis> {
1850+ let base = self.base?;
1851+ let here = Condition::at_only(at);
1852+ let changed = self
1853+ .changes
1854+ .iter()
1855+ .rev()
1856+ .find(|(chain, _)| Condition::at_only(chain).holds_at(&here))
1857+ .map(|&(_, axis)| axis);
1858+ Some(changed.unwrap_or(base))
1859+ }
1860+}
1861+
1862+/// `width` or `height`.
1863+#[derive(Clone, Copy, PartialEq, Eq)]
1864+enum Dim {
1865+ Width,
1866+ Height,
1867+}
1868+
1869+/// What a `width` or `height` says.
1870+#[derive(Clone, Copy, PartialEq, Eq)]
1871+enum Size {
1872+ Fill,
1873+ Shrink,
1874+ /// A size of its own (`width 300`)
1875+ Set,
1876+}
1877+
1878+impl Size {
1879+ fn of(value: &str) -> Size {
1880+ match value.trim() {
1881+ "fill" => Size::Fill,
1882+ "shrink" => Size::Shrink,
1883+ _ => Size::Set,
25531884 }
25541885 }
1886+}
1887+
1888+/// The declarations `fill` and `shrink` make in a parent laid out along
1889+/// `axis` (`None`: not a flex row or column). Along the parent's direction,
1890+/// `fill` takes the remaining space and `shrink` keeps the content's size;
1891+/// across it (or outside flex), `fill` is the full size and `shrink` fits
1892+/// the content.
1893+fn sizing(dim: Dim, size: Size, axis: Option<Axis>) -> &'static [(&'static str, &'static str)] {
1894+ match (dim, size, axis) {
1895+ (_, Size::Set, _) => &[],
1896+ (Dim::Width, Size::Fill, Some(Axis::Row)) => &[("flex", "1"), ("min-width", "0")],
1897+ (Dim::Width, Size::Fill, _) => &[("width", "100%")],
1898+ (Dim::Width, Size::Shrink, Some(Axis::Row)) => &[("flex-shrink", "0")],
1899+ (Dim::Width, Size::Shrink, _) => &[("width", "fit-content")],
1900+ (Dim::Height, Size::Fill, Some(Axis::Column)) => &[("flex", "1"), ("min-height", "0")],
1901+ (Dim::Height, Size::Fill, _) => &[("height", "100%")],
1902+ (Dim::Height, Size::Shrink, Some(Axis::Column)) => &[("flex-shrink", "0")],
1903+ (Dim::Height, Size::Shrink, _) => &[("height", "fit-content")],
1904+ }
1905+}
1906+
1907+/// Every property `fill` and `shrink` of `dim` can set, with its initial
1908+/// value (`flex` covers `flex-shrink`).
1909+fn sizing_properties(dim: Dim) -> [(&'static str, &'static str); 3] {
1910+ match dim {
1911+ Dim::Width => [
1912+ ("flex", "0 1 auto"),
1913+ ("min-width", "auto"),
1914+ ("width", "auto"),
1915+ ],
1916+ Dim::Height => [
1917+ ("flex", "0 1 auto"),
1918+ ("min-height", "auto"),
1919+ ("height", "auto"),
1920+ ],
1921+ }
1922+}
1923+
1924+/// What an element's attributes under some prefixes say about its size.
1925+#[derive(Default)]
1926+struct Sizes {
1927+ /// The last `width` and `height`
1928+ width: Option<Size>,
1929+ height: Option<Size>,
1930+ /// A `fill` or `shrink` for the width / height is among them (a later
1931+ /// size may replace it)
1932+ width_word: bool,
1933+ height_word: bool,
1934+ /// It writes `flex`, one of its longhands (`flex-grow`, `flex-shrink`,
1935+ /// `flex-basis`), `min-width` or `min-height` itself
1936+ flex: bool,
1937+ flex_grow: bool,
1938+ flex_shrink: bool,
1939+ flex_basis: bool,
1940+ min_width: bool,
1941+ min_height: bool,
1942+}
25551943
2556− for attr in attrs {
2557− // Determine the effective key for this pass
2558− let effective_key = if state_prefix.is_empty() {
2559− if is_prefixed_attr(&attr.key) {
1944+impl Sizes {
1945+ /// Read the attributes under the conditions that hold wherever `at`
1946+ /// does, a later condition over an earlier one.
1947+ fn of(attrs: &[Attribute], at: &Condition) -> Sizes {
1948+ let mut sizes = Sizes::default();
1949+ let mut read: Vec<(Condition, &str, &str)> = Vec::new();
1950+ for attr in attrs.iter().filter(|a| !a.html) {
1951+ let (condition, name) = Condition::of(&attr.key);
1952+ let Some(value) = attr.value.as_deref().filter(|v| !v.trim().is_empty()) else {
25601953 continue;
1954+ };
1955+ if condition.holds_at(at) {
1956+ read.push((condition, name, value));
1957+ }
1958+ }
1959+ read.sort_by_cached_key(|(condition, _, _)| condition.order());
1960+ for (_, name, value) in read {
1961+ match name {
1962+ "width" => {
1963+ let size = Size::of(value);
1964+ sizes.width = Some(size);
1965+ sizes.width_word |= size != Size::Set;
1966+ }
1967+ "height" => {
1968+ let size = Size::of(value);
1969+ sizes.height = Some(size);
1970+ sizes.height_word |= size != Size::Set;
1971+ }
1972+ "flex" => sizes.flex = true,
1973+ "flex-grow" => sizes.flex_grow = true,
1974+ "flex-shrink" => sizes.flex_shrink = true,
1975+ "flex-basis" => sizes.flex_basis = true,
1976+ "min-width" => sizes.min_width = true,
1977+ "min-height" => sizes.min_height = true,
1978+ _ => {}
25611979 }
2562− attr.key.as_str()
2563− } else {
2564− match attr.key.strip_prefix(state_prefix) {
2565− Some(k) => k,
2566− None => continue,
1980+ }
1981+ sizes
1982+ }
1983+
1984+ /// The element writes `property` itself: a layout word leaves it alone.
1985+ fn writes(&self, property: &str) -> bool {
1986+ match property {
1987+ "flex" => self.flex,
1988+ "flex-grow" => self.flex || self.flex_grow,
1989+ "flex-shrink" => self.flex || self.flex_shrink,
1990+ "flex-basis" => self.flex || self.flex_basis,
1991+ "min-width" => self.min_width,
1992+ "min-height" => self.min_height,
1993+ "width" => self.width == Some(Size::Set),
1994+ "height" => self.height == Some(Size::Set),
1995+ _ => false,
1996+ }
1997+ }
1998+
1999+ /// Write a layout word's `property: value`, unless the element writes
2000+ /// the property itself. When it writes some of `flex`'s longhands, a
2001+ /// `flex` is written as the others (`flex-shrink 0, width fill` still
2002+ /// grows).
2003+ fn push(&self, css: &mut String, property: &str, value: &str) {
2004+ if property == "flex" && !self.flex {
2005+ let longhands = match value {
2006+ "1" => [
2007+ ("flex-grow", "1"),
2008+ ("flex-shrink", "1"),
2009+ ("flex-basis", "0%"),
2010+ ],
2011+ // The reset, `0 1 auto`
2012+ _ => [
2013+ ("flex-grow", "0"),
2014+ ("flex-shrink", "1"),
2015+ ("flex-basis", "auto"),
2016+ ],
2017+ };
2018+ if longhands.iter().any(|&(p, _)| self.writes(p)) {
2019+ for (longhand, value) in longhands {
2020+ if !self.writes(longhand) {
2021+ push_css(css, longhand, value);
2022+ }
2023+ }
2024+ return;
25672025 }
2026+ }
2027+ if !self.writes(property) {
2028+ push_css(css, property, value);
2029+ }
2030+ }
2031+}
2032+
2033+/// The rule that gives an element's `fill` and `shrink`, as its attributes
2034+/// under the at-rules `at` set them, their meaning in a parent laid out
2035+/// along `axis`. Every other property a layout word could have set is put
2036+/// back to its initial value, so the rule is right whichever earlier rule
2037+/// it overrides. Properties the element writes itself are left alone.
2038+fn sizing_rule(attrs: &[Attribute], at: &[usize], axis: Axis) -> String {
2039+ let sizes = Sizes::of(attrs, &Condition::at_only(at));
2040+ let mut sets: Vec<(&str, &str)> = Vec::new();
2041+ let mut resets: Vec<(&str, &str)> = Vec::new();
2042+ for (dim, size, word) in [
2043+ (Dim::Width, sizes.width, sizes.width_word),
2044+ (Dim::Height, sizes.height, sizes.height_word),
2045+ ] {
2046+ if !word {
2047+ continue;
2048+ }
2049+ if let Some(size) = size {
2050+ sets.extend_from_slice(sizing(dim, size, Some(axis)));
2051+ }
2052+ resets.extend_from_slice(&sizing_properties(dim));
2053+ }
2054+ let mut css = String::new();
2055+ let mut written: Vec<&str> = Vec::new();
2056+ for &(property, value) in &resets {
2057+ if sets.iter().any(|&(p, _)| p == property) || written.contains(&property) {
2058+ continue;
2059+ }
2060+ written.push(property);
2061+ sizes.push(&mut css, property, value);
2062+ }
2063+ for &(property, value) in &sets {
2064+ sizes.push(&mut css, property, value);
2065+ }
2066+ css
2067+}
2068+
2069+/// The rules an element's `fill` and `shrink` need under each chain of
2070+/// at-rules where the direction of `flow` (its parent's) changes: `(at,
2071+/// body)`.
2072+fn sizing_changes(attrs: &[Attribute], flow: &Flow) -> Vec<(Vec<usize>, String)> {
2073+ flow.changes
2074+ .iter()
2075+ .map(|(at, axis)| (at.clone(), sizing_rule(attrs, at, *axis)))
2076+ .filter(|(_, body)| !body.is_empty())
2077+ .collect()
2078+}
2079+
2080+/// An element's generated class, with the rules keyed on its parent's
2081+/// class that its `fill` and `shrink` need where the parent's direction
2082+/// changes under a prefix (see [`Flow`]): `:where(.a)>.b`, one class of
2083+/// specificity like any class rule.
2084+fn element_class(elem: &Element, site: &Site, styles: &mut StyleCollector) -> Option<String> {
2085+ let as_child = match site.parent.class {
2086+ Some(_) => sizing_changes(&elem.attrs, site.parent),
2087+ None => Vec::new(),
2088+ };
2089+ // Two elements with the same CSS but different rules keyed on them
2090+ // need two classes
2091+ let mut distinct = String::new();
2092+ for (at, body) in &as_child {
2093+ distinct.push_str(&format!("<{:?}{}", at, body));
2094+ }
2095+ let class = compute_class(&elem.attrs, site, styles, distinct)?;
2096+ if let Some(parent) = &site.parent.class {
2097+ for (at, body) in as_child {
2098+ styles.add_keyed(at, format!(":where(.{})>.{}", parent, class), body);
2099+ }
2100+ }
2101+ Some(class)
2102+}
2103+
2104+/// The `display` of a layout (nothing for text, native and void elements,
2105+/// which keep HTML's own).
2106+fn layout_css(layout: Layout, inline: bool) -> &'static str {
2107+ match (layout, inline) {
2108+ (Layout::Column, false) => "display:flex;flex-direction:column;",
2109+ (Layout::Column, true) => "display:inline-flex;flex-direction:column;",
2110+ (Layout::Row, false) => "display:flex;flex-direction:row;",
2111+ (Layout::Row, true) => "display:inline-flex;flex-direction:row;",
2112+ (Layout::Grid, false) => "display:grid;",
2113+ (Layout::Grid, true) => "display:inline-grid;",
2114+ _ => "",
2115+ }
2116+}
2117+
2118+/// The declarations of the attributes under `condition` (the defaults of
2119+/// the element's kind are [`default_css`]'s).
2120+fn attrs_to_css(attrs: &[Attribute], condition: &Condition, site: &Site) -> String {
2121+ let mut css = String::new();
2122+ // The auto margins of `center-x`, `align-left`, ..., written at the end
2123+ let mut aligned = String::new();
2124+ let kind = site.kind;
2125+ // Under `children:` the styles go on the children, whose parent is this
2126+ // element: htmlang's words that place an element in its parent are an
2127+ // error there (the parser reports them), and left out
2128+ let on_children = condition.on_children();
2129+ let inside = condition.inside().is_some();
2130+ // The direction `fill` and `shrink` compile against
2131+ let axis = site.parent.at(&condition.at);
2132+
2133+ // htmlang's words for laying out children (`spacing`, `wrap`,
2134+ // `grid-cols`) mean nothing on an element that doesn't lay out its
2135+ // children, which the parser reports; they are left out. Under
2136+ // `children:` they go on the children, whose layout isn't known here.
2137+ let lays_out_children = kind.layout().is_container() || on_children;
2138+ fn under<'k>(key: &'k str, condition: &Condition) -> Option<&'k str> {
2139+ let (c, name) = Condition::of(key);
2140+ (c == *condition).then_some(name)
2141+ }
2142+
2143+ for (index, attr) in attrs.iter().enumerate() {
2144+ if attr.html {
2145+ continue;
2146+ }
2147+ let Some(effective_key) = under(&attr.key, condition) else {
2148+ continue;
25682149 };
2150+ if on_children && crate::vocab::places_in_parent(effective_key, attr.value.as_deref()) {
2151+ continue;
2152+ }
2153+ // Under an element prefix (`@td:`) the styles go on elements whose
2154+ // layout and parent aren't known here: htmlang's own words are an
2155+ // error there (the parser reports them), and left out
2156+ if inside && crate::vocab::is_htmlang_word(effective_key, attr.value.as_deref()) {
2157+ continue;
2158+ }
25692159
25702160 let val = attr.value.as_deref();
2161+ // A style whose value came out empty (a field a record doesn't
2162+ // have, `${if()}` without its other branch) is left out
2163+ if val.is_some_and(|v| v.trim().is_empty()) {
2164+ continue;
2165+ }
25712166
25722167 match effective_key {
2573− // Layout
2574− "spacing" | "gap" => {
2575− if let Some(v) = val {
2576− push_css(&mut css, "gap", &css_px(v));
2577− }
2578− }
2579− "padding" => {
2580− if let Some(v) = val {
2581− push_css(&mut css, "padding", &css_px_multi(v));
2582− }
2583− }
2584− "padding-x" => {
2585− if let Some(v) = val {
2586− // Logical property covers both inline sides in one
2587− // declaration; for symmetric values this is visually
2588− // identical to padding-left/right in LTR and RTL.
2589− push_css(&mut css, "padding-inline", &css_px(v));
2590− }
2591− }
2592− "padding-y" => {
2593− if let Some(v) = val {
2594− push_css(&mut css, "padding-block", &css_px(v));
2595− }
2596− }
2597− "padding-top" => {
2598− if let Some(v) = val {
2599− push_css(&mut css, "padding-top", &css_px(v));
2600− }
2601− }
2602− "padding-bottom" => {
2603− if let Some(v) = val {
2604− push_css(&mut css, "padding-bottom", &css_px(v));
2605− }
2606− }
2607− "padding-left" => {
2608− if let Some(v) = val {
2609− push_css(&mut css, "padding-left", &css_px(v));
2610− }
2611− }
2612− "padding-right" => {
2168+ // htmlang's own words: they lay out children or place the
2169+ // element in its parent, and mean more than one CSS property
2170+ "spacing" if !lays_out_children => {}
2171+ "spacing" => {
26132172 if let Some(v) = val {
2614− push_css(&mut css, "padding-right", &css_px(v));
2173+ push_css(&mut css, "gap", &with_px("gap", v));
26152174 }
26162175 }
26172176
2618− // Sizing
2619− "width" => {
2620− if let Some(v) = val {
2621− match v {
2622− "fill" => match parent_kind {
2623− Some(ElementKind::Row) => {
2624− push_css(&mut css, "flex", "1");
2625− push_css(&mut css, "min-width", "0");
2626− }
2627− _ => push_css(&mut css, "width", "100%"),
2628− },
2629− "shrink" => push_css(&mut css, "flex-shrink", "0"),
2630− _ => push_css(&mut css, "width", &css_px(v)),
2631− }
2177+ // Sizing: `fill` and `shrink` compile against the parent's
2178+ // direction. Only the last `width` (`height`) counts, as for
2179+ // any style written twice.
2180+ "width" | "height" if val.is_some_and(|v| Size::of(v) != Size::Set) => {
2181+ let later = attrs[index + 1..].iter().any(|a| {
2182+ !a.html
2183+ && under(&a.key, condition) == Some(effective_key)
2184+ && a.value.as_deref().is_some_and(|v| !v.trim().is_empty())
2185+ });
2186+ if later {
2187+ continue;
26322188 }
2633− }
2634− "height" => {
2635− if let Some(v) = val {
2636− match v {
2637− "fill" => match parent_kind {
2638− Some(ElementKind::Column) => {
2639− push_css(&mut css, "flex", "1");
2640− push_css(&mut css, "min-height", "0");
2641− }
2642− _ => push_css(&mut css, "height", "100%"),
2643− },
2644− "shrink" => push_css(&mut css, "flex-shrink", "0"),
2645− _ => push_css(&mut css, "height", &css_px(v)),
2189+ let dim = if effective_key == "width" {
2190+ Dim::Width
2191+ } else {
2192+ Dim::Height
2193+ };
2194+ let size = Size::of(val.unwrap_or_default());
2195+ // What the element writes itself, which a layout word
2196+ // leaves alone
2197+ let sizes = Sizes::of(attrs, condition);
2198+ for &(property, value) in sizing(dim, size, axis) {
2199+ sizes.push(&mut css, property, value);
2200+ }
2201+ }
2202+
2203+ // A size of its own under a prefix, where a `fill` or
2204+ // `shrink` that sets `flex` (along a flex parent's direction)
2205+ // holds too: the word's `flex` and minimum are put back, so the
2206+ // size is the one the element gets (`width fill, lg:width 200`
2207+ // in a row)
2208+ "width" | "height"
2209+ if *condition != Condition::default()
2210+ && attrs.iter().any(|a| {
2211+ let (c, name) = Condition::of(&a.key);
2212+ let along = match site.parent.at(&c.at) {
2213+ Some(Axis::Row) => name == "width",
2214+ Some(Axis::Column) => name == "height",
2215+ None => false,
2216+ };
2217+ !a.html
2218+ && name == effective_key
2219+ && along
2220+ && c != *condition
2221+ && c.holds_at(condition)
2222+ && a.value
2223+ .as_deref()
2224+ .is_some_and(|v| !v.trim().is_empty() && Size::of(v) != Size::Set)
2225+ }) =>
2226+ {
2227+ let dim = if effective_key == "width" {
2228+ Dim::Width
2229+ } else {
2230+ Dim::Height
2231+ };
2232+ let sizes = Sizes::of(attrs, condition);
2233+ for (property, value) in sizing_properties(dim) {
2234+ if property != effective_key {
2235+ sizes.push(&mut css, property, value);
26462236 }
26472237 }
2648− }
2649− "min-width" => {
2650− if let Some(v) = val {
2651− push_css(&mut css, "min-width", &css_px(v));
2652− }
2653− }
2654− "max-width" => {
2655− if let Some(v) = val {
2656− push_css(&mut css, "max-width", &css_px(v));
2657− }
2658− }
2659− "min-height" => {
2660− if let Some(v) = val {
2661− push_css(&mut css, "min-height", &css_px(v));
2662− }
2663− }
2664− "max-height" => {
26652238 if let Some(v) = val {
2666− push_css(&mut css, "max-height", &css_px(v));
2239+ push_css(&mut css, effective_key, &with_px(effective_key, v));
26672240 }
26682241 }
26692242
2670− // Alignment
2671− "center-x" => match parent_kind {
2672− Some(ElementKind::Column) | Some(ElementKind::El) => {
2673− push_css(&mut css, "align-self", "center");
2674− }
2675− _ => {
2676− push_css(&mut css, "margin-left", "auto");
2677− push_css(&mut css, "margin-right", "auto");
2678− }
2679− },
2680− "center-y" => match parent_kind {
2681− Some(ElementKind::Row) => push_css(&mut css, "align-self", "center"),
2682− _ => {
2683− push_css(&mut css, "margin-top", "auto");
2684− push_css(&mut css, "margin-bottom", "auto");
2685− }
2686− },
2687− "align-left" => match parent_kind {
2688− Some(ElementKind::Column) | Some(ElementKind::El) => {
2689− push_css(&mut css, "align-self", "flex-start");
2690− }
2691− _ => push_css(&mut css, "margin-right", "auto"),
2692− },
2693− "align-right" => match parent_kind {
2694− Some(ElementKind::Column) | Some(ElementKind::El) => {
2695− push_css(&mut css, "align-self", "flex-end");
2696− }
2697− _ => push_css(&mut css, "margin-left", "auto"),
2698− },
2699− "align-top" => match parent_kind {
2700− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-start"),
2701− _ => push_css(&mut css, "margin-bottom", "auto"),
2702− },
2703− "align-bottom" => match parent_kind {
2704− Some(ElementKind::Row) => push_css(&mut css, "align-self", "flex-end"),
2705− _ => push_css(&mut css, "margin-top", "auto"),
2706− },
2707−
2708− // Style
2709− "background" => {
2710− if let Some(v) = val {
2711− push_css(&mut css, "background", v);
2712− }
2243+ // Alignment: auto margins, which work along either direction.
2244+ // They are written last, so a `margin` on the same element
2245+ // keeps its other sides (`center-x, margin 20`)
2246+ "center-x" => {
2247+ push_css(&mut aligned, "margin-left", "auto");
2248+ push_css(&mut aligned, "margin-right", "auto");
27132249 }
2714− "color" => {
2715− if let Some(v) = val {
2716− push_css(&mut css, "color", v);
2717− }
2250+ "center-y" => {
2251+ push_css(&mut aligned, "margin-top", "auto");
2252+ push_css(&mut aligned, "margin-bottom", "auto");
27182253 }
2719− "border" => {
2254+ "align-left" => push_css(&mut aligned, "margin-right", "auto"),
2255+ "align-right" => push_css(&mut aligned, "margin-left", "auto"),
2256+ "align-top" => push_css(&mut aligned, "margin-bottom", "auto"),
2257+ "align-bottom" => push_css(&mut aligned, "margin-top", "auto"),
2258+
2259+ "wrap" if lays_out_children => push_css(&mut css, "flex-wrap", "wrap"),
2260+ "wrap" => {}
2261+
2262+ // Grid
2263+ "grid-cols" | "grid-rows" if !lays_out_children => {}
2264+ "grid-cols" | "grid-rows" => {
27202265 if let Some(v) = val {
2721− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2722− if parts.len() == 2 {
2723− push_css(
2724− &mut css,
2725− "border",
2726− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2727− );
2266+ let property = if effective_key == "grid-cols" {
2267+ "grid-template-columns"
27282268 } else {
2729− push_css(
2730− &mut css,
2731− "border",
2732− &format!("{} solid currentColor", css_px(parts[0])),
2733− );
2269+ "grid-template-rows"
2270+ };
2271+ match v.parse::<u32>() {
2272+ Ok(n) => push_css(&mut css, property, &format!("repeat({},1fr)", n)),
2273+ Err(_) => push_css(&mut css, property, &with_px(property, v)),
27342274 }
27352275 }
27362276 }
2737− "border-top" | "border-bottom" | "border-left" | "border-right" => {
2277+ "col-span" | "row-span" => {
27382278 if let Some(v) = val {
2739− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2740− if parts.len() == 2 {
2741− push_css(
2742− &mut css,
2743− effective_key,
2744− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2745− );
2279+ let property = if effective_key == "col-span" {
2280+ "grid-column"
27462281 } else {
2747− push_css(
2748− &mut css,
2749− effective_key,
2750− &format!("{} solid currentColor", css_px(parts[0])),
2751− );
2752− }
2753− }
2754− }
2755− "rounded" => {
2756− if let Some(v) = val {
2757− push_css(&mut css, "border-radius", &css_px(v));
2758− }
2759− }
2760− "bold" => push_css(&mut css, "font-weight", "bold"),
2761− "italic" => push_css(&mut css, "font-style", "italic"),
2762− "underline" => push_css(&mut css, "text-decoration", "underline"),
2763− "size" => {
2764− if let Some(v) = val {
2765− push_css(&mut css, "font-size", &css_px(v));
2766− }
2767− }
2768− "font" => {
2769− if let Some(v) = val {
2770− // `font "Inter, sans-serif"` quotes a whole font stack so
2771− // its commas don't split the attribute list.
2772− let v = match v.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
2773− Some(stack) if stack.contains(',') => stack,
2774− _ => v,
2282+ "grid-row"
27752283 };
2776− push_css(&mut css, "font-family", v);
2777− }
2778− }
2779− "transition" => {
2780− if let Some(v) = val {
2781− push_css(&mut css, "transition", v);
2782− }
2783− }
2784− "cursor" => {
2785− if let Some(v) = val {
2786− push_css(&mut css, "cursor", v);
2787− }
2788− }
2789− "opacity" => {
2790− if let Some(v) = val {
2791− push_css(&mut css, "opacity", v);
2284+ push_css(&mut css, property, &format!("span {}", v));
27922285 }
27932286 }
27942287
2795− // Typography
2796− "text-align" => {
2797− if let Some(v) = val {
2798− push_css(&mut css, "text-align", v);
2799− }
2800− }
2801− "line-height" => {
2802− if let Some(v) = val {
2803− push_css(&mut css, "line-height", &css_line_height(v));
2804− }
2805− }
2806− "letter-spacing" => {
2807− if let Some(v) = val {
2808− push_css(&mut css, "letter-spacing", &css_px(v));
2809− }
2810− }
2811− "text-transform" => {
2812− if let Some(v) = val {
2813− push_css(&mut css, "text-transform", v);
2814− }
2815− }
2816− "white-space" => {
2288+ // CSS's `line-clamp` has no support yet without its
2289+ // `-webkit-` fallback, which needs a box to clamp
2290+ "line-clamp" => {
28172291 if let Some(v) = val {
2818− push_css(&mut css, "white-space", v);
2292+ push_css(&mut css, "display", "-webkit-box");
2293+ push_css(&mut css, "-webkit-line-clamp", v);
2294+ push_css(&mut css, "-webkit-box-orient", "vertical");
2295+ push_css(&mut css, "overflow", "hidden");
28192296 }
28202297 }
28212298
2822− // Overflow & positioning
2823− "overflow" => {
2824− if let Some(v) = val {
2825− push_css(&mut css, "overflow", v);
2826− }
2827− }
2828− "position" => {
2299+ // Every other name is a CSS property (standard, custom,
2300+ // vendor-prefixed, or one htmlang doesn't know, which the
2301+ // parser warned about), written under its own name with the
2302+ // value as written, except for `px` after a bare number where
2303+ // the property takes a length
2304+ key if crate::vocab::is_property_name(key) => {
28292305 if let Some(v) = val {
2830− push_css(&mut css, "position", v);
2306+ push_css(&mut css, key, &with_px(key, v));
28312307 }
28322308 }
2833− "top" => {
2834− if let Some(v) = val {
2835− push_css(&mut css, "top", &css_px(v));
2836− }
2837− }
2838− "right" => {
2839− if let Some(v) = val {
2840− push_css(&mut css, "right", &css_px(v));
2841− }
2842− }
2843− "bottom" => {
2844− if let Some(v) = val {
2845− push_css(&mut css, "bottom", &css_px(v));
2846− }
2847− }
2848− "left" => {
2849− if let Some(v) = val {
2850− push_css(&mut css, "left", &css_px(v));
2851− }
2852− }
2853− "z-index" => {
2854− if let Some(v) = val {
2855− push_css(&mut css, "z-index", v);
2856− }
2857− }
2858−
2859− // Display & visibility
2860− "display" => {
2861− if let Some(v) = val {
2862− push_css(&mut css, "display", v);
2863− }
2864− }
2865− "visibility" => {
2866− if let Some(v) = val {
2867− push_css(&mut css, "visibility", v);
2868− }
2869− }
2870− "hidden" => push_css(&mut css, "display", "none"),
2871−
2872− // Transform & filters
2873− "transform" => {
2874− if let Some(v) = val {
2875− push_css(&mut css, "transform", v);
2876− }
2877− }
2878− "backdrop-filter" => {
2879− if let Some(v) = val {
2880− push_css(&mut css, "backdrop-filter", v);
2881− }
2882− }
2883−
2884− // Effects
2885− "shadow" => {
2886− if let Some(v) = val {
2887− push_css(&mut css, "box-shadow", v);
2888− }
2889− }
2890−
2891− // Flow
2892− "wrap" => push_css(&mut css, "flex-wrap", "wrap"),
2893− "gap-x" => {
2894− if let Some(v) = val {
2895− push_css(&mut css, "column-gap", &css_px(v));
2896− }
2897− }
2898− "gap-y" => {
2899− if let Some(v) = val {
2900− push_css(&mut css, "row-gap", &css_px(v));
2901− }
2902− }
2903−
2904− // Grid
2905− "grid" => {
2906− push_css(&mut css, "display", "grid");
2907− }
2908− "grid-cols" => {
2909− if let Some(v) = val {
2910− if let Ok(n) = v.parse::<u32>() {
2911− push_css(
2912− &mut css,
2913− "grid-template-columns",
2914− &format!("repeat({},1fr)", n),
2915− );
2916− } else {
2917− push_css(&mut css, "grid-template-columns", v);
2918− }
2919− }
2920− }
2921− "grid-rows" => {
2922− if let Some(v) = val {
2923− if let Ok(n) = v.parse::<u32>() {
2924− push_css(
2925− &mut css,
2926− "grid-template-rows",
2927− &format!("repeat({},1fr)", n),
2928− );
2929− } else {
2930− push_css(&mut css, "grid-template-rows", v);
2931− }
2932− }
2933− }
2934− "col-span" => {
2935− if let Some(v) = val {
2936− push_css(&mut css, "grid-column", &format!("span {}", v));
2937− }
2938− }
2939− "row-span" => {
2940− if let Some(v) = val {
2941− push_css(&mut css, "grid-row", &format!("span {}", v));
2942− }
2943− }
2944−
2945− // Animation
2946− "animation" => {
2947− if let Some(v) = val {
2948− push_css(&mut css, "animation", v);
2949− }
2950− }
2951−
2952− // Aspect ratio
2953− "aspect-ratio" => {
2954− if let Some(v) = val {
2955− push_css(&mut css, "aspect-ratio", v);
2956− }
2957− }
2958−
2959− // CSS containment for rendering performance
2960− "contain" => {
2961− if let Some(v) = val {
2962− push_css(&mut css, "contain", v);
2963− } else {
2964− push_css(&mut css, "contain", "layout style paint");
2965− }
2966− }
2967− "content-visibility" => {
2968− if let Some(v) = val {
2969− push_css(&mut css, "content-visibility", v);
2970− } else {
2971− push_css(&mut css, "content-visibility", "auto");
2972− }
2973− }
2974−
2975− // Outline (like border but doesn't affect layout)
2976− "outline" => {
2977− if let Some(v) = val {
2978− let parts: Vec<&str> = v.splitn(2, ' ').collect();
2979− if parts.len() == 2 {
2980− push_css(
2981− &mut css,
2982− "outline",
2983− &format!("{} solid {}", css_px(parts[0]), parts[1]),
2984− );
2985− } else {
2986− push_css(
2987− &mut css,
2988− "outline",
2989− &format!("{} solid currentColor", css_px(parts[0])),
2990− );
2991− }
2992− }
2993− }
2994−
2995− // Logical properties (i18n-aware)
2996− "padding-inline" => {
2997− if let Some(v) = val {
2998− push_css(&mut css, "padding-inline", &css_px_multi(v));
2999− }
3000− }
3001− "padding-block" => {
3002− if let Some(v) = val {
3003− push_css(&mut css, "padding-block", &css_px_multi(v));
3004− }
3005− }
3006− "margin-inline" => {
3007− if let Some(v) = val {
3008− push_css(&mut css, "margin-inline", &css_px_multi(v));
3009− }
3010− }
3011− "margin-block" => {
3012− if let Some(v) = val {
3013− push_css(&mut css, "margin-block", &css_px_multi(v));
3014− }
3015− }
3016−
3017− // Logical property start/end variants
3018− "padding-inline-start"
3019− | "padding-inline-end"
3020− | "padding-block-start"
3021− | "padding-block-end"
3022− | "margin-inline-start"
3023− | "margin-inline-end"
3024− | "margin-block-start"
3025− | "margin-block-end" => {
3026− if let Some(v) = val {
3027− push_css(&mut css, effective_key, &css_px(v));
3028− }
3029− }
3030−
3031− // Logical inset
3032− "inset-inline" | "inset-block" => {
3033− if let Some(v) = val {
3034− push_css(&mut css, effective_key, &css_px_multi(v));
3035− }
3036− }
3037− "inset-inline-start" | "inset-inline-end" | "inset-block-start" | "inset-block-end" => {
3038− if let Some(v) = val {
3039− push_css(&mut css, effective_key, &css_px(v));
3040− }
3041− }
3042−
3043− // Logical border
3044− "border-inline"
3045− | "border-block"
3046− | "border-inline-start"
3047− | "border-inline-end"
3048− | "border-block-start"
3049− | "border-block-end" => {
3050− if let Some(v) = val {
3051− push_css(&mut css, effective_key, v);
3052− }
3053− }
3054−
3055− // Logical border-radius
3056− "border-start-start-radius"
3057− | "border-start-end-radius"
3058− | "border-end-start-radius"
3059− | "border-end-end-radius" => {
3060− if let Some(v) = val {
3061− push_css(&mut css, effective_key, &css_px(v));
3062− }
3063− }
3064−
3065− // Logical scroll margins & padding
3066− "scroll-margin-inline"
3067− | "scroll-margin-block"
3068− | "scroll-padding-inline"
3069− | "scroll-padding-block" => {
3070− if let Some(v) = val {
3071− push_css(&mut css, effective_key, &css_px_multi(v));
3072− }
3073− }
3074−
3075− // Logical sizing
3076− "inline-size" | "block-size" | "min-inline-size" | "max-inline-size"
3077− | "min-block-size" | "max-block-size" => {
3078− if let Some(v) = val {
3079− push_css(&mut css, effective_key, &css_px(v));
3080− }
3081− }
3082−
3083− // Scroll snap
3084− "scroll-snap-type" => {
3085− if let Some(v) = val {
3086− push_css(&mut css, "scroll-snap-type", v);
3087− }
3088− }
3089− "scroll-snap-align" => {
3090− if let Some(v) = val {
3091− push_css(&mut css, "scroll-snap-align", v);
3092− }
3093− }
3094−
3095− // Margin
3096− "margin" => {
3097− if let Some(v) = val {
3098− push_css(&mut css, "margin", &css_px_multi(v));
3099− }
3100− }
3101− "margin-x" => {
3102− if let Some(v) = val {
3103− push_css(&mut css, "margin-inline", &css_px(v));
3104− }
3105− }
3106− "margin-y" => {
3107− if let Some(v) = val {
3108− push_css(&mut css, "margin-block", &css_px(v));
3109− }
3110− }
3111−
3112− // Filter
3113− "filter" => {
3114− if let Some(v) = val {
3115− push_css(&mut css, "filter", v);
3116− }
3117− }
3118−
3119− // Object fit/position (for images)
3120− "object-fit" => {
3121− if let Some(v) = val {
3122− push_css(&mut css, "object-fit", v);
3123− }
3124− }
3125− "object-position" => {
3126− if let Some(v) = val {
3127− push_css(&mut css, "object-position", v);
3128− }
3129− }
3130−
3131− // Text shadow
3132− "text-shadow" => {
3133− if let Some(v) = val {
3134− push_css(&mut css, "text-shadow", v);
3135− }
3136− }
3137−
3138− // Text overflow
3139− "text-overflow" => {
3140− if let Some(v) = val {
3141− push_css(&mut css, "text-overflow", v);
3142− }
3143− }
3144−
3145− // Interaction
3146− "pointer-events" => {
3147− if let Some(v) = val {
3148− push_css(&mut css, "pointer-events", v);
3149− }
3150− }
3151− "user-select" => {
3152− if let Some(v) = val {
3153− push_css(&mut css, "user-select", v);
3154− }
3155− }
3156−
3157− // Flexbox/grid alignment
3158− "justify-content" => {
3159− if let Some(v) = val {
3160− push_css(&mut css, "justify-content", v);
3161− }
3162− }
3163− "align-items" => {
3164− if let Some(v) = val {
3165− push_css(&mut css, "align-items", v);
3166− }
3167− }
3168−
3169− // Flex item order
3170− "order" => {
3171− if let Some(v) = val {
3172− push_css(&mut css, "order", v);
3173− }
3174− }
3175−
3176− // Background extras
3177− "background-size" => {
3178− if let Some(v) = val {
3179− push_css(&mut css, "background-size", v);
3180− }
3181− }
3182− "background-position" => {
3183− if let Some(v) = val {
3184− push_css(&mut css, "background-position", v);
3185− }
3186− }
3187− "background-repeat" => {
3188− if let Some(v) = val {
3189− push_css(&mut css, "background-repeat", v);
3190− }
3191− }
3192−
3193− // Text wrapping
3194− "word-break" => {
3195− if let Some(v) = val {
3196− push_css(&mut css, "word-break", v);
3197− }
3198− }
3199− "overflow-wrap" => {
3200− if let Some(v) = val {
3201− push_css(&mut css, "overflow-wrap", v);
3202− }
3203− }
3204−
3205− // Container queries
3206− "container" => {
3207− push_css(&mut css, "container-type", "inline-size");
3208− }
3209− "container-name" => {
3210− if let Some(v) = val {
3211− push_css(&mut css, "container-name", v);
3212− }
3213− }
3214− "container-type" => {
3215− if let Some(v) = val {
3216− push_css(&mut css, "container-type", v);
3217− }
3218− }
3219−
3220− // Overflow axis
3221− "overflow-x" => {
3222− if let Some(v) = val {
3223− push_css(&mut css, "overflow-x", v);
3224− }
3225− }
3226− "overflow-y" => {
3227− if let Some(v) = val {
3228− push_css(&mut css, "overflow-y", v);
3229− }
3230− }
3231−
3232− // Inset (shorthand for top/right/bottom/left)
3233− "inset" => {
3234− if let Some(v) = val {
3235− push_css(&mut css, "inset", &css_px(v));
3236− }
3237− }
3238−
3239− // Accent & caret colors
3240− "accent-color" => {
3241− if let Some(v) = val {
3242− push_css(&mut css, "accent-color", v);
3243− }
3244− }
3245− "caret-color" => {
3246− if let Some(v) = val {
3247− push_css(&mut css, "caret-color", v);
3248− }
3249− }
3250−
3251− // Color scheme & appearance
3252− "color-scheme" => {
3253− if let Some(v) = val {
3254− push_css(&mut css, "color-scheme", v);
3255− }
3256− }
3257− "appearance" => {
3258− if let Some(v) = val {
3259− push_css(&mut css, "appearance", v);
3260− }
3261− }
3262−
3263− // List style
3264− "list-style" => {
3265− if let Some(v) = val {
3266− push_css(&mut css, "list-style", v);
3267− }
3268− }
3269−
3270− // Table
3271− "border-collapse" => {
3272− if let Some(v) = val {
3273− push_css(&mut css, "border-collapse", v);
3274− }
3275− }
3276− "border-spacing" => {
3277− if let Some(v) = val {
3278− push_css(&mut css, "border-spacing", &css_px(v));
3279− }
3280− }
3281−
3282− // Text decoration
3283− "text-decoration" => {
3284− if let Some(v) = val {
3285− push_css(&mut css, "text-decoration", v);
3286− }
3287− }
3288− "text-decoration-color" => {
3289− if let Some(v) = val {
3290− push_css(&mut css, "text-decoration-color", v);
3291− }
3292− }
3293− "text-decoration-thickness" => {
3294− if let Some(v) = val {
3295− push_css(&mut css, "text-decoration-thickness", &css_px(v));
3296− }
3297− }
3298− "text-decoration-style" => {
3299− if let Some(v) = val {
3300− push_css(&mut css, "text-decoration-style", v);
3301− }
3302− }
3303− "text-underline-offset" => {
3304− if let Some(v) = val {
3305− push_css(&mut css, "text-underline-offset", &css_px(v));
3306− }
3307− }
3308−
3309− // Multi-column
3310− "column-width" => {
3311− if let Some(v) = val {
3312− push_css(&mut css, "column-width", &css_px(v));
3313− }
3314− }
3315− "column-rule" => {
3316− if let Some(v) = val {
3317− push_css(&mut css, "column-rule", v);
3318− }
3319− }
3320−
3321− // Place items/self
3322− "place-items" => {
3323− if let Some(v) = val {
3324− push_css(&mut css, "place-items", v);
3325− }
3326− }
3327− "place-self" => {
3328− if let Some(v) = val {
3329− push_css(&mut css, "place-self", v);
3330− }
3331− }
3332−
3333− // Scroll behavior
3334− "scroll-behavior" => {
3335− if let Some(v) = val {
3336− push_css(&mut css, "scroll-behavior", v);
3337− }
3338− }
3339−
3340− // Resize
3341− "resize" => {
3342− if let Some(v) = val {
3343− push_css(&mut css, "resize", v);
3344− }
3345− }
3346−
3347− // New CSS properties
3348− "clip-path" => {
3349− if let Some(v) = val {
3350− push_css(&mut css, "clip-path", v);
3351− }
3352− }
3353− "mix-blend-mode" => {
3354− if let Some(v) = val {
3355− push_css(&mut css, "mix-blend-mode", v);
3356− }
3357− }
3358− "background-blend-mode" => {
3359− if let Some(v) = val {
3360− push_css(&mut css, "background-blend-mode", v);
3361− }
3362− }
3363− "writing-mode" => {
3364− if let Some(v) = val {
3365− push_css(&mut css, "writing-mode", v);
3366− }
3367− }
3368− "column-count" => {
3369− if let Some(v) = val {
3370− push_css(&mut css, "column-count", v);
3371− }
3372− }
3373− "column-gap" => {
3374− if let Some(v) = val {
3375− push_css(&mut css, "column-gap", &css_px(v));
3376− }
3377− }
3378− "text-indent" => {
3379− if let Some(v) = val {
3380− push_css(&mut css, "text-indent", &css_px(v));
3381− }
3382− }
3383− "hyphens" => {
3384− if let Some(v) = val {
3385− push_css(&mut css, "hyphens", v);
3386− }
3387− }
3388− "flex-grow" => {
3389− if let Some(v) = val {
3390− push_css(&mut css, "flex-grow", v);
3391− }
3392− }
3393− "flex-shrink" => {
3394− if let Some(v) = val {
3395− push_css(&mut css, "flex-shrink", v);
3396− }
3397− }
3398− "flex-basis" => {
3399− if let Some(v) = val {
3400− push_css(&mut css, "flex-basis", &css_px(v));
3401− }
3402− }
3403− "isolation" => {
3404− if let Some(v) = val {
3405− push_css(&mut css, "isolation", v);
3406− }
3407− }
3408− "place-content" => {
3409− if let Some(v) = val {
3410− push_css(&mut css, "place-content", v);
3411− }
3412− }
3413− "background-image" => {
3414− if let Some(v) = val {
3415− push_css(&mut css, "background-image", v);
3416− }
3417− }
3418− "font-weight" => {
3419− if let Some(v) = val {
3420− push_css(&mut css, "font-weight", v);
3421− }
3422− }
3423− "font-style" => {
3424− if let Some(v) = val {
3425− push_css(&mut css, "font-style", v);
3426− }
3427− }
3428− "text-wrap" => {
3429− if let Some(v) = val {
3430− push_css(&mut css, "text-wrap", v);
3431− }
3432− }
3433− "will-change" => {
3434− if let Some(v) = val {
3435− push_css(&mut css, "will-change", v);
3436− }
3437− }
3438− "touch-action" => {
3439− if let Some(v) = val {
3440− push_css(&mut css, "touch-action", v);
3441− }
3442− }
3443− "vertical-align" => {
3444− if let Some(v) = val {
3445− push_css(&mut css, "vertical-align", v);
3446− }
3447− }
3448− "scroll-margin" => {
3449− if let Some(v) = val {
3450− push_css(&mut css, "scroll-margin", &css_px(v));
3451− }
3452− }
3453− "scroll-margin-top"
3454− | "scroll-margin-bottom"
3455− | "scroll-margin-left"
3456− | "scroll-margin-right" => {
3457− if let Some(v) = val {
3458− push_css(&mut css, effective_key, &css_px(v));
3459− }
3460− }
3461− "scroll-padding" => {
3462− if let Some(v) = val {
3463− push_css(&mut css, "scroll-padding", &css_px(v));
3464− }
3465− }
3466− "scroll-padding-top"
3467− | "scroll-padding-bottom"
3468− | "scroll-padding-left"
3469− | "scroll-padding-right" => {
3470− if let Some(v) = val {
3471− push_css(&mut css, effective_key, &css_px(v));
3472− }
3473− }
3474− "direction" => {
3475− if let Some(v) = val {
3476− push_css(&mut css, "direction", v);
3477− }
3478− }
3479−
3480− "content" => {
3481− if let Some(v) = val {
3482− // Wrap in quotes if not already quoted and not a CSS keyword
3483− if v.starts_with('"')
3484− || v.starts_with('\'')
3485− || v == "none"
3486− || v == "normal"
3487− || v.starts_with("attr(")
3488− || v.starts_with("counter(")
3489− {
3490− push_css(&mut css, "content", v);
3491− } else {
3492− push_css(&mut css, "content", &format!("\"{}\"", v));
3493− }
3494− }
3495− }
3496−
3497− // --- CSS Shorthands ---
3498− "truncate" => {
3499− push_css(&mut css, "overflow", "hidden");
3500− push_css(&mut css, "text-overflow", "ellipsis");
3501− push_css(&mut css, "white-space", "nowrap");
3502− }
3503− "line-clamp" => {
3504− if let Some(v) = val {
3505− push_css(&mut css, "display", "-webkit-box");
3506− push_css(&mut css, "-webkit-line-clamp", v);
3507− push_css(&mut css, "-webkit-box-orient", "vertical");
3508− push_css(&mut css, "overflow", "hidden");
3509− }
3510− }
3511− "blur" => {
3512− if let Some(v) = val {
3513− push_css(&mut css, "filter", &format!("blur({})", css_px(v)));
3514− }
3515− }
3516− "backdrop-blur" => {
3517− if let Some(v) = val {
3518− push_css(&mut css, "backdrop-filter", &format!("blur({})", css_px(v)));
3519− }
3520− }
3521− "no-scrollbar" => {
3522− push_css(&mut css, "scrollbar-width", "none");
3523− push_css(&mut css, "-ms-overflow-style", "none");
3524− }
3525− "skeleton" => {
3526− push_css(
3527− &mut css,
3528− "background",
3529− "linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%)",
3530− );
3531− push_css(&mut css, "background-size", "200% 100%");
3532− push_css(
3533− &mut css,
3534− "animation",
3535− "hl-skeleton 1.5s ease-in-out infinite",
3536− );
3537− }
3538− "gradient" => {
3539− if let Some(v) = val {
3540− // Parse: "from to [angle]" or "color1 color2 [angle]"
3541− let parts: Vec<&str> = v.split_whitespace().collect();
3542− let bg = if parts.len() >= 3
3543− && (parts[2].ends_with("deg")
3544− || parts[2].ends_with("turn")
3545− || parts[2].ends_with("rad"))
3546− {
3547− format!("linear-gradient({},{},{})", parts[2], parts[0], parts[1])
3548− } else if parts.len() >= 2 {
3549− format!("linear-gradient({},{})", parts[0], parts[1])
3550− } else {
3551− format!("linear-gradient({},transparent)", parts[0])
3552− };
3553− push_css(&mut css, "background", &bg);
3554− }
3555− }
3556−
3557− // Grid areas
3558− "grid-template-areas" => {
3559− if let Some(v) = val {
3560− push_css(&mut css, "grid-template-areas", v);
3561− }
3562− }
3563− "grid-area" => {
3564− if let Some(v) = val {
3565− push_css(&mut css, "grid-area", v);
3566− }
3567− }
3568−
3569− // View transitions
3570− "view-transition-name" => {
3571− if let Some(v) = val {
3572− push_css(&mut css, "view-transition-name", v);
3573− }
3574− }
3575−
3576−
3577− // CSS subgrid
3578− "grid-template-columns" => {
3579− if let Some(v) = val {
3580− push_css(&mut css, "grid-template-columns", v);
3581− }
3582− }
3583− "grid-template-rows" => {
3584− if let Some(v) = val {
3585− push_css(&mut css, "grid-template-rows", v);
3586− }
3587− }
3588−
3589− // Scroll-driven animations
3590− "animation-timeline" => {
3591− if let Some(v) = val {
3592− push_css(&mut css, "animation-timeline", v);
3593− }
3594− }
3595− "animation-range" => {
3596− if let Some(v) = val {
3597− push_css(&mut css, "animation-range", v);
3598− }
3599− }
3600− "view-timeline-name" => {
3601− if let Some(v) = val {
3602− push_css(&mut css, "view-timeline-name", v);
3603− }
3604− }
3605− "view-timeline-axis" => {
3606− if let Some(v) = val {
3607− push_css(&mut css, "view-timeline-axis", v);
3608− }
3609− }
3610− "scroll-timeline-name" => {
3611− if let Some(v) = val {
3612− push_css(&mut css, "scroll-timeline-name", v);
3613− }
3614− }
3615− "scroll-timeline-axis" => {
3616− if let Some(v) = val {
3617− push_css(&mut css, "scroll-timeline-axis", v);
3618− }
3619− }
3620−
3621− // Anchor positioning
3622− "anchor-name" => {
3623− if let Some(v) = val {
3624− push_css(&mut css, "anchor-name", v);
3625− }
3626− }
3627− "position-anchor" => {
3628− if let Some(v) = val {
3629− push_css(&mut css, "position-anchor", v);
3630− }
3631− }
3632− "position-area" => {
3633− if let Some(v) = val {
3634− push_css(&mut css, "position-area", v);
3635− }
3636− }
3637−
3638− // initial-letter (drop caps)
3639− "initial-letter" => {
3640− if let Some(v) = val {
3641− push_css(&mut css, "initial-letter", v);
3642− }
3643− }
3644−
3645− // Critical CSS hint — not CSS, handled elsewhere
3646− "critical" => {}
3647−
3648− // Identity and HTML passthrough — not CSS
3649− "id" | "class" => {}
3650− "type" | "placeholder" | "name" | "value" | "disabled" | "required" | "checked"
3651− | "for" | "action" | "method" | "autocomplete" | "min" | "max" | "step" | "pattern"
3652− | "maxlength" | "rows" | "cols" | "multiple" | "alt" | "role" | "tabindex"
3653− | "title" | "controls" | "autoplay" | "loop" | "muted" | "playsinline" | "poster"
3654− | "preload" | "loading" | "decoding" | "ordered" | "src" | "open" | "novalidate"
3655− | "low" | "high" | "optimum" | "colspan" | "rowspan" | "scope" | "inline"
3656− | "responsive" | "datetime" | "media" | "sizes" | "srcset" | "cite" | "list"
3657− | "sandbox" | "allow" | "allowfullscreen" | "referrerpolicy" | "formaction"
3658− | "formmethod" | "formtarget" | "target" | "autofocus" => {}
36592309
36602310 _ => {}
36612311 }
36622312 }
36632313
2314+ css.push_str(&aligned);
36642315 css
36652316}
36662317
@@ -3671,262 +2322,10 @@ fn push_css(css: &mut String, prop: &str, value: &str) {
36712322 css.push(';');
36722323}
36732324
3674−/// Known CSS units — if a value ends with one, skip appending `px`.
3675−/// Format a length value: a bare number gets `px` appended; anything else
3676−/// (values with units, keywords like `auto`, functions like `calc(...)`) is
3677−/// passed through unchanged.
3678−fn css_px(value: &str) -> String {
3679− let v = value.trim();
3680− if v == "0" {
3681− return "0".to_string();
3682− }
3683− let is_bare_number = !v.is_empty()
3684− && v.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'-' | b'+'))
3685− && v.parse::<f64>().is_ok();
3686− if is_bare_number {
3687− format!("{}px", v)
3688− } else {
3689− v.to_string()
3690− }
3691−}
3692−
3693−/// Rewrite literal values that match a declared CSS custom property (from
3694−/// `@theme` or `@let --name value`) to `var(--name)` references. Matches are
3695−/// anchored to CSS value boundaries so e.g. `#3b82f6` inside a longer hex or
3696−/// inside an identifier is not replaced. The `:root` block is emitted before
3697−/// this call runs, so its declarations are not affected.
3698−fn substitute_css_vars(css: &str, vars: &[(String, String)]) -> String {
3699− if css.is_empty() || vars.is_empty() {
3700− return css.to_string();
3701− }
3702− // Prefer longer values first so that if two vars share a prefix, the
3703− // longer (more specific) match wins.
3704− let mut pairs: Vec<(&str, String)> = vars
3705− .iter()
3706− .filter(|(name, value)| name.starts_with("--") && !value.is_empty())
3707− .map(|(name, value)| (value.as_str(), format!("var({})", name)))
3708− .collect();
3709− pairs.sort_by_key(|(v, _)| std::cmp::Reverse(v.len()));
3710− if pairs.is_empty() {
3711− return css.to_string();
3712− }
3713−
3714− let is_boundary_before = |b: Option<u8>| match b {
3715− None => true,
3716− Some(c) => matches!(c, b':' | b' ' | b',' | b'(' | b';' | b'{' | b'\n' | b'\t'),
3717− };
3718− let is_boundary_after = |b: Option<u8>| match b {
3719− None => true,
3720− Some(c) => matches!(c, b';' | b'}' | b',' | b' ' | b')' | b'\n' | b'\t'),
3721− };
3722−
3723− let bytes = css.as_bytes();
3724− let mut out = String::with_capacity(css.len());
3725− let mut i = 0;
3726− let mut prev: Option<u8> = None;
3727− // Only declaration values are rewritten — never selectors or at-rule
3728− // preludes such as `@media (min-width:768px)`. `blocks` records, for
3729− // each open `{`, whether it holds declarations (a style rule) or nested
3730− // rules (an at-rule like `@media` / `@layer`).
3731− let mut blocks: Vec<bool> = Vec::new();
3732− let mut prelude_start = 0;
3733− let mut in_value = false;
3734− while i < bytes.len() {
3735− match bytes[i] {
3736− b'{' => {
3737− let prelude = css[prelude_start..i].trim_start();
3738− blocks.push(!prelude.starts_with('@'));
3739− in_value = false;
3740− prelude_start = i + 1;
3741− }
3742− b'}' => {
3743− blocks.pop();
3744− in_value = false;
3745− prelude_start = i + 1;
3746− }
3747− b';' => {
3748− in_value = false;
3749− prelude_start = i + 1;
3750− }
3751− b':' if blocks.last() == Some(&true) => in_value = true,
3752− _ => {}
3753− }
3754− if in_value && is_boundary_before(prev) {
3755− let mut matched = false;
3756− for (val, repl) in &pairs {
3757− let vb = val.as_bytes();
3758− if i + vb.len() <= bytes.len() && &bytes[i..i + vb.len()] == vb {
3759− let next = bytes.get(i + vb.len()).copied();
3760− if is_boundary_after(next) {
3761− out.push_str(repl);
3762− prev = repl.as_bytes().last().copied();
3763− i += vb.len();
3764− matched = true;
3765− break;
3766− }
3767− }
3768− }
3769− if matched {
3770− continue;
3771− }
3772− }
3773− // Advance by one UTF-8 code point.
3774− let start = i;
3775− i += 1;
3776− while i < bytes.len() && (bytes[i] & 0xC0) == 0x80 {
3777− i += 1;
3778− }
3779− out.push_str(&css[start..i]);
3780− prev = bytes.get(i - 1).copied();
3781− }
3782− out
3783−}
3784−
3785−/// Scan generated CSS for literal property values that repeat often enough
3786−/// that substituting them with an auto-named custom property would reduce
3787−/// total byte count. Returns the rewritten CSS and any new vars that should
3788−/// be appended to `:root`.
3789−///
3790−/// The algorithm only promotes a value if it strictly saves bytes after
3791−/// accounting for the `--xN:value;` declaration overhead plus the
3792−/// `var(--xN)` reference cost at each call site. Values that are already
3793−/// `var(...)` references or contain `var(` calls are skipped so we never
3794−/// nest references. Names avoid collisions with `existing_vars`.
3795−fn auto_extract_repeats(
3796− css: &str,
3797− existing_vars: &[(String, String)],
3798−) -> (String, Vec<(String, String)>) {
3799− if css.is_empty() {
3800− return (css.to_string(), Vec::new());
3801− }
3802− // Count occurrences of each distinct property value (the text between
3803− // `:` and the next `;` or `}` at the top level of a declaration block,
3804− // ignoring balanced parentheses so that e.g. `rgba(...)` stays intact).
3805− let bytes = css.as_bytes();
3806− let mut counts: HashMap<String, usize> = HashMap::new();
3807− let mut depth: i32 = 0;
3808− let mut i = 0;
3809− while i < bytes.len() {
3810− match bytes[i] {
3811− b'{' => {
3812− depth += 1;
3813− i += 1;
3814− continue;
3815− }
3816− b'}' => {
3817− if depth > 0 {
3818− depth -= 1;
3819− }
3820− i += 1;
3821− continue;
3822− }
3823− _ => {}
3824− }
3825− if depth > 0 && bytes[i] == b':' {
3826− // Skip past `:` then walk to the terminator.
3827− let start = i + 1;
3828− let mut end = start;
3829− let mut pdepth = 0i32;
3830− while end < bytes.len() {
3831− match bytes[end] {
3832− b'(' => pdepth += 1,
3833− b')' if pdepth > 0 => pdepth -= 1,
3834− b';' | b'}' if pdepth == 0 => break,
3835− b'{' if pdepth == 0 => break,
3836− _ => {}
3837− }
3838− end += 1;
3839− }
3840− let val = css[start..end].trim();
3841− if !val.is_empty() && !val.starts_with("var(") && !val.contains("var(") {
3842− *counts.entry(val.to_string()).or_default() += 1;
3843− }
3844− i = end;
3845− continue;
3846− }
3847− i += 1;
3848− }
3849−
3850− // Decide which values are worth extracting. A value of length L appearing
3851− // N times costs N*L bytes inline; promoting it costs (L + 6) for the
3852− // `--hK:V;` declaration plus N * ref_len for the call sites. We estimate
3853− // ref_len optimistically as `var(--h0)` (9 bytes) and fall back to 10 for
3854− // two-digit indices, which only affects very large extraction counts.
3855− let existing: std::collections::HashSet<&str> =
3856− existing_vars.iter().map(|(n, _)| n.as_str()).collect();
3857− let mut candidates: Vec<(String, usize)> =
3858− counts.into_iter().filter(|(_, n)| *n >= 2).collect();
3859− // Stable, deterministic ordering — longest values first, tiebreak by text.
3860− candidates.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
3861−
3862− let mut extracted: Vec<(String, String)> = Vec::new();
3863− let mut next_idx: usize = 0;
3864− for (value, n) in candidates {
3865− let l = value.len();
3866− // Allocate the next unused `--hN` name.
3867− let (name, ref_len) = loop {
3868− let candidate = format!("--h{}", next_idx);
3869− next_idx += 1;
3870− let rl = candidate.len() + 6; // `var(` + name + `)`
3871− if !existing.contains(candidate.as_str())
3872− && !extracted.iter().any(|(n, _)| *n == candidate)
3873− {
3874− break (candidate, rl);
3875− }
3876− };
3877− // Skip if promotion would not strictly reduce byte count.
3878− // Before: n * l bytes. After: (l + name.len() + 2) for the :root
3879− // declaration (`<name>:<value>;`) plus n * ref_len for the sites.
3880− let decl_overhead = l + name.len() + 2;
3881− let before = n * l;
3882− let after = decl_overhead + n * ref_len;
3883− if after < before {
3884− extracted.push((name, value));
3885− } else {
3886− // Rewind the index so the next value can reuse this slot.
3887− next_idx -= 1;
3888− }
3889− }
3890−
3891− if extracted.is_empty() {
3892− return (css.to_string(), Vec::new());
3893− }
3894− let new_css = substitute_css_vars(css, &extracted);
3895− (new_css, extracted)
3896−}
3897−
3898−/// Format a `line-height` value. CSS accepts either a unitless multiplier
3899−/// (e.g. `1.5`) or a length (e.g. `24px`). Plain integers in htmlang source
3900−/// are ambiguous: `[line-height 24]` was historically emitted as `24` (which
3901−/// CSS interprets as 24× font-size — almost never what anyone wants). Treat
3902−/// integers ≥ 2 as pixel lengths; anything with a decimal, an existing unit,
3903−/// or the value `0`/`1` passes through unchanged.
3904−fn css_line_height(value: &str) -> String {
3905− let v = value.trim();
3906− if v == "0" || v == "1" {
3907− return v.to_string();
3908− }
3909− // Plain integer — treat as pixel length. Decimals, units, keywords and
3910− // functions pass through.
3911− if !v.is_empty() && v.chars().all(|c| c.is_ascii_digit()) {
3912− return format!("{}px", v);
3913− }
3914− v.to_string()
3915−}
3916−
3917−/// Format multiple space-separated values, each getting px if needed.
3918−fn css_px_multi(value: &str) -> String {
3919− value
3920− .split_whitespace()
3921− .map(css_px)
3922− .collect::<Vec<_>>()
3923− .join(" ")
3924−}
3925−
39262325fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
39272326 let mut id = None;
39282327 let mut class = None;
3929− for attr in attrs {
2328+ for attr in attrs.iter().filter(|a| a.html) {
39302329 match attr.key.as_str() {
39312330 "id" => id = attr.value.clone(),
39322331 "class" => class = attr.value.clone(),
@@ -3936,153 +2335,6 @@ fn extract_id_class(attrs: &[Attribute]) -> (Option<String>, Option<String>) {
39362335 (id, class)
39372336}
39382337
3939−/// Read image dimensions from a local file by parsing the header bytes.
3940−/// Supports PNG, JPEG, GIF, WebP, AVIF, and SVG.
3941−fn read_image_dimensions(path: &str) -> Option<(u32, u32)> {
3942− // SVG: parse as text for viewBox/width/height attributes
3943− if path.ends_with(".svg") || path.ends_with(".SVG") {
3944− let text = std::fs::read_to_string(path).ok()?;
3945− return read_svg_dimensions(&text);
3946− }
3947−
3948− let data = std::fs::read(path).ok()?;
3949− if data.len() < 12 {
3950− return None;
3951− }
3952−
3953− // PNG: 8-byte signature, then IHDR chunk with width/height at bytes 16-23
3954− if data.len() >= 24 && data.starts_with(b"\x89PNG\r\n\x1a\n") {
3955− let w = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
3956− let h = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
3957− return Some((w, h));
3958− }
3959−
3960− // GIF: "GIF87a" or "GIF89a", width/height at bytes 6-9 (little-endian)
3961− if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
3962− let w = u16::from_le_bytes([data[6], data[7]]) as u32;
3963− let h = u16::from_le_bytes([data[8], data[9]]) as u32;
3964− return Some((w, h));
3965− }
3966−
3967− // JPEG: scan for SOF0/SOF2 marker (0xFF 0xC0 or 0xFF 0xC2)
3968− if data.starts_with(b"\xff\xd8") {
3969− let mut i = 2;
3970− while i + 9 < data.len() {
3971− if data[i] != 0xFF {
3972− i += 1;
3973− continue;
3974− }
3975− let marker = data[i + 1];
3976− if marker == 0xC0 || marker == 0xC2 {
3977− let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as u32;
3978− let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as u32;
3979− return Some((w, h));
3980− }
3981− if i + 3 < data.len() {
3982− let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
3983− i += 2 + len;
3984− } else {
3985− break;
3986− }
3987− }
3988− }
3989−
3990− // WebP: "RIFF" ... "WEBP", VP8 header at byte 20
3991− if data.len() >= 30 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
3992− if &data[12..16] == b"VP8 " && data.len() >= 30 {
3993− let w = u16::from_le_bytes([data[26], data[27]]) as u32 & 0x3FFF;
3994− let h = u16::from_le_bytes([data[28], data[29]]) as u32 & 0x3FFF;
3995− return Some((w, h));
3996− }
3997− if &data[12..16] == b"VP8L" && data.len() >= 25 && data[21] == 0x2F {
3998− let bits = u32::from_le_bytes([data[22], data[23], data[24], data[25]]);
3999− let w = (bits & 0x3FFF) + 1;
4000− let h = ((bits >> 14) & 0x3FFF) + 1;
4001− return Some((w, h));
4002− }
4003− }
4004−
4005− // AVIF: ISOBMFF container with "ftyp" box containing "avif"/"avis" brand,
4006− // then "ispe" box with width/height
4007− if data.len() >= 12 && &data[4..8] == b"ftyp" {
4008− let brand = &data[8..12];
4009− if brand == b"avif" || brand == b"avis" || brand == b"mif1" {
4010− return read_avif_dimensions(&data);
4011− }
4012− }
4013−
4014− None
4015−}
4016−
4017−/// Parse SVG viewBox or width/height attributes to get dimensions.
4018−fn read_svg_dimensions(text: &str) -> Option<(u32, u32)> {
4019− // Try viewBox first: viewBox="minX minY width height"
4020− if let Some(vb_start) = text.find("viewBox=\"") {
4021− let rest = &text[vb_start + 9..];
4022− if let Some(end) = rest.find('"') {
4023− let parts: Vec<&str> = rest[..end].split_whitespace().collect();
4024− if parts.len() == 4
4025− && let (Ok(w), Ok(h)) = (parts[2].parse::<f64>(), parts[3].parse::<f64>())
4026− && w > 0.0
4027− && h > 0.0
4028− {
4029− return Some((w.round() as u32, h.round() as u32));
4030− }
4031− }
4032− }
4033− // Fall back to width/height attributes on <svg>
4034− let svg_tag = text.find("<svg")?;
4035− let tag_end = text[svg_tag..].find('>')? + svg_tag;
4036− let tag = &text[svg_tag..tag_end];
4037− let w = extract_svg_attr(tag, "width")?;
4038− let h = extract_svg_attr(tag, "height")?;
4039− Some((w, h))
4040−}
4041−
4042−fn extract_svg_attr(tag: &str, attr: &str) -> Option<u32> {
4043− let needle = format!("{}=\"", attr);
4044− let start = tag.find(&needle)? + needle.len();
4045− let rest = &tag[start..];
4046− let end = rest.find('"')?;
4047− let val = rest[..end].trim_end_matches("px");
4048− val.parse::<f64>().ok().map(|v| v.round() as u32)
4049−}
4050−
4051−/// Parse AVIF (ISOBMFF) container to find ispe box with image dimensions.
4052−fn read_avif_dimensions(data: &[u8]) -> Option<(u32, u32)> {
4053− // Walk ISOBMFF boxes looking for "ispe" (image spatial extents)
4054− let mut i = 0;
4055− while i + 8 <= data.len() {
4056− let box_size =
4057− u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) as usize;
4058− let box_type = &data[i + 4..i + 8];
4059− if box_size < 8 {
4060− break;
4061− }
4062− let box_end = (i + box_size).min(data.len());
4063− // ispe box: 4 bytes version/flags + 4 bytes width + 4 bytes height
4064− if box_type == b"ispe" && box_end >= i + 20 {
4065− let w = u32::from_be_bytes([data[i + 12], data[i + 13], data[i + 14], data[i + 15]]);
4066− let h = u32::from_be_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
4067− return Some((w, h));
4068− }
4069− // Recurse into container boxes (meta, iprp, ipco)
4070− if matches!(
4071− box_type,
4072− b"meta" | b"iprp" | b"ipco" | b"moov" | b"trak" | b"mdia"
4073− ) {
4074− let header_size = if box_type == b"meta" { 12 } else { 8 };
4075− if i + header_size < box_end
4076− && let Some(dims) = read_avif_dimensions(&data[i + header_size..box_end])
4077− {
4078− return Some(dims);
4079− }
4080− }
4081− i = box_end;
4082− }
4083− None
4084−}
4085−
40862338fn html_escape(s: &str) -> String {
40872339 s.replace('&', "&")
40882340 .replace('<', "<")
@@ -4198,49 +2450,30 @@ fn vlq_encode(value: i64, out: &mut String) {
41982450 }
41992451}
42002452
4201−/// Check if a specific element kind exists anywhere in the node tree.
4202−fn has_element_kind(nodes: &[Node], target: &ElementKind) -> bool {
4203− for node in nodes {
4204− if let Node::Element(elem) = node {
4205− if elem.kind == *target {
4206− return true;
4207− }
4208− if has_element_kind(&elem.children, target) {
4209− return true;
4210− }
4211− }
4212− }
4213− false
4214−}
4215−
4216−/// Collect unique external domains from generated HTML for DNS prefetch hints.
4217−fn collect_dns_prefetch(html: &str, dev: bool) -> String {
4218− let mut domains = Vec::new();
4219− let mut rest = html;
4220− while let Some(pos) = rest.find("https://") {
4221− let start = pos + 8; // skip "https://"
4222− rest = &rest[start..];
4223− let end = rest
4224− .find(['/', '"', '\'', ' ', '>', ')'])
4225− .unwrap_or(rest.len());
4226− let domain = &rest[..end];
4227− if !domain.is_empty() && domain.contains('.') && !domains.contains(&domain.to_string()) {
4228− domains.push(domain.to_string());
4229− }
4230− }
4231− let mut out = String::new();
4232− for domain in &domains {
4233− if dev {
4234− out.push_str(&format!(
4235− "<link rel=\"dns-prefetch\" href=\"//{}\">\n",
4236− domain
4237− ));
4238− } else {
4239− out.push_str(&format!(
4240− "<link rel=\"dns-prefetch\" href=\"//{}\">",
4241− domain
4242− ));
4243− }
2453+#[cfg(test)]
2454+mod tests {
2455+ use super::*;
2456+
2457+ #[test]
2458+ fn a_name_is_a_stable_hash_of_the_style() {
2459+ // The same in every build and on every platform
2460+ assert_eq!(stable_hash(""), 0xf52a_15e9_a9b5_e89b);
2461+ assert_eq!(hash_digits(35, 3), "z00");
2462+ assert_eq!(hash_digits(u64::MAX, 13), "fsgs46211e5w3");
2463+ }
2464+
2465+ #[test]
2466+ fn a_name_taken_in_the_file_takes_more_digits() {
2467+ // These two styles' hashes end in the same 7 digits
2468+ let mut styles = StyleCollector::new();
2469+ let first = styles.get_class("width:129555px;".into(), Vec::new(), String::new());
2470+ let second = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
2471+ let (first, second) = (first.unwrap(), second.unwrap());
2472+ assert_eq!(first.len(), 3 + CLASS_DIGITS, "{first}");
2473+ assert_eq!(second.len(), 3 + CLASS_DIGITS + 1, "{second}");
2474+ assert!(second.starts_with(&first), "{first} {second}");
2475+ // The same style gets the name it got before
2476+ let again = styles.get_class("width:170577px;".into(), Vec::new(), String::new());
2477+ assert_eq!(again.as_deref(), Some(second.as_str()));
42442478 }
4245− out
42462479}