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

Рецепты · Глава 12 · Учебники

Тема детского учебника на десяти языках

Девять полос темы для 3-го класса на десяти языках, справа налево и вертикально: цветные развороты, растущие врезки, карта с подписями.

На этой странице

с. 6–7 из 9

  • Образец на английском: русского издания пока нет
  • Обрезной формат 210 × 280 мм
  • 1 колонка
  • Nunito 12/17,5
  • Fredoka
  • 9 страниц
  • Уровень
  • Postext 1.65.0
  • Свёрстано за 53 мс
  • Строк кода: 296

Коротко

Тема школьного учебника о реке на девяти страницах. Каждый параграф занимает цветной разворот с ярлыком заголовка, текстом, картинками и врезками. На карте не нарисовано ни слова: названия берутся из текста.

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

Девять полос Our river («Наша река»), темы 4 вымышленного учебника обществознания для третьего класса, на странице 210 × 280 мм и на десяти языках: испанском, каталанском, английском, португальском, французском, немецком, итальянском, арабском, китайском и японском. Тему открывает картина долины, на полосе содержания перечислены две части, дальше идут три разворота, у каждого свой фон: голубой для воды, зелёный для поля, песочный для солнца. У каждого параграфа есть ярлык с номером и заголовком, текст в две колонки и врезки с ярлыками, которые растут вместе с текстом. Второй параграф — это одна рисованная карта на весь разворот: река, деревни и три течения подписаны на ней из Markdown, а от врезки каждого течения к его участку реки идёт линия. Всё повторяющееся задано один раз: шаблон раскладывает одну карточку картинки, одну врезку течения и одну врезку с картинкой столько раз, сколько просит Markdown, а три вопроса перед темой — это три применения одного модуля. Тексты различаются по длине на пятую часть и больше, но укладываются в одни и те же шаблоны: врезка берёт высоту, нужную её словам, и сдвигает следующую вниз, а карта уменьшается раньше, чем какой-либо текст. Арабская книга идёт справа налево, китайская и японская — сверху вниз; у всех трёх переплёт справа, и каждый разворот читают с правой полосы к левой.

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

  • Как набрать тему учебника на трёх языках по одним шаблонам страниц, если тексты разной длины?
  • Как сделать, чтобы врезки страницы росли вместе с текстом и сдвигали врезки под ними вниз?
  • Как взять названия на карте из текста, чтобы перевод менял слова, а не рисунок?

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

script.js · строки 90–122в полном коде
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];

Ингредиенты

Возможности
Макетные страницыСетки с повтором набора фреймовМодули друг под другом на страницеВыноски и легенды на рисункахФреймы, которые растут в группеНумерованные ярлыки врезокНадписи на рисункеСодержаниеШаблоны разворотовВрезкиТекст, линейки и рамки в дизайне страницыИллюстрации в дизайне страницыПривязка элементов дизайнаОформление, привязанное к фреймамЗеркальные поляКолонтитулы и колонцифрыСтили заголовковСемантическая палитраРисунки и таблицы как ресурсы
Шрифты
Nunito, Fredoka, Noto Naskh Arabic, Baloo Bhaijaan 2, Klee One, Zen Maru Gothic, Noto Serif SC, ZCOOL KuaiLe (SIL OFL 1.1)
Материалы
  • arroyo-720.jpg
  • cascada-720.jpg
  • limpieza-720.jpg
  • mapa-1900-rtl.jpg
  • mapa-1900.jpg
  • molino-720.jpg
  • nacimiento-720.jpg
  • piraguas-720.jpg
  • portada-1400.jpg
  • riego-720.jpg
  • The valley of the River Aldara, painted from the mountains to the sea, with two children watching the water. (Generated With Diffusion Models, оригинал)
  • The painted map of the valley, from the spring to the port, with no lettering: the names are labels set from the Markdown. (Generated With Diffusion Models, оригинал)
  • The same painted map mirrored, the mountains on the right, for the books bound on the right (Arabic, Chinese, Japanese). (Generated With Diffusion Models, оригинал)
  • A spring between mossy rocks. (Generated With Diffusion Models, оригинал)
  • A mountain stream over round stones. (Generated With Diffusion Models, оригинал)
  • A small waterfall into a green pool. (Generated With Diffusion Models, оригинал)
  • A farmer opening the gate of an irrigation canal. (Generated With Diffusion Models, оригинал)
  • An old stone watermill with its wheel. (Generated With Diffusion Models, оригинал)
  • Children paddling canoes on a calm river. (Generated With Diffusion Models, оригинал)
  • Children and a teacher picking up litter on a river bank. (Generated With Diffusion Models, оригинал)

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

