Skip to main content

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

Updated 2026-12-0410 minIn chapter 24 Integrationenescadeelfritptruzhjaar

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-viewer
import { 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).

Postext · an embeddable page viewer
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

OptionDefaultWhat it does
documentThe laid-out document.
markdownThe 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, maxZoom0.1, 8Bounds of a numeric zoom.
gap16CSS px between and round the pages.
trimfalseShow pages trimmed, without bleed and crop marks. Coordinates stay the sheet's.
selectabletrueWhether a drag selects text.
overscan2Pages painted beyond those in view, on each side.
renderOptions for renderPageToCanvas (singleInk, printPreview, finishes…).
geometry{ ownChapter } for a chapter of a book (see Text on the page).
marksOptions for layoutAnnotations (fontFamily, noteSide, paper…).
layers[]Host layers, bottom to top.
labelsEnglishWhat the viewer announces and names, for the host's language.
copyTextthe Markdown(range, markdown) => string: what a copy puts on the clipboard.

#Events

viewer.on(type, handler) returns a function that removes the handler.

EventWhenCarries
selectionchangeThe selection changed, during a drag too.range (or null), text, rects
selectA selection was made: pointer released, word double clicked, Shift + arrow.the same
clickA press on a page.pageIndex, x, y (page px), offset, chapter, blockId, annotations (ids, top first), originalEvent
hoverThe pointer moved onto another block or other marks.the same as click
annotationclickA mark was pressed, with the pointer or the keyboard.id, annotation, pageIndex, originalEvent
pagechangeThe page most in view changed.pageIndex
zoomchangeThe zoom changed (a call, a resize in a fitted mode).zoom
renderA 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

MethodWhat 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), annotationsReplace the marks.
setSelection(range), selectionSelect a range from code, or clear with null.
setZoom(zoom), zoomZoom, keeping the place in view.
goToPage(i), pageIndexScroll 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:

PropertyDefault
--pv-background#e8e6e1
--pv-page-background#fff
--pv-page-shadowa soft two-layer shadow
--pv-selectionrgb(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.