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

Рецепты · Глава 6 · Врезки и примечания

Карточка рецепта: продукты рядом с шагами

Две страницы кулинарной книги с белой карточкой под ярлыком SERVES 4: слева продукты, теги и список дел, справа шаги с красными цифрами 26 пт.

с. 58–59 · 1–2 из 2

  • Образец на английском: русского издания пока нет
  • Обрезной формат 190 × 250 мм
  • 1 колонка
  • Figtree 9,4/12,8
  • Caveat
  • Young Serif
  • 2 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 51 мс
  • Строк кода: 187

Коротко

Две страницы домашней кулинарной книги, по рецепту на каждой. Показывает, как поставить на карточке продукты и шаги приготовления рядом друг с другом.

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

Разворот из Salt & Olive Oil, вымышленной испанской домашней кулинарной книги, обрезной формат 190 × 250 мм, по рецепту на страницу. Фотография, созданная диффузионными моделями и загруженная как JPEG, идёт под обрез по верхним 104 мм: тортилья с вынутым ломтем на шафрановом столе, миска гаспачо на шалфейно-зелёном. На ней стоят надзаголовок, заголовок Young Serif 42 пт, плашки со временем, сложностью и сезоном и рукописная пометка шрифтом Caveat, которая указывает на блюдо. Под курсивным вступлением белая карточка с томатно-красным ярлыком порций в правом верхнем углу. Продукты идут по её левой колонке с оливковыми тире и тегами-плашками; под продуктами тортильи контурные рисунки миски, сковороды и тарелки открывают список дел. Шаги заполняют правую колонку, каждый начинается с минускульной цифры 26 пт.

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

  • Как разместить две колонки внутри врезки (колонка текста рядом с колонкой рисунка)?
  • Как добавить нумерованный ярлык («ВРЕЗКА 1-1»), значок в углу или значок на поле с линейкой?
  • Как настроить списки: маркеры по уровням, нумерация (a)/(i), флажки задач, отбивки по сетке?
  • Как сделать плашки в строке: клавиши, теги, банки слов для упражнений?
  • Как добавить на начальную полосу строку с автором, вводку или лид с буквицей?

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

script.js · строки 26–48в полном коде
// In the Markdown, :::callout{type="card" label="SERVES 4"} holds a :::columns{count=2} group
// of two nested boxes, :::callout{type="column" title="Ingredients"} and one for the method.
// The group levels its columns by cutting between blocks or lines, so loose lists would run
// the method on under the ingredients. A nested box is one block that never splits, so the
// only cut left is between the two.
const TAB = 5.6; // mm: the tab's height, and how far it rises above the card
const card = { id: 'card', background: col('card'),
  padding: { top: mm(4.5), right: mm(6), bottom: mm(5), left: mm(6) },
  // No space of its own above: the tab starts on the first grid line under the opener.
  columnGap: mm(7), marginTop: mm(0),
  // label="…" on the fence prints here: a tab on the top-right corner, a cutlery pictogram
  // beside it and a rule from the far corner that makes the tab part of the card.
  label: { fontFamily: TEXT, fontSize: pt(8), color: col('card'), // bold by default
    background: col('tomato'), height: mm(TAB), offset: mm(TAB), paddingX: mm(2.6),
    icon: { resourceId: 'cutlery', width: mm(TAB * 6 / 8), gap: mm(1.6) }, // as tall as the tab
    rule: { enabled: true, color: col('tomato'), width: pt(1.2) } } };
// The two columns: frameless boxes whose only device is a tracked title.
const NONE = { top: mm(0), right: mm(0), bottom: mm(0), left: mm(0) };
const column = { id: 'column', backgroundEnabled: false, padding: NONE,
  lists: { gap: mm(2.2), itemSpacing: pt(3.5) }, // for the steps as well as the dashes
  titleStyle: { fontFamily: TEXT, fontSize: pt(8), color: col('tomato'), // bold by default
    textTransform: 'uppercase', letterSpacing: pt(1.5), gap: mm(2.4) } };
// config() plugs them in: calloutStyles: [card, column, prep].

Ингредиенты

