Коротко
Карманный определитель птиц эстуария в двух частях: одна цвета бурого ила, другая цвета зелёного тростника. Показано, как одна настройка цвета на часть красит её первую страницу, ярлыки, колонцифры и строку содержания.
Что получится
Birds of the Estuary — карманный определитель в двух частях, по одной на место обитания. Илистые отмели печатаются бурым цветом ила, тростники — зелёным, и каждый цвет записан один раз, в :::part, который открывает место обитания. Каждый шмуцтитул — поле под обрез с римской цифрой 150 пт и кремовым перечнем видов. Оборот листа закрашен тем же цветом, с ярлыком части вывороткой у внешнего края. На страницах видов цвет части принимают ярлык, колонцифра, надзаголовок, линейка под латинским названием, полужирные признаки, маркеры списков и метка иллюстрации. Содержание открывается под полосой с видом эстуария и даёт каждой части цветную полосу с номером страницы её шмуцтитула. Обложка, полоса и четыре иллюстрации — картины, созданные диффузионными моделями и загруженные как JPEG; палитра части до изображений не доходит, поэтому цвета у них свои.
Рецепт отвечает на вопросы
- Как разделить книгу на части или разделы со своим цветом и шмуцтитулом?
- Как убрать колонтитулы с начальных и пустых полос или закрасить пустой оборот цветом части?
- Как добавить содержание, которое обновляется само (отточие, номера страниц, авторы, строки частей)?
- Как выделить цветом ключевые термины (полужирным или курсивом) в тексте или во врезках?
Короткий ответ
// In the Markdown: :::part{number="I" title="The \\ Mudflats" palette="band=#8c5e24"}
// Every colour below that is linked to 'band' takes #8c5e24 until the next part.
const parts = { // passed to the config as `parts`
// A divider opens on a recto by default. The break after it goes to the next recto too, so
// the back of the leaf stays blank and versoDesign paints it (gotcha: verso-design-breakafter).
breakAfter: { parity: 'odd' },
margins: { top: mm(125) }, // the fence's text starts low, under the title
design: { elements: [ // the divider: its container is the whole trim
box('field', col('band'), { ...at('top-left', 0, 0, 'bleed'), ...fill }),
text('part', t({ en: 'Part', es: 'Parte' }), { ...label, fontSize: pt(10),
letterSpacing: pt(2.4), color: col('paper') },
at('top-left', MARGIN.inner, MARGIN.top)), // a recto: the inner margin is on the left
// Roman for the parts, Arabic for the species. {numberRoman} re-formats number="I" (or
// "1"); the species design prints {number}, from numberingTemplate '{1}'.
text('numeral', '{numberRoman}', { ...display, fontSize: pt(150), lineHeight: 0.9,
color: col('paper') }, below('part', 0)),
// The \\ in the title breaks the line here; the contents and the heads get one line.
text('title', '{titleText}', { ...display, fontSize: pt(46), lineHeight: 0.98,
color: col('paper') }, below('numeral', 2, { width: mm(MEASURE) })),
rule('rule', col('paper'), 1, below('title', 7, { width: mm(14) })),
] },
// The back of the leaf: the same band, edge to edge, the part's tab in reverse at the
// fore-edge (a verso's is on the left) and its name at the foot.
versoDesign: { elements: [
box('field', col('band'), { ...at('top-left', 0, 0, 'bleed'), ...fill }),
text('tab', '{partNumber}', { ...label, fontSize: pt(9), color: col('band'), align: 'center',
box: { backgroundColor: col('paper') } }, { ...at('top-left', 0, TAB.y), size: TAB.size }),
text('name', '{partTitle}', { ...label, fontSize: pt(9), letterSpacing: pt(2.4),
color: col('paper') }, at('bottom-left', MARGIN.outer, -MARGIN.bottom)),
] },
// The fence's list of species, in the paper colour on the band.
bodyStyle: { fontSize: pt(11), color: col('paper'), textAlign: 'left', numberColor: col('paper'),
orderedLists: { fontFamily: 'Barlow Condensed', separator: '', gap: mm(4) } },
};
Ингредиенты
- Возможности
- Цвета частейШмуцтитулы частейСодержаниеСемантическая палитраПолужирный, курсив и их цветаЦветные поля навылет и метки на обрезеКолонтитулы по роли страницыКолонтитулы и колонцифрыОформленные начальные полосыАтрибуты заголовковНумерованные заголовкиСтили заголовковГлавы без номераРазрывы строк в заголовкахОбложки, титулы и колофоныИллюстрации в дизайне страницыСобственные типы ресурсовРисунки точно здесьЗакреплённые врезки и бейджиРазрывы страниц и колонок
- Также применяет
- ВрезкиЦвет бумагиСтили абзацевРисунки и таблицы как ресурсы
- Шрифты
- Alegreya, Zilla Slab, Barlow Condensed (SIL OFL 1.1)
- Материалы
cover-1152.jpgcurlew-1200.jpgredshank-1200.jpgreedling-1200.jpgstrip-1536.jpgwarbler-1200.jpg- The cover: a curlew on the estuary mud, reeds in front (Generated With Diffusion Models, оригинал)
- The contents strip: a curlew and a redshank on the mud, the reedbed beyond (Generated With Diffusion Models, оригинал)
- Plate 1: Eurasian curlew (Generated With Diffusion Models, оригинал)
- Plate 2: common redshank (Generated With Diffusion Models, оригинал)
- Plate 3: bearded reedling (Generated With Diffusion Models, оригинал)
- Plate 4: common reed warbler (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Один цвет палитры, который переопределяют части
const palette = {
ink: '#1f2624', // text: a green-tinted near-black
band: '#3c4b4f', // the house slate, before any part; each :::part brings its own
paper: '#f6f3ea', // the page, and the type set on a band
rule: '#d5d1c4', // hairlines
muted: '#61675f', // running heads, Latin names, the colophon
};
// The paletteId is the link a part's palette="band=#…" follows, in text and designs 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 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' } },
];
Часть переопределяет цвета палитры по id, поэтому всё, что должно меняться вместе с местом обитания, связано с одной записью, band. Её собственное значение, сланцевое, печатается только вне частей (надзаголовок обложки и название примечания под содержанием), и ни у какого другого цвета в конфигурации нет того же кода. col() даёт каждому цвету его paletteId, и за этим id следует переопределение части — и в стилях текста, и в элементах оформления.
#2 · Шмуцтитул, его оборот и перечень
Код для этого шага — в коротком ответе выше. :::part открывает шмуцтитул на правой полосе, а parts.design размещает его по всему обрезному формату. Markdown между ограждениями начинается в 125 мм от верхнего края, под названием: несколько строк о месте обитания стилем абзаца habitat, затем перечень видов в bodyStyle. versoDesign закрашивает оборот листа (поле и ярлык вывороткой), только если эта страница пуста, а breakAfter: { parity: 'odd' } оставляет её пустой, отправляя первый вид на следующую правую. {numberRoman} печатает number="I" части римской цифрой ("1" дал бы ту же I), а виды пронумерованы арабскими от 1 до 4. \\ в названии разрывает строку только на шмуцтитуле; содержание и колонтитулы ставят название в одну строку.
#3 · Акценты текста следуют за частью
const bodyText = {
fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('band'), // the field marks: **Bill**, **Voice.**
italicColor: col('ink'), referenceColor: col('ink'),
firstLineIndent: mm(4), indentAfterHeading: false,
// Tighter than the 0.6–2 defaults. runtMinCharacters counts word spaces, not letters:
// 45 are about 20 letters of Alegreya (the default 20, about 9); a shorter last line is a runt.
minWordSpacing: 0.75, maxWordSpacing: 1.7, runtMinCharacters: 45,
};
const unorderedLists = { bulletChar: '•', color: col('band'), // the field marks' bullets
marginTop: pt(0), marginBottom: pt(0) };
// The plates are numbered with the species, and their label is in the part's colour.
const resourceTypes = [{ id: 'plate', numberingTemplate: '{n}', resetOn: 'never',
counterFormat: 'decimal', ...t({
en: { name: 'Plate', namePlural: 'Plates', shortLabel: 'Pl.', captionPrefix: 'Plate' },
es: { name: 'Lámina', namePlural: 'Láminas', shortLabel: 'Lám.', captionPrefix: 'Lámina' },
}) }];
const captionStyle = { fontSize: pt(8.5), labelColor: col('band'), descriptionItalic: true,
gap: mm(1.8) };
От одного :::part до следующего каждый цвет текста, равный собственному значению band, принимает значение части (контейнер :::part). Здесь это полужирные признаки, маркеры и метки иллюстраций. Основной текст и курсив остаются чёрными. Иллюстрации — отдельный тип ресурса с меткой Plate и без сброса счётчика, поэтому они идут от 1 до 4 в ногу с видами.
#4 · Начало статьи о виде
const species = { enabled: true, slot: { elements: [
text('kicker', '{number} · {attr.status}', { ...label, fontSize: pt(8.5),
letterSpacing: pt(1.7), color: col('band') }, at('top-left', 0, 1, 'container')),
// 'cm' is a unit symbol: it keeps its lower case, so the size is not set in capitals.
text('size', '{attr.size}', { ...label, textTransform: 'none', fontSize: pt(8.5),
letterSpacing: pt(0.5), color: col('muted') }, at('top-right', 0, 1, 'container')),
text('name', '{titleText}', { ...display, fontSize: pt(22), lineHeight: 1.05,
color: col('ink') }, below('kicker', 1.5, { width: 'fill' })),
text('latin', '{attr.latin}', { fontFamily: 'Alegreya', italic: true, fontSize: pt(11.5),
color: col('ink') }, below('name', 0.8)),
rule('rule', col('band'), 0.75, below('latin', 2, { width: mm(MEASURE) })),
] } };
Оформление начала печатает три атрибута заголовка: status в надзаголовке после номера, size справа от надзаголовка и latin под названием. Надзаголовок и линейка под латинским названием связаны с band, поэтому одного оформления хватает обоим местам обитания. Сам заголовок не задаёт разрыва страницы: каждый вид начинается после :::pagebreak или после разрыва за частью, поэтому его страница считается страницей основного текста и несёт колонтитулы. Размер набран без прописных, как у метки, потому что cm — символ единицы.
#5 · Полоса для каждой части в содержании
const contents = {
levels: [{ level: 1, fontFamily: 'Zilla Slab', fontSize: pt(12), fontWeight: 600,
numberFontFamily: 'Barlow Condensed', numberFontWeight: 600, numberColor: col('muted'),
numberWidth: mm(5), numberGap: mm(3), marginTop: pt(4) }],
pageNumber: { fontFamily: 'Barlow Condensed', fontSize: pt(10), fontWeight: 600, width: mm(7) },
leader: { char: '. ' },
subtitle: { enabled: true, attr: 'latin', fontFamily: 'Alegreya', fontSize: pt(9.5),
color: col('muted') }, // the Latin name, in italic by default
// A part row lays out this design with the part's number, title, page and palette.
parts: { height: mm(8.5), marginTop: pt(LEAD), design: { elements: [
box('row', col('band'), { ...at('top-left', 0, 0, 'container'), ...fill }),
text('part', t({ en: 'Part {number}', es: 'Parte {number}' }), { ...label, fontSize: pt(8),
letterSpacing: pt(1.6), color: col('paper') }, at('left', 3, 0, 'container')),
text('title', '{titleText}', { ...display, fontSize: pt(12), color: col('paper') },
at('left', 20, 0, 'container')),
text('page', '{pageNumber}', { ...label, fontSize: pt(10), color: col('paper'),
align: 'right' }, at('right', -2.5, 0, 'container')),
] } },
};
:::toc даёт строку каждому :::part и размещает в ней toc.parts.design с номером, названием, страницей шмуцтитула и палитрой этой части (содержание), поэтому один и тот же прямоугольник печатается бурым для отмелей и зелёным для тростников. Каждая строка вида под полосой показывает его номер, отточие и страницу, а на строке ниже — латинское название из атрибута latin.
#6 · Часть в колонтитулах и на ярлыке
const head = (id, content, parity, placement, style = {}) => ({ ...text(id, content, { ...label,
fontSize: pt(8), letterSpacing: pt(1.4), color: col('muted'), overflow: 'clip', ...style },
placement), parity, pages: 'body' }); // dividers are 'part' pages, their versos 'blank'
const folio = { fontSize: pt(9), fontWeight: 700, color: col('band') };
const tab = (parity, edge) => head(`tab-${parity}`, '{partNumber}', parity,
{ ...at(edge, 0, TAB.y), size: TAB.size },
{ fontSize: pt(9), color: col('paper'), align: 'center', box: { backgroundColor: col('band') } });
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', at('top-left', MARGIN.outer, HEAD.y), folio),
head('verso-title', '{title}', 'even', at('top-left', MARGIN.outer + HEAD.gap, HEAD.y)),
head('recto-title', '{partTitle}', 'odd', at('top-right', -(MARGIN.outer + HEAD.gap), HEAD.y)),
head('recto-folio', '{pageNumber}', 'odd', at('top-right', -MARGIN.outer, HEAD.y), folio),
tab('even', 'top-left'), tab('odd', 'top-right'), // on the fore-edge, left on a verso
] };
С pages: 'body' колонтитулы печатаются только на страницах основного текста. Шмуцтитулы — это страницы part, их закрашенные обороты — страницы blank; обложка и содержание открываются заголовком во всю страницу и потому считаются начальными. Колонтитул левой полосы печатает {title}, название из метаданных, поэтому имя книги остаётся в Markdown. Колонтитул правой печатает {partTitle} в одну строку, а ярлык у внешнего края печатает {partNumber} на прямоугольнике, фон которого связан с band.
Рецепт целиком
// ═══ Postext Cookbook · Nº 019 · Parts in colour from one attribute ═══════════════════════
// https://postext.dev/en/cookbook/parts-in-colour
// Code: MIT · Text: original (CC BY 4.0) · Pictures: diffusion models
// Fonts: Alegreya, Zilla Slab, Barlow Condensed (SIL OFL 1.1) · Needs postext ≥ 1.57.0
// A pocket field guide to two habitats. Each :::part names its own 'band' colour, and every
// colour linked to 'band' takes it: the divider and its verso, the tab, the field marks.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'parts-in-colour';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: 'band' is the entry the parts override; the others keep their value
const palette = {
ink: '#1f2624', // text: a green-tinted near-black
band: '#3c4b4f', // the house slate, before any part; each :::part brings its own
paper: '#f6f3ea', // the page, and the type set on a band
rule: '#d5d1c4', // hairlines
muted: '#61675f', // running heads, Latin names, the colophon
};
// The paletteId is the link a part's palette="band=#…" follows, in text and designs 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 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: 150, height: 200 }; // a pocket guide
const MARGIN = { top: 22, bottom: 20, inner: 19, outer: 21 }; // mirrored; room for a thumb
const MEASURE = TRIM.width - MARGIN.inner - MARGIN.outer; // 110 mm, about 70 characters
const LEAD = 14.5; // body leading in pt: the baseline grid
const STRIP = 44; // the contents' picture strip, from the top edge (mm)
const HEAD = { y: 12, gap: 8 }; // running heads from the top edge; folio to title (mm)
const TAB = { y: 26, size: { width: mm(8), height: mm(24) } }; // the thumb tab, at the fore-edge
const TITLE_DROP = 6; // mm from the foot of the contents strip to the title's box
const BOOK = t({ en: 'Birds of the Estuary', es: 'Aves del estuario' });
const label = { fontFamily: 'Barlow Condensed', fontWeight: 600, textTransform: 'uppercase' };
const display = { fontFamily: 'Zilla Slab', fontWeight: 700 };
const at = (edge, x, y, to = 'page') => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const below = (id, y, size) => ({ ...at('below', 0, y, `#${id}`), ...(size && { size }) });
const fill = { size: { width: 'fill', height: 'fill' } };
const text = (id, content, style, placement) => ({ kind: 'text', id, content, overflow: 'wrap',
align: 'left', ...style, placement });
const box = (id, color, placement) => ({ kind: 'box', id, style: { backgroundColor: color },
placement });
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Добавьте третье место обитания
Ограждение перед первым видом солончака добавляет третий цвет со шмуцтитулом, закрашенным оборотом и строкой содержания, а конфигурация остаётся прежней. Уберите и примечание под содержанием: место нужно третьей полосе и её видам.
+:::part{number="III" title="The \\ Saltmarsh" palette="band=#6b4a7a"}
+:::
+
+# Common Shelduck {latin="Tadorna tadorna" size="58–67 cm" status="Resident"}#Поставьте вид напротив шмуцтитула
Без перехода на следующую правую полосу первый вид начинается на обороте шмуцтитула, и versoDesign закрашивать нечего.
- breakAfter: { parity: 'odd' },Частые ошибки
Подводный камень
Для parts.versoDesign нужен parts.breakAfter с parity 'odd'
Оборот шмуцтитула отрисовывается, только если parts.breakAfter { enabled: true, parity: 'odd' } оставляет эту левую полосу пустой. Шмуцтитулы частей →
Подводный камень
Страница 1 — правая: планируйте по физическим номерам
Страница 1 — правая полоса, страница 2 — первая левая, поэтому планируйте развороты по физическим номерам: начальная полоса на чётной странице стоит напротив следующей нечётной. Разрывы страниц и колонок →
- Часть перекрашивает текст, сравнивая значения: любой цвет текста, равный собственному значению
band, меняется вместе с частью, даже если он связан с другой записью или ни с какой. Держите этот код только дляband. - Ярлык печатает
{partNumber}, который вне части пуст, поэтому страница основного текста до первого:::partполучит пустой сланцевый ярлык. Держите все такие страницы внутри частей. - Изображения и образцы цвета в строке сохраняют записанные в них цвета. Иллюстрации здесь берут цвета места обитания из
HABITATв коде, поэтому новый цвет в:::partнужно внести и туда.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, CC BY 4.0
- Изображения
- The cover: a curlew on the estuary mud, reeds in front · Generated With Diffusion Models · оригинал
- The contents strip: a curlew and a redshank on the mud, the reedbed beyond · Generated With Diffusion Models · оригинал
- Plate 1: Eurasian curlew · Generated With Diffusion Models · оригинал
- Plate 2: common redshank · Generated With Diffusion Models · оригинал
- Plate 3: bearded reedling · Generated With Diffusion Models · оригинал
- Plate 4: common reed warbler · Generated With Diffusion Models · оригинал
- Шрифты
- Alegreya (SIL OFL 1.1) · Zilla Slab (SIL OFL 1.1) · Barlow Condensed (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)

