Skip to main content
Recipe number 103

Cookbook · Chapter 10 · Output & integration

A bench for the Folio viewer's settings

A form of every config.folio setting drives one postext-folio viewer through setAppearance: paper, binding, covers, desk, light and tilt change in place.

  • Trim 110 × 160 mm
  • 1 column
  • Source Serif 4 9.3/12.4
  • Outfit
  • 10 pages
  • Level
  • Postext 1.57.1
  • Laid out in 51 ms
  • 144 lines of code

In short

A small pocket book shown in 3D next to a panel of controls. Change the paper, the binding, the desk or the light and the book changes at once, without being set again.

What you'll build

Six Knots, a ten-page pocket book on a 110 × 160 mm trim, opened in Folio next to a panel with every setting of config.folio. Pick a stock and the leaves change colour, surface and stiffness; switch the binding from paperback to hardcover and a case grows round the block; choose the case instead of the printed covers, a cloth or leather material, a desk, a light, a tilt. The book is laid out once. Every change goes to the viewer with setAppearance, so no line moves and no page is painted again, and the settings appear under the form as the code to paste into config.folio.

This recipe answers

  • How do I preview a book's binding, cover, paper and lighting before it goes to print?
  • How do I show my document as a 3D book whose pages the reader turns by hand?

The short answer

script.js · lines 196–220in full code
const book = createFolioFromDocument(document.getElementById('folio'), doc, {
  // The look starts from doc.config.folio; setAppearance replaces it on every change.
  appearance: { textureBaseUrl: 'https://postext.dev/folio/textures' },
  onChange: ({ pages }) => kitStatus(`${doc.pages.length} pages · open at `
    + pages.map((i) => i + 1).join('–')),
});
function update() {
  const folio = folioOf();
  // Only the appearance changes: the pages keep their paintings, nothing is laid out again.
  book.setAppearance({ folio });
  show('grammage-out', `${folio.paper.grammage} g/m²`);
  show('intensity-out', folio.lighting.intensity.toFixed(2));
  show('tilt-out', `${folio.tilt}°`);
  document.getElementById('folio-json').textContent = `folio: ${JSON.stringify(folio, null, 2)}`;
}
form.addEventListener('input', update);
// A stock sets its own weight: picking one moves the weight slider to the stock's.
const WEIGHTS = { uncoated: 90, bookWove: 80, coatedMatte: 115, coatedSilk: 115,
  coatedGloss: 115, bible: 40, newsprint: 48, cardStock: 250 };
form.elements['paper.type'].addEventListener('change', (event) => {
  form.elements['paper.grammage'].value = WEIGHTS[event.target.value];
  update();
});
document.getElementById('reset-view').addEventListener('click', () => book.resetView());
update();

One viewer, restyled in place by setAppearance on every change

Ingredients

