aozora 0.5.0

Aozora Bunko notation parser with incremental document snapshots
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! The CSS class names the HTML renderer can emit.
//!
//! [`AOZORA_CLASSES`] is the authoritative, public list of every
//! `aozora-*` class `crate::render::render_node` / `crate::render::html` writes.
//! Downstream consumers (e.g. the sibling `afm` crate) import it instead
//! of hand-mirroring the contract. The `class_list_matches_emitted`
//! test renders every `Node` + `ContainerKind` variant and asserts
//! the emitted class tokens are *exactly* this set, so the published
//! list can never drift from the emit sites.

use crate::spec::roman_slug;
use crate::syntax::{BoutenKind, BoutenPosition, HeadingKind, HeadingStyle};

/// Every CSS class token the HTML renderer can emit.
///
/// Open-ended numeric variants are normalised to their stem
/// (`aozora-indent-2` → `aozora-indent`, `aozora-align-end-3` →
/// `aozora-align-end`); the fixed slug families (`aozora-bouten-<kind>`,
/// `aozora-section-break-<kind>`, the emphasis slugs, the
/// `aozora-heading-<level>` / `-<style>` modifiers) are listed in full.
/// Sorted and deduplicated.
///
/// Pinned by the `class_list_matches_emitted` test. A consumer that
/// accepts a numeric variant should match `aozora-indent` / etc. as a
/// stem and allow a trailing `-<n>`.
pub const AOZORA_CLASSES: &[&str] = &[
    "aozora-accent",
    "aozora-accent-dot",
    "aozora-align-end",
    "aozora-angle-quote",
    "aozora-body-end",
    "aozora-bouten",
    "aozora-bouten-batsu",
    "aozora-bouten-bosen",
    "aozora-bouten-both",
    "aozora-bouten-goma",
    "aozora-bouten-hasen",
    "aozora-bouten-janome",
    "aozora-bouten-kurosankaku",
    "aozora-bouten-kusarisen",
    "aozora-bouten-left",
    "aozora-bouten-maru",
    "aozora-bouten-namisen",
    "aozora-bouten-nijubosen",
    "aozora-bouten-nijumaru",
    "aozora-bouten-right",
    "aozora-bouten-shirogoma",
    "aozora-bouten-shiromaru",
    "aozora-bouten-shirosankaku",
    "aozora-bunsu",
    "aozora-caption",
    "aozora-center",
    "aozora-combine-upright",
    "aozora-container",
    "aozora-container-align-end",
    "aozora-container-center",
    "aozora-container-columns",
    "aozora-container-font-larger",
    "aozora-container-font-smaller",
    "aozora-container-futoji",
    "aozora-container-goshikku",
    "aozora-container-indent",
    "aozora-container-keigakomi",
    "aozora-container-line-kumi",
    "aozora-container-line-width",
    "aozora-container-shatai",
    "aozora-container-table",
    "aozora-container-warichu",
    "aozora-container-wrap-indent",
    "aozora-container-yokogumi",
    "aozora-directive",
    "aozora-editor-note",
    "aozora-enclosure-circle",
    "aozora-enclosure-circle-dotted",
    "aozora-enclosure-double-rule",
    "aozora-font-extra-large",
    "aozora-font-large",
    "aozora-font-larger",
    "aozora-font-medium",
    "aozora-font-small",
    "aozora-font-smaller",
    "aozora-futoji",
    "aozora-gaiji",
    "aozora-goshikku",
    "aozora-heading",
    "aozora-heading-hint",
    "aozora-heading-large",
    "aozora-heading-medium",
    "aozora-heading-same-line",
    "aozora-heading-small",
    "aozora-heading-window",
    "aozora-illustration",
    "aozora-indent",
    "aozora-kaeriten",
    "aozora-keigakomi-box",
    "aozora-keigakomi-inline",
    "aozora-kogaki-left",
    "aozora-kogaki-right",
    "aozora-line-font-extra-large",
    "aozora-line-font-large",
    "aozora-line-font-medium",
    "aozora-line-font-small",
    "aozora-line-futoji",
    "aozora-line-goshikku",
    "aozora-margin-note",
    "aozora-page-break",
    "aozora-ruby-left",
    "aozora-ruby-note",
    "aozora-section-break",
    "aozora-section-break-kaicho",
    "aozora-section-break-kaidan",
    "aozora-section-break-kaimihiraki",
    "aozora-shatai",
    "aozora-shitatsuki",
    "aozora-uwatsuki",
    "aozora-warichu",
    "aozora-yokogumi",
];

