Skip to main content
Recipe number 216

Cookbook · Chapter 13 · CMS integration

Click on the page to find the source

sourceAt and caretAt turn a click on a laid-out page into a block of the Markdown and an offset; the CMS shows that line of the source, marked.

On this page
Postext
Tested with Postext 1.103.1
Needs ≥ 1.103.0
Licence
Updated 4 Dec 2026
Code MIT · Text CC BY 4.0
A click on “a large correction” on page 1: its block is tinted on the page, a caret marks the offset, and the source beside it shows the same block and the chain text › line › block.
A click on “a large correction” on page 1: its block is tinted on the page, a caret marks the offset, and the source beside it shows the same block and the chain text › line › block.
  • Trim 148 × 210 mm
  • 1 column
  • Source Serif 4 9.5/13.5
  • IBM Plex Sans
  • 2 pages
  • Level
  • Postext 1.103.1
  • Laid out in 78 ms
  • 145 lines of code

In short

A chapter of a bicycle repair manual shown as pages, with the text it was written in beside them. A click on a word of a page finds the same word in the text, marks its paragraph and shows its line number.

What you'll build

A chapter of The Home Bicycle Workshop on a 148 × 210 mm page, shown in postext-viewer on the left, with its Markdown on the right as an editing system would keep it. A click anywhere on a page jumps the source panel to the line under the pointer: the paragraph is tinted in both places, a green caret stands at the character, and two status lines give the line, the column and the offset, and the chain of what is painted there. The card shows a click already made in the middle of a paragraph of the third section.

This recipe answers

  • How do I find which part of the Markdown a click on the page landed on?

The short answer

script.js · lines 122–145in full code
const span = ({ level, source: s }) => `${level} ${s.kind === 'config' ? s.path
  : s.start === undefined ? s.resourceId : `[${s.start}, ${s.end})`}`;
function pick(pageIndex, x, y) {
  // What is painted there, innermost first: a glyph, its line, its paragraph, a box round
  // it; a running head answers with the config entry that set it.
  const chain = sourceAt(doc, pageIndex, x, y);
  $('chain').textContent = chain.map(span).join(' › ');
  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
  const hit = caretAt(doc, pageIndex, x, y); // the character boundary nearest the point
  if (!block || !hit) return view.setAnnotations([]);
  // Offsets count UTF-16 units of the whole file, front matter included, so the line and
  // column come from the Markdown itself.
  const before = markdown.slice(0, hit.offset).split('\n');
  const [line, column] = [before.length, before.at(-1).length + 1];
  $('where').textContent = t({ en: `Line ${line}, column ${column} · offset ${hit.offset}`,
    es: `Línea ${line}, columna ${column} · posición ${hit.offset}` });
  showSource(block, hit.offset, line);
  // The same ranges, drawn back on the page.
  view.setAnnotations([
    { id: 'block', kind: 'highlight', range: block, color: '#2a9aa6' },
    { id: 'caret', kind: 'insert', range: { start: hit.offset, end: hit.offset } },
  ]);
}
view.on('click', ({ pageIndex, x, y }) => pick(pageIndex, x, y));

A point on a page, back to a line of the Markdown

Ingredients

Type
Source Serif 4, IBM Plex Sans (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Lay out a chapter in a design of its own

script.js · lines 33–43in full code
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'IBM Plex Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(0.6), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', 16, folio),
  head('verso-title', '{title}', 'even', 'top-left', 24),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -24),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -16, folio),
] };

The page is a plain workshop manual: Source Serif 4 at 9.5 pt, IBM Plex Sans headings and running heads that change side with the page. Nothing in the layout is there for the click; any laid-out document answers the same calls.

#2 · Ask the layout what is under the point

The code is the short answer above. The viewer's click event gives the page and the point in page px, and two calls read the layout at that point. sourceAt lists what is painted there, innermost first: the glyph, its line, its block, a box round it. A paragraph split across two pages answers with its whole range, and a running head answers with the config entry that set it, not with the Markdown. caretAt gives the character boundary nearest the point, as a click in a text editor does. Both count UTF-16 units of the file with its front matter, so the line and the column come from the Markdown itself.

#3 · Show the line in the source

script.js · lines 149–177in full code
function showSource(block, offset, line) {
  const rows = [];
  let at = 0;
  for (const [i, text] of markdown.split('\n').entries()) {
    const row = document.createElement('div');
    row.className = 'row';
    row.dataset.n = String(i + 1);
    const body = row.appendChild(document.createElement('span')); // one grid cell
    // Cut the line where the block starts and ends and where the caret is.
    const cuts = [at, at + text.length];
    for (const c of [block.start, block.end, offset]) if (c > at && c < cuts[1]) cuts.push(c);
    cuts.sort((a, b) => a - b);
    for (let k = 0; k < cuts.length - 1; k++) {
      const [from, to] = [cuts[k], cuts[k + 1]];
      if (from === offset) body.append(Object.assign(document.createElement('span'),
        { className: 'caret' }));
      const inBlock = from >= block.start && to <= block.end;
      body.append(inBlock ? Object.assign(document.createElement('mark'),
        { textContent: markdown.slice(from, to) }) : markdown.slice(from, to));
    }
    if (offset === cuts.at(-1) && offset > at) body.append(Object.assign(
      document.createElement('span'), { className: 'caret' })); // a caret at the line's end
    rows.push(row);
    at += text.length + 1;
  }
  $('lines').replaceChildren(...rows);
  const target = rows[line - 1];
  $('lines').scrollTop = target.offsetTop - $('lines').clientHeight / 3;
}

The panel cuts each line where the block starts and ends and where the caret falls, so the mark and the caret sit on the same characters the page shows. The same two ranges go back to the viewer as a highlight and an insertion caret, which is how a reader checks that the jump landed where they meant.

The whole recipe

// ═══ Postext Cookbook · Nº 216 · Click on the page to find the source ═════════════════
// https://postext.dev/en/cookbook/click-to-markdown-source
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, IBM Plex Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A chapter of a workshop manual in postext-viewer, with its Markdown beside it. A click on a
// page asks the layout which character and which block lie under the point, and the source
// panel scrolls to that line with the block marked and a caret at the character, the way a
// CMS jumps from a proof to the text an author has to change.
import { buildDocumentWithFonts, renderPageToCanvas, sourceAt, caretAt, rangeRects }
  from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'click-to-markdown-source';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1d2125', // text
  accent: '#1f6f78', // workshop teal: headings' rule, folios
  muted: '#68707a', // running heads
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const LEAD = 13.5; // pt of body leading

// #region book: a manual's page with running heads by parity
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  pages: 'body', fontFamily: 'IBM Plex Sans', fontSize: pt(7), fontWeight: 500,
  letterSpacing: pt(0.6), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(10) } }, ...extra });
const folio = { fontWeight: 600, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', 16, folio),
  head('verso-title', '{title}', 'even', 'top-left', 24),
  head('recto-chapter', '{chapterTitle}', 'odd', 'top-right', -24),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -16, folio),
] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Mark the word, not the paragraph

wordAt widens the offset to the word under the point, in the document's language.

-  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+  const block = wordAt(doc, pageIndex, x, y, markdown); // import wordAt from postext

#Mark the printed line

The line element of the chain is the stretch of Markdown one line of the page sets, which is what a proofreader points at.

-  const block = chain.find((e) => e.level === 'block' && e.source.kind === 'markdown')?.source;
+  const block = chain.find((e) => e.level === 'line' && e.source.kind === 'markdown')?.source;

Credits

Text
Original prose, CC BY 4.0
Fonts
Source Serif 4 (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)