Zum Hauptinhalt springen
Rezept Nummer 216

Rezepte · Kapitel 13 · CMS-Integration

Auf die Seite klicken, um die Quelle zu finden

sourceAt und caretAt machen aus einem Klick auf eine gesetzte Seite einen Block des Markdown und eine Position; das CMS zeigt diese Zeile markiert.

Auf dieser Seite
Stufe
Mittel
Postext
Getestet mit Postext 1.103.1
Erfordert ≥ 1.103.0
Lizenz
Aktualisiert am 4. Dez. 2026
Code MIT · Text CC BY 4.0
Ein Klick auf „a large correction“ auf Seite 1: sein Block ist auf der Seite getönt, eine Schreibmarke zeigt die Position, und die Quelle daneben zeigt denselben Block und die Kette text › line › block.
Ein Klick auf „a large correction“ auf Seite 1: sein Block ist auf der Seite getönt, eine Schreibmarke zeigt die Position, und die Quelle daneben zeigt denselben Block und die Kette text › line › block.
  • Englisches Beispiel: noch keine deutsche Ausgabe
  • Endformat 148 × 210 mm
  • 1 Spalte
  • Source Serif 4 9,5/13,5
  • IBM Plex Sans
  • 2 Seiten
  • Stufe
  • Postext 1.103.1
  • In 78 ms gesetzt
  • 145 Zeilen Code

Kurz gesagt

Ein Kapitel aus einem Handbuch zur Fahrradreparatur, als Seiten gezeigt, daneben der Text, aus dem sie entstehen. Ein Klick auf ein Wort der Seite findet dasselbe Wort im Text, markiert seinen Absatz und nennt die Zeilennummer.

Was Sie setzen

Ein Kapitel aus The Home Bicycle Workshop auf einer Seite von 148 × 210 mm, links in postext-viewer gezeigt, rechts sein Markdown, wie ein Redaktionssystem es aufbewahrt. Ein Klick irgendwo auf eine Seite bringt das Quelltextfeld zu der Zeile unter dem Zeiger: Der Absatz wird auf beiden Seiten getönt, eine grüne Einfügemarke steht am Zeichen, und zwei Statuszeilen nennen Zeile, Spalte und Position sowie die Kette dessen, was dort gemalt ist. Die Karte zeigt einen Klick mitten in einem Absatz des dritten Abschnitts.

Dieses Rezept beantwortet

  • Wie finde ich heraus, auf welchen Teil des Markdowns ein Klick auf die Seite gefallen ist?

Die kurze Antwort

script.js · Zeilen 122–145im vollständigen 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));

Zutaten

Schrift
Source Serif 4, IBM Plex Sans (SIL OFL 1.1)
Dateien
Keine: Jedes Bild wird im Code gezeichnet

Zubereitung

#1 · Ein Kapitel mit eigenem Entwurf setzen

script.js · Zeilen 33–43im vollständigen 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),
] };

Die Seite ist die eines schlichten Werkstatthandbuchs: Source Serif 4 in 9,5 pt, Überschriften in IBM Plex Sans und Kolumnentitel, die mit der Seite die Seite wechseln. Nichts am Satz ist für den Klick da; jedes gesetzte Dokument beantwortet dieselben Aufrufe.

#2 · Den Satz fragen, was unter dem Punkt liegt

Der Code steht in der kurzen Antwort oben. Das Ereignis click des Betrachters liefert die Seite und den Punkt in Seitenpixeln, und zwei Aufrufe lesen den Satz an diesem Punkt. sourceAt listet auf, was dort gemalt ist, von innen nach außen: die Glyphe, ihre Zeile, ihr Block, ein Kasten darum. Ein Absatz, der über zwei Seiten läuft, antwortet mit seinem ganzen Bereich, und ein Kolumnentitel antwortet mit dem Konfigurationseintrag, der ihn gesetzt hat, nicht mit dem Markdown. caretAt liefert die nächste Zeichengrenze, wie ein Klick in einem Texteditor. Beide zählen UTF-16-Einheiten der Datei samt Front Matter, Zeile und Spalte ergeben sich also aus dem Markdown selbst.

#3 · Die Zeile in der Quelle zeigen

script.js · Zeilen 149–177im vollständigen 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;
}

Das Feld schneidet jede Zeile dort, wo der Block beginnt und endet und wo die Einfügemarke fällt, sodass Markierung und Marke auf denselben Zeichen stehen, die die Seite zeigt. Dieselben zwei Bereiche gehen als Hervorhebung und Einfügezeichen an den Betrachter zurück; so prüft der Leser, dass der Sprung dort gelandet ist, wo er wollte.

Das ganze Rezept

// ═══ 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,

Das zusammengesetzte script.js läuft unverändert: Fügen Sie es in das Modulskript einer beliebigen Seite ein, oder öffnen Sie das Rezept auf CodePen. Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)

Varianten

#Das Wort markieren, nicht den Absatz

wordAt erweitert die Position auf das Wort unter dem Punkt, in der Sprache des Dokuments.

-  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

#Die gedruckte Zeile markieren

Das Element line der Kette ist das Stück Markdown, das eine Zeile der Seite setzt, und darauf zeigt, wer Korrektur liest.

-  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;

Nachweise

Text
Eigener Text, CC BY 4.0
Schriften
Source Serif 4 (SIL OFL 1.1) · IBM Plex Sans (SIL OFL 1.1)