Перейти к основному содержанию
Рецепт номер 30

Рецепты · Глава 5 · Структура книги

Антология с именами авторов

Три эссе о прогулках с автором, годом и журналом в заголовке: начальная полоса печатает всё, левый колонтитул и содержание — автора.

с. 2–3 из 9

  • Образец на английском: русского издания пока нет
  • Обрезной формат 135 × 180 мм
  • 1 колонка
  • Spectral 10/14
  • Gloock
  • Hanken Grotesk
  • 9 страниц
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 64 мс
  • Строк кода: 175

Коротко

Книжка из трёх эссе о прогулках. Автор и год каждого эссе набраны один раз и появляются всюду, где нужны книге, например в содержании.

Что получится

Девять страниц Afoot, карманной антологии из трёх эссе о прогулках: Хэзлитт (1822), Торо (1862) и Стивенсон (1876). Обложку занимает картина с вересковой пустошью в сумерках, JPEG, созданный диффузионными моделями. В содержании у каждого эссе номер цвета ржавчины, заглавие шрифтом Gloock, разреженное отточие до страницы и имя автора вересковым курсивом ниже. Каждое эссе открывают номер и заглавие, имя автора прописными вразрядку и строка с журналом и годом первой публикации. На левых полосах в колонтитуле автор, на правых заглавие эссе. Автор, год и источник записаны атрибутами в заголовке эссе, и начальная полоса, колонтитулы и содержание берут их оттуда, поэтому четвёртое эссе не потребует правок в конфигурации.

Рецепт отвечает на вопросы

  • Как добавить содержание, которое обновляется само (отточие, номера страниц, авторы, строки частей)?
  • Как добавить на начальную полосу строку с автором, вводку или лид с буквицей?
  • Как задать колонтитулы: название книги слева, название главы справа, номер страницы снаружи?

Короткий ответ

script.js · строки 44–64в полном коде
// Each essay's heading carries its credits, and every {attr.…} below reads them:
//   # Walking {author="Henry David Thoreau" year="1862" source="The Atlantic Monthly"}
// (a value cannot hold { or }, and one with " goes in single quotes; gotcha: attr-values)
// 1 · The opener: inside a heading's design, {attr.author} is that heading's attribute.
const byline = [
  text('byline', '{attr.author}', { ...label, fontSize: pt(8), letterSpacing: pt(1.6),
    color: col('heather') }, below('title', 5)),
  text('dateline', '{attr.source}, {attr.year}', { fontFamily: 'Spectral', italic: true,
    fontSize: pt(9.5), color: col('muted'), align: 'left' }, below('byline', 1.2)),
];
// 2 · The verso running head (head() is in the running-heads region): in the page header,
//     {attr.author} is the attribute of the essay the page belongs to.
const versoAuthor = head('verso-author', '{attr.author}', 'even',
  at('page', 'top-left', MARGIN.outer + HEAD.gap, HEAD.y));
// 3 · The contents: toc.subtitle prints the attribute it names as a line under each title.
//     'author' and italic are the defaults; attr is written out so it can become 'source'.
const authorLine = { enabled: true, attr: 'author', fontFamily: 'Spectral', fontSize: pt(10),
  color: col('heather') };
// Hooked up below: byline → the opener, versoAuthor → header, authorLine → toc.subtitle.
// A heading without author="…" gets an empty byline and running head and no line in the
// contents, and the build gives no warning: check every heading.

Ингредиенты

Возможности
СодержаниеАтрибуты заголовковКолонтитулы и колонцифрыОформленные начальные полосыНумерованные заголовкиСтили заголовковГлавы без номераОбложки, титулы и колофоныИллюстрации в дизайне страницыПривязка элементов дизайнаСтихи строка за строкойЗеркальные поляСтили абзацевЗакреплённые врезки и бейджиВрезкиЯвный вертикальный отступМетаданные документаСемантическая палитраРисунки и таблицы как ресурсыСтраницы на холсте
Шрифты
Spectral, Gloock, Hanken Grotesk (SIL OFL 1.1)
Материалы
  • cover-1200.jpg
  • The cover: a heath and hills at dusk, a painting (Generated With Diffusion Models, оригинал)

Порядок работы

#1 · Пронумеруйте эссе и опустите их текст

