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 ``) 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.
1378#[derive(Debug, Clone, Deserialize)]
1379#[serde(default, deny_unknown_fields)]
1380pub struct LastPageQr {
1381 /// Template for the data encoded in the code.
1382 pub value: String,
1383 /// Template for the caption drawn beneath the code (empty hides it).
1384 pub label: String,
1385 /// Rendered side length of the code, in points.
1386 pub size: f32,
1387 /// Error-correction level: `low` | `medium` | `quartile` | `high`.
1388 pub ecl: String,
1389 /// Horizontal placement on the page: `left` | `center` | `right`
1390 /// (default). `left`/`right` are inset by `margin_left` / `margin_right`;
1391 /// `center` ignores both and sits the code on the page centre-line.
1392 pub align: String,
1393 /// Gap from the page's left edge to the code's left edge, in points
1394 /// (used when `align = "left"`).
1395 pub margin_left: f32,
1396 /// Gap from the page's right edge to the code's right edge, in points
1397 /// (used when `align = "right"`, the default).
1398 pub margin_right: f32,
1399 /// Gap from the page's bottom edge to the caption's bottom, in points —
1400 /// set this larger than the footer band so the stamp clears it.
1401 pub margin_bottom: f32,
1402 /// Module (foreground) colour; the field stays white.
1403 pub color: ColorRgb,
1404 /// Font size of the caption.
1405 pub label_font_size: f32,
1406 /// When the document pads to an even page count, place the stamp on the
1407 /// physical last page — the blank duplex-padding page — instead of the
1408 /// last page carrying body content. Off by default (the stamp avoids the
1409 /// blank filler). No effect when there is no padding page.
1410 pub include_padding_page: bool,
1411 /// Font families for this element, in fallback order. Empty means
1412 /// "inherit the document body families" (`body_font_families`, or
1413 /// the bundled Noto defaults when that is also empty). Names must
1414 /// be families the font collection knows — either system-installed
1415 /// or exposed by a file listed in `font_paths`.
1416 ///
1417 /// Note this REPLACES the body list rather than extending it, so a
1418 /// Latin-only face here will lose the multi-script fallbacks. List
1419 /// the scripts you need explicitly if the document is not Latin-only.
1420 pub font_families: Vec<String>,
1421}
1422
1423impl Default for LastPageQr {
1424 fn default() -> Self {
1425 Self {
1426 font_families: Vec::new(),
1427 value: "{documentNumber}".to_string(),
1428 label: "{documentNumber}".to_string(),
1429 size: 54.0,
1430 ecl: "medium".to_string(),
1431 align: "right".to_string(),
1432 margin_left: 40.0,
1433 margin_right: 40.0,
1434 margin_bottom: 48.0,
1435 color: ColorRgb::new(0, 0, 0),
1436 label_font_size: 8.0,
1437 include_padding_page: false,
1438 }
1439 }
1440}
1441
1442/// A masthead drawn at the top of every page: a logo (with an optional
1443/// subtitle beneath it) on the left, a wrapping disclaimer paragraph
1444/// below them, an icon on the right whose label is centred beneath it
1445/// just above an optional note line + full-width rule closing the band.
1446///
1447/// All text fields are templates (`{title}` / `{date}` / `{language}` /
1448/// any `RenderContext` var). Every piece is optional; an empty field is
1449/// simply skipped. The band reserves `height` points at the top of the
1450/// page so body content never collides with it.
1451#[derive(Debug, Clone, Deserialize)]
1452#[serde(default, deny_unknown_fields)]
1453pub struct NoticeBanner {
1454 /// Reserved vertical space (pt) from the page top.
1455 pub height: f32,
1456 /// Left masthead logo.
1457 pub logo: Option<LogoSpec>,
1458 /// Small line drawn directly under the logo (e.g. a company name).
1459 pub logo_subtitle: String,
1460 pub logo_subtitle_color: ColorRgb,
1461 pub logo_subtitle_font_size: f32,
1462 /// Wrapping disclaimer paragraph, below the logo block.
1463 pub disclaimer: String,
1464 pub disclaimer_color: ColorRgb,
1465 pub disclaimer_font_size: f32,
1466 /// Max lines the disclaimer may wrap into (reserves no extra space;
1467 /// the band `height` governs layout).
1468 pub disclaimer_max_lines: u8,
1469 /// Right-side icon (e.g. a warning triangle).
1470 pub icon: Option<LogoSpec>,
1471 /// Label centred under the icon, just above the closing rule (e.g.
1472 /// `"Safety Notice"`).
1473 pub label: String,
1474 pub label_color: ColorRgb,
1475 pub label_font_size: f32,
1476 /// A note line near the band's bottom (e.g.
1477 /// `"Original language: {language}"`).
1478 pub note: String,
1479 pub note_color: ColorRgb,
1480 pub note_font_size: f32,
1481 /// Full-width rule closing the band (above the body).
1482 pub rule: bool,
1483 pub rule_color: ColorRgb,
1484 pub rule_thickness: f32,
1485 /// Font families for this element, in fallback order. Empty means
1486 /// "inherit the document body families" (`body_font_families`, or
1487 /// the bundled Noto defaults when that is also empty). Names must
1488 /// be families the font collection knows — either system-installed
1489 /// or exposed by a file listed in `font_paths`.
1490 ///
1491 /// Note this REPLACES the body list rather than extending it, so a
1492 /// Latin-only face here will lose the multi-script fallbacks. List
1493 /// the scripts you need explicitly if the document is not Latin-only.
1494 pub font_families: Vec<String>,
1495}
1496
1497impl Default for NoticeBanner {
1498 fn default() -> Self {
1499 Self {
1500 font_families: Vec::new(),
1501 height: 100.0,
1502 logo: None,
1503 logo_subtitle: String::new(),
1504 logo_subtitle_color: ColorRgb::new(140, 145, 150),
1505 logo_subtitle_font_size: 6.0,
1506 disclaimer: String::new(),
1507 disclaimer_color: ColorRgb::new(150, 155, 160),
1508 disclaimer_font_size: 8.0,
1509 disclaimer_max_lines: 3,
1510 icon: None,
1511 label: String::new(),
1512 label_color: ColorRgb::new(20, 20, 20),
1513 label_font_size: 11.0,
1514 note: String::new(),
1515 note_color: ColorRgb::new(60, 60, 60),
1516 note_font_size: 8.5,
1517 rule: true,
1518 rule_color: ColorRgb::new(180, 185, 190),
1519 rule_thickness: 0.6,
1520 }
1521 }
1522}
1523
1524#[derive(Debug, Clone, Deserialize)]
1525#[serde(default, deny_unknown_fields)]
1526pub struct HeaderFooterStyle {
1527 pub left: String,
1528 pub center: String,
1529 pub right: String,
1530 pub font_size: f32,
1531 pub color: ColorRgb,
1532 /// Distance from the page edge (top edge for header, bottom edge for footer).
1533 pub margin_from_edge: f32,
1534 /// If true, draws a thin separator rule between the decoration and
1535 /// the body (under a header, above a footer).
1536 pub rule: bool,
1537 pub rule_color: ColorRgb,
1538 pub rule_thickness: f32,
1539 /// Vertical gap between the text and the rule (when `rule = true`).
1540 pub rule_gap: f32,
1541 /// Maximum number of text lines a slot is allowed to wrap into.
1542 /// Pagination reserves vertical space for this many lines so the
1543 /// body never collides with a multi-line band. Defaults to 1.
1544 pub max_lines: u8,
1545 /// Optional logo image for each slot. When set, the logo replaces
1546 /// any text template for that slot. Sized exactly as configured —
1547 /// no automatic scaling; pick `width` and `height` to match your
1548 /// reserved band height.
1549 pub logo_left: Option<LogoSpec>,
1550 pub logo_center: Option<LogoSpec>,
1551 pub logo_right: Option<LogoSpec>,
1552 /// Optional even-page (verso) slot overrides. Page 1 is treated
1553 /// as recto (odd). When set and the current page is even, the
1554 /// corresponding slot template is used in place of the odd
1555 /// counterpart — typical book layout has e.g. chapter title on
1556 /// recto, document title on verso. Empty strings mean "fall back
1557 /// to the odd slot".
1558 pub even: Option<HeaderFooterSlots>,
1559 /// Per-h1-chapter slot overrides. Keyed by exact h1 text; the
1560 /// renderer switches as soon as a heading at that level is seen
1561 /// on the page, so the same page never mixes two chapters'
1562 /// headers. Empty string slots fall back to the parent.
1563 pub per_chapter: HashMap<String, HeaderFooterSlots>,
1564 /// Font families for this element, in fallback order. Empty means
1565 /// "inherit the document body families" (`body_font_families`, or
1566 /// the bundled Noto defaults when that is also empty). Names must
1567 /// be families the font collection knows — either system-installed
1568 /// or exposed by a file listed in `font_paths`.
1569 ///
1570 /// Note this REPLACES the body list rather than extending it, so a
1571 /// Latin-only face here will lose the multi-script fallbacks. List
1572 /// the scripts you need explicitly if the document is not Latin-only.
1573 pub font_families: Vec<String>,
1574}
1575
1576/// Just the three slot templates — used for even-page variants and
1577/// per-chapter overrides. Empty fields fall back to the parent
1578/// `HeaderFooterStyle`'s slot.
1579#[derive(Debug, Clone, Default, Deserialize)]
1580#[serde(default, deny_unknown_fields)]
1581pub struct HeaderFooterSlots {
1582 pub left: String,
1583 pub center: String,
1584 pub right: String,
1585}
1586
1587/// A header/footer logo: an asset URI plus the rendered display size
1588/// in PDF points. The renderer decodes the asset once per document
1589/// and caches the result by URI, so repeating the same logo across
1590/// pages costs the same as decoding it for one page.
1591#[derive(Debug, Clone, Deserialize)]
1592#[serde(default, deny_unknown_fields)]
1593pub struct LogoSpec {
1594 /// Asset-library GUID (file stem), same contract as `{% media id="…" /%}`.
1595 /// Template-substituted like `src`. Tried before `src`; probes
1596 /// `{id}.webp` / `.png` / … then `AssetResolver::resolve_id`.
1597 pub id: String,
1598 /// Asset URI — anything the configured asset resolver understands
1599 /// (`file://path`, relative path, `https://…`, `asset://…`). A bare
1600 /// GUID with no extension is treated as an `id`. Cover-page `src` is
1601 /// a template (`{title}`, `{coverImage}`, …).
1602 pub src: String,
1603 pub width: f32,
1604 pub height: f32,
1605 /// Gap between the logo and the slot's text when both are present.
1606 /// Only effective for the LEFT and RIGHT slots — CENTER slot
1607 /// remains logo-or-text. Defaults to 6 pt.
1608 pub gap: f32,
1609}
1610
1611impl Default for LogoSpec {
1612 fn default() -> Self {
1613 Self {
1614 id: String::new(),
1615 src: String::new(),
1616 width: 0.0,
1617 height: 0.0,
1618 gap: 6.0,
1619 }
1620 }
1621}
1622
1623impl Default for HeaderFooterStyle {
1624 fn default() -> Self {
1625 Self {
1626 font_families: Vec::new(),
1627 left: String::new(),
1628 center: String::new(),
1629 right: String::new(),
1630 font_size: 9.0,
1631 color: ColorRgb::new(110, 120, 130),
1632 margin_from_edge: 36.0,
1633 rule: false,
1634 rule_color: ColorRgb::new(220, 225, 230),
1635 rule_thickness: 0.5,
1636 rule_gap: 4.0,
1637 max_lines: 1,
1638 logo_left: None,
1639 logo_center: None,
1640 logo_right: None,
1641 even: None,
1642 per_chapter: HashMap::new(),
1643 }
1644 }
1645}
1646
1647impl HeaderFooterStyle {
1648 /// Resolve the `(left, center, right)` slot strings effective for
1649 /// this page given its parity and current chapter. Per-chapter
1650 /// overrides take precedence; even-page overrides apply next;
1651 /// missing/empty fields fall back to the parent slot.
1652 pub fn resolved_slots(&self, page_number: usize, chapter: &str) -> (String, String, String) {
1653 let mut left = self.left.clone();
1654 let mut center = self.center.clone();
1655 let mut right = self.right.clone();
1656 if page_number.is_multiple_of(2)
1657 && let Some(e) = &self.even
1658 {
1659 if !e.left.is_empty() {
1660 left = e.left.clone();
1661 }
1662 if !e.center.is_empty() {
1663 center = e.center.clone();
1664 }
1665 if !e.right.is_empty() {
1666 right = e.right.clone();
1667 }
1668 }
1669 if !chapter.is_empty()
1670 && let Some(c) = self.per_chapter.get(chapter)
1671 {
1672 if !c.left.is_empty() {
1673 left = c.left.clone();
1674 }
1675 if !c.center.is_empty() {
1676 center = c.center.clone();
1677 }
1678 if !c.right.is_empty() {
1679 right = c.right.clone();
1680 }
1681 }
1682 (left, center, right)
1683 }
1684}
1685
1686impl HeaderFooterStyle {
1687 /// Total vertical space this decoration consumes from one edge of
1688 /// the page (text height × max_lines + rule gap + rule thickness).
1689 pub fn reserved_height(&self) -> f32 {
1690 let lines = self.max_lines.max(1) as f32;
1691 let text = self.font_size * 1.2 * lines;
1692 let rule = if self.rule {
1693 self.rule_gap + self.rule_thickness
1694 } else {
1695 0.0
1696 };
1697 text + rule
1698 }
1699}
1700
1701impl Style {
1702 pub fn from_toml_str(s: &str) -> Result<Self, toml::de::Error> {
1703 toml::from_str(s)
1704 }
1705
1706 pub fn from_toml_file(path: impl AsRef<std::path::Path>) -> Result<Self, StyleLoadError> {
1707 let text = std::fs::read_to_string(path).map_err(StyleLoadError::Io)?;
1708 Self::from_toml_str(&text).map_err(StyleLoadError::Toml)
1709 }
1710
1711 /// Page-count multiple used for trailing blank pages. `pad_to_multiple`
1712 /// wins when it is greater than 1; otherwise `pad_to_even` means 2.
1713 pub fn padding_multiple(&self) -> usize {
1714 if self.pad_to_multiple > 1 {
1715 self.pad_to_multiple as usize
1716 } else if self.pad_to_even {
1717 2
1718 } else {
1719 0
1720 }
1721 }
1722}
1723
1724#[derive(Debug, thiserror::Error)]
1725pub enum StyleLoadError {
1726 #[error("failed to read style file: {0}")]
1727 Io(std::io::Error),
1728 #[error("failed to parse style TOML: {0}")]
1729 Toml(toml::de::Error),
1730}
1731
1732#[cfg(test)]
1733mod tests {
1734 use super::*;
1735
1736 #[test]
1737 fn default_loads() {
1738 let s = Style::default();
1739 assert_eq!(s.page_width, 595.0);
1740 assert_eq!(s.heading.h1.font_size, 26.0);
1741 }
1742
1743 #[test]
1744 fn frontmatter_tables_are_none_unless_a_style_names_them() {
1745 assert!(Style::default().frontmatter_tables.is_empty());
1746 assert!(
1747 Style::from_toml_str("page_width = 612.0\n")
1748 .unwrap()
1749 .frontmatter_tables
1750 .is_empty()
1751 );
1752 }
1753
1754 #[test]
1755 fn frontmatter_tables_load_by_tag_name() {
1756 let s = Style::from_toml_str(
1757 r#"
1758[frontmatter_tables.changes]
1759key = "changeLog"
1760heading = "Changes"
1761columns = [{ field = "when", header = "When" }, { field = "what", header = "What" }]
1762
1763[frontmatter_tables.people]
1764key = "contributors"
1765columns = [{ field = "name", header = "Name" }]
1766"#,
1767 )
1768 .unwrap();
1769 assert_eq!(
1770 s.frontmatter_tables["changes"],
1771 FrontmatterTable {
1772 key: "changeLog".into(),
1773 heading: Some("Changes".into()),
1774 columns: vec![
1775 FrontmatterColumn {
1776 field: "when".into(),
1777 header: "When".into(),
1778 },
1779 FrontmatterColumn {
1780 field: "what".into(),
1781 header: "What".into(),
1782 },
1783 ],
1784 }
1785 );
1786 assert_eq!(s.frontmatter_tables["people"].heading, None);
1787 assert_eq!(s.frontmatter_tables.len(), 2);
1788 }
1789
1790 #[test]
1791 fn a_frontmatter_table_needs_its_key_and_columns_and_nothing_else() {
1792 for toml in [
1793 "[frontmatter_tables.t]\ncolumns = []\n",
1794 "[frontmatter_tables.t]\nkey = \"k\"\n",
1795 "[frontmatter_tables.t]\nkey = \"k\"\ncolumns = []\nlevel = 3\n",
1796 "[frontmatter_tables.t]\nkey = \"k\"\ncolumns = [{ field = \"f\" }]\n",
1797 ] {
1798 assert!(Style::from_toml_str(toml).is_err(), "{toml}");
1799 }
1800 }
1801
1802 #[test]
1803 fn partial_toml_overrides_only_specified_fields() {
1804 let toml = r#"
1805page_width = 612.0
1806page_height = 792.0
1807margin_x = 54.0
1808"#;
1809 let s = Style::from_toml_str(toml).unwrap();
1810 // Letter-paper overrides applied.
1811 assert_eq!(s.page_width, 612.0);
1812 assert_eq!(s.page_height, 792.0);
1813 assert_eq!(s.margin_x, 54.0);
1814 // Untouched fields keep defaults.
1815 assert_eq!(s.body_font_size, 11.0);
1816 assert_eq!(s.heading.h1.font_size, 26.0);
1817 assert_eq!(
1818 s.callout_styles.warning.background,
1819 ColorRgb::new(255, 247, 230)
1820 );
1821 }
1822
1823 #[test]
1824 fn nested_overrides_work() {
1825 let toml = r#"
1826[heading.h1]
1827font_size = 32.0
1828"#;
1829 let s = Style::from_toml_str(toml).unwrap();
1830 assert_eq!(s.heading.h1.font_size, 32.0);
1831 // Other heading levels keep defaults.
1832 assert_eq!(s.heading.h2.font_size, 21.0);
1833 }
1834
1835 #[test]
1836 fn table_borders_default_and_override() {
1837 // Defaults to a full grid.
1838 assert_eq!(Style::default().table_borders, TableBorders::Grid);
1839 // snake_case values parse from a top-level key.
1840 let horizontal = Style::from_toml_str("table_borders = \"horizontal\"").unwrap();
1841 assert_eq!(horizontal.table_borders, TableBorders::Horizontal);
1842 let none = Style::from_toml_str("table_borders = \"none\"").unwrap();
1843 assert_eq!(none.table_borders, TableBorders::None);
1844 }
1845
1846 #[test]
1847 fn text_align_defaults_left_and_parses() {
1848 assert_eq!(Style::default().text_align, TextAlign::Left);
1849 assert_eq!(
1850 Style::from_toml_str("text_align = \"justify\"")
1851 .unwrap()
1852 .text_align,
1853 TextAlign::Justify
1854 );
1855 assert_eq!(
1856 TextAlign::Justify.to_parley(),
1857 parley::layout::Alignment::Justify
1858 );
1859 }
1860
1861 #[test]
1862 fn table_edge_color_optional() {
1863 // Unset by default — edges match the internal border colour.
1864 let d = Style::default();
1865 assert!(d.table_edge_color.is_none());
1866 assert!(d.table_edge_thickness.is_none());
1867 // A darker, thicker edge (booktabs look) parses.
1868 let s = Style::from_toml_str("table_edge_color = [0, 0, 0]\ntable_edge_thickness = 1.0")
1869 .unwrap();
1870 assert_eq!(s.table_edge_color, Some(ColorRgb::new(0, 0, 0)));
1871 assert_eq!(s.table_edge_thickness, Some(1.0));
1872 }
1873
1874 #[test]
1875 fn list_marker_badge_and_sequences() {
1876 // Defaults: no badge, decimal at every depth.
1877 let d = Style::default().list_marker;
1878 assert!(!d.badge);
1879 assert_eq!(d.sequence_for_depth(0), MarkerSequence::Decimal);
1880 assert_eq!(d.sequence_for_depth(3), MarkerSequence::Decimal);
1881
1882 let toml = r#"
1883[list_marker]
1884badge = true
1885ordered_sequences = ["decimal", "lower-alpha", "lower-roman"]
1886badge_fill = [223, 227, 232]
1887"#;
1888 let lm = Style::from_toml_str(toml).unwrap().list_marker;
1889 assert!(lm.badge);
1890 assert_eq!(lm.badge_fill, ColorRgb::new(223, 227, 232));
1891 // Depth cycles through the configured sequence and wraps.
1892 assert_eq!(lm.sequence_for_depth(0), MarkerSequence::Decimal);
1893 assert_eq!(lm.sequence_for_depth(1), MarkerSequence::LowerAlpha);
1894 assert_eq!(lm.sequence_for_depth(2), MarkerSequence::LowerRoman);
1895 assert_eq!(lm.sequence_for_depth(3), MarkerSequence::Decimal);
1896 }
1897
1898 #[test]
1899 fn callout_kind_lookup() {
1900 let s = Style::default();
1901 assert_eq!(
1902 s.callout_styles.for_kind("warning").background,
1903 ColorRgb::new(255, 247, 230)
1904 );
1905 assert_eq!(
1906 s.callout_styles.for_kind("info").background,
1907 ColorRgb::new(232, 244, 253)
1908 );
1909 // Unknown kind falls back to note.
1910 assert_eq!(
1911 s.callout_styles.for_kind("unknown").background,
1912 s.callout_styles.note.background
1913 );
1914 }
1915
1916 #[test]
1917 fn coverpage_hero_deserializes_without_explicit_size() {
1918 let toml = r#"
1919[coverpage.hero]
1920id = "{coverImage}"
1921src = "{title}.png"
1922"#;
1923 let s = Style::from_toml_str(toml).unwrap();
1924 let hero = s.coverpage.hero.expect("hero slot");
1925 assert_eq!(hero.id, "{coverImage}");
1926 assert_eq!(hero.src, "{title}.png");
1927 assert_eq!(hero.width, 0.0);
1928 assert_eq!(hero.height, 0.0);
1929 }
1930}