Skip to main content

Chapter 24.1 · Part III · In practice

Integration: text on the page

rangeRects, caretRect, caretAt, wordAt, blockAt and wordRangeAt: where a range of the Markdown is painted on the laid-out pages, and which offset, word or block lies under a point, on justified, right-to-left, vertical and composed pages

Updated 2026-12-048 minIn chapter 24 Integrationenescadeelfritptruzhjaar

In short

This page is for developers. It shows how to find where some words of the text are drawn on a page, as boxes you can paint over. It also shows the other way round: which letter or word is under the point someone clicked. Both work on pages set right to left, in vertical columns and in turned frames. The numbers are positions in the Markdown text, so they match what the system stores.

From a range of the Markdown to boxes on the page, and from a point on the page back to the Markdown.

These calls read a laid-out document (a VDTDocument from buildDocument or from the layout worker) and place text with the same code the canvas, HTML and PDF renderers paint it with: justified spaces, hyphens added at line ends, bidirectional lines, right-to-left and vertical pages, drop caps, opener band titles, composed frames turned or scaled, comic balloons.

Two units run through all of them:

  • Offsets are UTF-16 indices into the chapter's Markdown file, front matter counted, as sourceAt and every sourceStart of the VDT count them. A range is { start, end }, end excluded.
  • Coordinates are page px on the sheet, from its top-left corner (the sheet includes the bleed when the page has cut lines). Multiply by the scale you painted the page at.

#Where a range lies: rangeRects

import { buildDocument, renderPage, rangeRects } from 'postext';
 
const markdown = '# The apiary\n\nThe keeper walked the hives at dawn, lifting each lid with care.';
const doc = buildDocument({ markdown }, config);
 
const start = markdown.indexOf('the hives');
const pieces = rangeRects(doc, { start, end: start + 'the hives at dawn'.length });
// [{ pageIndex: 0, blockId: 'b2', rect: { x, y, width, height }, quad: [p0, p1, p2, p3],
//    baseline: [left, right], upright: true, fontSize: 13.3 }, …]

A range gives one piece per run of a line: a range that breaks across two lines gives two pieces, across a page break two pieces on two pages. Each piece has:

FieldWhat it is
pageIndexThe page it is on.
blockIdThe block it is in (a paragraph, a heading, a table cell's block, a balloon).
rectIts axis-aligned bounds on the sheet: enough for a highlight on an upright page.
quadIts four corners in the line's own order (top-left, top-right, bottom-right, bottom-left as the line runs). On a vertical page or in a turned frame it is not a rectangle of the sheet: draw the polygon.
baselineThe baseline under the piece, from its start to its end. An underline follows it.
uprightSet when rect is the piece exactly.
fontSizeThe text's em in px, for marks that set text of their own.

To highlight a selection on a page painted with renderPage:

const scale = 2;
const canvas = renderPage(doc.pages[0], doc, { scale });
const ctx = canvas.getContext('2d');
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.fillStyle = 'rgb(47 111 214 / 0.3)';
for (const piece of pieces.filter((p) => p.pageIndex === 0)) {
  ctx.beginPath();
  piece.quad.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
  ctx.fill();
}
Postext · the word under a click
import { buildDocument, renderPageToCanvas, rangeRects, wordAt } from 'https://esm.sh/postext';
 
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', paragraph, paragraph].join('\n\n');
const config = {
  page: { width: { value: 120, unit: 'mm' }, height: { value: 120, unit: 'mm' } },
  bodyText: { fontFamily: 'EB Garamond', fontSize: { value: 12, unit: 'pt' }, lineHeight: { value: 16, unit: 'pt' } },
};
await Promise.all([document.fonts.load('16px "EB Garamond"'), document.fonts.load('bold 16px "Open Sans"')]);
 
const doc = buildDocument({ markdown }, config);
const page = doc.pages[0];
const canvas = document.getElementById('page');
const scale = 2;
const status = document.getElementById('status');
 
function paint(range) {
  renderPageToCanvas(page, doc, canvas, { scale });
  canvas.style.width = `${page.width}px`;
  if (!range) return;
  const ctx = canvas.getContext('2d');
  ctx.setTransform(scale, 0, 0, scale, 0, 0);
  ctx.fillStyle = 'rgb(192 131 0 / 0.35)';
  // One piece per run of a line: a word broken by a hyphen gives two.
  for (const piece of rangeRects(doc, range).filter((p) => p.pageIndex === 0)) {
    ctx.beginPath();
    piece.quad.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
    ctx.fill();
  }
}
 
canvas.addEventListener('click', (e) => {
  // From the screen to page px.
  const r = canvas.getBoundingClientRect();
  const x = (e.clientX - r.left) * (page.width / r.width);
  const y = (e.clientY - r.top) * (page.height / r.height);
  const word = wordAt(doc, 0, x, y, markdown);
  paint(word);
  status.textContent = word ? `“${markdown.slice(word.start, word.end)}” is Markdown ${word.start}–${word.end}` : 'No text there.';
});
 
paint(null);
index.html
<p id="status">Click a word on the page.</p>
<canvas id="page"></canvas>
style.css
body {
  margin: 0;
  padding: 16px;
  font-family: system-ui, sans-serif;
  background: #ecebe6;
  color: #1d1d1f;
}
#status {
  margin: 0 0 12px;
  min-height: 1.4em;
}
canvas {
  display: block;
  max-width: 100%;
  height: auto;
  background: #fff;
  box-shadow: 0 2px 10px rgb(0 0 0 / 0.15);
  cursor: text;
}