script.js · строки 68–85в полном коде
const opener = { enabled: true,
  // The hairline ends 7 mm above the foot of this reserve, so the text starts on the same grid
  // line under every opener whose title fits on one line (SINK = 14 holds a two-line title).
  minHeight: pt(SINK * LEAD),
  slot: { elements: [
    // {number} prints the essay's number as numberingTemplate '{1:I}' writes it: I, II, III.
    text('number', '{number}', { ...gloock, fontSize: pt(34), lineHeight: 1, color: col('rust') },
      at('container', 'top-left', 0, 8)),
    text('title', '{titleText}', { ...gloock, fontSize: pt(26), lineHeight: 1.08,
      color: col('ink') }, below('number', 3, { width: 'fill' })),
    ...byline,
    { kind: 'rule', id: 'rule', thickness: pt(0.5), color: col('rule'),
      placement: below('dateline', 6) }, // a horizontal rule runs to the column's edge
  ] } };
const essays = { level: 1, numberingTemplate: '{1:I}', advancedDesign: opener,
  marginBottom: pt(0), // the heading's default margin would add to minHeight
  // The cover and contents styles inherit this break (gotcha: style-inherits-break).
  breakBefore: { enabled: true, parity: 'any' } }; // 'any': each piece opens on the next page

numberingTemplate: '{1:I}' уровня нумерует эссе I, II и III, а {number} печатает номер над заглавием (охват и расширенное оформление). minHeight резервирует 12 строк по 14 пт, и волосная линейка кончается на 7 мм выше, поэтому под заглавием в одну строку текст начинается в 79 мм от верхнего края на каждой начальной полосе. Вторая строка заглавия в 26 пт добавляет 9,9 мм и сдвигает текст на строку сетки; с SINK = 14 текст под заглавиями в одну и две строки начинается на одной строке. marginBottom: pt(0) не даёт отступу заголовка по умолчанию прибавиться к резерву.

#2 · Пусть содержание заполняется само

script.js · строки 89–99в полном коде
const ENTRY = 15; // pt: the essay titles in the contents
const contents = { // passed to the config as `toc`
  // An entry's numeral takes the title's face and size and stands on its baseline.
  levels: [{ level: 1, fontFamily: 'Gloock', fontSize: pt(ENTRY), color: col('ink'),
    numberFontWeight: 400, // Gloock has one weight
    numberColor: col('rust'), numberWidth: mm(8), numberGap: mm(3), marginBottom: pt(LEAD) }],
  pageNumber: { fontFamily: 'Hanken Grotesk', fontSize: pt(8.5), fontWeight: 600,
    color: col('muted'), width: mm(6) }, // the leader dots take this face and colour too
  leader: { char: '. ', gap: mm(2) }, // spaced dots, right-aligned so they line up
  subtitle: authorLine,
};

:::toc в Markdown печатает по строке на каждый учтённый заголовок: номер, заглавие, отточие, метку страницы и, через subtitle, автора. buildDocument верстает книгу заново, пока метки страниц не перестанут меняться, поэтому переименованное или удлинённое эссе обновляет содержание (содержание). Номер строки содержания берёт гарнитуру и кегль заглавия, если numberFontFamily или numberFontSize не говорят иного, и при любом кегле стоит на базовой линии первой строки заглавия. Книга с частями получает ещё по строке на каждую :::part, нарисованной toc.parts.design, как в рецепте «Части в цвете».

#3 · Автор слева, эссе справа

script.js · строки 103–119в полном коде
// Each head: the label face, the pages of its parity, never an opener (pages: 'body'), where
// the byline names the author. A function declaration, so the answer above can call it.
function head(id, content, parity, placement, look = {}) {
  return { ...text(id, content, { ...label, fontSize: pt(7.5), letterSpacing: pt(1.3),
    color: col('muted'), ...look }, placement), parity, pages: 'body' };
}
const folio = { color: col('ink') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', at('page', 'top-left', MARGIN.outer, HEAD.y), folio),
  versoAuthor,
  head('recto-title', '{chapterTitle}', 'odd',
    at('page', 'top-right', -(MARGIN.outer + HEAD.gap), HEAD.y), { align: 'right' }),
  head('recto-folio', '{pageNumber}', 'odd', at('page', 'top-right', -MARGIN.outer, HEAD.y),
    { ...folio, align: 'right' }),
] };
const footer = { elements: [{ ...head('drop-folio', '{pageNumber}', 'all', // an opener's folio
  at('container', 'top', 0, 9), { ...folio, align: 'center' }), pages: 'opener' }] };

