yog-book 0.46.0

In-game book/documentation framework for Yog mods (Patchouli-like).
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
//! yog-book — in-game book/documentation framework for Yog mods.
//!
//! Provides Patchouli-like book data model plus a full GPU renderer on top of
//! yog-ui and yog-gfx, with SVG icon support and custom TTF/OTF fonts.

pub mod state;
pub mod theme;
pub mod font;
pub mod svg;
pub mod renderer;

use serde::{Deserialize, Serialize};
use yog_registry::ItemDef;

pub use state::BookViewState;
pub use theme::BookTheme;
pub use font::{BookFont, BookFontRegistry};
pub use renderer::BookRenderer;

// ── Macros ───────────────────────────────────────────────────────────────────

/// A macro substitution (e.g. `$(thing)` → red color span).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BookMacro(pub String, pub String);

// ── Page types ───────────────────────────────────────────────────────────────

/// A single page variant inside a book entry.
///
/// The wire format (mod ↔ runtime JSON boundary, produced by
/// [`BookPage::to_json`]) is internally tagged with snake_case names —
/// `{"type": "spotlight", "item": "yog:ruby", ...}` — like Patchouli's
/// per-page "type" field. The serde attributes below keep `Deserialize`
/// in exact agreement with `to_json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum BookPage {
    /// Plain formatted text, optionally with a section title (for non-first pages).
    Text {
        text: String,
        #[serde(default)]
        title: Option<String>,
    },
    /// Display an item outlined (tooltip on hover).
    Spotlight {
        /// On the wire this is the item id string ("yog:ruby"); rich
        /// `ItemDef` maps are accepted too.
        #[serde(with = "item_ref")]
        item: ItemDef,
        #[serde(default)]
        title: Option<String>,
        #[serde(default)]
        text: Option<String>,
    },
    /// Crafting recipe display (autorenders 3×3 grid).
    Crafting {
        #[serde(rename = "recipe", alias = "recipe_id")]
        recipe_id: String,
        #[serde(default)]
        text: Option<String>,
    },
    /// Smelting recipe display.
    Smelting {
        #[serde(rename = "recipe", alias = "recipe_id")]
        recipe_id: String,
        #[serde(default)]
        text: Option<String>,
    },
    /// Image overlay page.
    Image {
        texture: String,
        #[serde(default)]
        title: Option<String>,
        #[serde(default)]
        text: Option<String>,
        #[serde(default)]
        border: bool,
    },
    /// Entity display page (renders a living entity in a box).
    Entity {
        #[serde(rename = "entity", alias = "entity_type")]
        entity_type: String,
        #[serde(default)]
        name: Option<String>,
        #[serde(default)]
        text: Option<String>,
    },
    /// Link to another entry (like Patchouli's relations).
    Relations {
        entries: Vec<String>,
        #[serde(default)]
        text: Option<String>,
    },
    /// Empty separator.
    Empty,
    /// Custom pattern page for Hexcasting-style mods (like `hexcasting:pattern`).
    Pattern {
        op_id: String,
        #[serde(default)]
        anchor: String,
        #[serde(default)]
        input: String,
        #[serde(default)]
        output: String,
        #[serde(default)]
        text: String,
    },
    /// SVG image page — rasterized at render time via `resvg`.
    Svg {
        /// Raw SVG source string.
        data:  String,
        #[serde(default)]
        title: Option<String>,
        #[serde(default)]
        text:  Option<String>,
    },
    /// Text rendered with a custom TTF/OTF font.
    CustomText {
        text:  String,
        /// Flattened on the wire: `"font_id": …, "size_px": …`.
        #[serde(flatten)]
        font:  BookFont,
        /// ARGB color (0xAARRGGBB).
        color: u32,
    },
}

/// (De)serialize `ItemDef` as a plain item-id string ("yog:ruby"), accepting
/// a full `ItemDef` map on input for richer definitions.
mod item_ref {
    use serde::{Deserialize, Deserializer, Serializer};
    use yog_registry::ItemDef;

    pub fn serialize<S: Serializer>(item: &ItemDef, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&item.id)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<ItemDef, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            Id(String),
            Def(ItemDef),
        }
        Ok(match Repr::deserialize(d)? {
            Repr::Id(id) => ItemDef::new(id),
            Repr::Def(def) => def,
        })
    }
}

// ── Category ─────────────────────────────────────────────────────────────────