#1 · Определите, с какой стороны начинает каждый язык

script.js · строки 33–44в полном коде
// Arabic runs right to left, Chinese and Japanese down the page, all bound on the right. Frames
// stand in the flow (x along the lines, mirrored in Arabic, down the page when vertical).
const AR = LANG === 'ar', CJK = LANG === 'zh' || LANG === 'ja';
const RIGHT_BOUND = AR || CJK, LATIN = !RIGHT_BOUND; // italics, capitals, tracking, hyphens
const [TEXT, DISPLAY] = { ar: ['Noto Naskh Arabic', 'Baloo Bhaijaan 2'], ja: ['Klee One',
  'Zen Maru Gothic'], zh: ['Noto Serif SC', 'ZCOOL KuaiLe'] }[LANG] ?? ['Nunito', 'Fredoka'];
const START = RIGHT_BOUND ? 'right' : 'left'; // the side a page starts reading from
const corner = (v) => `${v}-${START}`, inward = (x) => (RIGHT_BOUND ? -x : x);
const [SLANT, CAPS] = LATIN ? ['italic', 'uppercase'] : ['normal', 'none'];
const LEAD = AR ? 20 : CJK ? 21 : 17.5, track = (v) => (LATIN ? v : 0); // Naskh, ruby need room
const fw = (w) => ({ 'ZCOOL KuaiLe': 400, 'Zen Maru Gothic': w > 550 ? 700 : 500 })[DISPLAY] ?? w;
const BOLD = TEXT === 'Klee One' ? 600 : 700; // and the weights the faces have

Фреймы шаблона стоят в системе координат потока, где x идёт вдоль строк. При locale: 'ar' движок отражает эту систему, поэтому арабская книга берёт латинские фреймы без изменений: заголовок стоит первым на правой полосе, три картинки и три врезки течений идут справа налево, а ярлыки, полоски и внутренние отступы врезок следуют за строками. При layout.writingMode: 'vertical-rl' x идёт вниз по странице, а y — справа налево: width фрейма становится длиной по вертикали, стопка растёт влево, columns: 2 даёт два яруса (段) по 27 знаков, а фрейм, поставленный below другого, оказывается слева от него. Декор (фоны, ярлык заголовка, номер, колонтитулы и колонцифры) стоит на самом листе, поэтому его размещают от START — стороны, с которой начинают читать страницу. У каждой письменности есть текстовая гарнитура и округлая акцидентная, а в арабском, китайском и японском изданиях нет курсива, прописных и трекинга.

#2 · Соберите врезки через extends

script.js · строки 59–86в полном коде
// Two steps of `extends`: the box (shape, type, tab), then the kind. The colours are `tema`
// entries, so one style serves the three topics; paddings, stripes and tabs are in the flow.
const tab = (f) => ({ position: 'top-left', background: col(f), color: col('paper'),
  fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), height: mm(7), paddingX: mm(3.2),
  offset: mm(7), inset: mm(5), rule: { enabled: false, color: col(f) } });
const boxText = { fontFamily: TEXT, fontSize: pt(12), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), boldFontWeight: BOLD, firstLineIndent: pt(0),
  textAlign: CJK ? 'justify' : 'left', paragraphSpacing: true };
