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

Рецепты · Глава 5 · Структура книги

Руководство со ссылками на разделы и страницы

Руководство велосипеда, чьи ссылки гласят «see section 3.2 on page 3», вперёд и назад; все номера и страницы берёт вёрстка.

На этой странице
  • Образец на английском: русского издания пока нет
  • Обрезной формат 148 × 210 мм
  • 1 колонка
  • Archivo 9,3/13
  • Archivo Narrow
  • 4 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 64 мс
  • Строк кода: 131

Коротко

Короткое руководство к туристическому велосипеду. Если текст отсылает к другому разделу, он даёт его номер и страницу, и оба — ссылки.

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

Руководство вымышленного туристического велосипеда Ardena T3: четыре страницы A5 шрифтом Archivo, название модели на тёмно-синем поле первой страницы. Руководство читают вразбивку, поэтому каждое указание, которое зависит от другого, говорит, где оно: see section 3.2 on page 3. Автор даёт заголовку, абзацу или фразе шага идентификатор и пишет :ref везде, где текст на него указывает; Postext печатает номер, название или страницу и делает из них ссылку. Содержание на обложке записано так же, поэтому переставленный раздел или перевод, в котором текст стал длиннее, не оставят устаревшего номера.

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

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

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

script.js · строки 28–38в полном коде
// In the Markdown, `## Brakes {#sec-brakes}` names a heading, `:anchor{#warn-pressure}`
// a point in a paragraph and `[close the lever]{#step-close-lever}` a phrase in a step.
// `:ref{id="sec-pad-wear"}` prints "section 3.2", `style=page` "page 3", `style=title`
// the heading's words and `style=pageNumber` the bare 3. The page numbers come from the
// previous layout pass: the engine lays the manual out again until they hold.
const crossRefs = {
  section: t({ en: 'section {n}', es: 'apartado {n}' }), // H2 and H3: "section 3.2"
  page: t({ en: 'page {n}', es: 'página {n}' }), // spelt out: a manual is read by anyone
};
// Every reference is a link in the PDF and on screen; this makes it look like one.
const references = { referenceColor: col('orange'), referenceBold: true };

Ингредиенты

Шрифты
Archivo, Archivo Narrow (SIL OFL 1.1)
Материалы
Нет: все иллюстрации рисует код

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

#1 · Назовите то, на что указывает текст

Код приведён выше, в разделе «Короткий ответ». Заголовки получают идентификатор Pandoc, ### Checking pad wear {#sec-pad-wear}; предупреждение о давлении в шинах начинается с :anchor{#warn-pressure}, невидимой метки; последний шаг установки колеса — [close the lever so that it points backwards]{#step-close-lever}, он сохраняет свои слова и даёт им имя; врезка открывается :::callout{#box-wet type="note" title="Wet weather"}. Ссылка на шаг печатает слова шага, ссылка на врезку её заголовок.

#2 · Одна цель, четыре способа её назвать

:ref{id="sec-pad-wear"} печатает section 3.2 со словом из crossRefs.section; style=page печатает page 3 со словом из crossRefs.page; style=title печатает Checking pad wear; style=pageNumber печатает одно 3. Содержание на обложке соединяет номер без слова, название и страницу без слова и читается как обычное содержание. В испанской версии те же ссылки печатают apartado 3.2 и página 3, потому что шаблоны следуют языку версии.

#3 · Страницы находятся сами

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

#4 · Номера даёт счётчик уровня 2

script.js · строки 42–47в полном коде
const H2 = { level: 2, numberingTemplate: '{2}', numberSeparator: '   ', fontFamily: DISPLAY,
  fontWeight: 700, fontSize: pt(15), lineHeight: pt(LEAD * 1.5), color: col('navy'),
  marginTop: pt(LEAD), marginBottom: pt(LEAD / 3) };
const H3 = { level: 3, numberingTemplate: '{2}.{3}', numberSeparator: '  ', fontFamily: DISPLAY,
  fontWeight: 700, fontSize: pt(10.5), lineHeight: pt(LEAD), color: col('ink'),
  marginTop: pt(LEAD / 2), marginBottom: pt(LEAD / 4) };

В руководстве один заголовок первого уровня, название модели на обложке, поэтому разделы считаются с уровня 2: {2} даёт 1–5, а {2}.{3} даёт 1.1, 1.2.

#5 · Обложка — начальная полоса этого заголовка

script.js · строки 51–73в полном коде
const BAND = 104; // mm from the trim's top
const label = { fontFamily: DISPLAY, fontWeight: 700, textTransform: 'uppercase',
  letterSpacing: pt(1.6), align: 'left' };
