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

Рецепты · Глава 8 · Таблицы

Меню бистро: цены на позиции табуляции

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

На этой странице
  • Образец на английском: русского издания пока нет
  • Обрезной формат 230 × 310 мм
  • 1 колонка
  • Noticia Text 10,5/14,5
  • Josefin Sans
  • Limelight
  • 2 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 47 мс
  • Строк кода: 154

Коротко

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

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

Осенняя карта вымышленного парижского бистро Les Tanneurs: один лист 230 × 310 мм с печатью на двух сторонах. На лицевой стороне над названием, набранным Limelight, висит полосатый навес. Каждое название раздела стоит между двумя латунными линейками, идущими до полей, а под ним четыре блюда. Блюдо — это французское название полужирным с гарниром, под ним английская строка курсивом и цена полужирным с выключкой вправо. Тёмно-зелёный кружок V отмечает вегетарианские блюда, контурная плашка SG — блюда без глютена. Каждое блюдо занимает один абзац, и табуляция отправляет цену на позицию у правого поля. На обороте, под полкой с бутылками, стоит винная карта: цены бокала и бутылки в колонках 12 cl и 75 cl, таблица без линеек и без подписи.

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

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

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

script.js · строки 28–42в полном коде
// Each course is a :::paragraphs group in the dish style. Its one tab stop stands at the end of
// the measure and ends there the text after the tab, so `:tab **7**` sets the price flush right
// however long the dish is. A backslash at the end of the line breaks it: the dish and its
// translation are one paragraph, and the price shares the dish's first line.
const dish = { id: 'dish', name: 'Dish', textAlign: 'left', // the card is centred; a dish is not
  tabStops: [{ position: 'end', align: 'end' }],
  spaceBetween: pt(LEAD / 2), // half a line between two dishes: each dish 2½ lines of LEAD
  marginTop: pt(LEAD), // a line of air under the course head
  indent: pt(LEAD / 4), endIndent: pt(LEAD / 4) }; // in line with the wine list's cell text
// The wine list stays a table: its prices stand in two columns under the heads 12 cl and 75 cl.
// The document's tableStyle turns off every rule and fill (#region wines).
const tableStyle = { rules: 'none', cellPadding: pt(LEAD / 4), // a row: 1½ lines of LEAD
  bodyFontFamily: TEXT, bodyFontSize: pt(BODY), bodyColor: col('ink'),
  headerFontFamily: LABEL, headerFontSize: pt(8.5), headerColor: col('wine'),
  headerBackgroundEnabled: false }; // header cells: the wine list's labels

Ингредиенты

Шрифты
Limelight, Noticia Text, Josefin Sans (SIL OFL 1.1)
Материалы
  • The awning and the shelf of bottles, drawn in code in the page's palette (Ignacio Ferro, CC BY 4.0)

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

#1 · Поставьте позицию табуляции там, где нужна цена

Код приведён выше, в коротком ответе. Каждый раздел меню — группа :::paragraphs{style="dish"}, по абзацу на блюдо (стили абзацев). В стиле блюда одна позиция табуляции, 'end', то есть конец строки, с align: 'end': текст после табуляции заканчивается на этой позиции. Поэтому :tab **7** после гарнира и значков выключает цену вправо при любой длине блюда (табуляция и её позиции). :tab поглощает пробелы вокруг себя, а обратная косая черта в конце строки — принудительный перевод строки: английская строка курсивом начинает вторую строку того же абзаца, а цена остаётся на первой. spaceBetween ставит между блюдами полстроки, так что блюдо занимает две с половиной строки интерлиньяжа 14,5 пт. indent и endIndent в четверть строки выравнивают блюда по тексту в ячейках винной карты на обороте. Абзац с табуляцией набирается построчно; здесь все строки и так флаговые.

#2 · Один тип ресурса: на своём месте и без номера

script.js · строки 46–53в полном коде
// No caption prefix and no caption, so no 'Table 1' line prints under the wine list. Placement
// 'here' sets each piece at its ::resource line; a list that outgrows the page is cut
// between rows and goes on at the head of the next one.
const resourceTypes = [{ id: 'menu', name: 'Menu', shortLabel: 'Menu', captionPrefix: '',
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { position: 'here' } }];
const piece = (id, kind, body) => ({ id, typeId: 'menu', kind, createdAt: 0, updatedAt: 0,
  ...body });

