Коротко
Небольшая книга: три письма короля Пруссии и Вольтера. Показывает, как набрать дату, обращение и подпись каждого письма, когда письма идут подряд, без новых страниц.
Что получится
Пять страниц книги Mon sort est changé, издания 14 × 21 см с тремя письмами на французском: два письма Фридриха II к Вольтеру, написанные через шесть и двенадцать дней после того, как он стал королём Пруссии, в июне 1740 года, и письмо Вольтера от 1 апреля 1778 года, за два месяца до его смерти. На обложке фотография двух сложенных писем и красной сургучной печати, созданная диффузионными моделями, лежит на нарисованном кодом зелёном сафьяне внутри золочёной двойной линейки. Внутри письма идут подряд без разрыва страниц. Каждая шапка печатает номер красной капителью и двух корреспондентов курсивом Fell, а под ними место и дату справа. Обращение занимает свою строку, подпись капителью заканчивает письмо у правого поля; постскриптум Фридриха идёт за его подписью на кегль мельче. Колонтитул каждой правой полосы печатает дату письма.
Рецепт отвечает на вопросы
- Как набрать эпиграф, посвящение, подпись или выноску с крупной кавычкой?
- Как добиться хорошей выключки и переносов в испанском, французском или немецком тексте?
- Как задать колонтитулы: название книги слева, название главы справа, номер страницы снаружи?
Короткий ответ
// Each letter is a level-1 heading that carries its place and date as attributes:
// # Frédéric à Voltaire {place="À Charlottembourg" date="6 juin 1740"}
// (a value holds no { or }, and one with " goes in single quotes: gotcha attr-values)
const letterHead = { enabled: true, slot: { elements: [
// {number} prints the count as numberingTemplate '{1:I}' writes it.
{ kind: 'text', id: 'number', content: 'Lettre {number}', ...sc, fontSize: pt(9),
letterSpacing: pt(1.8), color: col('seal'), placement: at('container', 'top-left') },
{ kind: 'text', id: 'title', content: '{titleText}', ...fell, fontSize: pt(15),
color: col('ink'),
placement: at('#number', 'below', 0, 1) },
// The dateline spans the measure under the title and sets its words flush right;
// inlineMarks reads the attribute's marks, so date="1^er^ avril 1778" raises its ordinal.
{ kind: 'text', id: 'dateline', content: '{attr.place}, le {attr.date}.', ...crimson,
italic: true, fontSize: pt(10.4), color: col('ink'), align: 'right', inlineMarks: true,
placement: { ...at('#title', 'below', 0, 1.5), size: { width: 'fill' } } },
] } };
// The salutation, the signature and the postscript, each a :::paragraphs{style="…"} container:
// :::paragraphs{style="signature"}
// Fédéric.
// :::
const letterParts = [
{ id: 'vedette', firstLineIndent: pt(0) }, // 'Sire,' on a line of its own, flush left
{ id: 'signature', ...sc, fontSize: pt(10.5), textAlign: 'right', marginTop: pt(LEAD / 2) },
{ id: 'postscript', fontSize: pt(9), lineHeight: pt(12.6), marginTop: pt(LEAD / 2) },
];
// Hooked up below: letterHead designs the level-1 heading, letterParts joins paragraphStyles.
Ингредиенты
- Возможности
- Атрибуты заголовковПривязка элементов дизайнаСтили абзацевОформленные начальные полосыНумерованные заголовкиГлавы с правой полосыСтили заголовковОбложки, титулы и колофоныИллюстрации в дизайне страницыРазрывы строк в заголовкахКолонтитулы и колонцифрыСтихи строка за строкойЗеркальные поляЦвет бумагиПеренос слов и язык документаВерхние и нижние индексыМетаданные документаСемантическая палитраСтраницы на холсте
- Шрифты
- Crimson Pro, IM Fell French Canon, IM Fell DW Pica SC (SIL OFL 1.1)
- Материалы
letters-1160.jpg- The cover: two folded letters and a wax seal, a photograph (Generated With Diffusion Models, оригинал)
- The cover’s green morocco and gilt fillet, drawn in code (Ignacio Ferro, CC BY 4.0)
Порядок работы
#1 · Прочитайте место и дату из заголовка
Код приведён выше, в разделе «Короткий ответ». Каждое письмо — заголовок первого уровня, атрибуты которого хранят место и дату, и шапка печатает их как {attr.place}, le {attr.date}. (атрибуты заголовков). Рамка строки с датой доходит до правого края колонки (width: 'fill'), а align: 'right' прижимает слова к этому краю; без него текст оформления выключается по центру. Обращение, подпись и постскриптум — стили абзацев, которые применяет :::paragraphs{style="…"}. Подпись набрана IM Fell DW Pica SC, семейством, где строчные нарисованы капителью. inlineMarks: true заставляет строку с датой читать разметку в своём атрибуте, поэтому date="1^er^ avril 1778" поднимает окончание числительного.
#2 · Пустите письма подряд
const letters = { level: 1, numberingTemplate: '{1:I}', advancedDesign: letterHead,
// No break: left at the level's default, each letter would open on a recto.
breakBefore: { enabled: false }, marginTop: pt(2 * LEAD),
// The hidden heading line is measured in the heading face: italic keeps it the IM Fell cut
// that FONTS loads. Upright, it would need the roman, which FONTS
// leaves out; the layout would change only for a title long enough to wrap.
italic: true };
При выключенном breakBefore письмо начинается на две линии сетки (marginTop) ниже той, где кончается предыдущее. На странице 4 постскриптум, набранный с интерлиньяжем 12,6 пт, кончается между линиями сетки, поэтому над письмом III около трёх пустых строк. На странице 2 письмо I доходит до низа страницы, а письмо II открывает страницу 3. По умолчанию первый уровень открывал бы каждое письмо на правой полосе (разрыв перед заголовком). numberingTemplate: '{1:I}' нумерует письма от I до III, а шапка печатает цифру через {number}.
#3 · Поставьте на правой полосе дату письма
const HEAD_Y = 12; // mm from the top edge
const head = (id, content, parity, placement, look = {}) => ({ kind: 'text', id, content,
parity, pages: 'body', ...sc, fontSize: pt(8.5), letterSpacing: pt(0.9), color: col('muted'),
placement, ...look });
const folio = { ...crimson, fontSize: pt(9), letterSpacing: pt(0), color: col('ink') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', at('page', 'top-left', MARGIN.outer, HEAD_Y), folio),
head('verso-names', '{author}', 'even', at('page', 'top-left', MARGIN.outer + 8, HEAD_Y)),
// {attr.date} reads the last letter that starts on or before the page.
head('recto-date', '{attr.date}', 'odd', at('page', 'top-right', -(MARGIN.outer + 8), HEAD_Y),
{ ...crimson, italic: true, fontSize: pt(9.5), letterSpacing: pt(0), inlineMarks: true }),
head('recto-folio', '{pageNumber}', 'odd', at('page', 'top-right', -MARGIN.outer, HEAD_Y),
folio),
] };
В колонтитуле {attr.date} берёт атрибут последнего заголовка первого уровня, который начался на этой странице или раньше. Страница 3 печатает 12 juin 1740, а страница 5, где письмо Вольтера продолжается со страницы 4, — 1er avril 1778 с поднятым окончанием (текстовые элементы). Колонтитулы стоят в 12 мм от верхнего края страницы, колонцифра на внешнем поле, слова на 8 мм глубже. pages: 'body' убирает их с обложки, которая считается начальной полосой, потому что её заголовок идёт на всю страницу. Дата набрана курсивом Crimson Pro, как строка, которую она повторяет, а имена на левой полосе — капителью номеров писем.
#4 · Сделайте обложку заголовком
// The Markdown: # Mon sort \\ est changé {style="cover"}. The binding fills the page, so the
// design reserves all of it and the headnote starts on page 2.
const onCover = (y) => at('page', 'top', 0, y); // centred, y mm below the top edge
const LETTERS = { x: 12, y: 72, w: 116, h: 120 }; // mm: the photograph, inside the fillet
// numbered: false keeps the cover out of the count, so the first letter is I.
const cover = { id: 'cover', numbered: false,
// span: 'page' although the book has one column. Kept in the column, the design stops at
// the column's foot (a band of paper under the leather), and page 1 counts as a 'body' page
// and prints the running heads.
span: 'page', advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'binding', resourceId: 'binding',
placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } } },
{ kind: 'image', id: 'letters', resourceId: 'letters', placement: { ...at('page', 'top-left',
LETTERS.x, LETTERS.y), size: { width: mm(LETTERS.w), height: mm(LETTERS.h) } } },
{ kind: 'text', id: 'names', content: '{author}', ...sc, fontSize: pt(9.5),
letterSpacing: pt(2), color: col('gilt'), placement: onCover(18) },
// \\ in the heading breaks the title here.
{ kind: 'text', id: 'title', content: '{titleText}', ...fell, fontSize: pt(50),
lineHeight: 1, color: col('paper'), align: 'center', overflow: 'wrap',
placement: onCover(24) },
{ kind: 'text', id: 'subtitle', content: '{subtitle}', ...crimson, italic: true,
fontSize: pt(12), color: col('paper'), placement: onCover(62) },
] } } };
Обложка — первый заголовок, в стиле заголовка cover: элемент-изображение, привязанный к вылету, несёт нарисованный переплёт, второй ставит фотографию в 72 мм от верха, а заглавие, имена и подзаголовок берутся из заголовка и метаданных. numbered: false исключает её из счёта, поэтому первое письмо Фридриха — I. Изображение переплёта заполняет страницу, а начальная полоса занимает место до своего нижнего элемента, поэтому обложка берёт всю страницу 1, и вступительная заметка начинается на странице 2 без :::pagebreak.
#5 · Переносите французский и оставьте пробелы свободными
// Justification, hyphenation, whole-paragraph line breaking and the widow, orphan and runt
// rules are defaults; locale 'fr' (in the config) picks the French patterns.
// The letters keep the transcription's unspaced ; : ? and !; a narrow no-break space
// (U+202F) typed before each would give French spacing and never end a line.
const bodyText = { fontFamily: 'Crimson Pro', fontSize: pt(10), lineHeight: pt(LEAD),
color: col('ink'), firstLineIndent: mm(5),
// No :ref here: written out with the other colours, for the default-skin check.
referenceColor: col('ink'),
// A word space never shrinks below 75 % of the font's. At the default 60 %, the tightest
// line on page 5 sets its spaces at 0.70 (each VDT line carries its justifiedSpaceRatio).
minWordSpacing: 0.75 };
locale: 'fr' переносит по французским шаблонам (ou-vrage на странице 2, représen-tation на странице 4). Выключка по формату, разбивка на строки по целому абзацу и правила висячих и коротких концевых строк включены по умолчанию. minWordSpacing: 0.75 не даёт межсловному пробелу сжаться ниже трёх четвертей пробела Crimson Pro; при 0,6 по умолчанию самая тесная строка страницы 5 поставила бы пробелы 0,70 этой ширины. При интерлиньяже 14,4 пт на странице 33 строки, а нижнее поле — то, что под ними остаётся, 20,4 мм.
#6 · Свяжите каждый цвет с палитрой
const palette = {
ink: '#2a2320', // the text: a warm near-black
paper: '#f6efe2', // the page, and the lettering on the cover
seal: '#9c2b24', // the letter numbers
leather: '#2a4536', // the cover: a green morocco binding
gilt: '#d0b67c', // its tooled border and the names on it
muted: '#75695d', // the running heads
};
// col(id): a colour linked to its palette entry, in text styles and design elements alike.
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' } })),
// The engine's default colours, the italic of the headnote among them, link to 'main-color';
// here it is the ink, not the default blue.
{ id: 'main-color', name: 'ink (defaults)', value: { hex: palette.ink, model: 'hex' } },
];
col() связывает каждый цвет с записью палитры, и связь действует и в стилях текста, и в элементах оформления: в шапках писем, в колонтитулах и на обложке. Курсив вступительной заметки и выходных сведений берёт цвет курсива по умолчанию, связанный с main-color; эта запись равна цвету текста, поэтому курсив печатается им, а не синим движка #295AA3.
Рецепт целиком
// ═══ Postext Cookbook · Nº 064 · Letters edition: datelines and signatures ════════════
// https://postext.dev/en/cookbook/letters-edition
// Code: MIT · Text: Frederick II and Voltaire, 1740 and 1778 (PD) · Cover photo: diffusion models
// Fonts: Crimson Pro, IM Fell French Canon, IM Fell DW Pica SC (SIL OFL) · Needs postext ≥ 1.25.0
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'letters-edition';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: iron-gall ink on cream paper, wax red, green morocco and gilt
const palette = {
ink: '#2a2320', // the text: a warm near-black
paper: '#f6efe2', // the page, and the lettering on the cover
seal: '#9c2b24', // the letter numbers
leather: '#2a4536', // the cover: a green morocco binding
gilt: '#d0b67c', // its tooled border and the names on it
muted: '#75695d', // the running heads
};
// col(id): a colour linked to its palette entry, in text styles and design elements alike.
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' } })),
// The engine's default colours, the italic of the headnote among them, link to 'main-color';
// here it is the ink, not the default blue.
{ id: 'main-color', name: 'ink (defaults)', value: { hex: palette.ink, model: 'hex' } },
];
// #endregion
const TRIM = { width: 140, height: 210 }; // the French 14 × 21 format
const LEAD = 14.4; // pt: the body's leading, the grid every letter starts on
const LINES = 33; // lines of text on a full page
const TOP = 22; // mm: the top margin
const MARGIN = { top: TOP, inner: 17.5, outer: 14.5, // mm, mirrored
bottom: TRIM.height - TOP - (LINES * LEAD * 25.4) / 72 }; // ends the page on line 33
const sc = { fontFamily: 'IM Fell DW Pica SC' }; // its lower case is cut as small capitals
const fell = { fontFamily: 'IM Fell French Canon', italic: true }; // the display italic
const crimson = { fontFamily: 'Crimson Pro' }; // the text face
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
// #region answer: a letter head read from the heading, and styles for the letter's parts
// Each letter is a level-1 heading that carries its place and date as attributes:
// # Frédéric à Voltaire {place="À Charlottembourg" date="6 juin 1740"}
// (a value holds no { or }, and one with " goes in single quotes: gotcha attr-values)
const letterHead = { enabled: true, slot: { elements: [
// {number} prints the count as numberingTemplate '{1:I}' writes it.
{ kind: 'text', id: 'number', content: 'Lettre {number}', ...sc, fontSize: pt(9),
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Назвать место в колонтитуле
Те же атрибуты дают правой полосе всю строку, À Charlottembourg, le 12 juin 1740.
- head('recto-date', '{attr.date}', 'odd', at('page', 'top-right', -(MARGIN.outer + 8), HEAD_Y),
+ head('recto-date', '{attr.place}, le {attr.date}', 'odd',
+ at('page', 'top-right', -(MARGIN.outer + 8), HEAD_Y),Частые ошибки
Подводный камень
Значения атрибутов: без { и }; значение с " — в одинарных кавычках
Значение атрибута заканчивается на закрывающей фигурной скобке, поэтому { и } внутри него невозможны. Значение с двойной кавычкой берётся в одинарные; знак доллара допустим. Атрибуты заголовков →
- Правая полоса берёт дату последнего письма, которое начинается на этой странице или раньше. Страница, где одно письмо кончается и начинается другое, несёт дату нового, как колонтитул словаря называет последнюю статью на странице.
- Заголовок без атрибута печатает пустую строку без предупреждения: у письма без
place="…"строка с датой начинается с запятой. Проверьте заголовок каждого письма. - В письмах сохранены знаки ; : ? и ! без пробелов, как в транскрипции. По французскому обычаю перед ними ставят узкий неразрывный пробел (U+202F); набранный там, он удерживает знак на строке своего слова.
- У Crimson Pro нет модификаторов ᵉ (U+1D49) и ʳ (U+02B3), поэтому 1ᵉʳ, записанный в Unicode, напечатался бы запасным шрифтом. Пишите
1^er^: вступительная заметка, это основной текст, ставит его верхним индексом, и так же делают строка с датой и колонтитул правой полосы, у текстовых элементов которых стоитinlineMarks: true.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Frederick II’s letters to Voltaire of 6 and 12 June 1740 and Voltaire’s letter to him of 1 April 1778, in Correspondance de Voltaire avec le roi de Prusse (Paris, Librairie de la Bibliothèque nationale, 1889), one misprint corrected (ouvragés), the salutations and signatures set apart · Frédéric II · Voltaire · общественное достояние
- The headnote and the colophon · Ignacio Ferro · CC BY 4.0
- Изображения
- The cover: two folded letters and a wax seal, a photograph · Generated With Diffusion Models · оригинал
- The cover’s green morocco and gilt fillet, drawn in code · Ignacio Ferro · CC BY 4.0
- Шрифты
- Crimson Pro (SIL OFL 1.1) · IM Fell French Canon (SIL OFL 1.1) · IM Fell DW Pica SC (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