const calloutStyles = [
  { id: 'caja', backgroundEnabled: true, background: col('paper'), borderRadius: mm(3),
    border: { enabled: false }, padding: { top: mm(3.4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: boxText, lists: { color: col('ink'), gap: mm(2), itemSpacing: mm(1.6) } },
  { id: 'caja-tema', extends: 'caja', label: tab('tema'), lists: { color: col('tema') } },
  { id: 'dato', extends: 'caja-tema', background: col('tema-tint') },
  { id: 'palabras', extends: 'caja-tema', border: { enabled: true, color: col('tema'),
    width: pt(1.4) } }, { id: 'actividad', extends: 'caja-tema',
    stripe: { enabled: true, side: 'left', width: pt(4), color: col('tema') } },
  { id: 'titulo', extends: 'caja', backgroundEnabled: false,
    padding: { top: mm(2.6), right: mm(6), bottom: mm(3.2), left: mm(TAB) } },
  { id: 'titulo-plano', extends: 'titulo', padding: { left: mm(8) } },
  { id: 'portada', extends: 'caja', background: col('agua'), borderRadius: mm(4),
    padding: { top: mm(2.6), right: mm(8), bottom: mm(3.6), left: mm(8) } },
  { id: 'foto', extends: 'caja', borderRadius: mm(2),
    padding: { top: mm(1.8), right: mm(1.8), bottom: mm(2.2), left: mm(1.8) } },
  { id: 'respuesta', extends: 'caja', padding: NONE }, { id: 'colofon', extends: 'caja',
    backgroundEnabled: false, padding: NONE,
    body: { ...boxText, fontSize: pt(8), lineHeight: pt(AR ? 13 : 11), color: col('muted') } },
];

Стиль врезки складывается в три шага. caja держит форму, шрифт и геометрию ярлыка; caja-tema красит ярлык и маркеры списка в цвет темы; dato, palabras и actividad задают вид: врезка с заливкой, с контуром или с полоской. Их цвета — записи палитры (tema, tema-tint), поэтому каждый стиль написан один раз, а красит его шаблон темы.

#3 · Пусть каждая тема расширяет один базовый шаблон

script.js · строки 90–122в полном коде
// Ground, tab and number are decoration anchored to the title frame; the number,
// `{headingNumber}`, stands over the padding before its words. A topic extends the base.
const ground = () => ({ kind: 'box', id: 'ground',
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } },
  style: { backgroundColor: col('tema-ground') } });
const titleTab = () => ({ kind: 'box', id: 'tab', placement: { ...at('#titulo',
  'top-left'), size: { width: { to: '#titulo', edge: 'right' }, height: { to: '#titulo',
    edge: 'bottom' } } }, style: { backgroundColor: col('tema'), borderRadius: mm(4) } });
const badge = () => ({ kind: 'text', id: 'number', content: '{headingNumber}',
  fontFamily: DISPLAY, fontSize: pt(22), fontWeight: fw(700), color: col('tema'), align: 'center',
  box: { backgroundColor: col('paper'), borderRadius: mm(6) }, placement: { ...at('#titulo',
    corner('top'), inward(CJK ? 2.6 : 5), CJK ? 5 : 2.4), size: { width: mm(12), height: mm(12) } },
});
const title = { name: 'titulo', takes: 'h1', style: 'titulo', width: mm(MEASURE),
  placement: at('container', 'top-left') };

const base = {
  id: 'tema', spread: true, gutter: mm(12),
  decoration: { elements: [ground(), titleTab(), badge()] },
  frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
    width: mm(MEASURE), fit: { minScale: 0.9 } }],
  groups: [{ name: 'izquierda', kind: 'stack', gap: mm(6), frames: ['titulo', 'texto'] }],
};
const topic = (id, f, more) => ({ id, extends: 'tema', palette: swap(f), ...more });
const box = (name, style, minHeight, more) => ({ name, style, width: mm(MEASURE),
  minHeight: mm(minHeight), ...more });
const answer = (name, lines) => ({ name, optional: true, style: 'respuesta', width: mm(MEASURE),
  height: mm(LINE * lines), minHeight: mm(LINE * lines),
  rules: { every: mm(LINE), color: col('rule'), width: pt(0.75) } });
