Kurz gesagt
Ein Geschichtsbuch in einer Lern-App. Man markiert ein paar Wörter, und darunter öffnet sich eine Karte für eine Notiz. Die Wörter werden leicht getönt und bekommen eine nummerierte Marke am Rand. Neben dem Buch stehen alle Notizen.
Was Sie setzen
Ein Kapitel eines Geschichtsbuchs, When books became cheap („Als Bücher billig wurden“), in einer Lern-App. Eine Schülerin markiert eine Stelle, und darunter öffnet sich eine Karte mit den zitierten Wörtern und einem Feld zum Schreiben. Beim Speichern wird die Stelle getönt, und eine nummerierte Fahne erscheint im breiten Außenrand. Die Fahne oder die getönten Wörter öffnen die Notiz über der Seite, mit Knöpfen zum Bearbeiten und Löschen. Das Heft rechts listet alle Notizen in Lesereihenfolge, mit ihren Wörtern und ihrer Seite: der Lernzettel, der beim Lesen entsteht. Die Notizen bleiben als Anker auf dem Gerät, sodass eine korrigierte Auflage des Buchs sie auf ihren Wörtern hält.
Dieses Rezept beantwortet
- Wie lasse ich Leser eine Notiz zu einer markierten Stelle schreiben und ihre Notizen auflisten?
Die kurze Antwort
const view = createViewer($('viewer'), {
document: doc, markdown, zoom: 'fit-width', maxZoom: 0.85, labels: L.viewer,
marks: { noteSide: 'end' }, // the flags in the wide outer margin
});
let card = null; // what the card over the page shows: { range } to write, { id } to read
view.on('select', ({ range }) => {
const same = card?.range && card.range.start === range?.start && card.range.end === range?.end;
if (range && range.end > range.start && !same) compose({ range });
});
view.on('annotationclick', ({ id }) => read(id));
function addNote(range, body) {
notes = [...notes, { id: nextId(), body, range }];
save();
render();
}
function render() {
notes.sort((a, b) => a.range.start - b.range.start);
view.setAnnotations(notes.map(({ id, range }, i) => ({
id, kind: 'note', range, label: String(i + 1), color: INK,
})));
renderNotebook();
}
Zutaten
- Funktionen
- AnmerkungszeichenAnker über Überarbeitungen hinwegSeitenbetrachter (postext-viewer)Textgeometrie (Bereiche und Punkte)Schriften vor dem LayoutKolumnentitel und SeitenzahlenSemantische Farbpalette
- Schrift
- Source Serif 4, Source Sans 3 (SIL OFL 1.1)
- Dateien
- Keine: Jedes Bild wird im Code gezeichnet
Zubereitung
#1 · Jede Notiz mit einem Anker speichern
const KEY = `${RECIPE}:${LANG}`;
const quote = (text) => {
const start = markdown.indexOf(text);
return { start, end: start + text.length };
};
const seed = t({
en: [['the skins of some two hundred calves', 'A Bible cost a herd of calves. Compare with a house today.'],
['used again', 'Movable type: the letters are reused, not the page.'],
['Printing also fixed the text.', 'Key idea for the essay: printing made every copy the same.']],
es: [['la piel de unos doscientos terneros', 'Una Biblia costaba un rebaño de terneros. Compararlo con una casa hoy.'],
['se volvían a usar', 'Tipos móviles: se reutilizan las letras, no la página.'],
['La imprenta también fijó el texto.', 'Idea clave para el trabajo: la imprenta hizo iguales todos los ejemplares.']],
}).map(([text, body], i) => ({ id: `n${i + 1}`, body, anchor: textAnchor(markdown, quote(text)) }));
const kept = JSON.parse(localStorage.getItem(KEY) ?? 'null') ?? seed;
let notes = kept.flatMap((n) => {
const found = resolveAnchor(markdown, n.anchor);
return found.status === 'exact' || found.status === 'moved'
? [{ ...n, range: { start: found.start, end: found.end } }] : [];
});
const nextId = () => `n${1 + Math.max(0, ...notes.map((n) => Number(n.id.slice(1)) || 0))}`;
const save = () => localStorage.setItem(KEY, JSON.stringify(
notes.map(({ id, body, range }) => ({ id, body, anchor: textAnchor(markdown, range) }))));
Die App speichert eine Notiz als ihren Text und einen Anker der Stelle (textAnchor): den Bereich, die Wörter und etwas Kontext auf beiden Seiten. Beim Öffnen findet resolveAnchor jede Stelle in der vorliegenden Auflage. Eine Korrektur des Verlags eine Seite früher verschiebt die Positionen; der Anker findet die Wörter wieder, und verloren geht nur eine Stelle, die gestrichen wurde.
#2 · Aus einer Auswahl eine Notizmarke machen
Der Code steht in der kurzen Antwort oben. Der Betrachter meldet eine abgeschlossene Auswahl als Bereich des Markdowns, und die App öffnet dafür ihre Karte. Eine gespeicherte Notiz ist eine note-Marke: Sie tönt ihre Wörter und setzt eine Fahne an den Rand, und noteSide: 'end' schickt alle Fahnen an den äußeren. Die Etiketten sind die Nummern der Notizen in Lesereihenfolge; eine Notiz früh im Kapitel lässt die späteren Nummern aufrücken, wie in einem gedruckten Buch.
#3 · Die Karte unter den Wörtern öffnen
function compose({ range, id }) {
card = { range, id };
$('card').dataset.mode = 'write';
$('quote').textContent = plain(range);
$('body').value = id ? notes.find((n) => n.id === id).body : '';
show();
$('body').focus({ preventScroll: true });
}
function read(id) {
const note = notes.find((n) => n.id === id);
card = { id, range: note.range };
$('card').dataset.mode = 'read';
$('number').textContent = `${L.note} ${notes.indexOf(note) + 1}`;
$('quote').textContent = plain(note.range);
$('text').textContent = note.body;
show();
}
function show() {
$('card').hidden = false;
place();
for (const item of $('list').children) item.setAttribute('aria-current', String(item.dataset.id === card.id));
}
function hide() {
card = null;
$('card').hidden = true;
view.setSelection(null);
for (const item of $('list').children) item.removeAttribute('aria-current');
}
// Under the last line of the words: page px turned into the window's px.
function place() {
if (!card) return;
const last = view.rangeRects(card.range).at(-1);
const at = last && view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);
if (at) Object.assign($('card').style, { left: `${at.x}px`, top: `${at.y + 10}px` });
}
$('save').addEventListener('click', () => {
const body = $('body').value.trim();
if (body && card.id) notes = notes.map((n) => (n.id === card.id ? { ...n, body } : n));
else if (body) return void (addNote(card.range, body), hide());
save();
render();
hide();
});
$('cancel').addEventListener('click', hide);
$('edit').addEventListener('click', () => compose(card));
$('remove').addEventListener('click', () => {
notes = notes.filter((n) => n.id !== card.id);
save();
render();
hide();
});
view.on('zoomchange', place);
view.element.addEventListener('scroll', place, { capture: true, passive: true });
addEventListener('keydown', (e) => e.key === 'Escape' && hide());
Eine Karte dient beiden Zwecken: Schreiben, mit den zitierten Wörtern, einem Textfeld und Speichern; Lesen, mit der Notiz und Bearbeiten oder Löschen. rangeRects liefert die letzte Zeile der Stelle in Seitenpixeln, und pageToClient rechnet sie in Fensterpixel um, sodass die Karte bei jedem Zoom unter den Wörtern sitzt und ihnen beim Scrollen folgt.
#4 · Das Heft neben den Seiten führen
function renderNotebook() {
$('count').textContent = L.count(notes.length);
$('list').replaceChildren(...notes.map(({ id, body, range }, i) => {
const item = document.createElement('button');
item.type = 'button';
item.dataset.id = id;
item.innerHTML = '<span class="n"></span><q></q><p></p><small></small>';
item.querySelector('.n').textContent = i + 1;
item.querySelector('q').textContent = plain(range);
item.querySelector('p').textContent = body;
item.querySelector('small').textContent = L.page(view.rangeRects(range)[0].pageIndex + 1);
item.addEventListener('click', () => { view.revealAnnotation(id); read(id); });
return item;
}));
}
Das Heft besteht aus denselben Einträgen in Lesereihenfolge. Ein Druck auf einen Eintrag holt mit revealAnnotation seine Wörter ins Bild und öffnet seine Karte, und der Eintrag bleibt hervorgehoben, solange die Karte offen ist.
Das ganze Rezept
// ═══ Postext Cookbook · Nº 224 · A reader's notebook ═════════════════════════════════
// https://postext.dev/en/cookbook/reader-notebook
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A history textbook in a study app. Select a passage and write a note on it: the passage
// is tinted and a numbered flag goes in the margin. A flag opens its note over the page,
// and the notebook beside the pages lists every note with the words it is about. The notes
// are kept on this device as anchors, so a corrected edition of the book keeps them.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { textAnchor, resolveAnchor } from 'https://esm.sh/postext/annotate';
import { createViewer } from 'https://esm.sh/postext-viewer';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'reader-notebook';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
ink: '#1f2328', // text
accent: '#24527a', // ink blue: chapter number, headings, folio
muted: '#68707a', // running head
};
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
// #region page: a textbook page with a wide outer margin, where the reader's flags go
const config = {
locale: t({ en: 'en-gb', es: 'es' }),
colorPalette,
page: { sizePreset: 'custom', width: mm(170), height: mm(240), dpi: 150,
margins: { top: mm(22), bottom: mm(24), left: mm(20), right: mm(48) } },
layout: { layoutType: 'single' },
bodyText: { fontFamily: 'Source Serif 4', fontSize: pt(10.5), lineHeight: pt(15),
color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
headings: { fontFamily: 'Source Sans 3', color: col('accent'), fontWeight: 700, levels: [
{ level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(0), marginBottom: pt(15) },
{ level: 2, fontSize: pt(11), lineHeight: pt(15), marginTop: pt(15), marginBottom: pt(4) },
] },
header: { elements: [
{ kind: 'text', id: 'head', content: '{title}', fontFamily: 'Source Sans 3', fontSize: pt(7.5),
fontWeight: 700, letterSpacing: pt(1.2), textTransform: 'uppercase', color: col('muted'),
<main id="pages">
<div id="viewer"></div>
<aside id="panel">
<h2 id="title"></h2>
<p id="count"></p>
<div id="list"></div>
</aside>
<section id="card" role="dialog" aria-labelledby="number" data-mode="read" hidden>
<p id="number"></p>
<blockquote id="quote"></blockquote>
<p id="text"></p>
<textarea id="body" rows="3"></textarea>
<div class="actions">
<button id="save" type="button" class="primary"></button>
<button id="cancel" type="button"></button>
<button id="edit" type="button"></button>
<button id="remove" type="button"></button>
</div>
</section>
</main>
/* A study app: the textbook's pages on a cool desk, the reader's notebook beside them.
The viewer fills its container, so the container gets a height. */
main#pages {
display: grid; grid-template-columns: minmax(0, 1fr) 340px; height: max(560px, 100vh);
justify-items: stretch; gap: 0; padding: 0; font: 15px/1.45 system-ui, sans-serif; color: #1f2328;
color-scheme: light;
}
#viewer { min-height: 0; }
#viewer .postext-viewer {
--pv-background: #e4e8ec; --pv-focus: #0f766e; --pv-selection: rgb(15 118 110 / .2);
}
#panel { overflow: auto; padding: 26px 22px; background: #f7f9fa; border-left: 1px solid #d3dae0; }
#panel h2 { margin: 0; font: 700 22px/1.2 'Source Sans 3', system-ui, sans-serif; color: #24527a; }
#count { margin: 2px 0 18px; font-size: 13px; color: #68707a; }
#list { display: grid; gap: 10px; }
#list button {
display: grid; grid-template-columns: 26px 1fr; column-gap: 10px; row-gap: 4px;
min-height: 44px; padding: 12px 14px; text-align: left; color: inherit; font: inherit;
background: #fff; border: 1px solid #dce2e7; border-radius: 10px; cursor: pointer;
box-shadow: 0 1px 2px rgb(20 40 60 / .06);
}
#list button:hover, #list button[aria-current='true'] { border-color: #0f766e; }
#list button[aria-current='true'] { box-shadow: 0 0 0 1px #0f766e; }
#list button:focus-visible { outline: 2px solid #0f766e; outline-offset: 2px; }
#list .n {
grid-row: span 3; display: grid; place-items: center; width: 24px; height: 24px;
border-radius: 4px; background: #0f766e; color: #fff; font-size: 12px; font-weight: 700;
}
#list q { font: italic 14px/1.4 'Source Serif 4', Georgia, serif; color: #4b535c; }
#list p { margin: 0; }
#list small { font-size: 12px; font-weight: 600; color: #68707a; }
/* The card floats under the words: placed in window px from pageToClient, so fixed. */
#card {
position: fixed; z-index: 2; width: 320px; margin-left: -14px; padding: 14px 16px 12px;
background: #fff; border: 1px solid #c9d2da; border-top: 3px solid #0f766e; border-radius: 10px;
box-shadow: 0 14px 34px -10px rgb(15 30 45 / .4);
}
#card::before {
content: ''; position: absolute; top: -9px; left: 22px; width: 12px; height: 12px;
background: #0f766e; transform: rotate(45deg); z-index: -1;
}
#card[hidden] { display: none; }
#number { margin: 0 0 6px; font-size: 13px; font-weight: 700; letter-spacing: .04em; color: #0f766e; text-transform: uppercase; }
#quote {
margin: 0 0 8px; padding-left: 10px; border-left: 2px solid #cfe5e2;
font: italic 14px/1.4 'Source Serif 4', Georgia, serif; color: #4b535c;
}
#text { margin: 0 0 10px; }
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
#Erst markieren, später schreiben
Viele Lesende markieren eine Stelle und kommen später darauf zurück. Ein Textmarker für Leser: eine Passage, eine Farbe hält farbige Markierungen auf denselben Ankern; eine Notiz kann als eine solche beginnen.
#Das Heft als Markdown exportieren
Die Anker halten die Wörter jeder Stelle, also schreibt sich das Heft in wenigen Zeilen als Lernzettel aus.
const sheet = notes.map(({ range, body }) => `> ${plain(range)}\n\n${body}`).join('\n\n');Nachweise
- Rezept
- Ignacio Ferro
- Text
- Eigener Text, CC BY 4.0
- Schriften
- Source Serif 4 (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
- Code
- MIT, wie Postext
Diesen Text bearbeiten ↗ (öffnet sich in einem neuen Tab)Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)



