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

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

Один источник, печатная и экранная версии

Обе версии берутся из одной конфигурации: htmlViewer.overrides хранит тёмный экран, applyHtmlViewerOverrides накладывает его перед сборкой HTML.

  • Образец на английском: русского издания пока нет
  • Обрезной формат 225 × 297 мм
  • 2 колонки, средник 7 мм
  • Newsreader 10/14
  • Gloock
  • Reddit Sans
  • 4 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 121 мс
  • Строк кода: 238

Коротко

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

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

Notes on Weather, осенний раздел небольшого журнала, свёрстан дважды из одного Markdown. На бумаге это номер 225 × 297 мм: шмуцтитул цвета дождя, три заметки, которые открываются под бледной полосой тумана, две колонки с выключкой по формату, рисунки дождемера и розы ветров, фотография долины в тумане. На экране это одна колонка Newsreader флаговым набором, бледно-серая на почти чёрном, HTML-текстом, который можно выделить и скопировать, без шмуцтитула, полос тумана и колонцифр. Панель открывается на дождемере, уменьшенном до её высоты и нарисованном в ночных цветах, рядом с печатной страницей, где он стоит. Прокрутите вверх к началу Rain или потяните угол панели, и текст переверстается под новый размер. Экранное оформление — это девять ключей в htmlViewer.overrides внутри печатной конфигурации.

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

  • Как показать тот же документ в адаптивном HTML с прокруткой?
  • Как дать экранной версии более простое оформление, чем печатной, из одной конфигурации?

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

script.js · строки 61–87в полном коде
// config() stores it as htmlViewer: { overrides: screenOverrides() }; canvas and PDF ignore it.
const screenOverrides = () => ({
  colorPalette: paletteOf(night), // arrays are replaced whole: the night values
  parts: { page: false }, // no divider page; the part still names the notes after it
  // 96 dpi: the mm and pt inherited from print render at their CSS size.
  page: { dpi: 96, margins: { top: px(40), bottom: px(40), mirror: false } },
  layout: { layoutType: 'single', // one column
    fitFiguresToPage: true }, // tall figures shrink to the pane; off by default, as in print
  bodyText: { fontSize: px(17), lineHeight: px(27), textAlign: 'left' }, // ragged for reading
  // Heading levels merge on `level`: the print level keeps everything not restated here.
  headings: { levels: [{ level: 1, span: 'column', breakBefore: { enabled: false },
    marginTop: px(40), marginBottom: px(26),
    advancedDesign: { minHeight: px(0), slot: { elements: screenOpener } } }] }, // no band air
  footer: { elements: [] }, // a scrolling page runs no folios (print's header is empty already)
  captionStyle: { fontSize: px(13), gap: px(10) },
  paragraphStyles: [{ ...colophon, fontSize: px(13), lineHeight: px(20) }], // restated whole
});
// The host owns the page size: the pane's, in CSS pixels (gotcha: viewer-settings-sandbox-only).
// Wide panes get wider margins, so the measure stops at MEASURE.
const MEASURE = 470; // px: about 65 characters of Newsreader at 17 px
const MIN_SIDE = 34; // px: the side margins of a narrow pane
function screenConfig({ width, height }) {
  const merged = applyHtmlViewerOverrides(config()); // print + overrides, a fresh object
  const side = px(Math.max(MIN_SIDE, (width - MEASURE) / 2));
  return { ...merged, page: { ...merged.page, width: px(width), height: px(height),
    margins: { ...merged.page.margins, left: side, right: side } } };
}

Ингредиенты

Возможности
Более простой дизайн для экранаHTML-издание для чтенияРисунки по размеру страницыОформленные начальные полосыШмуцтитулы частейШапка главы на всю ширинуАтрибуты заголовковРазмещение рисунковСемантическая палитраКолонтитулы по роли страницыОдна или две колонкиЦвет бумагиСтраницы на холстеРисунки и таблицы как ресурсы«Рисунок» и «Таблица» на вашем языкеСобственные типы ресурсовСсылки, которые размещают рисункиСтили абзацев
Шрифты
Newsreader, Gloock, Reddit Sans (SIL OFL 1.1)
Материалы
  • valley-1610.jpg
  • Radiation fog in a valley at dawn (Figure 2) (Generated With Diffusion Models, оригинал)
  • The rain gauge, the wind rose and the part page's rain, drawn in code in both palettes (Ignacio Ferro, CC BY 4.0)

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

#1 · Один набор имён цветов, два набора значений

