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

Рецепты · Глава 10 · Вывод и интеграция

Тексты обложки с привязкой, цепочкой и ростом

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

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

с. 1 · 22 из 22

  • Образец на английском: русского издания пока нет
  • Обрезной формат 125 × 195 мм
  • 1 колонка
  • EB Garamond 11/14,6
  • Cinzel
  • 22 страницы
  • Уровень
  • Postext 1.101.0
  • Свёрстано за 105 мс
  • Строк кода: 243

Коротко

Небольшая книга с двумя рассказами Эдгара Аллана По и печатный лист её обложки. Каждый текст стоит под другим, над ним или вплотную к нему, поэтому длинный заголовок сдвигает остальное, а аннотация продолжается под цитатой.

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

Два рассказа Эдгара Аллана По, «Маска Красной смерти» и «Овальный портрет» (в испанском издании — перевод Карлоса Оливеры 1884 года), в мягкой обложке 125 × 195 мм и лист этой обложки. Каждый текст на ней — текстовая рамка без координат. На лицевой стороне заголовок подвешен к верху панели, подзаголовок — под заголовком, а автор стоит внизу. В обоих изданиях заголовок занимает две строки, поэтому его рамка растёт и подзаголовок опускается вместе с ней. На задней стороне аннотация заполняет рамку 50 мм, а строки, которые в неё не вошли, продолжаются во второй рамке под цитатой из рассказа. Над страницами пен рисует лист дважды: как он печатается и с контуром каждой рамки и обозначенной цепочкой.

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

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

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

script.js · строки 29–56в полном коде
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation. The barcode is placed the same way: on
// the foot of the back by the fore-edge, not in the default corner by the spine.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
  // Front: the title from the top of the panel, the subtitle hung under it, the author
  // standing on the foot. Only the title's box grows; the subtitle follows it down.
  { name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
    maxHeight: 40 },
  { name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
  { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
  // Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
  // What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
  { name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
    next: 'blurb-end' },
  { name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
    verticalAlign: 'middle' },
  { name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },
];
const cover = {
  background: col('night'),
  elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 201,
    resourceId: 'masque', fit: 'cover' }],
  textBoxes,
  barcode: { edge: 'bottom-left' },
};

Ингредиенты

Шрифты
EB Garamond, Cinzel (SIL OFL 1.1)
Материалы
  • masque-1024.jpg
  • The cover painting: a masked ball in a file of coloured rooms under a Gothic vault, with an ebony clock and a figure in a grave-shroud, in oils (Generated With Diffusion Models, оригинал)

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

#1 · Каждая рамка висит на панели или на другой рамке

Код — в разделе Короткий ответ выше. anchor называет зону листа или другую текстовую рамку и точку. На зоне это одна из девяти точек её безопасной зоны, и рамка прикладывает к ней ту же свою точку: edge: 'top' центрует заголовок на лицевой стороне и ставит его верх на верх безопасной зоны, edge: 'bottom' ставит низ автора на её низ. На рамке точкой может быть также below, above, right-of или left-of. x и y сдвигают рамку от этой точки, в мм. При якоре rect задаёт только размер рамки, поэтому рамки остаются на местах, когда растёт корешок или меняется формат книги.

#2 · Заголовок растёт и сдвигает подзаголовок вниз

script.js · строки 70–86в полном коде
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const mid = { textAlign: 'center' };
const caps = (tracking) => ({ fontWeight: 600, letterSpacing: pt(tracking) });
const coverStyles = [
  style('cover-title', 'Cinzel', 30, 33, col('bone'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'EB Garamond', 14, 18, col('gold'), { ...mid, italic: true }),
  style('cover-author', 'Cinzel', 10, 13, col('bone'), { ...mid, ...caps(2.2) }),
  style('cover-spine', 'Cinzel', 7, 8, col('bone'), { ...mid, ...caps(1.1) }),
  style('cover-blurb', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
    hyphenation: true, firstLineIndent: mm(4) }),
  style('cover-blurb-first', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
    hyphenation: true }),
  style('cover-quote', 'EB Garamond', 15, 19, col('gold'), { ...mid, italic: true }),
  style('cover-note', 'Cinzel', 7.5, 11, col('gold'), { ...caps(1.4), marginTop: pt(8) }),
];

Заголовок набран Cinzel 30 на 33 пт. Высота его рамки 14 мм, одна строка. “The Masque of the Red Death” и “La máscara de la muerte” требуют двух, поэтому рамка растёт с текстом до 40 мм, заданных в maxHeight, и только за этим пределом кегль стал бы уменьшаться. Подзаголовок привязан below к заголовку, на 2 мм ниже, поэтому опускается на высоту второй строки. Автор привязан к низу панели и остаётся на месте.

#3 · Аннотация продолжается в другой рамке