Каждый колонтитул привязан к странице, в 11 мм от верхнего края, а parity выбирает сторону: колонцифра стоит по наружному краю текста, имя или заглавие — на 7 мм глубже. pages: 'body' в head() не пускает колонтитулы на начальные полосы, где автор уже назван, а pages: 'opener' нижнего колонтитула печатает там колонцифру внизу (текстовые элементы). {chapterTitle} печатает заглавие эссе без номера.

#4 · Не считайте обложку и содержание

script.js · строки 123–146в полном коде
// Unnumbered, so the first essay is I; unlisted; and with no running heads or folio. They
// inherit the level's page break, 'any' (gotcha: style-inherits-break).
const bare = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
const cover = { enabled: true, slot: { elements: [
  { kind: 'image', id: 'art', resourceId: 'cover',
    placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } } },
  text('title', '{titleText}', { ...gloock, fontSize: pt(80), lineHeight: 1, color: col('ink') },
    at('page', 'top-left', MARGIN.inner, 22)), // page 1 is a recto: the inner margin is left
  text('subtitle', '{subtitle}', { fontFamily: 'Spectral', italic: true, fontSize: pt(14),
    color: col('ink'), align: 'left' }, below('title', 1)),
  text('authors', '{attr.authors}', { ...label, fontSize: pt(8.5), letterSpacing: pt(2),
    color: col('heather') }, below('subtitle', 5)),
  text('imprint', '{attr.imprint}', { ...label, fontSize: pt(7.5), letterSpacing: pt(1.8),
    color: col('paper') }, at('page', 'bottom-left', MARGIN.inner, -12)),
] } };
// span: 'page' in a one-column book: a design kept in its column is cut at the column's foot,
// which would leave a band of paper under the dusk.
const coverStyle = { id: 'cover', ...bare, span: 'page', advancedDesign: cover };
const contentsOpener = { enabled: true, slot: { elements: [ // {title}, {subtitle}: frontmatter
  text('kicker', '{title} · {subtitle}', { ...label, fontSize: pt(8), letterSpacing: pt(1.6),
    color: col('heather') }, at('container', 'top-left', 0, 8)),
  text('title', '{titleText}', { ...gloock, fontSize: pt(26), color: col('ink') },
    below('kicker', 2.5)),
] } };

С numbered: false обложка и содержание не сдвигают счётчик, и Хэзлитт остаётся I, а toc: false не пускает их в список (стили заголовков). Оба стиля наследуют breakBefore уровня с чётностью 'any', поэтому содержание следует за обложкой на странице 2 без :::pagebreak. Стиль обложки охватывает страницу в одноколонной книге, потому что оформление, оставленное в колонке, обрезается по её низу, и под пейзажем осталось бы 22 мм бумаги.

#5 · Пишите каждый цвет со ссылкой на палитру

script.js · строки 14–28в полном коде
const palette = {
  ink: '#241f26', // text: a plum-tinted near-black
  paper: '#f7f2e8', // the page
  heather: '#6b4468', // the bylines and the authors in the contents
  rust: '#a4502a', // the essay numbers
  rule: '#d5cabd', // hairlines
  muted: '#6d6570', // running heads, datelines, page numbers in the contents
};
// col() links a colour to its palette entry; the hex is the value the entry holds.
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 defaults link to 'main-color': point it at the ink, so nothing prints blue.
  { id: 'main-color', name: 'ink (defaults)', value: { hex: palette.ink, model: 'hex' } },
];

col() пишет hex каждого цвета рядом с его paletteId, и движок идёт по этой ссылке: имена авторов, колонтитулы и обложка берут то, что colorPalette держит под этим id, поэтому вторая палитра с теми же id перекрашивает всю книгу. main-color, направленный на цвет текста, покрывает все значения по умолчанию, не переписанные в конфигурации: иначе они напечатались бы синим движка, #295AA3.

Рецепт целиком