Встроенные типы рисунка и таблицы печатают строку подписи и выносят каждый ресурс в первое свободное место после первой ссылки. У типа menu нет префикса подписи, а у его объектов нет подписей, поэтому под рисунками и винной картой ничего не печатается. Задайте captionPrefix: 'Menu', и под каждым объектом, начиная с «Menu 1.» под навесом, появится нумерованная строка, а карта вырастет до четырёх страниц. defaultPlacement ставит винную карту и каждый рисунок на место их строки ::resource (встраивание блоком). Без неё винная карта уходит в низ оборота, под Le Comptoir и колофон. Навес и бутылки — SVG-ресурсы того же типа, нарисованные в коде и зарегистрированные функцией loadSvg из набора.

#3 · Объедините строки регионов

script.js · строки 57–70в полном коде
function wineList(tsv) {
  let m = { ...parseTSV(tsv, { headerRows: 1 }), columnWidths: [5, 1, 1] }; // the head row
  m.rows = m.rows.map((row, r) => row.map((cell, c) => (c === 0 ? cell : { ...cell, align: 'right',
    content: r > 0 && cell.content ? `**${cell.content}**` : cell.content }))); // as the dishes'
  m.rows.forEach(([first, ...rest], r) => { // a line with one field names a region
    if (r === 0 || !first.content || rest.some((cell) => cell.content)) return;
    // One cell across the table, centred on the card like the course heads; a label centred
    // in the first column alone would sit 22.6 mm left of them. The label face is the header's.
    m.rows[r][0] = { ...first, isHeader: true, align: 'center' };
    // mergeCells marks the two cells it covers hiddenBy (gotcha: merged-cells-hiddenby).
    m = mergeCells(m, { start: { row: r, col: 0 }, end: { row: r, col: 2 } });
  });
  return piece('wines', 'table', { table: { model: m } });
}

Винная карта остаётся таблицей: две цены стоят в колонках под заголовками 12 cl и 75 cl, а ряд позиций табуляции оставил бы их без заголовков. parseTSV(tsv, { headerRows: 1 }) читает первую строку как строку заголовков, поэтому Appellation · cépage, 12 cl и 75 cl печатаются над своими колонками шрифтом заголовков, Josefin Sans. Строка с одним полем называет регион. Её ячейка становится центрированной ячейкой заголовка, а mergeCells растягивает её на три колонки и помечает две закрытые ячейки как hiddenBy (построение моделей таблиц). Если центрировать BLANCS только в первой колонке, слово окажется на 22,6 мм левее оси, по которой стоят La Cave и Le Comptoir. Пустая строка TSV становится рядом пустых ячеек высотой в полторы строки: это и есть отбивка над Blancs и Rouges.

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

script.js · строки 74–88в полном коде
// The title has no width, so it shrink-wraps its text, and 'top' centres it on the column. Each
// rule hangs off one edge of the title ('left-of', 'right-of'), 4 mm away, and 'fill' runs it
// to the column's edge: 66.7 mm beside PLATS, 56.2 mm beside the longer LE COMPTOIR.
const rule = (edge, x) => ({ kind: 'rule', id: `rule-${edge}`, color: col('brass'),
  thickness: pt(0.75), // heavier than the default 0.5 pt hairline
  placement: { anchor: { to: '#title', edge },
    size: { width: 'fill' }, // to the column's edge
    offset: { x: mm(x), y: pt(6) } } }); // 6 pt down: the middle of Limelight's capitals
const courseHead = { enabled: true, slot: { elements: [
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(15),
    lineHeight: 0.96, // 14.4 pt: the title stays inside one 14.5 pt grid line
    textTransform: 'uppercase', color: col('wine'),
    placement: { anchor: { to: 'container', edge: 'top' } } },
  rule('left-of', -4), rule('right-of', 4),
] } };

Название раздела — оформление в колонке. У элемента {titleText} ширина не задана, поэтому его рамка равна ширине прописных, а якорь 'top' ставит её по центру колонки. Каждая линейка отходит от своего края названия через 'left-of' или 'right-of' и заполняет место до края колонки (размещение элементов): рядом с PLATS линейки длиной 66,7 мм, рядом с LE COMPTOIR — 56,2 мм, и от букв их отделяют 4 мм. lineHeight названия задан множителем 0,96: рамка получает 14,4 пт и умещается в одну линию сетки 14,5 пт. При 1 рамка равна 15 пт, каждое название занимает две строки, и карта вырастает до четырёх страниц.

#5 · Значки плашками, мелкий текст стилями абзацев