const PIC = CJK ? 30 : 56; // a picture at the end of a box's first lines pushes the text aside
const withPic = (name, style, minHeight, more) => [box(name, style, minHeight,
  { padding: { right: mm(PIC + 8) }, ...more }), { name: `${name}-foto`, layer: 2, width: mm(PIC),
  exclude: 'push', placement: at(`#${name}`, 'top-right', -5, 8) }];

Базовый шаблон — это разворот: фон до вылета, ярлык заголовка с номером и текст в две колонки. Тема расширяет его (extends: 'tema'), задаёт свою palette (три записи tema получают цвета семейства, и вместе меняются фон, ярлык, номер и все врезки) и добавляет собственные фреймы. Ярлык и номер — декор, привязанный к фрейму заголовка, поэтому высота ярлыка равна высоте заголовка на данном языке. Номер — это {headingNumber}, счётчик заголовка, попавшего во фрейм. Он рисуется поверх внутреннего отступа фрейма, перед словами: ни один блок страницы его не повторяет, а щелчок по нему попадает в номер, а не во фрейм.

#4 · Задайте повторяющееся один раз

script.js · строки 126–131в полном коде
const grid = (name, frames, columns, placement, more, width = MEASURE) => ({ name, kind: 'grid',
  columns, columnGap: mm(5), rowGap: mm(CJK ? 8 : 12), repeat: { frames },
  placement: { ...placement, size: { width: mm(width), height: 'fill' } }, ...more });
const question = { id: 'pregunta', role: 'module', // a question and the lines to answer it on
  frames: [box('caja', 'dato', CJK ? 22 : 14, { width: 'fill' }), { ...answer('lineas',
    CJK ? 2 : 3), width: 'fill', placement: at('#caja', 'below', 0, CJK ? 4 : 7) }] };

Группа-сетка повторяет набор фреймов по разу на каждый элемент страницы. Ряд картинок — это grid('fotos', ['foto'], 3, …): три блока :::figure{slot="foto"} дают три карточки с именами от #foto[1] до #foto[3], а врезка Try it висит под #foto[1]. Врезки солнечной темы — сетка в одну колонку, набор которой состоит из врезки и её картинки (['uso', 'uso-foto']): каждый :::frame{slot="uso"} содержит свои слова и внутри себя :::figure{slot="uso-foto"}, который к ним относится. На странице вопросов модуль идёт стопкой: pregunta — шаблон с role: 'module', врезка с заливкой и линейки для ответа, а группа preguntas этой страницы (modules: true) ставит по одному такому модулю на каждый :::module{template="pregunta"} в Markdown. Высота фрейма равна высоте его слов и не бывает меньше minHeight, поэтому более длинный испанский текст сдвигает нижние ряды, а когда странице не хватает места, лестница подгонки уменьшает карту и картинки раньше текста, до 90 %.

Врезки течений — сетка из трёх под картой (grid('cursos', ['curso'], 3, …)), по одной на каждый :::frame{slot="curso"}. Карта называет те же три участка подписями в стиле curso, на зелёном цвете ярлыков врезок, так что читатель находит участок каждой врезки по названию и цвету. На вертикальной странице течения стоят в одну колонку рядом с картой.

#5 · Поставьте названия на карту из текста