script.js · строки 15–24в полном коде
const day = { ink: '#1b222b', rain: '#3d6f9e', slate: '#2d3a4a', fog: '#e9edf1',
  rule: '#c8d0d8', muted: '#5f6a76', paper: '#ffffff' };
const night = { ink: '#e6e8eb', rain: '#9cc3e6', slate: '#56657a', fog: '#1b2129',
  rule: '#2e3742', muted: '#98a2ae', paper: '#111418' };
const paletteOf = (values) => // main-color: the engine's defaults follow the rain blue
  Object.entries({ ...values, 'main-color': values.rain })
    .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// Every colour names its palette entry: text, captions, the openers' design elements and the
// reference colour follow whichever palette the config carries. The hex is the day value.
const col = (id) => ({ hex: day[id], model: 'hex', paletteId: id });

Каждый цвет в конфигурации называет id палитры, а шестнадцатеричный код рядом — лишь дневное запасное значение. Поэтому экранная версия переходит на ночные цвета заменой одного массива. Переопределения в коротком ответе объединяют объекты по ключам, а уровни заголовков по level; любой другой массив, включая colorPalette, они заменяют целиком. main-color входит в палитру, поэтому меняются и значения движка по умолчанию, которые его используют. Новая палитра доходит до каждого связанного с ней цвета: текста, подписей, элементов оформления начал и цвета ссылок.

#2 · Начала: на бумаге полоса, на экране слова

script.js · строки 30–57в полном коде
const text = (id, content, fontFamily, style) => ({ kind: 'text', id, content, fontFamily,
  color: col('ink'), align: 'left', ...style,
  overflow: 'wrap' }); // titles break onto more lines
const kicker = text('kicker', '{partTitle} · {attr.kicker}', 'Reddit Sans',
  { fontWeight: 600, textTransform: 'uppercase', color: col('rain') });
const title = text('title', '{titleText}', 'Gloock');
const lead = text('lead', '{attr.lead}', 'Newsreader', { italic: true, hyphenate: true });
const at = (to, edge, y, x = px(0)) => ({ anchor: { to, edge }, offset: { x, y } });
const under = (id, y, width) => ({ ...at(`#${id}`, 'below', y), size: { width } });
const band = (y, height) => ({ ...at('bleed', 'top-left', y), size: { width: 'fill', height } });
const fromTop = (y, x) => at('container', 'top-left', y, x);
// minHeight sets the reservation: the band's foot below the top margin, plus AIR. The band hangs
// from the bleed and counts too, but ends higher (gotcha: opener-reserves-anchored).
const printOpener = { enabled: true, minHeight: mm(BAND - TOP + AIR), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('fog') },
    placement: band(mm(0), mm(BAND)) },
  { kind: 'rule', id: 'horizon', direction: 'horizontal', thickness: pt(2), color: col('rain'),
    placement: band(mm(BAND - 0.7), pt(2)) }, // 2 pt is 0.7 mm: the rule ends at the band's foot
  { ...kicker, fontSize: pt(8), letterSpacing: pt(1.8), placement: fromTop(mm(12)) },
  { ...title, fontSize: pt(54), lineHeight: 1.04, placement: under('kicker', mm(2.5), mm(150)) },
  { ...lead, fontSize: pt(11.5), lineHeight: 1.36, placement: under('title', mm(4), mm(118)) },
] } };
const screenOpener = [
  { ...kicker, fontSize: px(12), letterSpacing: px(2.6), placement: fromTop(px(4)) },
  { ...title, fontSize: px(48), lineHeight: 1.05, placement: under('kicker', px(6), 'fill') },
  { ...lead, fontSize: px(18), lineHeight: 1.45, color: col('muted'),
    placement: under('title', px(10), 'fill') },
];

Элементы надзаголовка, названия и вводки определены один раз и развёрнуты в оба оформления, поэтому обе версии показывают одни и те же атрибуты заголовка: {attr.kicker}, {attr.lead} и {partTitle} части. На бумаге заголовок первого уровня начинает новую страницу и охватывает обе колонки, а его оформление подвешивает полосу тумана от вылета. minHeight резервирует глубину полосы ниже верхнего поля плюс AIR, 9 мм между полосой и первой строкой. Печатные названия набраны кеглем 54 пт: каждое — одно короткое слово и единственный крупный текст на странице. На экране тот же уровень набран заголовком в колонке, без полосы и без воздуха. Переопределение объединяется по level, поэтому все настройки заголовка, которые оно не повторяет, остаются печатными.

