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

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

Каталог почтовой торговли с картинками в ячейках

Каталог семян, где прайс-лист — таблица из TSV: в ячейке каждого сорта рисованный пакетик, а список делится на две полосы разворота.

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

с. 2–3 из 4

  • Образец на английском: русского издания пока нет
  • Обрезной формат 190 × 250 мм
  • 2 колонки, средник 7 мм
  • Gelasio 9,5/13
  • Alfa Slab One
  • Cabin Condensed
  • 4 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 66 мс
  • Строк кода: 227

Коротко

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

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

Весенний прайс-лист Brindlewood Seed Co., вымышленного семенного хозяйства, — тетрадь из четырёх полос на палевой бумаге. На обложке Spring Seeds набрано Alfa Slab One над картиной с подсолнухом и томатом, ниже письмо садоводам в две колонки. Полосы 2 и 3 занимает список. Вверху ячейки каждого сорта — рисунок его пакетика, под ним название, а виды овощей идут вниз по объединённой первой колонке. Цены стоят у правого края узким шрифтом меток, а красные и зелёные плашки отмечают новинки и органические семена. Список прерывается после перца для жарки и продолжается на соседней полосе под той же красной полосой цвета с пометкой (continued). Последняя полоса — бланк заказа, две скруглённые сетки с пустыми строками для записи.

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

  • Как вставить иллюстрации или значки в ячейки таблицы?
  • Как разделить длинную таблицу между страницами с повтором шапки и пометкой «Продолжение»?
  • Как оформить несколько таблиц по-разному (заливки, чередование ячеек, скруглённые рамки) в одном документе?
  • Как сделать таблицу с шапкой, объединёнными ячейками, шириной колонок и выключкой по ячейкам?

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

script.js · строки 44–78в полном коде
const at = (row, c) => ({ row, col: c });
const slug = (name) => name.toLowerCase().replace(/\W+/g, '-'); // 'Gold Medal' → 'gold-medal'
function priceList(tsv) { // Kind · Variety · Description · Packet · Ounce, under one head row
  let m = { ...parseTSV(tsv, { headerRows: 1 }), columnWidths: [20, 40, 63, 17, 17] }; // mm
  for (const c of [0, 1]) m = setAlignment(m, at(0, c), 'center'); // each head over its column
  for (const c of [3, 4]) m = setAlignment(m, at(0, c), 'right');
  for (let r = 1; r < m.rows.length; r++) {
    // The picture is a resource of its own; the cell sets it at the top, centred, with the
    // variety's name under it, and the row grows to hold both.
    const variety = m.rows[r][1].content;
    m = setCellImage(m, at(r, 1), { resourceId: slug(variety), width: PACKET });
    m = setCellContent(m, at(r, 1), `**${variety}**`);
    m = setAlignment(m, at(r, 1), 'center');
    for (const c of [3, 4]) { // prices in the label face: lining figures, flush right
      m = setCellContent(m, at(r, c), `:chip[$${m.rows[r][c].content}]{style="price"}`);
      m = setAlignment(m, at(r, c), 'right');
    }
    if (!m.rows[r][0].content) continue; // an empty Kind goes on with the one above
    let end = r;
    while (m.rows[end + 1] && !m.rows[end + 1][0].content) end++;
    // One cell down the rows of its kind; mergeCells leaves the covered cells in the grid,
    // marked hiddenBy (gotcha: merged-cells-hiddenby). A split never cuts through it.
    m = mergeCells(m, { start: at(r, 0), end: at(end, 0) });
    m = setAlignment(m, at(r, 0), 'center', 'middle');
    m = setCellBackground(m, at(r, 0), col('cream'));
  }
  return m;
}
// The letter on page 1 cites the list, so it floats to the first free slot after the
// letter, page 2, and is cut between rows where the page ends; span 'page' gives it the
// full 157 mm, not a 75 mm column.
const vegetableList = (tsv) => ({ id: 'vegetables', typeId: 'list', kind: 'table',
  caption: '**Vegetable Seeds**', placement: { span: 'page' },
  note: 'A packet holds about 30 tomato or pepper seeds, 40 beans or 12 squash seeds.',
  table: { model: priceList(tsv) }, createdAt: 0, updatedAt: 0 });

Ингредиенты

