Skip to main content
Recipe number 11

Cookbook · Chapter 10 · Output & integration

One source, print and screen editions

Both editions come from one config: htmlViewer.overrides holds the dark screen design, and applyHtmlViewerOverrides merges it in before each HTML build.

  • Trim 225 × 297 mm
  • 2 columns, 7 mm gutter
  • Newsreader 10/14
  • Gloock
  • Reddit Sans
  • 4 pages
  • Level
  • Postext 1.57.1
  • Laid out in 121 ms
  • 238 lines of code

In short

The weather section of a magazine, made twice from the same text. It shows how one set of settings gives a printed version in columns and a dark, single-column version for reading on screen.

What you'll build

Notes on Weather, the autumn section of a small magazine, set twice from the same Markdown. On paper it is a 225 × 297 mm issue: a rain-blue divider page, three notes that open under a pale fog band, two justified columns, drawings of a rain gauge and a wind rose, and a photograph of a fogged valley. On screen it is a single ragged column of Newsreader, pale grey on near-black, in HTML text a reader can select and copy, with no divider page, fog bands or folios. The pane opens on the gauge, shrunk to the pane's height and drawn in night colours, beside the printed page it sits on. Scroll up for the Rain opener, or drag the pane's corner and the text is laid out again at the new size. The screen design is nine keys under htmlViewer.overrides, inside the print config.

This recipe answers

  • How do I show a responsive, scrollable HTML reading view of the same document?
  • How do I give the screen edition a simpler design than the print edition, from one config?

The short answer

script.js · lines 61–87in full code
// 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 } } };
}

The screen edition lives in the same config, as overrides of the print one

Ingredients

Type
Newsreader, Gloock, Reddit Sans (SIL OFL 1.1)
Assets
  • valley-1610.jpg
  • Radiation fog in a valley at dawn (Figure 2) (Generated With Diffusion Models, original)
  • The rain gauge, the wind rose and the part page's rain, drawn in code in both palettes (Ignacio Ferro, CC BY 4.0)

Method

#1 · One set of colour names, two sets of values

script.js · lines 15–24in full code
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 });

Every colour in the config names a palette id, and the hex written beside it is only the day fallback. So the screen edition switches to the night colours by replacing one array. The overrides in the short answer merge objects key by key and heading levels on level, and replace any other array whole, colorPalette included. main-color is part of the palette, so the engine defaults that use it change as well. The new palette reaches every colour linked to it: the text, the captions, the openers' design elements and the reference colour.

#2 · Openers: a band on paper, the words on screen

script.js · lines 30–57in full code
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') },
];

The kicker, title and lead elements are defined once and spread into both designs, so both editions show the same heading attributes: {attr.kicker}, {attr.lead} and the part's {partTitle}. On paper a level-1 heading breaks to a new page and spans both columns, and its design hangs a fog band from the bleed. minHeight reserves the band's depth below the top margin plus AIR, the 9 mm between the band and the first line. The printed titles are set at 54 pt because each is one short word and the only large type on its page. On screen the same level is set as an in-column heading with no band and no air. The override merges on level, so every heading setting it does not restate stays as printed.

#3 · A divider page that exists only on paper

script.js · lines 91–107in full code
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)) }),
  ] },
};

In print, :::part opens the rain-blue divider: a box bled off every edge, an image element of rain strokes that leave the type clear, the numeral and title from the fence, and the list of notes in white. The screen overrides set parts.page: false, so no page opens and the list is not set. The part still applies its number and title to the notes after it, and the screen kicker reads “Autumn · Note 1” as the printed one does.

#4 · Draw every figure twice

script.js · lines 201–234in full code
// 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
];

Swapping the palette does not recolour an SVG, so each drawing is made once per palette. The valley is a photograph, one JPEG that both editions share. figures(edition) builds the same resources for both editions, each pointing at that edition's file: gauge-day.svg in print, gauge-night.svg on screen. Ids, captions, alt texts and placements do not change, so every :ref in the Markdown resolves to the same figure and number in either edition. In the screen edition the alt text goes into each <img alt>, where a screen reader finds it.

#5 · Host the screen edition

script.js · lines 354–382in full code
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);

Each screen page is as tall as the pane, so fitFiguresToPage shrinks the gauge until it fits on one page with its caption (layout). At 96 dpi, the resolution CSS assumes, the millimetres and points inherited from print render at their nominal size (integrating the HTML viewer). The pen writes renderToHtml's absolutely positioned lines into a Shadow DOM, where the page's selectors cannot reach them. Inherited properties such as letter-spacing do cross that boundary, and the edition's root resets them itself, because the engine measured the lines without them. HTML pages are transparent unless painted, so page.backgroundColor takes the night paper from the palette. The ResizeObserver waits 150 ms and rebuilds from a fresh config() only when the pane's width or height has changed; after the rebuild the pane scrolls back to the same fraction of its height.

The whole recipe

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)) },

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Read by day

Remove the night palette and use the day values for the pane and the figures; the screen edition then shows white pages, dark ink and the day drawings.

-  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') },

#Give the print openers a chapter number on a colour band

For a heavier print opener, with a saturated band and a big chapter number, see Chapter opener on a full-bleed band; the screen overrides stay the same.

Pitfalls

Pitfall

HTML output has no column rule, grid or marks, and is transparent

renderToHtml draws no column rule, baseline grid or crop marks, and its pages are transparent unless you pass a background, which on a dark page means dark text on dark. HTML reading edition →

Pitfall

Some htmlViewer settings exist only in the Sandbox

htmlViewer.maxCharsPerLine, columnGap and optimalLineBreaking are read by the Sandbox's viewer, not by renderToHtml. In your own page, size the page yourself and pass mode and columnGap to renderToHtml; overrides are applied with applyHtmlViewerOverrides. HTML reading edition →

Pitfall

An opener reserves height down to its lowest page-anchored element

An advanced-design opener reserves the height of its lowest element, and page- or bleed-anchored elements below the heading count too, so decoration at the foot of the page pushes the text to the next page. Give such an element reserve: false (since postext 1.5): it is painted where it is anchored and reserves nothing. Elements that follow the band itself (anchored to its foot, or 'fill' tall) never set its height. Designed openers →

  • Keep the pane at least 400 px tall (the pen's min-height). In a narrow pane less than about 350 px tall, the screen opener is taller than the page's content area; it then takes the whole page, and the note's first paragraph starts on the next one.
  • Give the pane a size before you lay it out. A pane with no width, hidden or squeezed out of a flex row, would give a zero-width page, which is why showScreen() skips a pane narrower or shorter than FOLDED, 200 px.

Credits

Text
Original prose, CC BY 4.0
Images
  • Radiation fog in a valley at dawn (Figure 2) · Generated With Diffusion Models · original
  • The rain gauge, the wind rose and the part page's rain, drawn in code in both palettes · Ignacio Ferro · CC BY 4.0
Fonts
Newsreader (SIL OFL 1.1) · Gloock (SIL OFL 1.1) · Reddit Sans (SIL OFL 1.1)
Sandbox