Skip to main content

yog_book/
renderer.rs

1//! Book renderer — ties together yog-ui layout, yog-gfx GPU pipeline,
2//! SVG icon rasterization, and custom font rendering.
3
4use std::collections::HashMap;
5use yog_gfx::{GfxContext, gl, core::{DrawMode, DataType, blend}};
6use yog_ui::{widget, FlexDir, Align, UiRoot};
7
8use crate::{Book, BookPage};
9use crate::state::BookViewState;
10use crate::theme::BookTheme;
11use crate::font::{BookFontRegistry, FontAtlas};
12use crate::svg;
13
14// Patchouli-compatible book texture layout (512×256 sprite sheet).
15// UV coordinates are in pixels on a 512×256 sheet.
16// The full open-book background occupies 272×180 at UV (0,0).
17pub const BOOK_TEX_W: f32   = 512.0;
18pub const BOOK_TEX_H: f32   = 256.0;
19// Open-book dimensions in texture-space
20pub const BK_W: f32         = 272.0;
21pub const BK_H: f32         = 180.0;
22// Per-page dimensions and offsets (in book-local coords)
23pub const PAGE_W: f32       = 116.0;
24pub const PAGE_H: f32       = 156.0;
25pub const TOP_PAD: f32      = 18.0;   // vertical space above page text area
26pub const LEFT_X: f32       = 15.0;   // left page X inside book
27pub const RIGHT_X: f32      = 141.0;  // right page X inside book
28// Separator strip UV origin on the sprite sheet
29pub const SEP_U: f32        = 140.0;
30pub const SEP_V: f32        = 180.0;
31pub const SEP_W: f32        = 110.0;
32pub const SEP_H: f32        = 3.0;
33
34// ── Vertex for the custom 2D shader (pos + uv + color) ───────────────────────
35
36#[repr(C)]
37#[derive(Copy, Clone)]
38struct Vert { x: f32, y: f32, u: f32, v: f32, r: f32, g: f32, b: f32, a: f32 }
39
40fn rgba_f(c: u32) -> (f32, f32, f32, f32) {
41    let a = ((c >> 24) & 0xFF) as f32 / 255.0;
42    let r = ((c >> 16) & 0xFF) as f32 / 255.0;
43    let g = ((c >>  8) & 0xFF) as f32 / 255.0;
44    let b = ( c        & 0xFF) as f32 / 255.0;
45    (r, g, b, a)
46}
47
48fn quad(verts: &mut Vec<Vert>, x: f32, y: f32, w: f32, h: f32,
49        u0: f32, v0: f32, u1: f32, v1: f32, color: u32) {
50    let (r, g, b, a) = rgba_f(color);
51    let p = [
52        Vert { x,        y,        u: u0, v: v0, r, g, b, a },
53        Vert { x: x+w,   y,        u: u1, v: v0, r, g, b, a },
54        Vert { x,        y: y+h,   u: u0, v: v1, r, g, b, a },
55        Vert { x: x+w,   y: y+h,   u: u1, v: v1, r, g, b, a },
56    ];
57    // two triangles: 0,1,2  1,3,2
58    verts.extend_from_slice(&[p[0], p[1], p[2], p[1], p[3], p[2]]);
59}
60
61// ── GLSL shaders ─────────────────────────────────────────────────────────────
62
63const VERT: &str = r#"
64#version 330 core
65layout(location = 0) in vec2 aPos;
66layout(location = 1) in vec2 aUv;
67layout(location = 2) in vec4 aCol;
68out vec2 fUv;
69out vec4 fCol;
70uniform vec2 uScreen;
71void main() {
72    fUv  = aUv;
73    fCol = aCol;
74    vec2 ndc = aPos / uScreen * 2.0 - vec2(1.0);
75    gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
76}
77"#;
78
79const FRAG: &str = r#"
80#version 330 core
81in vec2 fUv;
82in vec4 fCol;
83out vec4 outColor;
84uniform sampler2D uTex;
85uniform int uMode;  // 0 = solid color, 1 = RGBA texture, 2 = alpha-only (font)
86void main() {
87    if (uMode == 0) {
88        outColor = fCol;
89    } else if (uMode == 1) {
90        outColor = texture(uTex, fUv) * fCol;
91    } else {
92        float alpha = texture(uTex, fUv).a;
93        outColor = vec4(fCol.rgb, fCol.a * alpha);
94    }
95}
96"#;
97
98// ── Embedded textures ─────────────────────────────────────────────────────────
99
100static BOOK_PNG:     &[u8] = include_bytes!("../assets/book_brown.png");
101static CRAFTING_PNG: &[u8] = include_bytes!("../assets/crafting.png");
102
103fn decode_png(data: &[u8]) -> Option<(Vec<u8>, u32, u32)> {
104    use png::Decoder;
105    let decoder = Decoder::new(std::io::Cursor::new(data));
106    let mut reader = decoder.read_info().ok()?;
107    let mut buf = vec![0u8; reader.output_buffer_size()];
108    let info = reader.next_frame(&mut buf).ok()?;
109    let rgba = match info.color_type {
110        png::ColorType::Rgba => buf[..info.buffer_size()].to_vec(),
111        png::ColorType::Rgb  => {
112            let rgb = &buf[..info.buffer_size()];
113            let mut out = Vec::with_capacity(rgb.len() / 3 * 4);
114            for px in rgb.chunks(3) { out.extend_from_slice(px); out.push(255); }
115            out
116        }
117        _ => return None,
118    };
119    Some((rgba, info.width, info.height))
120}
121
122// ── GL resource cache ─────────────────────────────────────────────────────────
123
124struct BookGl {
125    prog:         gl::ShaderProgram,
126    vao:          gl::VertexArray,
127    vbo:          gl::Buffer,
128    book_tex:     Option<(gl::Texture, u32, u32)>,
129    crafting_tex: Option<(gl::Texture, u32, u32)>,
130    svg_tex:      HashMap<u64, (gl::Texture, u32, u32)>,
131    font_atlas:   HashMap<u64, (gl::Texture, FontAtlas)>,
132}
133
134impl BookGl {
135    fn init(ctx: &GfxContext) -> Option<Self> {
136        let prog = ctx.create_shader(VERT, FRAG).ok()?;
137        let vbo  = ctx.create_buffer();
138        let vao  = ctx.create_vao();
139
140        const STRIDE: u32 = 32; // 8 × f32
141        vao.attrib(ctx, &vbo, 0, 2, DataType::F32, false, STRIDE, 0);  // pos
142        vao.attrib(ctx, &vbo, 1, 2, DataType::F32, false, STRIDE, 8);  // uv
143        vao.attrib(ctx, &vbo, 2, 4, DataType::F32, false, STRIDE, 16); // col
144
145        let load = |data: &[u8]| decode_png(data).map(|(rgba, w, h)| {
146            let tex = ctx.create_texture_rgba(w, h, &rgba, true);
147            (tex, w, h)
148        });
149        let book_tex     = load(BOOK_PNG);
150        let crafting_tex = load(CRAFTING_PNG);
151
152        Some(BookGl { prog, vao, vbo, book_tex, crafting_tex,
153                      svg_tex: HashMap::new(), font_atlas: HashMap::new() })
154    }
155
156    fn svg_tex(&mut self, ctx: &GfxContext, hash: u64, data: &str, w: u32, h: u32)
157        -> Option<&(gl::Texture, u32, u32)>
158    {
159        if !self.svg_tex.contains_key(&hash) {
160            let pixels = svg::rasterize(data, w, h)?;
161            let tex = ctx.create_texture_rgba(w, h, &pixels, true);
162            self.svg_tex.insert(hash, (tex, w, h));
163        }
164        self.svg_tex.get(&hash)
165    }
166
167    fn flush(&self, ctx: &GfxContext, verts: &[Vert]) {
168        if verts.is_empty() { return; }
169        unsafe { self.vbo.upload(ctx, verts, true); }
170        ctx.draw_arrays(&self.vao, &self.prog, DrawMode::Triangles, 0, verts.len() as u32);
171    }
172}
173
174// ── Draw helpers ──────────────────────────────────────────────────────────────
175
176impl BookGl {
177    fn begin_frame(&self, ctx: &GfxContext, sw: f32, sh: f32) {
178        ctx.set_blend(true, blend::SRC_ALPHA, blend::ONE_MINUS_SRC_ALPHA);
179        ctx.set_depth(false, false);
180        self.prog.uniform_2f(ctx, "uScreen", sw, sh);
181        self.prog.uniform_1i(ctx, "uTex", 0);
182    }
183
184    /// Blit a subrect of a sprite sheet at an arbitrary screen position.
185    fn draw_book_sprite(&self, ctx: &GfxContext, spr: &BgSprite) {
186        let sheet = match spr.sheet {
187            SpriteSheet::Book     => &self.book_tex,
188            SpriteSheet::Crafting => &self.crafting_tex,
189        };
190        let Some((tex, tw, th)) = sheet else { return };
191        let u0 = spr.u  / *tw as f32;
192        let v0 = spr.v  / *th as f32;
193        let u1 = (spr.u + spr.uw) / *tw as f32;
194        let v1 = (spr.v + spr.uh) / *th as f32;
195        self.prog.uniform_1i(ctx, "uMode", 1);
196        ctx.bind_texture(0, tex);
197        let mut v = Vec::with_capacity(6);
198        quad(&mut v, spr.x, spr.y, spr.w, spr.h, u0, v0, u1, v1, 0xFF_FFFFFF);
199        self.flush(ctx, &v);
200    }
201
202    /// Blit the open-book background from the embedded book texture.
203    fn draw_book_bg(&self, ctx: &GfxContext, bx: f32, by: f32, bw: f32, bh: f32) {
204        let Some((tex, tw, th)) = &self.book_tex else { return };
205        let su = BK_W / *tw as f32;
206        let sv = BK_H / *th as f32;
207        self.prog.uniform_1i(ctx, "uMode", 1);
208        ctx.bind_texture(0, tex);
209        let mut v = Vec::with_capacity(6);
210        quad(&mut v, bx, by, bw, bh, 0.0, 0.0, su, sv, 0xFF_FFFFFF);
211        self.flush(ctx, &v);
212    }
213
214    fn draw_svg(&mut self, ctx: &GfxContext, data: &str, x: f32, y: f32, w: f32, h: f32) {
215        let hash = svg::svg_hash(data);
216        let tw = w as u32; let th = h as u32;
217        if let Some(&(tex, _, _)) = self.svg_tex(ctx, hash, data, tw, th) {
218            self.prog.uniform_1i(ctx, "uMode", 1);
219            ctx.bind_texture(0, &tex);
220            let mut v = Vec::with_capacity(6);
221            quad(&mut v, x, y, w, h, 0.0, 0.0, 1.0, 1.0, 0xFF_FFFFFF);
222            self.flush(ctx, &v);
223        }
224    }
225
226    fn draw_text_custom(&mut self, ctx: &GfxContext, ttf: &[u8], size_px: f32,
227                        text: &str, mut x: f32, y: f32, color: u32) {
228        let hash = font_hash(ttf);
229        if !self.font_atlas.contains_key(&hash) {
230            if let Some(atlas) = FontAtlas::build(ttf, size_px) {
231                let tex = ctx.create_texture_rgba(
232                    atlas.atlas_size, atlas.atlas_size, &atlas.pixels, true);
233                self.font_atlas.insert(hash, (tex, atlas));
234            }
235        }
236        // Get raw pointers so the borrow of self.font_atlas ends before we call
237        // self.prog / self.flush, which also borrow fields of self.
238        let ptrs = self.font_atlas.get(&hash)
239            .map(|(t, a)| (t as *const gl::Texture, a as *const FontAtlas));
240        if let Some((tex_ptr, atlas_ptr)) = ptrs {
241            // SAFETY: we hold &mut self; font_atlas is not mutated below.
242            let tex   = unsafe { &*tex_ptr   };
243            let atlas = unsafe { &*atlas_ptr };
244            self.prog.uniform_1i(ctx, "uMode", 2);
245            ctx.bind_texture(0, tex);
246            let baseline = y + size_px;
247            let mut verts = Vec::new();
248            for ch in text.chars() {
249                if let Some(g) = atlas.glyphs.get(&ch) {
250                    if g.width > 0 {
251                        let gx = x + g.xoff;
252                        let gy = baseline - g.yoff - g.height as f32;
253                        quad(&mut verts, gx, gy, g.width as f32, g.height as f32,
254                             g.u0, g.v0, g.u1, g.v1, color);
255                    }
256                    x += g.advance;
257                }
258            }
259            self.flush(ctx, &verts);
260        }
261    }
262}
263
264fn font_hash(data: &[u8]) -> u64 {
265    use std::hash::{Hash, Hasher};
266    let mut h = std::collections::hash_map::DefaultHasher::new();
267    data.hash(&mut h);
268    h.finish()
269}
270
271// ── Background sprite (texture blit, drawn before yog-ui) ────────────────────
272
273#[derive(Clone, Copy, PartialEq)]
274pub(crate) enum SpriteSheet { Book, Crafting }
275
276/// A subrect blit from one of the embedded sprite sheets, drawn before yog-ui.
277#[derive(Clone)]
278pub(crate) struct BgSprite {
279    pub sheet: SpriteSheet,
280    /// Source rect in pixels on the sheet.
281    pub u: f32, pub v: f32, pub uw: f32, pub uh: f32,
282    /// Destination on screen.
283    pub x: f32, pub y: f32, pub w: f32, pub h: f32,
284}
285
286// ── Pending overlay draw commands ─────────────────────────────────────────────
287
288#[derive(Clone)]
289pub(crate) enum OverlayCmd {
290    Svg    { data: String, x: f32, y: f32, w: f32, h: f32 },
291    Text   { text: String, font: crate::font::BookFont, x: f32, y: f32, color: u32 },
292    /// MC default-font text rendered via draw2d (e.g. nameplate title/subtitle).
293    McText { text: String, x: f32, y: f32, color: u32 },
294    /// Item icon rendered through our GL pipeline from an MC-managed texture.
295    McItem { item_id: String, x: f32, y: f32, w: f32, h: f32 },
296}
297
298// ── Recipe visuals (parsed from registered recipe JSON) ───────────────────────
299
300#[derive(Clone)]
301pub(crate) enum RecipeVis {
302    Shaped    { grid: Vec<Option<String>>, width: usize, output: String, count: u32 },
303    Shapeless { ingredients: Vec<String>, output: String, count: u32 },
304    Smelting  { input: String, output: String },
305}
306
307fn parse_recipe(json: &str) -> Option<RecipeVis> {
308    let v: serde_json::Value = serde_json::from_str(json).ok()?;
309    match v.get("type")?.as_str()? {
310        "minecraft:crafting_shaped" => {
311            let pattern: Vec<&str> = v.get("pattern")?.as_array()?
312                .iter().filter_map(|p| p.as_str()).collect();
313            let width = pattern.iter().map(|r| r.chars().count()).max()?.max(1);
314            let key = v.get("key")?.as_object()?;
315            let mut grid = Vec::new();
316            for row in &pattern {
317                let mut chars: Vec<char> = row.chars().collect();
318                chars.resize(width, ' ');
319                for ch in chars {
320                    grid.push(key.get(&ch.to_string())
321                        .and_then(|k| k.get("item")).and_then(|i| i.as_str())
322                        .map(str::to_owned));
323                }
324            }
325            let result = v.get("result")?;
326            Some(RecipeVis::Shaped {
327                grid, width,
328                output: result.get("item")?.as_str()?.to_owned(),
329                count:  result.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as u32,
330            })
331        }
332        "minecraft:crafting_shapeless" => {
333            let ingredients = v.get("ingredients")?.as_array()?.iter()
334                .filter_map(|i| i.get("item").and_then(|x| x.as_str()).map(str::to_owned))
335                .collect();
336            let result = v.get("result")?;
337            Some(RecipeVis::Shapeless {
338                ingredients,
339                output: result.get("item")?.as_str()?.to_owned(),
340                count:  result.get("count").and_then(|c| c.as_u64()).unwrap_or(1) as u32,
341            })
342        }
343        "minecraft:smelting" | "minecraft:blasting"
344        | "minecraft:smoking" | "minecraft:campfire_cooking" => {
345            Some(RecipeVis::Smelting {
346                input:  v.get("ingredient")?.get("item")?.as_str()?.to_owned(),
347                output: v.get("result")?.as_str()?.to_owned(),
348            })
349        }
350        _ => None,
351    }
352}
353
354/// Normalize icon ids like "yog:item/ruby" / "yog:block/x" to registry item
355/// ids ("yog:ruby") accepted by the MC item renderer.
356fn normalize_item_id(id: &str) -> String {
357    let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
358    let name = path.trim_start_matches("item/").trim_start_matches("block/");
359    format!("{ns}:{name}")
360}
361
362/// "yog:ruby_block" → "Ruby Block" (fallback display name from an item id).
363fn pretty_item_name(id: &str) -> String {
364    let name = id.rsplit(':').next().unwrap_or(id);
365    name.split('_')
366        .map(|w| {
367            let mut c = w.chars();
368            match c.next() {
369                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
370                None    => String::new(),
371            }
372        })
373        .collect::<Vec<_>>()
374        .join(" ")
375}
376
377// ── BookRenderer ──────────────────────────────────────────────────────────────
378
379pub struct BookRenderer {
380    pub book:  Book,
381    pub state: BookViewState,
382    pub theme: BookTheme,
383    fonts:        BookFontRegistry,
384    recipes:      HashMap<String, RecipeVis>,
385    gl:           Option<BookGl>,
386    pub ui:       Option<UiRoot>,
387    bg_sprites:   Vec<BgSprite>,
388    overlays:     Vec<OverlayCmd>,
389    dirty:   bool,
390    last_sw: f32,
391    last_sh: f32,
392}
393
394impl BookRenderer {
395    pub fn new(book: Book) -> Self {
396        let theme = BookTheme::default().with_nameplate(&book.nameplate_color);
397        Self {
398            book,
399            state: BookViewState::default(),
400            theme,
401            fonts: BookFontRegistry::default(),
402            recipes: HashMap::new(),
403            gl: None,
404            ui: None,
405            bg_sprites: Vec::new(),
406            overlays: Vec::new(),
407            dirty: true,
408            last_sw: 0.0,
409            last_sh: 0.0,
410        }
411    }
412
413    pub fn handle_event(&mut self, ev: &str) {
414        if self.state.handle(ev, &self.book) {
415            self.dirty = true;
416        }
417    }
418
419    /// Register a custom TTF/OTF font for use in `BookPage::CustomText`.
420    pub fn register_font(&mut self, id: impl Into<String>, ttf: Vec<u8>) {
421        self.fonts.register(id, ttf);
422    }
423
424    /// Register a recipe (vanilla recipe JSON) so Crafting/Smelting pages can
425    /// render it visually. Unknown recipe types are ignored.
426    pub fn add_recipe(&mut self, id: impl Into<String>, json: &str) {
427        if let Some(vis) = parse_recipe(json) {
428            self.recipes.insert(id.into(), vis);
429            self.dirty = true;
430        }
431    }
432
433    pub fn render(&mut self, ctx: &GfxContext, sw: f32, sh: f32) {
434        // Lazy GL init.
435        if self.gl.is_none() {
436            self.gl = BookGl::init(ctx);
437        }
438
439        // Render at Patchouli-native size (272×180 GUI pixels). Scale DOWN only
440        // if the screen is smaller; never scale up (MC font is designed for 1×).
441        let scale = ((sw - 16.0) / BK_W).min((sh - 16.0) / BK_H).min(1.0).max(0.4);
442        let bw = BK_W * scale;
443        let bh = BK_H * scale;
444        let bx = (sw - bw) / 2.0;
445        let by = (sh - bh) / 2.0;
446
447        // Rebuild widget tree if dirty or screen resized.
448        if self.dirty || sw != self.last_sw || sh != self.last_sh {
449            let (root, bg_sprites, overlays) = build_ui(&self.book, &self.state, &self.theme, &self.recipes, sw, sh, bx, by, bw, bh);
450            self.ui = Some(root);
451            self.bg_sprites = bg_sprites;
452            self.overlays = overlays;
453            self.dirty = false;
454            self.last_sw = sw;
455            self.last_sh = sh;
456        }
457
458        // 1. Draw book background texture first.
459        if let Some(gl) = &mut self.gl {
460            gl.begin_frame(ctx, sw, sh);
461            gl.draw_book_bg(ctx, bx, by, bw, bh);
462        }
463
464        // 1b. Background sprites (nameplate banner, separator lines) from book texture.
465        if let Some(gl) = &mut self.gl {
466            for spr in &self.bg_sprites {
467                gl.draw_book_sprite(ctx, spr);
468            }
469        }
470
471        // 2. yog-ui: text, buttons, icons (transparent BG — texture is already there).
472        if let Some(ui) = &mut self.ui {
473            if ui.needs_layout { ui.layout(sw, sh); }
474            ui.render(ctx);
475        }
476
477        // 3. Custom GL overlays (SVG icons, custom font text) — raw GL first.
478        if let Some(gl) = &mut self.gl {
479            gl.begin_frame(ctx, sw, sh);
480            for ov in self.overlays.clone() {
481                match ov {
482                    OverlayCmd::Svg  { data, x, y, w, h } =>
483                        gl.draw_svg(ctx, &data, x, y, w, h),
484                    OverlayCmd::Text { text, font, x, y, color } => {
485                        if let Some(ttf) = self.fonts.get(&font.font_id) {
486                            gl.draw_text_custom(ctx, ttf, font.size_px, &text, x, y, color);
487                        }
488                    }
489                    OverlayCmd::McText { .. } | OverlayCmd::McItem { .. } => {}
490                }
491            }
492        }
493
494        // 4. MC-pipeline overlays (item stacks, MC-font text) — after all raw
495        //    GL, because item rendering resyncs and mutates MC's GL state.
496        for ov in self.overlays.clone() {
497            match ov {
498                OverlayCmd::McItem { item_id, x, y, w, h } => {
499                    ctx.draw2d().item(&normalize_item_id(&item_id), x, y, w.min(h));
500                }
501                OverlayCmd::McText { text, x, y, color } => {
502                    ctx.draw2d().text(&text, x, y, color, false);
503                }
504                _ => {}
505            }
506        }
507    }
508}
509
510// ── UI builder ────────────────────────────────────────────────────────────────
511
512/// Book label: MC font, no drop-shadow (Patchouli draws book text shadowless).
513fn lbl(text: impl Into<String>) -> widget::Widget { widget::label(text).shadow(false) }
514/// Book button: no drop-shadow.
515fn btn(text: impl Into<String>) -> widget::Widget { widget::button(text).shadow(false) }
516
517/// Build the yog-ui widget tree + bg sprites + overlay commands for the current book state.
518/// `bx/by/bw/bh` are the screen-space book rect (same values used to blit the bg texture).
519fn build_ui(book: &Book, state: &BookViewState, theme: &BookTheme,
520             recipes: &HashMap<String, RecipeVis>,
521             sw: f32, sh: f32,
522             bx: f32, by: f32, bw: f32, bh: f32) -> (UiRoot, Vec<BgSprite>, Vec<OverlayCmd>) {
523    let _ = (sw, sh);
524    let mut bg_sprites: Vec<BgSprite> = Vec::new();
525    let mut overlays:   Vec<OverlayCmd> = Vec::new();
526
527    // Scale from Patchouli's fixed BK_W×BK_H coordinate space → actual bw×bh.
528    let sx = bw / BK_W;
529    let sy = bh / BK_H;
530
531    // In book-local: left page starts at x=LEFT_X, right at RIGHT_X, both y=TOP_PAD.
532    let pw = PAGE_W * sx;
533    let ph = PAGE_H * sy;
534    let spine_gap = (RIGHT_X - LEFT_X - PAGE_W) * sx; // ≈10px scaled
535
536    // Content x/y in screen space (for SVG overlay positioning).
537    let lx = bx + LEFT_X  * sx;
538    let rx = bx + RIGHT_X * sx;
539    let py = by + TOP_PAD  * sy;
540
541    // Separator x offset within a page: centered = PAGE_W/2 - SEP_W/2 = 58-55 = 3.
542    let sep_cx = (PAGE_W / 2.0 - SEP_W / 2.0) * sx; // = 3*sx
543
544    if state.at_home {
545        // Nameplate banner: book-local (-8, 12) from LEFT_PAGE_X, size 140×31.
546        bg_sprites.push(BgSprite {
547            sheet: SpriteSheet::Book,
548            u: 0.0, v: 180.0, uw: 140.0, uh: 31.0,
549            x: bx + (LEFT_X - 8.0) * sx,
550            y: by + 12.0 * sy,
551            w: 140.0 * sx,
552            h: 31.0 * sy,
553        });
554        // Separator below "Categories" header on right page (y=12 page-local), centered.
555        bg_sprites.push(BgSprite {
556            sheet: SpriteSheet::Book,
557            u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
558            x: rx + sep_cx,
559            y: by + (TOP_PAD + 12.0) * sy,
560            w: SEP_W * sx,
561            h: (SEP_H * sy).max(1.0),
562        });
563    } else {
564        // Entry view: separator on right page below category name (y=12 page-local).
565        bg_sprites.push(BgSprite {
566            sheet: SpriteSheet::Book,
567            u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
568            x: rx + sep_cx,
569            y: by + (TOP_PAD + 12.0) * sy,
570            w: SEP_W * sx,
571            h: (SEP_H * sy).max(1.0),
572        });
573    }
574
575    let (left_page, right_page) = if state.at_home {
576        let l = build_landing_left(book, theme, pw, ph, lx, py, sx, sy, bx, by, &mut overlays);
577        let r = build_categories_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
578        (l, r)
579    } else {
580        let l = build_entry_left(book, state, theme, recipes, pw, ph, lx, py, sx, sy, sep_cx, &mut bg_sprites, &mut overlays);
581        let r = build_entries_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
582        (l, r)
583    };
584
585    // Root row spans the full book width.
586    // padding-left = LEFT_X*sx offsets both pages from the left cover edge.
587    // padding-top  = TOP_PAD*sy offsets from the header banner.
588    // spine_gap spacer sits between the two pages.
589    let root_widget = widget::panel(FlexDir::Row)
590        .w(bw).h(bh)
591        .padding(TOP_PAD * sy, 0.0, 0.0, LEFT_X * sx)
592        .child(left_page)
593        .child(widget::spacer().w(spine_gap))  // spine gap
594        .child(right_page);
595
596    // Outer shell: positions the book on screen via a full-screen transparent Row.
597    // We use a Column + Row arrangement to apply top/left offsets without margin support.
598    let outer = widget::panel(FlexDir::Column)
599        .w(bw).h(bh)
600        .child(root_widget);
601
602    // Screen-level container: positions book at (bx, by).
603    // bx offset via padding, by offset via padding-top.
604    // Note: layout computes from (0,0), so we pass bx/by into the UiRoot manually
605    // by wrapping in a full-screen panel with the right padding.
606    let screen_root = widget::panel(FlexDir::Row)
607        .padding(by, 0.0, 0.0, bx)
608        .child(outer);
609
610    let ui = UiRoot::new(&book.id, screen_root);
611    (ui, bg_sprites, overlays)
612}
613
614// ── Left page: landing (home view) ───────────────────────────────────────────
615
616fn build_landing_left(
617    book: &Book, theme: &BookTheme,
618    page_w: f32, page_h: f32,
619    _lx: f32, _py: f32,
620    sx: f32, sy: f32,
621    bx: f32, by: f32,
622    overlays: &mut Vec<OverlayCmd>,
623) -> widget::Widget {
624    // Patchouli: title at book-local (13, 16), subtitle at (24, 24).
625    // These overlap the nameplate sprite which is above/within the page top.
626    overlays.push(OverlayCmd::McText {
627        text: book.name.clone(),
628        x: bx + 13.0 * sx,
629        y: by + 16.0 * sy,
630        color: theme.nameplate,
631    });
632    if let Some(author) = &book.author {
633        overlays.push(OverlayCmd::McText {
634            text: format!("by {}", author),
635            x: bx + 24.0 * sx,
636            y: by + 24.0 * sy,
637            color: theme.nameplate,
638        });
639    }
640
641    // Widget content: landing text + entry count.
642    // Landing text starts at page-local y=25 (= book-local y=43).
643    // We push it down with top padding = 25*sy.
644    let mut col = widget::panel(FlexDir::Column)
645        .w(page_w).h(page_h)
646        .padding(25.0 * sy, 6.0, 4.0, 4.0)
647        .gap(0.0);
648
649    for para in book.landing_text.split('\n') {
650        if para.is_empty() {
651            col = col.child(widget::spacer().h(4.0 * sy));
652        } else {
653            col = col.child(lbl(para).color(theme.text));
654        }
655    }
656
657    let total = book.entries.len();
658    col = col.child(widget::spacer().flex(1.0));
659    col = col.child(
660        lbl(format!("{} entries", total))
661            .color(theme.nav).h(9.0 * sy).align(Align::Center)
662    );
663    col
664}
665
666// ── Right page: category list (home view) ────────────────────────────────────
667
668fn build_categories_right(
669    book: &Book, state: &BookViewState, theme: &BookTheme,
670    page_w: f32, page_h: f32,
671    rx: f32, py: f32,
672    sx: f32, sy: f32,
673    overlays: &mut Vec<OverlayCmd>,
674) -> widget::Widget {
675    // Patchouli right-page layout (landing):
676    //   "Categories" header at page-local y=0, centered
677    //   Separator at page-local y=12 (drawn as bg sprite, not here)
678    //   4-column 24×24 icon grid starting at page-local (10, 25)
679    let cell_w = 24.0 * sx;
680    let cell_h = 24.0 * sy;
681    let grid_pad_left = 10.0 * sx;
682    let header_h = 9.0 * sy;
683
684    let mut col = widget::panel(FlexDir::Column)
685        .w(page_w).h(page_h)
686        .padding(0.0, 4.0, 4.0, 0.0)
687        .gap(0.0);
688
689    col = col.child(
690        lbl("Categories").color(theme.divider).h(header_h).align(Align::Center)
691    );
692    // Gap covering the separator region up to grid start (page-local y=25).
693    col = col.child(widget::spacer().h(25.0 * sy - header_h));
694
695    // 4-column icon grid; icons drawn as GL overlays at exact Patchouli positions.
696    let cats = &book.categories;
697    let icon_s = 16.0 * sx.min(sy);
698    let mut row_i = 0usize;
699    loop {
700        let row_start = row_i * 4;
701        if row_start >= cats.len() { break; }
702        let mut row = widget::panel(FlexDir::Row)
703            .h(cell_h)
704            .gap(0.0)
705            .padding(0.0, 0.0, 0.0, grid_pad_left);
706        for col_i in 0..4 {
707            let idx = row_start + col_i;
708            if idx >= cats.len() { break; }
709            let cat = &cats[idx];
710            let selected = !state.at_home && idx == state.cat;
711            let bg = if selected { theme.nav_selected_bg } else { 0 };
712
713            if let Some(icon_id) = &cat.icon {
714                overlays.push(OverlayCmd::McItem {
715                    item_id: icon_id.clone(),
716                    x: rx + (10.0 + col_i as f32 * 24.0 + 4.0) * sx,
717                    y: py + (25.0 + row_i as f32 * 24.0 + 4.0) * sy,
718                    w: icon_s, h: icon_s,
719                });
720            }
721            let cell = widget::panel(FlexDir::Column)
722                .w(cell_w).h(cell_h).bg(bg)
723                .on_click(format!("cat:{}", idx))
724                .id(format!("book_cat_{}", idx));
725            row = row.child(cell);
726        }
727        col = col.child(row);
728        row_i += 1;
729    }
730    col
731}
732
733// ── Left page: entry content (entry view) ────────────────────────────────────
734
735fn build_entry_left(
736    book: &Book, state: &BookViewState, theme: &BookTheme,
737    recipes: &HashMap<String, RecipeVis>,
738    page_w: f32, page_h: f32,
739    ox: f32, oy: f32,
740    sx: f32, sy: f32,
741    sep_cx: f32,
742    bg_sprites: &mut Vec<BgSprite>,
743    overlays: &mut Vec<OverlayCmd>,
744) -> widget::Widget {
745    let entry      = state.current_entry(book);
746    let page       = entry.and_then(|e| e.pages.get(state.page));
747    let page_count = state.page_count(book);
748    let title_text = entry.map(|e| e.name.as_str()).unwrap_or("");
749
750    // Patchouli PageText page 0:
751    //   title centered at page-local (PAGE_W/2, 0)
752    //   separator at page-local (0, 12)  → centered ≡ sep_cx offset
753    //   text body at page-local (0, 22)
754    let title_h  = 9.0 * sy;
755    let sep_h_px = (SEP_H * sy).max(1.0);
756    let sep_y    = oy + 12.0 * sy;
757    let body_oy  = oy + 22.0 * sy;
758
759    bg_sprites.push(BgSprite {
760        sheet: SpriteSheet::Book,
761        u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
762        x: ox + sep_cx, y: sep_y,
763        w: SEP_W * sx, h: sep_h_px,
764    });
765
766    let page_label = format!("{}/{}", state.page + 1, page_count);
767    let nav = widget::panel(FlexDir::Row)
768        .h(12.0 * sy).gap(4.0)
769        .padding(0.0, 2.0, 0.0, 2.0)
770        .child(btn("◀").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
771            .on_click("prev_page").id("prev_page"))
772        .child(lbl(&page_label).color(theme.nav).flex(1.0).align(Align::Center))
773        .child(btn("⌂").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
774            .on_click("home").id("book_home"))
775        .child(btn("▶").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
776            .on_click("next_page").id("next_page"));
777
778    let page_body = build_page(page, state.page, theme, recipes, bg_sprites, overlays, ox, body_oy, sx, sy);
779
780    widget::panel(FlexDir::Column)
781        .w(page_w).h(page_h)
782        .padding(0.0, 6.0, 4.0, 4.0)
783        .gap(0.0)
784        .child(lbl(title_text).color(theme.title).h(title_h).align(Align::Center))
785        .child(widget::spacer().h((12.0 - 9.0) * sy))  // gap: title end → sep start
786        .child(widget::spacer().h(sep_h_px))             // height occupied by sep sprite
787        .child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy)) // gap: sep end → body
788        .child(page_body)
789        .child(nav)
790}
791
792// ── Right page: entry list for selected category (entry view) ─────────────────
793
794fn build_entries_right(
795    book: &Book, state: &BookViewState, theme: &BookTheme,
796    page_w: f32, page_h: f32, rx: f32, py: f32,
797    sx: f32, sy: f32,
798    overlays: &mut Vec<OverlayCmd>,
799) -> widget::Widget {
800    let entries  = state.entries_visible(book);
801    let cat_name = book.categories.get(state.cat).map(|c| c.name.as_str()).unwrap_or("Entries");
802    let spread_count = state.list_spread_count(book);
803
804    // Patchouli GuiBookEntryList layout (right page):
805    //   category name at page-local y=0, centered
806    //   separator at page-local y=12 (drawn as bg sprite in build_ui)
807    //   entries start at page-local y=20, each h=11
808    let header_h   = 9.0 * sy;
809    let row_h      = 11.0 * sy;
810    let icon_size  = 8.0 * sx.min(sy);
811
812    let mut col = widget::panel(FlexDir::Column)
813        .w(page_w).h(page_h)
814        .padding(0.0, 4.0, 4.0, 0.0)
815        .gap(0.0);
816
817    col = col.child(lbl(cat_name).color(theme.divider).h(header_h).align(Align::Center));
818    // sep region: y=9..15 (sep h=3), then gap to entries start at y=20
819    col = col.child(widget::spacer().h((12.0 - 9.0) * sy));    // gap to sep
820    col = col.child(widget::spacer().h((SEP_H * sy).max(1.0))); // sep height
821    col = col.child(widget::spacer().h((20.0 - 12.0 - SEP_H) * sy)); // gap to entries
822
823    let abs_start = state.list_spread_start();
824    for (i, entry) in entries.iter().enumerate() {
825        let abs_i    = abs_start + i;
826        let selected = abs_i == state.entry;
827        let bg    = if selected { theme.nav_selected_bg } else { 0 };
828        let color = if selected { theme.nav_selected } else { theme.nav };
829
830        // Icon at page-local (1, 20 + i*11 + 1), 8×8 (Patchouli renders entry
831        // icons at 0.5× scale).
832        if let Some(icon_id) = &entry.icon {
833            overlays.push(OverlayCmd::McItem {
834                item_id: icon_id.clone(),
835                x: rx + 1.0 * sx,
836                y: py + (20.0 + i as f32 * 11.0 + 1.0) * sy,
837                w: icon_size, h: icon_size,
838            });
839        }
840
841        let mut row = widget::panel(FlexDir::Row)
842            .h(row_h).gap(2.0).bg(bg)
843            .on_click(format!("entry:{}", abs_i))
844            .id(format!("book_entry_{}", abs_i))
845            .padding(1.0, 2.0, 1.0, 2.0);
846
847        row = row.child(widget::spacer().w(icon_size + 2.0));
848        row = row.child(lbl(&entry.name).color(color).flex(1.0));
849        col = col.child(row);
850    }
851
852    if spread_count > 1 {
853        col = col.child(widget::spacer().flex(1.0));
854        let spread_label = format!("{}/{}", state.list_spread + 1, spread_count);
855        col = col.child(
856            widget::panel(FlexDir::Row).h(12.0 * sy).gap(2.0)
857                .child(btn("◀").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
858                    .on_click("prev_list").id("prev_list"))
859                .child(lbl(&spread_label).color(theme.nav)
860                    .flex(1.0).align(Align::Center))
861                .child(btn("▶").w(12.0 * sx).h(12.0 * sy).color(theme.nav)
862                    .on_click("next_list").id("next_list"))
863        );
864    }
865    col
866}
867
868/// Draw a Patchouli-style crafting recipe: title, 100×62 grid background
869/// (UV 0,0 on the crafting sheet), 3×N ingredient icons, output item.
870/// `rx0`/`ry` are body-local recipe origin; `ox`/`oy` the body screen origin.
871#[allow(clippy::too_many_arguments)]
872fn draw_crafting_grid(
873    theme: &BookTheme,
874    bg_sprites: &mut Vec<BgSprite>,
875    overlays: &mut Vec<OverlayCmd>,
876    col: &mut widget::Widget,
877    grid: &[Option<String>], width: usize,
878    output: &str, count: u32, shapeless: bool,
879    ox: f32, oy: f32, rx0: f32, ry: f32, sx: f32, sy: f32,
880) {
881    let mut c = std::mem::replace(col, widget::panel(FlexDir::Column));
882    c = c.child(lbl(pretty_item_name(output)).color(theme.title)
883        .h(10.0 * sy).align(Align::Center));
884
885    // Grid background: blit at (rx0-2, ry-2) size 100×62, UV(0,0).
886    bg_sprites.push(BgSprite {
887        sheet: SpriteSheet::Crafting,
888        u: 0.0, v: 0.0, uw: 100.0, uh: 62.0,
889        x: ox + (rx0 - 2.0) * sx, y: oy + (ry - 2.0) * sy,
890        w: 100.0 * sx, h: 62.0 * sy,
891    });
892    // Shapeless marker: UV(0,64) 11×11 at (rx0+62, ry+2).
893    if shapeless {
894        bg_sprites.push(BgSprite {
895            sheet: SpriteSheet::Crafting,
896            u: 0.0, v: 64.0, uw: 11.0, uh: 11.0,
897            x: ox + (rx0 + 62.0) * sx, y: oy + (ry + 2.0) * sy,
898            w: 11.0 * sx, h: 11.0 * sy,
899        });
900    }
901
902    let icon_s = 16.0 * sx.min(sy);
903    let width = width.max(1);
904    for (i, slot) in grid.iter().enumerate() {
905        if let Some(item) = slot {
906            overlays.push(OverlayCmd::McItem {
907                item_id: item.clone(),
908                x: ox + (rx0 + 3.0 + (i % width) as f32 * 19.0) * sx,
909                y: oy + (ry  + 3.0 + (i / width) as f32 * 19.0) * sy,
910                w: icon_s, h: icon_s,
911            });
912        }
913    }
914    // Output item at (rx0+79, ry+22); stack count below it when > 1.
915    overlays.push(OverlayCmd::McItem {
916        item_id: output.to_owned(),
917        x: ox + (rx0 + 79.0) * sx, y: oy + (ry + 22.0) * sy,
918        w: icon_s, h: icon_s,
919    });
920    if count > 1 {
921        overlays.push(OverlayCmd::McText {
922            text: format!("x{}", count),
923            x: ox + (rx0 + 81.0) * sx, y: oy + (ry + 40.0) * sy,
924            color: theme.title,
925        });
926    }
927
928    // Spacer from title end (10) to below the grid (ry+62+4).
929    c = c.child(widget::spacer().h((ry + 62.0 + 4.0 - 10.0) * sy));
930    *col = c;
931}
932
933// ── Page content builder ──────────────────────────────────────────────────────
934
935/// Build the content widget for a single page.
936/// `ox/oy` = screen top-left of the page body area.
937/// `sx/sy` = book-local-to-screen scale factors.
938fn build_page(
939    page: Option<&BookPage>,
940    page_num: usize,
941    theme: &BookTheme,
942    recipes: &HashMap<String, RecipeVis>,
943    bg_sprites: &mut Vec<BgSprite>,
944    overlays: &mut Vec<OverlayCmd>,
945    ox: f32, oy: f32,
946    sx: f32, sy: f32,
947) -> widget::Widget {
948    let mut col = widget::panel(FlexDir::Column).flex(1.0).gap(4.0);
949
950    let Some(page) = page else {
951        return col.child(lbl("No entries yet.").color(theme.nav));
952    };
953
954    match page {
955        BookPage::Text { text, title } => {
956            // On non-first pages, show an optional section title + separator.
957            if page_num > 0 {
958                if let Some(t) = title {
959                    let sep_h_px = (SEP_H * sy).max(1.0);
960                    let title_h  = 9.0 * sy;
961                    col = col.child(lbl(t.as_str()).color(theme.title)
962                        .h(title_h).align(Align::Center));
963                    // sep at y=12 page-local, centered
964                    bg_sprites.push(BgSprite {
965                        sheet: SpriteSheet::Book,
966                        u: SEP_U, v: SEP_V, uw: SEP_W, uh: SEP_H,
967                        x: ox + (PAGE_W / 2.0 - SEP_W / 2.0) * sx,
968                        y: oy + 12.0 * sy,
969                        w: SEP_W * sx, h: sep_h_px,
970                    });
971                    col = col.child(widget::spacer().h((12.0 - 9.0) * sy));
972                    col = col.child(widget::spacer().h(sep_h_px));
973                    col = col.child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy));
974                }
975            }
976            for para in text.split('\n') {
977                col = col.child(lbl(para).color(theme.text));
978            }
979        }
980
981        BookPage::Spotlight { item, title, text } => {
982            // Patchouli PageSpotlight (page-body-local coordinates):
983            //   title at y=0 centered, item frame at (PAGE_W/2-33, 10) 66×26
984            //   (UV 0,102 on the 128×256 crafting sheet), item at (PAGE_W/2-8, 15),
985            //   text at y=40.
986            bg_sprites.push(BgSprite {
987                sheet: SpriteSheet::Crafting,
988                u: 0.0, v: 102.0, uw: 66.0, uh: 26.0,
989                x: ox + (PAGE_W / 2.0 - 33.0) * sx,
990                y: oy + 10.0 * sy,
991                w: 66.0 * sx, h: 26.0 * sy,
992            });
993
994            let item_name = title.as_deref()
995                .or(item.name.as_deref())
996                .unwrap_or(item.id.as_str());
997            col = col.child(lbl(item_name).color(theme.title)
998                .h(10.0 * sy).align(Align::Center));
999
1000            let icon_s = 16.0 * sx.min(sy);
1001            overlays.push(OverlayCmd::McItem {
1002                item_id: item.id.clone(),
1003                x: ox + (PAGE_W / 2.0 - 8.0) * sx,
1004                y: oy + 15.0 * sy,
1005                w: icon_s, h: icon_s,
1006            });
1007
1008            // Spacer from title end (y=10) to text start (y=40).
1009            col = col.child(widget::spacer().h(30.0 * sy));
1010
1011            if let Some(t) = text {
1012                col = col.child(lbl(t.as_str()).color(theme.text));
1013            }
1014        }
1015
1016        BookPage::Crafting { recipe_id, text } => {
1017            // Patchouli PageCrafting: recipe origin at page-local
1018            // (PAGE_W/2-49, 4); we place it in body-local coords below a title.
1019            let rx0 = PAGE_W / 2.0 - 49.0; // = 9
1020            let ry  = 12.0;                // body-local recipe y (title occupies 0..10)
1021            match recipes.get(recipe_id.as_str()) {
1022                Some(RecipeVis::Shaped { grid, width, output, count })  => {
1023                    draw_crafting_grid(theme, bg_sprites, overlays, &mut col,
1024                        grid, *width, output, *count, false, ox, oy, rx0, ry, sx, sy);
1025                }
1026                Some(RecipeVis::Shapeless { ingredients, output, count }) => {
1027                    let grid: Vec<Option<String>> =
1028                        ingredients.iter().cloned().map(Some).collect();
1029                    draw_crafting_grid(theme, bg_sprites, overlays, &mut col,
1030                        &grid, 3, output, *count, true, ox, oy, rx0, ry, sx, sy);
1031                }
1032                _ => {
1033                    col = col.child(lbl(format!("[Recipe: {}]", recipe_id))
1034                        .color(theme.nav));
1035                }
1036            }
1037            if let Some(t) = text {
1038                col = col.child(lbl(t.as_str()).color(theme.text));
1039            }
1040        }
1041
1042        BookPage::Smelting { recipe_id, text } => {
1043            // Patchouli PageSmelting: bg UV(11,71) 96×24, input at +4,+4,
1044            // output at +76,+4.
1045            let rx0 = PAGE_W / 2.0 - 49.0;
1046            let ry  = 12.0;
1047            match recipes.get(recipe_id.as_str()) {
1048                Some(RecipeVis::Smelting { input, output }) => {
1049                    col = col.child(lbl(pretty_item_name(output)).color(theme.title)
1050                        .h(10.0 * sy).align(Align::Center));
1051                    bg_sprites.push(BgSprite {
1052                        sheet: SpriteSheet::Crafting,
1053                        u: 11.0, v: 71.0, uw: 96.0, uh: 24.0,
1054                        x: ox + rx0 * sx, y: oy + ry * sy,
1055                        w: 96.0 * sx, h: 24.0 * sy,
1056                    });
1057                    let icon_s = 16.0 * sx.min(sy);
1058                    overlays.push(OverlayCmd::McItem {
1059                        item_id: input.clone(),
1060                        x: ox + (rx0 + 4.0) * sx, y: oy + (ry + 4.0) * sy,
1061                        w: icon_s, h: icon_s,
1062                    });
1063                    overlays.push(OverlayCmd::McItem {
1064                        item_id: output.clone(),
1065                        x: ox + (rx0 + 76.0) * sx, y: oy + (ry + 4.0) * sy,
1066                        w: icon_s, h: icon_s,
1067                    });
1068                    // Spacer from title end (10) to below the furnace strip (ry+24+4).
1069                    col = col.child(widget::spacer().h((ry + 24.0 + 4.0 - 10.0) * sy));
1070                }
1071                _ => {
1072                    col = col.child(lbl(format!("[Recipe: {}]", recipe_id))
1073                        .color(theme.nav));
1074                }
1075            }
1076            if let Some(t) = text {
1077                col = col.child(lbl(t.as_str()).color(theme.text));
1078            }
1079        }
1080
1081        BookPage::Image { texture, title, text, .. } => {
1082            if let Some(t) = title {
1083                col = col.child(lbl(t.as_str()).color(theme.title));
1084            }
1085            col = col.child(widget::mc_image(texture, 80.0, 80.0));
1086            if let Some(t) = text {
1087                col = col.child(lbl(t.as_str()).color(theme.text));
1088            }
1089        }
1090
1091        BookPage::Svg { data, title, text } => {
1092            if let Some(t) = title {
1093                col = col.child(lbl(t.as_str()).color(theme.title));
1094            }
1095            overlays.push(OverlayCmd::Svg { data: data.clone(), x: ox, y: oy, w: 64.0, h: 64.0 });
1096            col = col.child(widget::spacer().h(68.0));
1097            if let Some(t) = text {
1098                col = col.child(lbl(t.as_str()).color(theme.text));
1099            }
1100        }
1101
1102        BookPage::CustomText { text, font, color } => {
1103            overlays.push(OverlayCmd::Text {
1104                text: text.clone(), font: font.clone(), x: ox, y: oy, color: *color,
1105            });
1106            col = col.child(widget::spacer().h(font.size_px * 1.5));
1107        }
1108
1109        BookPage::Relations { entries, text } => {
1110            if let Some(t) = text {
1111                col = col.child(lbl(t.as_str()).color(theme.text));
1112            }
1113            col = col.child(lbl("See also:").color(theme.title));
1114            for e in entries {
1115                col = col.child(lbl(format!("• {}", e)).color(theme.nav));
1116            }
1117        }
1118
1119        BookPage::Entity { entity_type, name, text } => {
1120            let display = name.as_deref().unwrap_or(entity_type.as_str());
1121            col = col.child(lbl(display).color(theme.title));
1122            if let Some(t) = text {
1123                col = col.child(lbl(t.as_str()).color(theme.text));
1124            }
1125        }
1126
1127        BookPage::Pattern { op_id, input, output, text, .. } => {
1128            col = col.child(lbl(op_id.as_str()).color(theme.title));
1129            col = col.child(
1130                lbl(format!("{} → {}", input, output)).color(theme.nav)
1131            );
1132            if !text.is_empty() {
1133                col = col.child(lbl(text.as_str()).color(theme.text));
1134            }
1135        }
1136
1137        BookPage::Empty => {}
1138    }
1139
1140    col
1141}