Возможности
Иллюстрации в ячейках таблицТаблицы на нескольких страницахТаблицы из данныхИменованные стили таблицСтиль таблицЗаливка ячеекСтиль подписейПлашки в строкеСобственные типы ресурсовРисунки и таблицы как ресурсыРазмещение рисунковСсылки, которые размещают рисункиСтили заголовковАтрибуты заголовковОформленные начальные полосыИллюстрации в дизайне страницыОбложки, титулы и колофоныКолонтитулы и колонцифрыЦвет бумагиСемантическая палитра
Шрифты
Gelasio, Alfa Slab One, Cabin Condensed (SIL OFL 1.1)
Материалы
  • amish-paste-360.jpg
  • black-beauty-360.jpg
  • brandywine-360.jpg
  • cherokee-purple-360.jpg
  • cover-1500.jpg
  • dragon-tongue-360.jpg
  • gold-medal-360.jpg
  • jimmy-nardello-360.jpg
  • kentucky-wonder-360.jpg
  • waltham-butternut-360.jpg
  • The cover's sunflower and tomato plant, a painting (Generated With Diffusion Models, оригинал)
  • The Brandywine seed packet (Generated With Diffusion Models, оригинал)
  • The Cherokee Purple seed packet (Generated With Diffusion Models, оригинал)
  • The Gold Medal seed packet (Generated With Diffusion Models, оригинал)
  • The Amish Paste seed packet (Generated With Diffusion Models, оригинал)
  • The Jimmy Nardello seed packet (Generated With Diffusion Models, оригинал)
  • The Kentucky Wonder seed packet (Generated With Diffusion Models, оригинал)
  • The Dragon Tongue seed packet (Generated With Diffusion Models, оригинал)
  • The Black Beauty seed packet (Generated With Diffusion Models, оригинал)
  • The Waltham Butternut seed packet (Generated With Diffusion Models, оригинал)

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

#1 · Добавьте то, чего нет в TSV

Код — в разделе Короткий ответ выше. В TSV только слова и цены. setCellImage ставит пакетик каждого сорта, ресурс с именем этого сорта, вверх его ячейки на 55 % внутренней ширины, так что название оказывается под картинкой 20,3 × 27,1 мм, а каждая строка вырастает до 36 мм. mergeCells протягивает каждый вид вдоль первой колонки и помечает закрытые им ячейки hiddenBy. У ячеек тела таблицы одна гарнитура, здесь Gelasio, поэтому каждая цена — плашка без заливки, рамки и боковых отступов, набранная жирным Cabin Condensed в 1,12 em ради его маюскульных цифр.

#2 · Сошлитесь на список и разделите его на разворот

script.js · строки 82–98в полном коде
const tableStyle = { bodyFontSize: pt(9), headerFontFamily: LABEL, // body cells in Gelasio
  headerFontSize: pt(7.5), headerColor: col('paper'), headerBackground: col('ink'),
  rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5), cellPadding: mm(1.5),
  // 'split' is the default, written out as the key to change: 'clip' keeps the rows that fit
  // page 2 and drops the rest, 'hide' drops the whole list. Suffix and marker label the parts.
  overflow: 'split', continuedSuffix: '(continued)',
  continuesMarker: 'Continued on the facing page' };
const tableStyles = [{ id: 'form', rules: 'grid', borderRadius: mm(2.5), // a card to write on
  borderColor: col('muted'), borderWidth: pt(0.6), headerBackground: col('basil'),
  bodyFontFamily: LABEL, bodyFontSize: pt(8.5),
  bodyBackgroundEnabled: true, bodyBackground: col('cream'), cellPadding: mm(1.6) }];
// The caption sits above the table on a tomato band and is repeated on every part. Its note
// and the marker take the caption's face, so the caption keeps the body's Gelasio, which has
// the italic the suffix and the marker are set in; Cabin Condensed has none.
const captionStyle = { fontSize: pt(12), color: col('cream'),
  position: 'above', backgroundEnabled: true, background: col('tomato'), padding: mm(2),
  gap: mm(0), note: { fontSize: pt(7.8), color: col('muted') } };