#3 · Шмуцтитул, который есть только на бумаге

script.js · строки 91–107в полном коде
const onField = { color: col('paper'), lineHeight: 1 };
const parts = {
  margins: { top: mm(212), left: mm(24), right: mm(40) }, // the fence's list sits low
  bodyStyle: { fontSize: pt(13), lineHeight: pt(19), color: col('paper'),
    numberColor: col('paper') },
  design: { elements: [
    { kind: 'box', id: 'field', style: { backgroundColor: col('rain') },
      placement: band(mm(0), 'fill') },
    { kind: 'image', id: 'strokes', resourceId: 'rain', placement: band(mm(0), 'fill') },
    text('series', '{title}', 'Reddit Sans', { ...onField, fontWeight: 600, fontSize: pt(9),
      letterSpacing: pt(2.4), textTransform: 'uppercase', placement: fromTop(mm(30), mm(24)) }),
    text('numeral', '{number}', 'Gloock', { ...onField, fontSize: pt(190),
      placement: under('series', mm(10), mm(150)) }),
    text('name', '{titleText}', 'Gloock', { ...onField, fontSize: pt(60),
      placement: under('numeral', mm(-6), mm(150)) }),
  ] },
};

В печати :::part открывает шмуцтитул цвета дождя: прямоугольник под обрез со всех сторон, элемент-изображение со штрихами дождя, которые обходят текст, номер и название из ограждения и белый перечень заметок. Экранные переопределения задают parts.page: false, поэтому страница не открывается и перечень не набирается. Часть по-прежнему даёт номер и название следующим за ней заметкам, и на экране надзаголовок читается «Autumn · Note 1», как и в печати.

#4 · Рисуйте каждый рисунок дважды

script.js · строки 201–234в полном коде
// The valley is a photograph, one JPEG in assets/ that both editions share, at its pixels.
const photo = { kind: 'bitmap', svg: undefined,
  bitmap: { fileId: 'valley-1610.jpg', format: 'jpeg', width: 1610, height: 690 } };
const figure = (id, edition, [width, height], placement, caption, alt) => ({ id,
  typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0, placement,
  svg: { fileId: `${id}-${edition}.svg`, width, height },
  caption: caption && t(caption), altText: alt && t(alt) }); // the HTML edition's <img alt>
const figures = (edition) => [
  figure('gauge', edition, [900, 1260], { position: 'auto', span: 'column' }, {
    en: 'The rain gauge in section: the funnel feeds a tube with a tenth of its area.',
    es: 'El pluviómetro en sección: el embudo vierte en un tubo con la décima parte de su área.',
  }, {
    en: 'Rain falls on a funnel set in a can sunk in the lawn; the funnel drains into a narrow '
      + 'tube, half full, beside a graduated measuring stick.',
    es: 'La lluvia cae en un embudo sobre un vaso hundido en el césped; el embudo vierte en un '
      + 'tubo estrecho, medio lleno, junto a una regla graduada.' }),
  { ...figure('valley', edition, [1610, 690], { position: 'bottom', span: 'page' }, {
    en: 'Radiation fog at dawn: cold air drains off the hills overnight and fills the valley.',
    es: 'Niebla de irradiación al amanecer: el aire frío baja de las lomas y llena el valle.',
  }, {
    en: 'A valley between wooded hills lies under layers of fog at sunrise, with a church '
      + 'tower, trees and a river showing through it, seen from a fenced bank.',
    es: 'Un valle entre lomas boscosas yace bajo la niebla al amanecer; asoman la torre de '
      + 'una iglesia, árboles y un río, vistos desde un ribazo con una cerca.' }), ...photo },
  figure('rose', edition, [900, 900], { position: 'top', span: 'column' }, {
    en: 'Where a year of morning winds came from at the garden station: west and south-west.',
    es: 'De dónde vino el viento de un año de mañanas en el jardín: del oeste y del suroeste.',
  }, {
    en: 'A wind rose of sixteen petals on three rings; the longest petals point west and '
      + 'south-west, the shortest east.',
    es: 'Una rosa de los vientos de dieciséis pétalos sobre tres anillos; los más largos '
      + 'apuntan al oeste y al suroeste, los más cortos al este.' }),
  figure('rain', 'field', [2250, 2970]), // drawn by the part design, never cited: unnumbered
];

