-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.ts
220 lines (201 loc) · 6.52 KB
/
example.ts
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
// This is an example of how to use the library to generate an EPUB file.
// This example is currently **not** working because epub-builder is a work in progress.
import type {
CreateRenderer,
Locked,
RenderContext,
Renderer,
RenderView,
Templates,
} from "./render/types";
import type { EpubStructure } from "./generate/types";
import { Uint8ArrayWriter } from "@zip.js/zip.js";
import { NodeType } from "./types";
import { createPipeline } from "./pipeline";
import { makeRenderFile } from "./render/render";
import { generateEpub } from "./generate/generate";
import { createRenderContext } from "./render/helpers";
import { makeRenderChapters } from "./render/nodes/chapters";
import { makeRenderCss } from "./render/nodes/css";
import { makeRenderImages } from "./render/nodes/images";
import { makeRenderFonts } from "./render/nodes/fonts";
import { MetadataBuilder } from "./metadata/builder";
import { load } from "./load";
import { render, type RenderOptions } from "mustache";
import { createLog } from "./log";
// Helper function to add the `.mustache` extension to a filename.
const addExt = (name: string) => `${name}.mustache`;
// Create a renderer.
// We'll use Mustache to render the templates.
const createRenderer: CreateRenderer<any> = (template, options) => {
const renderer: Renderer<any> = async (view) =>
render(
template.template,
view,
options?.includer,
options as RenderOptions,
);
// Set the filename of the renderer - used for debugging.
renderer.filename = options?.filename;
return renderer;
};
const options = { createRenderer };
// Create the render pipeline.
// This pipeline generates the structure of the book.
const renderPipeline = createPipeline<Locked<RenderContext>>(
// Render the fonts so they're available in the structure.
makeRenderFonts({
transformFilename: (font) => `OEBPS/fonts/${font.name}`,
}),
// Render the CSS files so they're available in the structure.
makeRenderCss({
transformFilename: (css) => `OEBPS/css/${css.name}`,
}),
// Render the images so they're available in the structure.
makeRenderImages({
transformFilename: (image) => `OEBPS/images/${image.name}`,
}),
// Render the files required by the EPUB specification.
makeRenderFile(addExt("META-INF/container.xml"), options),
makeRenderFile(addExt("OEBPS/content.opf"), options),
makeRenderFile(addExt("OEBPS/toc.ncx"), options),
makeRenderFile(addExt("OEBPS/nav.xhtml"), {
createRenderer,
// Transform the view to include only the spine nodes.
transformView: (ctx) => ({ spine: ctx.view.spine }),
}),
// Render the chapters.
makeRenderChapters("chapter.xhtml", {
createRenderer,
// Transform the filename of a chapter.
transformFilename: (_, i) => `OEBS/chapters/chapter-${i}.xhtml`,
// Transform the view to include the chapter, CSS, and fonts nodes.
// For CSS and fonts, we only need the name (path) of the node in order to render the chapter.
transformView: (ctx, chapter) => {
const { view } = ctx;
const cssNodes = chapter!.css!.map((css) => {
const id = css.ref.id;
return view.css.find((node) => node.id === id)!.name;
});
const fontNodes = chapter!.fonts!.map((font) => {
const id = font.ref.id;
return view.fonts.find((node) => node.id === id)!.name;
});
return { chapter, css: cssNodes, fonts: fontNodes };
},
}),
// ... More steps here.
);
// Create the metadata.
// This represents the metadata of the book.
const metadata = MetadataBuilder.create()
.set("title", "Example Title")
.set("author", "Example Author")
.set("description", "Example Description")
.set("language", "en")
.set("identifier", "example-identifier")
.add("publisher", "Example Publisher")
.set("date", "2021-01-01")
.set("type", "Text")
.set("rights", "CC0")
.add("rights", "CC BY")
.build();
// Create the view.
// This represents the content of the book.
const view: RenderView = {
metadata: {
id: "metadata",
type: NodeType.Metadata,
metadata,
},
chapters: [
{
id: "chapter-1",
type: NodeType.Chapter,
title: "Chapter 1",
content: "<h1>Chapter 1</h1><p>This is chapter 1.</p>",
format: "text/html",
order: 1,
css: [
{
id: "css-ref-1",
type: NodeType.Ref,
ref: {
type: NodeType.Css,
id: "css-1",
},
},
],
},
{
id: "chapter-2",
type: NodeType.Chapter,
title: "Chapter 2",
content: "<h1>Chapter 2</h1><p>This is chapter 2.</p>",
format: "text/html",
order: 2,
},
],
spine: [
{
id: "spine-1",
type: NodeType.Spine,
order: 1,
ref: {
type: NodeType.Chapter,
id: "chapter-1",
},
},
],
cover: {
id: "cover",
type: NodeType.Image,
src: "cover.jpg",
format: "image/jpeg",
},
fonts: [],
css: [
{
id: "css-1",
type: NodeType.Css,
name: "styles.css",
content: "body { color: red; }",
},
],
images: [],
};
// Load the templates.
// The default templates are Mustache templates that are stored in the `templates/default` directory.
const templateDir = new URL("../templates/default", import.meta.url);
const templates = await load(templateDir) as Templates;
// Create a log.
// The log is used to log events during the render pipeline and generation of the EPUB file.
const log = createLog();
// Log events to the console.
log.addEventListener("log", (event) => {
console.log(log.format(event.detail));
});
// Create the context.
const context = createRenderContext(view, templates, { log });
// Run the render pipeline with the context.
await renderPipeline.run(context);
// Create a writer.
// This writer is used to write the EPUB file to a buffer.
// All writers supported by @zip.js/zip.js are supported.
const writer = new Uint8ArrayWriter();
// Generate the EPUB file.
const buffer = await generateEpub(
writer,
context.structure as EpubStructure,
{ log },
);
// Example of how to save the EPUB file to the Origin Private File System (OPFS) in a web browser.
// OPFS is a new web standard that allows web applications to store files in a private file system.
if (navigator?.storage?.getDirectory) {
const root = await navigator.storage.getDirectory();
const books = await root.getDirectoryHandle("books", { create: true });
const book = await books.getFileHandle("book.epub", { create: true });
const writable = await book.createWritable();
await writable.write(buffer);
await writable.close();
}