Письмо на полосе 1 ссылается на список через :ref{id="vegetables" text="the price list"}, и text печатает эти слова вместо номера. Таблица, на которую сослались, выносится на первое свободное место после ссылки, здесь вверх полосы 2. Там список не помещается, поэтому движок разрезает его между строками после Jimmy Nardello, но никогда внутри объединённого вида. Полоса 3 повторяет строку заголовков и полосу цвета подписи с суффиксом; маркер идёт под первой частью, примечание под последней (таблицы выше страницы). parseTSV(tsv, { headerRows: 1 }) делает первую строку строкой заголовков: её так и красят, и она повторяется на полосе 3. Суффикс и маркер набраны курсивом и берут гарнитуру подписи, поэтому полоса остаётся в Gelasio: у Cabin Condensed курсива нет.

#3 · Ресурс для каждого пакетика

script.js · строки 272–284в полном коде
// Nothing cites the pictures, so none is numbered or placed: the cover design and the cells
// draw them by id, and their typeId is never looked up.
const picture = (id, fileId, [w, h], altText) => ({ id, typeId: 'figure', kind: 'bitmap',
  altText, bitmap: { fileId, format: 'jpeg', width: w, height: h }, createdAt: 0, updatedAt: 0 });
const varieties = parseTSV(list).rows.slice(1).map((row) => row[1].content);
const resources = [vegetableList(list), shipTo, orderForm,
  picture('cover-art', 'cover-1500.jpg', [1500, 1040], // the cover's 150 × 104 mm
    'A sunflower and a staked tomato plant in a ploughed field.'),
  ...varieties.map((name) => picture(slug(name), `${slug(name)}-360.jpg`, [360, 480], // 3 : 4
    `Seed packet of ${name}.`))];
await prepareFonts(markdown + list, config(), kitFonts(FONTS));
await Promise.all(resources.flatMap(({ bitmap }) => bitmap
  ? [loadImage(bitmap.fileId, asset(bitmap.fileId))] : []));

Изображение в ячейке называет ресурс по id, поэтому каждый пакетик — отдельный растровый ресурс, JPEG 360 × 480 px, обрезанный под пропорции пакетика 3 : 4, а loadImage из набора регистрирует его под fileId через registerResourceImage. На пакетики никто не ссылается, поэтому ни один не получает номера и не ставится вне своей ячейки. Букв на рисунках нет: название набрано текстом ячейки, шрифтами страницы.

#4 · Второй стиль таблицы для бланка заказа

script.js · строки 241–260в полном коде
function form(id, widths, rows, merges, note) { // an empty cell still takes a line's height
  let m = { headerRowCount: 1, columnWidths: widths, rows: rows.map((row, r) =>
    widths.map((_, c) => ({ content: row[c] ?? '', isHeader: r === 0 }))) };
  for (const [r, c0, c1] of merges) m = mergeCells(m, { start: at(r, c0), end: at(r, c1) });
  m.rows.forEach((row, r) => row.forEach((cell, c) => { // a label takes the paper's buff
    if (r === 0 || !cell.content || cell.hiddenBy) return;
    m = setCellBackground(m, at(r, c), col('paper'));
    if (cell.colSpan > 1) m = setAlignment(m, at(r, c), 'right'); // the totals' labels
  }));
  return { id, typeId: 'list', kind: 'table', note, placement: { position: 'here' },
    table: { model: m, styleId: 'form' }, createdAt: 0, updatedAt: 0 };
}
const shipTo = form('ship-to', [24, 60, 24, 49], [['Ship to'], ['Name'], ['Street or box'],
  ['Town', '', 'State and ZIP']], [[0, 0, 3], [1, 1, 3], [2, 1, 3]]);
const lines = Array.from({ length: 11 }, () => []); // eleven varieties to a sheet
const orderForm = form('order', [16, 73, 20, 20, 28], [['No.', 'Variety', 'Packets', 'Ounces',
  'Amount'], ...lines, ['Seeds total'], ['Postage: free on orders of $40 or more, otherwise $4.50'],
['**Total enclosed**']], [1, 2, 3].map((k) => [lines.length + k, 0, 3]),
'We guarantee every packet to grow. If a variety fails to come up in your garden, write to '
  + 'us before August 1 and we will send a new packet or refund what you paid for it.');

Обе сетки берут именованный стиль form: линейки сеткой, радиус 2,5 мм у внешней рамки и кремовая заливка, чтобы писать по ней. Прайс-лист сохраняет tableStyle документа (именованные стили таблиц). Пустой ячейке заполнитель не нужен: её строка всё равно занимает строку текста, здесь 7,3 мм. Каждый итог объединяет четыре колонки в одну метку у правого края. Стиль заголовка бланка переводит полосу 4 на одну колонку, поэтому обе сетки занимают полную ширину 157 мм.