Возможности
Колонки во врезке или в текстеНумерованные ярлыки врезокНумерованные спискиВложенные врезкиЗначки врезок и бейджи в углуПлашки в строкеМаркированные списки и контрольные спискиВрезкиОформленные начальные полосыШапка главы на всю ширинуСтили заголовковАтрибуты заголовковТекст, линейки и рамки в дизайне страницыИллюстрации в дизайне страницыРазрывы строк в заголовкахЦвет бумагиКолонтитулы и колонцифрыСемантическая палитраСтили абзацевРисунки и таблицы как ресурсы
Шрифты
Young Serif, Figtree, Caveat (SIL OFL 1.1)
Материалы
  • gazpacho-1520.jpg
  • tortilla-1520.jpg
  • The tortilla on its plate, a photograph (Generated With Diffusion Models, оригинал)
  • The bowl of gazpacho, a photograph (Generated With Diffusion Models, оригинал)
  • The note’s arrow and the pictograms, drawn in code in the page’s palette (Ignacio Ferro, CC BY 4.0)

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

#1 · Дайте каждой колонке свою врезку

Со списками без обёртки группа колонок во врезке режется там, где колонки лучше выравниваются, между блоками или между строками одного блока, поэтому первый шаг гаспачо делится через средник: его первая строка закрывает колонку продуктов, а остальное открывает колонку шагов. Вложенная врезка, как в разделе «Короткий ответ» выше, — один блок, и группа никогда не режет её внутри. Изображению в ней нужен ::resource с размещением 'here': при любом другом оно становится плавающим объектом, покидает врезку и встаёт, как любой рисунок со ссылкой. label стиля карточки превращает label="SERVES 4" ограждения в ярлык: offset, равный его height, ставит ярлык на верхний край карточки, а rule идёт от дальнего угла до вилки и ножа (стили врезок).

#2 · Поставьте номера шагов по центру двух строк

script.js · строки 66–76в полном коде
// Young Serif has old-style figures: 1 and 2 stand 0.56 em, a little above its 0.50 em
// x-height, so 5.1 mm at STEP. A list number is centred 0.3 em (of the text) above the item's
// first baseline, with the canvas 'middle' baseline, which Chrome puts 0.24 em above Young
// Serif's own (gotcha: list-number-centred). DROP centres the figures on the step's first two
// lines, from the cap height of the first to the baseline of the second.
const [STEP, FIGURE, MIDDLE, CAP] = [26, 0.56, 0.24, 0.7]; // pt; em of each face
const DROP = (LEAD - CAP * BODY) / 2 + 0.3 * BODY + (FIGURE / 2 - MIDDLE) * STEP; // pt
const orderedLists = { fontFamily: DISPLAY, fontWeight: 400, // Young Serif ships 400 only
  numberFontSize: pt(STEP), color: col('tomato'),
  separatorColor: col('olive'), separatorGap: pt(0.6), // the default '.' as its own run
  numberVerticalOffset: pt(DROP) };

Номер списка рисуется с центром чуть выше первой базовой линии пункта, поэтому один numberFontSize поставил бы цифры 26 пт вровень с первой строкой; numberVerticalOffset опускает их на 2,5 мм, к середине полосы от прописных первой строки до базовой линии второй. У Young Serif минускульные цифры: 3, 4 и 5 опускаются под базовую линию, на которой стоят 1 и 2. Когда задан separatorColor, разделитель рисуется отдельным фрагментом, и точка по умолчанию печатается оливковой рядом с красной цифрой (нумерованные списки).

#3 · Откройте список дел полосой рисунков

script.js · строки 52–62в полном коде
// :::callout{type="prep" title="Before you start"}, closed at once, is a header: a box that
// holds only its title and icon. The icon is one picture of three drawings; a width KIT times
// its size makes its box a strip, and the picture is fitted into width × size, left of the
// title. Tasks set inside the box would start after that column, 21 mm in, so the '- [ ]'
// items follow the box, where they print the default task box, '☐'.
const [STRIP, KIT] = [5, 30 / 8]; // mm: the strip's height; the drawing's width over height
const prep = { id: 'prep', backgroundEnabled: false, padding: NONE,
  marginTop: pt(LEAD), marginBottom: column.titleStyle.gap, // the tasks follow at this gap
  icon: { kind: 'resource', resourceId: 'kit', size: mm(STRIP), width: mm(STRIP * KIT),
    align: 'center' }, // the title centred on the strip
  titleStyle: { ...column.titleStyle, color: col('olive') } };

Врезка prep содержит только заголовок и значок, поэтому работает как шапка: width значка в 3,75 раза больше его size растягивает квадрат значка в полосу 18,75 × 5 мм, и три рисунка заполняют её слева от заголовка (стили врезок). Значок занимает свою колонку рядом со всем содержимым врезки, поэтому дела идут после неё: там они стоят вровень с тире продуктов, а не начинаются на 21 мм правее. Пункты - [ ] печатают стандартный флажок задачи, а unorderedLists.marginTop: 0 позволяет им идти за шапкой на расстоянии её marginBottom, 2,4 мм, как у заголовков колонок (маркированные списки).