Loads an interactive editor from codepen.io. The example imports the latest postext release from a CDN.

Callouts, figures and other blocks that are not running text give no pieces; a range that covers them gives the pieces of the text around them. Text hidden under an opener band (the heading the band repeats) is left out, and the band's title gives the pieces instead.

#A caret: caretRect

caretRect(doc, offset) gives the line of a caret at a character boundary: { pageIndex, blockId, from, to }, from the top of the text line to its foot, in the line's frame. On a vertical page the caret lies across the column. It returns null for an offset that falls in no painted text.

#What is under a point: caretAt, wordAt, blockAt

canvas.addEventListener('click', (e) => {
  const r = canvas.getBoundingClientRect();
  const x = (e.clientX - r.left) * (doc.pages[0].width / r.width);
  const y = (e.clientY - r.top) * (doc.pages[0].height / r.height);
 
  const hit = caretAt(doc, 0, x, y);
  // { offset: 57, pageIndex: 0, blockId: 'b2' }, or null off the text
  const word = wordAt(doc, 0, x, y, markdown);
  // { start: 52, end: 59, pageIndex: 0, blockId: 'b2' }
  const block = blockAt(doc, 0, x, y);
  // { start: 14, end: 83, pageIndex: 0, blockId: 'b2' }: the paragraph's whole range
});
  • caretAt gives the character boundary nearest the point, like a click in a text editor. It finds the nearest line of the nearest block, so a click in the gutter between two lines still lands on one of them. On a composed page the frame painted on top wins.
  • wordAt widens that offset to the word around it, with Intl.Segmenter in the document's language (Chinese and Japanese words included), and leaves out Markdown emphasis marks at the word's edges. It takes the Markdown, or a function (chapter) => markdown for text a story carried in from another chapter.
  • blockAt gives the block and its source range: a paragraph to comment on as a whole.
  • wordRangeAt(markdown, offset, { locale }) does the word step on the Markdown alone, without a page.

#Chapters and books

A book is laid out one chapter at a time, and a page can carry text that a story brought in from another chapter (VDTBlock.sourceChapter). The options say which Markdown the offsets count in:

rangeRects(doc, range, { chapter: 3, ownChapter: 2 });
caretAt(doc, page, x, y, { ownChapter: 2 }); // → { offset, chapter: 3 } on carried text
  • ownChapter is the position of the chapter doc lays out. A chapter equal to it, or none, means the document's own file.
  • pages: { from, to } limits the search to a run of pages, for a document stitched from several chapters.

caretAt and wordAt set chapter in their answer when the text under the point belongs to another chapter.

#Writing modes and frames

Nothing changes in the calls. On a right-to-left page the quad runs from right to left, so quad[0] is the right end of the piece. On a vertical page (layout.writingMode: 'vertical-rl') a piece is a column segment: its quad runs top to bottom and its "top" is its right side, so an underline along quad[0]–quad[1] is the sideline Chinese and Japanese use. In a composed frame turned by 30° the quad is turned by 30°.

#The pieces underneath

postext/geometry exports what these calls are built from, for a host that draws its own caret or hit-tests its own way: placeLineSegments (each segment of a line where it is painted), sourceToPlainIndex and plainRangeInLine (Markdown offsets against the painted text), blockFrameMatrix and intoBlockSpace (a composed frame's matrix), bandLineBoxes (an opener band's title), sourceHitAt. The Sandbox's own canvas preview uses them.

#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.