From 330a0c896970d99320529a47f186c831a6ecc4a0 Mon Sep 17 00:00:00 2001 From: "Simen A. W. Olsen" Date: Thu, 28 May 2026 23:54:24 +0200 Subject: feat: add table of content instead of sidebar --- src/epub.zig | 27 ++++-- src/html.zig | 305 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- src/main.zig | 17 +++- 3 files changed, 326 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/epub.zig b/src/epub.zig index 0bdf563..7e35089 100644 --- a/src/epub.zig +++ b/src/epub.zig @@ -13,8 +13,11 @@ pub const Options = struct { /// Version name, used in the title and as the unique identifier basis. version: []const u8, lang: []const u8 = "en", - /// Well-formed XHTML5 body (output of html.toXhtml). + /// Well-formed XHTML5 body (output of html.transform). xhtml: []const u8, + /// `
    ...
` of TOC entries extracted from the page, or null. When + /// present it becomes the navigation document and the book's opening page. + toc: ?[]const u8 = null, }; /// Build an EPUB3 archive from `opts`. Caller owns the returned bytes. @@ -74,6 +77,7 @@ fn buildOpf(allocator: std.mem.Allocator, opts: Options) ![]u8 { \\ \\ \\ + \\ \\ \\ \\ @@ -82,21 +86,23 @@ fn buildOpf(allocator: std.mem.Allocator, opts: Options) ![]u8 { } fn buildNav(allocator: std.mem.Allocator, opts: Options) ![]u8 { + // Use the page's own table of contents when we extracted one; otherwise fall + // back to a single link to the whole document. + const list = opts.toc orelse + "
    \n
  1. Contents
  2. \n
"; return std.fmt.allocPrint(allocator, \\ \\ \\ {s} ({s}) \\ \\ \\ \\ \\ - , .{ opts.lang, opts.title, opts.version, opts.title, opts.version }); + , .{ opts.lang, opts.title, opts.version, opts.title, opts.version, list }); } test "epub starts with PK and mimetype, and round-trips" { @@ -105,6 +111,7 @@ test "epub starts with PK and mimetype, and round-trips" { .title = "Zig Language Reference", .version = "0.15.2", .xhtml = "\nhi", + .toc = "
  1. Intro
", }); defer gpa.free(bytes); @@ -126,4 +133,12 @@ test "epub starts with PK and mimetype, and round-trips" { const opf = try tmp.dir.readFileAlloc(gpa, "OEBPS/content.opf", 1 << 16); defer gpa.free(opf); try std.testing.expect(std.mem.indexOf(u8, opf, "0.15.2") != null); + // nav must come before index in the spine (TOC is the opening page). + const nav_ref = std.mem.indexOf(u8, opf, "idref=\"nav\"").?; + const idx_ref = std.mem.indexOf(u8, opf, "idref=\"index\"").?; + try std.testing.expect(nav_ref < idx_ref); + + const nav = try tmp.dir.readFileAlloc(gpa, "OEBPS/nav.xhtml", 1 << 16); + defer gpa.free(nav); + try std.testing.expect(std.mem.indexOf(u8, nav, "href=\"index.xhtml#Intro\"") != null); } diff --git a/src/html.zig b/src/html.zig index 56c5d91..ec9ecfd 100644 --- a/src/html.zig +++ b/src/html.zig @@ -1,13 +1,17 @@ //! Transform the Zig docs single-page HTML5 into well-formed XHTML5 for EPUB. //! //! The page is self-contained (embedded