script.js · строки 250–290в полном коде
// An anchor is a point of the painting (fractions of its width and height) and a label style;
// every language's ::label lines use the same anchors. A right-bound book shows the painting
// mirrored, the mountains on the right, so the river runs the way its pages are read: x comes
// from the other edge and a turn goes the other way. `start` is a label's own start, so the
// spring's label keeps it in Arabic and takes `end` in a label set left to right.
const halo = { color: col('paper'), width: pt(1.8) };
const labelStyles = [
  { id: 'sierra', fontFamily: DISPLAY, fontSize: pt(13), fontWeight: fw(600), color: col('ink'),
    textTransform: CAPS, letterSpacing: track(0.14), halo },
  { id: 'agua', fontFamily: TEXT, fontSize: pt(11), fontWeight: BOLD, fontStyle: SLANT,
    color: { hex: '#0b3a5c', model: 'hex' }, halo, // a name set away draws a leader to its point
    leader: { width: pt(1), endCap: 'dot', capSize: mm(1.6) } },
  { id: 'mar', fontFamily: TEXT, fontSize: pt(12), fontWeight: BOLD, fontStyle: SLANT,
    color: col('paper'), halo: { color: { hex: '#0b3a5c', model: 'hex' }, width: pt(1.8) } },
  { id: 'pueblo', fontFamily: DISPLAY, fontSize: pt(12), fontWeight: fw(600), color: col('ink'),
    halo },
  { id: 'curso', fontFamily: DISPLAY, fontSize: pt(10.5), fontWeight: fw(600), color: col('paper'),
    textTransform: CAPS, letterSpacing: track(0.08), background: col('campo'),
    padding: mm(1.6) },
];
const ANCHORS = [
  { id: 'sierra', x: 0.21, y: 0.055, style: 'sierra' },
  // The spring and the dam: the point is the place, `labelAt` where its name stands.
  { id: 'nacimiento', x: 0.049, y: 0.098, labelAt: { x: 0.075, y: 0.115 }, style: 'agua',
    align: 'start' },
  { id: 'fontalba', x: 0.135, y: 0.255, style: 'pueblo', verticalAlign: 'top' },
  { id: 'embalse', x: 0.293, y: 0.275, labelAt: { x: 0.31, y: 0.155 }, style: 'agua',
    width: 0.12 },
  { id: 'molinar', x: 0.505, y: 0.35, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'aldamar', x: 0.845, y: 0.505, style: 'pueblo', verticalAlign: 'bottom' },
  { id: 'mar', x: 0.965, y: 0.28, style: 'mar' },
  { id: 'rio', x: 0.61, y: 0.715, style: 'agua', rotate: -3 },
  { id: 'alto', x: 0.17, y: 0.45, style: 'curso' },
  { id: 'medio', x: 0.4, y: 0.77, style: 'curso' },
  { id: 'bajo', x: 0.74, y: 0.865, style: 'curso' },
];
const flip = (x) => Math.round((1 - x) * 1000) / 1000;
const flipped = (a) => ({ ...a, x: flip(a.x), ...(a.labelAt && { labelAt: { ...a.labelAt,
    x: flip(a.labelAt.x) } }),
  ...(a.rotate && { rotate: -a.rotate }), ...(a.align && !AR && { align: 'end' }) });
const anchors = RIGHT_BOUND ? ANCHORS.map(flipped) : ANCHORS;

Карта — это картина без единой буквы. Каждое место на ней — якорь изображения: точка в долях ширины и высоты со стилем подписи, а каждая языковая версия пишет у этих якорей свои строки ::label. Penalta Reservoir, Pantà de Penyalta и Embalse de Peñalta стоят в одном и том же месте, а более длинное название разбивается на строки в пределах width якоря. В книге с переплётом справа та же картина отражена (mapa-1900-rtl.jpg), и река течёт от гор справа к морю слева, как читаются её страницы; flipped переносит каждый якорь и место его подписи на другую сторону и поворачивает в обратном направлении. Spring и Penalta Reservoir отнесены от своих мест через labelAt, а leader стиля agua ведёт линию с точкой от названия к роднику и к плотине.

#6 · Не разрывайте части содержания

script.js · строки 227–246в полном коде
const partAt = (x) => (CJK ? at('container', 'left', x) : at('container', START, inward(x)));
const toc = {
  levels: [{ level: 1, fontFamily: DISPLAY, fontSize: pt(15), lineHeight: pt(22),
    fontWeight: fw(500), color: col('ink'), numberFontWeight: fw(600), numberColor: col('agua'),
    numberWidth: mm(9), marginTop: pt(4) }, { level: 2, fontFamily: TEXT, fontSize: pt(11.5),
    lineHeight: pt(18), indent: mm(9), color: col('ink') }],
  pageNumber: { fontFamily: DISPLAY, fontWeight: fw(500), width: mm(9), color: col('agua') },
  leader: { char: CJK ? '…' : '.', gap: mm(1.5) },
  parts: { height: pt(34), marginTop: pt(12), marginBottom: pt(4), design: { elements: [
    { kind: 'box', id: 'band',
      placement: { ...at('container', 'top-left'), size: { width: 'fill', height: 'fill' } },
      style: { backgroundColor: col('paper'), borderRadius: mm(3) } },
    { kind: 'text', id: 'letter', content: '{number}', fontFamily: DISPLAY, fontSize: pt(16),
      fontWeight: fw(700), color: col('paper'), align: 'center',
      box: { backgroundColor: col('agua'), borderRadius: mm(4) },
      placement: { ...partAt(2), size: { width: mm(8), height: mm(8) } } },
    { kind: 'text', id: 'name', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(13),
      fontWeight: fw(600), color: col('agua'), align: START, placement: partAt(14) },
  ] } },
};

