Book mode
@nextgensoftwares/folio-book shows a work stored as many documents (chapters, sections, units) as one book, inside FolioApp's chrome: the same app bar, panels, status bar, tokens, theme toggle, zoom and page look. Each chapter stays its own document: it is laid out alone, starts on a new page and keeps its own header and footer. Nothing is merged.
Setup
import { createBookLayout, FolioBookApp } from '@nextgensoftwares/folio-book';
import { tocPlugin } from '@nextgensoftwares/folio-plugin-toc';
// Create these once (a new source or layout opens a new book).
const layout = createBookLayout({
measurer: fontEngine, // the same FontEngine the editor measures with
plugins: [tocPlugin()], // block renderers, painters, live contents page numbers
layout: { theme, headerFooter: {} }, // the editor's layout options
fonts: { loader }, // the host's LoadFamily, as in the editor and reader
});
<FolioBookApp source={source} layout={layout} title="Field guide" numbering="global" />FolioBookApp takes every FolioApp prop (title, people, actions, theme, locale, messages, credit…), except the editor's own. The toolbar is hidden: the book is read-only. Your plugins' slot items (appOptions.plugins) that declare reader: true, such as your own sidebar tab or status-bar cells, show in a read-only book too (and in an editable one before a chapter goes live), drawn with editor: null and your slotProps: a sidebar tab brings the right panel and its toggle, also in the narrow drawer. Items that need an editor (Suggestions, Format shape, comment threads: no reader, or a reader predicate) wait for a live chapter, and when(null) still hides an item.
Like FolioApp, it needs Folio's styles on the page: render <FolioStyles /> (from @nextgensoftwares/folio-react) once, or import @nextgensoftwares/folio-react/styles.css.
The source
Any ReaderSource (the reader's), for example memorySource(splitIntoChapters(doc)) in a demo, or your API:
listChapters()returns cheap metadata. SendpageCountwhen your server knows it (from a stored layout report): the scrollbar and the page scrubber (the reader's: drag the handle beside the scrollbar through the whole book; pages paint when it rests) are right before anything loads, and book-wide page numbers are final from the start. Without it, counts are learned front to back in the background.loadChapter(id)must return the latest saved version of a chapter (no stale CDN cache): the book shows what it gets.loadChapter(id, signal, onProgress): callonProgress(fraction)(0–1) while a big chapter downloads (you know the chunk count from a manifest, or the response's length) and the book says "Loading chapter… 40%" over the chapter's first skeleton page, then "Laying out chapter…". Without it, it says "Loading chapter…".signalaborts when nothing shows the chapter any more (the reader went elsewhere for a moment and a half): stop the download there.- When
loadChapter(orloadPages) rejects, the chapter's pages show a state centred on them: an icon, "Couldn't load this chapter", one line of reason and Retry, which loads it again in place (no reload). Reject with what happened and the book says it:{ status: 403 }(or 401,locked: true,code: 'forbidden') shows "You don't have access to this chapter" with yourmessageand no Retry (retryable: truekeeps it);{ status: 504 },code: 'ETIMEDOUT'or aTimeoutErrorsay it took too long; offline and unreachable servers say so; anything else shows itsmessage(one line). The page being read announces it (role="alert") and its Retry takes keyboard focus, never from a field being typed in. The words are in the Arabic catalog (locale: 'ar'). The shape isChapterLoadError(@nextgensoftwares/folio-reader).
Going to a place in a chapter that isn't loaded yet (contents, goTo, find, a heading) lands on the chapter at once, on its skeleton pages and that status, and on the exact place when it arrives, unless the reader scrolled meanwhile. A newer goTo replaces one still waiting.
search(query)(optional) answers find across the whole book from the server. Without it, find fetches chapter text two at a time (no layout) and searches it locally.loadPages(windowed chapters) works as in the reader; find in those chapters needssearch.
After you rename, reorder, add or remove chapters, update the source and call bookRef.current.refresh(). Pass the ids of chapters whose content changed to reload them. A reloaded chapter keeps the objects of its leading and trailing blocks that didn't change, so its layout re-measures and re-paginates only from the first changed page.
Following other people's edits
A chapter being edited follows the server through its SyncClient. A chapter the book only shows can follow it too, by steps instead of reloads:
const follower = bookRef.current!.follow('ch-4', { api, version }); // api: folio-sync's DocumentApi (only `pull` is used)
socket.on('book-changed', (e) => e.chapterId === 'ch-4' && follower?.pull(e.version));
follower?.stop();- Who pulls: the host calls
pull(version?)when it hears the chapter changed, e.g. its own change event. Pulls run one at a time, and a pull asked for while one runs runs once more after it. A version the book already shows is skipped. There's no polling. - What a pull does: it fetches
api.pull(docId, shownVersion)and applies the steps to the shown document. Unchanged blocks keep their objects, so the layout re-measures only the changed blocks and re-paginates from the first changed page; earlier pages stay the same objects. The reading place stays where it is when pages above it change. - Versions: the version comes from
ChapterContent.version, when the source'sloadChaptersends it. Otherwise it comes fromfollow'sversion(first pull only). Send it from the source so the follower can carry on after a reload. - Falling back: a lost history (
HistoryGoneError, HTTP 410), a version gap, steps that don't apply, a windowed chapter (the book holds only some pages), or a chapter whose version isn't known all load the chapter again instead. Unchanged blocks are still reused. Other errors go toonError, and the nextpulltries again. - Chapters not loaded: a chapter that isn't laid out (scrolled away) is left alone; it loads the latest when it's shown.
- Live chapters: a chapter being edited belongs to its editor, and pulls do nothing.
snapshot()gives the shown document and its version, which anopenChaptercan start its editor and sync from without fetching the chapter again. - Schema:
docIddefaults to the chapter id.schemadefaults tocreateBookLayout's composed schema, which is what the steps are made in.
Page numbers
numbering="local" (default) numbers each chapter from 1. numbering="global" prints book-wide numbers inside the pages too: header/footer page fields and in-document page numbers (contents blocks, page references). Front matter keeps its roman count. A chapter's numbers change at most once, when the page counts before it become exact. With exact pageCounts they never change. The scroll position stays where it is meanwhile. NUMPAGES fields keep counting the chapter's own pages.
The status bar's "Page X of Y" shows Y only when the counts it adds up are known (the chapter's own in local mode, every chapter's in global mode). While a chapter's count is still being learned it reads "Page X", or "Page X of about Y" when the source sent estimatedPages for it. Send pageCount to have the total from the start.
Global numbering needs a layout function that honours ctx.pageNumbers: createBookLayout and the reader's localLayout do; workerLayout doesn't yet.
Dividers, contents and chapter actions
A divider (── Chapter 3 · Title ──, in the chapter's direction) sits above each chapter's first page. It is screen chrome outside the page, so print, PDF and Word export never see it. chapterDivider={false} hides it; a function renders your own.
The left panel lists chapters with their headings, marks the heading being read (the last one starting above a reading line a quarter down the view, so a page holding two headings marks the right one; above a chapter's first heading the chapter itself; its chapter keeps a lighter mark), keeps it in view (opening a chapter closed by hand) and links to any heading. While a chapter is edited the caret leads only when it is on screen or was just moved; scrolling elsewhere, the panel follows the view. A heading that only repeats its chapter's title isn't listed again; the chapter being read is open, and any chapter's chevron opens or closes its headings (what you open or close is kept for the book while the page is open). Chapter rows and headings read differently: a chapter row has its kind's icon (a document, a deck of slides, an inserted part) and a heavier title, the chapter being read is filled with a tint of the accent and the one being edited carries a dot ("Editing", through the strings); headings sit under their chapter on a guide line, smaller and muted, indented by level (H2 8px, H3 16px, deeper 24px; mirrored in right-to-left chapters). numberChapters puts "1.", "2.", "3." before the chapters' titles (front matter and inserted parts are not counted). chapterActions={(meta) => [{ id: 'rename', label: 'Rename', run }]} adds a menu per chapter: its ⋯ button, a right-click on the chapter in the panel, or a right-click on one of its pages (where Edit chapter puts the caret at the clicked point). With text selected, that menu starts with Copy. A chapter with no actions and no Edit chapter keeps the browser's own menu. The chapter being edited gets the editor's own context menu, with its plugins' items.
contentsActions puts small icon buttons in the contents panel's header, beside Contents (the book's own actions, e.g. New chapter, Import document). Each has a label (its tooltip and accessible name), an icon (a Folio icon name or your own element) and either onSelect or items (a menu: Enter, Space or ↓ opens it, arrows move, Escape closes it and returns focus). The host decides when to show them: pass [] (or nothing) when the book isn't editable. In right-to-left pages the header mirrors.
<FolioBookApp
contentsActions={canEdit ? [
{ id: 'add', label: 'Add', icon: 'plus', items: [
{ id: 'chapter', label: 'New chapter', onSelect: newChapter },
{ id: 'import', label: 'Import document', icon: 'upload', onSelect: importDoc },
] },
] : []}
/>Any side panel tab can do the same: a slot item's headerActions component is drawn in the panel's header while its tab shows.
One chapter at a time
chapterView="chapter" shows only the chapter being read: its divider, banners and pages, with the scroll range ending at its first and last page (the default, 'book', is every chapter in one scroll). Previous chapter and Next chapter buttons (with the target's title, in the chapter's direction) sit above and below it. Page numbers, headers, footers and watermarks stay the book's, so page 214 is still 214. The contents panel lists every chapter as before; choosing another chapter or heading, goTo, find and locate switch the chapter shown. The prop is controlled: switching it keeps the reading place (chapter, page and the fraction above the reading line) and the live editors, and doesn't remount the book. Translate the new labels (Previous chapter, Next chapter, Chapters) like the book's other strings.
protect (view access) blocks selection, copying (the chapter menu's Copy too), the context menu, dragging and printing on the book's pages, covers them while the tab is hidden or after PrintScreen, and reports the pages read through onPageSeen({ chapterId, page, at, visibleMs }). The pages stay DOM text: someone with view access has the chapters' documents. For readers who must only get page windows, use the reader's protect (canvas pages). See Protected viewing.
Reordering chapters
onMoveChapter={(chapterId, toIndex) => save(...)} lets readers of an editable book reorder chapters in the panel:
- Pointer: drag a chapter row; a line shows where it will drop, and the panel scrolls near its edges. On touch, drag from the grip, so the list still scrolls. A click that doesn't move still opens the chapter.
- Keyboard: focus the grip, press Space or Enter to pick the chapter up, move it with the arrow keys, then press Space or Enter to drop it or Escape to cancel. Each step is announced.
toIndex is the chapter's index among the book's chapters once moved. Front matter and inserted parts don't count and never move. Save the order, then call bookRef.refresh(). The new order shows at once. If the promise rejects, the old order comes back.
Which chapters can move:
- By default: the grips appear when some chapter is
editable(or ineditableChapters). Chapters that are editable can move, and so can drawn ones (decks, edited elsewhere). - Your own rule:
canMoveChapter={(meta) => …}decides instead, for example to keep a locked chapter in place.
<FolioBookApp source={source} layout={layout} editable={(id) => canEdit(id)}
onMoveChapter={async (id, to) => { await api.moveChapter(bookId, id, to); await bookRef.current?.refresh(); }}
bookRef={bookRef} />Find
Ctrl/⌘+F opens the editor's find bar over the book. Results are grouped by chapter with counts; Enter, F3 and the arrows go from chapter to chapter, loading them. Replace works in the active (editing) chapter only, through its editor (one undo step); other chapters' matches stay read-only, and with no editable active chapter the replace row is hidden.
Editing a chapter
Without openChapter the book is read-only: editable={(id) => canEdit(id)} adds Edit chapter to the chapter's menu and divider, which calls onEditChapter({ chapterId, page, offset }) (offset: the fraction of that page above the click or the viewport's top edge, null when the chapter is off screen). A click on a page only reads unless you pass editOnClick; a drag, a text selection or a link click never counts. A click beside a page (the gap between pages, either side of the column, a chapter divider's empty part) counts as one at the nearest point of the nearest page of that chapter.
Pass openChapter and the book edits one chapter at a time inside the same chrome. Each chapter keeps its own editor, undo, sync and save status; nothing ever moves between chapters.
import { FolioBookApp, createBookLayout } from '@nextgensoftwares/folio-book';
import { SyncClient, chapterSync } from '@nextgensoftwares/folio-sync';
<FolioBookApp
source={source}
layout={layout}
appOptions={{ measurer: fonts, plugins, layout: { theme }, fonts: { loader } }}
editable={(id) => canEdit(id)}
beforeActivate={(id, signal) => locks.take(id, signal)} // true, false or { ok: false, reason }
openChapter={async (id, signal) => {
const { doc, manifest } = await api.open(id, signal);
return { doc, plugins: [versioned(manifest)], createSync: (editor) => chapterSync(new SyncClient(editor, api, id, clientID, { manifest })) };
}}
onChapterBlur={(id) => locks.markIdle(id)} // keep the lock: edits may still be saving
onChapterReleased={(id) => locks.release(id)} // the only place to give the lock back
/>To save over a realtime socket instead, return collabChapterSync(new CollabClient(editor, transport, opts)) from @nextgensoftwares/folio-plugin-collab (see the collaboration plugin): the same statuses, terminal states and flush.
A live chapter always lays out print pages, whatever appOptions.reflow says: the book draws every chapter as pages fitted by one zoom, so on a phone the chapter being edited stays the same width as the chapters around it.
Ctrl/⌘+wheel, trackpad and touch pinch and Ctrl/⌘ +/−/0 zoom the book's pages, as in a single document (the reading place stays on screen); the zoom goes through zoom / onZoomChange.
Editing without a click
autoEdit makes an edit mode feel like one: the editable chapter in view goes live on its own, on load and then whichever chapter the reader scrolls to (once the view rests). Its caret waits at the top of what's on screen and it takes no focus (host fields keep it), so a click places the caret and types at once. beforeActivate still decides: a refused chapter stays read-only with your reason and isn't asked again until another chapter was in view or it became editable again (the host switching to edit mode). A chapter the user picked by hand is left alone.
bookRef.current.edit(chapterId) and editAt(target) do the same on demand, with focus: edit puts the caret at the top of the chapter's page on screen (its start when it is off screen), editAt scrolls to a goTo target and puts the caret there (a point, or a block's start). Both resolve false when the chapter isn't editable, beforeActivate refused or opening failed.
<FolioBookApp autoEdit={mode === 'edit'} editable={() => mode === 'edit'} … />
await book.current.editAt({ chapterId: 'ch-4', point: { block: 3, offset: 0 } });Spelling
The chapter being edited is checked as you type, as in FolioApp: red squiggles under misspelled words, and right-clicking one offers its suggestions, Ignore, Ignore All and (with a host dictionary) Add to Dictionary. The settings are FolioApp's view ones: spellcheck (absent: the built-in English checker, false: none), spellCache and spellDictionary. A huge chapter is checked in short slices, the pages on screen first, so it never holds the page; the Spelling tab fills in as it goes and shares the same check.
A book's own word list (every author of the book shares it) is a controlled spellDictionary: keep the words on your server and pass them back.
const [words, setWords] = useState<string[]>(book.words);
<FolioBookApp view={{ spellDictionary: {
words,
onAdd: (w) => { setWords((l) => [...l, w]); void api.addWord(bookId, w); },
onRemove: (w) => { setWords((l) => l.filter((x) => x !== w)); void api.removeWord(bookId, w); },
} }} … />Comment-only chapters (reviewers)
A reviewer comments on chapters without editing them. commentOnly (true, or a predicate on the chapter id) opens chapters that aren't editable live but read-only, so their plugins (comments) work: a click on a page, autoEdit or edit() opens one through openChapter, without beforeActivate (no lock to take) and without calling createSync. Selection, the menu (Copy, Comment) and plugin shortcuts work (Ctrl+Alt+M); typing, paste, cut, drop and undo never change the chapter. A reviewer gets no "Edit chapter" button.
openChapter can also return readOnly: true for a chapter it decides to show read-only (say, a draft the user may only comment on): the same, whatever editable says.
<FolioBookApp commentOnly autoEdit appOptions={…}
openChapter={async (id) => ({ doc: await loadDoc(id), plugins: [commentsPlugin({ anchors: 'detached', user: { id, name, role: 'commenter' }, store })] })} />Comments on a read-only chapter float on their quote (they never write marks into its document), with anchors: 'marks' too.
The chrome follows the editor's read-only state: plugin settings sections (header & footer, code blocks, the document's colours…) and plugin toolbar items change the document, so a reviewer doesn't get them; the Settings tab goes when none is left. A plugin's section or toolbar item about the view sets reader: true (or a predicate on the context) to stay, like a menu item's reader.
Readers see the selection but no caret; Comment shows in the selection bubble only; going to a comment from the Comments tab selects its text; the Comments tab offers a general comment on the chapter (documentComments on the comments plugin); side-panel tabs that edit (Format shape, Selection, Table) don't show, and the context bar's table and picture tools don't either.
Access levels
access sets what the user may do with the whole book, chapterAccess(id) a chapter's own level over it (undefined: the book's):
| Level | |
|---|---|
'edit' | the chapter edits (still only where editable / editableChapters allow, when given; others fall back to commentOnly) |
'comment' | it opens read-only for comments, as commentOnly above: select and Comment, reply and resolve as the comments plugin's policy allows; no typing, paste, drop, formatting or undo. The toolbar keeps no formatting, only items marked reader and the selection bubble's (Comment) |
'suggest' | it opens as for 'edit' (beforeActivate, sync) in suggest mode: typing and deleting become suggestions an editor accepts or rejects (Suggest mode; needs @nextgensoftwares/folio-plugin-suggest in the chapter's plugins). 'edit' users see them with Accept / Reject, 'comment' users read-only |
'view' | read only: nothing opens |
Without access or chapterAccess, editable and commentOnly decide as before. Changing either while the book is open applies to the live chapters in place, without remounting the book or moving the page:
- edit ↔ suggest: the live chapter switches suggest mode in place.
- edit → comment: the live chapter turns read-only (its sync keeps running, so others' edits still arrive); comments keep working.
- comment → edit:
beforeActivateis asked again; a chapter opened for comments (opened withoutcreateSync) is reopened throughopenChapter, with the caret where it was. - → view: the live chapter is released (after its unsaved edits are saved) and shows as read-only pages.
Keep chapterAccess stable (useCallback): a new function re-applies the levels. The server must enforce the same rules; these only shape the UI.
<FolioBookApp access={grant.level} chapterAccess={(id) => grant.chapters[id]} canExport={(f) => grant.download} … />canExport(format) (from FolioApp) decides which Export entries show ('pdf', 'docx'…) and, for 'print', whether Ctrl/⌘+P and printing the app work.
Locks
- Take the lock in
beforeActivate. It runs on every activation, also when returning to a chapter whose editor is still alive (the lock may have expired meanwhile), so make it cheap when you still hold it. A refusal keeps the chapter read-only and shows yourreason. - Keep it through blur. A blurred editor is alive and may still be saving; releasing on blur would let someone else take the chapter and get the pending saves rejected.
onChapterBlurmay mark the lock idle. - Release it in
onChapterReleased, which runs only after the editor's steps were flushed and the editor disposed. It never runs while the chapter is saving, unsaved, in error, offline, or held by sync (diverged,needs-confirmation,forbidden,gone): those stay live and read-only with a banner until you resolve them (reopen,confirmPending,discardPending). Once the status recovers, the chapter is editable again and the banner goes (a chapter that stopped being editable meanwhile stays read-only). - If an activation is abandoned after
beforeActivatesaid yes (a newer click, oropenChapterfailed),onChapterReleasedhands that lock back too. - A push refused as
forbidden(the server says the lock is gone) turns the chapter read-only; its edits stay in the outbox.
Freshness
After a release the book shows the editor's last pages, then re-fetches the chapter (loadChapter/loadPages, bypassing its cache) and swaps it in. source must return the latest saved version (no stale CDN cache) or readers see the pre-edit text.
openChapter's plugins are that chapter's own (here, tied to the version just loaded), added after appOptions.plugins; they go with its editor when it is released, and the next open asks again.
Live editors
The chapter being edited behaves like FolioApp's editor: a press keeps the keyboard there, the toolbar and menus hand focus back, the view follows the caret (to pages not on screen too), Shift+click extends, and the contents panel marks the heading at the caret.
keepEditors (default 3) live editors are kept; past that the least recently used clean one is released. Keys typed while a chapter opens are held (up to 200) and typed into it as one undo step; if it is refused the banner says how many were not applied. Arrow keys, PageDown/PageUp at a chapter's edge move to the next or previous editable chapter. editable/editableChapters can change at runtime: a chapter turning non-editable goes read-only and keeps syncing.
Watermarks and page layers
Plugins' page layers (a watermark from @nextgensoftwares/folio-plugin-watermark, stamps) draw on every page of the book, read-only and live chapters alike, as in FolioApp: pass the plugin to createBookLayout({ plugins }) and the viewer's values as layerVariables ({{name}}, {{nid}}, {{email}}…):
const layout = createBookLayout({ measurer, plugins: [watermarkPlugin({ text: { content: '{{name}} · {{nid}}' }, tile: true })] });
<FolioBookApp source={source} layout={layout} layerVariables={{ name, nid, email }} />A chapter's PDF gets the same layers (target 'pdf') from the layout: exportPdf(book.layoutOf(ci)!, { ...opts, pageLayers: layout.composed.pageLayers, painters: layout.exporters.pdf, variables }).
Collaborators
Several people can edit one chapter (each through its own SyncClient). To show their carets and selections on the live chapter, pass presence: { remotes(chapterId), subscribe(fn) }, the people in that chapter as { name, color, anchor, head } in the chapter's positions now, and a way to say they moved (book mode then redraws their carets and highlights).
Positions travel with a version. Send yours from the chapter's editor with watchSelection(editor, send) (@nextgensoftwares/folio-sync, in openChapter's createSync): it reports { anchor, head, version } once the selection settles, your unsaved steps already taken out. Place a received one with sync.remoteAt({ ...sent, clientID }): it maps the positions from the version they were sent at through the steps saved since and through your own unsaved ones; null means this editor hasn't reached that version yet (keep it and try after the next sync).
createSync: (editor) => {
const sync = new SyncClient(editor, api, id, me, { manifest });
const off = watchSelection(editor, (sel) => socket.emit('presence', { chapterId: id, ...sel, clientID: me, name, color }));
socket.on('presence', (p) => p.chapterId === id && people.set(p.clientID, p));
presence.remotes = (chapter) => [...people.values()].flatMap((p) => { const at = sync.remoteAt(p); return at ? [{ name: p.name, color: p.color, ...at }] : []; });
// …call presence's subscribers on every 'presence' message and after each sync.
const handle = chapterSync(sync);
return { ...handle, stop: () => (off(), handle.stop()) };
}Who is where, and following them
presence.people() adds everyone else in the book, readers too: an avatar on their chapter's contents row and on its divider (three, then "+2" naming the rest). Each person is { id, name, color, avatarUrl?, at }, where at is where they are: send each reader's own place from onLocationChange (or BookHandle.location()), or a block ({ chapterId, blockId }) for someone typing. Leave yourself out, and merge one person's tabs into one entry.
A click on an avatar follows that person: the book glides to at (goTo(…, { behavior: 'smooth' })) and again whenever it changes, until the reader scrolls, taps or presses a key, or clicks the avatar again; someone who leaves ends it too. Only the avatars re-render when people() changes, and nothing does when what it returns is the same (a caret moving inside the same place), so calling subscribe's functions on every presence message is fine. Both methods are optional: carets only (remotes), avatars only (people), or both.
const presence: BookPresence = {
remotes: (chapterId) => carets.get(chapterId) ?? [],
people: () => [...room.values()].filter((p) => p.id !== me),
subscribe: (fn) => room.on('change', fn),
};
// Each client reports its place: <FolioBookApp onLocationChange={(at) => socket.emit('here', { id: me, name, color, at })} … />Two people typing in the same chapter need no lock: the authority takes steps based on its latest version only, and a client whose steps were refused rebases them over the others' and sends again (prosemirror-collab, through SyncClient). A test plays seeded random sessions of two editors (typing, bold and italic, splitting and joining paragraphs, deletes across blocks, table rows and columns added and removed) over a slow network and checks both end in the same, valid document.
Slide deck chapters
A deck can sit between the book's chapters as it does in the reader: the source lists it with deckChapter(pres, { measurer })'s meta (its paint: 'drawings', exact pageCount, pageSize, headings) and returns its content (a layout, no document) from loadChapter. Give the book the reader plugin that draws slides:
import { deckChapter, slidesReaderPlugin } from '@nextgensoftwares/folio-plugin-slides/viewer';
<FolioBookApp source={source} layout={layout} readerPlugins={[slidesReaderPlugin()]} />- Each slide is drawn on a canvas under its text, which stays as an invisible layer: selection, copy and find reach it.
- In the contents panel a deck lists its slides as numbered thumbnails instead of headings ("Slide 3: Results", the slide's title when it has one): drawn small by the same
readerPluginsas they scroll into view, loaded when the deck is opened, a click goes to the slide, and the slide being read is marked.contentsThumbnailschanges which chapters do:falsefor none, or(meta) => boolean(a plain chapter then lists its pages, "Page N"). readerPluginsdraw on drawn (deck) pages and on zoomed images only. Document pages are the editor's pages: their watermark comes from the editor's plugins (appOptions.plugins, e.g. folio-plugin-watermark).- Pictures whose stored src needs a signed URL: pass
slidesReaderPlugin({ resolveSrc })(see the reader guide's deck section); it's asked on every paint, so expiring URLs are minted again. - Keep
deckChapter'spageCount: the book has no page windows (noloadPages), so the whole deck's layout loads withloadChapter, and the exact count sizes the column before it does. - A drawn chapter is never opened in place (no "Edit chapter", no click to edit,
edit()resolves false), whatevereditable,commentOnlyorautoEditsay: decks are edited inSlidesApp(see Collaborating on decks), then published back as adeckChapter. - To edit a deck from the book, pass
onEditDrawnChapter. A plain click on one of its pages, or the Edit slides button over the page's top corner, callsonEditDrawnChapter({ chapterId, page })for the deckseditable(oreditableChapters) allows. A drag, a text selection, a link or a zoomed image doesn't count. The button shows on hover and focus (Tab reaches it, Enter or Space runs it) and always on touch screens. It's chrome, so it never reaches the canvas, print or exports. Open yourSlidesAppwithinitialSlide={page}. It's kept apart fromonEditChapter, which asks to edit a chapter in place at a text offset; giving the prop is the opt-in, soeditOnClickisn't needed. Translate the newBOOK_STRINGS.editSlides('Edit slides'). editDrawnOnpicks what else on a deck's page hands it over:'click'(the default, as above),'dblclick'(a double-click), or'chip'(only the Edit slides button). With'dblclick'or'chip', a plain click stays a click, so readers can select, comment on or suggest in a deck in the book.- A deck's text can be selected in the book (copy, the browser's find). Selection is the browser's own (double click a word, triple click a paragraph, Shift+click, Shift+arrows), in reading order across boxes; a drag over a slide's empty space stays where it is instead of jumping to the slide's start, and copying keeps a line break between paragraphs. Pass
onDrawnSelectionActionand a selection on a deck's page gets a small Comment / Suggest bar. A button calls it with{ action, chapterId, page, text, start, end }, where each end is{ block, blockId, path, offset }(the text box, the paragraph in it first inpath, and the UTF-16 offset there). AdeckChapter's block ids areslide:shapeId:deckBlock(start.blockId)from@nextgensoftwares/folio-plugin-slides/viewergives{ slide, shapeId }. Open yourSlidesAppthere to comment or edit; the thread lives in the deck.
<FolioBookApp
source={source} layout={layout} readerPlugins={[slidesReaderPlugin()]}
editable={(id) => canEdit(id)}
onEditDrawnChapter={({ chapterId, page }) => navigate(`/decks/${chapterId}?slide=${page}`)}
/>Links
A web or mail link clicked on a page not being edited (slide links in a deck chapter too) opens in a new tab. onLinkClick hands it to the host instead, to show an exit page or ask first:
<FolioBookApp source={source} layout={layout} onLinkClick={(href) => openExitPage(href)} />Only http:, https: and mailto: links reach it; other hrefs (#anchor, script URLs) aren't followed. Links drawn as HTML anchors (a slide embed's link) are ordinary <a> elements the host's own click listener sees.
Image zoom
imageZoom opens an image of a page in the reader's lightbox when it's clicked (zoom, pan; Esc, a click beside it or Back closes it):
<FolioBookApp source={source} layout={layout} imageZoom={{ resolve: (a) => signedUrl(a.mediaId), onOpen: (a) => track(a) }} />- Pages not being edited only: the chapter being edited keeps its clicks (caret, selection). On an editable book with
editOnClick, a click on an image opens it rather than the chapter. resolvegives the full-resolution URL (a signed URL); without it the image's ownsrc(only safe URLs).- Drawn on a canvas, never an
<img>(no image URL in the DOM, no "Save image as…", no download). The page layers ofreaderPlugins(a readerwatermarkPlugin, filled withlayerVariables) are drawn over it, so a protected preview keeps its watermark; the book's own editor layers aren't, so a book whose pages carry an editor watermark should pass a readerwatermarkPlugininreaderPluginstoo for zoomed images.
Handle
const book = useRef<BookHandle>(null);
<FolioBookApp bookRef={book} … />
await book.current.goTo({ chapterId: 'ch-4', blockId: 'intro' }); // false: not in the book
await book.current.goTo({ chapterId: 'ch-9' }, { behavior: 'smooth' }); // glides there
book.current.location(); // { chapterId, page, offset }
await book.current.find('quantum'); // match count
await book.current.refresh(['ch-4']);
await book.current.edit('ch-4'); // with openChapter: edit in place (false: refused)initial and onLocationChange restore and save the reading place.
goTo's behavior (the reader's GoToOptions, exported here too): 'instant' (the default) jumps; 'smooth' glides, and a target more than three viewports away jumps to one viewport short of it first, then glides the rest (page 8,000 doesn't scroll past every page); 'auto' glides only when the target is within a viewport. Reduced motion jumps, and so does another chapter in chapterView="chapter" (the chapter shown changes). A target in a chapter not laid out yet still lands on its place once it is. The wheel, a touch, a key or a press stops a glide where it is. The contents panel's chapters, headings and slide thumbnails glide.
Theming and fonts
<FolioHostTheme tokens={…}/> themes the book like the editor (dividers, contents and messages use the same --folio-* tokens). Pass the editor's LoadFamily-based loader to createBookLayout({ fonts: { loader } }) so uploaded fonts show in every chapter.