Коротко
Несколько страниц «Алисы в Стране чудес» с примечаниями редактора на боковом поле. Каждое стоит рядом со строками, которые поясняет, и отмечено цветной буквой.
Что получится
Начало главы VII «Алисы в Стране чудес», безумное чаепитие, — три полосы комментированного издания книжного формата 156 × 234 мм. Текст Кэрролла идёт одной колонкой гарнитуры Unna с выключкой по формату, около 66 знаков в строке. В полосе шириной 33 мм у внешнего края стоят восемь глосс редактора, каждая рядом с абзацем, где напечатана её буква, то есть на правой полосе справа, на левой слева. Глоссы о словах и шутках зелёные, об истории — красные, и каждая буква в тексте окрашена в цвет своей глоссы. Главу открывает акварель с чайным столом, увиденным сверху, за ней номер, заголовок шрифтом Rozha One и вводка курсивом с зелёной буквицей; примечание об этом издании стоит на поле рядом с вводкой.
Рецепт отвечает на вопросы
- Как поставить примечания или глоссы на полях рядом с абзацем, который они поясняют?
- Как сделать сноски?
- Как сделать полосу в полторы колонки: широкая колонка текста и узкая боковая?
- Как добавить на начальную полосу строку с автором, вводку или лид с буквицей?
Короткий ответ
const layout = {
layoutType: 'oneAndHalf', // one text column and a narrower side column
sideColumnPercent: 26, // of the 127 mm between the margins: a 33 mm channel
sideColumnRole: 'floats', // no text runs in it: it holds side boxes and figures
sideColumnSide: 'outer', // at the fore-edge, which mirrored margins move page by page
gutterWidth: mm(4.5), // the text column keeps 127 − 33 − 4.5 = 89.5 mm
};
// A gloss is :::callout{type="note" span="side" title="a · …"} in the Markdown.
// span="side" moves it out of the flow into the channel, level with the block after
// the fence, so the fence goes just before the paragraph that carries its letter.
// Glosses never float. One that meets the gloss above stacks under it. One that would
// run past the column's foot slides up, as far as the gloss above allows, until its
// foot sits on the foot; if it still does not fit, it waits for the next page
// (gotcha: side-box-starts-at-fence).
const gloss = (id, hue) => ({ id,
backgroundEnabled: false, // one device: a hairline over the gloss, in its colour
stripe: { enabled: true, side: 'top', width: pt(0.5), color: col(hue) },
padding: { top: mm(1.5), right: pt(0), bottom: pt(0), left: pt(0) },
// Cormorant SC draws lower case as small capitals: the title needs no textTransform.
titleStyle: { fontFamily: LABEL, fontWeight: 600, fontSize: pt(8.5),
letterSpacing: pt(0.3), color: col(hue), gap: mm(0.8) },
// Face and colours come from bodyText. A box body also inherits its 4 mm first-line
// indent, which a gloss sets back to 0.
body: { fontSize: pt(7.8), lineHeight: pt(10), textAlign: 'left',
firstLineIndent: pt(0) } });
const calloutStyles = [gloss('note', 'lawn'), gloss('context', 'jam')]; // words, history
Ингредиенты
- Возможности
- Примечания на поляхКолонка на полях для плавающих объектовПолторы колонкиЗеркальные поляВрезкиВерхние и нижние индексыОформленные начальные полосыШапка главы на всю ширинуТекст, линейки и рамки в дизайне страницыИллюстрации в дизайне страницыПривязка элементов дизайнаБуквицы на начальных полосахАтрибуты заголовковКолонтитулы и колонцифрыКолонтитулы по роли страницыРисунки и таблицы как ресурсыСемантическая палитраОптимальное разбиение на строки (Кнут — Пласс)Плашки в строке
- Также применяет
- СноскиЦвет бумаги
- Шрифты
- Unna, Rozha One, Cormorant SC (SIL OFL 1.1)
- Материалы
tea-table-1560.jpg- The tea-table seen from above, a watercolour (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Отдайте внешний край глоссам
Код — в разделе Короткий ответ выше. В вёрстке в полторы колонки sideColumnPercent: 26 отдаёт боковой колонке 33 мм из 127 мм между полями, а тексту после средника 4,5 мм остаётся 89,5 мм. sideColumnRole: 'floats' не пускает Кэрролла в боковую колонку: в ней стоит только то, что туда поставлено через span: 'side'. Сноска ждёт внизу колонки, под линейкой; на поле каждая глосса стоит на уровне поясняемой строки и не отнимает строк у колонки текста. Два стиля глосс различаются только цветом тонкой линейки и заголовка, поэтому читатель отличает глоссу о слове от глоссы об истории ещё до чтения.
#2 · Отразите страницу, чтобы полоса глосс шла по внешнему краю
const PT = 25.4 / 72; // mm in a point
const [TRIM_W, TRIM_H] = [156, 234]; // mm
const [TOP, BOTTOM, INNER, OUTER] = [22, 22, 15, 14]; // mm: 38 lines of text
const page = { width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
backgroundColor: col('paper'),
// left is a recto's inner margin; mirror swaps the sides on a verso, and 'outer' moves
// the channel with them: right on a recto, left on a verso.
margins: { top: mm(TOP), bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER),
mirror: true } };
const CONTENT_W = TRIM_W - INNER - OUTER; // 127 mm
const SIDE_W = CONTENT_W * layout.sideColumnPercent / 100; // 33 mm: the glosses' measure
const TEXT_W = CONTENT_W - SIDE_W - layout.gutterWidth.value;
При mirror: true поля меняются местами на каждой левой полосе, а sideColumnSide: 'outer' переносит вместе с ними и боковую колонку, поэтому глоссы идут справа на странице 81 и странице 83 и слева на странице 82. Верхнее и нижнее поля по 22 мм оставляют 190 мм, то есть место для 38 строк по 14 пт, и каждая глосса начинается на строке той же сетки.
#3 · Запишите каждую глоссу перед абзацем, который она поясняет
const bodyText = { // justified and hyphenated (en-us) by default
// Copy-fitted to the 89.5 mm column: at 9.5 pt '“Have some wine,” the March Hare said in
// an encouraging tone.' fits one line. At 10.4 pt every measure from 77 to 93 mm left
// it a short last line: 'couraging tone.', 'aging tone.', 'ing tone.' or 'tone.'.
fontFamily: TEXT, fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), firstLineIndent: mm(4),
// The chapter's first paragraph is set flush, though the fences of glosses a and b stand
// between the heading and it: a box that leaves the flow is not the block after a heading.
indentAfterHeading: false,
// Unna's space is narrow, 0.22 em. At the default 0.6 the line breaker set 'Alice felt
// dreadfully puzzled. The Hatter’s remark seemed to have' with its spaces at 0.69.
minWordSpacing: 0.75,
// The dictionary divides the heroine's name, 'said Al-' | 'ice indignantly' on page 81.
// The list keeps it whole wherever it stands; every other word is divided as before.
hyphenation: { exceptions: ['Alice'] } };
Врезка с span="side" в своём блоке :::callout уходит из потока и встаёт в боковую колонку на уровне блока, идущего следом, поэтому каждая глосса записана прямо перед абзацем со своей буквой, как ниже. Глоссы a и b относятся к первому абзацу, и их блоки стоят между заголовком и этим абзацем. Врезка, ушедшая из потока, не считается блоком после заголовка, поэтому indentAfterHeading: false и здесь набирает абзац без отступа. Основной текст подогнан под колонку: при 9,5 пт абзац, который начинается с “Have some wine,”, помещается в одну строку 89,5 мм, а при 10,4 пт любая ширина от 77 до 93 мм оставляла ему короткую концевую строку вроде “ing tone.” или “tone.”. Межсловный пробел Unna узкий, 0,22 em, и при minWordSpacing по умолчанию, 0,6, в одной строке страницы 83 пробелы сжимались до 0,69 этой ширины; minWordSpacing: 0.75 такую строку исключает. На странице 81 словарь разделил имя героини на “Al-” и “ice”, поэтому этот абзац обёрнут в :::paragraphs{style="whole"}, стиль с hyphenation: false; единственный его перенос — мягкий (U+00AD), набранный внутри “together”.
:::callout{type="context" span="side" title="c · Hair"}
Tenniel drew Alice with long, loose hair. …
:::
“Your hair wants cutting,”:chip[^c^]{style="context"} said the Hatter. …#4 · Напечатайте каждую букву в цвете её глоссы
// A letter in the text is a chip named after its gloss's type, :chip[^a^]{style="note"}:
// the Markdown has no mark for coloured text, and a chip style sets a colour. With no
// fill, outline, padding or gap the chip adds no width, so the lines break as they would
// with a plain ^a^.
const letter = (id, hue) => ({ id, backgroundEnabled: false, borderWidth: pt(0),
paddingX: pt(0), gap: pt(0), color: col(hue), bold: true });
const chipStyles = [letter('note', 'lawn'), letter('context', 'jam')];
В Markdown нет разметки для цветного текста, но стиль плашки задаёт цвет текста, поэтому каждая буква — плашка, стиль которой назван так же, как тип её глоссы. :chip[^c^]{style="context"} печатает красную c, того же красного, что линейка и заголовок глоссы c. Без заливки, контура, отступа и промежутка плашка не добавляет ширины, и все строки разрываются там же, где с обычным ^c^.
#5 · Откройте главу под чайным столом
const HEADPIECE = 72; // mm: the depth of the painting at the head of the page
const HEADNOTE = { size: 9.8, lead: LEAD }; // pt: the headnote keeps the body's leading
const CAPS = { text: 0.597, initial: 0.56 }; // cap heights, em: Unna and Rozha One
// The initial's size: its capital runs from the first line's cap height down to the
// last baseline it spans. At the default size it stops short of the first line's capitals.
const dropSize = (lines) => pt(((lines - 1) * HEADNOTE.lead + CAPS.text * HEADNOTE.size)
/ CAPS.initial);
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
offset: { y: mm(y) }, size: { width } });
// The opener reserves the height of its lowest element, rounded up to the grid, and the
// heading's default bottom margin adds one blank line: with a four-line headnote the
// text starts on line 23. The kicker, the title and the headnote hang below the painting.
const opener = { enabled: true, slot: { elements: [
// An image element draws a resource without number or caption. It hangs from the
// trim's corner, over the top margin and both side margins.
{ kind: 'image', id: 'headpiece', resourceId: 'tea-table',
placement: { anchor: { to: 'page', edge: 'top-left' },
size: { width: mm(TRIM_W) } } },
// The numeral comes from the heading line,
// # A Mad Tea-Party {num="VII" headnote="…" …}: the excerpt stands alone, so
// {chapterNumber} would count its one heading and print 1.
{ kind: 'text', id: 'kicker', content: 'Chapter {attr.num}', fontFamily: LABEL,
fontWeight: 600, fontSize: pt(9), letterSpacing: pt(2), textTransform: 'uppercase',
color: col('jam'), align: 'left',
placement: { anchor: { to: 'container', edge: 'top-left' },
offset: { y: mm(HEADPIECE - TOP + 8) } } }, // 8 mm under the painting's foot
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY,
fontSize: pt(40), lineHeight: 1.05, color: col('ink'), align: 'left', // wraps when longer
placement: below('kicker', 2, 'fill') },
// The drop cap opens the headnote, the editor's voice, italic and ragged; Carroll's
// text opens in the flow, justified.
{ kind: 'text', id: 'headnote', content: '{attr.headnote}', fontFamily: TEXT,
italic: true, fontSize: pt(HEADNOTE.size),
lineHeight: pt(HEADNOTE.lead), color: col('ink'),
align: 'left',
dropCap: { lines: 2, fontFamily: DISPLAY, fontSize: dropSize(2), color: col('lawn'),
gap: mm(1.5) },
placement: below('title', 5, mm(TEXT_W)) },
// The note on this edition stands in the channel, level with the headnote's top.
{ kind: 'text', id: 'edition-label', content: 'This edition', fontFamily: LABEL,
fontWeight: 600, fontSize: pt(8.5), letterSpacing: pt(0.3), color: col('muted'),
align: 'left', placement: { anchor: { to: '#headnote', edge: 'right-of' },
offset: { x: layout.gutterWidth }, size: { width: mm(SIDE_W) } } },
{ kind: 'text', id: 'edition', content: '{attr.source}', fontFamily: TEXT,
fontSize: pt(7.5), lineHeight: pt(10), color: col('muted'), align: 'left',
placement: { anchor: { to: '#edition-label', edge: 'below' }, offset: { y: mm(0.8) },
size: { width: mm(SIDE_W) } } },
] } };
Слот оформления заголовка занимает всю страницу, чтобы картина доходила до обреза. Рубрика, заголовок и вводка подвешены под картиной, а начальная полоса резервирует место до самого нижнего из них с округлением до сетки; нижний отступ заголовка по умолчанию добавляет одну пустую строку. При вводке в четыре строки текст начинается со строки 23, пятая сдвинула бы его на строку 24. Номер, вводка и примечание об издании берутся из атрибутов заголовка, {num="VII" headnote="…" source="…"}. Номер задан там потому, что {chapterNumber} напечатал бы 1 в отрывке, который сам по себе отдельный документ. Буквица открывает вводку редактора, набранную курсивом во флаг, а текст Кэрролла начинается в потоке ниже, с выключкой по формату. dropSize() подбирает размер инициала так, чтобы его верх совпал с прописными первой строки вводки.
#6 · Красьте глоссу по тому, что она поясняет
const palette = {
ink: '#1f1b1a', // text: a warm near-black
lawn: '#1e6f6b', // glosses on words and jokes, the drop cap
jam: '#b23a48', // glosses on history, the kicker
muted: '#6e645b', // running heads, the note on this edition
paper: '#f8f3e6', // the page, and the tablecloth
};
// col(id): a colour linked to its palette entry, with the entry's hex beside the id.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const entry = (id, hex, name = id) => ({ id, name, value: { hex, model: 'hex' } });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => entry(id, hex)),
// The engine's defaults link to 'main-color': aimed at the green, nothing prints blue.
entry('main-color', palette.lawn, 'lawn (defaults)'),
];
Зелёный цвет лужайки отмечает глоссы о словах, присказках и шутках, красный цвет варенья — о людях, датах и истории текста. Новое значение jam в том же объекте palette одной правкой перекрашивает глоссы об истории, их буквы и рубрику; акварель над ними подобрана под те же зелёный и красный.
Рецепт целиком
// ═══ Postext Cookbook · Nº 032 · Annotated classic with margin glosses ════════════
// https://postext.dev/en/cookbook/annotated-classic-glosses
// Code: MIT · Text: Lewis Carroll (PD), glosses (CC BY 4.0) · Headpiece: diffusion models
// Fonts: Unna, Rozha One, Cormorant SC (SIL OFL 1.1) · Needs postext ≥ 1.28.0
// The mad tea-party as an annotated edition: the text keeps to one column, and its glosses stand
// in the outer margin beside the lines they explain, changing sides with the spread.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en')
const RECIPE = 'annotated-classic-glosses';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a lawn green and a jam red on cream paper
const palette = {
ink: '#1f1b1a', // text: a warm near-black
lawn: '#1e6f6b', // glosses on words and jokes, the drop cap
jam: '#b23a48', // glosses on history, the kicker
muted: '#6e645b', // running heads, the note on this edition
paper: '#f8f3e6', // the page, and the tablecloth
};
// col(id): a colour linked to its palette entry, with the entry's hex beside the id.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const entry = (id, hex, name = id) => ({ id, name, value: { hex, model: 'hex' } });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => entry(id, hex)),
// The engine's defaults link to 'main-color': aimed at the green, nothing prints blue.
entry('main-color', palette.lawn, 'lawn (defaults)'),
];
// #endregion
const [TEXT, DISPLAY, LABEL] = ['Unna', 'Rozha One', 'Cormorant SC'];
const LEAD = 14; // body leading in pt: the grid of every page
// #region answer: a float-only channel at the fore-edge, and two gloss styles for it
const layout = {
layoutType: 'oneAndHalf', // one text column and a narrower side column
sideColumnPercent: 26, // of the 127 mm between the margins: a 33 mm channel
sideColumnRole: 'floats', // no text runs in it: it holds side boxes and figures
sideColumnSide: 'outer', // at the fore-edge, which mirrored margins move page by page
gutterWidth: mm(4.5), // the text column keeps 127 − 33 − 4.5 = 89.5 mm
};
// A gloss is :::callout{type="note" span="side" title="a · …"} in the Markdown.
// span="side" moves it out of the flow into the channel, level with the block after
// the fence, so the fence goes just before the paragraph that carries its letter.
// Glosses never float. One that meets the gloss above stacks under it. One that would
// run past the column's foot slides up, as far as the gloss above allows, until its
// foot sits on the foot; if it still does not fit, it waits for the next page
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Оставьте глоссы справа на каждой странице
Для издания, которое читают на экране по одной странице, отключите зеркальность: тогда 'outer' означает правый край каждой страницы, а колонтитулы остаются на местах, потому что привязаны к обрезу.
- mirror: true } };
+ mirror: false } };#Отправьте длинные примечания вниз страницы
Примечание, слишком длинное для поля, запишите сноской: [^1] в тексте и определение [^1]: под абзацем. Postext ставит его внизу колонки текста, на ширину 89,5 мм под короткой линейкой, а боковая колонка остаётся глоссам. Такие сноски оформляет рецепт Сноски внизу колонки, которая на них ссылается.
Частые ошибки
Подводный камень
Врезка на полях начинается на уровне блока после неё
В postext 1.4.1 врезка span: 'side' встаёт в боковую колонку на высоте, которой текст достиг у её блока, на следующей линии сетки и ниже уже стоящих там врезок. Ставьте глоссу прямо перед абзацем, который она поясняет: поставленная после него, она начнётся рядом со следующим. Врезка, которой не хватает места до низа колонки, поднимается, пока её низ не совпадёт с низом колонки, насколько позволяет врезка над ней; если она всё равно не помещается, ждёт боковой колонки следующей страницы. Примечания на полях →
- Глоссы складываются в порядке Markdown, одна под другой, поэтому длинная сдвигает следующую вниз. На странице 81 обе буквы попадают во вторую строку первого абзаца: глосса a начинается на уровне абзаца, а глосса b под ней, на пять строк ниже своей буквы. Там, где буквы стоят близко, пишите глоссы короче.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Alice’s Adventures in Wonderland (1865), the opening of chapter VII, “A Mad Tea-Party” · Lewis Carroll · общественное достояние
- The headnote, the eight glosses and the note on this edition · Ignacio Ferro · CC BY 4.0
- Изображения
- The tea-table seen from above, a watercolour · Generated With Diffusion Models · оригинал
- Шрифты
- Unna (SIL OFL 1.1) · Rozha One (SIL OFL 1.1) · Cormorant SC (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