:::toc{keep="part" levels="1-2"} перечисляет темы с их разделами и держит строку каждой части вместе с её пунктами. Блок :::part при parts.page: false — лишь строка содержания и раздел для колонтитулов: шмуцтитула он не добавляет. Содержание — макетная страница: в её шаблоне есть фрейм с takes: "toc", который принимает :::toc и верстает его по собственным правилам содержания. Поэтому строки частей, отточия и keep работают как в обычном тексте, а бледный фон — декор шаблона.

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

Sandbox
// ═══ Postext Cookbook · Nº 156 · A children's textbook unit in ten languages ═════
// https://postext.dev/en/cookbook/children-textbook-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Nunito, Fredoka and three pairs for Arabic, Chinese, Japanese · Needs postext ≥ 1.65.0
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
  loadVerticalAlternates,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the unit (es en ca pt fr de it ar zh ja)
const RECIPE = 'children-textbook-pages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// One ink and three families (accent, box tint, page ground); a topic swaps the `tema` entries.
const FAMILIES = {
  agua: { main: '#1b6aa0', tint: '#e1f0fa', ground: '#d3e8f6' },
  campo: { main: '#336f27', tint: '#e5f1dc', ground: '#d9ebcb' },
  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
};
const palette = { ink: '#1d2f3f', muted: '#4f6272', rule: '#7e98ab', paper: '#ffffff',
  agua: FAMILIES.agua.main, campo: FAMILIES.campo.main, // the blue of the folios and the contents
  tema: FAMILIES.agua.main, 'tema-tint': FAMILIES.agua.tint, 'tema-ground': FAMILIES.agua.ground };
const swap = (f) => `tema=${FAMILIES[f].main}, tema-tint=${FAMILIES[f].tint}, `
  + `tema-ground=${FAMILIES[f].ground}`;
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: 'water (defaults)', value: { hex: palette.agua, model: 'hex' } },
];

// #region editions: how each language runs and is bound, and the two faces of its script
// Arabic runs right to left, Chinese and Japanese down the page, all bound on the right. Frames
// stand in the flow (x along the lines, mirrored in Arabic, down the page when vertical).
const AR = LANG === 'ar', CJK = LANG === 'zh' || LANG === 'ja';
const RIGHT_BOUND = AR || CJK, LATIN = !RIGHT_BOUND; // italics, capitals, tracking, hyphens
const [TEXT, DISPLAY] = { ar: ['Noto Naskh Arabic', 'Baloo Bhaijaan 2'], ja: ['Klee One',
  'Zen Maru Gothic'], zh: ['Noto Serif SC', 'ZCOOL KuaiLe'] }[LANG] ?? ['Nunito', 'Fredoka'];
const START = RIGHT_BOUND ? 'right' : 'left'; // the side a page starts reading from
const corner = (v) => `${v}-${START}`, inward = (x) => (RIGHT_BOUND ? -x : x);
const [SLANT, CAPS] = LATIN ? ['italic', 'uppercase'] : ['normal', 'none'];
const LEAD = AR ? 20 : CJK ? 21 : 17.5, track = (v) => (LATIN ? v : 0); // Naskh, ruby need room
const fw = (w) => ({ 'ZCOOL KuaiLe': 400, 'Zen Maru Gothic': w > 550 ? 700 : 500 })[DISPLAY] ?? w;
const BOLD = TEXT === 'Klee One' ? 600 : 700; // and the weights the faces have
// #endregion