#4 · Сделайте теги плашками

script.js · строки 80–82в полном коде
const chipStyles = [{ id: 'tag', fontSize: em(0.86), bold: true, background: col('tint'),
  borderWidth: pt(0), borderRadius: em(1), // no outline; a radius past half the height: a pill
  paddingX: em(0.7), paddingY: em(0.18), gap: em(0.3) }];

:chip[Vegetarian]{style="tag"} помещает слово в рамку, которая не разрывается между строками. borderRadius больше половины высоты рамки ограничивается этой половиной, и оба конца становятся полукругами; при borderWidth: 0 плашка рисуется одной подложкой. Высота рамки 11,4 пт, меньше интерлиньяжа карточки 12,8 пт, поэтому вторая строка тегов не коснулась бы первой (стили плашек).

#5 · Одно оформление, по фотографии на рецепт

script.js · строки 86–120в полном коде
const BAND = 104; // mm: the photo's foot; the pills sit 13 mm above it, the lead 6 mm below
const NOTE = { x: 18, y: 24, w: 70 }; // mm on the page: the box ends 2 mm before the arrow
const at = (x, y, size) => ({ anchor: { to: 'container', edge: 'top-left' },
  offset: { x: mm(x), y: mm(y - PAGE.top) }, size }); // y in mm from the top of the page
const text = (id, content, family, size, placement, extra) => ({ kind: 'text', id, content,
  fontFamily: family, fontSize: pt(size), color: col('ink'), align: 'left',
  overflow: 'wrap', placement, ...extra }); // a foot wraps too, where the default is '…'
const tracked = { fontWeight: 700, textTransform: 'uppercase', letterSpacing: pt(1.6) };
// Pills are text boxes chained right-of each other; each prints one heading attribute.
const pill = (id, after) => text(id, `{attr.${id}}`, TEXT, 8.4, after ? { anchor:
  { to: `#${after}`, edge: 'right-of' }, offset: { x: mm(1.8) } } : at(0, BAND - 13), {
  fontWeight: 600, box: { backgroundColor: col('card'), borderRadius: mm(3),
    padding: { top: mm(1.1), right: mm(2.8), bottom: mm(1.1), left: mm(2.8) } } });
// One heading style for every recipe; each heading names its photo: art="tortilla".
const opener = { id: 'receta', advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'art', resourceId: '{attr.art}', // filled in per heading, like a text
      placement: { anchor: { to: 'page', edge: 'top-left' },
        size: { width: mm(PAGE.w), height: mm(BAND) } } },
    { kind: 'image', id: 'arrow', resourceId: 'arrow', // the note's arrow, over the photo
      placement: { anchor: { to: 'page', edge: 'top-left' },
        size: { width: mm(PAGE.w), height: mm(BAND) } } },
    text('note', '{attr.note}', HAND, 19, { anchor: { to: 'page', edge: 'top-left' },
      offset: { x: mm(NOTE.x), y: mm(NOTE.y) }, size: { width: mm(NOTE.w) } },
    { fontWeight: 600, align: 'right' }), // on the page, like the arrow and the photo
    pill('time'), pill('level', 'time'), pill('season', 'level'),
    text('title', '{titleText}', DISPLAY, 42, { anchor: { to: '#time', edge: 'above' },
      offset: { y: mm(-3.2) }, size: { width: mm(96) } }, // two lines: the \\ in the heading
    { lineHeight: 1 }), // set solid: 42 pt from line to line
    text('kicker', '{attr.kicker}', TEXT, 8.2, { anchor: { to: '#title', edge: 'above' },
      offset: { y: mm(-2.4) }, size: { width: mm(96) } }, tracked),
    // The lead is the design's lowest element: the opener reserves down to its last line, and
    // the card starts under it without a minHeight.
    text('lead', '{attr.lead}', TEXT, 10.5, at(0, BAND + 6, { width: mm(122) }),
      { italic: true, lineHeight: 1.45 }),
  ] } } };

# Tortilla \\ de patatas {style="receta" art="tortilla" kicker="…" lead="…"} выбирает стиль заголовка и заполняет его слоты из атрибутов, в том числе курсивное вступление (атрибуты заголовков). resourceId элемента-изображения равен '{attr.art}', это подстановка, как в тексте, поэтому оба рецепта делят один стиль, а каждый заголовок называет свою фотографию (элементы-изображения). Каждая плашка привязана right-of к предыдущей, заголовок above к первой плашке, а надзаголовок к заголовку, поэтому заголовок подлиннее поднимает надзаголовок, а плашки остаются на своей линии. Вступление — нижний элемент оформления, поэтому начальная полоса занимает место до его последней строки, и карточка начинается под ним без minHeight. Пометка привязана к странице, как фотография и стрелка, второй элемент-изображение, нарисованный кодом, и на обеих страницах кончается в 2 мм от стрелки, хотя зеркальные поля сдвигают полосу набора на правой странице на 2 мм вправо.

