Skip to main content

Chapter 24.5 · Part III · In practice

Integration: reading apps and other viewers

The integration API in a reading app, an e-reader or a study platform: a highlighter that snaps to words and keeps its colours across editions, reader notes in the margin with a notebook, and the same marks in a viewer of your own

Updated 2026-12-049 minIn chapter 24 Integrationenescadeelfritptruzhjaar

In short

This page is for developers who build an app where people read a book. It shows how readers can mark passages in colour and write notes beside them. The marks are saved on the reader's device and still find their words when a corrected edition comes out. The same tools work in the ready-made viewer and in a viewer the app draws itself.

The calls a content system uses to point at a book's words serve a reading app just as well: readers select, mark and annotate, and the marks follow the text.

The overview speaks of editors and reviewers, but nothing in the integration API knows who is looking at the pages. A reading app, an e-reader for a publisher's catalogue, a study platform with textbooks or a library's online reader asks the same questions: which words did the reader select, where are they on the page, how do I paint a colour over them, and will they still be there in next year's edition. The host is the app, the records are the reader's, and Postext does the same page work.

The reader wants toThe app uses
Select a passage, and get whole words even after a careless dragThe viewer's select event, wordRangeAt
Shade it in a colour, or attach a note to itsetAnnotations with highlight and note marks
See a toolbar or a note card right over the wordsrangeRects and pageToClient
Press a mark to change or read itannotationclick, or annotationAt outside the viewer
Keep the marks after the publisher corrects the booktextAnchor to store, resolveAnchor to find again
Find a passage from a list of marksrevealAnnotation

The two examples below are the core of two Cookbook recipes, with a runnable pen each: a reader's highlighter and a reader's notebook.

#A highlighter

The reader drags across a sentence, a small bar with four colours appears over it, and a press shades the sentence. A press on a shaded passage brings the bar back to change the colour or remove it.

import { buildDocument, wordRangeAt } from 'postext';
import { textAnchor, resolveAnchor } from 'postext/annotate';
import { createViewer } from 'postext-viewer';
 
const PENS = { yellow: '#f2c230', green: '#5cb85c', blue: '#4a90d9', pink: '#e26a9a' };
const doc = buildDocument({ markdown }, config);
const view = createViewer(element, { document: doc, markdown, zoom: 'fit-width' });
 
let highlights = load(); // [{ id, pen, range }], see "Keeping the marks" below
let pending = null; // what the bar acts on: { range } for a new one, { id } for one saved
 
// A drag that starts or ends inside a word takes the whole word.
const snap = ({ start, end }) => {
  const a = wordRangeAt(markdown, start, { locale: config.locale });
  const b = wordRangeAt(markdown, end, { locale: config.locale });
  return { start: a && a.start < start && start < a.end ? a.start : start,
    end: b && b.start < end && end < b.end ? b.end : end };
};
 
view.on('select', ({ range }) => {
  if (!range || range.end <= range.start) return closeBar();
  const same = pending?.range?.start === range.start && pending?.range?.end === range.end;
  if (same) return; // the snapped range coming back from setSelection
  pending = { range: snap(range) };
  view.setSelection(pending.range);
  openBar(pending.range);
});
view.on('annotationclick', ({ id }) => {
  pending = { id };
  openBar(highlights.find((h) => h.id === id).range);
});
 
function pick(pen) {
  if (pending.id) highlights = highlights.map((h) => (h.id === pending.id ? { ...h, pen } : h));
  else highlights = [...highlights, { id: crypto.randomUUID(), pen, range: pending.range }];
  closeBar();
  view.setSelection(null);
  save(highlights);
  view.setAnnotations(highlights.map(({ id, pen, range }) =>
    ({ id, kind: 'highlight', range, color: PENS[pen] })));
}

Three details matter:

  • Snap before storing. The viewer selects character by character, as a browser does. wordRangeAt works on the Markdown alone and follows the language's word rules (Chinese and Japanese included), so the stored range never starts in the middle of a word.
  • Ignore the echo. setSelection fires select again with the snapped range. Without the check the handler would offer the bar forever.
  • Colours are the app's. A highlight mark takes any CSS colour and lays it as a translucent fill (35 %) over the words, so the ink stays legible. The marks are the app's own data: the viewer keeps no list of them, and every setAnnotations replaces the whole set.

#The bar over the words

The bar is the app's own HTML, placed over the viewer. view.rangeRects gives the pieces of the range on the pages, in page pixels; pageToClient turns a point of a page into window coordinates at the current zoom and scroll.

function placeBar(range) {
  const first = view.rangeRects(range)[0];
  const at = first && view.pageToClient(first.pageIndex,
    first.rect.x + first.rect.width / 2, first.rect.y);
  if (!at) return closeBar(); // the passage is on no page in view
  Object.assign(bar.style, { left: `${at.x}px`, top: `${at.y - 10}px` });
}
view.on('zoomchange', () => pending && placeBar(currentRange()));
view.element.addEventListener('scroll', () => pending && placeBar(currentRange()),
  { capture: true, passive: true });