Type
Source Serif 4, Outfit (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Name the fields after the config

script.js · lines 72–86in full code
const form = document.getElementById('controls');
const hex = (value) => ({ hex: value, model: 'hex' });
function folioOf() { // 'paper.grammage' → { paper: { grammage } }, typed by the input
  const folio = {};
  for (const el of form.elements) {
    if (!el.name || el.type === 'button' || el.tagName === 'OUTPUT') continue;
    const value = el.type === 'checkbox' ? el.checked : el.type === 'range' ? Number(el.value)
      : el.type === 'color' ? hex(el.value) : el.value;
    const [group, key] = el.name.split('.');
    if (key) (folio[group] ??= {})[key] = value;
    else folio[group] = value;
  }
  return folio;
}
const show = (name, value) => { form.elements[name].value = value; };

Each field of the form is named by its path in config.folio (paper.grammage, binding.cover, lighting.environment), so one loop turns the form into the object the viewer takes: numbers from the sliders, booleans from the checkboxes, a { hex, model } colour from the picker. The same object is the document's own config.folio when the pen builds it, so the Sandbox opens the book as the form starts.

#2 · Covers the viewer can turn as boards

script.js · lines 40–61in full code
const field = { kind: 'box', id: 'field', style: { backgroundColor: col('brick') },
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(TRIM_H) } } };
const flush = { numbered: false, span: 'page', footer: { elements: [] },
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const cover = (id, title, extra = {}) => ({ id, ...flush, ...extra, advancedDesign: {
  enabled: true, minHeight: mm(TRIM_H), slot: { elements: [field, ...title] } } });
const headingStyles = [
  cover('cover', [
    text('title', '{titleText}', { fontFamily: SANS, fontWeight: 700, fontSize: pt(40),
      lineHeight: 0.92, color: col('cream') },
    { ...at('page', 'top-left', INNER, 30), size: { width: mm(80) } }),
    text('strap', '{attr.strap}', { fontFamily: 'Source Serif 4', italic: true,
      fontSize: pt(11), lineHeight: 1.3, color: col('cream') },
    { ...at('#title', 'below', 0, 6), size: { width: mm(72) } }),
    text('author', '{author}', caps(7, col('cream')), at('page', 'bottom-left', INNER, -16)),
  ]),
  cover('back', [
    text('strap', '{attr.strap}', { fontFamily: 'Source Serif 4', italic: true,
      fontSize: pt(11), lineHeight: 1.3, color: col('cream'), align: 'center' },
    { ...at('page', 'center', 0, 0), size: { width: mm(76) } }),
  ], { breakBefore: { enabled: true, parity: 'even' } }), // the back: always a verso
];

With binding.cover: 'pages' the first page is the front board and the last the back, when it falls on a verso. The back cover's heading style breaks to an even page, so the book always ends on a verso and both covers turn. Switch the form to A case round the pages and the same two pages turn as ordinary leaves inside a cloth case.

#3 · Restyle the book in place

The code is the short answer above. setAppearance({ folio }) replaces the document's settings and redraws the scene: paper thickness and stiffness, the case, the desk maps and the light. The pages keep their paintings, so a change lands in the next frame. A stock sets its own weight, which is why picking one moves the weight slider; resetView() brings the camera back after the reader orbits the book with a right-drag.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 103 · A bench for the Folio viewer's settings ═══════════════
// https://postext.dev/en/cookbook/folio-settings-bench
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Outfit (SIL OFL 1.1) · Needs postext ≥ 1.26.0
//
// A pocket book of knots, laid out once and opened in postext-folio next to a form of every
// folio setting: paper, binding, covers, desk, light and tilt. Each change goes to the viewer
// with setAppearance, so the book is redrawn in place and no page is laid out or painted
// again. The settings as code sit under the form, ready to paste into config.folio.
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { createFolioFromDocument } from 'https://esm.sh/postext-folio';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: brick red for the covers and the knot numbers, a warm ink for the text
const palette = {
  ink: '#24211f',
  brick: '#9a3b2e', // the cover field, kickers and folios
  cream: '#f6efe2', // type on the covers
  muted: '#6f6860',
};
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.brick, model: 'hex' } },
];
// #endregion
const [TRIM_W, TRIM_H, TOP, BOTTOM, INNER, OUTER] = [110, 160, 15, 17, 14, 12]; // mm: a pocket
const LEAD = 12.4; // pt
const SANS = 'Outfit';
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, overflow: 'wrap',
  align: 'left', placement, ...look });
const caps = (size, color) => ({ fontFamily: SANS, fontSize: pt(size), fontWeight: 600,
  letterSpacing: pt(size * 0.16), textTransform: 'uppercase', color });

// #region covers: a full-page colour field on page 1 and on the last page
const field = { kind: 'box', id: 'field', style: { backgroundColor: col('brick') },
  placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(TRIM_H) } } };
const flush = { numbered: false, span: 'page', footer: { elements: [] },
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const cover = (id, title, extra = {}) => ({ id, ...flush, ...extra, advancedDesign: {
  enabled: true, minHeight: mm(TRIM_H), slot: { elements: [field, ...title] } } });
const headingStyles = [
  cover('cover', [
    text('title', '{titleText}', { fontFamily: SANS, fontWeight: 700, fontSize: pt(40),

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

#Start from a hardcover in a cloth case

Change the form's defaults in index.html; the document and the Sandbox follow them.

-        <option value="hardcover">Hardcover</option><option value="paperback" selected>Paperback</option>
+        <option value="hardcover" selected>Hardcover</option><option value="paperback">Paperback</option>

#One book, its look in the config

A book on the desk writes the same settings once in config.folio, with no form, and the swatch book sets a different paper on each leaf.

Pitfalls

Pitfall

The Folio viewer takes the size of its container

createFolioFromDocument fits the book into the element you give it, with the buttons and the page count in its margins. An element with no height (an empty div in normal flow) shows nothing: give it a height in CSS. 3D book viewer (Folio) →

Pitfall

cover: 'pages' needs an even page count for the back board

With binding.cover set to 'pages' the first page turns as the front board and the last page as the back board only when it falls on a verso. An odd page count leaves the book with a front cover and no back: pad it to an even count or keep the case. Paper, binding, desk and light (Folio) →

Credits

Text
Original prose, CC BY 4.0
Fonts
Source Serif 4 (SIL OFL 1.1) · Outfit (SIL OFL 1.1)
Sandbox