#6 · Зарегистрируйте изображения как ресурсы

script.js · строки 271–293в полном коде
// The opener's image elements and both icons name a resource id; the resource names the file
// the canvas paints (loadImage or loadSvg registers it). No :ref cites them, so none is numbered.
const photo = (id, altText) => ({ id, typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  altText, bitmap: { fileId: `${id}-1520.jpg`, format: 'jpeg', width: 1520, height: 832 } });
const ART = { // markup, width and height in mm, and the alt text
  arrow: [arrow, PAGE.w, BAND, t({ en: 'An arrow to the dish', es: 'Una flecha al plato' })],
  cutlery: [cutlery, 6, 8, t({ en: 'Fork and knife', es: 'Tenedor y cuchillo' })],
  kit: [kit, 8 * KIT, 8, t({ en: 'A bowl with two eggs, a frying pan and a plate',
    es: 'Un bol con dos huevos, una sartén y un plato' })] };
const resources = [
  photo('tortilla', t({ en: 'A potato omelette with a slice pulled out, on a blue-rimmed plate '
    + 'and a red-checked napkin', es: 'Una tortilla de patatas con una porción separada, en un '
    + 'plato de borde azul sobre una servilleta de cuadros rojos' })),
  photo('gazpacho', t({ en: 'A bowl of gazpacho with diced vegetables and a spoon, on a '
    + 'blue-checked napkin beside a tomato', es: 'Un cuenco de gazpacho con dados de verdura '
    + 'y una cuchara, sobre una servilleta de cuadros azules junto a un tomate' })),
  ...Object.entries(ART).map(([id, [, w, h, altText]]) => ({ id, typeId: 'figure',
    kind: 'svg', createdAt: 0, updatedAt: 0, altText, svg: { fileId: `${id}.svg`, width: w * 10,
      height: h * 10 } })), // 10 px a millimetre: the sizes only set the aspect ratio here
];
const photos = resources.filter((r) => r.kind === 'bitmap').map((r) => r.bitmap.fileId);
await Promise.all([...photos.map((file) => loadImage(file, asset(file))),
  ...Object.entries(ART).map(([id, [svg]]) => loadSvg(`${id}.svg`, svg))]);

Два элемента-изображения начальной полосы, значок ярлыка и значок шапки списка дел называют каждый свой ресурс, а холст рисует файл, который зарегистрировали для него loadImage или loadSvg. Ни один :ref на эти ресурсы не ссылается, поэтому нумерованными рисунками они не становятся. Слов на изображениях нет: рукописные пометки — текст оформления поверх них.

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

Sandbox
// ═══ Postext Cookbook · Nº 033 · Recipe card: ingredients beside the method ═══════
// https://postext.dev/en/cookbook/recipe-card
// Code: MIT · Text: original (CC BY 4.0) · Photos: diffusion models · Pictograms: CC BY 4.0
// Fonts: Young Serif, Figtree, Caveat (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 = 'recipe-card';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#2b2118', muted: '#76634e', // text; folios and the colophon
  paper: '#f7eddb', card: '#fffdf8', // the cream page; the white recipe card on it
  tomato: '#bf3d29', olive: '#6b7a3a', tint: '#f6e3c1' }; // numbers and tab; dashes; tags
// Each colour names its palette entry and carries its hex.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the tomato, so nothing prints blue.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.tomato })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, HAND] = ['Figtree', 'Young Serif', 'Caveat'];
const PAGE = { w: 190, h: 250, top: 22, inner: 18, outer: 16 }; // mm, mirrored margins
const [BODY, LEAD] = [9.4, 12.8]; // pt: the text of the cards and the notes under them

