Standalone reader
@nextgensoftwares/folio-reader shows published books to readers without shipping the editor: no @nextgensoftwares/folio-editor, no ProseMirror, no editing plugins. It paints Folio layouts (the same pages the editor and the PDF export produce) into a virtualized, accessible page view, one chapter at a time.
pnpm add @nextgensoftwares/folio-reader @nextgensoftwares/folio-layout @nextgensoftwares/folio-model
# optional: @nextgensoftwares/folio-fonts (client-side layout), @nextgensoftwares/folio-export-pdf (PDF export), reactA book is chapters
A ReaderSource lists the parts of a book cheaply, then hands over each chapter when the reader needs it:
import { createReader, localLayout, type ReaderSource } from '@nextgensoftwares/folio-reader';
const source: ReaderSource = {
listChapters: async () => (await api.get(`/books/${id}/chapters`)).map((c) => ({
id: c.id, title: c.title, kind: c.kind, // 'chapter' | 'front-matter' | 'inserted'
pageCount: c.layoutReport?.pages, // exact counts size the scrollbar up front
headings: c.headings, // TOC before the chapter loads
})),
loadChapter: async (chapterId) => api.get(`/books/${id}/chapters/${chapterId}/content`), // { doc } or { layout }
search: async (q) => api.get(`/books/${id}/search`, { q }), // optional
};
const reader = createReader(el, { source, layout: localLayout({ measurer: engine, theme }) });- Chapters near the viewport are loaded (two at a time), the next one is prefetched near a chapter's end, and laid-out chapters beyond
keepChapters(default 4) are dropped again: memory stays flat in a 7,000-page book. - Chapters whose count the metadata doesn't give are laid out in idle time just to learn it (
countInBackground), so "Page X of Y" becomes exact; until then totals show≈. Navigation to a book-wide page number lays out the chapters before it first, so it always lands right. - A chapter can arrive as a document (laid out on the client), a precomputed layout (
toPlainLayout(layout)on the server; validated byreadLayouton the client) or both (layout for pages, document for find and block ids). - Windowed chapters: with
loadPages(id, from, to)and a knownpageCount, a chapter is never loaded whole; pages arrive in windows of 8 as they near the viewport and are dropped far from it. The client then holds only what it shows: the strongest option for protected books. See Windowed (server) chapters.
Where layout runs
localLayout(options, { prepare }) | main thread; prepare loads the chapter's fonts first (readerFonts(...).prepare) |
workerLayout(new Worker(...), { math }) | a Web Worker running serveLayout(setup); with math: katexMathMeasurer() in the setup, math is measured in the worker too (otherwise on the main thread on request) |
| server | send { layout } (or windows) and skip layout code on the client entirely; math through @nextgensoftwares/folio-math in plain Node |
Plugin blocks (code, charts…) are laid out by the reader plugins' renderers. The reader hands them to its layout function (ChapterLayoutContext.renderers) and localLayout merges them under its own options' renderers, so plugins: [code.plugin] is enough on the main thread. Functions can't cross into a worker: with workerLayout, the worker's serveLayout setup must build the same renderers itself (for code blocks, codeLayout() from @nextgensoftwares/folio-plugin-code/layout, see Code blocks), and its layout wrappers as wrapLayout (a contents block's live rows: (next) => withTableOfContents(withChapterDefaults(next)) with tocRenderer in renderers).
Same pages everywhere. The editor, the book app, localLayout, serveLayout and a server all build their options with pageLayoutOptions (@nextgensoftwares/folio-layout), so with the same measurer, theme, math and header/footer a chapter lays out identically on every surface (a parity test checks it). Build a server's options with it too; see One page setup. Only the editor's reflow (a narrow screen's view) differs, and exports always take the print pages. The pages also paint through one HTML painter (/html): the reader's page elements are the editor's (.folio-body, .folio-blk, .folio-text, .folio-rect, .folio-media, .folio-math, .folio-media-missing; before 0.58 the reader used its own .fr-body, .fr-blk, .fr-t… classes).
Math without a browser. @nextgensoftwares/folio-math measures and draws KaTeX math with no DOM, so the server, a worker and the browser give the same boxes and therefore the same line and page breaks. Use the same measurer everywhere a book is laid out:
import { katexMathMeasurer, fallbackText } from '@nextgensoftwares/folio-math';
import { katexMathNode } from '@nextgensoftwares/folio-math/node';
const math = katexMathMeasurer({ fallback: fallbackText(engine, 'Noto Sans Arabic') }); // Arabic in \text{}
const layout = layoutDocument(doc, { measurer: engine, theme, math }); // server, worker or browser
const pdf = await exportPdf(layout, { fonts, shaper: engine, math: katexMathNode() }); // vector math in NodeThe reader paints math with the same drawing (canvas: { math: katexMath({ fonts: katexFontsFromUrl('/fonts/katex/') }) }), and @nextgensoftwares/folio-render-node uses it by default. See the folio-math API.
Code blocks
@nextgensoftwares/folio-plugin-code/layout is the code plugin's layout part alone: no React, no editor, no DOM. codeLayout() gives the codeBlock and codeGroup renderers the editor uses, so the reader, a layout worker and a server lay code out exactly as the editor does.
import { codeLayout } from '@nextgensoftwares/folio-plugin-code/layout';
const code = codeLayout({ palette: 'github', preload: ['python', 'typescript'] });
createReader(el, { source, layout: localLayout({ measurer, theme }), plugins: [code.plugin] });code.plugin hands the renderers to localLayout and lays chapters out again (reader.relayout()) when a grammar they asked for arrives, so code shows plain at first and coloured a moment later. In a worker or on a server, nothing can lay the chapter out again for you: pass preload (or 'all') and await code.ready() before serving:
// layout.worker.ts
const code = codeLayout({ preload: 'all' });
serveLayout(async () => (await code.ready(), { measurer: await engine, theme, renderers: code.renderers }));reader.relayout(chapterId?) is there for any renderer whose output changes without an edit: it lays one chapter (or every laid-out chapter) out again from its document and keeps the reading position. Windowed chapters are the server's layout: use refreshChapter (below).
Page numbers
reader.setNumbering('global'); // book pages: 1…N over chapters, front matter i, ii…, inserted pages unnumbered
reader.setNumbering('local'); // chapter pages: 1…n in each chapterstate.current.position is "Page X of Y" in the current mode. The go-to box (goToInput) takes 12, xiv, 3:12 (chapter 3, page 12) and Arabic-Indic digits. A book page number whose chapters still have estimated counts is resolved chapter by chapter: the reader lays out only the chapters before the target (until the number lands in chapters whose counts are exact), not the whole book. state.navigating is true meanwhile; the toolbar's page box shows it (aria-busy and a small spinner). insertedPart(id, title, pages) builds covers, plates, title and blank pages: no number, no header/footer, skipped by "Page X of Y".
Deep links and restore: goTo({ chapterId, page }), goTo({ chapterId, blockId }), goTo({ chapterId, point }), goTo({ global: 120 }); save onLocationChange's ReaderLocation and pass it back as initial. A point or block id lands with its line at the reading line. When the target's page is already on screen (a heading further down a zoomed-in page) goTo glides there; otherwise it jumps. goTo(target, { behavior: 'smooth' | 'instant' }) forces either, and reduced motion always jumps.
await reader.pageText(chapterId, page) gives a page's plain text in reading order (right-to-left included): one line per paragraph, heading or table cell, read from the layout, so any page works, mounted or not (its chapter or window is loaded first); '' for a locked or missing page. Use it for an assistant's context, "explain this page" or read-aloud. On a server, pageText(bundle.layout.pages[n]) (/anchors) does the same from a stored bundle.
A host showing one chapter at a time (its source lists only that one) can still let readers reach the others: onOutsideTarget(target) is called for a goTo into a chapter the source doesn't list, and for a find hit there (the server's search may return hits from any chapter, with chapterTitle to name its group in the list and locked to grey it with a padlock and the reason). Open that chapter and goTo the same target once it's there; return false when it can't be opened (the hit is then shown as unavailable). Find never opens another chapter by itself: only a click or Enter does.
A find hit's target also carries find: { start, end, query, options }: the hit's range and the search that found it. Pass them on to the reader that shows that chapter, and it opens with the find bar on the same query and that hit current and marked; next and previous go on from there:
onOutsideTarget={(t) => (openChapter(t.chapterId, t.find), true)}
// …then, in the chapter's reader:
<FolioReaderShell initialFind={find && { query: find.query, options: find.options, at: { chapterId, start: find.start } }} />Without the shell, createFind(reader).restore({ query, options, at }) does the same: once the reader has its chapters it goes to at, searches, and makes the hit there current (the next one in its chapter if the text moved).
Hosts can draw over pages (lecture ink, stamps) with pageOverlay (FolioReaderView, FolioReaderShell): (at) => ReactNode, called for each painted page with { chapterId, page, width, height } and drawn in that page's own px at zoom 1, above its content and layers. It scales, moves and survives repaints with the page (a portal into a slot kept per page). overlayPointer: 'capture' lets it take pointer input (a recorder drawing): text selection and page turns by tap or swipe are off and the turn buttons hide. Without React: reader.pageSlots() / onPageSlots(fn) / setOverlayPointer(mode), and reader.pageRect(chapterId, page) for a mounted page's box on screen. reader.rangeRects(range) gives a range's boxes on each mounted page it reaches, [{ chapterId, page, rects: [{ x, y, width, height }] }] in page px at zoom 1 (the overlay's own coordinates: pin a margin icon beside a passage). They come from the page's text layer, so DOM and canvas pages alike; pages not mounted give nothing (goTo the range first, or ask again on onPageSlots).
Every page carries Folio's mark: a small "Made with Folio" in its bottom-end corner, inked to read at WCAG AA on the page in every theme (light, sepia, dark, or a host's page colour), on screen, in canvas pages, on printed pages and on zoomed images (exported PDFs carry their own, in the same corner). On screen it is never smaller than 11px at any zoom: zoomed out, it grows within the page's margin. It is built in: credit (on createReader, FolioReaderView and FolioReaderShell) moves it to another corner and tunes its tone and opacity within CREDIT_MARK_LIMITS; nothing removes it.
Page scrubber
In both views, a handle beside the scrollbar shows while the book moves, with "Page 12 of 40" and the chapter's title in a bubble (it fades a moment after). Drag it, by mouse or touch, to fly through the book. In the scroll view the view jumps page by page as the bubble counts, once a frame; meanwhile pages mount as blank frames and nothing is fetched or painted, real pages paint when the handle rests (150 ms) or is let go, and the drop lands on that page. In the paged view no page turns while it moves: the bubble follows the handle and the page (or the spread holding it) turns once, where the handle rests or is let go, and the toolbar's page box follows; turning a page (buttons, keys, swipes, the page box) moves the handle and shows it a moment. The track spans the whole book from the server's exact counts (pageCount in the chapter list), else each chapter's estimate, so it is right before chapters load.
It is placed from the first frame, before anything scrolls, and faded it still takes the pointer: press the handle where it is to drag at once, or hover the strip along the edge to show it (on touch screens, a first tap on the strip shows it; a press once shown jumps the handle there). Keyboard focus shows it too.
It is a role="scrollbar" controlling the scroller (aria-valuenow is the page, aria-valuetext "Page 12 of 40, Chapter 3"): Tab to it, then the arrows move a page, PageUp/PageDown a tenth of the book, Home and End to its ends. It sits at the inline end, clear of the native scrollbar (the left in right-to-left books), grows while grabbed and on touch screens, and doesn't fade with reduced motion. scrubber: false (createReader, FolioReaderView) or hide: ['scrubber'] (FolioReaderShell) leaves it out. Its track stays below focus mode's header while that header shows, and below the host's own bars laid over the view's top with scrubber: { clear: () => [bar] } (also through FolioReaderShell); strings.scrubber and strings.pageOf translate it (Arabic in READER_STRINGS_AR). The editor and the book app use the same one (createScrubber and SCRUBBER_CSS from @nextgensoftwares/folio-a11y, PageScrubber in @nextgensoftwares/folio-react): restyle it with --folio-scrub-thumb, --folio-tooltip-bg / --folio-tooltip-fg and --folio-focus.
The scroller's own scrollbar is thin and drawn in --fr-scrollbar (by default --folio-scrollbar, else the theme's muted colour), 3:1 or more on the backdrop in the light, sepia and dark themes.
Plugins
Reader plugins have the FolioPlugin shape a reader understands (pageLayers, colors, renderers, exporters, ui.items with reader: true) plus attach:
const hl = highlights({ store: { load: api.highlights, save: api.saveHighlight, remove: api.deleteHighlight } });
createReader(el, {
source, layout,
variables: { nid: user.nationalId, email: user.email },
plugins: [
watermarkPlugin({ text: 'NID:{{nid}}\n{{email}}', opacity: 0.07, angle: -40 }),
protectPlugin({ copy: { maxChars: 200 }, print: 'current-page' }),
hl.plugin,
],
});Highlights: anchors are
TextAnchors: block id + textblock path + offsets, plusquote/prefix/suffix. On load each one is re-found withreanchor: exact, else the same quote elsewhere by context ('moved'), else an approximate match when the quote was reworded ('fuzzy', with aconfidence), elseorphaned. The placed highlight carriesreanchored: { how, confidence };highlights({ fuzzy: false })turns the approximate pass off, or passFuzzyOptionsto tune it. The same DOM-free code runs on a server (see Anchors on the server).hl.flash(range)flashes a range;visibleLayersfiltersmine/shared/teaching.toolbarItem: falseleaves out the toolbar's "Highlight" item (hosts that highlight from their own selection menu).Several highlight layers: each
highlights()writes one decoration set,'highlights'by default. A second one (checkpoints, exercises) takes its owndecorationKeyand never replaces the first's marks; it adds no toolbar item unlesstoolbarItem: true, and itsonClickgets its own marks only:tsconst notes = highlights({ store: notesStore, onClick: openNote }); const checkpoints = highlights({ store: checkpointStore, decorationKey: 'checkpoints', colors: { cp: 'rgba(59,130,246,.35)' }, onClick: (h) => openCard(h.id) });Any decoration can be clicked:
reader.onDecorationClick((d, e, key) => …)fires for marks with anidthat areclickable(default:kind: 'highlight'; find results never), with the set'skeyfromsetDecorations(key, list).{ kind: 'exercise', id, clickable: true, range }makes your own kind clickable.Links to a passage:
selectionLink(reader, { buildUrl })makes a "copy link to selection" URL andseekTextLink(reader, location.search)opens one (textLinkPlugin()adds the action to the reader's menu). See Links to a passage.Find:
createFind(reader)searches loaded chapters (Arabic diacritics, tatweel and letter variants ignored) and merges the source'ssearchhits. Windowed chapters are left tosearch. The shell's find bar lists the hits grouped by chapter, each with its printed page (book-wide numbers by default, as the toolbar shows them, or "Not loaded yet") and every match in its snippet marked with the same matching rules, server snippets included. A status line announces "12 matches in 3 chapters", "Searching the whole book…" or a failed server search. Enter / ↓ and Shift+Enter / ↑ step through the hits; a new search starts at the first hit from the page being read. In the shell the find bar floats over the pages as a card (<ReaderFind overlay>), so opening it never moves them; picking a hit folds the list so its page shows (the list button brings it back). Find marks (and every decoration) repaint a frame after they change, measured in one batch: pages on screen first, the other mounted pages when the browser is idle, so typing never waits on them. A host building its own list can usegroupResultsandsnippetMatcher/snippetParts(from/react) andfind.pageLabel(result).Tables of contents:
tocReaderPlugin()from@nextgensoftwares/folio-plugin-toc/readerlays outtableOfContentsblocks as the editor does (dot leaders, page numbers on the far side) and makes each row a link to its heading: a focusable<a>over the row's text named "Title, page 12" (labeltranslates it), drawn over canvas pages too. Page numbers come from the chapter's own layout:localLayoutapplies the plugin'swrapLayout(any reader plugin can wrap the layout this way). A worker or server layout needstocRendererin its renderers andwithTableOfContentsaround its layout. A TOC block'sscopeis'chapter'(default: this document's headings) or'book'(the editor's Lists → All chapters): every chapter's headings, for books whose chapters are separate documents. The layout asks the host for the book around the document:withTableOfContents(next, { book: (doc) => ({ chapterId, chapters: [{ id, title, headings: [{ level, text, page, block, blockId }] }], pageLabel }) })(tocPlugin({ book }),tocReaderPlugin({ book })forlocalLayout); without it the TOC lists its own document. A server builds it from what it stores:bookTocOf(bundlesInOrder, chapterId)(/anchors; a chapter not laid out yet can be its metadata), andhasBookToc(doc)says which chapters need it (key their stored layout by the outline too, so they are laid out again when another chapter changes). In the reader,links: 'all' | 'same-chapter' | 'none'sets which rows link; rows of locked chapters (access(chapterId)returningfalseor a reason, else the reader'spageAccess) are plain, dimmed, with a padlock and the reason. A row in a chapter the reader doesn't hold goes throughnavigate(link)(a host showing one chapter at a time changes its route there); without it such rows are plain text. The heading a row goes to pulses briefly (atoc-pulsemark,pulsems, default 1400,0turns it off), so a jump to a heading already on screen still shows where it landed.Themes, zoom, display:
setTheme('light' | 'sepia' | 'dark'),setZoom(n | 'fit-width' | 'fit-page'),setDisplay('single' | 'spread'),toggleFullscreen(). RTL books: spreads and ←/→ followdirection. A chapter withspread: falsein its meta (slide decks) keeps one page per row in the spread display. A fit zoom measures the view again after laying out, so a scrollbar that appears never makes the pages overflow. In a chapter with mixed page sizes (a landscape page in a portrait Word chapter), a fit zoom keeps the chapter's zoom, but any page that would overflow the column (or the view, at fit-page) is scaled down to fit. Pages are never scaled up, and in a spread the row shares one box.pageZoom(chapterId, page)gives a page's zoom on screen. Page slots, overlays, locations andgoTostay in page px at zoom 1. A number zoom is never capped. The fit modes keep fitting as the window or panel resizes, until the user zooms by hand. In the shell's toolbar the zoom percentage is a menu at every width: Fit width, Fit page (a fit mode shows as "Fit · 80%") and 50–200%, with − and + beside it on wide screens.hide: ['fit']leaves only the presets;hide: ['zoom']removes it. Hiding the view menu's sections or'settings'no longer hides zoom on narrow screens.view: 'paged'(orsetView('paged'), the toolbar's Reading switch) shows one page, or one spread, at a time at fit-page zoom: side buttons, ←/→, PageUp/PageDown/Space, Home/End, the wheel, swipes and click zones on the outer fifths (turnZones: falseturns those off) all turn pages, mirrored in right-to-left books. The new page slides in from the reading direction, except underprefers-reduced-motion.pageHash: truekeeps#page=3:12in the URL and follows any go-to-page input put there (12,iv,3:12). The side buttons (turnButtons):'gutter'(default) beside the page,'edge-hover'on its edges while the reader is hovered,'page-hover'on its edges only while a page (or a button) is hovered or one is focused, never on touch-only screens;'toolbar'or'none'. "Previous" hides on the book's first page and "next" on its last once page counts are exact (withonChapterEndset, "next" stays: turning goes on to the host).
The shell's host slots
FolioReaderShell (from @nextgensoftwares/folio-reader/react) has three slots for the host's own UI, so a host does not need to rebuild the reader's chrome:
<FolioReaderShell
source={source} layout={layout} interaction="select" plugins={[hl.plugin]} highlights={hl} locale="ar"
header={<nav aria-label="Breadcrumbs">Course › Unit 2 › Chapter 4 <ChapterPicker /></nav>}
panel={{
label: 'Study', content: <StudyRail />, // notes, quizzes, cards…
open, onOpenChange: setOpen, // or defaultOpen (uncontrolled)
width: 340, breakpoint: 960, side: 'end',
}}
selectionActions={[
{ id: 'hl', label: 'Highlight', onSelect: () => hl.add() },
{ id: 'note', label: 'Note', icon: <NoteIcon />, onSelect: ({ anchor, text }) => openNote(anchor, text) },
{ id: 'ask', label: 'Ask AI', when: ({ text }) => text.length > 3, onSelect: ({ text }) => ask(text) },
]}
/>| Prop | Type | Notes |
|---|---|---|
header | ReactNode | A bar above the toolbar (breadcrumbs, chapter navigation). Hidden in focus mode. |
panel | ReaderShellPanel | The host's side panel. Docked beside the pages when the shell is at least breakpoint px wide (default 900), a modal drawer below that. Its content stays mounted while closed. |
panel.label / icon | string / ReactNode | Names the panel, its toolbar toggle and the drawer's title. |
panel.open / defaultOpen / onOpenChange | Controlled or uncontrolled; by default open when docked, closed as a drawer. | |
panel.width / side / toggle | number (320) / 'start' | 'end' ('end') / boolean (true) | Sides are logical: 'end' is on the left in right-to-left. |
selectionActions | ReaderSelectionAction[] or (ctx) => ReactNode | The host's buttons in the reader's selection popover. Needs interaction: 'select'. |
brand / title | ReactNode | The host's mark and the book's title at the toolbar's start, after the contents toggle (as in FolioApp's app bar). The title hides under 720 px; a string title also names the reader region. |
contents / contentsLabel | ReactNode or (ctx) => ReactNode / string | The contents panel's own content instead of the built-in chapter list. The function gets { reader, state, navigate(target), close() }; navigate closes the panel on narrow screens. The panel, its toggle (named by contentsLabel, default "Contents") and its drawer stay the shell's. |
hide | ReaderShellHide[] | Built-in parts to leave out. Toolbar: 'pages' (previous, page box, next), 'chapterTitle', 'zoom', 'fit', 'settings' (the whole view menu; it also goes when all its sections are hidden) and its sections 'theme', 'view', 'display', 'numbering', 'chapter'; 'fullscreen', 'highlights', 'more' (narrow screens' menu; the "Made with Folio" credit always stays), and any plugin item by its id. Shell: 'toc' (the contents panel and its button; toc={false} only starts it closed), 'find', 'focus'; focus bar: 'focusZoom', 'focusPosition', 'focusProgress'. 'theme' also hides focus mode's page swatches, for hosts that switch light and dark themselves. |
focusZoom | ReaderZoom | 'keep' ('fit-width') | Zoom in focus mode: by default the page fills the screen's width (cap the column with the --fr-focus-width CSS variable); the reader's zoom comes back on exit. |
focusWidth | number | 'full' ('full') | The reading column's width in focus mode, CSS px (sets --fr-focus-width). |
focusHeader / focusBar | ReactNode | The host's bar across the top in focus mode (it slides in with the bottom bar when the pointer moves and out while reading), and its items in the bottom bar. It stays while a menu it opened is open (a trigger with aria-expanded="true", wherever the menu is portaled), or while focus or the pointer is in an element it owns: one its controls name with aria-controls / aria-owns, or one the host marks data-folio-keep-awake. |
focusSelection | boolean (false) | Keeps selectionActions (the popover over selected text) in focus mode, for a full-screen reading mode that keeps notes and highlights. |
focusBarPosition | 'bottom' | 'top' | 'header' ('bottom') | Where focus mode's bar (zoom, page, way out) sits: floating at the bottom or the top, or inside the header's slide-away bar after focusHeader's content: one auto-hiding bar. |
An action is { id, label, icon?, when?(ctx), onSelect(ctx), keepOpen? } (the shared SelectionAction type from @nextgensoftwares/folio-a11y). The context is { reader, range, text, anchor, rect, close() }; anchor is the selection's TextAnchor when the shell has the highlights controller. After an action runs, the popover closes and the selection clears, unless the action sets keepOpen. Labels go through the shell's messages; an action whose when throws is hidden, and a failing onSelect is logged. A render function's popover (a dialog) can hold a form: it stays open while focus or the pointer is inside it, even though the page selection moves away, keys typed in its fields stay its own, and close() from inside returns focus to the pages.
The toolbar names the current chapter beside the page counter (a lock marks a locked chapter); the counter never wraps, and the chapter name gives way under 440 px.
The drawer is a modal dialog (focus moves in and stays there, Escape or the scrim closes it, focus returns to its toggle). The popover is a toolbar: Escape dismisses it, Alt+F10 moves focus into it. With a locale, the shell's chrome takes the locale's direction (an Arabic UI puts the panel and the TOC on the mirrored sides) while the pages keep the book's own direction.
FolioApp (editor) and SlidesApp / SlideDeck (slides) take the same brand, credit, locale and FolioHostTheme, and slides take selectionActions too: see Slides shell.
On narrow screens (under 720 px) the reader shell's toolbar keeps navigation, the view menu, the host's toolbarEnd and the panel toggle; find, highlights, focus mode, plugin items, full screen and the credit move into a More actions menu, so the bar fits a 320 px phone in either direction. Keep toolbarEnd small (one or two buttons) for the same reason.
Theming the shell
FolioReaderShell reads Folio's design tokens. Every --fr-ui-* colour, the font and the radii are var(--folio-<token>, <reader default>), and the shell root is a .folio-ui. One <FolioHostTheme/> (from @nextgensoftwares/folio-react) themes the editor, slides and the reader alike. A reader-only app can render hostThemeCss(tokens) from @nextgensoftwares/folio-tokens (pure TS, no React UI) in a <style>.
<FolioHostTheme tokens={{ bg: 'var(--surface)', text: 'var(--ink)', accent: 'var(--brand-600)', border: 'var(--line)', radius: '4px', font: 'var(--font-body)' }} />
<FolioReaderShell source={source} layout={layout} chromeTheme="system" pages="paper" />| Prop | Type | Notes |
|---|---|---|
chromeTheme | 'light' | 'dark' | 'system' | 'page' ('page') | The chrome's light or dark, apart from the page theme. 'page' follows the page (sepia tints included); 'system' follows data-folio-theme when set (setFolioTheme, followHostTheme), else the OS. |
pages | 'theme' | 'paper' ('theme') | 'paper' keeps pages light (no colour adapter) on a canvas that follows the chrome, as in the editor; the Page control and focus swatches are hidden. |
| Shell variable | Folio token |
|---|---|
--fr-ui-bg (toolbar, TOC, header) | chrome |
--fr-ui-panel (menus, inputs, side panel) | bg |
--fr-ui-fg / --fr-ui-muted | text / muted |
--fr-ui-border / --fr-ui-hover / --fr-ui-seg | border / hover / bg-2 |
--fr-ui-on / --fr-ui-on-fg / --fr-ui-accent | on-bg / on-fg / accent |
--fr-ui-shadow | pop-shadow |
| focus ring, invalid page number, font, radii, focus-mode canvas | focus, danger, font, radius-sm/radius/radius-lg, canvas |
Hand-written overrides still work. The --fr-ui-* variables are declared on .fr-shell (.fr-shell[data-theme=dark] and [data-theme=sepia] for those themes), and FolioHostTheme only sets --folio-*. A host rule more specific than those (for example .app .fr-shell.fr-shell) wins in every theme. The shell's sheet loads last, so equal specificity loses. Sepia's chrome tints stay the reader's own. With no Folio tokens on the page, the shell looks as it did in 0.15.
Previews and locked chapters
pageAccess decides which pages show. Return true to show a page; anything else locks it, and a string says why:
pageAccess: ({ chapterId, page }) =>
owned.has(chapterId) || page < 3 || 'Buy the book to keep reading.',A locked page is a placeholder with a padlock and the reason (also in its accessible name); its content is never painted. Each chapter in the state has access: 'locked' (its first page is locked), 'preview' (it opens, its last page is locked) or 'open', with lockReason. The contents panel marks locked and preview chapters (the reason in the tooltip and for screen readers). After an unlock, call reader.repaint(). The server must still never send locked content.
Image zoom
imageZoom: true lets readers click or tap an image to see it enlarged:
createReader(el, {
source, layout,
resolveMedia: (a) => signedUrl(a.mediaId), // pages and the lightbox
imageZoom: { resolve: (a) => signedUrl(a.mediaId, { full: true }), onOpen: (a) => track('zoom', a.mediaId) },
});- The image opens in a modal dialog over the reader (its
altnames it), at up to its full resolution: wheel or pinch to zoom about the pointer, drag to pan, double-click to toggle,+/−/0keys. Esc, a click beside the image, the close button or the browser's Back closes it, and focus returns where it was. - Its URL comes from
imageZoom.resolve, elseresolveMedia, else the image'ssrc(only safe URLs, as on the pages). - It is drawn on a canvas, never as an
<img>: no image URL in the DOM, no "Save image as…" (the context menu and dragging are blocked), no download button. The pages' layers are drawn over it as on canvas pages, so awatermarkPlugin(with itsvariables) andcanvas.forensicmarks are on the zoomed image too. Like every protection here it's a deterrent, not a lock. - It opens on a click without a drag or a text selection, never on links, turn buttons or host overlays, and in paged view a tap on an image opens it instead of turning the page. Canvas pages (
paint: 'canvas') work the same (the image is found in the page's layout). Drawn chapters' pictures (deck slides) don't open. - The dialog's code is a lazy chunk (about 2.6 KB gzipped) loaded on the first open.
Slide decks as chapters
A deck can be a chapter of the book, one page per slide. deckChapter from @nextgensoftwares/folio-plugin-slides/viewer lays it out with your measurer. The slides are painted on a canvas, as in a slide show, with the text of their text boxes as an invisible layer on top for selection, find, highlights and screen readers. Slide titles become the chapter's headings. Add slidesReaderPlugin() so the slides are drawn on screen and in PDF exports:
import { deckChapter, slidesReaderPlugin } from '@nextgensoftwares/folio-plugin-slides/viewer';
const deck = deckChapter(presentation, { measurer: fonts });
const source = memorySource([
{ meta: { id: 'intro', title: 'Introduction' }, content: { doc } },
{ meta: { id: 'deck', title: 'Lecture slides', ...deck.meta }, content: deck.content },
]);
createReader(el, { source, layout, plugins: [slidesReaderPlugin()] });deck.meta carries paint: 'drawings'. It paints the chapter's pages on a canvas whatever paint the reader uses; its lines only make up the text layer. Any chapter can be painted this way with paint: 'canvas' in its meta. Text in boxes inside groups can be selected and found, and so can text tilted by up to 20° (its selection is a level box over it). Text turned further, flipped, and in tables is drawn but can't be selected or found yet. A slide's text boxes are read in reading order, not in the order they're drawn: the slide is split at its widest clear gaps (a column gap: left part first, right first on an RTL slide; a row gap: top part first), and boxes no gap separates are read in rows. A selection or highlight from one box to another takes only the boxes between them on screen. The invisible text is stretched onto the drawn words, so a selection lines up with them even where the browser sets the text in a different face than the slide was laid out with. Pictures load from their src as they are, unless the plugin is given resolveSrc: it maps a stored src (a host path that needs a signed URL) to the URL to load, and is asked each time a slide is painted or exported, so a repaint mints expired URLs again. Null skips the picture; the resolved URL still has to pass the reader's safe-URL check.
In the spread display ('Two pages') a deck stays one slide per row: its meta has spread: false (the default for paint: 'drawings' chapters; any chapter can set it, or spread: true to pair drawn pages). Such a chapter gets its own zoom: in a fit mode it is fitted itself, so a slide fills the width as in the single display; at a set zoom its rows are as wide as the spreads around them, and zooming in or out keeps both in step. The percentage shown is the zoom of the chapter the reader was fitted to.
slidesReaderPlugin({ resolveSrc: (src) => (src.startsWith('/media/') ? api.viewUrl(src) : src) });A slide's colours are its design, so the dark and sepia themes (and a plugin's colors) leave paint: 'drawings' chapters as they are, the same as exports do: the slide stays on its own white or coloured background, and only the reader around it takes the theme. Folio's mark is still inked for the pixels under it. To have a chapter recoloured anyway, set recolor: true in its meta (recolor: false keeps any other chapter's own colours).
A chapter's meta, paint included, is in reader.getState().chapters[i].meta, so a host can tell a deck from a document chapter (show "Slide 3" rather than "Page 3", or slide thumbnails).
Page thumbnails
reader.thumbnail(chapterId, page, { width, dpr? }) draws a page small for your own navigation, such as a slide rail or a list of chapters. It returns a canvas width CSS px wide, sharp at dpr device px per CSS px (default devicePixelRatio). It loads the page's chapter, or its window, without moving the reader. A thumbnail is navigation, not a page view: it is drawn in the page's own colours whatever the theme, and without page layers, so it has no watermark and no "Made with Folio" mark. For that reason it is capped at 240 CSS px wide and 480 device px, so it can't stand in for the page. A deck's slides are drawn by the reader's canvas painters (slidesReaderPlugin), other pages from their layout. Drawings are cached per page and size until the chapter is laid out again, and each call gets a canvas of its own. It resolves to null for an unknown chapter, a page out of range or a locked page.
<ReaderPageThumbnail reader={reader} chapterId="deck" page={2} width={120} /> from @nextgensoftwares/folio-reader/react draws one once it comes near the view. It is an image to screen readers, named "Slide 3" in a deck and "Page 3" otherwise, or by its alt prop. Wrap it in a button or link to make it go somewhere:
const at = reader.getState().current;
{[-2, -1, 0, 1, 2].map((d) => at && at.page + d >= 0 && (
<button key={d} onClick={() => reader.goTo({ chapterId: 'deck', page: at.page + d })}>
<ReaderPageThumbnail reader={reader} chapterId="deck" page={at.page + d} width={96} />
</button>
))}Windowed (server) chapters
When the source has loadPages(id, from, to) and the metadata gives a chapter's pageCount, the chapter is windowed: the server lays it out (toPlainLayout(layout).pages) and the client only ever holds the pages near the viewport. Its document never reaches the client. Everything below works with windows plus a few optional hooks.
const source: ReaderSource = {
listChapters: () => api.get(`/books/${id}/chapters`), // with pageCount, pageSize, headings
loadChapter: () => Promise.reject(new Error('windowed only')),
loadPages: (chapterId, from, to) => api.get(`/books/${id}/chapters/${chapterId}/pages`, { from, to }), // { pages, blockIds }
search: (q) => api.get(`/books/${id}/search`, { q }), // hits with `page`
locate: (query) => api.post(`/books/${id}/locate`, query), // optional
};Fetching
- Pages are fetched in aligned windows of up to 8 pages, clipped to what is on screen plus at most 8 pages past (and before) the current page, in book order across chapter ends. That holds for page turns, rapid turns, zoom changes, spreads and the scroll view.
- Pages more than a window away from the viewport are dropped, and fetched again on return. Chapters far from the viewport are never asked for.
Fonts
Pages laid out on the server can use any family. With ensureFonts, a page window (or a chapter sent as a layout) stays a placeholder until the families it uses are loaded: the chapter's families metadata (chapterMeta and publishChapter fill it from the layout) and the families on the pages themselves. Each family is asked for once; a failed load is logged and the pages paint anyway.
const fonts = readerFonts({ engine, loadFamily }); // @nextgensoftwares/folio-reader/fonts
createReader(el, { source, ensureFonts: fonts.ensure });Server hooks
| Hook | Used for |
|---|---|
loadPages(id, from, to) → { pages, blockIds? } | the pages themselves (required) |
search(query) → ReaderSearchHit[] | find, and passage links without locate. Give each hit a page (0-based chapter page) so the reader fetches the right window at once. |
locate(query) → { page, start?, end? } | optional: the page of a point, a block id or a quote (quote, quoteEnd, prefix, suffix, page hint). Used by goTo, by find hits without a page, and by passage links. |
Without locate, the reader uses page hints, then searches the windows by block range (about log₂(pages / 8) page fetches).
Server endpoints
The server entry has a helper for each hook. Publish each chapter once with publishChapter and store the JSON it returns (a ChapterBundle: metadata, the plain layout, a page index with block ids, the text). Every endpoint then answers from the stored bundle, with no document and no layout engine:
import { layoutDocument } from '@nextgensoftwares/folio-layout';
import { publishChapter, chapterWindow, searchBook, locateInChapter, type ChapterBundle } from '@nextgensoftwares/folio-reader/anchors';
// Publish time: lay out once (the same fonts, theme and math as the client) and store the bundle.
const bundle = publishChapter(doc, { layoutDocument, options: { measurer, theme, math } }, { id: chapter.id, title: chapter.title, lang: 'ar' });
await db.chapters.put(chapter.id, JSON.stringify(bundle));
const load = async (id: string): Promise<ChapterBundle> => JSON.parse(await db.chapters.get(id));
app.get('/books/:book/chapters', async (req, res) => {
// Access: may req.user open this book? List only the chapters they may read.
const ids = await db.books.chapterIds(req.params.book);
res.json(await Promise.all(ids.map(async (id) => (await load(id)).meta)));
});
app.get('/books/:book/chapters/:id/pages', async (req, res) => {
// Access: may req.user read this chapter? Every window request repeats the check.
res.json(chapterWindow(await load(req.params.id), Number(req.query.from), Number(req.query.to))); // clamped, at most 16 pages
});
app.get('/books/:book/search', async (req, res) => {
// Access: search only the chapters req.user may read.
const chapters = await Promise.all((await db.books.chapterIds(req.params.book)).map(load));
res.json(searchBook(chapters, String(req.query.q ?? ''))); // hits with block ids and `page`
});
app.post('/books/:book/locate', async (req, res) => {
// Access: may req.user read req.body.chapterId?
res.json(locateInChapter(req.body, await load(req.body.chapterId)));
});chapterWindow(source, from, to, { maxPages })takes a bundle, a live layout or a storedtoPlainLayoutresult (with{ doc }or{ blockIds }for the ids). It clamps[from, to)to the chapter and tomaxPages(default 16,SERVER_LIMITS.pages).blockIdslists exactly the blocks those pages show.searchChapter(chapterId, source, query, options)andsearchBook(chapters, query, options)match like the reader's find: Arabic diacritics, tatweel and letter variants are folded, andcaseSensitive,wholeWordandloosework as there. A query over 256 chars finds nothing, and at most 500 hits come back (maxQuery,limit). Keepregexoff for client queries.searchBookkeeps the order given and applies one limit to the whole book.locateInChapter(query, source)answers a point, a block id or a quote with context (nearest the client'spagehint), with block ids on the points. Strings are capped like passage links (TEXT_LINK_LIMITS), and a malformed query givesnull.- Other sources: a document, or its
docTextRunswith apageIndex(andblockIds).publishChapter(doc, layout, info)takes a layout you made yourself (in a worker, or from a cache). With{ text: false }the bundle has no text; windows and point or block locates still work.chapterMeta(doc, layout, info)gives the metadata alone. - On republish: publish again, store the new bundle, re-anchor stored highlights (
reanchor, below) and callreader.refreshChapter(id).
Very long chapters: layout in chunks
publishChapter lays a chapter out whole before any page can be served. For a chapter of thousands of pages, lay it out in chunks instead: layoutChapterUntil stops once the pages asked for are final, and the bundle grows with each chunk (appendChunk). The endpoints take the partial bundle; past its pages they say how far to lay out first.
import { layoutDocument } from '@nextgensoftwares/folio-layout';
import { appendChunk, chapterWindow, isPartial, layoutChapterUntil, type GrowingBundle } from '@nextgensoftwares/folio-reader/anchors';
const kit = { layoutDocument, options: { measurer, theme, math } };
// A worker: the first pages now, the rest in the background, stored every chunk.
let bundle: GrowingBundle | null = null;
while (!bundle || isPartial(bundle)) {
const resume = bundle && isPartial(bundle) ? bundle.partial.resume : null;
const chunk = layoutChapterUntil(doc, kit, { untilPage: (bundle?.layout.pages.length ?? 0) + 200, resume, kitKey: 'fonts-v3' });
bundle = appendChunk(bundle, chunk, doc, { id: chapter.id, title: chapter.title });
await db.chapters.put(chapter.id, JSON.stringify(bundle));
}
// The pages endpoint: answer from what is laid out, or lay out further first.
const win = chapterWindow(stored, from, to);
if ('needsLayout' in win) {
/* layoutChapterUntil(doc, kit, { ...win.needsLayout, resume: stored.partial.resume }), append, store, answer */
}- Exact pages. Blocks past the target are only estimated; the pages a chunk returns stop two pages before the first one holding an estimated block, and are the pages a single complete layout gives. Fields that count pages not laid out yet are the exception: page totals in headers and footers (
numpages,sectionpages) and tables of contents print estimates until the completing chunk, which lists the pages it redrew inrevised(appendChunkswaps them in). - Resume.
LayoutResumeis plain JSON (v, the document's fingerprint, yourkitKey, pages and blocks done, a hash per page). Store it with the bundle. A resume for another version of the document or another kit is refused (restarted: true) and layout starts over at page 0. - Cost. In one process, calls on the same document object reuse what is already measured: a chunk costs about the pages it adds, plus O(blocks) bookkeeping. A resume in a new process measures the blocks before it once more. On an 8,114-page synthetic chapter (57,000 blocks, HarfBuzz, Node): first page 0.4 s against 6.8 s for the whole layout, then 150-250 ms per 100 pages; a resume at page 1,000 in a fresh process 1.1 s.
- Lists and locate.
meta.estimatedPages(pages so far plus the rest at the measured pages-per-char rate) feeds "page n of about N" until thepageCountis exact.headingPages(bundle)gives each heading's page, or null past the laid-out pages;searchChapterfinds text without layout (hits past the pages have a block and offset but nopage), andlocateInChapteranswers{ needsLayout: { untilBlock } }for them. - A short chapter completes in the first call;
publishChapterstays the simplest call for those.
What works on windows
- Find:
createFind/<ReaderFind>leave windowed chapters tosource.search. Next and previous go to hits in pages that aren't loaded: the window is fetched, shown, and the hit is marked. - Selection and highlights:
selectionAnchor()andadd()build anchors from the loaded pages' text. When the selection sits at the edge of the loaded pages,add()fetches the neighbouring page first, so the quote, prefix and suffix are the ones the server computes.highlights({ store })asks for a windowed chapter's highlights once its first pages arrive, trusts their points as stored (the server re-anchors them on publish), paints them on loaded pages only and repaints as windows arrive or come back. - Passage links: see below;
?text=seek works throughlocate, the link's page hint, orsearch. - Protection:
watermarkPluginand other page layers paint on each window page as it arrives;protectPlugincopy limits apply as usual.
When the server republishes a chapter
reader.refreshChapter(chapterId) (or an array of ids) drops what the reader holds for it and keeps the reader open:
listChaptersis asked again, and the chapter takes its new metadata (page count, headings, page size);- its layout and page windows are dropped (requests in flight for the old version are ignored), and the pages on screen are fetched again;
- the reader stays on the same chapter page, or the nearest one when the chapter got shorter;
- plugins reload what they hold for it (
ReaderPlugin.onChapterRefresh):highlightsasks its store again once the new pages arrive.
It works for chapters laid out on the client too (their document is loaded again). Chapters added or removed need a new reader.
Links to a passage
import { selectionLink, seekTextLink, textLinkPlugin } from '@nextgensoftwares/folio-reader';
// "Copy link to selection" (or textLinkPlugin({ buildUrl }) as a menu action)
const url = await selectionLink(reader, { buildUrl: (p) => `/books/42?${new URLSearchParams(p)}` });
// → /books/42?chapter=c3&text=prefix-,quote,-suffix&page=14
// On open: go there and flash it (null when it can't be found)
await seekTextLink(reader, location.search);text uses the URL text-fragment syntax, [prefix-,]quote[,quoteEnd][,-suffix], with long quotes sent as their start and end (maxQuote, default 120; context 24 chars a side). textLinkParams gives the parts unencoded, with only the fragment's own syntax (%, ,, -, &) escaped, so put them in the URL through URLSearchParams, which encodes them once (formatTextFragment(t) alone is URL-ready; { raw: true } is the parameter form). parseTextLink also opens links whose text was encoded twice (made before this fix). A popover action can link a passage after the selection cleared: selectionLink(reader, { range }) or { anchor }. seekText(reader, target, { flash, color }) takes a parsed target. The DOM-free helpers (textLinkParams, parseTextLink, formatTextFragment, parseTextFragment, findQuote) are exported from the server entry too, for a locate endpoint. Links are untrusted input: each part is capped at 1,000 chars and the parameter at 4 KB (TEXT_LINK_LIMITS), and matching is linear in the chapter's length.
Anchors on the server
@nextgensoftwares/folio-reader/anchors is the reader's anchor code without DOM, React or editor code: anchors, chapter text, search, passage links, page indexes and page layouts (toPlainLayout, readLayout, docHeadings: a server, or a server in a Web Worker, can lay chapters out and serve their windows without the main entry). Use it in a backend:
import { docTextRuns, chapterText, reanchor, chapterPageIndex, pagesForAnchor, blockIdOf } from '@nextgensoftwares/folio-reader/anchors';
// On publish: re-anchor stored annotations against the new text…
const ct = chapterText(docTextRuns(doc));
const index = (id: string) => doc.content.findIndex((b) => blockIdOf(b) === id);
for (const note of notes) {
const hit = reanchor(note.anchor, ct, index, (i) => blockIdOf(doc.content[i]!) ?? undefined);
if (!hit) markOrphaned(note); // gone, or ambiguous
else save(note, { ...note.anchor, start: hit.range.start, end: hit.range.end }, hit.how, hit.confidence);
}
// …and store a page index next to the chapter's layout.
const pageIndex = chapterPageIndex(layout, doc.content.map(blockIdOf));
// Later, without loading the chapter: which page is this note on?
const pages = pagesForAnchor(pageIndex, note.anchor); // { page, endPage } (0-based chapter pages) or nullreanchor returns { range, how, confidence }:
'exact': the stored positions still hold the quote (confidence 1).'moved': the same quote elsewhere, chosen by matching context, then nearness (confidence 1).'fuzzy': the quote itself was reworded (words edited, inserted or deleted). It is found approximately: edit distance on the quote, scored with how well the prefix and suffix still fit and how near it is to its old block.confidenceis 0–1.null: the passage is gone, the best match is belowthreshold, two places score withinmarginof each other, or the anchor's own paragraph is still recognizable by its surroundings but reworded beyond the thresholds. It prefers no answer to a wrong one.
Options (FUZZY_DEFAULTS): threshold 0.7, minQuoteSimilarity 0.6, contextWeight 0.3, nearWeight 0.1, margin 0.08, maxCandidates 8, maxWork 4,000,000; { fuzzy: false } keeps exact and moved only. In tests, anchors whose quote had one or two words edited, inserted or deleted recover 98.6% of the time with none misplaced. Cost is bounded for any input: only 64 characters of context a side are used, quotes over 2,000 characters are matched by their head and tail, and a work budget turns pathological input into null (a re-anchor takes about 2 ms on a 350,000-character chapter).
chapterPageIndex(layout, blockIds?) is compact JSON (per page, its block range and the inline offsets of each textblock's lines). pagesForAnchor returns the pages where the reader shows the anchor's start and end. If the chapter changed since the anchor was made, reanchor first.
Accessibility
Pages are region landmarks named "Page 3 of 120, Chapter 2"; text is real text in reading order (bidi runs in logical order), headings are headings, math has its LaTeX as a label, decorative chrome (headers/footers, repeated table headers, watermarks) is hidden from assistive tech, and page changes are announced politely. Keys: ←/→ page, [/] chapter, Ctrl/⌘ +/−/0 zoom, Ctrl/⌘ F find; PageUp/PageDown/Space/Home/End scroll natively.
Security
- Document text is only ever inserted as text nodes; link targets and image URLs pass an allowlist (no
javascript:, nodata:text/html); colours go tobackground-color(neverurl()); styles use constructed stylesheets, so the reader runs under a strict CSP.renderMathoutput is inserted as HTML: use KaTeX withtrust: false. - Highlights without copying.
interaction: 'select'withprotectPlugin({ copy: 'block', copyNotice: '…' }): readers select text and the host's highlight popover works (selectionRects(),highlights().selectionAnchor()), while keyboard copy/cut, the context menu, dragging the text out andcopy/cutevents put only the notice on the clipboard. A deterrent: devtools, extensions and screenshots get around it. - Copy and print protection are deterrents. Anyone controlling the browser can bypass them. Print policies:
allow,current-page(only the page on screen prints, watermarked, with Folio's mark) andblock. - The watermark deters and traces; it can't prevent screenshots or cameras.
- Real limits belong on the server: send only allowed pages (windowed sources), enforce
pageAccessthere, count downloads incanExport's server twin. See Reader & protection.
Export
const { exportReaderPdf } = await import('@nextgensoftwares/folio-reader/export-pdf'); // pdf-lib loads only now
const pdf = await exportReaderPdf(reader, {
scope: 'chapter', // 'page' | 'chapter' | 'selection' | 'book' | { from, to, chapterId? }
canExport: (req) => api.allowDownload(req), // asked before anything is exported
pdf: { fonts, shaper: engine },
variables: { downloadId },
});The watermark (and any page layer with a PDF painter) is drawn into every page as vector text with this download's variables.
'page' is the page on screen. A range is 0-based and inclusive, clamped to what exists: { chapterId: 'ch3', from: 2, to: 9 } takes a chapter's pages, { from: 40, to: 59 } book-wide page positions (state.current.sequence) across chapter ends, laying out only the chapters up to the range's end. canExport gets the scope as given, the chapters touched and the page count.
Server-side watermarked download (Node / NestJS)
The authoritative copy should be stamped on the server, per user, without a browser. Everything involved is DOM-free: lay the chapters out with @nextgensoftwares/folio-layout and HarfBuzz (@nextgensoftwares/folio-fonts), then exportPagesPdf bakes the reader plugins' page layers into every page:
import { FontEngine } from '@nextgensoftwares/folio-fonts';
import { layoutDocument } from '@nextgensoftwares/folio-layout';
import { mapZoneConfig } from '@nextgensoftwares/folio-import';
import { watermarkPlugin } from '@nextgensoftwares/folio-reader';
import { exportPagesPdf } from '@nextgensoftwares/folio-reader/export-pdf';
const engine = await FontEngine.create({ fallback: ['Noto Sans Arabic'] }); // once per worker
for (const f of fontFiles) engine.addFont({ family: f.family, data: f.bytes });
const fonts = (spec) => fontBytesFor(spec); // the same files, by family/weight
let first = 1;
const layouts = [];
for (const ch of chapters) { // Folio documents, in book order
const hf = mapZoneConfig(ch.headerFooterConfig, { title: ch.title, bookTitle, author, firstPageNumber: first });
const layout = layoutDocument(ch.doc, { measurer: engine, theme, headerFooter: hf.config, variables: hf.variables, firstPageNumber: first, totalPages: bookTotal });
layouts.push(layout);
first += layout.pages.length;
}
const pdf = await exportPagesPdf(layouts, {
pdf: { fonts, shaper: engine, images: (src) => loadImageBytes(src), math }, // images/math as for exportPdf
plugins: [watermarkPlugin({ text: 'NID:{{nid}}\n{{email}}', opacity: 0.07, angle: -40, fontFamily: 'Geist', guard: false })],
variables: { nid: user.nationalId, email: user.email, downloadId },
});- Cache the unwatermarked layouts (or their page reports) per published version; only
exportPagesPdfruns per download. - The watermark is real text drawn at 7% opacity: it survives printing and copying the file, and it can be traced. It is not encryption; add
encryptPdf(permissions) from@nextgensoftwares/folio-export-pdfif needed. - Run it in a queue worker (it is CPU-bound), and keep one
FontEngineper worker. - Video, audio and file attachments print as cards without registering plugin-media's painters. For a code readers can scan, give them an absolute link:
pdf: { ..., mediaQr: true, mediaLink: (attrs, kind) => 'https://example.org/watch/' + idOf(attrs.src) }(kind:'video','audio','file','embed';nullprints neither link nor code). Deck pages (withslidesPdfPainters) get the same card over their media posters. See media cards.
A university library
- Publish. The server lays out each chapter with
@nextgensoftwares/folio-layout(math through@nextgensoftwares/folio-math, no browser needed), stores the pages (toPlainLayout), the page count, headings and block ids, and achapterPageIndex. It re-anchors stored annotations withreanchorfrom/anchorsand marks the orphans. - Students get
listChaptersmetadata only.loadPagesreturns page windows after checking enrolment and access (token per request);searchandlocateanswer from the stored text and index. The document JSON never reaches the browser. - The reader (
FolioReaderShell) shows them with the user's watermark,protectPluginand the host's highlights; the host's study panel sits inpanel, its breadcrumbs inheader, and Highlight / Note / Ask actions inselectionActions.onPageViewfeeds progress and analytics; passage links useselectionLinkandseekTextLink. - Staff edit in
FolioApp; slides useSlidesApp/SlideDeck. - Downloads go through
exportReaderPdffor UX, and the server re-checks quotas and stamps its own watermark withexportPagesPdf(above).
Not yet covered
- Laying out from a mid-chapter block cursor (
loadWindow → { blocks, cursor }): layout can't start inside a split block yet; windowed sources send page layouts instead. - Highlight hover callbacks with page rects; checkpoint markers at block positions.
- Windowed chapters: at extreme zoom-out every page on screen is fetched, even past 8; without
search, find covers only the loaded pages; a passage link whose distinguishing context spans several blocks may be missed withoutlocate(the reader then shows the link's page); highlights are re-anchored on the server, never on the client; rapid page turns are not cancelled. - Canvas pages repaint (not rescale) on zoom; mixed page sizes in one spread row are top-aligned.