// ── Per-enum class-token slugs ────────────────────────────────────────
// Single source of truth for the variable `aozora-*` slugs the renderer
// composes, shared by `crate::render::render_node` (the emit sites) and the
// `class_list_matches_emitted` derivation below. Fixed, structure-bound
// class literals stay inline in the HTML templates they belong to.

/// Romaji slug for a [`BoutenKind`] — the `aozora-bouten-<slug>` suffix.
///
/// The slug lives in the spec table (`RENDER_SLUGS`), keyed by the
/// canonical 青空文庫 keyword; `BoutenKind` is `#[non_exhaustive]`, so an
/// unknown kind falls back to `other` and rendering stays infallible.
#[must_use]
pub(crate) fn bouten_kind_slug(kind: BoutenKind) -> &'static str {
    roman_slug(kind.keyword()).unwrap_or("other")
}

/// Side slug for a [`BoutenPosition`] — the `aozora-bouten-<slug>` /
/// `aozora-kogaki-<slug>` suffix.
#[must_use]
pub(crate) const fn bouten_position_slug(pos: BoutenPosition) -> &'static str {
    match pos {
        BoutenPosition::Left => "left",
        BoutenPosition::Both => "both",
        _ => "right",
    }
}

/// Outline-level slug for a [`HeadingKind`] — the `aozora-heading-<slug>`
/// suffix.
///
/// Shared by the forward-reference leaf and the paired/block heading
/// container. `HeadingKind` is `#[non_exhaustive]`; an unknown level
/// defaults to the top (`large`).
#[must_use]
pub(crate) const fn heading_level_slug(kind: HeadingKind) -> &'static str {
    match kind {
        HeadingKind::Medium => "medium",
        HeadingKind::Small => "small",
        _ => "large",
    }
}