/// Represents a book category tab (e.g. "Basics", "Patterns").
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct BookCategory {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    /// MC texture path for the category icon (e.g. `"minecraft:textures/item/book.png"`).
    pub icon: Option<String>,
    /// Raw SVG string for the category icon (takes priority over `icon`).
    pub icon_svg: Option<String>,
    /// Sort priority (lower = first).
    pub sortnum: i32,
}

// ── Entry ────────────────────────────────────────────────────────────────────

/// One entry in a book (like a "page" in the TOC sidebar).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct BookEntry {
    pub id: String,
    pub name: String,
    pub category: String,
    pub pages: Vec<BookPage>,
    /// Entry icon (item id or texture path).
    pub icon: Option<String>,
    /// Raw SVG icon string (takes priority over `icon`).
    pub icon_svg: Option<String>,
    /// If true, hides from the book (used for unlocks).
    pub secret: bool,
    /// Sort priority (lower = first).
    pub priority: i32,
    /// If true, read by default when opening the book.
    pub read_by_default: bool,
    /// Advancement required to unlock.
    pub advancement: Option<String>,
}

// ── Book ─────────────────────────────────────────────────────────────────────

/// The top-level book definition — replaces `patchouli_books/<id>/book.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Book {
    pub id: String,
    pub name: String,
    pub nameplate_color: String,
    pub landing_text: String,
    pub author: Option<String>,
    pub book_texture: String,
    pub filler_texture: String,
    pub model: String,
    pub categories: Vec<BookCategory>,
    pub entries: Vec<BookEntry>,
    pub macros: Vec<BookMacro>,
    pub use_resource_pack: bool,
    pub show_progress: bool,
    pub i18n: bool,
    pub creative_tab: Option<String>,
}

impl Book {
    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            nameplate_color: "FFDD98".into(), // Patchouli default nameplateColor
            landing_text: String::new(),
            author: None,
            book_texture: "yog:textures/gui/book.png".into(),
            filler_texture: "yog:textures/gui/book_filler.png".into(),
            model: "minecraft:book".into(),
            categories: Vec::new(),
            entries: Vec::new(),
            macros: Vec::new(),
            use_resource_pack: false,
            show_progress: true,
            i18n: false,
            creative_tab: None,
        }
    }

    pub fn author(mut self, author: impl Into<String>) -> Self {
        self.author = Some(author.into());
        self
    }

    pub fn book_texture(mut self, tex: impl Into<String>) -> Self {
        self.book_texture = tex.into();
        self
    }

    pub fn filler_texture(mut self, tex: impl Into<String>) -> Self {
        self.filler_texture = tex.into();
        self
    }

    pub fn nameplate(mut self, color: impl Into<String>) -> Self {
        self.nameplate_color = color.into();
        self
    }

    pub fn landing_text(mut self, text: impl Into<String>) -> Self {
        self.landing_text = text.into();
        self
    }

    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    pub fn creative_tab(mut self, tab: impl Into<String>) -> Self {
        self.creative_tab = Some(tab.into());
        self
    }

    pub fn show_progress(mut self, show: bool) -> Self {
        self.show_progress = show;
        self
    }

    pub fn i18n(mut self, val: bool) -> Self {
        self.i18n = val;
        self
    }

    pub fn use_resource_pack(mut self, val: bool) -> Self {
        self.use_resource_pack = val;
        self
    }

    pub fn add_macro(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.macros.push(BookMacro(key.into(), value.into()));
        self
    }

    pub fn add_category(mut self, category: BookCategory) -> Self {
        self.categories.push(category);
        self
    }

    pub fn add_entry(mut self, entry: BookEntry) -> Self {
        self.entries.push(entry);
        self
    }
}

impl Default for Book {
    fn default() -> Self {
        Self::new("yog:default", "Unknown Book")
    }
}

// ── Registry ─────────────────────────────────────────────────────────────────

/// Global registry for all in-game books.
#[derive(Debug, Default)]
pub struct BookRegistry {
    books: std::collections::HashMap<String, Book>,
}

impl BookRegistry {
    pub fn register(&mut self, book: Book) {
        self.books.insert(book.id.clone(), book);
    }

    pub fn get(&self, id: &str) -> Option<&Book> {
        self.books.get(id)
    }

    pub fn all(&self) -> impl Iterator<Item = &Book> {
        self.books.values()
    }
}

// ── Builder helpers ──────────────────────────────────────────────────────────

pub fn text_page(text: impl Into<String>) -> BookPage {
    BookPage::Text { text: text.into(), title: None }
}

pub fn text_page_titled(title: impl Into<String>, text: impl Into<String>) -> BookPage {
    BookPage::Text { text: text.into(), title: Some(title.into()) }
}

