Skip to main content

yog_book/
lib.rs

1//! yog-book — in-game book/documentation system for Yog mods (Patchouli-like).
2//! Full replacement: books, categories, entries, page types, macros, textures.
3
4use yog_registry::ItemDef;
5
6// ── Macros ───────────────────────────────────────────────────────────────────
7
8/// A macro substitution (e.g. `$(thing)` → red color span).
9#[derive(Debug, Clone)]
10pub struct BookMacro(pub String, pub String);
11
12// ── Page types ───────────────────────────────────────────────────────────────
13
14/// A single page variant inside a book entry.
15#[derive(Debug, Clone)]
16pub enum BookPage {
17    /// Plain formatted text (Patchouli-style).
18    Text {
19        text: String,
20    },
21    /// Display an item outlined (tooltip on hover).
22    Spotlight {
23        item: ItemDef,
24        title: Option<String>,
25        text: Option<String>,
26    },
27    /// Crafting recipe display (autorenders 3×3 grid).
28    Crafting {
29        recipe_id: String,
30        text: Option<String>,
31    },
32    /// Smelting recipe display.
33    Smelting {
34        recipe_id: String,
35        text: Option<String>,
36    },
37    /// Image overlay page.
38    Image {
39        texture: String,
40        title: Option<String>,
41        text: Option<String>,
42        border: bool,
43    },
44    /// Entity display page (renders a living entity in a box).
45    Entity {
46        entity_type: String,
47        name: Option<String>,
48        text: Option<String>,
49    },
50    /// Link to another entry (like Patchouli's relations).
51    Relations {
52        entries: Vec<String>,
53        text: Option<String>,
54    },
55    /// Empty separator.
56    Empty,
57    /// Custom pattern page for Hexcasting-style mods (like `hexcasting:pattern`).
58    Pattern {
59        op_id: String,
60        anchor: String,
61        input: String,
62        output: String,
63        text: String,
64    },
65}
66
67// ── Category ─────────────────────────────────────────────────────────────────
68
69/// Represents a book category tab (e.g. "Basics", "Patterns").
70#[derive(Debug, Clone)]
71pub struct BookCategory {
72    pub id: String,
73    pub name: String,
74    pub description: Option<String>,
75    /// Texture for the category icon (path like "minecraft:textures/..." or "hexcasting:textures/item/...")
76    pub icon: Option<String>,
77    /// Sort priority (lower = first).
78    pub sortnum: i32,
79}
80
81// ── Entry ────────────────────────────────────────────────────────────────────
82
83/// One entry in a book (like a "page" in the TOC sidebar).
84#[derive(Debug, Clone, Default)]
85pub struct BookEntry {
86    pub id: String,
87    pub name: String,
88    pub category: String,
89    pub pages: Vec<BookPage>,
90    /// Entry icon (item id or texture path).
91    pub icon: Option<String>,
92    /// If true, hides from the book (used for unlocks).
93    pub secret: bool,
94    /// Sort priority (lower = first).
95    pub priority: i32,
96    /// If true, read by default when opening the book.
97    pub read_by_default: bool,
98    /// Advancement required to unlock.
99    pub advancement: Option<String>,
100}
101
102// ── Book ─────────────────────────────────────────────────────────────────────
103
104/// The top-level book definition — replaces `patchouli_books/<id>/book.json`.
105#[derive(Debug, Clone)]
106pub struct Book {
107    pub id: String,
108    pub name: String,
109    pub nameplate_color: String,
110    pub landing_text: String,
111    pub author: Option<String>,
112    pub book_texture: String,
113    pub filler_texture: String,
114    pub model: String,
115    pub categories: Vec<BookCategory>,
116    pub entries: Vec<BookEntry>,
117    pub macros: Vec<BookMacro>,
118    pub use_resource_pack: bool,
119    pub show_progress: bool,
120    pub i18n: bool,
121    pub creative_tab: Option<String>,
122}
123
124impl Book {
125    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
126        Self {
127            id: id.into(),
128            name: name.into(),
129            nameplate_color: "000000".into(),
130            landing_text: String::new(),
131            author: None,
132            book_texture: "yog:textures/gui/book.png".into(),
133            filler_texture: "yog:textures/gui/book_filler.png".into(),
134            model: "minecraft:book".into(),
135            categories: Vec::new(),
136            entries: Vec::new(),
137            macros: Vec::new(),
138            use_resource_pack: false,
139            show_progress: true,
140            i18n: false,
141            creative_tab: None,
142        }
143    }
144
145    pub fn author(mut self, author: impl Into<String>) -> Self {
146        self.author = Some(author.into());
147        self
148    }
149
150    pub fn book_texture(mut self, tex: impl Into<String>) -> Self {
151        self.book_texture = tex.into();
152        self
153    }
154
155    pub fn filler_texture(mut self, tex: impl Into<String>) -> Self {
156        self.filler_texture = tex.into();
157        self
158    }
159
160    pub fn nameplate(mut self, color: impl Into<String>) -> Self {
161        self.nameplate_color = color.into();
162        self
163    }
164
165    pub fn landing_text(mut self, text: impl Into<String>) -> Self {
166        self.landing_text = text.into();
167        self
168    }
169
170    pub fn model(mut self, model: impl Into<String>) -> Self {
171        self.model = model.into();
172        self
173    }
174
175    pub fn creative_tab(mut self, tab: impl Into<String>) -> Self {
176        self.creative_tab = Some(tab.into());
177        self
178    }
179
180    pub fn show_progress(mut self, show: bool) -> Self {
181        self.show_progress = show;
182        self
183    }
184
185    pub fn i18n(mut self, val: bool) -> Self {
186        self.i18n = val;
187        self
188    }
189
190    pub fn use_resource_pack(mut self, val: bool) -> Self {
191        self.use_resource_pack = val;
192        self
193    }
194
195    pub fn add_macro(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
196        self.macros.push(BookMacro(key.into(), value.into()));
197        self
198    }
199
200    pub fn add_category(mut self, category: BookCategory) -> Self {
201        self.categories.push(category);
202        self
203    }
204
205    pub fn add_entry(mut self, entry: BookEntry) -> Self {
206        self.entries.push(entry);
207        self
208    }
209}
210
211impl Default for Book {
212    fn default() -> Self {
213        Self::new("yog:default", "Unknown Book")
214    }
215}
216
217// ── Registry ─────────────────────────────────────────────────────────────────
218
219/// Global registry for all in-game books.
220#[derive(Debug, Default)]
221pub struct BookRegistry {
222    books: std::collections::HashMap<String, Book>,
223}
224
225impl BookRegistry {
226    pub fn register(&mut self, book: Book) {
227        self.books.insert(book.id.clone(), book);
228    }
229
230    pub fn get(&self, id: &str) -> Option<&Book> {
231        self.books.get(id)
232    }
233
234    pub fn all(&self) -> impl Iterator<Item = &Book> {
235        self.books.values()
236    }
237}
238
239// ── Builder helpers ──────────────────────────────────────────────────────────
240
241pub fn text_page(text: impl Into<String>) -> BookPage {
242    BookPage::Text { text: text.into() }
243}
244
245pub fn spotlight_page(item: ItemDef) -> BookPage {
246    BookPage::Spotlight { item, title: None, text: None }
247}
248
249pub fn crafting_page(recipe_id: impl Into<String>) -> BookPage {
250    BookPage::Crafting { recipe_id: recipe_id.into(), text: None }
251}
252
253pub fn crafting_page_with_text(recipe_id: impl Into<String>, text: impl Into<String>) -> BookPage {
254    BookPage::Crafting { recipe_id: recipe_id.into(), text: Some(text.into()) }
255}
256
257pub fn smelting_page(recipe_id: impl Into<String>) -> BookPage {
258    BookPage::Smelting { recipe_id: recipe_id.into(), text: None }
259}
260
261pub fn image_page(texture: impl Into<String>) -> BookPage {
262    BookPage::Image { texture: texture.into(), title: None, text: None, border: true }
263}
264
265pub fn entity_page(entity_type: impl Into<String>) -> BookPage {
266    BookPage::Entity { entity_type: entity_type.into(), name: None, text: None }
267}
268
269pub fn relations_page(entries: Vec<String>) -> BookPage {
270    BookPage::Relations { entries, text: None }
271}
272
273pub 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 {
274    BookPage::Pattern {
275        op_id: op_id.into(),
276        anchor: anchor.into(),
277        input: input.into(),
278        output: output.into(),
279        text: text.into(),
280    }
281}
282
283// ── JSON serialization ────────────────────────────────────────────────────────
284
285fn esc(s: &str) -> String {
286    s.replace('\\', "\\\\").replace('"', "\\\"")
287}
288
289impl BookPage {
290    pub fn to_json(&self) -> String {
291        match self {
292            Self::Text { text } =>
293                format!(r#"{{"type":"text","text":"{}"}}"#, esc(text)),
294            Self::Spotlight { item, title, text } => {
295                let t = title.as_deref().map(|s| format!(r#","title":"{}""#, esc(s))).unwrap_or_default();
296                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
297                format!(r#"{{"type":"spotlight","item":"{id}"{t}{tx}}}"#, id = esc(&item.id))
298            }
299            Self::Crafting { recipe_id, text } => {
300                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
301                format!(r#"{{"type":"crafting","recipe":"{}"{}}}"#, esc(recipe_id), tx)
302            }
303            Self::Smelting { recipe_id, text } => {
304                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
305                format!(r#"{{"type":"smelting","recipe":"{}"{}}}"#, esc(recipe_id), tx)
306            }
307            Self::Image { texture, title, text, border } => {
308                let t = title.as_deref().map(|s| format!(r#","title":"{}""#, esc(s))).unwrap_or_default();
309                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
310                format!(r#"{{"type":"image","texture":"{}","border":{}{}{}}}"#,
311                    esc(texture), border, t, tx)
312            }
313            Self::Entity { entity_type, name, text } => {
314                let n = name.as_deref().map(|s| format!(r#","name":"{}""#, esc(s))).unwrap_or_default();
315                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
316                format!(r#"{{"type":"entity","entity":"{}"{}{}}}"#, esc(entity_type), n, tx)
317            }
318            Self::Relations { entries, text } => {
319                let e: String = entries.iter().map(|s| format!(r#""{}""#, esc(s))).collect::<Vec<_>>().join(",");
320                let tx = text.as_deref().map(|s| format!(r#","text":"{}""#, esc(s))).unwrap_or_default();
321                format!(r#"{{"type":"relations","entries":[{}]{}}}"#, e, tx)
322            }
323            Self::Empty => r#"{"type":"empty"}"#.to_string(),
324            Self::Pattern { op_id, anchor, input, output, text } =>
325                format!(r#"{{"type":"pattern","op_id":"{}","anchor":"{}","input":"{}","output":"{}","text":"{}"}}"#,
326                    esc(op_id), esc(anchor), esc(input), esc(output), esc(text)),
327        }
328    }
329}
330
331impl BookEntry {
332    pub fn to_json(&self) -> String {
333        let pages: String = self.pages.iter().map(|p| p.to_json()).collect::<Vec<_>>().join(",");
334        let icon = self.icon.as_deref().map(|s| format!(r#","icon":"{}""#, esc(s))).unwrap_or_default();
335        let adv = self.advancement.as_deref().map(|s| format!(r#","advancement":"{}""#, esc(s))).unwrap_or_default();
336        format!(
337            r#"{{"id":"{}","name":"{}","category":"{}","pages":[{}],"secret":{},"priority":{},"read_by_default":{}{}{}}}"#,
338            esc(&self.id), esc(&self.name), esc(&self.category), pages,
339            self.secret, self.priority, self.read_by_default, icon, adv
340        )
341    }
342}
343
344impl BookCategory {
345    pub fn to_json(&self) -> String {
346        let desc = self.description.as_deref().map(|s| format!(r#","description":"{}""#, esc(s))).unwrap_or_default();
347        let icon = self.icon.as_deref().map(|s| format!(r#","icon":"{}""#, esc(s))).unwrap_or_default();
348        format!(
349            r#"{{"id":"{}","name":"{}","sortnum":{}{}{}}}"#,
350            esc(&self.id), esc(&self.name), self.sortnum, desc, icon
351        )
352    }
353}
354
355impl Book {
356    pub fn to_json(&self) -> String {
357        let cats: String = self.categories.iter().map(|c| c.to_json()).collect::<Vec<_>>().join(",");
358        let entries: String = self.entries.iter().map(|e| e.to_json()).collect::<Vec<_>>().join(",");
359        let author = self.author.as_deref().map(|s| format!(r#","author":"{}""#, esc(s))).unwrap_or_default();
360        let tab = self.creative_tab.as_deref().map(|s| format!(r#","creative_tab":"{}""#, esc(s))).unwrap_or_default();
361        format!(
362            r#"{{"id":"{}","name":"{}","nameplate_color":"{}","landing_text":"{}","book_texture":"{}","filler_texture":"{}","model":"{}","show_progress":{},"i18n":{},"use_resource_pack":{},"categories":[{}],"entries":[{}]{}{}}}"#,
363            esc(&self.id), esc(&self.name), esc(&self.nameplate_color), esc(&self.landing_text),
364            esc(&self.book_texture), esc(&self.filler_texture), esc(&self.model),
365            self.show_progress, self.i18n, self.use_resource_pack,
366            cats, entries, author, tab
367        )
368    }
369}