Skip to main content

markdoc_pdf/render/
style.rs

1//! Document style spec.
2//!
3//! Loaded either from a TOML file (`Style::from_toml_str` /
4//! `Style::from_toml_file`) or built from the in-code `Default` impl. All
5//! fields are `#[serde(default)]` so partial overrides are easy: a TOML
6//! file can specify just the page size and inherit everything else.
7
8use std::collections::{BTreeMap, HashMap};
9
10use serde::Deserialize;
11
12#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct ColorRgb {
15    pub r: u8,
16    pub g: u8,
17    pub b: u8,
18}
19
20impl ColorRgb {
21    pub const fn new(r: u8, g: u8, b: u8) -> Self {
22        Self { r, g, b }
23    }
24}
25
26impl From<ColorRgb> for krilla::color::rgb::Color {
27    fn from(c: ColorRgb) -> Self {
28        krilla::color::rgb::Color::new(c.r, c.g, c.b)
29    }
30}
31
32#[derive(Debug, Clone, Deserialize)]
33#[serde(default, deny_unknown_fields)]
34pub struct HeadingStyle {
35    pub font_size: f32,
36    pub font_weight: f32,
37    pub space_before: f32,
38    pub space_after: f32,
39    /// Text colour for this heading level. Defaults to the document
40    /// body `text_color` when unset; set it (e.g. to a brand colour)
41    /// to tint headings independently of body text.
42    pub color: Option<ColorRgb>,
43    /// Font families for this element, in fallback order. Empty means
44    /// "inherit the document body families" (`body_font_families`, or
45    /// the bundled Noto defaults when that is also empty). Names must
46    /// be families the font collection knows — either system-installed
47    /// or exposed by a file listed in `font_paths`.
48    ///
49    /// Note this REPLACES the body list rather than extending it, so a
50    /// Latin-only face here will lose the multi-script fallbacks. List
51    /// the scripts you need explicitly if the document is not Latin-only.
52    pub font_families: Vec<String>,
53}
54
55impl Default for HeadingStyle {
56    fn default() -> Self {
57        Self {
58            font_families: Vec::new(),
59            font_size: 14.0,
60            font_weight: 700.0,
61            space_before: 12.0,
62            space_after: 6.0,
63            color: None,
64        }
65    }
66}
67
68#[derive(Debug, Clone, Deserialize)]
69#[serde(default, deny_unknown_fields)]
70pub struct HeadingStyles {
71    pub h1: HeadingStyle,
72    pub h2: HeadingStyle,
73    pub h3: HeadingStyle,
74    pub h4: HeadingStyle,
75    pub h5: HeadingStyle,
76    pub h6: HeadingStyle,
77}
78
79impl Default for HeadingStyles {
80    fn default() -> Self {
81        Self {
82            h1: HeadingStyle {
83                font_size: 26.0,
84                font_weight: 700.0,
85                space_before: 18.0,
86                space_after: 12.0,
87                color: None,
88                font_families: Vec::new(),
89            },
90            h2: HeadingStyle {
91                font_size: 21.0,
92                font_weight: 700.0,
93                space_before: 16.0,
94                space_after: 10.0,
95                color: None,
96                font_families: Vec::new(),
97            },
98            h3: HeadingStyle {
99                font_size: 17.0,
100                font_weight: 700.0,
101                space_before: 14.0,
102                space_after: 8.0,
103                color: None,
104                font_families: Vec::new(),
105            },
106            h4: HeadingStyle {
107                font_size: 14.0,
108                font_weight: 700.0,
109                space_before: 12.0,
110                space_after: 6.0,
111                color: None,
112                font_families: Vec::new(),
113            },
114            h5: HeadingStyle {
115                font_size: 12.0,
116                font_weight: 700.0,
117                space_before: 10.0,
118                space_after: 6.0,
119                color: None,
120                font_families: Vec::new(),
121            },
122            h6: HeadingStyle {
123                font_size: 11.0,
124                font_weight: 700.0,
125                space_before: 10.0,
126                space_after: 4.0,
127                color: None,
128                font_families: Vec::new(),
129            },
130        }
131    }
132}
133
134impl HeadingStyles {
135    pub fn for_level(&self, level: u8) -> &HeadingStyle {
136        match level {
137            1 => &self.h1,
138            2 => &self.h2,
139            3 => &self.h3,
140            4 => &self.h4,
141            5 => &self.h5,
142            _ => &self.h6,
143        }
144    }
145}
146
147/// Automatic section numbering for headings (`1`, `1.1`, `1.1.1`, …).
148///
149/// Off by default — themes that don't opt in render headings exactly as
150/// before. When enabled, the computed prefix is baked into the heading
151/// text itself, so it flows automatically into the visible heading, the
152/// running header (`{chapter}` / `{section}`), and the table of contents.
153///
154/// Only levels `1..=max_depth` are numbered; deeper headings render
155/// unprefixed (a common convention — e.g. number chapters/sections but
156/// leave sub-sub-subsections plain). An individual heading opts out by
157/// carrying an anchor tag with `numbered="false"`
158/// (`## Copyright {% tag numbered="false" /%}`) — used for front-matter
159/// sections (copyright, preface) that should precede `1.` without
160/// consuming a number.
161#[derive(Debug, Clone, Deserialize)]
162#[serde(default, deny_unknown_fields)]
163pub struct HeadingNumbering {
164    /// Master switch. When `false` (the default) no numbering happens.
165    pub enabled: bool,
166    /// Deepest heading level that receives a number. `3` numbers
167    /// `h1`/`h2`/`h3` and leaves `h4`+ plain. Clamped to `1..=6`.
168    pub max_depth: u8,
169    /// String placed between the last number and the heading text.
170    /// Defaults to a single space (`"1.2 Title"`); set to e.g. `". "`
171    /// for `"1.2. Title"`.
172    pub separator: String,
173}
174
175impl Default for HeadingNumbering {
176    fn default() -> Self {
177        Self {
178            enabled: false,
179            max_depth: 3,
180            separator: " ".to_string(),
181        }
182    }
183}
184
185/// How a callout is framed.
186#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq)]
187#[serde(rename_all = "snake_case")]
188pub enum CalloutDecoration {
189    /// Filled rectangle with optional border and a left accent stripe
190    /// (the default — the "admonition box" look).
191    #[default]
192    Box,
193    /// No fill or stripe — a horizontal rule above and below the content
194    /// (the "bulletin / notice" look). The rule colour is the callout's
195    /// `accent`; its thickness is the global `callout_rule_thickness`.
196    Rules,
197}
198
199#[derive(Debug, Clone, Deserialize)]
200#[serde(default, deny_unknown_fields)]
201pub struct CalloutStyle {
202    pub background: ColorRgb,
203    pub border: ColorRgb,
204    /// Left accent bar colour. Drawn as a thicker stripe on the left side
205    /// of the box (`decoration = "box"`), or as the rule colour
206    /// (`decoration = "rules"`).
207    pub accent: ColorRgb,
208    /// How the callout is framed. Defaults to a filled box.
209    pub decoration: CalloutDecoration,
210    /// Optional bold heading drawn as the first line of the box (e.g.
211    /// `"WARNING"`). Empty / unset renders no label, preserving the
212    /// plain-box behaviour. Typically uppercase.
213    pub label: String,
214    /// Colour for the `label`. Defaults to the document body text
215    /// colour; set it (e.g. to the accent) to tint the heading.
216    pub label_color: Option<ColorRgb>,
217    /// Centre the label across the content column instead of
218    /// left-aligning it. Used by the bulletin layout.
219    pub label_centered: bool,
220    /// Optional icon asset (any `AssetResolver` URI / path) drawn at the
221    /// box's top-left, with the label and body indented past it. Empty /
222    /// unset renders no icon.
223    pub icon: String,
224    /// Font families for this element, in fallback order. Empty means
225    /// "inherit the document body families" (`body_font_families`, or
226    /// the bundled Noto defaults when that is also empty). Names must
227    /// be families the font collection knows — either system-installed
228    /// or exposed by a file listed in `font_paths`.
229    ///
230    /// Note this REPLACES the body list rather than extending it, so a
231    /// Latin-only face here will lose the multi-script fallbacks. List
232    /// the scripts you need explicitly if the document is not Latin-only.
233    pub font_families: Vec<String>,
234}
235
236impl Default for CalloutStyle {
237    fn default() -> Self {
238        Self {
239            font_families: Vec::new(),
240            background: ColorRgb::new(247, 248, 250),
241            border: ColorRgb::new(220, 225, 230),
242            accent: ColorRgb::new(120, 130, 145),
243            decoration: CalloutDecoration::Box,
244            label: String::new(),
245            label_color: None,
246            label_centered: false,
247            icon: String::new(),
248        }
249    }
250}
251
252/// How `[text](url)` links are visually distinguished from body text.
253/// The PDF link annotation is created regardless of these settings;
254/// these only affect the glyphs underneath so readers spot the link
255/// without hovering.
256#[derive(Debug, Clone, Deserialize)]
257#[serde(default, deny_unknown_fields)]
258pub struct LinkStyle {
259    /// Text colour applied to the link's glyphs.
260    pub color: ColorRgb,
261    /// Render link text in italic.
262    pub italic: bool,
263    /// Render link text in bold (font weight 700).
264    pub bold: bool,
265    /// Draw a stroked rule directly below each line of the link's
266    /// text, in `color` and at `underline_thickness`. Useful when
267    /// colour alone isn't enough to make the link stand out (e.g.
268    /// for accessibility or B&W printing).
269    pub underline: bool,
270    /// Stroke thickness for the underline rule, in PDF points.
271    /// Ignored when `underline = false`.
272    pub underline_thickness: f32,
273}
274
275impl Default for LinkStyle {
276    fn default() -> Self {
277        Self {
278            color: ColorRgb::new(20, 95, 175),
279            italic: false,
280            bold: false,
281            underline: false,
282            underline_thickness: 0.6,
283        }
284    }
285}
286
287/// Per-token-class colour palette for the built-in syntax highlighter.
288/// Token classes a language doesn't produce simply go unused; languages
289/// without a recognised name (or `language` attribute) fall back to
290/// `code_text_color`.
291#[derive(Debug, Clone, Deserialize)]
292#[serde(default, deny_unknown_fields)]
293pub struct CodeHighlightStyle {
294    pub keyword: ColorRgb,
295    pub string: ColorRgb,
296    pub comment: ColorRgb,
297    pub number: ColorRgb,
298}
299
300impl Default for CodeHighlightStyle {
301    fn default() -> Self {
302        Self {
303            keyword: ColorRgb::new(170, 50, 130),
304            string: ColorRgb::new(70, 120, 50),
305            comment: ColorRgb::new(120, 130, 140),
306            number: ColorRgb::new(190, 110, 30),
307        }
308    }
309}
310
311#[derive(Debug, Clone, Deserialize)]
312#[serde(default, deny_unknown_fields)]
313pub struct CalloutStyles {
314    pub note: CalloutStyle,
315    pub info: CalloutStyle,
316    pub warning: CalloutStyle,
317    pub caution: CalloutStyle,
318    pub danger: CalloutStyle,
319    pub success: CalloutStyle,
320    pub notice: CalloutStyle,
321}
322
323impl Default for CalloutStyles {
324    fn default() -> Self {
325        // Colours per kind; `label` / `label_color` / `icon` inherit the
326        // label-less, icon-less defaults (`..CalloutStyle::default()`) so
327        // existing themes render unchanged until they opt in.
328        Self {
329            note: CalloutStyle {
330                background: ColorRgb::new(247, 248, 250),
331                border: ColorRgb::new(220, 225, 230),
332                accent: ColorRgb::new(120, 130, 145),
333                ..CalloutStyle::default()
334            },
335            info: CalloutStyle {
336                background: ColorRgb::new(232, 244, 253),
337                border: ColorRgb::new(180, 213, 240),
338                accent: ColorRgb::new(54, 130, 200),
339                ..CalloutStyle::default()
340            },
341            warning: CalloutStyle {
342                background: ColorRgb::new(255, 247, 230),
343                border: ColorRgb::new(252, 211, 166),
344                accent: ColorRgb::new(217, 119, 6),
345                ..CalloutStyle::default()
346            },
347            caution: CalloutStyle {
348                background: ColorRgb::new(255, 247, 230),
349                border: ColorRgb::new(252, 211, 166),
350                accent: ColorRgb::new(217, 119, 6),
351                ..CalloutStyle::default()
352            },
353            danger: CalloutStyle {
354                background: ColorRgb::new(254, 232, 232),
355                border: ColorRgb::new(248, 187, 187),
356                accent: ColorRgb::new(204, 51, 51),
357                ..CalloutStyle::default()
358            },
359            success: CalloutStyle {
360                background: ColorRgb::new(232, 250, 240),
361                border: ColorRgb::new(168, 220, 188),
362                accent: ColorRgb::new(46, 160, 100),
363                ..CalloutStyle::default()
364            },
365            notice: CalloutStyle {
366                background: ColorRgb::new(245, 240, 255),
367                border: ColorRgb::new(214, 198, 240),
368                accent: ColorRgb::new(120, 80, 200),
369                ..CalloutStyle::default()
370            },
371        }
372    }
373}
374
375impl CalloutStyles {
376    pub fn for_kind(&self, kind: &str) -> &CalloutStyle {
377        match kind {
378            "info" => &self.info,
379            "warning" => &self.warning,
380            "caution" => &self.caution,
381            "danger" => &self.danger,
382            "success" => &self.success,
383            "notice" => &self.notice,
384            _ => &self.note,
385        }
386    }
387}
388
389#[derive(Debug, Clone, Deserialize)]
390#[serde(default, deny_unknown_fields)]
391pub struct PageLayoutStyle {
392    /// Number of text columns on each body page (1 = default full-width column).
393    pub columns: u8,
394    /// Horizontal gap between columns, in points.
395    pub gap: f32,
396    /// Headings at this level and above span all columns (1 = H1 only).
397    pub span_heading_through: u8,
398}
399
400impl Default for PageLayoutStyle {
401    fn default() -> Self {
402        Self {
403            columns: 1,
404            gap: 20.0,
405            span_heading_through: 1,
406        }
407    }
408}
409
410#[derive(Debug, Clone, Deserialize)]
411#[serde(default, deny_unknown_fields)]
412pub struct Style {
413    /// Schema-version stamp; reserved for future incompatible bumps.
414    pub schema_version: u32,
415
416    // ── Page geometry ─────────────────────────────────────────────────
417    pub page_width: f32,
418    pub page_height: f32,
419    pub margin_x: f32,
420    pub margin_y: f32,
421    /// Multi-column body layout (1 = single column, the default).
422    pub page_layout: PageLayoutStyle,
423    /// When the rendered document ends on an odd page, append one page so
424    /// the physical total is even. Intended for duplex (double-sided)
425    /// printing, where each new document should begin on the front of a
426    /// fresh sheet. The padding page carries the running header / footer
427    /// (and watermark) like any other page but has no body content, and it
428    /// is counted in the `{total}` page-of total. Off by default.
429    /// Ignored when [`pad_to_multiple`] is greater than 1.
430    pub pad_to_even: bool,
431    /// Append blank pages (header / footer / watermark only) until the
432    /// physical page count is a multiple of this value. `0` or `1` leaves
433    /// the count unchanged. `4` is the booklet / saddle-stitch case (four
434    /// pages per folded sheet). Counts toward `{total}`. When set, it
435    /// supersedes [`pad_to_even`].
436    pub pad_to_multiple: u32,
437
438    // ── Body text ─────────────────────────────────────────────────────
439    pub body_font_size: f32,
440    pub body_line_height: f32,
441    pub paragraph_space_after: f32,
442    pub text_color: ColorRgb,
443    /// Horizontal alignment for body prose (paragraphs, list-item and
444    /// callout bodies). Headings, captions and table cells are
445    /// unaffected. Defaults to `left`; `justify` spreads every line but
446    /// the last to the column width.
447    pub text_align: TextAlign,
448    /// How `[text](url)` links are visually distinguished from body
449    /// text. The PDF link annotation is created regardless; this is
450    /// purely the visual cue so a reader spots the link before they
451    /// hover over it.
452    pub link: LinkStyle,
453
454    // ── Headings ──────────────────────────────────────────────────────
455    pub heading: HeadingStyles,
456    /// Automatic `1` / `1.1` / `1.1.1` section numbering. Off by default.
457    pub heading_numbering: HeadingNumbering,
458
459    // ── Lists ─────────────────────────────────────────────────────────
460    pub list_indent: f32,
461    pub list_item_space_after: f32,
462    pub list_marker_gap: f32,
463    pub list_marker: ListMarkerStyle,
464
465    // ── Block quotes ──────────────────────────────────────────────────
466    pub blockquote_indent: f32,
467    pub blockquote_bar_width: f32,
468    pub blockquote_bar_color: ColorRgb,
469    pub blockquote_text_color: ColorRgb,
470
471    // ── Code ──────────────────────────────────────────────────────────
472    pub code_font_family: String,
473    pub code_font_size: f32,
474    pub code_padding: f32,
475    pub code_background: ColorRgb,
476    pub code_text_color: ColorRgb,
477    /// Per-token-class palette for the small built-in syntax
478    /// highlighter. Applies to fenced code blocks whose `language`
479    /// attribute is recognised.
480    pub code_highlight: CodeHighlightStyle,
481
482    // ── Callouts ──────────────────────────────────────────────────────
483    pub callout_padding: f32,
484    pub callout_accent_width: f32,
485    pub callout_styles: CalloutStyles,
486    pub callout_space_after: f32,
487    /// Font size (pt) for a callout's bold label line.
488    pub callout_label_size: f32,
489    /// Square draw size (pt) for a callout's icon.
490    pub callout_icon_size: f32,
491    /// Horizontal gap (pt) between the icon and the label / body column.
492    pub callout_icon_gap: f32,
493    /// Stroke thickness (pt) for the rules of a `decoration = "rules"`
494    /// callout.
495    pub callout_rule_thickness: f32,
496
497    // ── Horizontal rule ───────────────────────────────────────────────
498    pub rule_color: ColorRgb,
499    pub rule_thickness: f32,
500    pub rule_space_around: f32,
501
502    // ── Table of contents / list of figures / list of tables ─────────
503    pub toc: TocStyle,
504    pub lof: ListSectionStyle,
505    pub lot: ListSectionStyle,
506
507    // ── PDF export profile ────────────────────────────────────────────
508    pub pdf_export: PdfExportProfile,
509
510    // ── Page decoration (header / footer) ─────────────────────────────
511    pub page_decoration: PageDecorationStyle,
512
513    // ── Captions ──────────────────────────────────────────────────────
514    pub caption_position: CaptionPosition,
515    /// Colour for figure/table caption text. `None` falls back to
516    /// `blockquote_text_color` (the historical default); a per-caption
517    /// `{% caption color="#…" %}` overrides both.
518    pub caption_color: Option<ColorRgb>,
519    /// Prefix used for figure caption labels — `"<prefix> N"` or
520    /// `"<prefix> N: caption"`. Defaults to "Figure"; common alternates
521    /// include "Fig.", "Image", localised forms, etc.
522    pub figure_caption_prefix: String,
523    /// Prefix for table caption labels. Defaults to "Table"; common
524    /// alternates include "Tab.".
525    pub table_caption_prefix: String,
526    /// Separator between the numbered prefix and the caption text
527    /// (when present). Defaults to ":".
528    pub caption_separator: String,
529    /// When true, an image's `title` attribute (from `{% media title="…" /%}`
530    /// or markdown `![alt](url "title")`) is used as the caption /
531    /// accessibility text when neither an explicit `{% caption %}` nor `alt`
532    /// is present. Off by default — `title` is otherwise ignored in the PDF,
533    /// since it has no natural print rendering.
534    pub image_title_fallback: bool,
535
536    // ── Tables ────────────────────────────────────────────────────────
537    pub table_column_sizing: TableColumnSizing,
538    /// Explicit relative column widths. When set and the count matches a
539    /// table's column count, the table's inner width is split in these
540    /// proportions (weights, not absolute units — `[1.0, 3.0]` makes the
541    /// second column three times the first) and `table_column_sizing` is
542    /// ignored for that table. Ideal for key/value metadata tables where a
543    /// fixed-width label column reads better than content-based sizing.
544    /// Empty (the default) leaves every table on automatic sizing.
545    pub table_column_weights: Vec<f32>,
546    /// Which rules the table draws: a full `grid` (default), only
547    /// `horizontal` row separators, or `none`.
548    pub table_borders: TableBorders,
549    pub table_cell_padding: f32,
550    pub table_border_color: ColorRgb,
551    pub table_border_thickness: f32,
552    /// Colour of the table's outer frame — the top/bottom rules (and the
553    /// left/right rules in `grid` mode). Unset means edges match the
554    /// internal `table_border_color`; a darker edge gives a booktabs look.
555    pub table_edge_color: Option<ColorRgb>,
556    /// Thickness of those outer rules; defaults to `table_border_thickness`.
557    pub table_edge_thickness: Option<f32>,
558    pub table_header_background: ColorRgb,
559    pub table_header_text_color: ColorRgb,
560    /// Background fill for alternating body rows (zebra striping); applied
561    /// to every other body row. `None` (the default) disables it. A table
562    /// can override it with the `{% table stripe="#rrggbb" %}` attribute,
563    /// or `stripe="none"` to switch striping off for that one table.
564    pub table_stripe_color: Option<ColorRgb>,
565    /// Treat the first column as a header column (row headers): its cells
566    /// render in the header text style (bold, `table_header_text_color`)
567    /// over a `table_header_background` fill, and are tagged as row headers
568    /// for accessibility. Off by default; set per table with
569    /// `{% table header_column=true %}`. Independent of the header row, so
570    /// a table can have both.
571    pub table_header_column: bool,
572    pub table_space_after: f32,
573
574    // ── Footnotes ─────────────────────────────────────────────────────
575    pub footnote: FootnoteStyle,
576
577    // ── Watermark / page background ───────────────────────────────────
578    /// Optional watermark drawn beneath every page's body content. Use
579    /// for letterhead images, "DRAFT" diagonals, confidentiality
580    /// markings, etc. Tagged as `Artifact` so screen readers ignore it.
581    pub watermark: Option<Watermark>,
582
583    // ── Custom fonts ──────────────────────────────────────────────────
584    /// File paths to additional `.ttf`/`.otf` fonts that should be
585    /// loaded into the font collection before laying out the document.
586    /// Any family they expose can then be referenced via `font_families`
587    /// just like the bundled Noto family. Loaded once at the start of
588    /// the render — paths are not re-checked.
589    pub font_paths: Vec<String>,
590    /// Family names used for body text (in fallback order). Empty list
591    /// means "use the bundled defaults" (Noto Sans + the multi-script
592    /// Noto fallbacks). Pass family names registered by your own
593    /// `font_paths` to swap in a custom typeface.
594    pub body_font_families: Vec<String>,
595
596    // ── Hyphenation ───────────────────────────────────────────────────
597    pub hyphenation: HyphenationStyle,
598
599    // ── Cover page ────────────────────────────────────────────────────
600    /// Synthesised cover page rendered before any body content. Drawn
601    /// from frontmatter (title, description, authors, date) plus an
602    /// optional logo. Source documents stay output-agnostic — all
603    /// cover-page knobs live here in the style.
604    pub coverpage: CoverPageStyle,
605
606    // ── Tables drawn from frontmatter ─────────────────────────────────
607    /// Tags that stand for a table built from the document's frontmatter,
608    /// keyed by tag name. Each `{% <name> /%}` in the composed document
609    /// (partials and sections included) becomes a level-2 heading and a
610    /// table, one row per map in the frontmatter list the entry names.
611    /// Empty by default: a tag named nowhere here renders as Markdoc
612    /// renders it, which for a self-closing tag is nothing.
613    ///
614    /// ```toml
615    /// [frontmatter_tables.document-history]
616    /// key = "documentHistory"
617    /// heading = "Document history"
618    /// columns = [
619    ///   { field = "version", header = "Version" },
620    ///   { field = "date", header = "Date" },
621    ///   { field = "description", header = "Description" },
622    /// ]
623    /// ```
624    pub frontmatter_tables: BTreeMap<String, FrontmatterTable>,
625}
626
627/// One entry of [`Style::frontmatter_tables`]: where the rows of a table
628/// come from, its columns, and the heading above it.
629#[derive(Debug, Clone, PartialEq, Deserialize)]
630#[serde(deny_unknown_fields)]
631pub struct FrontmatterTable {
632    /// The frontmatter field the rows come from: a list of maps, one row
633    /// per map. An item that is not a map is skipped. When the field is
634    /// absent, is not a list or holds no map, the tag is removed, heading
635    /// and all.
636    pub key: String,
637    /// The heading above the table. Absent or `""`, there is none. The
638    /// tag's `title` attribute replaces it, and `title=""` drops it.
639    #[serde(default)]
640    pub heading: Option<String>,
641    /// The columns, left to right. With none, the tag is removed.
642    pub columns: Vec<FrontmatterColumn>,
643}
644
645/// One column of a [`FrontmatterTable`].
646#[derive(Debug, Clone, PartialEq, Deserialize)]
647#[serde(deny_unknown_fields)]
648pub struct FrontmatterColumn {
649    /// The key each cell is read from, in a map of the list. A cell whose
650    /// key is absent, or holds no text (a list, a map, null, `""`), is
651    /// empty; a number reads as YAML read it.
652    pub field: String,
653    /// The column's header cell.
654    pub header: String,
655}
656
657impl Default for Style {
658    fn default() -> Self {
659        Self {
660            schema_version: 1,
661            page_width: 595.0,
662            page_height: 842.0, // A4 — real page size now that we paginate
663            margin_x: 72.0,
664            margin_y: 72.0,
665            page_layout: PageLayoutStyle::default(),
666            pad_to_even: false,
667            pad_to_multiple: 0,
668            text_align: TextAlign::default(),
669            body_font_size: 11.0,
670            body_line_height: 1.5,
671            paragraph_space_after: 8.0,
672            text_color: ColorRgb::new(20, 20, 20),
673            link: LinkStyle::default(),
674            heading: HeadingStyles::default(),
675            heading_numbering: HeadingNumbering::default(),
676            list_indent: 24.0,
677            list_item_space_after: 4.0,
678            list_marker_gap: 8.0,
679            list_marker: ListMarkerStyle::default(),
680            blockquote_indent: 24.0,
681            blockquote_bar_width: 3.0,
682            blockquote_bar_color: ColorRgb::new(200, 205, 215),
683            blockquote_text_color: ColorRgb::new(80, 90, 100),
684            code_font_family: "Noto Sans Mono".into(),
685            code_font_size: 10.0,
686            code_padding: 12.0,
687            code_background: ColorRgb::new(245, 246, 248),
688            code_text_color: ColorRgb::new(40, 50, 70),
689            code_highlight: CodeHighlightStyle::default(),
690            callout_padding: 12.0,
691            callout_accent_width: 4.0,
692            callout_styles: CalloutStyles::default(),
693            callout_space_after: 12.0,
694            callout_label_size: 11.0,
695            callout_icon_size: 20.0,
696            callout_icon_gap: 10.0,
697            callout_rule_thickness: 0.7,
698            rule_color: ColorRgb::new(200, 205, 215),
699            rule_thickness: 0.75,
700            rule_space_around: 12.0,
701            toc: TocStyle::default(),
702            lof: ListSectionStyle::default(),
703            lot: ListSectionStyle::default(),
704            pdf_export: PdfExportProfile::default(),
705            page_decoration: PageDecorationStyle::default(),
706            caption_position: CaptionPosition::Above,
707            caption_color: None,
708            figure_caption_prefix: "Figure".to_string(),
709            table_caption_prefix: "Table".to_string(),
710            caption_separator: ":".to_string(),
711            image_title_fallback: false,
712            table_column_sizing: TableColumnSizing::Auto,
713            table_column_weights: Vec::new(),
714            table_borders: TableBorders::Grid,
715            table_cell_padding: 6.0,
716            table_border_color: ColorRgb::new(210, 215, 225),
717            table_border_thickness: 0.5,
718            table_edge_color: None,
719            table_edge_thickness: None,
720            table_header_background: ColorRgb::new(240, 242, 246),
721            table_header_text_color: ColorRgb::new(20, 30, 50),
722            table_stripe_color: None,
723            table_header_column: false,
724            table_space_after: 12.0,
725            footnote: FootnoteStyle::default(),
726            watermark: None,
727            font_paths: Vec::new(),
728            body_font_families: Vec::new(),
729            hyphenation: HyphenationStyle::default(),
730            coverpage: CoverPageStyle::default(),
731            frontmatter_tables: BTreeMap::new(),
732        }
733    }
734}
735
736/// A page-level watermark. Use the `kind` field to pick image vs text.
737#[derive(Debug, Clone, Deserialize)]
738#[serde(default, deny_unknown_fields)]
739pub struct Watermark {
740    pub kind: WatermarkKind,
741    /// 0.0 (fully transparent) to 1.0 (fully opaque). Defaults to 0.15
742    /// which gives a subtle "DRAFT"-style overlay.
743    pub opacity: f32,
744    /// If true, the first page renders without the watermark — useful
745    /// when the cover/title page should stay clean.
746    pub skip_first_page: bool,
747}
748
749impl Default for Watermark {
750    fn default() -> Self {
751        Self {
752            kind: WatermarkKind::Text(WatermarkText::default()),
753            opacity: 0.15,
754            skip_first_page: false,
755        }
756    }
757}
758
759#[derive(Debug, Clone, Deserialize)]
760#[serde(tag = "type", rename_all = "snake_case")]
761pub enum WatermarkKind {
762    /// A static image stretched to the configured size and anchored
763    /// to a page-relative position (top-left origin, in PDF points).
764    Image(WatermarkImage),
765    /// Diagonal text overlay across the page centre. Rotation in
766    /// degrees, anti-clockwise; e.g. `-30.0` slants from bottom-left
767    /// to top-right.
768    Text(WatermarkText),
769}
770
771#[derive(Debug, Clone, Default, Deserialize)]
772#[serde(default)]
773pub struct WatermarkImage {
774    pub src: String,
775    /// Top-left origin in PDF points. Defaults to (0, 0).
776    pub x: f32,
777    pub y: f32,
778    pub width: f32,
779    pub height: f32,
780}
781
782#[derive(Debug, Clone, Deserialize)]
783#[serde(default)]
784pub struct WatermarkText {
785    pub text: String,
786    pub font_size: f32,
787    pub color: ColorRgb,
788    pub rotation_deg: f32,
789    /// Font families for this element, in fallback order. Empty means
790    /// "inherit the document body families" (`body_font_families`, or
791    /// the bundled Noto defaults when that is also empty). Names must
792    /// be families the font collection knows — either system-installed
793    /// or exposed by a file listed in `font_paths`.
794    ///
795    /// Note this REPLACES the body list rather than extending it, so a
796    /// Latin-only face here will lose the multi-script fallbacks. List
797    /// the scripts you need explicitly if the document is not Latin-only.
798    pub font_families: Vec<String>,
799}
800
801impl Default for WatermarkText {
802    fn default() -> Self {
803        Self {
804            font_families: Vec::new(),
805            text: "DRAFT".to_string(),
806            font_size: 96.0,
807            color: ColorRgb::new(180, 180, 180),
808            rotation_deg: -30.0,
809        }
810    }
811}
812
813/// Synthesised cover/title page placed before any body content. The
814/// renderer pulls title / description / authors / date from
815/// `RenderContext` (which the CLI populates from frontmatter), plus an
816/// optional logo image. Disabled by default — most documents don't
817/// need a cover page.
818///
819/// Layout is centred vertically by the `top_margin` you pick; entries
820/// stack with explicit gaps between them. Set `subtitle` to a template
821/// string (`{description}`, `{date}`, etc.) when you want anything
822/// below the title.
823/// Where the optional logo / hero image sits in the cover-page stack.
824#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq)]
825#[serde(rename_all = "snake_case")]
826pub enum LogoPosition {
827    /// At the top of the page, above the title. The default — fits
828    /// the "letterhead + report title" pattern.
829    #[default]
830    Above,
831    /// Between the title and the subtitle. Use this when the front
832    /// page leads with a big title and the image acts as a hero
833    /// rather than a small mark.
834    BelowTitle,
835}
836
837/// Horizontal alignment of the cover-page text blocks.
838#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq)]
839#[serde(rename_all = "snake_case")]
840pub enum CoverAlign {
841    /// Centred in the body column (the default).
842    #[default]
843    Center,
844    /// Flush against the left margin — fits a "title page" look where
845    /// the title and metadata stack at the top-left.
846    Left,
847}
848
849/// Horizontal alignment for body prose. Mirrors CSS `text-align`.
850#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
851#[serde(rename_all = "snake_case")]
852pub enum TextAlign {
853    /// Flush against the start (left for LTR) edge — the default.
854    #[default]
855    Left,
856    /// Spread every line but the last to fill the column width.
857    Justify,
858    /// Centre each line within the column.
859    Center,
860    /// Flush against the end (right for LTR) edge.
861    Right,
862}
863
864impl TextAlign {
865    /// The parley alignment this maps to.
866    pub fn to_parley(self) -> parley::layout::Alignment {
867        use parley::layout::Alignment;
868        match self {
869            TextAlign::Left => Alignment::Start,
870            TextAlign::Justify => Alignment::Justify,
871            TextAlign::Center => Alignment::Center,
872            TextAlign::Right => Alignment::End,
873        }
874    }
875}
876
877#[derive(Debug, Clone, Deserialize)]
878#[serde(default, deny_unknown_fields)]
879pub struct CoverPageStyle {
880    pub enabled: bool,
881    /// Horizontal page margin for the cover page only, in points. Defaults
882    /// to the document `margin_x`. A smaller value lets cover art (the hero
883    /// image) bleed wider than the body text column.
884    pub margin_x: Option<f32>,
885    /// Vertical page margin for the cover page only, in points. Defaults to
886    /// the document `margin_y`. A smaller value gives the cover more room
887    /// (e.g. for a tall hero) and lifts the logo toward the page top. Only
888    /// honoured when the cover page skips its header / footer.
889    pub margin_y: Option<f32>,
890    pub logo: Option<LogoSpec>,
891    /// Where the logo sits relative to the title. See [`LogoPosition`].
892    pub logo_position: LogoPosition,
893    /// Optional hero image (e.g. a product photo) drawn below the cover
894    /// metadata — a second image slot so a cover can show both a brand
895    /// logo (above the title) and a hero image. `id` / `src` are templates
896    /// (`{title}` / any frontmatter var). Prefer `id` for an asset-library
897    /// GUID (`{coverImage}`); `src` still accepts a filename such as
898    /// `{title}.png`. Unlike the logo, the hero fills the cover column
899    /// width and keeps the source aspect ratio; `width` / `height` on the
900    /// spec are ignored.
901    pub hero: Option<LogoSpec>,
902    /// Gap above the hero image.
903    pub hero_gap: f32,
904    /// Vertical space above the first element on the page (the logo
905    /// when `logo_position = "above"`, otherwise the title).
906    /// Defaults to ~1/4 of A4 height.
907    pub top_margin: f32,
908    /// Gap between the logo image and the title text — applied
909    /// regardless of `logo_position`. When `above`, the gap is below
910    /// the logo; when `below_title`, it's between the title and the
911    /// logo.
912    pub logo_to_title_gap: f32,
913    pub title_font_size: f32,
914    /// Optional accent run appended inline to the title and rendered in
915    /// a lighter weight and (optionally) a different colour — e.g. a
916    /// title of "MyProduct" with `title_accent = " Manual"` renders the
917    /// product name bold and "Manual" in a muted accent beside it. The
918    /// string is a template (`{title}` / `{date}` / any frontmatter var)
919    /// so the accent can come from metadata; empty omits it.
920    pub title_accent: String,
921    /// Colour for `title_accent`. Defaults to `text_color` when unset.
922    pub title_accent_color: Option<ColorRgb>,
923    pub title_to_subtitle_gap: f32,
924    /// Template string for the subtitle — supports the same
925    /// `{title}`/`{description}`/`{date}` substitutions as headers.
926    /// Empty string omits the subtitle entirely.
927    pub subtitle: String,
928    pub subtitle_font_size: f32,
929    pub subtitle_to_authors_gap: f32,
930    pub show_authors: bool,
931    pub authors_font_size: f32,
932    pub authors_to_date_gap: f32,
933    pub show_date: bool,
934    pub date_font_size: f32,
935    pub text_color: ColorRgb,
936    /// Horizontal alignment of every cover text block (title, subtitle,
937    /// detail lines, authors, date). Defaults to centred.
938    pub align: CoverAlign,
939    /// Extra metadata lines rendered under the title, each a template
940    /// string (`{title}` / `{description}` / `{date}` / any
941    /// `RenderContext` var). Use for "Date: {date}", "Version:
942    /// {version}", etc. A line whose substitution is empty is skipped.
943    pub detail_lines: Vec<String>,
944    /// Font size for `detail_lines`.
945    pub detail_font_size: f32,
946    /// Gap below the title before the detail lines.
947    pub title_to_detail_gap: f32,
948    /// Vertical gap between consecutive detail lines.
949    pub detail_line_gap: f32,
950    /// Colour for `detail_lines`. Defaults to `text_color` when unset;
951    /// typically a muted grey.
952    pub detail_color: Option<ColorRgb>,
953    /// When `true`, insert a fully blank page directly after the
954    /// cover page so the body content starts on page 3 — a recto in
955    /// double-sided printing. Useful for printed reports / books;
956    /// no effect when the document is read on screen.
957    pub blank_page_after: bool,
958    /// Font families for this element, in fallback order. Empty means
959    /// "inherit the document body families" (`body_font_families`, or
960    /// the bundled Noto defaults when that is also empty). Names must
961    /// be families the font collection knows — either system-installed
962    /// or exposed by a file listed in `font_paths`.
963    ///
964    /// Note this REPLACES the body list rather than extending it, so a
965    /// Latin-only face here will lose the multi-script fallbacks. List
966    /// the scripts you need explicitly if the document is not Latin-only.
967    pub font_families: Vec<String>,
968}
969
970impl Default for CoverPageStyle {
971    fn default() -> Self {
972        Self {
973            font_families: Vec::new(),
974            enabled: false,
975            margin_x: None,
976            margin_y: None,
977            logo: None,
978            logo_position: LogoPosition::Above,
979            hero: None,
980            hero_gap: 40.0,
981            top_margin: 200.0,
982            logo_to_title_gap: 32.0,
983            title_font_size: 32.0,
984            title_accent: String::new(),
985            title_accent_color: None,
986            title_to_subtitle_gap: 12.0,
987            subtitle: String::new(),
988            subtitle_font_size: 14.0,
989            subtitle_to_authors_gap: 24.0,
990            show_authors: true,
991            authors_font_size: 12.0,
992            authors_to_date_gap: 8.0,
993            show_date: true,
994            date_font_size: 11.0,
995            text_color: ColorRgb::new(20, 20, 20),
996            align: CoverAlign::Center,
997            detail_lines: Vec::new(),
998            detail_font_size: 11.0,
999            title_to_detail_gap: 14.0,
1000            detail_line_gap: 3.0,
1001            detail_color: None,
1002            blank_page_after: false,
1003        }
1004    }
1005}
1006
1007/// Ordered-list numbering style for one nesting level. Mirrors the CSS
1008/// `list-style-type` values of the same name.
1009#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
1010#[serde(rename_all = "kebab-case")]
1011pub enum MarkerSequence {
1012    /// 1, 2, 3, …
1013    Decimal,
1014    /// a, b, c, … z, aa, ab, …
1015    LowerAlpha,
1016    /// A, B, C, …
1017    UpperAlpha,
1018    /// i, ii, iii, iv, …
1019    LowerRoman,
1020    /// I, II, III, IV, …
1021    UpperRoman,
1022}
1023
1024/// Styling for list-item markers. Bullets (unordered lists) are
1025/// unaffected; these knobs shape ordered-list numbering and the
1026/// optional circular badge treatment.
1027#[derive(Debug, Clone, Deserialize)]
1028#[serde(default, deny_unknown_fields)]
1029pub struct ListMarkerStyle {
1030    /// Ordered-list numbering style per nesting depth — index 0 is the
1031    /// outermost list, deeper levels cycle through the list (wrapping
1032    /// when the nesting runs deeper than the list). Empty means decimal
1033    /// at every depth, e.g. `["decimal", "lower-alpha", "lower-roman"]`
1034    /// gives `1.` → `a.` → `i.` as lists nest.
1035    pub ordered_sequences: Vec<MarkerSequence>,
1036    /// Draw each ordered marker centred inside a filled circle. The
1037    /// trailing `.` is dropped — the badge itself delimits the marker.
1038    pub badge: bool,
1039    /// Badge fill colour.
1040    pub badge_fill: ColorRgb,
1041    /// Marker text colour inside a badge. Defaults to the body text
1042    /// colour when unset.
1043    pub badge_text_color: Option<ColorRgb>,
1044    /// Badge diameter as a multiple of the marker font size.
1045    pub badge_scale: f32,
1046    /// Font families for this element, in fallback order. Empty means
1047    /// "inherit the document body families" (`body_font_families`, or
1048    /// the bundled Noto defaults when that is also empty). Names must
1049    /// be families the font collection knows — either system-installed
1050    /// or exposed by a file listed in `font_paths`.
1051    ///
1052    /// Note this REPLACES the body list rather than extending it, so a
1053    /// Latin-only face here will lose the multi-script fallbacks. List
1054    /// the scripts you need explicitly if the document is not Latin-only.
1055    pub font_families: Vec<String>,
1056}
1057
1058impl Default for ListMarkerStyle {
1059    fn default() -> Self {
1060        Self {
1061            font_families: Vec::new(),
1062            ordered_sequences: Vec::new(),
1063            badge: false,
1064            badge_fill: ColorRgb::new(223, 227, 232),
1065            badge_text_color: None,
1066            badge_scale: 1.7,
1067        }
1068    }
1069}
1070
1071impl ListMarkerStyle {
1072    /// The numbering style to use at the given nesting depth (0 = the
1073    /// outermost ordered list).
1074    pub fn sequence_for_depth(&self, depth: usize) -> MarkerSequence {
1075        if self.ordered_sequences.is_empty() {
1076            MarkerSequence::Decimal
1077        } else {
1078            self.ordered_sequences[depth % self.ordered_sequences.len()]
1079        }
1080    }
1081}
1082
1083/// Word-hyphenation settings. When `enabled`, the renderer pre-walks
1084/// body text and inserts soft hyphens (U+00AD) at every Knuth–Liang
1085/// hyphenation point for the configured language. parley breaks lines
1086/// at those points when needed and the hyphens stay invisible
1087/// otherwise.
1088///
1089/// Only English-US is bundled by default — other languages need a
1090/// `.bincode` pattern file built with the `hyphenation` crate's
1091/// `build_dictionaries` feature, supplied via `dictionary_path`.
1092#[derive(Debug, Clone, Deserialize)]
1093#[serde(default, deny_unknown_fields)]
1094pub struct HyphenationStyle {
1095    pub enabled: bool,
1096    /// Language tag (e.g. `"en-us"`). The bundled tag is `"en-us"`;
1097    /// other languages need `dictionary_path`.
1098    pub language: String,
1099    /// Don't hyphenate words shorter than this. Defaults to 5.
1100    pub min_word_chars: u8,
1101    /// Optional path to a `.bincode` hyphenation pattern file (built
1102    /// from the upstream `hyphenation` repo). Required when
1103    /// `language` isn't the bundled `"en-us"`.
1104    pub dictionary_path: Option<String>,
1105}
1106
1107impl Default for HyphenationStyle {
1108    fn default() -> Self {
1109        Self {
1110            enabled: false,
1111            language: "en-us".to_string(),
1112            min_word_chars: 5,
1113            dictionary_path: None,
1114        }
1115    }
1116}
1117
1118/// Per-page footnote pool styling.
1119#[derive(Debug, Clone, Deserialize)]
1120#[serde(default, deny_unknown_fields)]
1121pub struct FootnoteStyle {
1122    /// Body font size for footnote entries (typically smaller than
1123    /// body text — e.g. 9pt against an 11pt body).
1124    pub font_size: f32,
1125    /// Line height (em multiplier) for footnote entries.
1126    pub line_height: f32,
1127    /// Vertical gap between consecutive footnote entries on the page.
1128    pub entry_space_after: f32,
1129    /// Vertical gap between body content and the separator rule.
1130    pub gap_above: f32,
1131    /// Vertical gap between the separator rule and the first entry.
1132    pub gap_below_rule: f32,
1133    /// Width of the separator rule, expressed as a fraction of the
1134    /// printable column width (0.0–1.0). Use 1.0 for a full-width
1135    /// rule, 0.3 for a short academic-style separator.
1136    pub rule_width_frac: f32,
1137    /// Stroke thickness for the separator rule.
1138    pub rule_thickness: f32,
1139    pub rule_color: ColorRgb,
1140    pub text_color: ColorRgb,
1141    /// Font families for this element, in fallback order. Empty means
1142    /// "inherit the document body families" (`body_font_families`, or
1143    /// the bundled Noto defaults when that is also empty). Names must
1144    /// be families the font collection knows — either system-installed
1145    /// or exposed by a file listed in `font_paths`.
1146    ///
1147    /// Note this REPLACES the body list rather than extending it, so a
1148    /// Latin-only face here will lose the multi-script fallbacks. List
1149    /// the scripts you need explicitly if the document is not Latin-only.
1150    pub font_families: Vec<String>,
1151}
1152
1153impl Default for FootnoteStyle {
1154    fn default() -> Self {
1155        Self {
1156            font_families: Vec::new(),
1157            font_size: 9.0,
1158            line_height: 1.35,
1159            entry_space_after: 3.0,
1160            gap_above: 12.0,
1161            gap_below_rule: 6.0,
1162            rule_width_frac: 0.3,
1163            rule_thickness: 0.5,
1164            rule_color: ColorRgb::new(150, 155, 165),
1165            text_color: ColorRgb::new(70, 80, 95),
1166        }
1167    }
1168}
1169
1170/// Table of contents — generated from the document's heading outline.
1171/// Disabled by default. When enabled, the TOC pages are inserted at
1172/// `position` and each entry links to its target heading via PDF
1173/// internal destinations (powered by the same anchor mechanism that
1174/// `{% tagref %}` uses, with synthetic anchor ids assigned to every
1175/// heading).
1176#[derive(Debug, Clone, Deserialize)]
1177#[serde(default, deny_unknown_fields)]
1178pub struct TocStyle {
1179    pub enabled: bool,
1180    pub position: TocPosition,
1181    /// Title to render at the top of the TOC (e.g. "Table of Contents").
1182    pub title: String,
1183    /// Font size for the TOC's title heading.
1184    pub title_font_size: f32,
1185    /// Font size for individual entries.
1186    pub entry_font_size: f32,
1187    /// Vertical gap after each entry.
1188    pub entry_space_after: f32,
1189    /// Horizontal indent applied per heading-level depth.
1190    pub entry_indent_per_level: f32,
1191    /// Maximum heading level included (1 = h1 only, 6 = all).
1192    pub max_depth: u8,
1193    /// Font families for this element, in fallback order. Empty means
1194    /// "inherit the document body families" (`body_font_families`, or
1195    /// the bundled Noto defaults when that is also empty). Names must
1196    /// be families the font collection knows — either system-installed
1197    /// or exposed by a file listed in `font_paths`.
1198    ///
1199    /// Note this REPLACES the body list rather than extending it, so a
1200    /// Latin-only face here will lose the multi-script fallbacks. List
1201    /// the scripts you need explicitly if the document is not Latin-only.
1202    pub font_families: Vec<String>,
1203}
1204
1205impl Default for TocStyle {
1206    fn default() -> Self {
1207        Self {
1208            font_families: Vec::new(),
1209            enabled: false,
1210            position: TocPosition::Start,
1211            title: "Table of Contents".to_string(),
1212            title_font_size: 24.0,
1213            entry_font_size: 11.0,
1214            entry_space_after: 4.0,
1215            entry_indent_per_level: 16.0,
1216            max_depth: 3,
1217        }
1218    }
1219}
1220
1221#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1222#[serde(rename_all = "snake_case")]
1223pub enum TocPosition {
1224    #[default]
1225    Start,
1226    End,
1227}
1228
1229/// Where the visual caption block sits relative to its figure or table.
1230/// Applies to both `{% caption %}`-attached and alt-derived captions.
1231#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1232#[serde(rename_all = "snake_case")]
1233pub enum CaptionPosition {
1234    #[default]
1235    Above,
1236    Below,
1237}
1238
1239/// Strategy for sizing table columns.
1240///
1241/// - `Auto`: measure each cell's natural width and longest-word width,
1242///   distribute the available column space proportionally between them.
1243///   Compact tables stay narrow; wide tables fill the column.
1244/// - `Equal`: every column gets `available_width / num_cols` (the
1245///   pre-auto behaviour). Predictable but wastes space on tables with
1246///   short columns.
1247#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1248#[serde(rename_all = "snake_case")]
1249pub enum TableColumnSizing {
1250    #[default]
1251    Auto,
1252    Equal,
1253}
1254
1255/// Which rules a table draws.
1256#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1257#[serde(rename_all = "snake_case")]
1258pub enum TableBorders {
1259    /// Full grid — outer box plus every row and column separator (the
1260    /// default).
1261    #[default]
1262    Grid,
1263    /// Horizontal row separators only; no verticals or outer box. The
1264    /// clean "ruled" look for key-value / metadata tables.
1265    Horizontal,
1266    /// No rules at all — cells are separated by whitespace (and the
1267    /// optional header fill) only.
1268    None,
1269}
1270
1271/// Generic auto-generated list section: List of Figures, List of
1272/// Tables. Same shape as a TOC but flat (no level indenting). The
1273/// `title` field is optional so callers can omit it from TOML and let
1274/// the renderer pick a sensible default per section ("List of Figures"
1275/// for `lof`, "List of Tables" for `lot`).
1276#[derive(Debug, Clone, Default, Deserialize)]
1277#[serde(default, deny_unknown_fields)]
1278pub struct ListSectionStyle {
1279    pub enabled: bool,
1280    pub position: TocPosition,
1281    pub title: Option<String>,
1282    #[serde(default = "default_list_title_size")]
1283    pub title_font_size: f32,
1284    #[serde(default = "default_list_entry_size")]
1285    pub entry_font_size: f32,
1286    #[serde(default = "default_list_entry_space_after")]
1287    pub entry_space_after: f32,
1288    /// Font families for this element, in fallback order. Empty means
1289    /// "inherit the document body families" (`body_font_families`, or
1290    /// the bundled Noto defaults when that is also empty). Names must
1291    /// be families the font collection knows — either system-installed
1292    /// or exposed by a file listed in `font_paths`.
1293    ///
1294    /// Note this REPLACES the body list rather than extending it, so a
1295    /// Latin-only face here will lose the multi-script fallbacks. List
1296    /// the scripts you need explicitly if the document is not Latin-only.
1297    pub font_families: Vec<String>,
1298}
1299
1300fn default_list_title_size() -> f32 {
1301    24.0
1302}
1303fn default_list_entry_size() -> f32 {
1304    11.0
1305}
1306fn default_list_entry_space_after() -> f32 {
1307    4.0
1308}
1309
1310impl ListSectionStyle {
1311    /// Title to display, falling back to the supplied default when
1312    /// the caller didn't override it.
1313    pub fn resolved_title<'a>(&'a self, fallback: &'a str) -> &'a str {
1314        self.title.as_deref().unwrap_or(fallback)
1315    }
1316}
1317
1318/// PDF export profile — selects the krilla validator and provides
1319/// document-metadata defaults that the renderer applies via `RenderContext`.
1320///
1321/// PDF/A profiles require certain compliance items (embedded subset fonts,
1322/// ToUnicode CMaps, document metadata). krilla handles the technical
1323/// compliance automatically; the caller's only job is to provide title,
1324/// language, and creator strings via `RenderContext` (the bin pulls these
1325/// from the document's frontmatter).
1326#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
1327#[serde(rename_all = "snake_case")]
1328pub enum PdfExportProfile {
1329    /// Plain PDF, no validator. Smallest file size; no compliance guarantees.
1330    #[default]
1331    None,
1332    /// PDF/A-1b — long-term archival, level B (basic visual reproduction).
1333    A1B,
1334    /// PDF/A-2b — extends A-1b with JPEG 2000, transparency, and more.
1335    A2B,
1336    /// PDF/A-3b — like A-2b but allows arbitrary embedded files.
1337    A3B,
1338    /// PDF/A-4 — the modern archival profile (PDF 2.0 base).
1339    A4,
1340    /// PDF/UA-1 — universal accessibility. Requires tagged PDF (deferred).
1341    UA1,
1342}
1343
1344/// Page-level header/footer decoration. Both are optional — by default
1345/// no decoration is drawn, matching the previous behaviour.
1346///
1347/// Template strings support these variables:
1348///   - `{page}`    — current page number, 1-indexed
1349///   - `{total}`   — total page count
1350///   - `{title}`   — document title (set via `Style::with_title()` at runtime)
1351///   - `{chapter}` — most recent h1 heading text on or before this page
1352#[derive(Debug, Clone, Default, Deserialize)]
1353#[serde(default, deny_unknown_fields)]
1354pub struct PageDecorationStyle {
1355    pub header: Option<HeaderFooterStyle>,
1356    pub footer: Option<HeaderFooterStyle>,
1357    /// Optional rich "banner" drawn at the top of every page above the
1358    /// body — a taller masthead than the 3-slot header, for bulletin /
1359    /// notice documents. Reserves its `height` so the body starts below
1360    /// it. See [`NoticeBanner`].
1361    pub banner: Option<NoticeBanner>,
1362    /// If true, the first page is rendered without header/footer (useful
1363    /// when the first page is a title or cover page).
1364    pub skip_first_page: bool,
1365    /// Optional QR-code stamp on the last content page — the printed-guide
1366    /// pattern where production scans a small code (encoding the document
1367    /// number) when packing. Drawn in the bottom-right corner above its
1368    /// human-readable label. See [`LastPageQr`].
1369    pub last_page_qr: Option<LastPageQr>,
1370}
1371
1372/// A small QR code stamped in a bottom corner of the last page (per `align`)
1373/// that carries content, above a human-readable label. `value` and `label` are
1374/// templates (default `"{documentNumber}"`, resolved against the document's
1375/// frontmatter and the usual `{page}`/`{title}`/… tokens); a `value` that
1376/// doesn't resolve (no such field) skips the stamp entirely, and an empty
1377/// resolved `label` hides the caption. A field whose value is one of
1378/// `missing_values` counts as not set.
1379#[derive(Debug, Clone, Deserialize)]
1380#[serde(default, deny_unknown_fields)]
1381pub struct LastPageQr {
1382    /// Template for the data encoded in the code.
1383    pub value: String,
1384    /// Template for the caption drawn beneath the code (empty hides it).
1385    pub label: String,
1386    /// Values that mean a field is not set, such as a document number of
1387    /// `0` until one is assigned. A `{token}` holding one counts as
1388    /// unresolved: in `value` it skips the stamp, in `label` it hides the
1389    /// caption. Matched against the token's whole value, trimmed, ignoring
1390    /// case. Empty (the default) treats every value as real.
1391    pub missing_values: Vec<String>,
1392    /// Rendered side length of the code, in points.
1393    pub size: f32,
1394    /// Error-correction level: `low` | `medium` | `quartile` | `high`.
1395    pub ecl: String,
1396    /// Horizontal placement on the page: `left` | `center` | `right`
1397    /// (default). `left`/`right` are inset by `margin_left` / `margin_right`;
1398    /// `center` ignores both and sits the code on the page centre-line.
1399    pub align: String,
1400    /// Gap from the page's left edge to the code's left edge, in points
1401    /// (used when `align = "left"`).
1402    pub margin_left: f32,
1403    /// Gap from the page's right edge to the code's right edge, in points
1404    /// (used when `align = "right"`, the default).
1405    pub margin_right: f32,
1406    /// Gap from the page's bottom edge to the caption's bottom, in points —
1407    /// set this larger than the footer band so the stamp clears it.
1408    pub margin_bottom: f32,
1409    /// Module (foreground) colour; the field stays white.
1410    pub color: ColorRgb,
1411    /// Font size of the caption.
1412    pub label_font_size: f32,
1413    /// When the document pads to an even page count, place the stamp on the
1414    /// physical last page — the blank duplex-padding page — instead of the
1415    /// last page carrying body content. Off by default (the stamp avoids the
1416    /// blank filler). No effect when there is no padding page.
1417    pub include_padding_page: bool,
1418    /// Font families for this element, in fallback order. Empty means
1419    /// "inherit the document body families" (`body_font_families`, or
1420    /// the bundled Noto defaults when that is also empty). Names must
1421    /// be families the font collection knows — either system-installed
1422    /// or exposed by a file listed in `font_paths`.
1423    ///
1424    /// Note this REPLACES the body list rather than extending it, so a
1425    /// Latin-only face here will lose the multi-script fallbacks. List
1426    /// the scripts you need explicitly if the document is not Latin-only.
1427    pub font_families: Vec<String>,
1428}
1429
1430impl Default for LastPageQr {
1431    fn default() -> Self {
1432        Self {
1433            font_families: Vec::new(),
1434            value: "{documentNumber}".to_string(),
1435            label: "{documentNumber}".to_string(),
1436            missing_values: Vec::new(),
1437            size: 54.0,
1438            ecl: "medium".to_string(),
1439            align: "right".to_string(),
1440            margin_left: 40.0,
1441            margin_right: 40.0,
1442            margin_bottom: 48.0,
1443            color: ColorRgb::new(0, 0, 0),
1444            label_font_size: 8.0,
1445            include_padding_page: false,
1446        }
1447    }
1448}
1449
1450impl LastPageQr {
1451    /// Whether `value` is one of [`missing_values`](Self::missing_values):
1452    /// equal to one of them once both are trimmed, ignoring case.
1453    pub fn is_missing(&self, value: &str) -> bool {
1454        let value = value.trim().to_lowercase();
1455        self.missing_values
1456            .iter()
1457            .any(|missing| missing.trim().to_lowercase() == value)
1458    }
1459}
1460
1461/// A masthead drawn at the top of every page: a logo (with an optional
1462/// subtitle beneath it) on the left, a wrapping disclaimer paragraph
1463/// below them, an icon on the right whose label is centred beneath it
1464/// just above an optional note line + full-width rule closing the band.
1465///
1466/// All text fields are templates (`{title}` / `{date}` / `{language}` /
1467/// any `RenderContext` var). Every piece is optional; an empty field is
1468/// simply skipped. The band reserves `height` points at the top of the
1469/// page so body content never collides with it.
1470#[derive(Debug, Clone, Deserialize)]
1471#[serde(default, deny_unknown_fields)]
1472pub struct NoticeBanner {
1473    /// Reserved vertical space (pt) from the page top.
1474    pub height: f32,
1475    /// Left masthead logo.
1476    pub logo: Option<LogoSpec>,
1477    /// Small line drawn directly under the logo (e.g. a company name).
1478    pub logo_subtitle: String,
1479    pub logo_subtitle_color: ColorRgb,
1480    pub logo_subtitle_font_size: f32,
1481    /// Wrapping disclaimer paragraph, below the logo block.
1482    pub disclaimer: String,
1483    pub disclaimer_color: ColorRgb,
1484    pub disclaimer_font_size: f32,
1485    /// Max lines the disclaimer may wrap into (reserves no extra space;
1486    /// the band `height` governs layout).
1487    pub disclaimer_max_lines: u8,
1488    /// Right-side icon (e.g. a warning triangle).
1489    pub icon: Option<LogoSpec>,
1490    /// Label centred under the icon, just above the closing rule (e.g.
1491    /// `"Safety Notice"`).
1492    pub label: String,
1493    pub label_color: ColorRgb,
1494    pub label_font_size: f32,
1495    /// A note line near the band's bottom (e.g.
1496    /// `"Original language: {language}"`).
1497    pub note: String,
1498    pub note_color: ColorRgb,
1499    pub note_font_size: f32,
1500    /// Full-width rule closing the band (above the body).
1501    pub rule: bool,
1502    pub rule_color: ColorRgb,
1503    pub rule_thickness: f32,
1504    /// Font families for this element, in fallback order. Empty means
1505    /// "inherit the document body families" (`body_font_families`, or
1506    /// the bundled Noto defaults when that is also empty). Names must
1507    /// be families the font collection knows — either system-installed
1508    /// or exposed by a file listed in `font_paths`.
1509    ///
1510    /// Note this REPLACES the body list rather than extending it, so a
1511    /// Latin-only face here will lose the multi-script fallbacks. List
1512    /// the scripts you need explicitly if the document is not Latin-only.
1513    pub font_families: Vec<String>,
1514}
1515
1516impl Default for NoticeBanner {
1517    fn default() -> Self {
1518        Self {
1519            font_families: Vec::new(),
1520            height: 100.0,
1521            logo: None,
1522            logo_subtitle: String::new(),
1523            logo_subtitle_color: ColorRgb::new(140, 145, 150),
1524            logo_subtitle_font_size: 6.0,
1525            disclaimer: String::new(),
1526            disclaimer_color: ColorRgb::new(150, 155, 160),
1527            disclaimer_font_size: 8.0,
1528            disclaimer_max_lines: 3,
1529            icon: None,
1530            label: String::new(),
1531            label_color: ColorRgb::new(20, 20, 20),
1532            label_font_size: 11.0,
1533            note: String::new(),
1534            note_color: ColorRgb::new(60, 60, 60),
1535            note_font_size: 8.5,
1536            rule: true,
1537            rule_color: ColorRgb::new(180, 185, 190),
1538            rule_thickness: 0.6,
1539        }
1540    }
1541}
1542
1543#[derive(Debug, Clone, Deserialize)]
1544#[serde(default, deny_unknown_fields)]
1545pub struct HeaderFooterStyle {
1546    pub left: String,
1547    pub center: String,
1548    pub right: String,
1549    pub font_size: f32,
1550    pub color: ColorRgb,
1551    /// Distance from the page edge (top edge for header, bottom edge for footer).
1552    pub margin_from_edge: f32,
1553    /// If true, draws a thin separator rule between the decoration and
1554    /// the body (under a header, above a footer).
1555    pub rule: bool,
1556    pub rule_color: ColorRgb,
1557    pub rule_thickness: f32,
1558    /// Vertical gap between the text and the rule (when `rule = true`).
1559    pub rule_gap: f32,
1560    /// Maximum number of text lines a slot is allowed to wrap into.
1561    /// Pagination reserves vertical space for this many lines so the
1562    /// body never collides with a multi-line band. Defaults to 1.
1563    pub max_lines: u8,
1564    /// Optional logo image for each slot. When set, the logo replaces
1565    /// any text template for that slot. Sized exactly as configured —
1566    /// no automatic scaling; pick `width` and `height` to match your
1567    /// reserved band height.
1568    pub logo_left: Option<LogoSpec>,
1569    pub logo_center: Option<LogoSpec>,
1570    pub logo_right: Option<LogoSpec>,
1571    /// Optional even-page (verso) slot overrides. Page 1 is treated
1572    /// as recto (odd). When set and the current page is even, the
1573    /// corresponding slot template is used in place of the odd
1574    /// counterpart — typical book layout has e.g. chapter title on
1575    /// recto, document title on verso. Empty strings mean "fall back
1576    /// to the odd slot".
1577    pub even: Option<HeaderFooterSlots>,
1578    /// Per-h1-chapter slot overrides. Keyed by exact h1 text; the
1579    /// renderer switches as soon as a heading at that level is seen
1580    /// on the page, so the same page never mixes two chapters'
1581    /// headers. Empty string slots fall back to the parent.
1582    pub per_chapter: HashMap<String, HeaderFooterSlots>,
1583    /// Font families for this element, in fallback order. Empty means
1584    /// "inherit the document body families" (`body_font_families`, or
1585    /// the bundled Noto defaults when that is also empty). Names must
1586    /// be families the font collection knows — either system-installed
1587    /// or exposed by a file listed in `font_paths`.
1588    ///
1589    /// Note this REPLACES the body list rather than extending it, so a
1590    /// Latin-only face here will lose the multi-script fallbacks. List
1591    /// the scripts you need explicitly if the document is not Latin-only.
1592    pub font_families: Vec<String>,
1593}
1594
1595/// Just the three slot templates — used for even-page variants and
1596/// per-chapter overrides. Empty fields fall back to the parent
1597/// `HeaderFooterStyle`'s slot.
1598#[derive(Debug, Clone, Default, Deserialize)]
1599#[serde(default, deny_unknown_fields)]
1600pub struct HeaderFooterSlots {
1601    pub left: String,
1602    pub center: String,
1603    pub right: String,
1604}
1605
1606/// A header/footer logo: an asset URI plus the rendered display size
1607/// in PDF points. The renderer decodes the asset once per document
1608/// and caches the result by URI, so repeating the same logo across
1609/// pages costs the same as decoding it for one page.
1610#[derive(Debug, Clone, Deserialize)]
1611#[serde(default, deny_unknown_fields)]
1612pub struct LogoSpec {
1613    /// Asset-library GUID (file stem), same contract as `{% media id="…" /%}`.
1614    /// Template-substituted like `src`. Tried before `src`; probes
1615    /// `{id}.webp` / `.png` / … then `AssetResolver::resolve_id`.
1616    pub id: String,
1617    /// Asset URI — anything the configured asset resolver understands
1618    /// (`file://path`, relative path, `https://…`, `asset://…`). A bare
1619    /// GUID with no extension is treated as an `id`. Cover-page `src` is
1620    /// a template (`{title}`, `{coverImage}`, …).
1621    pub src: String,
1622    pub width: f32,
1623    pub height: f32,
1624    /// Gap between the logo and the slot's text when both are present.
1625    /// Only effective for the LEFT and RIGHT slots — CENTER slot
1626    /// remains logo-or-text. Defaults to 6 pt.
1627    pub gap: f32,
1628}
1629
1630impl Default for LogoSpec {
1631    fn default() -> Self {
1632        Self {
1633            id: String::new(),
1634            src: String::new(),
1635            width: 0.0,
1636            height: 0.0,
1637            gap: 6.0,
1638        }
1639    }
1640}
1641
1642impl Default for HeaderFooterStyle {
1643    fn default() -> Self {
1644        Self {
1645            font_families: Vec::new(),
1646            left: String::new(),
1647            center: String::new(),
1648            right: String::new(),
1649            font_size: 9.0,
1650            color: ColorRgb::new(110, 120, 130),
1651            margin_from_edge: 36.0,
1652            rule: false,
1653            rule_color: ColorRgb::new(220, 225, 230),
1654            rule_thickness: 0.5,
1655            rule_gap: 4.0,
1656            max_lines: 1,
1657            logo_left: None,
1658            logo_center: None,
1659            logo_right: None,
1660            even: None,
1661            per_chapter: HashMap::new(),
1662        }
1663    }
1664}
1665
1666impl HeaderFooterStyle {
1667    /// Resolve the `(left, center, right)` slot strings effective for
1668    /// this page given its parity and current chapter. Per-chapter
1669    /// overrides take precedence; even-page overrides apply next;
1670    /// missing/empty fields fall back to the parent slot.
1671    pub fn resolved_slots(&self, page_number: usize, chapter: &str) -> (String, String, String) {
1672        let mut left = self.left.clone();
1673        let mut center = self.center.clone();
1674        let mut right = self.right.clone();
1675        if page_number.is_multiple_of(2)
1676            && let Some(e) = &self.even
1677        {
1678            if !e.left.is_empty() {
1679                left = e.left.clone();
1680            }
1681            if !e.center.is_empty() {
1682                center = e.center.clone();
1683            }
1684            if !e.right.is_empty() {
1685                right = e.right.clone();
1686            }
1687        }
1688        if !chapter.is_empty()
1689            && let Some(c) = self.per_chapter.get(chapter)
1690        {
1691            if !c.left.is_empty() {
1692                left = c.left.clone();
1693            }
1694            if !c.center.is_empty() {
1695                center = c.center.clone();
1696            }
1697            if !c.right.is_empty() {
1698                right = c.right.clone();
1699            }
1700        }
1701        (left, center, right)
1702    }
1703}
1704
1705impl HeaderFooterStyle {
1706    /// Total vertical space this decoration consumes from one edge of
1707    /// the page (text height × max_lines + rule gap + rule thickness).
1708    pub fn reserved_height(&self) -> f32 {
1709        let lines = self.max_lines.max(1) as f32;
1710        let text = self.font_size * 1.2 * lines;
1711        let rule = if self.rule {
1712            self.rule_gap + self.rule_thickness
1713        } else {
1714            0.0
1715        };
1716        text + rule
1717    }
1718}
1719
1720impl Style {
1721    pub fn from_toml_str(s: &str) -> Result<Self, toml::de::Error> {
1722        toml::from_str(s)
1723    }
1724
1725    pub fn from_toml_file(path: impl AsRef<std::path::Path>) -> Result<Self, StyleLoadError> {
1726        let text = std::fs::read_to_string(path).map_err(StyleLoadError::Io)?;
1727        Self::from_toml_str(&text).map_err(StyleLoadError::Toml)
1728    }
1729
1730    /// Page-count multiple used for trailing blank pages. `pad_to_multiple`
1731    /// wins when it is greater than 1; otherwise `pad_to_even` means 2.
1732    pub fn padding_multiple(&self) -> usize {
1733        if self.pad_to_multiple > 1 {
1734            self.pad_to_multiple as usize
1735        } else if self.pad_to_even {
1736            2
1737        } else {
1738            0
1739        }
1740    }
1741}
1742
1743#[derive(Debug, thiserror::Error)]
1744pub enum StyleLoadError {
1745    #[error("failed to read style file: {0}")]
1746    Io(std::io::Error),
1747    #[error("failed to parse style TOML: {0}")]
1748    Toml(toml::de::Error),
1749}
1750
1751#[cfg(test)]
1752mod tests {
1753    use super::*;
1754
1755    #[test]
1756    fn default_loads() {
1757        let s = Style::default();
1758        assert_eq!(s.page_width, 595.0);
1759        assert_eq!(s.heading.h1.font_size, 26.0);
1760    }
1761
1762    #[test]
1763    fn frontmatter_tables_are_none_unless_a_style_names_them() {
1764        assert!(Style::default().frontmatter_tables.is_empty());
1765        assert!(
1766            Style::from_toml_str("page_width = 612.0\n")
1767                .unwrap()
1768                .frontmatter_tables
1769                .is_empty()
1770        );
1771    }
1772
1773    #[test]
1774    fn frontmatter_tables_load_by_tag_name() {
1775        let s = Style::from_toml_str(
1776            r#"
1777[frontmatter_tables.changes]
1778key = "changeLog"
1779heading = "Changes"
1780columns = [{ field = "when", header = "When" }, { field = "what", header = "What" }]
1781
1782[frontmatter_tables.people]
1783key = "contributors"
1784columns = [{ field = "name", header = "Name" }]
1785"#,
1786        )
1787        .unwrap();
1788        assert_eq!(
1789            s.frontmatter_tables["changes"],
1790            FrontmatterTable {
1791                key: "changeLog".into(),
1792                heading: Some("Changes".into()),
1793                columns: vec![
1794                    FrontmatterColumn {
1795                        field: "when".into(),
1796                        header: "When".into(),
1797                    },
1798                    FrontmatterColumn {
1799                        field: "what".into(),
1800                        header: "What".into(),
1801                    },
1802                ],
1803            }
1804        );
1805        assert_eq!(s.frontmatter_tables["people"].heading, None);
1806        assert_eq!(s.frontmatter_tables.len(), 2);
1807    }
1808
1809    #[test]
1810    fn a_frontmatter_table_needs_its_key_and_columns_and_nothing_else() {
1811        for toml in [
1812            "[frontmatter_tables.t]\ncolumns = []\n",
1813            "[frontmatter_tables.t]\nkey = \"k\"\n",
1814            "[frontmatter_tables.t]\nkey = \"k\"\ncolumns = []\nlevel = 3\n",
1815            "[frontmatter_tables.t]\nkey = \"k\"\ncolumns = [{ field = \"f\" }]\n",
1816        ] {
1817            assert!(Style::from_toml_str(toml).is_err(), "{toml}");
1818        }
1819    }
1820
1821    #[test]
1822    fn partial_toml_overrides_only_specified_fields() {
1823        let toml = r#"
1824page_width = 612.0
1825page_height = 792.0
1826margin_x = 54.0
1827"#;
1828        let s = Style::from_toml_str(toml).unwrap();
1829        // Letter-paper overrides applied.
1830        assert_eq!(s.page_width, 612.0);
1831        assert_eq!(s.page_height, 792.0);
1832        assert_eq!(s.margin_x, 54.0);
1833        // Untouched fields keep defaults.
1834        assert_eq!(s.body_font_size, 11.0);
1835        assert_eq!(s.heading.h1.font_size, 26.0);
1836        assert_eq!(
1837            s.callout_styles.warning.background,
1838            ColorRgb::new(255, 247, 230)
1839        );
1840    }
1841
1842    #[test]
1843    fn nested_overrides_work() {
1844        let toml = r#"
1845[heading.h1]
1846font_size = 32.0
1847"#;
1848        let s = Style::from_toml_str(toml).unwrap();
1849        assert_eq!(s.heading.h1.font_size, 32.0);
1850        // Other heading levels keep defaults.
1851        assert_eq!(s.heading.h2.font_size, 21.0);
1852    }
1853
1854    #[test]
1855    fn table_borders_default_and_override() {
1856        // Defaults to a full grid.
1857        assert_eq!(Style::default().table_borders, TableBorders::Grid);
1858        // snake_case values parse from a top-level key.
1859        let horizontal = Style::from_toml_str("table_borders = \"horizontal\"").unwrap();
1860        assert_eq!(horizontal.table_borders, TableBorders::Horizontal);
1861        let none = Style::from_toml_str("table_borders = \"none\"").unwrap();
1862        assert_eq!(none.table_borders, TableBorders::None);
1863    }
1864
1865    #[test]
1866    fn text_align_defaults_left_and_parses() {
1867        assert_eq!(Style::default().text_align, TextAlign::Left);
1868        assert_eq!(
1869            Style::from_toml_str("text_align = \"justify\"")
1870                .unwrap()
1871                .text_align,
1872            TextAlign::Justify
1873        );
1874        assert_eq!(
1875            TextAlign::Justify.to_parley(),
1876            parley::layout::Alignment::Justify
1877        );
1878    }
1879
1880    #[test]
1881    fn table_edge_color_optional() {
1882        // Unset by default — edges match the internal border colour.
1883        let d = Style::default();
1884        assert!(d.table_edge_color.is_none());
1885        assert!(d.table_edge_thickness.is_none());
1886        // A darker, thicker edge (booktabs look) parses.
1887        let s = Style::from_toml_str("table_edge_color = [0, 0, 0]\ntable_edge_thickness = 1.0")
1888            .unwrap();
1889        assert_eq!(s.table_edge_color, Some(ColorRgb::new(0, 0, 0)));
1890        assert_eq!(s.table_edge_thickness, Some(1.0));
1891    }
1892
1893    #[test]
1894    fn list_marker_badge_and_sequences() {
1895        // Defaults: no badge, decimal at every depth.
1896        let d = Style::default().list_marker;
1897        assert!(!d.badge);
1898        assert_eq!(d.sequence_for_depth(0), MarkerSequence::Decimal);
1899        assert_eq!(d.sequence_for_depth(3), MarkerSequence::Decimal);
1900
1901        let toml = r#"
1902[list_marker]
1903badge = true
1904ordered_sequences = ["decimal", "lower-alpha", "lower-roman"]
1905badge_fill = [223, 227, 232]
1906"#;
1907        let lm = Style::from_toml_str(toml).unwrap().list_marker;
1908        assert!(lm.badge);
1909        assert_eq!(lm.badge_fill, ColorRgb::new(223, 227, 232));
1910        // Depth cycles through the configured sequence and wraps.
1911        assert_eq!(lm.sequence_for_depth(0), MarkerSequence::Decimal);
1912        assert_eq!(lm.sequence_for_depth(1), MarkerSequence::LowerAlpha);
1913        assert_eq!(lm.sequence_for_depth(2), MarkerSequence::LowerRoman);
1914        assert_eq!(lm.sequence_for_depth(3), MarkerSequence::Decimal);
1915    }
1916
1917    #[test]
1918    fn callout_kind_lookup() {
1919        let s = Style::default();
1920        assert_eq!(
1921            s.callout_styles.for_kind("warning").background,
1922            ColorRgb::new(255, 247, 230)
1923        );
1924        assert_eq!(
1925            s.callout_styles.for_kind("info").background,
1926            ColorRgb::new(232, 244, 253)
1927        );
1928        // Unknown kind falls back to note.
1929        assert_eq!(
1930            s.callout_styles.for_kind("unknown").background,
1931            s.callout_styles.note.background
1932        );
1933    }
1934
1935    #[test]
1936    fn coverpage_hero_deserializes_without_explicit_size() {
1937        let toml = r#"
1938[coverpage.hero]
1939id = "{coverImage}"
1940src = "{title}.png"
1941"#;
1942        let s = Style::from_toml_str(toml).unwrap();
1943        let hero = s.coverpage.hero.expect("hero slot");
1944        assert_eq!(hero.id, "{coverImage}");
1945        assert_eq!(hero.src, "{title}.png");
1946        assert_eq!(hero.width, 0.0);
1947        assert_eq!(hero.height, 0.0);
1948    }
1949
1950    #[test]
1951    fn last_page_qr_missing_values_default_to_none() {
1952        let qr = Style::from_toml_str("[page_decoration.last_page_qr]\n")
1953            .unwrap()
1954            .page_decoration
1955            .last_page_qr
1956            .expect("the table enables the stamp");
1957        assert!(qr.missing_values.is_empty());
1958        assert!(!qr.is_missing("0"));
1959        assert!(!qr.is_missing(""));
1960    }
1961
1962    #[test]
1963    fn last_page_qr_missing_values_trim_and_ignore_case() {
1964        let qr = Style::from_toml_str(
1965            "[page_decoration.last_page_qr]\nmissing_values = [\"0\", \"n/a\", \" TBD \"]\n",
1966        )
1967        .unwrap()
1968        .page_decoration
1969        .last_page_qr
1970        .expect("the table enables the stamp");
1971        assert_eq!(qr.missing_values, ["0", "n/a", " TBD "]);
1972        for value in ["0", " 0 ", "n/a", "N/A", " N/a\n", "tbd", "TBD"] {
1973            assert!(qr.is_missing(value), "{value:?} should be missing");
1974        }
1975        // Otherwise the whole value has to match: no prefixes, no numeric
1976        // equality, no item of a list.
1977        for value in ["00", "0.0", "10", "n/a2", "0, 1234567", "1234567", ""] {
1978            assert!(!qr.is_missing(value), "{value:?} should be a real value");
1979        }
1980    }
1981}