/// Per-style modifier slug for a [`HeadingStyle`].
///
/// `None` for the standard style, which adds no modifier so a standard
/// heading's markup is unchanged. An unknown (`#[non_exhaustive]`) style
/// is treated as standard.
#[must_use]
pub(crate) const fn heading_style_slug(style: HeadingStyle) -> Option<&'static str> {
    match style {
        HeadingStyle::SameLine => Some("same-line"),
        HeadingStyle::Window => Some("window"),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::{AOZORA_CLASSES, bouten_kind_slug, bouten_position_slug};
    use crate::render::render_node::render;
    use crate::render::spelling::html::render_container;
    use crate::syntax::alloc::Allocator;
    use crate::syntax::ast::{Node, NodeStore};
    use crate::syntax::{
        AbsoluteSize, AccentMark, BOUTEN_KINDS, BlockStyles, BoutenKind, BoutenPosition,
        ColumnCount, Container, DirectiveKind, EnclosureKind, FontShift, ForwardAttr,
        ForwardOrigin, HEADING_KINDS, HEADING_STYLES, HeadingKind, HeadingStyle, IndentBlock,
        IndentLayout, Kumi, LineFormat, LineWidth, MarginNoteKind, RegionFormat, SECTION_KINDS,
    };
    use core::num::{NonZeroI8, NonZeroU8};
    use std::collections::BTreeSet;

    fn fs(steps: i8) -> FontShift {
        FontShift(NonZeroI8::new(steps).expect("non-zero"))
    }
    fn lw(n: u8) -> LineWidth {
        LineWidth(NonZeroU8::new(n).expect("non-zero"))
    }
    fn cc(n: u8) -> ColumnCount {
        ColumnCount(NonZeroU8::new(n).expect("non-zero"))
    }
    fn kumi(lines: u8, width: u8) -> Kumi {
        Kumi {
            lines: NonZeroU8::new(lines).expect("non-zero"),
            width: NonZeroU8::new(width).expect("non-zero"),
        }
    }

    /// E1-1: a no-referent forward ([`ForwardOrigin::SelfContained`]) owns the
    /// only copy of its target, so it renders the styled run — it is **not**
    /// short-circuited like [`ForwardOrigin::Referenced`] (the #228 guard). The
    /// producer is wired in E1-2/E1-3; the render fall-through is pinned here so
    /// the plumbing PR carries its own proof.
    #[test]
    fn self_contained_forward_renders_styled_run() {
        let mut a = Allocator::new();
        let bold_t = a.content_plain("");
        let bold = a.forward_format(ForwardAttr::Bold, bold_t, ForwardOrigin::SelfContained);
        let bouten_t = a.content_plain("");
        let bouten = a.bouten(
            BoutenKind::Goma,
            bouten_t,
            BoutenPosition::Right,
            ForwardOrigin::SelfContained,
        );
        let store = a.into_store();

        let mut bold_html = String::new();
        render(bold, &store, &mut bold_html).expect("render into String is infallible");
        assert_eq!(bold_html, r#"<b class="aozora-futoji">強</b>"#);

        let mut bouten_html = String::new();
        render(bouten, &store, &mut bouten_html).expect("render into String is infallible");
        assert_eq!(
            bouten_html,
            r#"<em class="aozora-bouten aozora-bouten-goma aozora-bouten-right">点</em>"#
        );
    }

    /// Pull the `aozora-*` tokens out of every `class="…"` attribute in
    /// `html`, collapsing a trailing `-<digits>` run to its stem so
    /// open-ended numeric variants (indent / align-end amounts) don't
    /// explode the set.
    fn collect_classes(html: &str, into: &mut BTreeSet<String>) {
        let mut rest = html;
        while let Some(p) = rest.find("class=\"") {
            rest = &rest[p + "class=\"".len()..];
            let end = rest.find('"').unwrap_or(rest.len());
            for c in rest[..end].split_whitespace() {
                if !c.starts_with("aozora-") {
                    continue;
                }
                let stem = match c.rfind('-') {
                    Some(i)
                        if i + 1 < c.len() && c[i + 1..].bytes().all(|b| b.is_ascii_digit()) =>
                    {
                        &c[..i]
                    }
                    _ => c,
                };
                into.insert(stem.to_owned());
            }
            rest = &rest[end..];
        }
    }

    /// Collect a built owned node for later rendering (the allocator's store is
    /// still borrowed mutably during the build, so the render pass runs after
    /// `into_store`).
    fn render_into(node: Node, nodes: &mut Vec<Node>) {
        nodes.push(node);
    }

    fn render_collected(node: Node, store: &NodeStore, set: &mut BTreeSet<String>) {
        let mut s = String::new();
        render(node, store, &mut s).expect("render into String is infallible");
        collect_classes(&s, set);
    }

    /// Render every `Node` + `ContainerKind` variant and collect the
    /// emitted `aozora-*` class tokens (numeric variants collapsed to their
    /// stem). The authoritative derivation [`AOZORA_CLASSES`] is pinned to;
    /// enum families enumerate through the `*_KINDS` constants so a new
    /// variant flows in automatically.
    #[allow(
        clippy::too_many_lines,
        reason = "one render call per Node + ContainerKind variant; \
                  splitting would scatter the exhaustive enumeration"
    )]
    fn all_emitted_classes() -> BTreeSet<String> {
        let mut a = Allocator::new();
        let mut nodes: Vec<Node> = Vec::new();

        // --- leaf nodes ---
        render_into(a.page_break(), &mut nodes);
        render_into(a.body_end(), &mut nodes);
        render_into(a.forced_break(), &mut nodes);
        render_into(a.kaeriten(""), &mut nodes);
        render_into(a.line(LineFormat::Center { page: true }), &mut nodes);
        render_into(a.line(LineFormat::Center { page: false }), &mut nodes);
        render_into(
            a.line(LineFormat::Indent {
                amount: 2,
                end_offset: None,
            }),
            &mut nodes,
        );
        // Both-margin compound emits the align-end classes alongside the indent
        // classes (both stems already listed in `AOZORA_CLASSES`).
        render_into(
            a.line(LineFormat::Indent {
                amount: 2,
                end_offset: Some(2),
            }),
            &mut nodes,
        );
        render_into(a.line(LineFormat::AlignEnd { offset: 0 }), &mut nodes);
        render_into(a.line(LineFormat::AlignEnd { offset: 2 }), &mut nodes);
        render_into(a.line(LineFormat::Gothic), &mut nodes);
        for size in [
            AbsoluteSize::ExtraLarge,
            AbsoluteSize::Large,
            AbsoluteSize::Medium,
            AbsoluteSize::Small,
        ] {
            render_into(
                a.line(LineFormat::FontSizeAbsolute { size, bold: false }),
                &mut nodes,
            );
        }
        // The `、太字` compound adds the line-bold class (already covered above).
        render_into(
            a.line(LineFormat::FontSizeAbsolute {
                size: AbsoluteSize::Large,
                bold: true,
            }),
            &mut nodes,
        );
        render_into(a.sashie("f.png", None, None, None), &mut nodes);
        render_into(a.sashie_general("f.png", "", None), &mut nodes);
        render_into(
            a.heading_hint(HeadingKind::Large, HeadingStyle::Standard, "x", false),
            &mut nodes,
        );
        render_into(
            a.heading_hint(HeadingKind::Medium, HeadingStyle::Standard, "x", true),
            &mut nodes,
        );

        for &k in SECTION_KINDS {
            render_into(a.section_break(k), &mut nodes);
        }

        let g = a.make_gaiji("X", None, false);
        render_into(a.gaiji(g), &mut nodes);
        for kind in [
            DirectiveKind::WarichuOpen,
            DirectiveKind::WarichuClose,
            DirectiveKind::NonCanonical,
            DirectiveKind::Editorial,
        ] {
            let p = a.make_directive("[#注]", kind);
            render_into(a.annotation(p), &mut nodes);
        }
        // EditorNote renders a visible 注N superscript from its raw shape.
        let editor_note = a.make_directive("[#入力者注(1)]", DirectiveKind::EditorNote);
        render_into(a.annotation(editor_note), &mut nodes);
        // Ruby-placement notes render a compact `aozora-ruby-note` marker.
        for (kind, raw) in [
            (DirectiveKind::RubyAttached, "[#「親」にルビ]"),
            (DirectiveKind::RubyRetarget, "[#ルビは「親」にかかる]"),
            (DirectiveKind::RubyPairOpen, "[#左にルビ付き]"),
            (
                DirectiveKind::RubyPairClose,
                "[#左に「よみ」のルビ付き終わり]",
            ),
        ] {
            let p = a.make_directive(raw, kind);
            render_into(a.annotation(p), &mut nodes);
        }
        // Margin-note span markers render a compact `aozora-margin-note` marker.
        for (kind, raw) in [
            (DirectiveKind::MarginNotePairOpen, "[#注記付き]"),
            (DirectiveKind::MarginNotePairOpen, "[#左に注記付き]"),
            (
                DirectiveKind::MarginNotePairClose,
                "[#「よみ」の注記付き終わり]",
            ),
            (
                DirectiveKind::MarginNotePairClose,
                "[#左に「よみ」の注記付き終わり]",
            ),
        ] {
            let p = a.make_directive(raw, kind);
            render_into(a.annotation(p), &mut nodes);
        }

        // Nodes needing Content. `content_plain` takes `&mut self` but
        // returns a Content borrowing the arena (not the allocator), so
        // the `&mut` borrow ends before each `&self` constructor runs and
        // plain sequential lets compile.
        let ruby_base = a.content_plain("");
        let ruby_reading = a.content_plain("おや");
        render_into(a.ruby(ruby_base, ruby_reading), &mut nodes);
        let lruby_base = a.content_plain("");
        let lruby_reading = a.content_plain("");
        render_into(a.left_ruby(lruby_base, lruby_reading), &mut nodes);
        let note_base = a.content_plain("");
        let note_text = a.content_plain("");
        render_into(
            a.side_note(MarginNoteKind::Gloss, note_base, note_text),
            &mut nodes,
        );
        let tcy = a.content_plain("");
        render_into(a.tate_chu_yoko(tcy, ForwardOrigin::Reclaimed), &mut nodes);
        let angle = a.content_plain("");
        render_into(a.angle_quote(angle), &mut nodes);
        for &kind in BOUTEN_KINDS {
            for pos in [BoutenPosition::Right, BoutenPosition::Left] {
                let t = a.content_plain("");
                render_into(a.bouten(kind, t, pos, ForwardOrigin::Reclaimed), &mut nodes);
            }
        }
        // Every forward-emphasis attribute that produces a distinct class.
        for attr in [
            ForwardAttr::Bold,
            ForwardAttr::Italic,
            ForwardAttr::SuperScript,
            ForwardAttr::SubScript,
            ForwardAttr::SmallScript(BoutenPosition::Right),
            ForwardAttr::SmallScript(BoutenPosition::Left),
            ForwardAttr::Framed(EnclosureKind::Rule),
            ForwardAttr::Framed(EnclosureKind::Box),
            ForwardAttr::Framed(EnclosureKind::Circle),
            ForwardAttr::Framed(EnclosureKind::CircleDotted),
            ForwardAttr::Framed(EnclosureKind::DoubleRule),
            ForwardAttr::Horizontal,
            ForwardAttr::Caption,
            ForwardAttr::Fraction,
            ForwardAttr::FontSizeAbsolute(AbsoluteSize::ExtraLarge),
            ForwardAttr::FontSizeAbsolute(AbsoluteSize::Large),
            ForwardAttr::FontSizeAbsolute(AbsoluteSize::Medium),
            ForwardAttr::FontSizeAbsolute(AbsoluteSize::Small),
            ForwardAttr::FontSize(fs(1)),
            ForwardAttr::AlignEnd { offset: 1 },
        ] {
            let t = a.content_plain("");
            render_into(
                a.forward_format(attr, t, ForwardOrigin::Reclaimed),
                &mut nodes,
            );
        }
        // AccentDot (#331) needs an interned body + a composable run, so it uses
        // its own constructor rather than the loop above; this exercises the
        // `aozora-accent-dot` class through the compose path.
        let dotted = a.content_plain("Sam");
        render_into(
            a.accent_dot(dotted, "mは上ドット付き", ForwardOrigin::Reclaimed),
            &mut nodes,
        );
        // Accent (forward accent-mark): the letter rides on the target (no
        // interned body), so it uses `forward_format`; a composable single
        // letter exercises the `aozora-accent` class through the compose path.
        let accented = a.content_plain("e");
        render_into(
            a.forward_format(
                ForwardAttr::Accent(AccentMark::Acute),
                accented,
                ForwardOrigin::Reclaimed,
            ),
            &mut nodes,
        );
        // FontSize positive → font-larger above; its negative magnitude
        // (font-smaller) is the only other class the variant produces.
        let smaller = a.content_plain("");
        render_into(
            a.forward_format(
                ForwardAttr::FontSize(fs(-1)),
                smaller,
                ForwardOrigin::Reclaimed,
            ),
            &mut nodes,
        );
        for &kind in HEADING_KINDS {
            for &style in HEADING_STYLES {
                let t = a.content_plain("");
                render_into(a.aozora_heading(kind, style, t), &mut nodes);
            }
        }

        // --- containers (open + close) ---
        let mut containers = vec![
            RegionFormat::Indent(IndentBlock {
                amount: 2,
                wrap: None,
                center: false,
                layout: IndentLayout::None,
                styles: BlockStyles::EMPTY,
            }),
            RegionFormat::Indent(IndentBlock {
                amount: 2,
                wrap: Some(4),
                center: true,
                layout: IndentLayout::None,
                styles: BlockStyles::EMPTY,
            }),
            // #78 line-layout compounds — exercise the new line-kumi class
            // (字詰め reuses the standalone line-width class).
            RegionFormat::Indent(IndentBlock {
                amount: 3,
                wrap: None,
                center: false,
                layout: IndentLayout::Kumi(kumi(1, 20)),
                styles: BlockStyles::EMPTY,
            }),
            RegionFormat::Indent(IndentBlock {
                amount: 8,
                wrap: None,
                center: false,
                layout: IndentLayout::LineWidth(lw(18)),
                styles: BlockStyles::EMPTY,
            }),
            // #78 co-applied style stack — exercises the flat decoration
            // classes (futoji / yokogumi / keigakomi / font-smaller) on one
            // indent `<div>`.
            RegionFormat::Indent(IndentBlock {
                amount: 4,
                wrap: None,
                center: false,
                layout: IndentLayout::None,
                styles: BlockStyles {
                    gothic: true,
                    horizontal: true,
                    framed: true,
                    font: Some(FontShift(NonZeroI8::new(-1).unwrap())),
                },
            }),
            RegionFormat::Warichu,
            RegionFormat::Framed(EnclosureKind::Rule),
            RegionFormat::AlignEnd { offset: 0 },
            RegionFormat::AlignEnd { offset: 2 },
            RegionFormat::LineWidth(lw(30)),
            RegionFormat::Bold { padded: false },
            RegionFormat::Bold { padded: true },
            RegionFormat::Gothic { padded: false },
            RegionFormat::Gothic { padded: true },
            RegionFormat::Italic { padded: false },
            RegionFormat::Italic { padded: true },
            RegionFormat::Columns(cc(2)),
            RegionFormat::Table,
            RegionFormat::Horizontal,
            RegionFormat::FontSize(fs(2)),
            RegionFormat::FontSize(fs(-2)),
            RegionFormat::SmallScript(BoutenPosition::Right),
            RegionFormat::SmallScript(BoutenPosition::Left),
            RegionFormat::Caption { padded: false },
            RegionFormat::Caption { padded: true },
        ];
        for &kind in BOUTEN_KINDS {
            for position in [
                BoutenPosition::Right,
                BoutenPosition::Left,
                BoutenPosition::Both,
            ] {
                containers.push(RegionFormat::Bouten { kind, position });
            }
        }
        for &level in HEADING_KINDS {
            for &style in HEADING_STYLES {
                containers.push(RegionFormat::Heading {
                    level,
                    style,
                    padded: true,
                });
            }
        }
        let store = a.into_store();
        let mut emitted: BTreeSet<String> = BTreeSet::new();
        for node in nodes {
            render_collected(node, &store, &mut emitted);
        }
        for kind in containers {
            let mut html = String::new();
            let container = Container { kind };
            render_container(container, true, &mut html).expect("render into String is infallible");
            render_container(container, false, &mut html)
                .expect("render into String is infallible");
            collect_classes(&html, &mut emitted);
        }
        emitted
    }

    #[test]
    fn class_list_matches_emitted() {
        let listed: BTreeSet<String> = AOZORA_CLASSES.iter().map(|s| (*s).to_owned()).collect();
        assert_eq!(
            all_emitted_classes(),
            listed,
            "AOZORA_CLASSES is out of sync with the renderer's emitted classes"
        );

        // The published list must stay sorted + deduplicated so a binary
        // search / diff against it is well-defined downstream.
        let mut sorted = AOZORA_CLASSES.to_vec();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(
            sorted.as_slice(),
            AOZORA_CLASSES,
            "AOZORA_CLASSES must be sorted and free of duplicates"
        );
    }

    #[test]
    fn bouten_kind_slug_covers_every_variant() {
        for (kind, slug) in [
            (BoutenKind::Goma, "goma"),
            (BoutenKind::WhiteSesame, "shirogoma"),
            (BoutenKind::Circle, "maru"),
            (BoutenKind::WhiteCircle, "shiromaru"),
            (BoutenKind::DoubleCircle, "nijumaru"),
            (BoutenKind::Janome, "janome"),
            (BoutenKind::Cross, "batsu"),
            (BoutenKind::WhiteTriangle, "shirosankaku"),
            (BoutenKind::WavyLine, "namisen"),
            (BoutenKind::UnderLine, "bosen"),
            (BoutenKind::DoubleUnderLine, "nijubosen"),
            (BoutenKind::ChainLine, "kusarisen"),
            (BoutenKind::DashedLine, "hasen"),
            (BoutenKind::BlackTriangle, "kurosankaku"),
        ] {
            assert_eq!(
                bouten_kind_slug(kind),
                slug,
                "bouten_kind_slug mismatch for {kind:?}"
            );
        }
    }

    #[test]
    fn bouten_position_slug_maps_left_and_right() {
        assert_eq!(bouten_position_slug(BoutenPosition::Left), "left");
        assert_eq!(bouten_position_slug(BoutenPosition::Right), "right");
    }

    /// The canonical reference stylesheet
    /// (`assets/aozora-notation.css`) is the single source of truth for
    /// how every emitted `aozora-*` class is presented. This test pins
    /// its `.aozora-*` selectors to [`AOZORA_CLASSES`] *exactly*, so a
    /// renamed class (the `aozora_gaiji` / `aozora_tcy` drift that broke
    /// the VS Code preview), a typo, or a forgotten style is a test
    /// failure rather than a silent visual regression. The two consumer
    /// scope hooks — `.aozora-notation` (base) and `.aozora-vertical`
    /// (縦書き) — are not renderer-emitted, so they are the only
    /// non-`AOZORA_CLASSES` selectors the sheet may carry.
    #[test]
    fn canonical_stylesheet_matches_emitted_classes() {
        const CSS: &str = include_str!("../../assets/aozora-notation.css");

        let styled = extract_css_classes(CSS);
        let scope: BTreeSet<String> = ["aozora-notation", "aozora-vertical"]
            .into_iter()
            .map(str::to_owned)
            .collect();
        let emitted: BTreeSet<String> = AOZORA_CLASSES.iter().map(|s| (*s).to_owned()).collect();

        for hook in &scope {
            assert!(
                styled.contains(hook),
                "canonical stylesheet must use the consumer scope hook `.{hook}`",
            );
        }

        let notation: BTreeSet<String> = styled.difference(&scope).cloned().collect();

        let dead: Vec<&String> = notation.difference(&emitted).collect();
        assert!(
            dead.is_empty(),
            "canonical stylesheet references classes the renderer never emits \
             (dead / typo'd): {dead:?}",
        );

        let missing: Vec<&String> = emitted.difference(&notation).collect();
        assert!(
            missing.is_empty(),
            "canonical stylesheet is missing a rule for emitted classes: {missing:?}",
        );
    }

    /// Collect every `.aozora-*` class selector in the stylesheet,
    /// normalising open-ended numeric variants to their stem
    /// (`aozora-indent-3` → `aozora-indent`) to match how
    /// [`AOZORA_CLASSES`] lists them. Block comments are stripped first so
    /// class names mentioned in prose do not count.
    fn extract_css_classes(css: &str) -> BTreeSet<String> {
        let mut cleaned = String::with_capacity(css.len());
        let mut chars = css.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '/' && chars.peek() == Some(&'*') {
                chars.next();
                let mut prev = '\0';
                for d in chars.by_ref() {
                    if prev == '*' && d == '/' {
                        break;
                    }
                    prev = d;
                }
            } else {
                cleaned.push(c);
            }
        }

        let bytes = cleaned.as_bytes();
        let mut out = BTreeSet::new();
        let mut i = 0;
        while i < bytes.len() {
            if bytes[i] == b'.' {
                let start = i + 1;
                let mut j = start;
                while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'-') {
                    j += 1;
                }
                let ident = &cleaned[start..j];
                if ident
                    .strip_prefix("aozora-")
                    .is_some_and(|rest| !rest.is_empty())
                {
                    out.insert(normalize_numeric_variant(ident));
                }
                i = j.max(i + 1);
            } else {
                i += 1;
            }
        }
        out
    }

    /// Strip a trailing `-<digits>` so `aozora-indent-3` collapses to the
    /// `aozora-indent` stem `AOZORA_CLASSES` records. No emitted class
    /// name ends in a digit, so this never corrupts a real name.
    fn normalize_numeric_variant(cls: &str) -> String {
        if let Some(idx) = cls.rfind('-') {
            let suffix = &cls[idx + 1..];
            if !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit()) {
                return cls[..idx].to_owned();
            }
        }
        cls.to_owned()
    }
}