With position: fixed and translate(-50%, -100%) on the bar, it sits centred above the first line of the passage and follows it when the reader scrolls or zooms.

#Notes in the margin

A study app lets the reader write a note on a passage. The passage is tinted, a numbered flag goes in the outer margin, and the flag opens the note in a card under its words. A notebook beside the pages lists every note in reading order.

const view = createViewer(element, {
  document: doc, markdown, zoom: 'fit-width',
  marks: { noteSide: 'end' }, // every flag in the outer margin
});
 
function render() {
  notes.sort((a, b) => a.range.start - b.range.start); // numbered in reading order
  view.setAnnotations(notes.map(({ id, range }, i) => ({
    id, kind: 'note', range, label: String(i + 1), color: '#0f766e',
  })));
  renderNotebook(notes);
}
 
view.on('select', ({ range }) => {
  if (range && range.end > range.start) openCard({ range, mode: 'write' });
});
view.on('annotationclick', ({ id }) => openCard({ id, mode: 'read' }));

A note mark tints the words and draws a flag on the margin nearest its line, joined to the words by a dashed leader; noteSide: 'end' sends all flags to the end margin (the right one in a left-to-right book). Flags at the same height stack down the margin without overlapping. Leave the margin room for them in the book's own design: a page with a 20 mm outer margin has nowhere to put a flag.

The card is placed like the highlighter's bar, under the last piece of the range instead of over the first:

const last = view.rangeRects(range).at(-1);
const at = view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);

Each entry of the notebook is a button that calls view.revealAnnotation(id) and opens the card: the viewer scrolls the note's words into view, whatever page they are on. The page number for the entry comes from view.rangeRects(range)[0].pageIndex.

#Keeping the marks

A reader's marks outlive the edition they were made in. The publisher fixes a typo, a footnote is added, a paragraph is rewritten, and every offset after the change moves. Store an anchor, not the bare range:

const save = (marks) => localStorage.setItem(key, JSON.stringify(
  marks.map(({ id, pen, range }) => ({ id, pen, anchor: textAnchor(markdown, range) }))));
 
const load = () => (JSON.parse(localStorage.getItem(key) ?? '[]')).flatMap((m) => {
  const found = resolveAnchor(markdown, m.anchor);
  if (found.status === 'exact' || found.status === 'moved') {
    return [{ ...m, range: { start: found.start, end: found.end } }];
  }
  return []; // ambiguous or orphaned: see below
});

textAnchor keeps the range, the words it covered and some text on each side. resolveAnchor looks for them in the text the app has now:

  • exact: same place, same words. The common case.
  • moved: the words are found elsewhere, by their context. Save the anchor again so the next search starts from the new place.
  • ambiguous: the words occur more than once and the context does not settle which. Show the candidates and let the reader choose, or keep the mark aside.
  • orphaned: the words are gone. Do not drop the reader's note in silence; list it apart with the words it was about ("this passage was removed in the new edition").

The anchor is plain JSON, so the same records can go to the app's server to follow the reader from phone to tablet. Key them by the book and the chapter file; the edition does not need to be part of the key, because the anchor finds its words in any edition.

#In a viewer of your own

An app that already draws the pages its own way (page images from the command line, a canvas, a native view on a tablet) does without postext-viewer and uses the functions underneath.

Painting: layoutAnnotations lays the marks out once for the document; paintAnnotations paints a page's marks on a canvas context in page pixels, and annotationsSvg writes them as an SVG the size of the page to lay over an image.

import { layoutAnnotations, annotationsSvg, annotationAt } from 'postext/annotate';
 
const shapes = layoutAnnotations(doc, marks, { fontFamily: 'Inter' });
overlay.innerHTML = annotationsSvg(shapes, doc.pages[i], { pageIndex: i });

Pointing: turn the pointer into page pixels with the page element's size, then ask what is there.

import { caretAt } from 'postext';
 
pageImage.addEventListener('pointerup', (e) => {
  const r = pageImage.getBoundingClientRect();
  const x = (e.clientX - r.left) * (doc.pages[i].width / r.width);
  const y = (e.clientY - r.top) * (doc.pages[i].height / r.height);
  const [id] = annotationAt(shapes, i, x, y); // the mark on top, if any
  if (id) return openMark(id);
  const hit = caretAt(doc, i, x, y); // else the character boundary under the pointer
  if (hit) extendSelection(hit.offset);
});

A selection made from two caretAt offsets is snapped with wordRangeAt and painted from rangeRects like any other range. Text on the page has the details for turned frames and vertical pages, and the Cookbook recipe Your own canvas builds a selection and a caret this way.

#In the Cookbook

RecipeShows
A reader's highlighterFour colours over the selection, words snapped, anchors in localStorage, a list beside the pages
A reader's notebookNotes written on a selection, flags in the margin, a card placed from page coordinates, a notebook
Notes in the margin, with a popoverFlags and a popover under the words, for notes that come from elsewhere
Search results drawn on the pagesEvery match tinted, the current one boxed, next and previous
Marks as SVG over page images, for a reportThe same marks without the viewer, over PNG pages