const cover = {
  enabled: true,
  minHeight: mm(BAND - PAGE.top + 8), // the contents start 8 mm under the band
  slot: { elements: [
    { kind: 'box', id: 'band', style: { backgroundColor: col('navy') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(BAND) } } },
    { kind: 'box', id: 'stripe', style: { backgroundColor: col('orange') },
      placement: { ...at('page', 'top-left', 0, BAND), size: { width: 'fill', height: mm(2.5) } } },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', ...label, fontSize: pt(9),
      color: col('tint'), placement: at('container', 'top-left', 0, 6) },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontWeight: 700,
      fontSize: pt(58), lineHeight: 1, color: col('paper'), align: 'left',
      placement: at('container', 'top-left', -1, 30) },
    { kind: 'text', id: 'subtitle', content: '{attr.subtitle}', fontFamily: TEXT,
      fontSize: pt(11), color: col('paper'), align: 'left',
      placement: at('container', 'top-left', 0, 55) },
    { kind: 'text', id: 'edition', content: '{attr.edition}', ...label, fontSize: pt(7.5),
      color: col('tint'), placement: at('container', 'top-left', 0, 74) },
  ] },
};

Поле глубиной 104 мм, в полстраницы, и замыкает его оранжевая полоса. Надзаголовок, подзаголовок и строка издания — атрибуты заголовка, поэтому испанская версия меняет их в своём тексте.

script.js · строки 13–20в полном коде
const palette = {
  ink: '#1b1f24', navy: '#1d2c3c', orange: '#b8471b', tint: '#f7e7de', rule: '#d5cfc8',
  muted: '#5c636b', paper: '#ffffff',
};
// Each colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.orange })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));

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

Sandbox
// ═══ Postext Cookbook · Nº 092 · A manual whose references point to pages ══════════
// https://postext.dev/en/cookbook/manual-see-page-references
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Archivo, Archivo Narrow (SIL OFL 1.1) · Needs postext ≥ 1.28.0
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'manual-see-page-references';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a navy cover band and one signal orange for numbers and references
const palette = {
  ink: '#1b1f24', navy: '#1d2c3c', orange: '#b8471b', tint: '#f7e7de', rule: '#d5cfc8',
  muted: '#5c636b', paper: '#ffffff',
};
// Each colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.orange })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const TEXT = 'Archivo', DISPLAY = 'Archivo Narrow';
const PAGE = { w: 148, h: 210, top: 20, bottom: 20, inner: 18, outer: 15 }; // mm: A5, mirrored
const LEAD = 13; // pt
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });

// #region answer: the words a reference prints, and references that are links
// In the Markdown, `## Brakes {#sec-brakes}` names a heading, `:anchor{#warn-pressure}`
// a point in a paragraph and `[close the lever]{#step-close-lever}` a phrase in a step.
// `:ref{id="sec-pad-wear"}` prints "section 3.2", `style=page` "page 3", `style=title`
// the heading's words and `style=pageNumber` the bare 3. The page numbers come from the
// previous layout pass: the engine lays the manual out again until they hold.
const crossRefs = {
  section: t({ en: 'section {n}', es: 'apartado {n}' }), // H2 and H3: "section 3.2"
  page: t({ en: 'page {n}', es: 'página {n}' }), // spelt out: a manual is read by anyone
};
// Every reference is a link in the PDF and on screen; this makes it look like one.
const references = { referenceColor: col('orange'), referenceBold: true };
// #endregion

// #region numbers: sections 1–5 and 1.1, 1.2… under the one level-1 heading
const H2 = { level: 2, numberingTemplate: '{2}', numberSeparator: '   ', fontFamily: DISPLAY,
  fontWeight: 700, fontSize: pt(15), lineHeight: pt(LEAD * 1.5), color: col('navy'),
  marginTop: pt(LEAD), marginBottom: pt(LEAD / 3) };
const H3 = { level: 3, numberingTemplate: '{2}.{3}', numberSeparator: '  ', fontFamily: DISPLAY,
  fontWeight: 700, fontSize: pt(10.5), lineHeight: pt(LEAD), color: col('ink'),
  marginTop: pt(LEAD / 2), marginBottom: pt(LEAD / 4) };
// #endregion

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

Варианты

#Пишите в ссылках «p.»

Справочник со множеством ссылок на страницы экономит место сокращением.

-  page: t({ en: 'page {n}', es: 'página {n}' }), // spelt out: a manual is read by anyone
+  page: t({ en: 'p. {n}', es: 'pág. {n}' }),

#Оставьте ссылки чёрными

Если страница состоит почти из одних ссылок, оставьте их цветом текста и полужирными; в PDF и на экране это по-прежнему ссылки.

-const references = { referenceColor: col('orange'), referenceBold: true };
+const references = { referenceColor: col('ink'), referenceBold: true };

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

  • Ссылка на :anchor без стиля печатает страницу, потому что у невидимого якоря нет своих слов. Ставьте [words]{#id}, когда ссылка должна повторять текст.
  • Идентификатор в книге должен быть единственным. Ссылки попадают на первый {#sec-brakes}, а панель «Проверки» в Sandbox называет второй duplicateAnchor.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Шрифты
Archivo (SIL OFL 1.1) · Archivo Narrow (SIL OFL 1.1)
SandboxPDF