const PAGE = { w: 210, h: 280, top: 18, bottom: 18, inner: 14, outer: 12 }; // mm, mirrored
const HALF = PAGE.w - PAGE.inner - PAGE.outer, TALL = PAGE.h - PAGE.top - PAGE.bottom; // 184, 244

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

Варианты

#Добавьте четвёртое семейство

Тема о море — это четвёртая запись в FAMILIES и шаблон, созданный вызовом topic('tema-mar', 'mar', { frames }). swap('mar') записывает его палитру, а врезки и фон ей следуют.

-  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
+  sol: { main: '#9a5209', tint: '#fcefd2', ground: '#f8e6b8' },
+  mar: { main: '#0f5a6b', tint: '#dcf0f2', ground: '#cbe6ea' },

#Сохраните кегль текста

Фрейм, который не должен уменьшать свой текст, получает fit: { shrinkText: false }. Тогда более длинный текст сильнее давит на соседние фреймы, и лестница первыми уменьшает картинки.

   frames: [title, { name: 'texto', flow: true, columns: 2, columnGap: mm(CJK ? 16 : 7), // 段
-    width: mm(MEASURE), fit: { minScale: 0.9 } }],
+    width: mm(MEASURE), fit: { shrinkText: false } }],

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

  • Название, нарисованное в картинке, не сменится вместе с языком: на карте нет ни слова, все названия — подписи.
  • Палитра темы меняет только записи tema. Колонцифры и содержание берут agua, где тот же синий, поэтому на зелёных и песочных страницах они остаются синими; свяжите их с tema, и они последуют за темой.
  • Арабско-индийская цифра рядом с точкой посередине строки читается как две цифры: ١ · ماء похоже на ٠١ ماء, потому что арабский ноль — это точка. В арабском издании написано ١- ماء للحقول, а номер темы дан словом.
  • Элемент декора стоит на листе, а не в потоке: значок, поставленный в top-left фрейма, остаётся слева и в арабской книге. corner('top') и inward(x) размещают его от стороны, с которой начинают читать страницу.
  • В сетке каждый элемент — отдельный блок: картинка врезки входит в её набор, только если её :::figure написан внутри :::frame врезки. Написанная после него, картинка становится отдельным элементом и занимает собственную ячейку.
  • Два рисунка с одним и тем же ресурсом берут слова первого: маленькая карта на странице содержания — тот же файл под отдельным ресурсом rio, без якорей.

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

Рецепт
Ignacio Ferro
Текст
  • Our river, a children's textbook unit written for this recipe in Spanish and set in ten languages · Postext Cookbook · CC BY 4.0
Изображения
  • The valley of the River Aldara, painted from the mountains to the sea, with two children watching the water. · Generated With Diffusion Models · оригинал
  • The painted map of the valley, from the spring to the port, with no lettering: the names are labels set from the Markdown. · Generated With Diffusion Models · оригинал
  • The same painted map mirrored, the mountains on the right, for the books bound on the right (Arabic, Chinese, Japanese). · Generated With Diffusion Models · оригинал
  • A spring between mossy rocks. · Generated With Diffusion Models · оригинал
  • A mountain stream over round stones. · Generated With Diffusion Models · оригинал
  • A small waterfall into a green pool. · Generated With Diffusion Models · оригинал
  • A farmer opening the gate of an irrigation canal. · Generated With Diffusion Models · оригинал
  • An old stone watermill with its wheel. · Generated With Diffusion Models · оригинал
  • Children paddling canoes on a calm river. · Generated With Diffusion Models · оригинал
  • Children and a teacher picking up litter on a river bank. · Generated With Diffusion Models · оригинал
Шрифты
Nunito (SIL OFL 1.1) · Fredoka (SIL OFL 1.1) · Noto Naskh Arabic (SIL OFL 1.1) · Baloo Bhaijaan 2 (SIL OFL 1.1) · Klee One (SIL OFL 1.1) · Zen Maru Gothic (SIL OFL 1.1) · Noto Serif SC (SIL OFL 1.1) · ZCOOL KuaiLe (SIL OFL 1.1)
SandboxPDF