pub fn spotlight_page(item: ItemDef) -> BookPage {
    BookPage::Spotlight { item, title: None, text: None }
}

pub fn crafting_page(recipe_id: impl Into<String>) -> BookPage {
    BookPage::Crafting { recipe_id: recipe_id.into(), text: None }
}

pub fn crafting_page_with_text(recipe_id: impl Into<String>, text: impl Into<String>) -> BookPage {
    BookPage::Crafting { recipe_id: recipe_id.into(), text: Some(text.into()) }
}

pub fn smelting_page(recipe_id: impl Into<String>) -> BookPage {
    BookPage::Smelting { recipe_id: recipe_id.into(), text: None }
}

pub fn image_page(texture: impl Into<String>) -> BookPage {
    BookPage::Image { texture: texture.into(), title: None, text: None, border: true }
}

pub fn entity_page(entity_type: impl Into<String>) -> BookPage {
    BookPage::Entity { entity_type: entity_type.into(), name: None, text: None }
}

pub fn relations_page(entries: Vec<String>) -> BookPage {
    BookPage::Relations { entries, text: None }
}

pub fn pattern_page(op_id: impl Into<String>, anchor: impl Into<String>, input: impl Into<String>, output: impl Into<String>, text: impl Into<String>) -> BookPage {
    BookPage::Pattern {
        op_id: op_id.into(),
        anchor: anchor.into(),
        input: input.into(),
        output: output.into(),
        text: text.into(),
    }
}

// ── Book → yog-ui bridge ─────────────────────────────────────────────────────
pub mod book_ui {
    use crate::{Book, BookEntry, BookPage};
    use yog_ui::widget::{self, Widget};
    use yog_ui::{Align, FlexDir, UiRoot};

    /// Build a `UiRoot` from a `Book`.
    /// The UI has: left panel (categories + entries), right panel (pages),
    /// prev/next buttons at bottom.
    pub fn build_book_ui(book: &Book, selected_cat: usize, selected_entry: usize, current_page: usize) -> UiRoot {
        let mut cats: Vec<Widget> = Vec::new();
        for (i, cat) in book.categories.iter().enumerate() {
            let color = if i == selected_cat { 0xFF_FFFF55 } else { 0xFF_CCCCCC };
            cats.push(widget::button(&cat.name)
                .color(color)
                .on_click(format!("cat:{}", i)));
        }

        let cat = book.categories.get(selected_cat);
        let mut entries: Vec<Widget> = Vec::new();
        if let Some(cat) = cat {
            let cat_entries: Vec<&BookEntry> = book.entries.iter()
                .filter(|e| e.category == cat.id).collect();
            for (i, entry) in cat_entries.iter().enumerate() {
                let color = if i == selected_entry { 0xFF_FFFF55 } else { 0xFF_CCCCCC };
                let label = if entry.name.len() > 14 { &entry.name[..14] } else { &entry.name };
                entries.push(widget::button(label)
                    .color(color)
                    .on_click(format!("entry:{}", i)));
            }
        }

        let mut pages: Vec<Widget> = Vec::new();
        if let Some(cat) = cat {
            let cat_entries: Vec<&BookEntry> = book.entries.iter()
                .filter(|e| e.category == cat.id).collect();
            if let Some(entry) = cat_entries.get(selected_entry) {
                if let Some(page) = entry.pages.get(current_page) {
                    pages.push(render_page(page));
                }
            }
        }

        let nav = widget::panel(FlexDir::Row).gap(4.0)
            .child(widget::button("<").w(28.0).on_click("prev_page"))
            .child(widget::label(&format!("{}/{}", current_page + 1,
                cat.map_or(0, |c| {
                    book.entries.iter().filter(|e| e.category == c.id).nth(selected_entry)
                        .map_or(0, |e| e.pages.len())
                }))).color(0xFF_888888).flex(1.0).align(Align::Center))
            .child(widget::button(">").w(28.0).on_click("next_page"));

        UiRoot::new(&book.id,
            widget::panel(FlexDir::Row).gap(2.0)
                .padding(2.0, 2.0, 2.0, 2.0).bg(0xFF_2A1A0E)
                .child(
                    widget::panel(FlexDir::Column).w(104.0)
                        .child(widget::label("Categories").color(0xFF_888888))
                        .child(widget::panel(FlexDir::Column).gap(1.0)
                            .child_many(cats))
                        .child(widget::label("Entries").color(0xFF_888888))
                        .child(widget::panel(FlexDir::Column).gap(1.0)
                            .child_many(entries))
                )
                .child(
                    widget::panel(FlexDir::Column).flex(1.0).gap(2.0)
                        .child(widget::panel(FlexDir::Column).flex(1.0)
                            .child_many(pages))
                        .child(nav)
                )
        )
    }