#5 · Удержите письмо под картиной

script.js · строки 115–137в полном коде
const ART = { w: 150, h: 104, y: 60 }; // mm: the cover painting, and its top on the page
const FRAME = 8; // mm: the cover's frame, in from the trim
const AIR = 10; // mm: at least this much between the painting and the letter
const SINK = Math.ceil((ART.y + ART.h + AIR - MARGIN.top) / (LEAD * 25.4 / 72)); // lines
const cover = { id: 'cover', span: 'page', footer: { elements: [] },
  // The opener reserves down to the painting's foot; minHeight is a floor AIR lower, on the
  // grid. The frame reaches the page's foot, so it stays out of that count: reserve: false
  // (gotcha: opener-reserves-anchored).
  advancedDesign: { enabled: true, minHeight: pt(SINK * LEAD), slot: { elements: [
    { kind: 'box', id: 'frame', reserve: false,
      style: { borderColor: col('basil'), borderWidth: pt(1.2) },
      placement: on('page', 'top-left', FRAME, FRAME,
        { width: mm(TRIM.w - 2 * FRAME), height: mm(TRIM.h - 2 * FRAME) }) },
    text('publisher', '{title}', on('page', 'top', 0, 17), { ...caps(9.5), color: col('basil') }),
    text('title', '{titleText}', on('page', 'top', 0, 23), { fontFamily: DISPLAY,
      fontSize: pt(58), lineHeight: 1, color: col('tomato') }),
    text('issue', '{subtitle}', on('page', 'top', 0, 49), { ...caps(8.5, 700), color: col('ink'),
      box: { backgroundColor: col('sun'), padding: { top: mm(1.3), bottom: mm(1.1),
        left: mm(4), right: mm(4) } } }),
    { kind: 'image', id: 'art', resourceId: 'cover-art',
      placement: on('page', 'top', 0, ART.y, { width: mm(ART.w) }) },
  ] } },
};

Обложка резервирует место до низа своей картины, 164 мм от верха страницы, и без minHeight письмо началось бы с первой строки сетки под ней, вплотную к земле. minHeight — нижний предел, заданный чуть ниже: SINK добавляет 10 мм воздуха под картиной и округляет глубину от верхнего поля до целого числа строк по 13 пт, до 34, поэтому обе колонки письма начинаются на сетке, 177,9 мм от верха страницы. Рамка обложки доходит до низа страницы; reserve: false исключает её из этого расчёта.

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

Sandbox
// ═══ Postext Cookbook · Nº 036 · Mail-order catalogue with pictures in cells ═══════
// https://postext.dev/en/cookbook/seed-catalogue
// Code: MIT · Text: original (CC BY 4.0) · Pictures: diffusion models
// Fonts: Gelasio, Alfa Slab One, Cabin Condensed (SIL OFL 1.1) · Needs postext ≥ 1.25.0
// A fictional seed farm's spring list: a table read from TSV, a packet pictured in each row.
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage, parseTSV,
  mergeCells, setAlignment, setCellBackground, setCellContent, setCellImage,
} from 'https://esm.sh/postext';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // eight named colours; every colour in the config links to one of them
  ink: '#2d2620', paper: '#f0e2c4', // brown-black text on buff
  cream: '#fcf7ea', tomato: '#c23b22', // cells to write in; the accent: bands, titles, NEW
  basil: '#2f6b3b', sun: '#e8b53a', // rules, ORGANIC, the form's head; the cover's banner
  rule: '#c7ae86', muted: '#6d5f50', // hairlines; running heads and notes
};
// col() links a colour to its palette entry; the hex is the value the entry holds.
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' } }));

const TRIM = { w: 190, h: 250 }; // mm: a stapled mail-order booklet
const MARGIN = { top: 22, bottom: 20, inner: 18, outer: 15 }; // mm, mirrored: 157 mm wide
const LEAD = 13; // pt: the body leading, the grid the headings keep to
const TEXT = 'Gelasio', DISPLAY = 'Alfa Slab One', LABEL = 'Cabin Condensed';
const PACKET = 0.55; // the packet picture's share of its cell's inner width
const caps = (size, fontWeight = 600) => ({ fontFamily: LABEL, fontSize: pt(size), fontWeight,
  letterSpacing: pt(size * 0.18), textTransform: 'uppercase' });