Sandbox
// ═══ Postext Cookbook · Nº 030 · Anthology with bylines ═══════════════════════════════
// https://postext.dev/en/cookbook/anthology-with-bylines
// Code: MIT · Text: Hazlitt, Thoreau, Stevenson (public domain) · Cover: diffusion models
// Fonts: Spectral, Gloock, Hanken Grotesk (SIL OFL 1.1) · 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 = 'anthology-with-bylines';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: heather for the credits, rust for the numbers, plum ink on warm paper
const palette = {
  ink: '#241f26', // text: a plum-tinted near-black
  paper: '#f7f2e8', // the page
  heather: '#6b4468', // the bylines and the authors in the contents
  rust: '#a4502a', // the essay numbers
  rule: '#d5cabd', // hairlines
  muted: '#6d6570', // running heads, datelines, page numbers in the contents
};
// col() links a colour to its palette entry; the hex is the value the entry holds.
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 defaults link to 'main-color': point it at the ink, so nothing prints blue.
  { id: 'main-color', name: 'ink (defaults)', value: { hex: palette.ink, model: 'hex' } },
];
// #endregion
const TRIM = { width: 135, height: 180 }; // a pocket book, 3 : 4
const MARGIN = { top: 20, bottom: 22, inner: 19, outer: 15 }; // mirrored
const LEAD = 14; // body leading in pt: the baseline grid
const SINK = 12; // grid lines an essay opener reserves above its first line of text
const HEAD = { y: 11, gap: 7 }; // running heads: mm from the top edge, folio to words
const label = { fontFamily: 'Hanken Grotesk', fontWeight: 600, textTransform: 'uppercase',
  align: 'left' }; // design text is centred by default
// One weight, no italic; 'wrap' breaks a long title onto a second line.
const gloock = { fontFamily: 'Gloock', overflow: 'wrap', align: 'left' };
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const below = (id, y, size) => ({ ...at(`#${id}`, 'below', 0, y), ...(size && { size }) });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, ...look, placement });

// #region answer: one set of heading attributes, read in three places
// Each essay's heading carries its credits, and every {attr.…} below reads them:
//   # Walking {author="Henry David Thoreau" year="1862" source="The Atlantic Monthly"}
// (a value cannot hold { or }, and one with " goes in single quotes; gotcha: attr-values)
// 1 · The opener: inside a heading's design, {attr.author} is that heading's attribute.
const byline = [

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Укажите, где каждое эссе вышло впервые

toc.subtitle печатает любой атрибут заголовка, и тот же Markdown может показать под заглавием каждого эссе его первый журнал.

-const authorLine = { enabled: true, attr: 'author', fontFamily: 'Spectral', fontSize: pt(10),
+const authorLine = { enabled: true, attr: 'source', fontFamily: 'Spectral', fontSize: pt(10),

#Поставьте на левую полосу заглавие книги

Многие книги ставят слева своё заглавие, а справа — заглавие главы; {title} берёт его из метаданных Markdown и печатает AFOOT.

-const versoAuthor = head('verso-author', '{attr.author}', 'even',
+const versoAuthor = head('verso-author', '{title}', 'even',

#Начинайте каждое эссе с правой полосы

С чётностью 'odd' Стивенсон переходит на страницу 9, за пустую страницу 8. Двум стилям вводной части тогда нужна собственная 'any', иначе содержание унаследует 'odd' и откроется на странице 3, за пустой левой.

-  breakBefore: { enabled: true, parity: 'any' } }; // 'any': each piece opens on the next page
+  breakBefore: { enabled: true, parity: 'odd' } };
-const bare = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
+const bare = { numbered: false, toc: false, breakBefore: { enabled: true, parity: 'any' },
+  header: { elements: [] }, footer: { elements: [] } };

Частые ошибки

Подводный камень

Значения атрибутов: без { и }; значение с " — в одинарных кавычках

Значение атрибута заканчивается на закрывающей фигурной скобке, поэтому { и } внутри него невозможны. Значение с двойной кавычкой берётся в одинарные; знак доллара допустим. Атрибуты заголовков →

Подводный камень

Стиль заголовка наследует разрыв страницы своего уровня

Запись headingStyles берёт каждое пропущенное поле у своего уровня заголовка, в том числе breakBefore. Страница содержания или выходных данных со стилем на H1 после :::pagebreak наследует parity 'odd' и оказывается после пустой страницы. Дайте такому стилю breakBefore: { enabled: false }. Стили заголовков →

  • Хэзлитт цитирует стихи посреди фразы. Стихотворные строки помещены в блок :::verse{style="verse" align=start}, строка Markdown на строку стиха с отступом 8 мм, а продолжение фразы после них — в стиль runon без абзацного отступа. Цитата Markdown не подошла бы: её строки соединяются, как в абзаце, и стихи слились бы в прозу.
  • Атрибут, которого у заголовка нет, ничего не печатает и предупреждения не вызывает. Без author="…" имя автора и левый колонтитул эссе выходят пустыми, а строка под заглавием пропадает из содержания.

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Изображения
  • The cover: a heath and hills at dusk, a painting · Generated With Diffusion Models · оригинал
Шрифты
Spectral (SIL OFL 1.1) · Gloock (SIL OFL 1.1) · Hanken Grotesk (SIL OFL 1.1)
Sandbox