Замена палитры не перекрашивает SVG, поэтому каждый рисунок сделан для каждой палитры. Долина — фотография, один JPEG на обе версии. figures(edition) создаёт одинаковые ресурсы для обеих версий, каждый со ссылкой на файл своей: gauge-day.svg в печати, gauge-night.svg на экране. Идентификаторы, подписи, альтернативные тексты и размещения не меняются, поэтому каждый :ref в Markdown ведёт к тому же рисунку и номеру в любой версии. На экране альтернативный текст попадает в каждый <img alt>, где его находит программа чтения с экрана.

#5 · Разместите экранную версию

script.js · строки 354–382в полном коде
const FOLDED = 200; // px: a pane narrower or shorter than this is hidden or squeezed; skip it
if (!pane.clientHeight) { // no style.css: a height, and a corner to drag the pane smaller, but
  // not under 400 px, where an opener can take a whole page and push its text to the next
  pane.style.cssText = 'height:580px;min-height:400px;min-width:240px;overflow:auto;resize:both';
}
pane.style.background = night.paper; // the pane's own ground, beside the pages and the scrollbar
const shadow = pane.attachShadow({ mode: 'open' }); // the page's selectors cannot reach in, and
// the edition's root resets the text properties it would inherit (letter-spacing…) by itself
const inShadow = `<style>::selection{background:${night.rain}55}</style>`; // the night blue
let size = '';
function showScreen() {
  const [width, height] = [pane.clientWidth, pane.clientHeight];
  if (`${width}×${height}` === size || width < FOLDED || height < FOLDED) return; // same, or folded
  const first = !size; // the first build opens on Figure 1's page, like the print proof
  size = `${width}×${height}`;
  const screenDoc = buildDocument({ markdown, resources: figures('night') },
    screenConfig({ width, height }));
  const place = pane.scrollTop / pane.scrollHeight; // the reader's place, kept across rebuilds
  shadow.innerHTML = inShadow + renderToHtml(screenDoc,
    { mode: 'single', padding: 0, resourceImageUrl: imageUrl });
  const fig = first && screenDoc.pages.find((page) => holds(page, 'gauge')); // 'single' mode
  pane.scrollTop = fig ? fig.index * height : place * pane.scrollHeight; // stacks pane-tall pages
  screenLabel.textContent =
    `${t({ en: 'Screen', es: 'Pantalla' })} · HTML · ${width} × ${height} px`;
}
showScreen();
let timer = 0; // debounced; its first call, on observe(), finds the size unchanged
new ResizeObserver(() => { clearTimeout(timer); timer = setTimeout(showScreen, 150); })
  .observe(pane);

Каждая экранная страница равна по высоте панели, поэтому fitFiguresToPage уменьшает дождемер, пока он не уместится на одной странице с подписью (вёрстка). При 96 dpi, разрешении, которое предполагает CSS, миллиметры и пункты, унаследованные от печати, отображаются в номинальном размере (встраивание HTML-просмотра). Пен записывает абсолютно позиционированные строки renderToHtml в Shadow DOM, куда селекторы страницы не достают. Наследуемые свойства вроде letter-spacing эту границу проходят, и корень версии сбрасывает их сам, потому что движок измерял строки без них. HTML-страницы прозрачны, если их не закрасить, поэтому page.backgroundColor берёт из палитры ночную бумагу. ResizeObserver ждёт 150 мс и пересобирает документ из новой config(), только если изменилась ширина или высота панели; после сборки панель прокручивается к той же доле своей высоты.

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

Sandbox
// ═══ Postext Cookbook · Nº 011 · One source, print and screen editions ═══════════
// https://postext.dev/en/cookbook/print-and-screen-editions
// Code: MIT · Text: original (CC BY 4.0) · Drawings: code (CC BY 4.0) · Photo: diffusion models
// Fonts: Newsreader, Gloock, Reddit Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocument, prepareFonts, withLoadedFonts, renderPageToCanvas, renderToHtml,
  applyHtmlViewerOverrides, registerResourceImage, defaultResourceTypes,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'print-and-screen-editions';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: one set of colour ids, two sets of values: day for paper, night for screens
const day = { ink: '#1b222b', rain: '#3d6f9e', slate: '#2d3a4a', fog: '#e9edf1',
  rule: '#c8d0d8', muted: '#5f6a76', paper: '#ffffff' };
const night = { ink: '#e6e8eb', rain: '#9cc3e6', slate: '#56657a', fog: '#1b2129',
  rule: '#2e3742', muted: '#98a2ae', paper: '#111418' };
const paletteOf = (values) => // main-color: the engine's defaults follow the rain blue
  Object.entries({ ...values, 'main-color': values.rain })
    .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// Every colour names its palette entry: text, captions, the openers' design elements and the