script.js · строки 92–110в полном коде
// A chip is a box around inline text: the V disc is filled, the SG pill only outlined. A chip
// takes the weight of the text around it, so without bold the V is set in 400, a weight not loaded.
const badge = { fontFamily: LABEL, fontSize: pt(7.5), bold: true, // Josefin Sans 700
  borderRadius: pt(8), paddingY: em(0.1), gap: em(0.6) }; // radius clamped to a half-height
const chipStyles = [
  // V: paddingX makes the box as wide as it is tall, a disc. borderWidth 0 removes the default
  // outline, 0.5 pt of main-color, which would ring the green in wine red.
  { id: 'veg', name: 'Vegetarian', ...badge, paddingX: em(0.3), borderWidth: pt(0),
    background: col('bottle'), color: col('paper') },
  { id: 'gf', name: 'Gluten-free', ...badge, paddingX: em(0.45), backgroundEnabled: false,
    borderColor: col('bottle'), borderWidth: pt(0.6), color: col('bottle') },
];
// The notes under the desserts and the colophon on the back: smaller, on the card's axis, a
// line of air above each.
const paragraphStyles = [dish,
  { id: 'notes', name: 'Notes', fontSize: pt(9), marginTop: pt(LEAD) },
  { id: 'colophon', name: 'Colophon', fontSize: pt(7.5), color: col('muted'),
    marginTop: pt(LEAD) },
];

Плашка рисует рамку вокруг фрагмента текста в строке (стили плашек), поэтому :chip[V]{style="veg"} после гарнира ставит кружок на французскую строку блюда, перед табуляцией. В стилях плашек задано bold: true: плашка берёт насыщенность окружающего текста, после гарнира это 400, а FONTS загружает Josefin Sans только в 700. Примечания под десертами и колофон на обороте — блоки :::paragraphs кеглем 9 и 7,5 пт, и у обоих стилей marginTop в одну строку (стили абзацев). Без этого отступа примечания начинаются сразу после английской строки сырной тарелки, будто относятся к этому блюду.

#6 · Выровняйте карту по одной оси

script.js · строки 114–126в полном коде
// bodyText (in config) centres the lines under the name and the notes; only the dishes and the
// wine list keep a left edge. Ragged text is hyphenated only with bodyText.hyphenation.ragged,
// so no word on this card is divided, the French dish names included. The config's locale
// names each edition's language, English or Spanish, for the bundle the Sandbox opens.
const headings = { fontFamily: DISPLAY, fontWeight: 400, color: col('wine'), textAlign: 'center',
  levels: [ // Limelight ships one weight, 400, and no italic
    // The H1 break is off: by default an H1 opens a recto, which would part the name from the
    // awning and La Cave from its bottles.
    { level: 1, fontSize: pt(48), lineHeight: pt(3 * LEAD), breakBefore: { enabled: false },
      marginTop: pt(LEAD), marginBottom: pt(0) }, // three grid lines, one of air above
    { level: 2, lineHeight: pt(LEAD), advancedDesign: courseHead, // one line; #region heads
      marginTop: pt(LEAD), marginBottom: pt(0) }, // the dishes below add a line of their own
  ] };

headings.textAlign и bodyText.textAlign ставят на среднюю линию карты всё, кроме блюд и винной карты. lineHeight: pt(3 * LEAD) отводит названию кеглем 48 пт три линии сетки. Без этого название берёт интерлиньяж по умолчанию и четыре строки, вторая строка примечаний уходит на отдельную страницу, и карта вырастает до четырёх страниц. На уровне 1 разрыв перед H1 отключён, breakBefore: { enabled: false }, потому что название и La Cave стоят на странице рисунка над ними. Оставьте значение по умолчанию, { enabled: true, parity: 'always-odd' }, и каждый рисунок займёт отдельную страницу, всего их будет семь. locale в конфигурации не задана: выключки по формату на карте нет, а флаговый текст переносится только при включённом bodyText.hyphenation.ragged.

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

Sandbox
// ═══ Postext Cookbook · Nº 052 · Bistro menu: prices on a tab stop ═══════════════════
// https://postext.dev/en/cookbook/bistro-menu
// Code: MIT · Text: original, in French (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: Limelight, Noticia Text, Josefin Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
// The autumn menu of an imaginary Paris bistro: two sides of one card, each dish a paragraph
// whose price a tab sends to the right margin, the wine list a table with no rules.
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage, parseTSV,
  mergeCells,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'bistro-menu';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#1f2a24', paper: '#f6efdf', // green-black text on cream card
  wine: '#6d1f2c', brass: '#a9823a', // the name, heads and labels; rules and the drawings' metal
  straw: '#e8d4a8', bottle: '#2f4235', sage: '#8a9a78', // awning stripes and labels; glass
  muted: '#6b6457' }; // the colophon
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color' (#295aa3, a blue); this palette makes it the wine red.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.wine })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, LABEL] = ['Noticia Text', 'Limelight', 'Josefin Sans'];
const [BODY, LEAD] = [10.5, 14.5]; // pt: the text, and the leading every table row keeps

