Chapter 24.4 · Part III · In practice
Integration: the page viewer
postext-viewer: an embeddable viewer that shows the pages, reports selections and presses as Markdown ranges and offsets, paints annotation marks, gives the host layers over each page, and converts between page and screen coordinates; with a React component
In short
This page is for developers. It shows a ready-made viewer that puts the pages of a book inside a web page with one call. People can scroll, zoom and select words, and the system learns which words of the text they chose. The system can draw its marks on the pages and place its own buttons over them. The viewer also works with the keyboard and with screen readers.
postext-viewer shows the pages and speaks in Markdown ranges: what was selected, what was pressed, where a mark goes.
npm install postext postext-viewerimport { buildDocument } from 'postext';
import { createViewer } from 'postext-viewer';
const doc = buildDocument({ markdown }, config);
const viewer = createViewer(document.getElementById('pages'), { document: doc, markdown });
viewer.on('select', ({ range, text }) => {
console.log(range, text); // { start: 52, end: 65 } 'hives at dawn'
});The viewer fills its container: give the container a height. It shows the
pages in a scrolling column and paints with renderPageToCanvas at the size
they are shown, times the screen's pixel ratio. Only the pages in view and
two on each side are painted (overscan); pages further away give their
memory back, so a 600-page book costs a few pages of canvas.
As for renderPage, load the fonts and register the images the document
uses before the viewer paints (document.fonts.load, registerResourceImage).
import { buildDocument } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';
const paragraph = 'The keeper walked the hives at dawn, lifting each lid with care and reading the frames for brood, honey and the queen. A hive that hums low in the cold keeps its cluster tight; one that roars at noon wants more room before the flow.';
const markdown = ['# The apiary', ...Array.from({ length: 10 }, () => paragraph)].join('\n\n');
const config = {
page: { width: { value: 120, unit: 'mm' }, height: { value: 170, unit: 'mm' } },
bodyText: { fontFamily: 'EB Garamond', fontSize: { value: 11, unit: 'pt' }, lineHeight: { value: 15, unit: 'pt' } },
};
// Postext measures text with the fonts the browser has loaded.
await Promise.all([
document.fonts.load('16px "EB Garamond"'),
document.fonts.load('italic 16px "EB Garamond"'),
document.fonts.load('bold 16px "Open Sans"'),
]);
const doc = buildDocument({ markdown }, config);
// Fitted to the width, but never larger than 1.4 CSS px per page px.
const viewer = createViewer(document.getElementById('pages'), { document: doc, markdown, maxZoom: 1.4 });
// The host's own records. Postext only sees ranges and kinds.
const marks = [];
let selected = null;
const selection = document.getElementById('selection');
const highlight = document.getElementById('highlight');
const note = document.getElementById('note');
const list = document.getElementById('marks');
viewer.on('selectionchange', ({ range, text }) => {
selected = range;
const shown = text.length > 80 ? `${text.slice(0, 80)}…` : text;
selection.textContent = range ? `“${shown}” (Markdown ${range.start}–${range.end})` : 'Select some words on the page.';
highlight.disabled = note.disabled = !range;
});
function add(kind) {
if (!selected) return;
const id = `m${marks.length + 1}`;
marks.push({ id, kind, range: selected, label: kind === 'note' ? String(marks.length + 1) : undefined });
viewer.setAnnotations(marks);
viewer.setSelection(null);
draw();
}
highlight.addEventListener('click', () => add('highlight'));
note.addEventListener('click', () => add('note'));
function draw() {
list.replaceChildren(...marks.map((m) => {
const li = document.createElement('li');
const go = document.createElement('button');
go.textContent = `${m.kind}: ${markdown.slice(m.range.start, m.range.end)}`;
go.addEventListener('click', () => viewer.revealAnnotation(m.id, { behavior: 'smooth' }));
li.append(go);
return li;
}));
}
// A press on a mark, with the pointer or the keyboard.
viewer.on('annotationclick', ({ id }) => {
const i = marks.findIndex((m) => m.id === id);
list.children[i]?.querySelector('button')?.focus();
});index.html
<main>
<div id="pages"></div>
<aside>
<p id="selection">Select some words on the page.</p>
<div class="actions">
<button id="highlight" disabled>Highlight</button>
<button id="note" disabled>Note</button>
</div>
<ol id="marks"></ol>
</aside>
</main>style.css
body {
margin: 0;
font-family: system-ui, sans-serif;
color: #1d1d1f;
}
main {
display: grid;
grid-template-columns: 1fr 240px;
height: 100vh;
}
/* The viewer fills its container: give it a height. */
#pages {
height: 100vh;
min-width: 0;
--pv-background: #ecebe6;
}
aside {
padding: 16px;
border-left: 1px solid #d8d6cf;
overflow: auto;
font-size: 14px;
}
#selection {
min-height: 3.5em;
color: #555;
}
.actions {
display: flex;
gap: 8px;
}
button {
min-height: 44px;
padding: 0 14px;
font: inherit;
border: 1px solid #2f6fd6;
border-radius: 6px;
background: #fff;
color: #1f4f9e;
cursor: pointer;
}
button:disabled {
border-color: #c8c6bf;
color: #8a8880;
cursor: default;
}
#marks {
padding-left: 20px;
}
#marks li {
margin: 8px 0;
}
#marks button {
min-height: 32px;
border: 0;
padding: 0;
text-align: left;
color: #1d1d1f;
text-decoration: underline;
}Loads an interactive editor from codepen.io. The example imports the latest postext release from a CDN.
#Options
| Option | Default | What it does |
|---|---|---|
document | The laid-out document. | |
markdown | The Markdown it was laid out from: needed for words on double click, the selected text and copying. | |
annotations | [] | Marks from postext/annotate. |
zoom | 'fit-width' | A number (CSS px per page px), 'fit-width' or 'fit-page'. |
minZoom, maxZoom | 0.1, 8 | Bounds of a numeric zoom. |
gap | 16 | CSS px between and round the pages. |
trim | false | Show pages trimmed, without bleed and crop marks. Coordinates stay the sheet's. |
selectable | true | Whether a drag selects text. |
overscan | 2 | Pages painted beyond those in view, on each side. |
render | Options for renderPageToCanvas (singleInk, printPreview, finishes…). | |
geometry | { ownChapter } for a chapter of a book (see Text on the page). | |
marks | Options for layoutAnnotations (fontFamily, noteSide, paper…). | |
layers | [] | Host layers, bottom to top. |
labels | English | What the viewer announces and names, for the host's language. |
copyText | the Markdown | (range, markdown) => string: what a copy puts on the clipboard. |
#Events
viewer.on(type, handler) returns a function that removes the handler.
| Event | When | Carries |
|---|---|---|
selectionchange | The selection changed, during a drag too. | range (or null), text, rects |
select | A selection was made: pointer released, word double clicked, Shift + arrow. | the same |
click | A press on a page. | pageIndex, x, y (page px), offset, chapter, blockId, annotations (ids, top first), originalEvent |
hover | The pointer moved onto another block or other marks. | the same as click |
annotationclick | A mark was pressed, with the pointer or the keyboard. | id, annotation, pageIndex, originalEvent |
pagechange | The page most in view changed. | pageIndex |
zoomchange | The zoom changed (a call, a resize in a fitted mode). | zoom |
render | A page was painted. | pageIndex |
The first pages are painted on the frame after createViewer, so handlers
added right after it hear the first render and pagechange.
A selection turned into a comment, the whole host side:
viewer.on('select', async ({ range }) => {
if (!range) return;
const body = prompt('Comment');
if (!body) return;
const anchor = textAnchor(markdown, range);
const saved = await api.createComment({ chapter, anchor, body }); // the host's own API
viewer.setAnnotations([...viewer.annotations, { id: saved.id, kind: 'note', range, label: String(saved.number) }]);
viewer.setSelection(null);
});
viewer.on('annotationclick', ({ id }) => openThread(id));#Methods
| Method | What it does |
|---|---|
setDocument(doc, markdown?) | Show a new layout (after an edit). The page in view, the selection's offsets and the marks are kept. |
setMarkdown(md) | Change the Markdown without a new layout. |
setAnnotations(list), annotations | Replace the marks. |
setSelection(range), selection | Select a range from code, or clear with null. |
setZoom(zoom), zoom | Zoom, keeping the place in view. |
goToPage(i), pageIndex | Scroll to a page. |
revealRange(range), revealAnnotation(id) | Scroll a range or a mark into view. False when it is on no page. |
rangeRects(range) | rangeRects on the document shown. |
pageToClient(page, x, y), clientToPage(x, y) | Page px to viewport px and back, for placing popovers. |
pageElement(i) | A page's element. |
addLayer(layer), removeLayer(id), refreshLayers() | Host layers. |
destroy() | Remove the viewer and free its canvases. |
#Host layers
A layer draws what the host owns over the pages: comment pins, a collaborator's cursor, the boxes of a translation memory match.
viewer.addLayer({
id: 'pins',
// On a canvas in page px, above the marks
paint(ctx, { pageIndex, page }) {
for (const c of commentsOn(pageIndex)) {
ctx.fillStyle = c.color;
ctx.beginPath();
ctx.arc(page.width - 24, c.y, 7, 0, Math.PI * 2);
ctx.fill();
}
},
// DOM over the page; its CSS px are page px
mount(el, { pageIndex }) {
const root = createRoot(el);
root.render(<Avatars page={pageIndex} />);
return () => root.unmount();
},
});mount runs when a page enters the painted window and its return value when
it leaves, so a long book never has more than a few pages of host DOM.
refreshLayers() paints and mounts the layers again after the host's data
changed.
#Keyboard and screen readers
- The viewer is a focusable region named by
labels.viewer; each page is named "Page 3 of 41". - Page Up and Page Down go a page back and forward, Home and End to the first and last page; Ctrl or ⌘ with + and − zoom.
- Escape clears the selection; Shift + ← and → move its end a character.
- Each mark is a button over its words, with a name such as "Replacement: young bees", in the tab order; Enter or Space fires
annotationclick. - A selection is announced in a live region ("13 characters selected").
labels translates all of it:
createViewer(el, {
document: doc,
labels: {
viewer: 'Páginas del libro',
page: 'Página {n} de {count}',
selection: '{count} caracteres seleccionados',
selectionCleared: 'Selección borrada',
kinds: { replace: 'Sustitución', note: 'Nota' },
},
});#Look
The viewer adds one small stylesheet. Set these custom properties on the container or any ancestor:
| Property | Default |
|---|---|
--pv-background | #e8e6e1 |
--pv-page-background | #fff |
--pv-page-shadow | a soft two-layer shadow |
--pv-selection | rgb(47 111 214 / .3) |
--pv-focus | #2f6fd6 |
#React
import { PostextViewer } from 'postext-viewer/react';
function Proofs({ doc, markdown, marks, onComment }) {
const viewer = useRef(null);
return (
<PostextViewer
ref={viewer}
document={doc}
markdown={markdown}
annotations={marks}
onSelect={({ range }) => range && onComment(range)}
onAnnotationClick={({ id }) => openThread(id)}
style={{ height: '80vh' }}
/>
);
}Props follow the options and the events (onSelect, onSelectionChange,
onClick, onHover, onAnnotationClick, onPageChange, onZoomChange,
onRender). document, markdown, annotations, zoom, layers and
selection are applied to the live viewer when they change; handlers may be
new functions on each render. The ref is the viewer's handle, with every
method above.
#Without the viewer
A host with its own page display (a canvas it already paints, page images, a 3D book) does not need the viewer: Text on the page and Annotation marks give the same geometry and marks as calls.
#Examples in the Cookbook
Recipes that use what this page describes, each under the section it suits best. A recipe shows its pages beside the whole script.
The page viewer
- Nº 212Select on the page, read the Markdown range and text
- Nº 213Highlights from a list of ranges
- Nº 211A book in a page viewer: pages, zoom, navigation
- Nº 214Proofreading marks: strike, replace and insert
- Nº 215Notes in the margin, with a popover from page coordinates
- Nº 224A reader's notebook: notes on what they select
6 more recipes with Page viewer (postext-viewer) in the Cookbook





