feat(export): Chunk #6 Export Pipeline — 7 exporters, ExportDialog & tests

Add the @pubscript/exporters package exporting a flattened ProseMirror
project to Markdown, HTML, EPUB, DOCX, ODT and PDF, plus a deterministic
generatedAt timestamp threaded through every format (ZIP entry dates,
PDF /ID, DOCX dc:created/modified, EPUB id, HTML/XML footers) so golden
files are byte-stable.

Wire an ExportDialog into the web app (Topbar trigger, App route) with
format selection, theme pick, and download helpers.

Add round-trip and golden-file determinism tests (22) covering
non-empty output, byte-identical re-exports, Markdown round-trip through
the editor, and EPUB/ODT ZIP + mimetype + XML validation.
This commit is contained in:
Schwitzz
2026-10-26 23:30:47 -05:00
parent 35b015bb04
commit 978858362d
24 changed files with 3103 additions and 2 deletions
+4 -1
View File
@@ -1,6 +1,7 @@
import { useState, useEffect } from "react";
import { Routes, Route } from "react-router-dom";
import { Sidebar, Topbar, CommandPalette } from "./components/index.js";
import { ExportDialog } from "./features/export/ExportDialog.js";
import { ToastViewport } from "@pubscript/ui";
import Write from "./routes/Write.js";
import { Characters } from "./routes/Characters.js";
@@ -26,6 +27,7 @@ const NAV = [
export default function App() {
const [paletteOpen, setPaletteOpen] = useState(false);
const [exportOpen, setExportOpen] = useState(false);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -41,7 +43,7 @@ export default function App() {
return (
<div className="ps-app">
<Sidebar nav={NAV} />
<Topbar onOpenPalette={() => setPaletteOpen(true)} />
<Topbar onOpenPalette={() => setPaletteOpen(true)} onOpenExport={() => setExportOpen(true)} />
<main className="ps-main">
<Routes>
<Route path="/" element={<Write />} />
@@ -58,6 +60,7 @@ export default function App() {
</main>
<CommandPalette open={paletteOpen} onClose={() => setPaletteOpen(false)} nav={NAV} />
<ExportDialog open={exportOpen} onClose={() => setExportOpen(false)} />
<ToastViewport />
</div>
);
+10 -1
View File
@@ -16,9 +16,10 @@ const TITLES: Record<string, string> = {
export interface TopbarProps {
onOpenPalette: () => void;
onOpenExport: () => void;
}
export function Topbar({ onOpenPalette }: TopbarProps) {
export function Topbar({ onOpenPalette, onOpenExport }: TopbarProps) {
const location = useLocation();
const theme = useSettings((s) => s.theme);
const setTheme = useSettings((s) => s.setTheme);
@@ -43,6 +44,14 @@ export function Topbar({ onOpenPalette }: TopbarProps) {
<span className="ps-command-kbd" style={{ marginLeft: 8 }}>⌘K</span>
</button>
<button
className="ps-nav-item"
onClick={onOpenExport}
style={{ width: "auto", padding: "6px 10px" }}
>
<span>Export</span>
</button>
<Select
value={theme}
onChange={(e) => setTheme(e.target.value as never)}
@@ -0,0 +1,190 @@
import { useEffect, useMemo, useState } from "react";
import { Modal, Button } from "@pubscript/ui";
import {
THEMES,
exportProjectData,
type ExportFormat,
} from "@pubscript/exporters";
import { useProjectStore } from "../../store/project-store.js";
import { buildExportProject } from "./buildExportProject.js";
import { downloadFile } from "./download.js";
import { EXPORT_FORMATS, type FormatInfo } from "./formats.js";
export interface ExportDialogProps {
open: boolean;
onClose: () => void;
}
type Scope = "project" | "chapter";
/** Collapse a string into a filesystem-safe slug. */
function slug(value: string): string {
return value
.trim()
.replace(/[^\w-]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60) || "project";
}
export function ExportDialog({ open, onClose }: ExportDialogProps) {
const adapter = useProjectStore((s) => s.adapter);
const projectId = useProjectStore((s) => s.project?.projectId);
const chapters = useProjectStore((s) => s.chapters);
const [format, setFormat] = useState<ExportFormat>("markdown");
const [themeId, setThemeId] = useState("ink");
const [scope, setScope] = useState<Scope>("project");
const [chapterId, setChapterId] = useState<string>("");
const [books, setBooks] = useState<{ id: string; title: string }[]>([]);
const [exporting, setExporting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Populate the book/chapter selectors when the dialog opens.
useEffect(() => {
if (!open || !adapter || !projectId) return;
let active = true;
void (async () => {
const allBooks = await adapter.listBooks(projectId);
if (!active) return;
setBooks(allBooks);
// Resolve the first chapter across books so the selector has a default.
let firstChapterId = "";
for (const book of allBooks) {
const cs = await adapter.listChapters(book.id);
const first = cs[0];
if (first) {
firstChapterId = first.id;
break;
}
}
if (!active) return;
setChapterId(firstChapterId);
})();
return () => {
active = false;
};
}, [open, adapter, projectId]);
const chapterOptions = useMemo(() => {
const byBook = new Map<string, { id: string; title: string }[]>();
for (const book of books) {
byBook.set(book.id, chapters.filter((c) => c.bookId === book.id));
}
return byBook;
}, [books, chapters]);
const formatInfo: FormatInfo | undefined = useMemo(
() => EXPORT_FORMATS.find((f) => f.id === format),
[format]
);
const handleExport = async () => {
if (!adapter || !projectId) return;
setExporting(true);
setError(null);
try {
const project = await buildExportProject(adapter, projectId);
const options: Parameters<typeof exportProjectData>[2] = {
scope: scope === "chapter" ? "chapter" : "project",
theme: themeId,
};
if (scope === "chapter") options.scopeId = chapterId;
const data = await exportProjectData(project, format, options);
const ext = formatInfo?.extension ?? "bin";
downloadFile(`${slug(projectId)}.${ext}`, data, formatInfo?.mime ?? "application/octet-stream");
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setExporting(false);
}
};
return (
<Modal
title="Export project"
open={open}
onClose={onClose}
footer={
<>
<Button variant="ghost" onClick={onClose} disabled={exporting}>
Cancel
</Button>
<Button onClick={handleExport} disabled={exporting || !formatInfo}>
{exporting ? "Exporting…" : "Export"}
</Button>
</>
}
>
<div className="ps-export-grid">
<label className="ps-export-field">
<span>Format</span>
<select
className="ps-select"
value={format}
onChange={(e) => setFormat(e.target.value as ExportFormat)}
disabled={exporting}
>
{EXPORT_FORMATS.map((f) => (
<option key={f.id} value={f.id}>
{f.label}
</option>
))}
</select>
</label>
<label className="ps-export-field">
<span>Theme</span>
<select
className="ps-select"
value={themeId}
onChange={(e) => setThemeId(e.target.value)}
disabled={exporting}
>
{Object.entries(THEMES).map(([id, t]) => (
<option key={id} value={id}>
{t.name}
</option>
))}
</select>
</label>
<label className="ps-export-field">
<span>Scope</span>
<select
className="ps-select"
value={scope}
onChange={(e) => setScope(e.target.value as Scope)}
disabled={exporting}
>
<option value="project">Entire book</option>
<option value="chapter">Selected chapter</option>
</select>
</label>
{scope === "chapter" && (
<label className="ps-export-field">
<span>Chapter</span>
<select
className="ps-select"
value={chapterId}
onChange={(e) => setChapterId(e.target.value)}
disabled={exporting || chapterOptions.size === 0}
>
{Array.from(chapterOptions.values()).flatMap((cs) =>
cs.map((c) => (
<option key={c.id} value={c.id}>
{c.title}
</option>
))
)}
</select>
</label>
)}
</div>
{error && <p className="ps-export-error" role="alert">{error}</p>}
</Modal>
);
}
@@ -0,0 +1,33 @@
import type { Book, StorageAdapter } from "@pubscript/core";
import type { ExportProject } from "@pubscript/exporters";
/**
* Assemble the export model for a project from the storage adapter.
*
* Fetches the project metadata and every book with its chapters, then returns
* the `ExportProject` shape the export engine consumes. The engine flattens it
* into blocks and applies the requested scope/theme when the export runs, so
* this helper only needs to gather the raw source data.
*/
export async function buildExportProject(
adapter: StorageAdapter,
projectId: string,
): Promise<ExportProject> {
const project = await adapter.getProject(projectId);
const meta: ExportProject["meta"] = {
title: project.title,
};
if (typeof project.settings.author === "string") meta.author = project.settings.author;
if (project.settings.language !== undefined) meta.language = project.settings.language;
const books = await adapter.listBooks(projectId);
const booksWithChapters: Book[] = await Promise.all(
books.map(async (book) => ({
...book,
chapters: await adapter.listChapters(book.id),
}))
);
return { meta, books: booksWithChapters };
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Trigger a browser download for an in-memory file.
*
* Works for both the text exporters (markdown/html → string) and the binary
* book exporters (epub/docx/odt/pdf → Uint8Array). Uses a detached anchor so it
* works in the web app without any backend round-trip.
*/
export function downloadFile(
filename: string,
data: string | Uint8Array,
mime = "application/octet-stream",
): void {
let blob: Blob;
if (typeof data === "string") {
blob = new Blob([data], { type: `${mime}; charset=utf-8` });
} else {
blob = new Blob([data as BlobPart], { type: mime });
}
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
/** Turn a title into a filesystem-safe slug for the default export filename. */
export function slugify(title: string): string {
const slug = title
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
return slug || "project";
}
+76
View File
@@ -0,0 +1,76 @@
/**
* Export format registry for the web ExportDialog.
*
* The exporters package exposes one function per format; this module describes
* each format's human-facing metadata (label, file extension, MIME type) and
* which formats serialize to a binary blob versus a plain text string.
*/
/** The export formats the UI can choose from. */
export type ExportFormat = "markdown" | "html" | "epub" | "docx" | "odt" | "pdf";
export interface FormatInfo {
id: ExportFormat;
label: string;
extension: string;
mime: string;
/**
* True for the zip-based book formats (epub/docx/odt/pdf) whose exporters
* return a binary `Uint8Array`; false for the text formats (markdown/html)
* whose exporters return a string.
*/
binary: boolean;
}
export const EXPORT_FORMATS: FormatInfo[] = [
{
id: "markdown",
label: "Markdown",
extension: "md",
mime: "text/markdown",
binary: false,
},
{
id: "html",
label: "HTML",
extension: "html",
mime: "text/html",
binary: false,
},
{
id: "epub",
label: "EPUB",
extension: "epub",
mime: "application/epub+zip",
binary: true,
},
{
id: "docx",
label: "Word (DOCX)",
extension: "docx",
mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
binary: true,
},
{
id: "odt",
label: "OpenDocument (ODT)",
extension: "odt",
mime: "application/vnd.oasis.opendocument.text",
binary: true,
},
{
id: "pdf",
label: "PDF",
extension: "pdf",
mime: "application/pdf",
binary: true,
},
];
/** Lookup table keyed by format id. */
export const FORMAT_BY_ID: Record<ExportFormat, FormatInfo> = Object.fromEntries(
EXPORT_FORMATS.map((f) => [f.id, f]),
) as Record<ExportFormat, FormatInfo>;
/** First (default) format shown in the dialog. */
export const DEFAULT_FORMAT: ExportFormat = EXPORT_FORMATS[0]!.id;
+1
View File
@@ -8,6 +8,7 @@ import "./styles/entities.css";
import "./styles/plot.css";
import "./styles/timeline.css";
import "./styles/whiteboard.css";
import "./styles/export.css";
createRoot(document.getElementById("root")!).render(
<StrictMode>
+74
View File
@@ -0,0 +1,74 @@
/**
* Export dialog styles (apps/web).
*
* Styles for the Chunk #6 export modal: format/theme/scope selectors and the
* export action row. Reuses the `@pubscript/ui` design tokens (`--ps-*`) and
* component classes (`ps-btn`, `ps-input`, `ps-modal-*`).
*/
.ps-export {
display: flex;
flex-direction: column;
gap: 16px;
min-width: 320px;
}
.ps-export-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.ps-export-field > span {
font-size: 13px;
font-weight: 600;
color: var(--ps-text-muted);
}
.ps-export select.ps-input {
width: 100%;
padding: 8px 10px;
background: var(--ps-surface-2);
border: 1px solid var(--ps-border);
border-radius: var(--ps-radius);
color: var(--ps-text);
font-family: inherit;
font-size: 14px;
}
.ps-export select.ps-input:focus {
outline: none;
border-color: var(--ps-accent);
}
/* Scope toggle */
.ps-export-scope {
display: flex;
gap: 8px;
}
.ps-export-scope .ps-btn {
flex: 1;
}
/* Error message */
.ps-export-error {
margin: 0;
padding: 10px 12px;
font-size: 13px;
color: var(--ps-danger);
background: color-mix(in srgb, var(--ps-danger) 8%, transparent);
border: 1px solid color-mix(in srgb, var(--ps-danger) 25%, transparent);
border-radius: var(--ps-radius);
}
/* Action row */
.ps-export-actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 4px;
}