// #region answer: dish on the left, price flush right: a tab stop at the end of the measure
// Each course is a :::paragraphs group in the dish style. Its one tab stop stands at the end of
// the measure and ends there the text after the tab, so `:tab **7**` sets the price flush right
// however long the dish is. A backslash at the end of the line breaks it: the dish and its
// translation are one paragraph, and the price shares the dish's first line.
const dish = { id: 'dish', name: 'Dish', textAlign: 'left', // the card is centred; a dish is not
  tabStops: [{ position: 'end', align: 'end' }],
  spaceBetween: pt(LEAD / 2), // half a line between two dishes: each dish 2½ lines of LEAD
  marginTop: pt(LEAD), // a line of air under the course head
  indent: pt(LEAD / 4), endIndent: pt(LEAD / 4) }; // in line with the wine list's cell text
// The wine list stays a table: its prices stand in two columns under the heads 12 cl and 75 cl.
// The document's tableStyle turns off every rule and fill (#region wines).
const tableStyle = { rules: 'none', cellPadding: pt(LEAD / 4), // a row: 1½ lines of LEAD
  bodyFontFamily: TEXT, bodyFontSize: pt(BODY), bodyColor: col('ink'),
  headerFontFamily: LABEL, headerFontSize: pt(8.5), headerColor: col('wine'),
  headerBackgroundEnabled: false }; // header cells: the wine list's labels
// #endregion

// #region type: one resource type for the whole card: set where it stands, never numbered
// No caption prefix and no caption, so no 'Table 1' line prints under the wine list. Placement
// 'here' sets each piece at its ::resource line; a list that outgrows the page is cut
// between rows and goes on at the head of the next one.

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

Варианты

#Ограничьте длину линеек

Фиксированная ширина вместо 'fill' оставляет каждой линейке 20 мм длины и 4 мм от названия, поэтому рядом с PLATS пара стоит ближе к центру, чем рядом с LE COMPTOIR.

-    size: { width: 'fill' }, // to the column's edge
+    size: { width: mm(20) }, // 20 mm, wherever the title ends

#Протяните отточие до цены

Отточие заполняет место перед позицией табуляции. '. ' повторяет точку с пробелом: от половины em после последнего значка или слова блюда до половины em перед ценой.

-  tabStops: [{ position: 'end', align: 'end' }],
+  tabStops: [{ position: 'end', align: 'end', leader: '. ' }],

#Разлинуйте винную карту как счётную книгу

rules: 'horizontal' проводит латунную волосяную линейку 0,5 пт над каждой строкой винной карты и под ней. Линейки не занимают места, поэтому вёрстка обеих сторон сохраняется, а пустые строки над Blancs и Rouges получают собственную пару линеек.

-const tableStyle = { rules: 'none', cellPadding: pt(LEAD / 4), // a row: 1½ lines of LEAD
+const tableStyle = { rules: 'horizontal', borderColor: col('brass'),
+  borderWidth: pt(0.5), cellPadding: pt(LEAD / 4),

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

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

Объединённым ячейкам нужны заглушки hiddenBy: берите mergeCells

Ячейки верстаются по позиции в массиве строки, поэтому объединённой ячейке нужны ячейки-заглушки с hiddenBy там, куда она простирается; если их пропустить, как в HTML, все следующие колонки сдвинутся. Объединяйте через mergeCells. Начиная с postext 1.5 таблица с неровной сеткой попадает в doc.contentWarnings как raggedTableGrid, а parseTSV(text, { headerRows }) помечает строки шапки. Таблицы из данных →

Оставьте место для цены на первой строке блюда. Когда блюдо с гарниром заходят туда, где нужна цена, табуляция переносит последнее слово блюда на следующую строку вместе с ценой, а английская строка идёт за ними. Блюдо занимает три строки, и раздел заканчивается на строку ниже.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • The awning and the shelf of bottles, drawn in code in the page's palette · Ignacio Ferro · CC BY 4.0
Шрифты
Limelight (SIL OFL 1.1) · Noticia Text (SIL OFL 1.1) · Josefin Sans (SIL OFL 1.1)
Sandbox