const on = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, placement, style) => ({ kind: 'text', id, content, placement,
  overflow: 'wrap', ...style }); // a long line takes a second one, in the heads too
const chip = (id, size, ink, box) => ({ id, fontFamily: LABEL, bold: true, fontSize: em(size),
  color: col(ink), borderRadius: pt(1.2), ...box });
const rule = (id, below, gap, thickness) => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(thickness), color: col('basil'),
  placement: { ...on(`#${below}`, 'below', 0, gap), size: { width: 'fill' } } });

// #region answer: a price list from TSV: a packet in each variety's cell, kinds merged down
const at = (row, c) => ({ row, col: c });
const slug = (name) => name.toLowerCase().replace(/\W+/g, '-'); // 'Gold Medal' → 'gold-medal'
function priceList(tsv) { // Kind · Variety · Description · Packet · Ounce, under one head row
  let m = { ...parseTSV(tsv, { headerRows: 1 }), columnWidths: [20, 40, 63, 17, 17] }; // mm
  for (const c of [0, 1]) m = setAlignment(m, at(0, c), 'center'); // each head over its column

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

Варианты

#Оставьте только то, что помещается

При overflow: 'clip' список останавливается после пяти сортов, поместившихся на полосе 2, с примечанием под ними, а на полосе 3 остаются только заметки с опытного участка, в первой колонке.

-  overflow: 'split', continuedSuffix: '(continued)',
+  overflow: 'clip', continuedSuffix: '(continued)',

#Уменьшите пакетики

При 40 % строки сжимаются до 29 мм, но две фасоли стоят в объединённой ячейке, и вместе им нужно 57 мм, больше 44 мм, оставшихся на полосе 2. На это место поднимаются заметки с опытного участка, а на полосе 3 остаётся только конец списка, и ниже 157 мм она пуста.

-const PACKET = 0.55; // the packet picture's share of its cell's inner width
+const PACKET = 0.4; // the packet picture's share of its cell's inner width

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

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

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

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

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

Начальная полоса резервирует высоту до самого нижнего элемента, привязанного к странице

Начальная полоса с расширенным оформлением резервирует высоту своего самого нижнего элемента, причём элементы под заголовком, привязанные к странице или вылету, тоже считаются: декор внизу страницы выталкивает текст на следующую. Дайте такому элементу reserve: false (начиная с postext 1.5): он рисуется на месте привязки и ничего не резервирует. Элементы, которые следуют за самой областью заголовка (привязаны к её низу или имеют высоту 'fill'), её высоту не определяют. Оформленные начальные полосы →

  • Ресурс, на который никто не ссылается, не ставится никогда. Уберите :ref из письма, и в каталоге не будет прайс-листа.
  • В колонках 75 мм алгоритм Кнута–Пласса может оставить строку с пробелами шире maxWordSpacing; bodyText.maxJustifyTracking позволяет такой строке взять вместо этого немного трекинга. Здесь письмо и заметки с опытного участка правили, пока пробелы самой разреженной строки не стали в 1,33 раза шире обычных.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • The cover's sunflower and tomato plant, a painting · Generated With Diffusion Models · оригинал
  • The Brandywine seed packet · Generated With Diffusion Models · оригинал
  • The Cherokee Purple seed packet · Generated With Diffusion Models · оригинал
  • The Gold Medal seed packet · Generated With Diffusion Models · оригинал
  • The Amish Paste seed packet · Generated With Diffusion Models · оригинал
  • The Jimmy Nardello seed packet · Generated With Diffusion Models · оригинал
  • The Kentucky Wonder seed packet · Generated With Diffusion Models · оригинал
  • The Dragon Tongue seed packet · Generated With Diffusion Models · оригинал
  • The Black Beauty seed packet · Generated With Diffusion Models · оригинал
  • The Waltham Butternut seed packet · Generated With Diffusion Models · оригинал
Шрифты
Gelasio (SIL OFL 1.1) · Alfa Slab One (SIL OFL 1.1) · Cabin Condensed (SIL OFL 1.1)
Sandbox