@nextgensoftwares/folio-reader
Standalone, read-only book reader. Depends on @nextgensoftwares/folio-model, @nextgensoftwares/folio-layout and @nextgensoftwares/folio-render-canvas only: no @nextgensoftwares/folio-editor, no ProseMirror, no @nextgensoftwares/folio-react (a test fails the build if one sneaks in, see Bundle size). Guide: Standalone reader.
| Entry | What |
|---|---|
@nextgensoftwares/folio-reader | the reader (framework-free DOM), sources, numbering, anchors, search, plugins |
@nextgensoftwares/folio-reader/react | FolioReaderView, useReaderState, ReaderToolbar (navigation |
@nextgensoftwares/folio-reader/anchors | DOM-free, React-free server entry (anchors, chapter text, page indexes and page layouts): anchorFromRange, withBlockId, reanchor (exact, moved, fuzzy), reanchorExact, reanchorFuzzy, FUZZY_DEFAULTS, chapterText, docTextRuns, layoutTextRuns, docHeadings, blockIdOf, searchRuns, toPlainLayout, readLayout (lay chapters out and serve their windows without the main entry), chapterPageIndex, pagesForAnchor, pageOfIndexedPoint, passage-link helpers (textLinkParams, parseTextLink, formatTextFragment, parseTextFragment, findQuote, TEXT_LINK_LIMITS), and the endpoint helpers (publishChapter, chapterMeta, chapterWindow, searchChapter, searchBook, locateInChapter, SERVER_LIMITS), and incremental layout (layoutChapterUntil, appendChunk, headingPages, isPartial, bundlePages, docFingerprint) |
@nextgensoftwares/folio-reader/worker | workerLayout (main thread), serveLayout (in the worker; its setup may return a DOM-free math measurer such as folio-math's katexMathMeasurer(), then math is measured in the worker and only failures go to the main thread), mathKey, MathRequest, ToWorker, FromWorker |
@nextgensoftwares/folio-reader/fonts | readerFonts (prepare(doc, theme) before a local layout, ensure(families) for the reader's ensureFonts, ready()), chapterFamilies (wraps createFontLoader from @nextgensoftwares/folio-fonts) |
@nextgensoftwares/folio-reader/export-pdf | exportReaderPdf, ReaderPdfOptions, ReaderExportRequest, ReaderExportScope ('page' (on screen) | 'chapter' | 'selection' | 'book' | ReaderPageRange), ReaderPageRange ({ chapterId?, from, to }: 0-based, inclusive, clamped; a chapter's pages, or book page positions without chapterId), all carrying the reader's plugins (watermark) and variables; exportPagesPdf(layouts, { pdf, plugins?, variables? }), PagesPdfOptions (DOM-free: the server-side watermarked download, see the reader guide) |
Reader
createReader(container, options): FolioReader
Mounts a reader into container (give it a height). FolioReader implements ReaderHandle. ReaderOptions:
| Option | Meaning |
|---|---|
source: ReaderSource | chapters and their content (required) |
layout?: ChapterLayoutFn | lays out chapters that arrive as documents: localLayout(...) or workerLayout(...) |
plugins?: ReaderPlugin[] | watermark, protection, highlights, host plugins |
variables? | {{variables}} for page layers (user, email, nid…) |
paint?: 'dom' | 'canvas' | real text (default) or canvas pixels over an invisible text layer; canvas?: CanvasPaintOptions |
interaction?: ReaderInteraction | 'none' (default: no selection) or 'select'; same values as <FolioView readerInteraction> |
numbering?: NumberingMode | 'global' (default) or 'local' |
display?: ReaderDisplay, firstPageAlone? | 'single' or 'spread' |
view?: ReaderView | 'scroll' (default) or 'paged': one page or spread at a time, turned with side buttons, ←/→ (mirrored in RTL), PageUp/PageDown/Space at the page edges, Home/End, the wheel, swipes and click zones; slides in, no motion under prefers-reduced-motion. Fit-page zoom by default |
turnButtons?: TurnButtons | paged view's previous/next buttons: 'gutter' (default) in the empty space beside the page, never over it (smaller in a tight gutter, none below 32 px: swipes and tap zones remain), 'edge-hover' (at the page edges, shown on hover/focus, semi-transparent), 'toolbar' (only the toolbar's), 'none' |
turnZones? | paged view: a click or tap in the outer fifths turns pages (default true). Only a press and release without movement (< 4 px) and without a text selection: a drag that starts in a zone selects text |
wheelTurns? | paged view: the wheel turns pages past a page's edge (default false: the wheel only scrolls a zoomed page). Deliberate gestures only: deltas accumulate per gesture, trackpad inertia after a turn is ignored, sideways scrolls and an active selection never turn. Swipes are touch/pen only, never a mouse. PagedViewOptions |
pageHash? | #page=… deep links: any go-to-page input (12, iv, 3:12) is read on open and on hashchange; the hash follows the current page as chapter:page |
zoom?: ReaderZoom | a number, 'fit-width' (scroll default) or 'fit-page' (paged default) |
theme?: ReaderTheme | 'light', 'sepia', 'dark' |
direction? | 'ltr'/'rtl' (default from the first chapter's dir) |
metrics?, renderMath?, bodySize? | font metrics the layout used; LaTeX → safe HTML (KaTeX with trust: false) |
keepChapters?, countInBackground?, tocLevels? | memory (laid-out chapters kept, default 4), exact page counts in idle time (default true), TOC depth |
initial?: ReaderTarget | where to open (a saved ReaderLocation, a deep link) |
pageAccess? | ({ chapterId, page, chapter }) => boolean | string: true shows a page; anything else locks it (a placeholder, never painted), a string being the reason shown on it. Chapters get access ('open' | 'preview' | 'locked') and lockReason in the state. See Previews and locked chapters |
plugins[].wrapLayout? | (next: (doc) => DocumentLayout) => (doc) => DocumentLayout: wraps the chapter layout (as FolioPlugin.wrapLayout); localLayout applies the composed wrappers (first plugin outermost), handed over as ChapterLayoutContext.wrapLayout; a worker or server applies its own |
ensureFonts? | (families, chapter) => Promise<unknown>: loads the families of pages laid out elsewhere (windows, ChapterContent.layout) before they paint; pass readerFonts(...).ensure |
resolveMedia? | attrs → url (sync or async; e.g. signed URLs by mediaId); only safe URLs are used. Every picture goes through it: pages (DOM and canvas), thumbnails, picture bullets, the lightbox. null means "use the node's own src"; a throw or a rejection means it failed: nothing is requested (a stored /folio-media/<id> isn't a URL) and the picture shows "Couldn't load image" with its alt text and Retry. While a promise is pending the box shimmers (aria-busy). strings.mediaFailed / strings.retry translate it |
onLocationChange?, onPageView?, onChapterEnd?, onLinkClick? | events (ReaderLocation, ReaderPageView) |
label?, strings?: Partial<ReaderStrings>, gap? | accessible name, i18n, spacing |
protect?: boolean | ReaderProtectOptions | the restricted viewer: canvas pages without DOM text (accessibleText keeps the text layer), no selection, copy, context menu, drag or print (print relaxes it), covered while the tab is hidden (blurWhenHidden), after PrintScreen (printScreen) and optionally on focus loss (blurOnFocusLoss), singlePage, onPageSeen({ chapterId, page, at, visibleMs }), onBlocked (plus 'screenshot'). Read at creation. See Protected viewing. The same pieces for other views: protectGuard(root, options, pages) and protectElement from @nextgensoftwares/folio-reader/protect |
ReaderHandle
getState(): ReaderState (status, chapters: ReaderChapterInfo[], current: ReaderPageInfo, totalPages, exact, zoom, display, view, theme, numbering, interaction, direction, fullscreen, navigating: a goTo / goToInput is resolving; the page box is aria-busy with a spinner meanwhile) · subscribe(fn) · goTo(target: ReaderTarget) · goToInput(text) (a book page number lays out only the chapters up to it) · next() · prev() · nextChapter() · prevChapter() · setZoom · zoomBy · setDisplay · setView(ReaderView) · setTheme · setNumbering · setInteraction · setVariables · toggleFullscreen() · location() · selection(): ReaderRange | null · selectionText() · selectionRects(): DOMRect[] (client rects of the selected text, for a popover) · setDecorations(key, ReaderDecoration[]) · onDecorationClick(fn) · ensureChapter(i) · chapterIndex(id) · loadedChapters() · currentPage() (live, as location()) · renderPage(chapter, page, target) · repaint() · relayout(chapterId?) (lay one chapter, or every laid-out one, out again from its document, keeping the position: a lazy code grammar arrived) · refreshChapter(chapterId | chapterIds) (the server republished it: metadata from listChapters again, its layout and windows dropped, what is on screen fetched again at the same or nearest page, plugins' onChapterRefresh, e.g. highlights, reload it) · element() · variables() · plugins · options · destroy().
ReaderTarget: { chapterId, page?, offset?, point? }, { chapterId, blockId }, { global } (printed arabic number), { sequence } (0-based position in the book).
Sources
ReaderSource:listChapters(),loadChapter(id, signal?, onProgress?)→ChapterContent(doc,layout,blockIds);onProgress(fraction)(0–1, optional to call) shows as "Loading… 40%" on the chapter's placeholder pages (strings.loadingProgress,{percent}), then "Laying out…" (strings.layingOut);signalalso aborts when nothing shows the chapter any more (1.5 s later, so scrolling past doesn't restart it;ChapterLoader'scancelAfter). Going to a block or point in a chapter not loaded yet lands on its placeholder pages at once, then on the place.- A chapter that fails to load (or a windowed page whose
loadPagesfails) shows a state centred on its pages: an icon, "Couldn't load this chapter" (strings.failed; a page:strings.pageFailed), one line of reason and Retry (strings.retry), which loads it again in place (ChapterLoader.retry(ci),PageWindows.retry). The state is announced (role="alert", once per chapter) and Retry takes keyboard focus on the page being read, never from a field being typed in or from outside the reader. What the source rejects with says why (ChapterLoadError, anyErrorworks):status401 / 403,locked: trueorcode'forbidden'/'locked'/'unauthorized'/'denied'show "You don't have access to this chapter" (strings.denied) with itsmessageand no Retry (unlessretryable: true);status408 / 504,code'ETIMEDOUT'/'timeout'or aTimeoutErrorsay it took too long (strings.failedTimeout); offline (strings.failedOffline) and a fetchTypeError("couldn't reach the server",strings.failedNetwork); otherwise itsmessageis the reason (plain text, one line, cut at 160 characters).retryable: falsehides Retry.classifyLoadError(error, isOnline?)→LoadFailure(kind,reason,retryable) is the same rule.READER_STRINGS_ARhas the reader's strings in Arabic (strings: READER_STRINGS_AR). Optionalsearch(query)→ReaderSearchHit[], optionalloadPages(id, from, to)→ChapterWindow(windowed chapters: only pages near the viewport are ever fetched). ReaderChapterMeta:id,title,kind?: ChapterKind(chapter,front-matter,inserted),pageCount?,estimatedPages?,pageSize?,headings?: ReaderHeading[],dir?,lang?,families?(font families its pages use;chapterMetafills it).memorySource(chapters: MemoryChapter[], MemorySourceOptions),splitIntoChapters(doc, SplitOptions).insertedPart(id, title, InsertedPage[], size): unnumbered cover/image/title/blank pages;insertedTextPainter,INSERTED_TEXT.toPlainLayout(layout)(serialize a layout: lazy fragments materialized),readLayout(json)(validate an untrusted one).localLayout(options: ChapterLayoutOptions, hooks?: LocalLayoutHooks): main-threadChapterLayoutFn;ChapterLayoutContext.
Numbering, text and anchors (DOM-free)
PageNumbering(NumberingChapter,PagePosition,PageRef):label,position,sequence,at,globalArabic,globalRoman.resolvePageInput(text, numbering, mode, chapter)(12,iv,3:12, Arabic-Indic digits),parseRoman.docTextRuns,layoutTextRuns,docHeadings,blockIdOf,isTextblock,inlineText,nodeText,ATOM,TextRun.TextAnchor(positions +quote/prefix/suffix),anchorFromRange(ct, range, context?, blockId?)(with a block index → id lookup the points carry block ids, soreanchorfinds the anchor's own paragraph),reanchor→Reanchored | null,chapterText(ChapterText),offsetOf,pointAt,withBlockId(point, blockId),comparePoints.ReaderPoint,ReaderRange.normalizeSearchText,searchRuns(SearchOptions,TextMatch),snippet.
Server endpoints (DOM-free)
Also in @nextgensoftwares/folio-reader/anchors. See Server endpoints.
| API | What |
|---|---|
publishChapter(doc, layout | { layoutDocument, options }, PublishOptions) → ChapterBundle | one call at publish time: { v: 1, meta, layout, pageIndex, text? }, plain JSON to store; PublishOptions = ChapterInfo + text? (default true); PublishLayout<O> |
chapterMeta(doc, layout, ChapterInfo) → ReaderChapterMeta | pageCount, pageSize, headings with block ids, dir (given, the document's, or its lines'); ChapterInfo = { id, title, kind?, dir?, lang? } |
chapterWindow(bundle | layout, from, to, ChapterWindowOptions?) → ChapterWindow | loadPages: plain pages [from, to), clamped to the chapter and maxPages (16), blockIds of exactly those pages' blocks (from the bundle, doc or blockIds: BlockIdList); windowBounds(pageCount, from, to, maxPages?) |
searchChapter(chapterId, ChapterTextSource, query, ChapterSearchOptions?) → ReaderSearchHit[] | the reader's matching (Arabic folding), block ids on the points, snippet, page from the page index; maxQuery (256), limit (500) |
searchBook(BookSearchChapter[], query, options?) → ReaderSearchHit[] | every chapter in the order given, one limit for the book |
locateInChapter(ReaderLocateQuery, bundle | LocateChapter) → ReaderLocateResult | null | a point, block id or quote (+ context, page hint), points with block ids; capped like TEXT_LINK_LIMITS |
layoutChapterUntil(doc, { layoutDocument, options }, LayoutUntilOptions?) → LayoutChunk | incremental layout: { untilPage?, untilBlock?, resume?, fingerprint?, kitKey? }; returns the new final pages [from, …) with their page index, complete, resume: LayoutResume | null (plain JSON, versioned, tied to the document and kit), estimatedPages, and on completion revised pages and warnings |
appendChunk(bundle | null, LayoutChunk, doc, PublishOptions) → GrowingBundle | adds a chunk to a bundle: a PartialChapterBundle (partial: { estimatedPages, resume }, meta.estimatedPages) until complete, then the same bundle publishChapter gives; isPartial, bundlePages (exact or estimated count) |
headingPages(bundle) → (number | null)[] | each meta.headings entry's page, null past a partial bundle's pages |
NeedsLayout | { needsLayout: { untilPage } | { untilBlock } }: what chapterWindow and locateInChapter answer on a partial bundle past its pages; searchChapter hits there have no page |
docFingerprint(doc) | the document's content hash (16 hex chars) a LayoutResume is tied to |
SERVER_LIMITS | { pages: 16, query: 256, hits: 500 } |
ChapterTextSource | a document, its TextRun[], or a ChapterBundle |
Painting
READER_CSS, injectReaderStyles (constructed stylesheets: strict-CSP safe) · THEME_ADAPTERS, PAGE_BACKGROUND, ReaderTheme, ReaderColorAdapter · paintPageContent(PagePaintInput) · safeSrc, isFollowableHref, browserMetrics · DomPainter, DomPaintContext, ReaderPaintEnv, ReaderColor, CanvasPaintOptions.
Plugins
ReaderPlugin is FolioPlugin's reader subset: pageLayers, painters (DOM painters), renderers (handed to layout as ChapterLayoutContext.renderers; localLayout merges them under its own, a serveLayout setup must build its own), exporters.canvas / exporters.pdf, colors, ui.items (ReaderUIItem; shown only with reader: true or a predicate, like a read-only FolioView), css, attach(reader), onChapterRefresh(chapterId) (after refreshChapter; highlights asks its store again). composeReaderPlugins → ComposedReaderPlugins; isReaderItem(item, ctx: ReaderUIContext).
watermarkPlugin(ReaderWatermarkOptions): tiled text (NID:{{nid}}\n{{email}}, opacity 0.07, −40°), DOM / canvas / PDF; a guard repaints a removed watermark and reports it.density(sparsedefault,normal,dense;WATERMARK_DENSITY) orgapX/gapYset the spacing.fillTemplate,watermarkTiles,WATERMARK_TYPE.protectPlugin(ProtectOptions): copyallow/block/{ maxChars }(withinteraction: 'select', text stays selectable for highlights whileblockstops Ctrl/Cmd+C/X, Ctrl+Insert, Shift+Delete, the context menu, dragging the text out and everycopy/cutof a reader selection; the clipboard getscopyNoticeor nothing),print: PrintPolicy(allow,current-page: only the page on screen, watermarked,block), context menu, drag, Ctrl+S.printCurrentPage(reader, open). Deterrents only. The same on any element:protectElement(root, options, printCurrent(open))(returns the detach),printElement(el, width, height, open)prints one element alone (PRINT_CSSin the document); the slides student viewer uses them.highlights(HighlightsOptions)→HighlightsController(plugin,selectionAnchor,add,remove,update,list,setVisibleLayers,setVisible(on)/visible()to hide and show them all,flash,reload(chapterId?)to ask the store again and repaint (after the server re-anchored them on publish),subscribe(fn)for the placed list);ReaderHighlight,HighlightStore.FolioReaderShell highlights={controller}adds a Show / Hide highlights toggle to the toolbar; its find bar goes to the next match with Enter and the previous with Shift+Enter; fullscreen is on the toolbar (hide: ['fullscreen']removes it).focus/onFocusChange(or Ctrl/⌘+Shift+F, or its button) give focus mode: the chrome hidden, one page per row in a centred column (one page per screen in the paged view: focus keeps the reading view, and the display and view come back exactly on exit), a progress line, and a fading bar with text size, page colour, page n of N and exit (Escape leaves). See Focus mode.createFind(reader)→FindController(search,next,prev,go,clear,state(): FindState,subscribe);FindResult.
Bundle size
Measured by pnpm --filter @nextgensoftwares/folio-reader size (esbuild, minified, every dependency inlined but React); budgets enforced by src/__tests__/deps.test.ts:
| Entry | min | gzip |
|---|---|---|
| core (createReader + plugins; precomputed layouts) | 75 KB | 27 KB |
core + localLayout (layout engine, bidi, line breaking) | 192 KB | 74 KB |
| react shell | 82 KB | 28 KB |
| worker client | 1 KB | 0.5 KB |
Added in 0.13
| API | What |
|---|---|
ReaderSource.locate?(query) | optional server hook: ReaderLocateQuery (chapterId, point?, blockId?, quote?, quoteEnd?, prefix?, suffix?, page?) → ReaderLocateResult (page, start?, end?) or null |
ReaderSearchHit.page? | 0-based chapter page of a hit: the reader fetches that window directly |
reanchor(anchor, ct, blockIndex?, blockId?, options?) | { range, how: 'exact' | 'moved' | 'fuzzy', confidence } or null; ReanchorOptions = FuzzyOptions + fuzzy? |
chapterPageIndex(layout, blockIds?), pagesForAnchor(index, anchor) | a compact JSON page index (ChapterPageIndex) stored on publish; AnchorPages { page, endPage } without loading the chapter |
MAX_CONTEXT, resolvePoint(point, blockIndex?) | context chars a side used when re-anchoring (64); a point with its block index taken from its block id |
highlights({ fuzzy }), ReaderHighlight.reanchored | approximate re-anchoring on the client (lazy chunk); { how, confidence } on placed highlights |
selectionLink(reader, options?), seekText(reader, target, options?), seekTextLink(reader, url?, options?), textLinkPlugin(options?) | copy a link to the selection (or to options.range / options.anchor: SelectionLinkOptions, for a popover action after the selection cleared); open ?text= links (windowed chapters included). TextLinkOptions (buildUrl, keys, maxQuote, context), SeekOptions (flash, color) |
TextLinkTarget, TextLinkKeys, textLinkTarget(anchor, options?), textLinkWithinLimits(target) | a link's target (chapter, quote, quoteEnd, context, page hint), its query parameter names, a target from an anchor, the input caps check |
HighlightsController.reload(chapterId?): Promise<void>, .subscribe(fn: (list) => void): () => void | ask the store again and repaint (e.g. after the server re-anchored on publish); follow the placed list (a host rail) |
anchorFromRange(ct, range, context?, blockId?), withBlockId(point, blockId?) | anchors whose points carry block ids (windowed chapters' too) |
FolioReaderShell header, panel, selectionActions, brand, title, contents, contentsLabel, hide | host slots: see the shell's host slots. ReaderShellHide, ReaderShellContents, ReaderContentsContext; groupResults, snippetParts, FindGroup, FIND_CSS for a host's own find list |
Windowed chapters (loadPages) now support find, highlights, selection anchors, passage links, watermark and protection, and never fetch more than 8 pages past the current one: see Windowed (server) chapters.