// #region answer: a white card with a servings tab, two columns inside it
// In the Markdown, :::callout{type="card" label="SERVES 4"} holds a :::columns{count=2} group
// of two nested boxes, :::callout{type="column" title="Ingredients"} and one for the method.
// The group levels its columns by cutting between blocks or lines, so loose lists would run
// the method on under the ingredients. A nested box is one block that never splits, so the
// only cut left is between the two.
const TAB = 5.6; // mm: the tab's height, and how far it rises above the card
const card = { id: 'card', background: col('card'),
  padding: { top: mm(4.5), right: mm(6), bottom: mm(5), left: mm(6) },
  // No space of its own above: the tab starts on the first grid line under the opener.
  columnGap: mm(7), marginTop: mm(0),
  // label="…" on the fence prints here: a tab on the top-right corner, a cutlery pictogram
  // beside it and a rule from the far corner that makes the tab part of the card.
  label: { fontFamily: TEXT, fontSize: pt(8), color: col('card'), // bold by default
    background: col('tomato'), height: mm(TAB), offset: mm(TAB), paddingX: mm(2.6),
    icon: { resourceId: 'cutlery', width: mm(TAB * 6 / 8), gap: mm(1.6) }, // as tall as the tab
    rule: { enabled: true, color: col('tomato'), width: pt(1.2) } } };
// The two columns: frameless boxes whose only device is a tracked title.
const NONE = { top: mm(0), right: mm(0), bottom: mm(0), left: mm(0) };
const column = { id: 'column', backgroundEnabled: false, padding: NONE,
  lists: { gap: mm(2.2), itemSpacing: pt(3.5) }, // for the steps as well as the dashes
  titleStyle: { fontFamily: TEXT, fontSize: pt(8), color: col('tomato'), // bold by default
    textTransform: 'uppercase', letterSpacing: pt(1.5), gap: mm(2.4) } };
// config() plugs them in: calloutStyles: [card, column, prep].

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

Варианты

#Считать блоки вместо врезок в колонках

Без врезок колонок breaks называет элемент, который открывает правую колонку; каждый пункт списка, строка тегов и шапка списка дел считаются за один: гаспачо нужно breaks="10" (сначала восемь продуктов и теги), тортилье breaks="11". Вместе с врезками пропадают заголовки колонок и отступы между шагами, заданные стилем колонки.

 :::callout{type="card" label="SERVES 6"}
-:::columns{count=2}
-:::callout{type="column" title="Ingredients"}
+:::columns{count=2 breaks="10"}
 - **1.5 kg** ripe plum tomatoes
@@ seven more ingredients and a blank line @@
 :chip[Vegan]{style="tag"} :chip[No-cook]{style="tag"} :chip[Make ahead]{style="tag"}
-:::
-:::callout{type="column" title="Method"}
+
 1. Chop the tomatoes, seeded pepper, peeled cucumber and garlic.
@@ steps 2 to 5 @@
 :::
-:::
 :::

#Поставить ярлык в левый угол

'top-left' отражает ярлык: он переходит в левый угол, вилка и нож встают справа от него, а линейка идёт справа.

     background: col('tomato'), height: mm(TAB), offset: mm(TAB), paddingX: mm(2.6),
+    position: 'top-left', // 'top-right' by default

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

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

Номер списка центрирован по первой строке, а не стоит на базовой линии

Номер упорядоченного списка рисуется с базовой линией canvas 'middle', на 0,3 em текста выше первой базовой линии пункта; поэтому номер другого начертания или с большим numberFontSize растёт от неё вверх и вниз, а не стоит на строке: акцидентный шрифт уходит вверх, крупный номер шага свисает поперёк первой строки. Поставьте его через orderedLists.numberVerticalOffset и проверьте в полном размере. Номера содержания стоят на базовой линии начиная с postext 1.5; номера списков по-прежнему центрированы. Нумерованные списки →

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

lists.color врезки перекрашивает и номера списков

lists.color стиля врезки окрашивает и маркеры, и номера упорядоченных списков, когда стиль его задаёт: сделайте так маркеры оливковыми, и номера шагов тоже станут оливковыми. (До postext 1.4 включительно он доходил до номеров, только если отличался от unorderedLists.color.) Чтобы окрасить только маркеры, задайте unorderedLists.color для документа и не указывайте lists.color в стиле врезки: номера останутся в orderedLists.color. Врезки →

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

Плашки выше шага строк касаются следующей строки

Плашка, рамка которой выше шага строк, касается плашек следующей строки (предупреждение chipOverlap). Уменьшите её вертикальные внутренние отступы, обводку или кегль либо увеличьте интерлиньяж. Плашки в строке →

  • У ярлыка нет textTransform и letterSpacing, поэтому SERVES 4 и PARA 4 набраны в ограждениях прописными.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • The tortilla on its plate, a photograph · Generated With Diffusion Models · оригинал
  • The bowl of gazpacho, a photograph · Generated With Diffusion Models · оригинал
  • The note’s arrow and the pictograms, drawn in code in the page’s palette · Ignacio Ferro · CC BY 4.0
Шрифты
Young Serif (SIL OFL 1.1) · Figtree (SIL OFL 1.1) · Caveat (SIL OFL 1.1)
Sandbox