Рамка аннотации указывает next: 'blurb-end'. Текст, который в неё не вошёл, разрезается между строками и продолжается в этой рамке; своего фрейма в Markdown обложки у неё нет. Цитата висит под аннотацией, а blurb-end под цитатой, поэтому все три сохраняют расстояния, если сделать рамку аннотации выше. Только когда мало и второй рамки, текст цепочки уменьшается целиком, по умолчанию до 90 % (fit.minScale). Строка золотой капителью — последний абзац фрейма аннотации, поэтому она закрывает текст во второй рамке:

:::frame{slot="front"}
:::
 
:::frame{slot="blurb"}
:::paragraphs{style="cover-blurb-first"}
While a plague empties his country, Prince Prospero shuts himself up …
:::
 
:::paragraphs{style="cover-note"}
From the Raven Edition of Poe's works
:::
:::

Пустой фрейм front не пропускает заголовок, подзаголовок и автора, которых buildCover иначе поставил бы на лицевую сторону из метаданных книги: здесь их ставят рамки.

#4 · Мягкая обложка с корешком по числу страниц

script.js · строки 60–66в полном коде
const production = {
  bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
    measures: { bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
    isbn: '978-84-0000-200-8', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f8f3e8' } };

Клеевое скрепление PUR тетрадями по 16 страниц, на веленевой бумаге 120 г/м² с пухлостью 2,2. В книге 21 страница, после переплёта 32, поэтому корешок около 4,7 мм, меньше 6 мм, с которых надпись на корешке ставится по умолчанию; версия задаёт spineText.minSpine равным 4,5, и на корешке стоят название и автор. ISBN — образец номера, он не присвоен ни одной книге.

#5 · Книжный блок

script.js · строки 90–130в полном коде
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 195, 21, 23, 18, 16, 14.6]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(box && { size: box }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Cinzel', size, color, caps(size / 6));
const titling = (size, extra) => face('Cinzel', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const wide = { width: mm(84) };
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', titling(12), at('page', 'top', 0, 62, wide))]) },
  // The title runs to two lines at 22 pt in both editions; the subtitle sits under them.
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', titling(22, { lineHeight: pt(27) }), at('page', 'top', 0, 44, wide)),
    text('s', '{subtitle}', face('EB Garamond', 13, col('ink'), { italic: true }),
      at('page', 'top', 0, 67)),
    rule('r', 77),
    text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 82)),
    text('c', '{attr.credit}', face('EB Garamond', 10, col('muted'), { italic: true }),
      at('page', 'top', 0, 118, { width: mm(76) })),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -26)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(90, [rule('r', 84, 'container')]) },
  // Each tale opens on a recto, sunk 50 mm, its title on one line of Cinzel over a short rule.
  { ...page('odd'), id: 'tale', toc: false, header: { elements: [] }, advancedDesign: design(50, [
    text('t', '{titleText}', titling(13.5, { letterSpacing: pt(0.6) }),
      at('container', 'top', 0, 24, { width: mm(W - INNER - OUTER) })),
    rule('r', 40, 'container')]) },
  { ...none, ...page('odd'), id: 'colophon', advancedDesign: design(70, [
    rule('r', 62, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.6), parity, pages: 'body' },
  at('page', 'top', 0, 11));

Авантитул, титул и сведения о правах, затем каждый рассказ с правой полосы, со спуском 50 мм, под заголовком Cinzel и короткой красной линейкой. В колонтитулах слева автор, справа название рассказа, а книгу закрывают выходные сведения на последней правой полосе.

#6 · Лист собирается из свёрстанных страниц

script.js · строки 295–303в полном коде
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
  await loadSvg(id, new TextDecoder().decode(bytes)
    .replace(/font-family="[^"]*"/g, 'font-family="Cinzel"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));

buildCover берёт страницы, метаданные и Markdown обложки и возвращает документ, единственная страница которого — лист. Текстовые рамки становятся фреймами этой страницы и верстаются как фреймы макетной страницы. Цифры штрихкода требуют OCR-B, которого нет ни на одном сервере шрифтов, поэтому пен набирает их шрифтом Cinzel.

#7 · Где оказалась каждая рамка

script.js · строки 310–367в полном коде
// Each text box comes back as a frame of the sheet's composed page, with the rect it was
// given after anchoring and growing, and `continuesTo` when its text goes on elsewhere.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const names = new Set(textBoxes.map((b) => b.name));
const frames = (leaf.composed?.frames ?? []).filter((f) => names.has(f.name));
const views = document.createElement('section');
views.id = 'box-views';
views.style.cssText = 'display: grid; gap: 18px; '
  + 'grid-template-columns: repeat(auto-fit, minmax(300px, 600px)); justify-content: center; '
  + 'padding: 24px 16px; color: #ddd; font: 14px sans-serif';
for (const [mode, name] of [['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
  ['boxes', t({ en: 'The text boxes', es: 'Las cajas de texto' })]]) {
  const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  figure.style.cssText = 'margin: 0; min-width: 0';
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
  renderPageToCanvas(leaf, sheet, canvas, { scale });
  if (mode === 'boxes') {
    // Each box outlined and named; a chain drawn from the foot of a box to its next.
    const ctx = canvas.getContext('2d');
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    ctx.lineWidth = 2 / scale;
    ctx.font = `${13 / scale}px sans-serif`;
    for (const f of frames) {
      const { x, y, width, height } = f.rect;
      ctx.strokeStyle = ctx.fillStyle = '#f2c14e';
      ctx.setLineDash([8 / scale, 5 / scale]);
      ctx.strokeRect(x, y, width, height);
      ctx.setLineDash([]);
      // The name on a dark tab over the box's top-left corner, clear of the text.
      const tab = ctx.measureText(f.name).width + 10 / scale;
      ctx.fillStyle = '#141117';
      ctx.fillRect(x, y - 18 / scale, tab, 18 / scale);
      ctx.fillStyle = '#f2c14e';
      ctx.fillText(f.name, x + 5 / scale, y - 5 / scale);
      const next = frames.find((g) => g.id === f.continuesTo);
      if (next) {
        ctx.strokeStyle = '#ff7a59';
        // Out of the box's foot, down its right side, into the top of the next.
        const side = Math.max(x + width, next.rect.x + next.rect.width) + 14 / scale;
        ctx.beginPath();
        ctx.moveTo(x + width - 20 / scale, y + height);
        ctx.lineTo(side, y + height);
        ctx.lineTo(side, next.rect.y);
        ctx.lineTo(next.rect.x + next.rect.width - 20 / scale, next.rect.y);
        ctx.stroke();
      }
    }
  }
  // After the render, which sizes the canvas in CSS pixels: the column sets its width.
  canvas.style.cssText = 'display: block; width: 100%; height: auto';
  caption.textContent = name;
  figure.append(canvas, caption);
  views.append(figure);
}
document.getElementById('pages').before(views);

Страница листа возвращается со своими фреймами в page.composed.frames, у каждого прямоугольник, который вёрстка дала ему после привязки и роста, и continuesTo, когда его текст продолжается в другом фрейме. Второй вид обводит шесть рамок поверх листа и рисует цепочку от низа аннотации к верху blurb-end.

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

Sandbox
// ═══ Postext Cookbook · Nº 200 · Cover text boxes anchored, chained and grown ══════════════
// https://postext.dev/en/cookbook/cover-text-boxes-anchored
// Code: MIT · Text: E. A. Poe, tr. C. Olivera (public domain) · Art: diffusion models
// Fonts: EB Garamond, Cinzel (SIL OFL 1.1) · Needs postext ≥ 1.101.0
//
// Two of Poe's tales as a small paperback, and its cover sheet set from six text boxes.
// None of them has coordinates: each hangs from a panel of the sheet or from another box,
// so a title that runs to two lines takes the subtitle down with it, and the blurb on the
// back runs on under a quotation into a second box.
import { buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts }
  from 'https://esm.sh/postext';
import { buildCover } from 'https://esm.sh/postext/production';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'cover-text-boxes-anchored';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' four colours, then the cover's: a night ground, bone type, a dull gold.
const palette = { ink: '#231f1c', accent: '#8e2219', muted: '#6a625a', paper: '#faf6ee',
  night: '#141117', bone: '#ece3cf', gold: '#c9a66b' };
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: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

// #region answer: six text boxes placed against the panels and against each other
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation. The barcode is placed the same way: on
// the foot of the back by the fore-edge, not in the default corner by the spine.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
  // Front: the title from the top of the panel, the subtitle hung under it, the author
  // standing on the foot. Only the title's box grows; the subtitle follows it down.
  { name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
    maxHeight: 40 },
  { name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
  { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
  // Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
  // What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
  { name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
    next: 'blurb-end' },
  { name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
    verticalAlign: 'middle' },
  { name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },

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

Варианты

#Подвесьте автора под подзаголовком

Тогда автор тоже опускается вслед за заголовком, а не стоит внизу панели.

-  { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
+  { name: 'author', rect: size(100, 8), anchor: { to: 'subtitle', edge: 'below', y: 6 } },

#Уменьшите длинный заголовок до одной строки

Без maxHeight рамка заголовка сохраняет свои 14 мм, а лестница подгонки уменьшает заголовок, пока он не поместится: здесь в одну строку, примерно на двух третях кегля.

   { name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
-    maxHeight: 40 },
+    fit: { minScale: 0.6 } },

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

  • Рамка, названная в next другой рамки, принимает текст, который та передаёт. Не давайте ей собственного фрейма в Markdown обложки, а фрейм первой рамки кончайте тем, что должно закрыть текст, как здесь примечанием.
  • Якорь, который ни на что не указывает, указывает на саму рамку или замыкает петлю, попадает в предупреждения, а рамка встаёт по своему rect. Давайте каждой привязанной рамке rect с настоящим размером.
  • maxHeight не действует на повёрнутую рамку (rotate): она сохраняет размер своего rect.

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

Рецепт
Ignacio Ferro
Текст
Изображения
  • The cover painting: a masked ball in a file of coloured rooms under a Gothic vault, with an ebony clock and a figure in a grave-shroud, in oils · Generated With Diffusion Models · оригинал
Шрифты
EB Garamond (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)
SandboxPDF