leaf_core/style.rs
1//! A toolkit-neutral text style — the seam that lets one document model drive
2//! any frontend.
3//!
4//! The WYSIWYG builder ([`crate::wysiwyg`]) tags each rendered glyph with one of
5//! these instead of a `ratatui::Style` or a `gpui::TextStyle`, so the caret
6//! model and the AST→glyph layout stay free of any GUI/TUI dependency.
7//!
8//! What core records is *what a glyph is*, never *what color to paint it*: a
9//! [`Role`] (heading, code, link, a list bullet, …) plus the portable emphasis
10//! the author actually wrote (`**bold**`, `*em*`, `{+ins+}`, `{-del-}`). Palette
11//! is presentation, and presentation belongs to the frontend — a terminal tells
12//! a heading from body text by color because color is all it can vary, while a
13//! GUI varies size and font instead. So each frontend maps a [`Role`] to its own
14//! look: `leaf-tui` turns it into terminal colors, `leaf-gpui` into an `Hsla`
15//! plus a font size and family. Core stays out of that argument.
16//!
17//! The one place core does carry a paint value is the presentation vocabulary
18//! the author writes by hand: a `data-size` is a *name* ([`SizeStep`]) where a
19//! name will do and a measurement ([`FontSize::Points`]) where the author needed
20//! exactness, and the open type beside each closed enum — [`FontSize`],
21//! [`LineHeight`], [`TextColor`], [`FontFace`] — is where the two meet. A name
22//! outlives a theme change and a value does not, which is the trade the author
23//! makes knowingly; see `docs/proposals/exact-presentation-values.md`.
24
25use std::borrow::Cow;
26
27/// The value `key` carries in an attribute list, or `None` where the key is
28/// absent or bare (`<span data-size>`, which names nothing).
29///
30/// The one line every `from_attrs` in this module opens with. It takes the
31/// attribute list rather than the node so the module stays free of twig as well
32/// as of any toolkit; the pairs are plain `String`s, and the WYSIWYG builder,
33/// the source builder and the caret queries all hand over the same
34/// `node.attrs`.
35fn attr<'a>(attrs: &'a [(String, Option<String>)], key: &str) -> Option<&'a str> {
36 attrs
37 .iter()
38 .find(|(k, _)| k == key)
39 .and_then(|(_, v)| v.as_deref())
40}
41
42/// What a glyph *is*, typographically — the semantic role a frontend maps to its
43/// own presentation. Mutually exclusive per glyph (a glyph is a heading, or a
44/// link, or body text — not two at once); the compositional emphasis a run can
45/// also carry lives in [`Style`]'s `bold`/`italic`/`underline`/`strikethrough`
46/// flags alongside this.
47#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
48pub enum Role {
49 /// Ordinary prose — the surface's default text.
50 #[default]
51 Body,
52 /// A heading of the given level (1 = top). A GUI scales the font by level; a
53 /// terminal cycles a color by it.
54 Heading(u8),
55 /// Code — inline `` `verbatim` `` or a fenced block. A GUI renders it in a
56 /// monospace family; a terminal tints it.
57 Code,
58 /// A hyperlink's visible text (or bare URL/email).
59 Link,
60 /// Highlighted / marked text (`==mark==`), carrying the colour the author
61 /// named if they named one. `None` is a plain highlight — the only kind
62 /// there was before twig grew Obsidian's `==🔴 red==` spelling, and
63 /// still the only kind a format without the colour extension can produce.
64 Mark(Option<MarkColor>),
65 /// A list item's bullet or number — synthetic decoration, not authored text.
66 ListMarker,
67 /// A block quote's gutter (`│`), drawn down its left edge.
68 QuoteGutter,
69 /// A drawn rule: a thematic break (`───`) or a table's borders. A GUI that
70 /// draws its own tables ignores the border glyphs; the rule still reaches it.
71 Rule,
72 /// Raw markup a revealed line is showing: the `*` around an emphasis, the
73 /// `# ` opening a heading, a link's `](dest)`. Only ever emitted for the
74 /// caret's line under [`MarkupMode::Full`](crate::MarkupMode::Full) —
75 /// every other line resolves its markup away and has none of these.
76 ///
77 /// A role rather than a `Style` flag because it is what the glyph *is*: the
78 /// delimiter of an emphasis is not itself emphasised text. A frontend
79 /// typically dims it, so the revealed line still reads as prose with its
80 /// scaffolding visible rather than as source code. One that doesn't map it
81 /// draws it as body text, which is correct if unsubtle.
82 Delimiter,
83 /// A block-level image's placeholder text (`🖼 alt`). The glyphs are a
84 /// *default* rendering any surface can paint as-is (a terminal shows the
85 /// label); an image-capable frontend skips the placeholder row named by the
86 /// map's [`MediaInfo`](crate::wysiwyg::MediaInfo) `rows_span` and paints the
87 /// real picture in its place — the same skip-the-picture contract
88 /// [`Role::Rule`] table borders use.
89 Image,
90}
91
92/// The colour an author named on a highlight — the closed vocabulary twig
93/// records as a `mark` node's `data-color`, one variant per circle emoji the
94/// `==🔴 text==` spelling recognises.
95///
96/// A *name*, not a paint value, which is why this lives in core at all when
97/// [`Style`] otherwise holds no colour: `red` here is what the author wrote,
98/// and each frontend still decides which red draws it — a terminal picks an
99/// ANSI hue, a GUI an `Hsla`, the web a CSS custom property. The distinction is
100/// the same one [`Role::Heading`] makes by carrying a level rather than a size.
101///
102/// These seven stay the whole of a *highlight's* vocabulary, because they are
103/// encoded in twig's Markdown bytes as circle emoji and are twig's to keep
104/// closed. A run's foreground has no such constraint and opens: see
105/// [`TextColor`], which is one of these names or a hex triple.
106#[derive(Clone, Copy, PartialEq, Eq, Debug)]
107pub enum MarkColor {
108 Red,
109 Orange,
110 Yellow,
111 Green,
112 Blue,
113 Purple,
114 Brown,
115}
116
117impl MarkColor {
118 /// The colour a `mark` node's attributes name, if any — twig records it
119 /// under `data-color`, having stripped the emoji that spelled it out of the
120 /// node's content.
121 ///
122 /// Reads the list through [`attr`], which is why the pairs are plain
123 /// `String`s rather than anything of twig's.
124 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
125 attr(attrs, "data-color").and_then(Self::from_attr)
126 }
127
128 /// Read a `data-color` attribute value. `None` for a name outside the
129 /// vocabulary, which a frontend then draws as a plain highlight rather than
130 /// guessing at a hue.
131 pub fn from_attr(value: &str) -> Option<Self> {
132 Some(match value {
133 "red" => Self::Red,
134 "orange" => Self::Orange,
135 "yellow" => Self::Yellow,
136 "green" => Self::Green,
137 "blue" => Self::Blue,
138 "purple" => Self::Purple,
139 "brown" => Self::Brown,
140 _ => return None,
141 })
142 }
143
144 /// The name twig spells it with, and what [`from_attr`](Self::from_attr)
145 /// reads back — also the suffix the web and Swift frontends build a class
146 /// id out of.
147 pub const fn name(self) -> &'static str {
148 match self {
149 Self::Red => "red",
150 Self::Orange => "orange",
151 Self::Yellow => "yellow",
152 Self::Green => "green",
153 Self::Blue => "blue",
154 Self::Purple => "purple",
155 Self::Brown => "brown",
156 }
157 }
158
159 /// This colour's position in [`ALL`](Self::ALL) — the index a frontend's
160 /// own palette array is keyed by, the way [`Role::Heading`]'s level keys a
161 /// heading ramp.
162 pub const fn index(self) -> usize {
163 match self {
164 Self::Red => 0,
165 Self::Orange => 1,
166 Self::Yellow => 2,
167 Self::Green => 3,
168 Self::Blue => 4,
169 Self::Purple => 5,
170 Self::Brown => 6,
171 }
172 }
173
174 /// Every colour, in the order twig's own enum declares them. The frontends
175 /// iterate this to build their palettes, so a colour added here is one a
176 /// palette test immediately demands an entry for.
177 pub const ALL: [Self; 7] = [
178 Self::Red,
179 Self::Orange,
180 Self::Yellow,
181 Self::Green,
182 Self::Blue,
183 Self::Purple,
184 Self::Brown,
185 ];
186}
187
188/// How a block's lines are set across the measure — the one presentation
189/// property an author reaches for before any other, and the only one of the
190/// six whose vocabulary is a *class* rather than a `data-` key.
191///
192/// A `class` is a space-separated token list in every format leaf opens, and
193/// this reads the one token it knows and leaves the rest: a paragraph that
194/// arrives as `class="lead center"` is centred and keeps `lead`. A token
195/// outside the vocabulary is not an error — it is somebody else's class, and a
196/// document from elsewhere passes through the editor unharmed.
197///
198/// There is no `Left`, because absence is left: the default alignment is the
199/// theme's, and a document that agrees with it has no reason to say so. A
200/// right-to-left default is a theme matter, not a class.
201#[derive(Clone, Copy, PartialEq, Eq, Debug)]
202pub enum Align {
203 Center,
204 Right,
205 Justify,
206}
207
208impl Align {
209 /// The alignment a block's attributes name, if any — the first token of
210 /// `class` that is one of the three, in source order.
211 ///
212 /// Takes the attribute list rather than the node for [`MarkColor`]'s
213 /// reason: this module stays free of twig as well as of any toolkit, and
214 /// both the block walker and the caret query hand over the same
215 /// `node.attrs`.
216 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
217 attr(attrs, "class")?
218 .split_whitespace()
219 .find_map(Self::from_token)
220 }
221
222 /// Read one `class` token. `None` for a token outside the vocabulary,
223 /// which is how a foreign class is *kept* rather than misread — the
224 /// gesture that rewrites the alignment removes only the tokens this
225 /// answers `Some` for.
226 pub fn from_token(token: &str) -> Option<Self> {
227 Some(match token {
228 "center" => Self::Center,
229 "right" => Self::Right,
230 "justify" => Self::Justify,
231 _ => return None,
232 })
233 }
234
235 /// The token twig spells it with, and what [`from_token`](Self::from_token)
236 /// reads back — also the class a frontend's stylesheet selects on, which is
237 /// why it is CSS's own word for the same thing.
238 pub const fn name(self) -> &'static str {
239 match self {
240 Self::Center => "center",
241 Self::Right => "right",
242 Self::Justify => "justify",
243 }
244 }
245
246 /// This alignment's position in [`ALL`](Self::ALL) — the index a frontend's
247 /// own segmented control is keyed by, the way [`MarkColor::index`] keys a
248 /// palette.
249 pub const fn index(self) -> usize {
250 match self {
251 Self::Center => 0,
252 Self::Right => 1,
253 Self::Justify => 2,
254 }
255 }
256
257 /// Every alignment, in the order a toolbar offers them. Left is absent
258 /// because absence *is* left; a segmented control draws a fourth segment
259 /// for it and calls [`crate::Doc::set_alignment`] with `None`.
260 pub const ALL: [Self; 3] = [Self::Center, Self::Right, Self::Justify];
261}
262
263/// How far apart a block's lines are set, as a multiple of the theme's own line
264/// height — the spacing menu every word processor has, less the single spacing
265/// that is absence.
266///
267/// The tokens are the numbers rather than names (`loose`, `double`) so that a
268/// stylesheet's line is `line-height: 1.5` and a reader of the source sees the
269/// ratio. `1` is not a token, because `1` is absence and a document should not
270/// carry a key that says nothing.
271#[derive(Clone, Copy, PartialEq, Eq, Debug)]
272pub enum LineSpacing {
273 /// `1.15` — the word processor's default "a little more air".
274 OneFifteen,
275 /// `1.5`.
276 OneHalf,
277 /// `2` — double spacing.
278 Double,
279}
280
281impl LineSpacing {
282 /// The spacing a block's attributes name, if any — twig records it under
283 /// `data-line-height`.
284 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
285 attr(attrs, "data-line-height").and_then(Self::from_attr)
286 }
287
288 /// Read a `data-line-height` value. `None` for anything that is not one of
289 /// the three names — an exact ratio is [`LineHeight::Ratio`]'s to read, and
290 /// [`LineHeight::from_attr`] is the door that reads both.
291 pub fn from_attr(value: &str) -> Option<Self> {
292 Some(match value {
293 "1.15" => Self::OneFifteen,
294 "1.5" => Self::OneHalf,
295 "2" => Self::Double,
296 _ => return None,
297 })
298 }
299
300 /// The token twig spells it with, and what [`from_attr`](Self::from_attr)
301 /// reads back.
302 pub const fn name(self) -> &'static str {
303 match self {
304 Self::OneFifteen => "1.15",
305 Self::OneHalf => "1.5",
306 Self::Double => "2",
307 }
308 }
309
310 /// The ratio itself — what a frontend multiplies the theme's line height by
311 /// to lay the row out. A *derived* number, not a carried one: the document
312 /// says `1.5`, and this is that name read as arithmetic.
313 pub const fn ratio(self) -> f32 {
314 match self {
315 Self::OneFifteen => 1.15,
316 Self::OneHalf => 1.5,
317 Self::Double => 2.0,
318 }
319 }
320
321 /// This spacing's position in [`ALL`](Self::ALL) — the index a frontend's
322 /// own menu is keyed by.
323 pub const fn index(self) -> usize {
324 match self {
325 Self::OneFifteen => 0,
326 Self::OneHalf => 1,
327 Self::Double => 2,
328 }
329 }
330
331 /// Every spacing, in the order a menu offers them. Single is absent for the
332 /// reason `left` is absent from [`Align::ALL`].
333 pub const ALL: [Self; 3] = [Self::OneFifteen, Self::OneHalf, Self::Double];
334}
335
336/// How large a run is set relative to the text around it — CSS's
337/// `<absolute-size>` keyword set with `medium` removed, because `medium` is
338/// absence.
339///
340/// A *step*, never a measurement, for the reason [`MarkColor`] is a name and
341/// not a hex triple: a run set to `14pt` in a theme whose body is 12pt is a
342/// step up, and the same run under a 16pt theme is a step *down* — the author's
343/// intent inverted by a change they never made. A run set to `Large` is a step
344/// up under every theme.
345///
346/// A heading keeps its own ramp: a `data-size` on a heading scales the
347/// heading's size, not the body's.
348#[derive(Clone, Copy, PartialEq, Eq, Debug)]
349pub enum SizeStep {
350 XxSmall,
351 XSmall,
352 Small,
353 Large,
354 XLarge,
355 XxLarge,
356 XxxLarge,
357}
358
359impl SizeStep {
360 /// The size a run's or block's attributes name, if any — twig records it
361 /// under `data-size`.
362 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
363 attr(attrs, "data-size").and_then(Self::from_attr)
364 }
365
366 /// Read a `data-size` value. `None` for a name outside the vocabulary — a
367 /// `data-size="14pt"` is a measurement and [`FontSize::Points`]'s to read,
368 /// and [`FontSize::from_attr`] is the door that reads both.
369 pub fn from_attr(value: &str) -> Option<Self> {
370 Some(match value {
371 "xx-small" => Self::XxSmall,
372 "x-small" => Self::XSmall,
373 "small" => Self::Small,
374 "large" => Self::Large,
375 "x-large" => Self::XLarge,
376 "xx-large" => Self::XxLarge,
377 "xxx-large" => Self::XxxLarge,
378 _ => return None,
379 })
380 }
381
382 /// The token twig spells it with, and what [`from_attr`](Self::from_attr)
383 /// reads back — CSS's own keyword, so a stylesheet rule is
384 /// `[data-size="large"] { font-size: large }` and nothing is learned twice.
385 pub const fn name(self) -> &'static str {
386 match self {
387 Self::XxSmall => "xx-small",
388 Self::XSmall => "x-small",
389 Self::Small => "small",
390 Self::Large => "large",
391 Self::XLarge => "x-large",
392 Self::XxLarge => "xx-large",
393 Self::XxxLarge => "xxx-large",
394 }
395 }
396
397 /// The multiple of the theme's body size this step sets — the ratios CSS's
398 /// own user-agent stylesheet uses for the same seven words, so a browser
399 /// given only leaf's stylesheet and a native renderer given the theme agree
400 /// about how big `large` is.
401 ///
402 /// A *default*: a theme is free to scale its own ramp, the way a frontend
403 /// is free to pick its own red for [`MarkColor::Red`]. What the document
404 /// carries is the name.
405 pub const fn scale(self) -> f32 {
406 match self {
407 Self::XxSmall => 0.5625,
408 Self::XSmall => 0.625,
409 Self::Small => 0.8125,
410 Self::Large => 1.125,
411 Self::XLarge => 1.5,
412 Self::XxLarge => 2.0,
413 Self::XxxLarge => 3.0,
414 }
415 }
416
417 /// This step's position in [`ALL`](Self::ALL) — smallest first, so a
418 /// frontend's menu is `ALL` in order and a "larger" button is `index() + 1`.
419 pub const fn index(self) -> usize {
420 match self {
421 Self::XxSmall => 0,
422 Self::XSmall => 1,
423 Self::Small => 2,
424 Self::Large => 3,
425 Self::XLarge => 4,
426 Self::XxLarge => 5,
427 Self::XxxLarge => 6,
428 }
429 }
430
431 /// Every step, smallest first. `medium` is absent because `medium` is
432 /// absence — a menu draws it as the entry that calls
433 /// [`crate::Doc::set_font_size`] with `None`.
434 pub const ALL: [Self; 7] = [
435 Self::XxSmall,
436 Self::XSmall,
437 Self::Small,
438 Self::Large,
439 Self::XLarge,
440 Self::XxLarge,
441 Self::XxxLarge,
442 ];
443}
444
445/// The face a run is set in — CSS's generic families, less `fantasy` and
446/// `system-ui`, neither of which an author asks for.
447///
448/// A generic, never a font name, for [`SizeStep`]'s reason: a document that
449/// names `Georgia` renders in the fallback everywhere Georgia is not installed,
450/// which is every Linux terminal and most of the web. The theme names the
451/// concrete face for each — `Serif` is Georgia on a Mac and Noto Serif on a
452/// Linux box, and `Monospace` is the theme's mono face, which inline code
453/// already uses.
454///
455/// A named family is not in this vocabulary: [`from_attr`](Self::from_attr)
456/// answers `None` for it, and it is [`FontFace::Named`]'s to read — the open
457/// type beside this one, which the toolbar offers under the four generics.
458#[derive(Clone, Copy, PartialEq, Eq, Debug)]
459pub enum FontFamily {
460 Serif,
461 SansSerif,
462 Monospace,
463 Cursive,
464}
465
466impl FontFamily {
467 /// The face a run's or block's attributes name, if any — twig records it
468 /// under `data-font`.
469 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
470 attr(attrs, "data-font").and_then(Self::from_attr)
471 }
472
473 /// Read a `data-font` value. `None` for a concrete family name, which is
474 /// [`FontFace::Named`]'s to read; [`FontFace::from_attr`] is the door that
475 /// reads both.
476 ///
477 /// The four generics are matched without regard to case, because they are
478 /// CSS keywords and CSS reads a keyword either way — a hand-written
479 /// document says `Serif` as readily as `serif`, and a family actually
480 /// *named* "Serif" is not a thing anyone has installed. The canonical
481 /// spelling [`name`](Self::name) writes back is the lowercase one.
482 pub fn from_attr(value: &str) -> Option<Self> {
483 Self::ALL
484 .into_iter()
485 .find(|f| value.eq_ignore_ascii_case(f.name()))
486 }
487
488 /// The token twig spells it with, and what [`from_attr`](Self::from_attr)
489 /// reads back — CSS's own generic, so the stylesheet line is
490 /// `font-family: serif`.
491 pub const fn name(self) -> &'static str {
492 match self {
493 Self::Serif => "serif",
494 Self::SansSerif => "sans-serif",
495 Self::Monospace => "monospace",
496 Self::Cursive => "cursive",
497 }
498 }
499
500 /// This face's position in [`ALL`](Self::ALL) — the index a frontend's own
501 /// font table is keyed by.
502 pub const fn index(self) -> usize {
503 match self {
504 Self::Serif => 0,
505 Self::SansSerif => 1,
506 Self::Monospace => 2,
507 Self::Cursive => 3,
508 }
509 }
510
511 /// Every face, in the order a menu offers them. The theme's own body face
512 /// is absent because it is absence — the menu entry for it calls
513 /// [`crate::Doc::set_font_family`] with `None`.
514 pub const ALL: [Self; 4] = [Self::Serif, Self::SansSerif, Self::Monospace, Self::Cursive];
515}
516
517// ── the exact forms: a value where a name will not do ───────────────────────
518//
519// Each of the four run- and block-level properties gets an *open* type beside
520// its closed enum: the name, or the measurement the name cannot be. The enums
521// above are unchanged and still the menus' first offer — a name is portable
522// and a value is exact, and the author who takes the second takes the
523// portability cost knowingly.
524//
525// Each open type reads its own key with `from_attrs`, tries the **name first**
526// and the value second, and spells what it holds back with `name()`. A value
527// the grammar does not cover — `huge`, `14px`, `rgb(…)`, `1.3em` — answers
528// `None` exactly as it did before these types existed: carried untouched by the
529// document and drawn at the theme's default.
530
531/// A number a presentation value carries, in hundredths — 14 points is `1400`,
532/// a ratio of 1.3 is `130`.
533///
534/// Fixed point rather than an `f32` because a [`Style`] is stamped on every
535/// glyph and compared for run-merging, so the type has to be `Eq`, and because
536/// two spellings of the same number must be the same value: an author's
537/// `14.0pt` and the menu's `14pt` are one size, not two runs. Hundredths is
538/// more precision than any menu writes and enough for the `13.25pt` a fitted
539/// theme lands on.
540///
541/// `u16`, so the largest value is 655.35 — past any type size a sheet of paper
542/// holds and any line height a document means. A number above it is not a
543/// number this vocabulary carries, and reads as `None`.
544#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
545pub struct Hundredths(u16);
546
547impl Hundredths {
548 /// The number `value` names, rounded to the nearest hundredth. `None` for
549 /// anything that is not a positive finite number this can hold — the same
550 /// answer the parsers give a value outside the grammar.
551 pub fn from_f32(value: f32) -> Option<Self> {
552 if !value.is_finite() {
553 return None;
554 }
555 let h = (value * 100.0).round();
556 (1.0..=f32::from(u16::MAX))
557 .contains(&h)
558 .then_some(Self(h as u16))
559 }
560
561 /// The number itself — what a frontend lays out with.
562 pub fn as_f32(self) -> f32 {
563 self.0 as f32 / 100.0
564 }
565
566 /// The hundredths themselves, for a frontend that would rather do integer
567 /// arithmetic than divide and multiply back.
568 pub const fn hundredths(self) -> u16 {
569 self.0
570 }
571
572 /// Read a decimal — digits, at most one point, no sign and no exponent,
573 /// which is the whole of what a word processor's field writes. `None` for
574 /// anything else, and for zero: a size or a spacing of nothing is not a
575 /// value, it is a mistake.
576 ///
577 /// CSS's `<number>` wants digits on whichever side of the point it has, so
578 /// `.5` is a number and `14.` is not, and this reads them the same way.
579 ///
580 /// A third decimal place rounds rather than being refused, because the
581 /// number a colour picker or a font panel hands back is whatever floating
582 /// point made of the slider.
583 fn parse(value: &str) -> Option<Self> {
584 let (int, frac) = match value.split_once('.') {
585 // A trailing bare point is not a `<number>`: `14.` is a typo, and
586 // reading it as 14 would write a document the author did not mean.
587 Some((_, "")) => return None,
588 Some(pair) => pair,
589 None => (value, ""),
590 };
591 if int.is_empty() && frac.is_empty() {
592 return None;
593 }
594 if !int.bytes().chain(frac.bytes()).all(|b| b.is_ascii_digit()) {
595 return None;
596 }
597 let whole: u32 = if int.is_empty() { 0 } else { int.parse().ok()? };
598 // Out of range before the arithmetic rather than after it, so a
599 // thousand digits of integer part is a `None` and not an overflow.
600 if whole > u32::from(u16::MAX) / 100 {
601 return None;
602 }
603 let digit = |i: usize| frac.as_bytes().get(i).map_or(0, |b| u32::from(b - b'0'));
604 let mut h = whole * 100 + digit(0) * 10 + digit(1);
605 if digit(2) >= 5 {
606 h += 1;
607 }
608 (1..=u32::from(u16::MAX))
609 .contains(&h)
610 .then_some(Self(h as u16))
611 }
612}
613
614impl std::fmt::Display for Hundredths {
615 /// The shortest decimal that means this number: `14`, `13.5`, `1.25`. What
616 /// a document is written with, so that a value set twice from the same menu
617 /// spells the same bytes both times.
618 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
619 let (whole, frac) = (self.0 / 100, self.0 % 100);
620 match frac {
621 0 => write!(f, "{whole}"),
622 _ if frac % 10 == 0 => write!(f, "{whole}.{}", frac / 10),
623 _ => write!(f, "{whole}.{frac:02}"),
624 }
625 }
626}
627
628/// How large a run is set: a [`SizeStep`] relative to the text around it, or
629/// the point size the author asked for.
630///
631/// The step is what a menu offers first, and is what a document should say
632/// where a name will do — it reads as a step up under every theme. The point
633/// size is what the author typed and is all it is: 14 points of the sheet on
634/// the paginated view, and 14 points before the zoom on screen, which is how
635/// every other point size on a page behaves. A heading set to an exact size is
636/// that size and not its ramp scaled — the name scales the ramp, the value
637/// replaces it.
638///
639/// Only `pt` is a unit. `px` is a screen's unit and a document is not a screen;
640/// `em`, `rem` and `%` are relative, which is what the steps already are.
641#[derive(Clone, Copy, PartialEq, Eq, Debug)]
642pub enum FontSize {
643 Step(SizeStep),
644 Points(Hundredths),
645}
646
647impl FontSize {
648 /// The size a run's or block's attributes name, if any — twig records it
649 /// under `data-size`.
650 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
651 attr(attrs, "data-size").and_then(Self::from_attr)
652 }
653
654 /// Read a `data-size` value: one of CSS's seven keywords, or a `<number>pt`.
655 /// The unit is matched without regard to case, because a hand-written
656 /// document says `14PT` as readily as `14pt` and CSS reads both.
657 pub fn from_attr(value: &str) -> Option<Self> {
658 let value = value.trim();
659 if let Some(step) = SizeStep::from_attr(value) {
660 return Some(Self::Step(step));
661 }
662 let number = value.strip_suffix("pt").or_else(|| {
663 let (n, unit) = value.split_at_checked(value.len().checked_sub(2)?)?;
664 unit.eq_ignore_ascii_case("pt").then_some(n)
665 })?;
666 Hundredths::parse(number).map(Self::Points)
667 }
668
669 /// A size in points, or `None` for a number this vocabulary cannot carry —
670 /// the constructor an *Other…* field calls with what the author typed.
671 pub fn points(points: f32) -> Option<Self> {
672 Hundredths::from_f32(points).map(Self::Points)
673 }
674
675 /// The token twig spells it with, and what [`from_attr`](Self::from_attr)
676 /// reads back: the step's CSS keyword, or the shortest decimal with `pt`
677 /// after it.
678 pub fn name(self) -> Cow<'static, str> {
679 match self {
680 Self::Step(step) => Cow::Borrowed(step.name()),
681 Self::Points(pt) => Cow::Owned(format!("{pt}pt")),
682 }
683 }
684
685 /// The step, for a menu asking which of its seven rows to tick — `None`
686 /// when the size is an exact one, which the menu shows as its own row.
687 pub const fn step(self) -> Option<SizeStep> {
688 match self {
689 Self::Step(step) => Some(step),
690 Self::Points(_) => None,
691 }
692 }
693
694 /// The point size, or `None` when the size is a step — whose size in points
695 /// is the theme's business and not this type's.
696 pub fn points_value(self) -> Option<f32> {
697 match self {
698 Self::Step(_) => None,
699 Self::Points(pt) => Some(pt.as_f32()),
700 }
701 }
702}
703
704/// How far apart a block's lines are set: a [`LineSpacing`] from the menu's
705/// three, or the ratio the author asked for. [`FontSize`]'s peer, one property
706/// along, and with no unit at all — a line height is a multiple.
707///
708/// A ratio that spells one of the three names *is* that name:
709/// [`from_attr`](Self::from_attr) answers `Step(OneHalf)` for `1.50` as well as
710/// for `1.5`, so that two spellings of one spacing are one value and the
711/// document is rewritten with the name a menu can tick.
712///
713/// And a ratio of **1 is absence**, exactly as it is for [`LineSpacing`], whose
714/// three names begin above it: single spacing is what a block with no
715/// `data-line-height` is set at, and a document should not carry a key that
716/// says nothing. `from_attr("1")` and `ratio(1.0)` both answer `None`, so a
717/// gesture given one clears the key and the query then ticks *Single*.
718#[derive(Clone, Copy, PartialEq, Eq, Debug)]
719pub enum LineHeight {
720 Step(LineSpacing),
721 Ratio(Hundredths),
722}
723
724impl LineHeight {
725 /// The spacing a block's attributes name, if any — twig records it under
726 /// `data-line-height`.
727 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
728 attr(attrs, "data-line-height").and_then(Self::from_attr)
729 }
730
731 /// Read a `data-line-height` value: one of the three names, or any positive
732 /// decimal other than 1, which is absence.
733 pub fn from_attr(value: &str) -> Option<Self> {
734 let value = value.trim();
735 if let Some(step) = LineSpacing::from_attr(value) {
736 return Some(Self::Step(step));
737 }
738 Hundredths::parse(value).and_then(Self::of)
739 }
740
741 /// A ratio, or `None` for a number this vocabulary cannot carry — the
742 /// constructor an *Other…* field calls with what the author typed. 1 is one
743 /// of those numbers: see the type's note.
744 pub fn ratio(ratio: f32) -> Option<Self> {
745 Hundredths::from_f32(ratio).and_then(Self::of)
746 }
747
748 /// Whether `value` spells the one ratio that is **absence** — `1`, in any
749 /// of its spellings (`1`, `1.0`, `1.00`), which is single spacing and is
750 /// the theme's own.
751 ///
752 /// [`from_attr`](Self::from_attr) answers `None` for it exactly as it does
753 /// for a token outside the grammar, and the two mean opposite things: `1`
754 /// is an author asking for the theme's spacing, and `huge` is a typo. A
755 /// binding that turns the first into a cleared key and the second into a
756 /// refusal asks this to tell them apart — leaf-wasm's `setLineSpacing`
757 /// does.
758 pub fn is_absence(value: &str) -> bool {
759 Hundredths::parse(value.trim()).is_some_and(|r| r.hundredths() == Self::SINGLE)
760 }
761
762 /// Single spacing in hundredths — the ratio that has no token, written
763 /// down once for [`of`](Self::of) and [`is_absence`](Self::is_absence).
764 const SINGLE: u16 = 100;
765
766 /// A ratio as the name for it where there is one, and `None` where the
767 /// ratio is 1 — see the type's note.
768 ///
769 /// Compared in hundredths rather than through [`Display`](std::fmt::Display)
770 /// and [`LineSpacing::from_attr`], so that reading a spacing does not format
771 /// a `String` to throw away.
772 fn of(ratio: Hundredths) -> Option<Self> {
773 if ratio.hundredths() == Self::SINGLE {
774 return None;
775 }
776 let step = LineSpacing::ALL
777 .into_iter()
778 .find(|s| (s.ratio() * 100.0).round() as u16 == ratio.hundredths());
779 Some(match step {
780 Some(step) => Self::Step(step),
781 None => Self::Ratio(ratio),
782 })
783 }
784
785 /// The token twig spells it with, and what [`from_attr`](Self::from_attr)
786 /// reads back.
787 pub fn name(self) -> Cow<'static, str> {
788 match self {
789 Self::Step(step) => Cow::Borrowed(step.name()),
790 Self::Ratio(r) => Cow::Owned(r.to_string()),
791 }
792 }
793
794 /// The step, for a menu asking which of its three rows to tick — `None` for
795 /// an exact ratio, which the menu shows as its own row.
796 pub const fn step(self) -> Option<LineSpacing> {
797 match self {
798 Self::Step(step) => Some(step),
799 Self::Ratio(_) => None,
800 }
801 }
802
803 /// The ratio itself — what a frontend multiplies the theme's line height
804 /// by. Unlike [`FontSize`]'s points this always answers, because a step's
805 /// ratio is the name read as arithmetic ([`LineSpacing::ratio`]) and not a
806 /// theme's choice.
807 pub fn as_f32(self) -> f32 {
808 match self {
809 Self::Step(step) => step.ratio(),
810 Self::Ratio(r) => r.as_f32(),
811 }
812 }
813}
814
815/// A run's foreground colour: one of the seven [`MarkColor`] names, or the RGB
816/// triple the author asked for.
817///
818/// A name is two inks, one per appearance, and the theme owns both. A triple is
819/// painted as written in the light appearance and in the dark one alike — that
820/// is what "exact" means, and the proposal does not soften it with a heuristic.
821/// `#rgb` is read and never written; six lowercase digits is the spelling.
822#[derive(Clone, Copy, PartialEq, Eq, Debug)]
823pub enum TextColor {
824 Named(MarkColor),
825 Rgb { r: u8, g: u8, b: u8 },
826}
827
828impl TextColor {
829 /// The colour a run's or block's attributes name, if any — twig records it
830 /// under `data-color`, the key a `mark` node carries its *highlight's*
831 /// colour under. The two never collide: a `mark` is a `mark` and a span is
832 /// a span.
833 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
834 attr(attrs, "data-color").and_then(Self::from_attr)
835 }
836
837 /// Read a `data-color` value: one of the seven names, `#rrggbb`, or the
838 /// `#rgb` shorthand a stylesheet author writes (`#f00` is `#ff0000`, each
839 /// digit doubled, as CSS expands it).
840 pub fn from_attr(value: &str) -> Option<Self> {
841 let value = value.trim();
842 if let Some(named) = MarkColor::from_attr(value) {
843 return Some(Self::Named(named));
844 }
845 let hex = value.strip_prefix('#')?;
846 if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
847 return None;
848 }
849 let nib = |i: usize| u8::from_str_radix(&hex[i..i + 1], 16).ok();
850 let byte = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
851 match hex.len() {
852 3 => Some(Self::Rgb {
853 r: nib(0)? * 0x11,
854 g: nib(1)? * 0x11,
855 b: nib(2)? * 0x11,
856 }),
857 6 => Some(Self::Rgb {
858 r: byte(0)?,
859 g: byte(2)?,
860 b: byte(4)?,
861 }),
862 _ => None,
863 }
864 }
865
866 /// The token twig spells it with, and what [`from_attr`](Self::from_attr)
867 /// reads back: the name, or six lowercase hex digits behind a `#`.
868 pub fn name(self) -> Cow<'static, str> {
869 match self {
870 Self::Named(c) => Cow::Borrowed(c.name()),
871 Self::Rgb { r, g, b } => Cow::Owned(format!("#{r:02x}{g:02x}{b:02x}")),
872 }
873 }
874
875 /// The name, for a palette asking which of its seven swatches to tick —
876 /// `None` for an exact triple, which the palette shows as a swatch of its
877 /// own.
878 pub const fn named(self) -> Option<MarkColor> {
879 match self {
880 Self::Named(c) => Some(c),
881 Self::Rgb { .. } => None,
882 }
883 }
884
885 /// The triple, or `None` for a name — whose two inks are the theme's.
886 pub const fn rgb(self) -> Option<(u8, u8, u8)> {
887 match self {
888 Self::Named(_) => None,
889 Self::Rgb { r, g, b } => Some((r, g, b)),
890 }
891 }
892}
893
894/// The face a run is set in: one of CSS's four generics, or the family the
895/// author named.
896///
897/// A generic opens on every machine and a family name does not, which is the
898/// trade stated once in [`FontFamily`]'s own note. A named family is resolved
899/// through the platform's font registry by the frontends that have one, and
900/// falls back to the body face where it is not installed.
901///
902/// Owned, because a family name is a `String` and this is what a gesture takes
903/// and a query answers — neither is per-glyph. What a *glyph* carries is
904/// [`FaceRef`], the `Copy` half, whose name is looked up in the map's
905/// [`FaceTable`].
906#[derive(Clone, PartialEq, Eq, Debug)]
907pub enum FontFace {
908 Generic(FontFamily),
909 Named(String),
910}
911
912impl FontFace {
913 /// The face a run's or block's attributes name, if any — twig records it
914 /// under `data-font`.
915 pub fn from_attrs(attrs: &[(String, Option<String>)]) -> Option<Self> {
916 attr(attrs, "data-font").and_then(Self::from_attr)
917 }
918
919 /// Read a `data-font` value: one of the four generics, or any other
920 /// non-empty string, which is a family name. Trimmed, and nothing else —
921 /// a family name is what the author typed, and leaf has no table of real
922 /// ones to check it against.
923 pub fn from_attr(value: &str) -> Option<Self> {
924 let value = value.trim();
925 match FontFamily::from_attr(value) {
926 Some(generic) => Some(Self::Generic(generic)),
927 None => (!value.is_empty()).then(|| Self::Named(value.to_string())),
928 }
929 }
930
931 /// The token twig spells it with, and what [`from_attr`](Self::from_attr)
932 /// reads back — the generic's CSS keyword, or the family name as given.
933 pub fn name(&self) -> Cow<'_, str> {
934 match self {
935 Self::Generic(generic) => Cow::Borrowed(generic.name()),
936 Self::Named(name) => Cow::Borrowed(name.as_str()),
937 }
938 }
939
940 /// The generic, for a menu asking which of its four rows to tick — `None`
941 /// for a named family, which the menu shows as a row of its own.
942 pub const fn generic(&self) -> Option<FontFamily> {
943 match self {
944 Self::Generic(generic) => Some(*generic),
945 Self::Named(_) => None,
946 }
947 }
948}
949
950/// A named family's id on a glyph — what [`FaceRef::Named`] carries and
951/// [`FaceTable::name`] reads back.
952///
953/// A 32-bit FNV-1a of the family name, and *not* an index, for one reason: a
954/// glyph's id has to mean the same thing however its row was built. A row comes
955/// from a fresh walk, from a [`crate::wysiwyg::BlockCache`] hit cloned at a
956/// shifted offset, or from a previous map a splice kept untouched — and an
957/// index into a table that each of those three assembled differently would have
958/// the same glyph naming two faces. Derived from the name, nothing has to be
959/// remapped and a spliced map's glyphs compare equal to a fresh build's.
960///
961/// Two family names that hashed alike would draw in one face. That needs about
962/// 2¹⁶ distinct families in one document to become likely, and a document with
963/// 2¹⁶ families has a different problem.
964#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
965pub struct FaceId(u32);
966
967impl FaceId {
968 /// The id a family name has. FNV-1a, written out rather than taken from
969 /// `DefaultHasher`, because the value is compared across builds and must
970 /// not depend on a hasher's seed or version.
971 pub fn of(name: &str) -> Self {
972 let mut h: u32 = 0x811c_9dc5;
973 for b in name.as_bytes() {
974 h ^= u32::from(*b);
975 h = h.wrapping_mul(0x0100_0193);
976 }
977 Self(h)
978 }
979}
980
981/// The face a *glyph* is set in — [`FontFace`]'s `Copy` half, so that a
982/// [`Style`] stays `Copy` and `Eq` and can be stamped on every glyph and
983/// compared for run-merging.
984///
985/// A named family is an id into the map's [`FaceTable`], which the walker
986/// interns into as it meets each name. A frontend reads the name back with
987/// [`crate::wysiwyg::VisualMap::face_name`].
988#[derive(Clone, Copy, PartialEq, Eq, Debug)]
989pub enum FaceRef {
990 Generic(FontFamily),
991 Named(FaceId),
992}
993
994impl FaceRef {
995 /// The generic, or `None` for a named family — [`FontFace::generic`]'s peer.
996 pub const fn generic(self) -> Option<FontFamily> {
997 match self {
998 Self::Generic(generic) => Some(generic),
999 Self::Named(_) => None,
1000 }
1001 }
1002
1003 /// The id of the named family, or `None` for a generic.
1004 pub const fn id(self) -> Option<FaceId> {
1005 match self {
1006 Self::Generic(_) => None,
1007 Self::Named(id) => Some(id),
1008 }
1009 }
1010}
1011
1012/// Every named family a [`crate::wysiwyg::VisualMap`] draws, by the id its
1013/// glyphs carry — the side table that lets [`Style`] stay `Copy` while a face
1014/// name stays a `String`.
1015///
1016/// Small: one entry per *distinct* family name in the document, which is
1017/// normally none. A splice may leave an entry no glyph names any more, because
1018/// the splice reuses the previous map's table rather than rebuilding it from
1019/// rows it deliberately did not walk; an unused entry costs a string and draws
1020/// nothing.
1021#[derive(Clone, Default, Debug, PartialEq, Eq)]
1022pub struct FaceTable {
1023 /// Ascending by id, so a lookup is a binary search and two tables built
1024 /// from the same names compare equal whatever order they met them in.
1025 entries: Vec<(FaceId, String)>,
1026}
1027
1028impl FaceTable {
1029 /// The family name `id` stands for, or `None` for an id from another map —
1030 /// which a frontend draws in the theme's body face, as it draws a face it
1031 /// cannot resolve.
1032 pub fn name(&self, id: FaceId) -> Option<&str> {
1033 let i = self.entries.binary_search_by_key(&id, |(k, _)| *k).ok()?;
1034 Some(self.entries[i].1.as_str())
1035 }
1036
1037 /// The face a glyph carries, spelled — the generic's CSS keyword, or the
1038 /// family name this table holds for the id. The one place a [`FaceRef`]
1039 /// becomes the token a `data-font` is written with, which is what every
1040 /// frontend wants of it.
1041 ///
1042 /// `None` for an id no table knows, which is an id from another map: a
1043 /// frontend draws that in the theme's body face, and a face that draws as
1044 /// absence names itself as absence too.
1045 ///
1046 /// leaf-ffi's and leaf-wasm's `Run::font` are this; leaf-swift's and
1047 /// leaf-ratatui's face resolvers can be.
1048 pub fn spell(&self, face: FaceRef) -> Option<Cow<'_, str>> {
1049 match face {
1050 FaceRef::Generic(generic) => Some(Cow::Borrowed(generic.name())),
1051 FaceRef::Named(id) => self.name(id).map(Cow::Borrowed),
1052 }
1053 }
1054
1055 /// Every family in the table, by id — how a frontend warms a font cache
1056 /// before it draws.
1057 pub fn iter(&self) -> impl Iterator<Item = (FaceId, &str)> {
1058 self.entries.iter().map(|(id, name)| (*id, name.as_str()))
1059 }
1060
1061 pub fn is_empty(&self) -> bool {
1062 self.entries.is_empty()
1063 }
1064
1065 pub fn len(&self) -> usize {
1066 self.entries.len()
1067 }
1068
1069 /// Record one family, keeping the vec ascending by id — the sorted insert
1070 /// both doors below are, written once.
1071 fn insert(&mut self, id: FaceId, name: &str) {
1072 if let Err(i) = self.entries.binary_search_by_key(&id, |(k, _)| *k) {
1073 self.entries.insert(i, (id, name.to_string()));
1074 }
1075 }
1076
1077 /// Record `face` and hand back what a glyph carries for it. A generic needs
1078 /// no entry — it names itself.
1079 pub(crate) fn intern(&mut self, face: &FontFace) -> FaceRef {
1080 match face {
1081 FontFace::Generic(generic) => FaceRef::Generic(*generic),
1082 FontFace::Named(name) => {
1083 let id = FaceId::of(name);
1084 self.insert(id, name);
1085 FaceRef::Named(id)
1086 }
1087 }
1088 }
1089
1090 /// The face `attrs` name, interned — the walker's door.
1091 pub(crate) fn face_from_attrs(
1092 &mut self,
1093 attrs: &[(String, Option<String>)],
1094 ) -> Option<FaceRef> {
1095 FontFace::from_attrs(attrs).map(|face| self.intern(&face))
1096 }
1097
1098 /// Take in everything `other` knows — how a build assembles one table out
1099 /// of the per-block walks, cache hits and spliced remnants it is made of.
1100 pub(crate) fn merge(&mut self, other: &FaceTable) {
1101 for (id, name) in &other.entries {
1102 self.insert(*id, name);
1103 }
1104 }
1105}
1106
1107/// What a glyph in a fenced code block is *to the language it is written in*
1108/// — the syntax-highlighting vocabulary, one level down from [`Role`].
1109///
1110/// Eight classes rather than the hundreds of scopes a Sublime grammar names,
1111/// and the same eight `plates` colours its published pages with: each is the
1112/// *first atom* of a TextMate scope — `keyword.control.rust` is a keyword,
1113/// `string.quoted.double` a string — and a palette that tells these eight apart
1114/// is a palette that reads. Finer than this is a theme's business, and a theme
1115/// is exactly what core does not carry: like [`Role`], a token says what a
1116/// glyph *is* and leaves what colour to paint it to the frontend, so the same
1117/// document highlights in ANSI colours on a terminal and in an `Hsla` in a GUI.
1118///
1119/// Only a glyph with [`Role::Code`] carries one, and only in a fenced block
1120/// whose info string names a language the bundled grammars know (see
1121/// [`crate::syntax`]). Inline `` `code` ``, an indented block, a bare fence, and
1122/// a language no grammar covers all carry `None`, and draw in the code colour
1123/// exactly as they did before this existed.
1124#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1125pub enum Token {
1126 /// Brackets, operators, separators — `punctuation.*`. The quietest class:
1127 /// a frontend typically draws it in the comment colour, so the `"` opening
1128 /// a string reads as the string's and not as its own thing.
1129 Punctuation,
1130 /// A reserved word or a storage modifier — `keyword.*` and `storage.*`
1131 /// (`fn`, `let`, `pub`, `const`, `if`).
1132 Keyword,
1133 /// A name the author defined or named — `entity.*` (a function or type at
1134 /// its definition) and `variable.*` (a parameter, a field, `self`).
1135 Entity,
1136 /// A name the language or its library provides — `support.*` (a builtin
1137 /// function, a standard type).
1138 Support,
1139 /// A literal that is not a string — `constant.*` (a number, `true`, an
1140 /// escape sequence, a character literal).
1141 Constant,
1142 /// A string literal, delimiters included — `string.*`.
1143 String,
1144 /// A comment — `comment.*`. A frontend typically italicises it as well.
1145 Comment,
1146 /// What the grammar could not parse — `invalid.*`.
1147 Invalid,
1148}
1149
1150impl Token {
1151 /// The class id a frontend keys a stylesheet or a palette on — the first
1152 /// atom of the scope it stands for, so a rule written for `plates` output
1153 /// (`plates-keyword`) and one written for leaf (`leaf-t-keyword`) name the
1154 /// same thing.
1155 pub const fn name(self) -> &'static str {
1156 match self {
1157 Self::Punctuation => "punctuation",
1158 Self::Keyword => "keyword",
1159 Self::Entity => "entity",
1160 Self::Support => "support",
1161 Self::Constant => "constant",
1162 Self::String => "string",
1163 Self::Comment => "comment",
1164 Self::Invalid => "invalid",
1165 }
1166 }
1167
1168 /// The token a class id names, or `None` for a name outside the
1169 /// vocabulary — the inverse of [`name`](Self::name).
1170 pub fn from_name(name: &str) -> Option<Self> {
1171 Self::ALL.into_iter().find(|t| t.name() == name)
1172 }
1173
1174 /// This token's position in [`ALL`](Self::ALL) — the index a frontend's own
1175 /// palette array is keyed by, the way [`MarkColor::index`] keys the
1176 /// highlighter washes.
1177 pub const fn index(self) -> usize {
1178 match self {
1179 Self::Punctuation => 0,
1180 Self::Keyword => 1,
1181 Self::Entity => 2,
1182 Self::Support => 3,
1183 Self::Constant => 4,
1184 Self::String => 5,
1185 Self::Comment => 6,
1186 Self::Invalid => 7,
1187 }
1188 }
1189
1190 /// Every token, in **precedence order**: a scope whose atoms name two of
1191 /// these (`punctuation.definition.string.begin` is both punctuation and
1192 /// string) is the *later* one, so a string's quotes read as string and a
1193 /// comment's `//` as comment. The frontends iterate this to build their
1194 /// palettes, so a token added here is one a palette test immediately
1195 /// demands an entry for.
1196 pub const ALL: [Self; 8] = [
1197 Self::Punctuation,
1198 Self::Keyword,
1199 Self::Entity,
1200 Self::Support,
1201 Self::Constant,
1202 Self::String,
1203 Self::Comment,
1204 Self::Invalid,
1205 ];
1206}
1207
1208/// Which line a glyph sits on relative to the text around it.
1209///
1210/// Not a [`Role`], because a raised glyph keeps whatever it already was — the
1211/// `1` of a footnote reference is still a link, an author's `^2^` inside a
1212/// heading is still heading text. And not one of [`Style`]'s `bool` flags,
1213/// because unlike bold-and-italic these do not compose: a glyph is raised, or
1214/// lowered, or neither, and two flags would let a caller ask for both.
1215///
1216/// A frontend that ignores this draws every glyph on the normal baseline, which
1217/// is what every frontend did before the variant existed.
1218#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1219pub enum Baseline {
1220 /// The ordinary text baseline.
1221 #[default]
1222 Normal,
1223 /// Raised and typically drawn smaller — an author's `^x^`, and the label of
1224 /// a footnote reference.
1225 Super,
1226 /// Lowered and typically drawn smaller — an author's `~x~`.
1227 Sub,
1228}
1229
1230/// A glyph's style: a typographic [`Role`] plus the compositional emphasis flags
1231/// the author wrote. Deliberately *no* color — that is a frontend's call, keyed
1232/// on the [`Role`]. Builder methods (`.bold`, `.italic`, …) mirror the shape of
1233/// ratatui's `Style` so the WYSIWYG builder reads the same as it did before the
1234/// split.
1235#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1236pub struct Style {
1237 pub bold: bool,
1238 pub italic: bool,
1239 pub underline: bool,
1240 pub strikethrough: bool,
1241 /// The typographic role — [`Role::Body`] for ordinary text.
1242 pub role: Role,
1243 /// Which line the glyph sits on — [`Baseline::Normal`] for ordinary text.
1244 pub baseline: Baseline,
1245 /// What a code glyph is to its language — `None` for every glyph outside a
1246 /// highlighted fenced block, which is every glyph there was before syntax
1247 /// highlighting. Only meaningful beside [`Role::Code`]; a frontend that
1248 /// ignores it draws code in one colour, as every frontend once did.
1249 pub token: Option<Token>,
1250 /// How large this run is set — the author's `data-size` as a step or a
1251 /// point size, and `None` for the theme's own size, which is every glyph
1252 /// there was before the presentation vocabulary.
1253 ///
1254 /// Read at both levels, the nearer winning: a span's `data-size` inside a
1255 /// block carrying its own applies to the span. A frontend that ignores it
1256 /// draws one size, as `leaf-ratatui` does — a cell has one size.
1257 pub size: Option<FontSize>,
1258 /// The face this run is set in — the author's `data-font` as a generic or
1259 /// as an id into the map's [`FaceTable`], and `None` for the theme's body
1260 /// face. Read at the same two levels [`size`](Self::size) is.
1261 pub font: Option<FaceRef>,
1262 /// The run's *foreground* colour — the author's `data-color` on an
1263 /// attributed span, and `None` for the theme's text colour.
1264 ///
1265 /// The same seven names [`Role::Mark`] carries, over the same enum: a
1266 /// frontend that has a red for a highlight has a red for text, and both
1267 /// should be *that* red. The two never collide, because a `mark` is a
1268 /// `mark` and a span is a span — a `data-color` on a `mark` node is the
1269 /// highlight's background and reaches a glyph through its role, while this
1270 /// is what a `<span data-color="red">` paints the letters. Only this one
1271 /// opens to a triple, for the reason [`MarkColor`]'s note gives.
1272 pub color: Option<TextColor>,
1273}
1274
1275impl Style {
1276 pub const fn bold(mut self) -> Self {
1277 self.bold = true;
1278 self
1279 }
1280
1281 pub const fn italic(mut self) -> Self {
1282 self.italic = true;
1283 self
1284 }
1285
1286 pub const fn underline(mut self) -> Self {
1287 self.underline = true;
1288 self
1289 }
1290
1291 pub const fn strikethrough(mut self) -> Self {
1292 self.strikethrough = true;
1293 self
1294 }
1295
1296 pub const fn role(mut self, r: Role) -> Self {
1297 self.role = r;
1298 self
1299 }
1300
1301 pub const fn baseline(mut self, b: Baseline) -> Self {
1302 self.baseline = b;
1303 self
1304 }
1305
1306 pub const fn token(mut self, t: Option<Token>) -> Self {
1307 self.token = t;
1308 self
1309 }
1310
1311 pub const fn size(mut self, s: Option<FontSize>) -> Self {
1312 self.size = s;
1313 self
1314 }
1315
1316 pub const fn font(mut self, f: Option<FaceRef>) -> Self {
1317 self.font = f;
1318 self
1319 }
1320
1321 pub const fn color(mut self, c: Option<TextColor>) -> Self {
1322 self.color = c;
1323 self
1324 }
1325}
1326
1327#[cfg(test)]
1328mod tests {
1329 use super::*;
1330
1331 /// [`MarkColor`] carries three hand-written tables — `ALL`, `index`, and the
1332 /// `name`/`from_attr` pair — and nothing but this makes them agree. The
1333 /// frontends index their palettes by `index` and look colours up by `name`,
1334 /// so a variant added to one table and missed in another draws the wrong
1335 /// wash rather than failing to compile.
1336 #[test]
1337 fn the_colour_tables_agree_with_each_other() {
1338 for (i, c) in MarkColor::ALL.into_iter().enumerate() {
1339 assert_eq!(c.index(), i, "{} is not where ALL puts it", c.name());
1340 assert_eq!(MarkColor::from_attr(c.name()), Some(c), "name round-trip");
1341 }
1342 assert_eq!(MarkColor::from_attr("chartreuse"), None);
1343 assert_eq!(MarkColor::from_attr(""), None);
1344 }
1345
1346 /// [`Token`] carries the same three tables [`MarkColor`] does, held to
1347 /// each other for the same reason: a frontend indexes its palette by
1348 /// `index` and a stylesheet keys on `name`.
1349 #[test]
1350 fn the_token_tables_agree_with_each_other() {
1351 for (i, t) in Token::ALL.into_iter().enumerate() {
1352 assert_eq!(t.index(), i, "{} is not where ALL puts it", t.name());
1353 assert_eq!(Token::from_name(t.name()), Some(t), "name round-trip");
1354 }
1355 assert_eq!(Token::from_name("meta"), None);
1356 assert_eq!(Token::from_name(""), None);
1357 }
1358
1359 /// Each presentation enum carries the same three hand-written tables
1360 /// [`MarkColor`] does — `ALL`, `index`, and the `name`/`from_*` pair — and
1361 /// nothing but this makes them agree. A frontend indexes its own menu by
1362 /// `index` and a stylesheet keys on `name`, so a variant added to one table
1363 /// and missed in another draws the wrong thing rather than failing to
1364 /// compile.
1365 #[test]
1366 fn the_presentation_tables_agree_with_each_other() {
1367 for (i, a) in Align::ALL.into_iter().enumerate() {
1368 assert_eq!(a.index(), i, "{} is not where ALL puts it", a.name());
1369 assert_eq!(Align::from_token(a.name()), Some(a), "name round-trip");
1370 }
1371 for (i, l) in LineSpacing::ALL.into_iter().enumerate() {
1372 assert_eq!(l.index(), i, "{} is not where ALL puts it", l.name());
1373 assert_eq!(LineSpacing::from_attr(l.name()), Some(l), "name round-trip");
1374 }
1375 for (i, z) in SizeStep::ALL.into_iter().enumerate() {
1376 assert_eq!(z.index(), i, "{} is not where ALL puts it", z.name());
1377 assert_eq!(SizeStep::from_attr(z.name()), Some(z), "name round-trip");
1378 }
1379 for (i, f) in FontFamily::ALL.into_iter().enumerate() {
1380 assert_eq!(f.index(), i, "{} is not where ALL puts it", f.name());
1381 assert_eq!(FontFamily::from_attr(f.name()), Some(f), "name round-trip");
1382 }
1383 // Nothing outside the vocabulary is guessed at.
1384 assert_eq!(Align::from_token("left"), None);
1385 assert_eq!(LineSpacing::from_attr("1"), None);
1386 assert_eq!(SizeStep::from_attr("medium"), None);
1387 assert_eq!(SizeStep::from_attr("14pt"), None);
1388 assert_eq!(FontFamily::from_attr("Garamond"), None);
1389 assert_eq!(FontFamily::from_attr("fantasy"), None);
1390 // A generic is a CSS keyword, and CSS reads a keyword either way — the
1391 // spelling written back is still the lowercase one.
1392 assert_eq!(FontFamily::from_attr("Serif"), Some(FontFamily::Serif));
1393 assert_eq!(
1394 FontFamily::from_attr("SANS-SERIF"),
1395 Some(FontFamily::SansSerif)
1396 );
1397 assert_eq!(
1398 FontFamily::from_attr("MonoSpace").unwrap().name(),
1399 "monospace"
1400 );
1401 assert_eq!(
1402 FontFace::from_attr("Serif"),
1403 Some(FontFace::Generic(FontFamily::Serif)),
1404 "and the open type reads it as the generic, not as a family name"
1405 );
1406 assert_eq!(FontFace::from_attr("Serif").unwrap().name(), "serif");
1407 }
1408
1409 /// The size ramp's defaults are CSS's own user-agent ratios for the same
1410 /// seven words, so a browser given only leaf's stylesheet and a native
1411 /// renderer given the theme agree about how big `large` is. Pinned because
1412 /// they are the one place core carries a *number*.
1413 #[test]
1414 fn the_size_ramp_is_css_s_own() {
1415 let ramp: Vec<f32> = SizeStep::ALL.into_iter().map(SizeStep::scale).collect();
1416 assert_eq!(
1417 ramp,
1418 vec![0.5625, 0.625, 0.8125, 1.125, 1.5, 2.0, 3.0],
1419 "the CSS absolute-size ratios, medium removed"
1420 );
1421 // Monotonic, and `medium` (1.0) is the gap absence sits in.
1422 assert!(ramp.windows(2).all(|w| w[0] < w[1]));
1423 assert!(SizeStep::Small.scale() < 1.0 && SizeStep::Large.scale() > 1.0);
1424 let spacing: Vec<f32> = LineSpacing::ALL
1425 .into_iter()
1426 .map(LineSpacing::ratio)
1427 .collect();
1428 assert_eq!(spacing, vec![1.15, 1.5, 2.0]);
1429 }
1430
1431 /// `class` is a token list, and leaf reads the one token it knows out of it
1432 /// and leaves the rest — the rule that lets a document from elsewhere pass
1433 /// through the editor unharmed.
1434 #[test]
1435 fn an_alignment_is_one_token_of_a_class_and_the_rest_is_somebody_else_s() {
1436 let class = |v: &str| vec![("class".to_string(), Some(v.to_string()))];
1437 assert_eq!(Align::from_attrs(&class("center")), Some(Align::Center));
1438 assert_eq!(
1439 Align::from_attrs(&class("lead center")),
1440 Some(Align::Center)
1441 );
1442 assert_eq!(
1443 Align::from_attrs(&class("center lead")),
1444 Some(Align::Center)
1445 );
1446 assert_eq!(Align::from_attrs(&class("lead wide")), None);
1447 assert_eq!(Align::from_attrs(&class("")), None);
1448 assert_eq!(Align::from_attrs(&[]), None);
1449 // A bare `class` has no token list to read.
1450 assert_eq!(Align::from_attrs(&[("class".to_string(), None)]), None);
1451 // The other three read their own key and nothing else.
1452 let attr = |k: &str, v: &str| vec![(k.to_string(), Some(v.to_string()))];
1453 assert_eq!(
1454 LineSpacing::from_attrs(&attr("data-line-height", "1.5")),
1455 Some(LineSpacing::OneHalf)
1456 );
1457 assert_eq!(LineSpacing::from_attrs(&attr("class", "1.5")), None);
1458 assert_eq!(
1459 SizeStep::from_attrs(&attr("data-size", "large")),
1460 Some(SizeStep::Large)
1461 );
1462 assert_eq!(
1463 FontFamily::from_attrs(&attr("data-font", "monospace")),
1464 Some(FontFamily::Monospace)
1465 );
1466 // Text colour is the highlight's own vocabulary, read off the same key.
1467 assert_eq!(
1468 MarkColor::from_attrs(&attr("data-color", "blue")),
1469 Some(MarkColor::Blue)
1470 );
1471 }
1472
1473 /// The attribute twig actually writes, read off the shape a `FlatNode`
1474 /// hands over — a `mark` with no colour, one with the colour, and one
1475 /// carrying some other attribute entirely.
1476 #[test]
1477 fn a_colour_is_read_out_of_the_data_color_attribute_and_nothing_else() {
1478 let attr = |k: &str, v: &str| vec![(k.to_string(), Some(v.to_string()))];
1479 assert_eq!(
1480 MarkColor::from_attrs(&attr("data-color", "green")),
1481 Some(MarkColor::Green)
1482 );
1483 assert_eq!(MarkColor::from_attrs(&[]), None);
1484 assert_eq!(MarkColor::from_attrs(&attr("id", "red")), None);
1485 // A bare attribute has no value to read a colour out of.
1486 assert_eq!(
1487 MarkColor::from_attrs(&[("data-color".to_string(), None)]),
1488 None
1489 );
1490 }
1491
1492 /// Each open type reads the **name first** and the value second, and spells
1493 /// back what it read in one canonical form — so a size set twice from the
1494 /// same field writes the same bytes both times, and a document rewritten by
1495 /// leaf is a document a stylesheet can still key on where a name was used.
1496 #[test]
1497 fn each_property_reads_a_name_or_a_value_and_spells_one_of_them_back() {
1498 // Size: the seven keywords, then `<number>pt`.
1499 let size = |v: &str| FontSize::from_attr(v);
1500 assert_eq!(size("large"), Some(FontSize::Step(SizeStep::Large)));
1501 assert_eq!(size("14pt"), FontSize::points(14.0));
1502 assert_eq!(size("14.0pt"), size("14pt"), "the same size, spelled twice");
1503 assert_eq!(size(" 13.5pt "), FontSize::points(13.5));
1504 assert_eq!(size("14PT"), size("14pt"), "CSS reads its units either way");
1505 assert_eq!(size("14pt").unwrap().name(), "14pt");
1506 assert_eq!(size("13.50pt").unwrap().name(), "13.5pt");
1507 assert_eq!(size("13.25pt").unwrap().name(), "13.25pt");
1508 assert_eq!(size("large").unwrap().name(), "large");
1509 assert_eq!(size("14pt").unwrap().points_value(), Some(14.0));
1510 assert_eq!(size("large").unwrap().points_value(), None);
1511 assert_eq!(size("large").unwrap().step(), Some(SizeStep::Large));
1512
1513 // Line height: the three names, then any positive decimal — and a
1514 // decimal that spells a name *is* the name.
1515 let lh = |v: &str| LineHeight::from_attr(v);
1516 assert_eq!(lh("1.5"), Some(LineHeight::Step(LineSpacing::OneHalf)));
1517 assert_eq!(lh("1.50"), lh("1.5"), "one spacing, not two");
1518 assert_eq!(lh("2.0"), Some(LineHeight::Step(LineSpacing::Double)));
1519 assert_eq!(lh("1.3"), LineHeight::ratio(1.3));
1520 assert_eq!(lh("1.3").unwrap().name(), "1.3");
1521 assert_eq!(lh("1.25").unwrap().name(), "1.25");
1522 assert_eq!(lh("1.5").unwrap().name(), "1.5");
1523 assert!((lh("1.3").unwrap().as_f32() - 1.3).abs() < 1e-6);
1524 assert!((lh("1.5").unwrap().as_f32() - 1.5).abs() < 1e-6);
1525 // Single is absence, however it is spelled, so a gesture given it
1526 // clears the key rather than writing a `data-line-height="1"` that
1527 // says nothing.
1528 for v in ["1", "1.0", "1.00", " 1 "] {
1529 assert_eq!(lh(v), None, "{v:?} is single, which is absence");
1530 }
1531 assert_eq!(LineHeight::ratio(1.0), None);
1532
1533 // Colour: the seven names, `#rrggbb`, and `#rgb` read but never
1534 // written.
1535 let col = |v: &str| TextColor::from_attr(v);
1536 assert_eq!(col("red"), Some(TextColor::Named(MarkColor::Red)));
1537 assert_eq!(
1538 col("#c03030"),
1539 Some(TextColor::Rgb {
1540 r: 0xc0,
1541 g: 0x30,
1542 b: 0x30
1543 })
1544 );
1545 assert_eq!(col("#C03030"), col("#c03030"));
1546 assert_eq!(col("#f00"), col("#ff0000"), "each digit doubled");
1547 assert_eq!(col("#c03030").unwrap().name(), "#c03030");
1548 assert_eq!(col("red").unwrap().name(), "red");
1549 assert_eq!(col("#c03030").unwrap().rgb(), Some((0xc0, 0x30, 0x30)));
1550 assert_eq!(col("red").unwrap().named(), Some(MarkColor::Red));
1551
1552 // Face: the four generics, then any other non-empty string.
1553 let face = |v: &str| FontFace::from_attr(v);
1554 assert_eq!(face("serif"), Some(FontFace::Generic(FontFamily::Serif)));
1555 assert_eq!(face("Garamond"), Some(FontFace::Named("Garamond".into())));
1556 assert_eq!(face(" Garamond "), face("Garamond"));
1557 assert_eq!(face("Garamond").unwrap().name(), "Garamond");
1558 assert_eq!(face("serif").unwrap().name(), "serif");
1559 assert_eq!(face("Garamond").unwrap().generic(), None);
1560 }
1561
1562 /// A value outside the grammar is what it was before the vocabulary opened:
1563 /// `None` here, carried untouched by the document, and drawn at the theme's
1564 /// default. `px` is a screen's unit and a document is not a screen; the
1565 /// relative units are what the steps already are; and a colour function is
1566 /// a CSS parser leaf is not going to become.
1567 #[test]
1568 fn a_value_outside_the_grammar_is_carried_and_not_guessed_at() {
1569 for v in ["huge", "14px", "1.3em", "14", "pt", "-14pt", "0pt", ""] {
1570 assert_eq!(FontSize::from_attr(v), None, "{v:?} is not a size");
1571 }
1572 for v in ["1.3em", "normal", "-1.3", "0", "1.2.3", ""] {
1573 assert_eq!(LineHeight::from_attr(v), None, "{v:?} is not a spacing");
1574 }
1575 for v in [
1576 "rgb(192, 48, 48)",
1577 "chartreuse",
1578 "#c0303",
1579 "#gggggg",
1580 "c03030",
1581 "#",
1582 "",
1583 ] {
1584 assert_eq!(TextColor::from_attr(v), None, "{v:?} is not a colour");
1585 }
1586 // A face has almost no grammar to fall outside of — only emptiness,
1587 // because a family name is whatever the author typed.
1588 assert_eq!(FontFace::from_attr(" "), None);
1589 assert_eq!(FontFace::from_attr(""), None);
1590 // And a bare attribute has no value at all, at every key.
1591 let bare = |k: &str| vec![(k.to_string(), None)];
1592 assert_eq!(FontSize::from_attrs(&bare("data-size")), None);
1593 assert_eq!(LineHeight::from_attrs(&bare("data-line-height")), None);
1594 assert_eq!(TextColor::from_attrs(&bare("data-color")), None);
1595 assert_eq!(FontFace::from_attrs(&bare("data-font")), None);
1596 }
1597
1598 /// The fixed point is the reason a [`Style`] stays `Copy` and `Eq`, and
1599 /// hundredths is where the rounding lands. Pinned because the spelling is
1600 /// what a document is written with: a shortest decimal, so a size set twice
1601 /// from the same field writes the same bytes.
1602 #[test]
1603 fn a_value_is_hundredths_and_spells_itself_as_short_as_it_can() {
1604 let h = |v: f32| Hundredths::from_f32(v).unwrap().to_string();
1605 assert_eq!(h(14.0), "14");
1606 assert_eq!(h(13.5), "13.5");
1607 assert_eq!(h(1.25), "1.25");
1608 assert_eq!(h(1.3), "1.3");
1609 assert_eq!(h(0.05), "0.05");
1610 assert_eq!(Hundredths::from_f32(14.0).unwrap().as_f32(), 14.0);
1611 assert_eq!(Hundredths::from_f32(14.0).unwrap().hundredths(), 1400);
1612 // Out of what a u16 of hundredths holds, and out of what a size means.
1613 assert_eq!(Hundredths::from_f32(700.0), None);
1614 assert_eq!(Hundredths::from_f32(0.0), None);
1615 assert_eq!(Hundredths::from_f32(-1.0), None);
1616 assert_eq!(Hundredths::from_f32(f32::NAN), None);
1617 // And an integer part too long to hold is a `None`, not an overflow.
1618 assert_eq!(FontSize::from_attr("42949672.99pt"), None);
1619 assert_eq!(FontSize::from_attr("999999999999pt"), None);
1620 assert_eq!(FontSize::from_attr("655.36pt"), None);
1621 assert_eq!(FontSize::from_attr("655.35pt").unwrap().name(), "655.35pt");
1622 // A third decimal place rounds rather than being refused — a font panel
1623 // hands back whatever floating point made of its slider.
1624 assert_eq!(FontSize::from_attr("13.456pt"), FontSize::points(13.46));
1625 assert_eq!(FontSize::from_attr("13.454pt"), FontSize::points(13.45));
1626 // CSS wants digits on whichever side of the point the number has: `.5`
1627 // is a number, a trailing bare point is a typo.
1628 assert_eq!(FontSize::from_attr(".5pt"), FontSize::points(0.5));
1629 assert_eq!(LineHeight::from_attr(".5"), LineHeight::ratio(0.5));
1630 assert_eq!(FontSize::from_attr("14.pt"), None);
1631 assert_eq!(LineHeight::from_attr("1."), None);
1632 assert_eq!(FontSize::from_attr(".pt"), None);
1633 }
1634
1635 /// A glyph carries a [`FaceId`], not a `String`, and the id is derived from
1636 /// the name so that a row built three different ways names one face. The
1637 /// table is the only place the string lives.
1638 #[test]
1639 fn a_named_face_is_interned_once_and_its_id_is_the_name_s_own() {
1640 let mut faces = FaceTable::default();
1641 let garamond = FontFace::Named("Garamond".into());
1642 let a = faces.intern(&garamond);
1643 let b = faces.intern(&FontFace::Named("Garamond".into()));
1644 assert_eq!(a, b, "one name, one id");
1645 assert_eq!(faces.len(), 1, "and one entry");
1646 assert_eq!(a, FaceRef::Named(FaceId::of("Garamond")));
1647 assert_eq!(faces.name(FaceId::of("Garamond")), Some("Garamond"));
1648 assert_eq!(a.generic(), None);
1649
1650 // A generic names itself and needs no entry.
1651 let serif = faces.intern(&FontFace::Generic(FontFamily::Serif));
1652 assert_eq!(serif, FaceRef::Generic(FontFamily::Serif));
1653 assert_eq!(serif.id(), None);
1654 assert_eq!(faces.len(), 1);
1655
1656 // Two tables that met the same names in opposite orders are equal, so
1657 // a map assembled out of cache hits compares against a fresh build.
1658 let mut one = FaceTable::default();
1659 one.intern(&FontFace::Named("Futura".into()));
1660 one.intern(&garamond);
1661 let mut two = FaceTable::default();
1662 two.intern(&garamond);
1663 two.intern(&FontFace::Named("Futura".into()));
1664 assert_eq!(one, two);
1665
1666 // And a merge is how a build makes one table out of several walks.
1667 let mut merged = FaceTable::default();
1668 merged.merge(&one);
1669 merged.merge(&faces);
1670 assert_eq!(merged.len(), 2);
1671 assert_eq!(merged.name(FaceId::of("Futura")), Some("Futura"));
1672 assert_eq!(merged.name(FaceId::of("Bodoni")), None);
1673 }
1674
1675 /// `spell` is the one door from what a glyph carries to what a `data-font`
1676 /// says — the line every binding and every native resolver would otherwise
1677 /// write for itself, and all four would have to agree that an id from
1678 /// another map names nothing.
1679 #[test]
1680 fn a_face_table_spells_the_face_a_glyph_carries() {
1681 let mut faces = FaceTable::default();
1682 let garamond = faces.intern(&FontFace::Named("Garamond".into()));
1683 assert_eq!(faces.spell(garamond).as_deref(), Some("Garamond"));
1684 assert_eq!(
1685 faces
1686 .spell(FaceRef::Generic(FontFamily::SansSerif))
1687 .as_deref(),
1688 Some("sans-serif"),
1689 "a generic names itself, and needs no entry to do it"
1690 );
1691 assert_eq!(
1692 faces.spell(FaceRef::Named(FaceId::of("Bodoni"))),
1693 None,
1694 "an id from another map draws in the body face and names nothing"
1695 );
1696 }
1697
1698 /// The one ratio that is absence, told apart from the ratios that are
1699 /// mistakes. `from_attr` answers `None` for both, which is why a binding
1700 /// that must clear the key for the first and refuse the second asks this.
1701 #[test]
1702 fn single_spacing_is_the_one_ratio_that_means_the_theme_s_own() {
1703 for single in ["1", "1.0", "1.00", " 1 "] {
1704 assert!(LineHeight::is_absence(single), "{single}");
1705 assert_eq!(LineHeight::from_attr(single), None, "{single}");
1706 }
1707 for value in ["1.3", "1.5", "2", "0", "0.5", "huge", "1.", "", "1em"] {
1708 assert!(!LineHeight::is_absence(value), "{value}");
1709 }
1710 }
1711}