@ideascol/flow-editor
v0.1.56
Published
Visual flow editor for ebook page layout and PDF export
Readme
@ideascol/flow-editor
Visual flow editor for ebook page layout and PDF export.
Paginates an ebook's chapters into real pages — text flowing around images, page templates, floats — and exports the result as a PDF that matches what the editor shows.
Two ways to use it:
- Standalone CLI — run a local dev server with browser-side storage. Good for trying it out or authoring ebooks without a backend.
- Embedded library — mount
<FlowEditor />inside another React/Next.js app and wire it to your own auth, persistence, chat, and AI.
1. Standalone CLI
Setup (saves Gemini API key, encrypted)
npx @ideascol/flow-editor@latest setupYou'll be prompted for:
- Gemini API key — get one at https://aistudio.google.com/apikey
- Passphrase — used to encrypt the key on disk (
~/.cli-maker/flow-editor-config.json)
Run the editor
npx @ideascol/flow-editor@latest dev --ai geminiPrompts for the same passphrase you set in setup to decrypt the Gemini key. Editor opens at http://localhost:4242 with local browser storage (IndexedDB) — no backend needed.
Flags:
| Flag | Description |
|------|-------------|
| --port <n> | Port (default 4242) |
| --file <path> | Load an ebook JSON file on start |
| --ai <provider> | none (default) or gemini |
Skip the passphrase prompt by exporting GEMINI_API_KEY instead:
GEMINI_API_KEY=... npx @ideascol/flow-editor@latest dev --ai geminiOther commands:
npx @ideascol/flow-editor@latest show-config # show masked saved key2. Embedded in another app
Use the package as a React library. Host app supplies auth, persistence, toast, optional chat panel, and optional header actions. Reference integration: personal/ebook — src/components/flow-editor/FlowProviders.tsx.
Install
npm install @ideascol/flow-editorPeer deps required in the host: react 19, react-dom 19, @base-ui/react, @tiptap/react + @tiptap/starter-kit + @tiptap/pm + @tiptap/extension-placeholder, pdf-lib, @pdf-lib/fontkit, lucide-react, @chenglou/pretext.
Mount
"use client";
import {
FlowEditor,
FlowEditorProvider,
type EbookData,
type FlowLocale,
type FlowToast,
type FlowPersistence,
} from "@ideascol/flow-editor";
import { toast } from "sonner";
const flowToast: FlowToast = {
success: (m, o) => toast.success(m, o),
error: (m, o) => toast.error(m, o),
loading: (m) => toast.loading(m),
};
const flowPersistence: FlowPersistence = {
// load/save ebook + run edits against your backend (Firestore, Postgres, etc.)
// see ebook reference impl: src/lib/flow/persistence.ts
};
export function FlowEditorMount({
ebook,
ebookId,
canEdit,
user,
authLoading,
locale,
}: {
ebook: EbookData;
ebookId: string;
canEdit: boolean;
user: { uid: string } | null;
authLoading: boolean;
locale: FlowLocale;
}) {
return (
<FlowEditorProvider
user={user}
canEdit={canEdit}
authLoading={authLoading}
locale={locale}
persistence={flowPersistence}
toast={flowToast}
renderChatPanel={({ open, onClose, onChangesApplied }) => (
<YourChatPanel
ebookId={ebookId}
open={open}
onClose={onClose}
onChangesApplied={onChangesApplied}
/>
)}
renderHeaderActions={({ ebook, refetchEbook, jumpToChapter }) => (
<YourHeaderActions
ebook={ebook}
onApplied={refetchEbook}
onSelectChapter={jumpToChapter}
/>
)}
>
<FlowEditor ebook={ebook} />
</FlowEditorProvider>
);
}Read-only preview
import { FlowPreview } from "@ideascol/flow-editor";
<FlowEditorProvider /* ...same provider, canEdit={false}... */>
<FlowPreview ebook={ebook} />
</FlowEditorProvider>Pagination snapshot (server-side AI redesign, etc.)
import { flattenEbook, paginate, type PageLayout } from "@ideascol/flow-editor";
const lines = flattenEbook(ebook);
const pages: PageLayout[] = paginate(lines, layoutOpts);Themes
A FlowTheme is a complete design decision — palette, modular type scale,
font pairing, spatial rhythm, ornament motifs. FlowLayout.typography stays
the compiled result the paginator reads, so nothing downstream needs to know
themes exist.
Eight curated presets: storybook-warm, kids-playful, workbook-bright,
editorial-magazine, minimal-serif, notebook-hand, comic-panel,
dark-focus.
import {
THEME_PRESETS,
applyTheme,
themeVariants,
flowLayoutFromTheme,
} from "@ideascol/flow-editor";
// Apply to an existing layout. Both destructive options default to off, so
// previewing a theme never discards hand-tuned per-block typography.
const next = applyTheme(layout, THEME_PRESETS["editorial-magazine"]);
// Or build a layout for an ebook that has none yet.
const fresh = flowLayoutFromTheme(THEME_PRESETS["storybook-warm"]);
// Four derived takes on a theme: calm, bold, airy, compact.
const options = themeVariants(THEME_PRESETS["comic-panel"]);A layout with no theme renders exactly as it did before themes existed —
resolveTypography(undefined, x) returns x by identity.
Covers
The cover is composed as absolute boxes rather than stacked runs. Five
templates: framed, band, full-bleed, typographic, and stacked (the
original flow layout).
The theme picks a default; FlowLayout.coverSettings overrides it per book,
because the right cover depends on the artwork as much as the theme —
full-bleed is perfect over a photograph and wrong over art that already
carries its own title.
layout.coverSettings = {
template: "framed",
scrimStart: 0.58, // full-bleed only
scrimOpacity: 0.82, // full-bleed only
imageShare: 0.62, // band only
offsets: { title: { dx: 0, dy: -12 } }, // per-block nudges, draggable in the UI
};Text colours are chosen by measured WCAG contrast against whatever sits behind them, so a title never lands in the colour of its own band.
Fonts and PDF export
39 faces, self-hosted as TTF under the host's public/fonts/. That is not
cosmetic: Google's CSS API serves only WOFF2 to a browser and pdf-lib cannot
embed WOFF2, so a Google-hosted face exports as Helvetica. scripts/vendor-fonts.py
downloads and instances them.
Faces that fail to embed are reported to the author rather than silently substituted. As of 0.1.51 no face resolves through Google — JetBrains Mono was the last, and an exported code block was coming out in Helvetica.
AI-proposed layout changes
The chat assistant can propose design operations, applied through a pure reducer:
import { applyLayoutOps, isLayoutOp, themeCatalogForPrompt } from "@ideascol/flow-editor/server";
// Generated from the registry, so the list the model sees can never drift
// from what set_theme resolves.
const catalog = themeCatalogForPrompt();
const next = applyLayoutOps(layout, changes.filter((c) => isLayoutOp(c.op)));Ops: set_theme, set_typography, set_margins, set_page_template,
set_default_template, set_page_size. Every payload is validated in the
reducer, not only in the UI — these arrive as parsed JSON from a language
model, and a heading size in px would wreck a page laid out in points.
Server-safe entrypoint
@ideascol/flow-editor pulls React, TipTap and pdf-lib. Importing it from a
route handler breaks the build. Import from @ideascol/flow-editor/server
instead for the theme registry, layout reducer and font catalog — plain data
and arithmetic, no DOM.
import { THEME_PRESETS, applyLayoutOps } from "@ideascol/flow-editor/server";Editing
- Formatting appears over the selection rather than as a standing toolbar.
/opens a block-type menu (heading, lists, quote, inline code).- Editing happens on the page's own surface, so dark themes stay readable while typing.
- Clicking away from a block saves it.
Code blocks
Select a paragraph and the inspector offers Mark as code; a code block offers a language picker and the way back to prose. Both are pure functions, so a host can drive them without the UI:
import {
applyCodeConversion, canConvertToCode, CODE_LANGUAGES,
} from "@ideascol/flow-editor";
canConvertToCode(section); // prose only
applyCodeConversion(ebook, chapterId, sectionId, "to-code", "python");
applyCodeConversion(ebook, chapterId, sectionId, "to-text");CODE_LANGUAGES is exactly what the tokenizer handles — offering a language
it does not would promise highlighting that never arrives. Each entry says
which level it delivers (full includes keywords, basic is strings,
numbers and comments), and a test asserts the tokenizer actually delivers it.
Blocks are drawn on a panel derived from the page's own ink and surface, so the plate recedes on a light page and lightens on a dark one instead of importing a terminal theme. The panel spans the text column rather than the longest line: code is ragged-right, and per-block widths read as a bug.
Highlighting is hand-rolled rather than Shiki or Prism — the paginator needs
flat {text, colour} runs it can measure, not HTML. Tokenizing is
single-line, since the paginator hands over lines that are already wrapped.
Sized to the column, not to the body
Code inherits the body size, so a large-type theme produced code too wide
for the page: kids-playful sets 15pt body, giving 13.8pt code that fits 58
characters in a 483pt column. Lines wrapped, and the continuation landed at
the left margin where it read as a new statement at zero indentation.
Wrapping is ordinary in prose and destructive in code, where indentation
carries the structure.
import { codeFontSize } from "@ideascol/flow-editor";
codeFontSize(15, 483); // 10.59 — capped, would have wrapped
codeFontSize(10.5, 483); // 9.66 — untouched, already fitsIt targets 76 characters per line (close to the 79 Python itself recommends) and reads the real region width, so it holds for any page size or margins. It only ever lowers a size — a theme that already fits is left exactly as authored, and a deliberately small theme stays small.
Contrast against the panel, not the page
A theme accent is chosen to look right as a heading: large, sparse, often
bold. Code is the opposite — small, dense, read a character at a time.
kids-playful's coral sat at 2.48:1 against the plate and
storybook-warm's orange at 2.58:1, which is tiring over forty lines of
Python. syntaxPalette now measures each token against the panel it is
drawn on and deepens it toward the ink until it clears 3:1, keeping the
hue rather than collapsing to black:
kids-playful #FF6B6B -> #db615e 2.48 -> 3.19
storybook-warm #E07A3F -> #bf6b3b 2.58 -> 3.36The other six presets are returned unchanged, and a test asserts that — a readability pass that quietly repaints themes nobody complained about is a worse bug than the one it fixes.
Fonts
Code sets in theme.fonts.code, defaulting to JetBrains Mono, which ships
self-hosted as TTF like every other face (see Fonts and PDF export).
Its GSUB table is stripped at vendoring time: it is a coding face with
programming ligatures, == maps to one wide glyph, and pdf-lib measures
without GSUB while the PDF renderer applies it — so each == left the
drawing cursor ~8pt behind the ink and swallowed the following space.
A book should show the characters the author typed anyway.
Provider contracts
persistence: FlowPersistence— load/save ebook, persist run edits, list catalog/user images.toast: FlowToast—success/error/loading.renderChatPanel?— your AI chat UI; receives{ open, onClose, onChangesApplied }.renderHeaderActions?— extra buttons in the editor header; receives{ ebook, refetchEbook, jumpToChapter }.locale: "en" | "es"— built-in messages; override viamessagesprop.
See src/index.ts for the full public API.
License
MIT