    fn render_page(page: &BookPage) -> Widget {
        match page {
            BookPage::Text { text, .. } =>
                widget::label(text).color(0xFF_CCCCAA),
            BookPage::Spotlight { item, title, text } => {
                let mut p = widget::panel(FlexDir::Column).gap(2.0);
                if let Some(t) = title { p = p.child(widget::label(t).color(0xFF_FFFF55)); }
                p = p.child(widget::item_slot(&item.id));
                if let Some(t) = text { p = p.child(widget::label(t).color(0xFF_CCCCAA)); }
                p
            }
            BookPage::Crafting { recipe_id, text } => {
                let mut p = widget::panel(FlexDir::Column).gap(2.0);
                p = p.child(widget::label(format!("Crafting: {}", recipe_id)).color(0xFF_888888));
                if let Some(t) = text { p = p.child(widget::label(t).color(0xFF_CCCCAA)); }
                p
            }
            BookPage::Smelting { recipe_id, text } => {
                let mut p = widget::panel(FlexDir::Column).gap(2.0);
                p = p.child(widget::label(format!("Smelting: {}", recipe_id)).color(0xFF_888888));
                if let Some(t) = text { p = p.child(widget::label(t).color(0xFF_CCCCAA)); }
                p
            }
            BookPage::Empty => widget::spacer(),
            _ => widget::label("(unsupported page)").color(0xFF_888888),
        }
    }

    // Helper: add multiple children to a widget
    trait WidgetExt {
        fn child_many(self, children: Vec<Widget>) -> Self;
    }
    impl WidgetExt for Widget {
        fn child_many(mut self, children: Vec<Widget>) -> Self {
            for c in children { self = self.child(c); }
            self
        }
    }
}

// ── JSON serialization ────────────────────────────────────────────────────────

fn esc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"'  => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => {
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            _ => out.push(ch),
        }
    }
    out
}

impl BookPage {
    pub fn to_json(&self) -> String {
        match self {
            Self::Text { text, title } => {
                let t = title.as_deref().map(|s| format!(r#","title":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"text","text":"{}"{}}}"#, esc(text), t)
            }
            Self::Spotlight { item, title, text } => {
                let t = title.as_deref().map(|s| format!(r#","title":"{}""#, esc(s))).unwrap_or_default();
                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"spotlight","item":"{id}"{t}{tx}}}"#, id = esc(&item.id))
            }
            Self::Crafting { recipe_id, text } => {
                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"crafting","recipe":"{}"{}}}"#, esc(recipe_id), tx)
            }
            Self::Smelting { recipe_id, text } => {
                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"smelting","recipe":"{}"{}}}"#, esc(recipe_id), tx)
            }
            Self::Image { texture, title, text, border } => {
                let t = title.as_deref().map(|s| format!(r#","title":"{}""#, esc(s))).unwrap_or_default();
                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"image","texture":"{}","border":{}{}{}}}"#,
                    esc(texture), border, t, tx)
            }
            Self::Entity { entity_type, name, text } => {
                let n = name.as_deref().map(|s| format!(r#","name":"{}""#, esc(s))).unwrap_or_default();
                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"entity","entity":"{}"{}{}}}"#, esc(entity_type), n, tx)
            }
            Self::Relations { entries, text } => {
                let e: String = entries.iter().map(|s| format!(r#""{}""#, esc(s))).collect::<Vec<_>>().join(",");
                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"relations","entries":[{}]{}}}"#, e, tx)
            }
            Self::Empty => r#"{"type":"empty"}"#.to_string(),
            Self::Pattern { op_id, anchor, input, output, text } =>
                format!(r#"{{"type":"pattern","op_id":"{}","anchor":"{}","input":"{}","output":"{}","text":"{}"}}"#,
                    esc(op_id), esc(anchor), esc(input), esc(output), esc(text)),
            Self::Svg { data, title, text } => {
                let t = title.as_deref().map(|s| format!(r#","title":"{}""#, esc(s))).unwrap_or_default();
                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
                format!(r#"{{"type":"svg","data":"{}"{}{}}}"#, esc(data), t, tx)
            }
            Self::CustomText { text, font, color } =>
                format!(r#"{{"type":"custom_text","text":"{}","font_id":"{}","size_px":{},"color":{}}}"#,
                    esc(text), esc(&font.font_id), font.size_px, color),
        }
    }
}

