Коротко
Две соседние страницы учебника истории, сделанные как одна: цветная полоса пересекает середину книги, под ней шесть карточек с картинками, а шаблон рисует одну карточку и одну линию при любом числе дат.
Что получится
Страницы 48 и 49 учебника истории для средней школы: The paper road («Дорога бумаги»), тысяча лет бумажного дела от мастерской Цай Луня до жёрнова Келлера. Левая страница открывается заголовком и двумя абзацами, правая — врезкой о том, как лист делали вручную. Посередине идёт лента времени: полоса цвета индиго для Азии и терракотовая для Европы, которая начинается на левой странице и пересекает корешок. Под ней шесть карточек с картинками, подвешенных к полосе кольцом и вертикальной линией. Шаблон рисует одну азиатскую карточку, одну европейскую и по одной соединительной линии на полосу: сетка кладёт карточку на каждую дату из Markdown, а линия находит все карточки, положенные сеткой. Все слова лежат в Markdown, на испанском, английском и японском.
Рецепт отвечает на вопросы
- Как сверстать ленту времени на разворот, с полосой через корешок и карточками на обеих полосах?
- Как сделать, чтобы ряд врезок делил ширину и врезка с самым длинным текстом становилась шире?
Короткий ответ
const pageTemplates = [{
id: 'timeline',
spread: true, // two facing pages laid as one sheet; it opens on a verso
gutter: mm(10), // the band round the spine that frames keep off
grid: { columns: 2, rows: ROWS, columnGap: mm(2 * PAGE.inner), rowGap: mm(ROW_GAP) },
frames: [
{ name: 'title', takes: 'h1' },
{ name: 'lead', flow: true, fit: { minScale: 0.8 } },
{ name: 'box', style: 'box', grid: { col: 2, row: 1, rows: 4 }, height: 'fill',
padding: { right: mm(66) }, fit: { minScale: 0.85 } },
{ name: 'box-picture', layer: 2, width: mm(56), placement: at('#box', 'top-right', -5, 10) },
{ name: 'band-1', style: 'band-asia', grid: { col: 1, row: 5 }, height: mm(BAND) },
{ name: 'band-2', style: 'band-europe', crossGutter: true, width: 'fill', height: mm(BAND),
padding: { left: mm(2 * PAGE.inner + 4) }, // the colour crosses the fold, the words do not
placement: at('#band-1', 'right-of') },
card('asia', 'card-asia'), card('europe', 'card-europe'),
{ name: 'colophon', style: 'colophon', optional: true, width: mm(170),
placement: at('page', 'bottom-right', -PAGE.outer, -7) },
],
groups: [
{ name: 'opening', kind: 'stack', grid: { col: 1, row: 1, rows: 4 }, gap: mm(4),
frames: ['title', 'lead'] },
// A row of cards under each band, as many as the Markdown has: a longer text makes its
// row taller, and the other cards of the row stretch to the same height.
row('asia', 1), row('europe', 2),
],
decoration: { elements: [ground(), ticks('band-1', 'asia'), ticks('band-2', 'europe')] },
}];
Ингредиенты
- Возможности
- Шаблоны разворотовСетки с повтором набора фреймовСоединительные линии между фреймамиМакетные страницыФреймы, которые растут в группеОформление, привязанное к фреймамНумерованные ярлыки врезокВрезкиПривязка элементов дизайнаКолонтитулы и колонцифрыЗеркальные поляНумерованные спискиКитайские, японские и корейские шрифтыСемантическая палитраСтраницы на холстеЭкспорт в PDF
- Также применяет
- Рисунки точно здесьШрифты, встроенные в PDFСобственные типы ресурсовРисунки и таблицы как ресурсы
- Шрифты
- Literata, Archivo, Noto Serif JP, Noto Sans JP (SIL OFL 1.1)
- Материалы
forma-800.jpgv105-1000.jpgv1150-1000.jpgv1282-1000.jpgv1844-1000.jpgv610-1000.jpgv751-1000.jpg- A Han court official watches a craftsman lift a bamboo mould from a vat. (Generated With Diffusion Models, оригинал)
- A monk shows two Japanese courtiers how to hold a papermaking mould. (Generated With Diffusion Models, оригинал)
- Papermakers by a canal in Samarkand, sheets drying on a wall. (Generated With Diffusion Models, оригинал)
- A paper workshop below the castle of Xàtiva. (Generated With Diffusion Models, оригинал)
- A Fabriano mill with its water wheel; a sheet held up to the light. (Generated With Diffusion Models, оригинал)
- A craftsman grinds a spruce log against a stone into wood pulp. (Generated With Diffusion Models, оригинал)
- Two hands lift a papermaker's mould from a vat of pulp. (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Один лист на две страницы
const pageTemplates = [{
id: 'timeline',
spread: true, // two facing pages laid as one sheet; it opens on a verso
gutter: mm(10), // the band round the spine that frames keep off
grid: { columns: 2, rows: ROWS, columnGap: mm(2 * PAGE.inner), rowGap: mm(ROW_GAP) },
frames: [
{ name: 'title', takes: 'h1' },
{ name: 'lead', flow: true, fit: { minScale: 0.8 } },
{ name: 'box', style: 'box', grid: { col: 2, row: 1, rows: 4 }, height: 'fill',
padding: { right: mm(66) }, fit: { minScale: 0.85 } },
{ name: 'box-picture', layer: 2, width: mm(56), placement: at('#box', 'top-right', -5, 10) },
{ name: 'band-1', style: 'band-asia', grid: { col: 1, row: 5 }, height: mm(BAND) },
{ name: 'band-2', style: 'band-europe', crossGutter: true, width: 'fill', height: mm(BAND),
padding: { left: mm(2 * PAGE.inner + 4) }, // the colour crosses the fold, the words do not
placement: at('#band-1', 'right-of') },
card('asia', 'card-asia'), card('europe', 'card-europe'),
{ name: 'colophon', style: 'colophon', optional: true, width: mm(170),
placement: at('page', 'bottom-right', -PAGE.outer, -7) },
],
groups: [
{ name: 'opening', kind: 'stack', grid: { col: 1, row: 1, rows: 4 }, gap: mm(4),
frames: ['title', 'lead'] },
// A row of cards under each band, as many as the Markdown has: a longer text makes its
// row taller, and the other cards of the row stretch to the same height.
row('asia', 1), row('europe', 2),
],
decoration: { elements: [ground(), ticks('band-1', 'asia'), ticks('band-2', 'europe')] },
}];
spread: true делает шаблон одним листом шириной в обе страницы, и ограждение страницы говорит то же словом spread. Разворот открывается на левой полосе, поэтому сборка передаёт continuation: { pageIndexOffset: 1, pageNumbering: { startAt: 48 } }: страница 1 этого фрагмента — страница 48 книги, левая, и пустая страница впереди не появляется. В сетке по колонке на страницу с просветом в два внутренних поля, поэтому к сгибу подходит только полоса. У второй полосы заданы crossGutter и внутренний отступ слева 36 мм: её цвет идёт от конца первой полосы через корешок, а слова начинаются на правой странице, где их и читает вёрстка.
#2 · Одна карточка, повторённая сеткой
// Each `:::frame{slot="asia"}` of the page is an item of the `asia` grid: the grid lays the
// card frame once per item, three to a row, and names the copies `#asia[1]`, `#asia[2]`…
const card = (name, style) => ({ name, style, minHeight: mm(CARD) }); // auto above that height
const row = (name, col) => ({ name: `${name}-row`, kind: 'grid', columns: 3, columnGap: mm(5),
grid: { col, row: 6, rows: ROWS - 5 }, repeat: { frames: [name] } });
Группа с kind: 'grid' и repeat: { frames: ['asia'] } кладёт фрейм asia по разу на каждый :::frame{slot="asia"} страницы, по три в ряд, в ячейку сетки шаблона col: 1, строки 6–12. Копии называются #asia[1], #asia[2] и #asia[3], и каждая берёт label своего ограждения, дату на ярлыке. Высота карточки не меньше minHeight, а сверх того auto: если один текст длинный, как в карточке 1844 года на испанском и японском, её ряд растёт, а остальные карточки ряда вытягиваются до той же высоты (rowAlign по умолчанию 'stretch'). Четвёртая дата в Markdown начинает второй ряд под первым; шаблон не меняется.
#3 · Соединительная линия на каждую полосу
// `routing: 'tree'` with `trunk: 0` draws no bar of its own: each drop hangs from the band's
// foot straight down to the middle of a card's top, and `#asia[*]` names every card laid.
function ticks(band, cards) {
return { kind: 'connector', id: `${cards}-ticks`, routing: 'tree', trunk: 0,
from: { to: `#${band}`, side: 'bottom', gap: mm(2.4) }, to: { to: `#${cards}[*]`, side: 'top' },
color: col(cards), width: pt(1), startCap: 'ring', capSize: mm(3.6) };
}
Линии — по одному connector на полосу в decoration шаблона. routing: 'tree' соединяет одного родителя с несколькими потомками; при trunk: 0 своей перекладины нет, есть только прямая вертикаль от низа полосы к середине верхнего края каждой карточки, а startCap: 'ring' ставит кольцо в начале каждой вертикали, на 2,4 мм ниже полосы (gap). Кольцо — пустая точка, нарисованная толщиной линии, с внешним диаметром 3,6 мм (capSize), а вертикаль останавливается у её края, поэтому в отверстии виден кремовый фон. #asia[*] называет все карточки, положенные сеткой на страницу, и дата, добавленная в Markdown или убранная из него, добавляет или убирает вертикаль. Соединительные линии строятся после фреймов, поэтому при росте ряда они по-прежнему доходят до карточек. Кремовый фон тоже декор: прямоугольник, привязанный к низу вылета, высота которого доходит до нижнего края #band-1 (size: { height: { to: '#band-1', edge: 'bottom' } }), поэтому он следует за полосой.
#4 · Картинки в том размере, в каком печатаются
const ART = {
v105: t({ es: 'Un funcionario de la corte Han mira cómo un artesano saca de la tina un molde '
+ 'de bambú lleno de pasta, junto a corteza, trapos y redes viejas.',
en: 'A Han court official watches a craftsman lift a bamboo mould full of pulp from a vat, '
+ 'beside bark, rags and old nets.',
ja: '漢の役人が見守るなか、職人が竹のすき枠を漉き舟から引き上げる。そばに樹皮、ぼろ布、古い網。' }),
v610: t({ es: 'Un monje enseña a dos cortesanos japoneses a sostener el molde sobre una tina, '
+ 'con ramas de kozo en una estera.',
en: 'A monk shows two Japanese courtiers how to hold the mould over a tub, with kozo '
+ 'branches on a mat.',
ja: '僧が二人の宮廷人に、桶の上ですき枠を持つ手つきを見せる。むしろの上に楮の枝。' }),
v751: t({ es: 'Papeleros de Samarcanda junto a un canal; las hojas se secan al sol contra un '
+ 'muro de adobe.',
en: 'Samarkand papermakers by a canal; the sheets dry in the sun against a mud-brick wall.',
ja: '水路のそばで働くサマルカンドの紙すき職人。日干しれんがの壁に紙が張られて乾いている。' }),
v1150: t({ es: 'Un taller de Xàtiva bajo el castillo: un operario golpea trapos en una pila '
+ 'de piedra y las hojas cuelgan de cuerdas.',
en: 'A workshop in Xàtiva below the castle: a worker pounds rags in a stone trough and the '
+ 'sheets hang on ropes.',
ja: '城の下のシャティバの工房。職人が石の槽でぼろ布をたたき、紙が綱につるされている。' }),
v1282: t({ es: 'Un molino de Fabriano con su rueda hidráulica y sus mazos; un papelero mira '
+ 'una filigrana al trasluz.',
en: 'A Fabriano mill with its water wheel and hammers; a papermaker holds a watermark up '
+ 'to the light.',
ja: '水車と木づちのあるファブリアーノの製紙場。職人が紙を光にかざして透かしを見ている。' }),
v1844: t({ es: 'Un artesano aprieta un tronco de abeto contra una muela que gira; debajo se '
+ 'amontonan las fibras.',
en: 'A craftsman presses a spruce log against a turning grindstone; the fibres pile up '
+ 'below.',
ja: '職人がトウヒの丸太を回る砥石に押し当て、その下に木の繊維が積もっていく。' }),
forma: t({ es: 'Dos manos sacan de la tina el molde con una capa fina de fibras.',
en: 'Two hands lift the mould from the vat with a thin layer of fibres on it.',
ja: '両手ですき枠を引き上げる。網の上に繊維の薄い層ができている。' }),
};
const SIZE = { forma: [800, 800, 363] }; // pixels and ppi: 56 mm wide; the cards' are 46 mm
const resources = await Promise.all(Object.entries(ART).map(async ([id, altText]) => {
const px = SIZE[id] ?? [1000, 667, 550];
const fileId = `${id}-${px[0]}.jpg`;
await loadImage(fileId, asset(fileId));
return { id, typeId: 'picture', kind: 'bitmap', caption: '', altText, createdAt: 0,
updatedAt: 0,
bitmap: { fileId, format: 'jpeg', width: px[0], height: px[1], resolution: px[2] } };
}));
Виньетки шириной 1000 px при 550 ppi, на странице 46 мм, а картинку никогда не увеличивают. Три равные колонки сетки шириной 56,3 мм на каждой странице, поэтому картинка стоит внутри отступов карточки 3,5 мм в своём размере, а остальное в карточке — текст.
Рецепт целиком
// ═══ Postext Cookbook · Nº 158 · An illustrated timeline across a double page ═══════
// https://postext.dev/en/cookbook/illustrated-timeline-spread
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Literata, Archivo, Noto Serif JP, Noto Sans JP (SIL OFL 1.1) · Needs postext ≥ 1.49.0
import {
buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('es' | 'en' | 'ja')
const RECIPE = 'illustrated-timeline-spread';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: one ink, an accent for each half of the timeline, a pale ground
const palette = {
ink: '#22201d', // text
asia: '#2f4f7a', // indigo: the Asian half of the timeline
europe: '#a2412a', // terracotta: the European half
ground: '#f1ebdf', // the cream under the cards
rule: '#c9bfae', // hairlines and the card borders
muted: '#6b6359', // running heads and the colophon
paper: '#ffffff',
};
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: 'europe (defaults)', value: { hex: palette.europe, model: 'hex' } },
];
// #endregion
const JA = LANG === 'ja';
const SERIF = JA ? 'Noto Serif JP' : 'Literata';
const SANS = JA ? 'Noto Sans JP' : 'Archivo';
// A Western textbook page is 210 × 280 mm; a Japanese one is AB判, 210 × 257 mm.
const PAGE = { w: 210, h: JA ? 257 : 280, top: 22, bottom: 20, inner: 16, outer: 15 };
const ROWS = 12;
const ROW_GAP = 3;
const ROW = (PAGE.h - PAGE.top - PAGE.bottom - (ROWS - 1) * ROW_GAP) / ROWS; // one grid row, mm
const BAND = 9; // the timeline band, in grid row 5
const CARD_TOP = 5 * (ROW + ROW_GAP); // grid row 6
// The drawn height of a card; 16 mm of the area stay free for a longer text.
const CARD = PAGE.h - PAGE.top - PAGE.bottom - CARD_TOP - 16;
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
// #region cards: one card frame per row, repeated by a grid once for each card of the Markdown
// Each `:::frame{slot="asia"}` of the page is an item of the `asia` grid: the grid lays the
// card frame once per item, three to a row, and names the copies `#asia[1]`, `#asia[2]`…
const card = (name, style) => ({ name, style, minHeight: mm(CARD) }); // auto above that height
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Четыре карточки в ряд
При columns: 4 каждая полоса ставит рядом четыре даты; карточки становятся узкими, тексты длиннее, и ряды становятся выше.
-const row = (name, col) => ({ name: `${name}-row`, kind: 'grid', columns: 3, columnGap: mm(5),
+const row = (name, col) => ({ name: `${name}-row`, kind: 'grid', columns: 4, columnGap: mm(5),#Стрелки вместо колец
endCap: 'arrow' ставит остриё там, где вертикаль встречает карточку, а startCap: 'none' убирает кольца.
Частые ошибки
- Сетка кладёт ячейку на элемент, а элемент — это отдельное ограждение
:::frame{slot="asia"}: тексты двух карточек в одном ограждении дают одну карточку. #asiaбез[*]— рамка сетки, а не её карточки: линия к ней рисует одну вертикаль к середине ряда.- Размер, который доходит до края другого прямоугольника, отсчитывается от точки привязки самого элемента: фон привязан к низу вылета и растёт вверх до
#band-1. Край позади точки привязки даёт высоту 0.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- The paper road, a double-page timeline written for this recipe in Spanish, English and Japanese · Postext Cookbook · CC BY 4.0
- Изображения
- A Han court official watches a craftsman lift a bamboo mould from a vat. · Generated With Diffusion Models · оригинал
- A monk shows two Japanese courtiers how to hold a papermaking mould. · Generated With Diffusion Models · оригинал
- Papermakers by a canal in Samarkand, sheets drying on a wall. · Generated With Diffusion Models · оригинал
- A paper workshop below the castle of Xàtiva. · Generated With Diffusion Models · оригинал
- A Fabriano mill with its water wheel; a sheet held up to the light. · Generated With Diffusion Models · оригинал
- A craftsman grinds a spruce log against a stone into wood pulp. · Generated With Diffusion Models · оригинал
- Two hands lift a papermaker's mould from a vat of pulp. · Generated With Diffusion Models · оригинал
- Шрифты
- Literata (SIL OFL 1.1) · Archivo (SIL OFL 1.1) · Noto Serif JP (SIL OFL 1.1) · Noto Sans JP (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