// reference colour follow whichever palette the config carries. The hex is the day value.
const col = (id) => ({ hex: day[id], model: 'hex', paletteId: id });
// #endregion
const px = (value) => ({ value, unit: 'px' }); // screen sizes, written as CSS pixels
const [TOP, BAND, AIR] = [22, 86, 9]; // mm: top margin, the fog band's depth, air under it

// #region opener: print opens each note under a fog band; the screen keeps the words only
const text = (id, content, fontFamily, style) => ({ kind: 'text', id, content, fontFamily,
  color: col('ink'), align: 'left', ...style,
  overflow: 'wrap' }); // titles break onto more lines
const kicker = text('kicker', '{partTitle} · {attr.kicker}', 'Reddit Sans',
  { fontWeight: 600, textTransform: 'uppercase', color: col('rain') });
const title = text('title', '{titleText}', 'Gloock');
const lead = text('lead', '{attr.lead}', 'Newsreader', { italic: true, hyphenate: true });
const at = (to, edge, y, x = px(0)) => ({ anchor: { to, edge }, offset: { x, y } });
const under = (id, y, width) => ({ ...at(`#${id}`, 'below', y), size: { width } });
const band = (y, height) => ({ ...at('bleed', 'top-left', y), size: { width: 'fill', height } });
const fromTop = (y, x) => at('container', 'top-left', y, x);
// minHeight sets the reservation: the band's foot below the top margin, plus AIR. The band hangs
// from the bleed and counts too, but ends higher (gotcha: opener-reserves-anchored).
const printOpener = { enabled: true, minHeight: mm(BAND - TOP + AIR), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('fog') },
    placement: band(mm(0), mm(BAND)) },
  { kind: 'rule', id: 'horizon', direction: 'horizontal', thickness: pt(2), color: col('rain'),
    placement: band(mm(BAND - 0.7), pt(2)) }, // 2 pt is 0.7 mm: the rule ends at the band's foot
  { ...kicker, fontSize: pt(8), letterSpacing: pt(1.8), placement: fromTop(mm(12)) },

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

Варианты

#Читайте днём

Уберите ночную палитру и возьмите дневные значения для панели и рисунков; экранная версия покажет белые страницы, тёмный текст и дневные рисунки.

-  colorPalette: paletteOf(night), // arrays are replaced whole: the night values
   parts: { page: false }, // no divider page; the part still names the notes after it
@@
-pane.style.background = night.paper; // the pane's own ground, beside the pages and the scrollbar
+pane.style.background = day.paper; // the pane's own ground, beside the pages and the scrollbar
@@
-  const screenDoc = buildDocument({ markdown, resources: figures('night') },
+  const screenDoc = buildDocument({ markdown, resources: figures('day') },

#Дайте печатным началам номер главы на цветной полосе

Более тяжёлое печатное начало, с насыщенной полосой и крупным номером главы, — в рецепте Начало главы на полосе под обрез; экранные переопределения остаются теми же.

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

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

В HTML нет линейки колонок, сетки и меток, а фон прозрачный

renderToHtml не рисует линейку колонок, сетку базовых линий и метки обреза, а страницы прозрачны, если не передать background: на тёмной странице это тёмный текст на тёмном. HTML-издание для чтения →

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

Часть настроек htmlViewer действует только в Sandbox

htmlViewer.maxCharsPerLine, columnGap и optimalLineBreaking читает просмотрщик Sandbox, а не renderToHtml. На своей странице задайте её размер сами и передайте renderToHtml значения mode и columnGap; переопределения применяет applyHtmlViewerOverrides. HTML-издание для чтения →

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

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

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

  • Панель должна быть не ниже 400 px (min-height в пене). В узкой панели ниже примерно 350 px экранное начало выше области содержимого страницы; оно занимает страницу целиком, и первый абзац заметки начинается на следующей.
  • Задайте панели размер до вёрстки. Панель без ширины, скрытая или выдавленная из ряда flex, дала бы страницу нулевой ширины, поэтому showScreen() пропускает панель уже или ниже FOLDED, 200 px.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • Radiation fog in a valley at dawn (Figure 2) · Generated With Diffusion Models · оригинал
  • The rain gauge, the wind rose and the part page's rain, drawn in code in both palettes · Ignacio Ferro · CC BY 4.0
Шрифты
Newsreader (SIL OFL 1.1) · Gloock (SIL OFL 1.1) · Reddit Sans (SIL OFL 1.1)
Sandbox