impl BookEntry {
    pub fn to_json(&self) -> String {
        let pages: String = self.pages.iter().map(|p| p.to_json()).collect::<Vec<_>>().join(",");
        let icon = self.icon.as_deref().map(|s| format!(r#","icon":"{}""#, esc(s))).unwrap_or_default();
        let adv = self.advancement.as_deref().map(|s| format!(r#","advancement":"{}""#, esc(s))).unwrap_or_default();
        format!(
            r#"{{"id":"{}","name":"{}","category":"{}","pages":[{}],"secret":{},"priority":{},"read_by_default":{}{}{}}}"#,
            esc(&self.id), esc(&self.name), esc(&self.category), pages,
            self.secret, self.priority, self.read_by_default, icon, adv
        )
    }
}

impl BookCategory {
    pub fn to_json(&self) -> String {
        let desc = self.description.as_deref().map(|s| format!(r#","description":"{}""#, esc(s))).unwrap_or_default();
        let icon = self.icon.as_deref().map(|s| format!(r#","icon":"{}""#, esc(s))).unwrap_or_default();
        format!(
            r#"{{"id":"{}","name":"{}","sortnum":{}{}{}}}"#,
            esc(&self.id), esc(&self.name), self.sortnum, desc, icon
        )
    }
}

impl Book {
    pub fn to_json(&self) -> String {
        let cats: String = self.categories.iter().map(|c| c.to_json()).collect::<Vec<_>>().join(",");
        let entries: String = self.entries.iter().map(|e| e.to_json()).collect::<Vec<_>>().join(",");
        let author = self.author.as_deref().map(|s| format!(r#","author":"{}""#, esc(s))).unwrap_or_default();
        let tab = self.creative_tab.as_deref().map(|s| format!(r#","creative_tab":"{}""#, esc(s))).unwrap_or_default();
        format!(
            r#"{{"id":"{}","name":"{}","nameplate_color":"{}","landing_text":"{}","book_texture":"{}","filler_texture":"{}","model":"{}","show_progress":{},"i18n":{},"use_resource_pack":{},"categories":[{}],"entries":[{}]{}{}}}"#,
            esc(&self.id), esc(&self.name), esc(&self.nameplate_color), esc(&self.landing_text),
            esc(&self.book_texture), esc(&self.filler_texture), esc(&self.model),
            self.show_progress, self.i18n, self.use_resource_pack,
            cats, entries, author, tab
        )
    }
}
// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod wire_format_tests {
    use super::*;

    /// The hand-written `to_json` wire format must stay parseable by the
    /// serde `Deserialize` impls (runtime side of the mod ↔ runtime boundary).
    #[test]
    fn book_to_json_roundtrips_through_serde() {
        let book = Book::new("yog:test", "Test Book")
            .author("Tester")
            .landing_text("hello")
            .add_category(BookCategory {
                id: "c1".into(), name: "Cat".into(),
                description: Some("d".into()),
                icon: Some("yog:item/ruby".into()), icon_svg: None, sortnum: 0,
            })
            .add_entry(BookEntry {
                id: "e1".into(), name: "Entry".into(), category: "c1".into(),
                pages: vec![
                    text_page("plain"),
                    spotlight_page(yog_registry::ItemDef::new("yog:ruby")),
                    crafting_page("yog:r1"),
                    smelting_page("yog:r2"),
                    BookPage::Empty,
                ],
                icon: Some("yog:ruby".into()), icon_svg: None,
                secret: false, priority: 0, read_by_default: false, advancement: None,
            });

        let json = book.to_json();
        let parsed: Book = serde_json::from_str(&json)
            .unwrap_or_else(|e| panic!("wire JSON failed to parse: {e}\njson: {json}"));
        assert_eq!(parsed.id, "yog:test");
        assert_eq!(parsed.entries.len(), 1);
        assert_eq!(parsed.entries[0].pages.len(), 5);
        match &parsed.entries[0].pages[1] {
            BookPage::Spotlight { item, .. } => assert_eq!(item.id, "yog:ruby"),
            p => panic!("expected spotlight, got {p:?}"),
        }
        match &parsed.entries[0].pages[2] {
            BookPage::Crafting { recipe_id, .. } => assert_eq!(recipe_id, "yog:r1"),
            p => panic!("expected crafting, got {p:?}"),
        }
    }
}