# Una carta de forn en tinta blanca sobre kraft

> El blanc opac com a tinta plana sobre kraft: lletra blanca sobre la cartolina bruna, un fons blanc sota lletra bruna i blanc calat en un plafó verd.

- Versió HTML: https://postext.dev/ca/cookbook/white-ink-kraft-menu
- Recepta Núm. 191 · Sortida i integració · Nivell 3 (Avançat) · Sortides: Canvas, PDF
- Gèneres: Fulls solts i efímers
- Requereix postext ≥ 1.85.1, postext-pdf ≥ 1.85.1 · provada amb 1.85.1, postext-pdf 1.85.1 el 2026-11-13
- Pàgines: [1](https://postext.dev/cookbook/white-ink-kraft-menu/es/p01.webp?v=2f25d1bb), [2](https://postext.dev/cookbook/white-ink-kraft-menu/es/p02.webp?v=2f25d1bb), [3](https://postext.dev/cookbook/white-ink-kraft-menu/es/p03.webp?v=2f25d1bb), [4](https://postext.dev/cookbook/white-ink-kraft-menu/es/p04.webp?v=2f25d1bb)
- PDF: https://postext.dev/cookbook/white-ink-kraft-menu/es/white-ink-kraft-menu.pdf?v=2f25d1bb
- Obre al Sandbox: https://postext.dev/ca/sandbox#recipe=white-ink-kraft-menu&lang=es (.postext: https://postext.dev/cookbook/white-ink-kraft-menu/es/white-ink-kraft-menu.postext)
- Última actualització: 2026-11-13
- Altres idiomes: [en](https://postext.dev/en/cookbook/white-ink-kraft-menu.md), [es](https://postext.dev/es/cookbook/white-ink-kraft-menu.md), [de](https://postext.dev/de/cookbook/white-ink-kraft-menu.md), [fr](https://postext.dev/fr/cookbook/white-ink-kraft-menu.md), [it](https://postext.dev/it/cookbook/white-ink-kraft-menu.md), [pt](https://postext.dev/pt/cookbook/white-ink-kraft-menu.md), [zh](https://postext.dev/zh/cookbook/white-ink-kraft-menu.md), [ja](https://postext.dev/ja/cookbook/white-ink-kraft-menu.md), [ar](https://postext.dev/ar/cookbook/white-ink-kraft-menu.md)

## En poques paraules

La carta d'un forn impresa en cartolina kraft marró. El nom i els títols van en una tinta blanca que la impremta afegeix com una tinta més. L'arxiu d'impremta posa el blanc en una planxa pròpia.

## Què compondràs

La carta d'Horno Alto, un forn de poble inventat: una cartolina kraft A5 plegada una vegada, quatre pàgines. El kraft no té blanc, així que cada blanc de la carta és una tinta que afegeix la impremta: el nom i els títols de secció directament sobre el bru, els paspartús on van les tres pintures al gouache i la targeta de l'horari. Els preus van en un tabulador amb línia de punts, en un bru fosc de quadricromia. A la pàgina del cafè, un plafó verd porta la fornada del dia en lletra blanca calada en el verd. Folio obre la carta sobre un taulell de roure amb llum de dia.

**Aquesta recepta respon a:**

- Com imprimeixo en blanc sobre paper kraft, com a lletra i sota els colors?

## La resposta curta

```js
// script.js, línies 20–35
// The paper is a colour that prints no ink: the screen and Folio paint kraft, and no plate
// gets a dot of it. Because it is not white, the preflight knows the white ink shows on it.
// The white is a spot ink with the white finish: its own plate, laid down before the others.
const kraft = { hex: '#c19a6b', model: 'cmyk', cmyk: { c: 0, m: 0, y: 0, k: 0 } };
const WHITE = { name: 'Opaque White', cmyk: { c: 0, m: 0, y: 0, k: 0 } };
// A white ink overprints by default: laid under the colours, it must not cut holes in them.
const white = { hex: '#f7f4ee', model: 'spot', spot: { ...WHITE, finish: { kind: 'white' } } };
const PRINT = { standard: 'pdfx4', outputProfile: 'fogra52', convertImages: false,
  inks: [{ name: 'Opaque White', aliases: ['White'], finish: { kind: 'white' } }] };

// White type on a green panel must knock the green out.
// White printed under the green is hidden by it. For white type on a colour, the type must cut
// its shape out of the colour, so this white says overprint: false. Its hex differs by one
// step from the other white, since the PDF tells colours apart by hex; both print on one plate.
const whiteOut = { hex: '#f6f3ed', model: 'spot',
  spot: { ...WHITE, finish: { kind: 'white' }, overprint: false } };
```

## Ingredients

**Ensenya**

- [Tintes especials](https://postext.dev/ca/docs/special-inks-die-cuts.md#acabats): Una tinta plana amb acabat: metàl·lica, daurat en calent, fluorescent, blanc opac o vernís. S'imprimeix en una planxa pròpia, el canvas en pot mostrar la brillantor o un mapa d'acabats, i Folio la il·lumina.
- [Tintes planes i taula de tintes](https://postext.dev/ca/docs/configuration-pdf-output.md#tintes-planes): Un color amb model 'spot' s'imprimeix en una planxa pròpia, al seu percentatge. La taula de tintes anomena la planxa com la coneix l'impressor i aplega els altres noms que la paleta, els SVG i els fitxers importats donen a la mateixa tinta.

**També fa servir**

- [PDF en CMYK i en escala de grisos](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#generació-de-pdf-configuració)
- [Visor de llibre en 3D (Folio)](https://postext.dev/ca/docs/configuration-html-folio-epub.md#un-llibre-en-3d-postext-folio)
- [Paper, enquadernació, taula i llum (Folio)](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#visor-folio-configuració)
- [Paleta de color semàntica](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors)
- [Cobertes, portades i colofons](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Estils de títol](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Textos, filets i caixes als dissenys de pàgina](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus)
- [Imatges als dissenys de pàgina](https://postext.dev/ca/docs/configuration-headers-footers.md#elements-dimatge)
- [Estils de paràgraf](https://postext.dev/ca/docs/configuration-styles.md#estils-de-paràgraf)
- [Tabuladors i farciments](https://postext.dev/ca/docs/configuration-text.md#tabulacions)
- [Requadres](https://postext.dev/ca/docs/configuration-callouts.md#estils-de-requadre)
- [Exportació a PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#generació-de-pdf)
- [Pàgines en un canvas](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits)
- [Atributs de títol](https://postext.dev/ca/docs/document-format.md#atributs-dencapçalament)
- [Banda de capítol d'amplada completa](https://postext.dev/ca/docs/configuration-headings.md#extensió-i-disseny-avançat)
- [Obertures dissenyades](https://postext.dev/ca/docs/configuration-headings.md#extensió-i-disseny-avançat)
- [Color del paper](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina)
- [Fonts incrustades al PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#per-què-un-proveïdor-de-fonts)
- [Tipus de recurs propis](https://postext.dev/ca/docs/configuration-resources.md#tipus-de-recurs)
- [Figures i taules com a recursos](https://postext.dev/ca/docs/document-format-resources.md#recursos)
- [Capçaleres per secció](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Capítols sense número](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)

**La configuració d'un cop d'ull**

- [`bodyText`](https://postext.dev/ca/docs/configuration-text.md#text-de-cos), [`calloutStyles`](https://postext.dev/ca/docs/configuration-callouts.md#estils-de-requadre), [`colorPalette`](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors), [`folio`](https://postext.dev/ca/docs/configuration-html-folio-epub.md#aspecte), [`footer`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`header`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`headingStyles`](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament), [`headings`](https://postext.dev/ca/docs/configuration-headings.md#encapçalaments), [`layout`](https://postext.dev/ca/docs/configuration-page-layout.md#disposició), [`locale`](https://postext.dev/ca/docs/configuration-language.md#partició-de-mots), [`page`](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina), [`paragraphStyles`](https://postext.dev/ca/docs/configuration-styles.md#estils-de-paràgraf), [`print`](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#producció-per-a-impremta-configuració), [`resourceTypes`](https://postext.dev/ca/docs/configuration-resources.md#tipus-de-recurs)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre), [`createFolioFromDocument`](https://postext.dev/ca/docs/configuration-html-folio-epub.md#un-llibre-en-3d-postext-folio), [`decompressWoff2`](https://postext.dev/ca/docs/configuration-pdf-output.md#proveïdor-de-fonts-al-navegador-fontsource--woff2), `preflightDocument`, [`registerResourceImage`](https://postext.dev/ca/docs/architecture.md#superfície-dapi), [`renderPageToCanvas`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits), [`renderToPdf`](https://postext.dev/ca/docs/configuration-pdf-output.md#generació-de-pdf)

**Tipus de lletra**

- Alfa Slab One (OFL-1.1), Lora (OFL-1.1)

## Elaboració

### 1 · El paper és kraft i el blanc és una tinta

El codi és [la resposta curta](https://postext.dev/ca/cookbook/white-ink-kraft-menu.md#la-resposta-curta) de més amunt. El paper és un color de la paleta definit en CMYK al 0 %: la pantalla i Folio pinten el kraft i cap planxa no l'imprimeix. El blanc és una tinta plana amb l'acabat blanc ([acabats](https://postext.dev/ca/docs/special-inks-die-cuts.md#acabats)), anomenada `Opaque White` a la taula de tintes, tal com se li dirà a la impremta. El PDF/X-4 la posa en una `Separation` pròpia al costat de les quatre planxes de quadricromia. El seu hex de pantalla queda un pas per sota de `#ffffff`, perquè la màscara d'acabats distingeixi la tinta d'un full blanc.

### 2 · Blanc directament sobre el bru

```js
// script.js, línies 63–70
// The mount is a box in the white, the painting a picture over it. The white goes down first
// on press and runs on under the whole painting, so its light tones print on white.
const mount = (x, y, w, h, extra) => [
  { kind: 'box', id: 'mount', style: { backgroundColor: col('white') },
    placement: at('page', 'top-left', x, y, { width: mm(w), height: mm(h) }) },
  { kind: 'image', id: 'photo', resourceId: '{attr.photo}', fit: 'cover', ...extra,
    placement: at('page', 'top-left', x + 4, y + 4, { width: mm(w - 8), height: mm(h - 8) }) },
];
```

El nom, els títols de secció i els de les pàgines interiors són lletra en el blanc, en Alfa Slab One. Una tinta blanca cobreix menys que el negre: el bru es transparenta en un traç fi, així que una egípcia gruixuda de 12 pt o més es llegeix on una romana fina quedaria beix. Els paspartús són caixes en el mateix blanc, 4 mm més grans que cada pintura per tots els costats. El blanc continua per sota de tota la pintura, no només al voltant, així que els tons clars de la pintura s'imprimeixen sobre blanc i no sobre el bru.

### 3 · Color damunt del blanc

L'horari va sobre una targeta de tinta blanca, en el bru fosc del text de la carta. Una tinta blanca se sobreimprimeix per defecte, i el bru també (`overprint: true` en el color de la paleta), així que a la màquina el bru cau sobre el blanc en lloc de calar-hi les lletres.

### 4 · Blanc damunt del color: calat

```js
// script.js, línies 114–126
const calloutStyles = [
  { id: 'bake', background: col('green'), marginTop: pt(LEAD), marginBottom: pt(0),
    padding: { top: mm(4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: { fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('whiteOut'),
      boldColor: col('whiteOut'), italicColor: col('whiteOut'), textAlign: 'left',
      firstLineIndent: pt(0) } },
  // The hours: brown type on a card of white ink, the colour printed over the white.
  { id: 'hours', background: col('white'), marginTop: pt(LEAD), marginBottom: pt(0),
    padding: { top: mm(4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: { fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
      boldColor: col('ink'), textAlign: 'left', firstLineIndent: pt(0),
      tabStops: [{ position: 'end', align: 'end' }] } },
];
```

La màquina posa primer el blanc i al damunt els colors, així que una lletra blanca sobre el plafó verd desapareixeria sota el verd. La lletra del plafó pren un segon blanc de la mateixa planxa, amb `overprint: false`: la lletra retalla la seva forma en el verd i el blanc l'omple. Els dos blancs es diferencien en un pas d'hex perquè el PDF distingeix els colors pel seu hex.

### 5 · Els preus en un tabulador

```js
// script.js, línies 106–110
const dish = { id: 'dish', name: 'Dish', textAlign: 'left',
  tabStops: [{ position: 'end', align: 'end', leader: '. ' }],
  spaceBetween: pt(LEAD / 3), marginTop: pt(LEAD / 2) };
// The story on the back: half a line between paragraphs.
const story = { id: 'story', name: 'Story', spaceBetween: pt(LEAD / 2) };
```

Cada secció és un grup `:::paragraphs` amb l'estil de plat; `:tab` abans del preu l'envia al final de la mida amb una línia de punts fins a ell, com a [la carta del bistrot](https://postext.dev/ca/cookbook/bistro-menu.md).

### 6 · Què diu la revisió prèvia

```js
// script.js, línies 274–282
// A white ink on white paper prints nothing you can see, and the preflight warns of it
// (whiteInkOnWhite). On kraft it does not fire; the findings left say which special ink the
// job carries and that the press lays the white first.
const findings = preflightDocument(doc);
const report = document.createElement('p');
report.textContent = `Preflight: ${findings.map((f) => f.kind === 'inkPressOrder'
  ? `inkPressOrder (first: ${f.first.join(', ')})` : `${f.kind}${f.ink ? ` (${f.ink})` : ''}`)
  .join('; ') || 'no findings'}`;
document.querySelector(`[data-postext-pdf="${RECIPE}.pdf"]`).after(report);
```

`preflightDocument` avisa amb `whiteInkOnWhite` quan una tinta blanca cau en una pàgina amb paper blanc o sense definir, on no es veu. Sobre kraft no avisa, i la línia sota el botó de baixada mostra el que queda: el blanc com a tinta especial (`spotInkFinish`) i l'ordre de la màquina, que el posa primer (`inkPressOrder`).

### 7 · Folio mostra la carta en un taulell

```js
// script.js, línies 130–136
const folio = {
  tilt: 20, yaw: -12,
  paper: { type: 'cardStock', grammage: 250, texture: 'felt', shade: kraft },
  binding: { type: 'folded', cover: 'pages' },
  surface: { type: 'oak' },
  lighting: { environment: 'daylight', intensity: 1.1 },
};
```

Folio pinta el blanc de manera que cobreix el to del paper, com fa la tinta, i la cartolina amb textura de feltre fa que el bru es llegeixi com a kraft.

## La recepta completa

Un sol fitxer, compost a partir de la carpeta de la recepta amb el text d'exemple i el kit comú del Receptari ja inclosos; construeix la seva pròpia pàgina. Per executar-lo, posa'l en un `<script type="module">` d'una pàgina buida o enganxa'l al tauler JS d'un pen nou de CodePen (com a mòdul). Importa postext des d'esm.sh, així que no cal instal·lar ni compilar res.

- Carpeta de la recepta: https://github.com/drnachio/postext/tree/main/cookbook/white-ink-kraft-menu

### script.js

```js
// ═══ Postext Cookbook · Nº 191 · A bakery menu in white ink on kraft ═════════════════════
// https://postext.dev/en/cookbook/white-ink-kraft-menu
// Code: MIT · Text: original (CC BY 4.0) · Paintings: diffusion models
// Fonts: Alfa Slab One, Lora (SIL OFL 1.1) · Needs postext ≥ 1.85.1
//
// The menu of a bakery, a folded card of brown kraft. Kraft takes no white from the paper, so
// the name and the course heads print in an opaque white ink, and the paintings sit on white
// mounts that the same ink lays under them; the menu text is a dark brown in process colour.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, preflightDocument,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
import { createFolioFromDocument } from 'https://esm.sh/postext-folio';

const LANG = 'es'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'white-ink-kraft-menu';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: kraft as the paper, and an opaque white as a spot ink
// The paper is a colour that prints no ink: the screen and Folio paint kraft, and no plate
// gets a dot of it. Because it is not white, the preflight knows the white ink shows on it.
// The white is a spot ink with the white finish: its own plate, laid down before the others.
const kraft = { hex: '#c19a6b', model: 'cmyk', cmyk: { c: 0, m: 0, y: 0, k: 0 } };
const WHITE = { name: 'Opaque White', cmyk: { c: 0, m: 0, y: 0, k: 0 } };
// A white ink overprints by default: laid under the colours, it must not cut holes in them.
const white = { hex: '#f7f4ee', model: 'spot', spot: { ...WHITE, finish: { kind: 'white' } } };
const PRINT = { standard: 'pdfx4', outputProfile: 'fogra52', convertImages: false,
  inks: [{ name: 'Opaque White', aliases: ['White'], finish: { kind: 'white' } }] };

// White type on a green panel must knock the green out.
// White printed under the green is hidden by it. For white type on a colour, the type must cut
// its shape out of the colour, so this white says overprint: false. Its hex differs by one
// step from the other white, since the PDF tells colours apart by hex; both print on one plate.
const whiteOut = { hex: '#f6f3ed', model: 'spot',
  spot: { ...WHITE, finish: { kind: 'white' }, overprint: false } };
// #endregion

const palette = {
  kraft, white, whiteOut,
  // The brown overprints: on the white card it lands on the white instead of cutting it away.
  ink: { hex: '#3b2a1c', model: 'cmyk', cmyk: { c: 0, m: 45, y: 75, k: 82 }, overprint: true },
  green: { hex: '#2f5a43', model: 'cmyk', cmyk: { c: 80, m: 25, y: 75, k: 40 } }, // the panel
};
const col = (id) => ({ ...palette[id], paletteId: id });
const colorPalette = [...Object.entries(palette).map(([id, value]) => ({ id, name: id, value })),
  { id: 'main-color', name: 'ink (defaults)', value: palette.ink }];

const [TRIM_W, TRIM_H] = [148, 210]; // A5, an A4 card folded once
const MARGIN = 13;
const MEASURE = TRIM_W - 2 * MARGIN;
const [BODY, LEAD] = [9.6, 13.2]; // pt
const [DISPLAY, SERIF] = ['Alfa Slab One', 'Lora'];
const at = (to, edge, x = 0, y = 0, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, align: 'left',
  overflow: 'wrap', placement, ...look });
const label = (size, color) => ({ fontFamily: SERIF, fontWeight: 700, fontSize: pt(size),
  letterSpacing: pt(size * 0.14), textTransform: 'uppercase', color });
const bare = { numbered: false, toc: false, span: 'page', header: { elements: [] },
  footer: { elements: [] } };

// #region mount: a painting on a white mount, 4 mm of white round it
// The mount is a box in the white, the painting a picture over it. The white goes down first
// on press and runs on under the whole painting, so its light tones print on white.
const mount = (x, y, w, h, extra) => [
  { kind: 'box', id: 'mount', style: { backgroundColor: col('white') },
    placement: at('page', 'top-left', x, y, { width: mm(w), height: mm(h) }) },
  { kind: 'image', id: 'photo', resourceId: '{attr.photo}', fit: 'cover', ...extra,
    placement: at('page', 'top-left', x + 4, y + 4, { width: mm(w - 8), height: mm(h - 8) }) },
];
// #endregion

// The cover: the name in white straight on the kraft, the loaf on its mount.
const cover = { ...bare, id: 'cover', advancedDesign: { enabled: true, minHeight: mm(170),
  slot: { elements: [
    text('title', '{titleText}', { fontFamily: DISPLAY, fontSize: pt(50), lineHeight: 0.9,
      textTransform: 'uppercase', align: 'center', color: col('white') },
    at('page', 'top-left', MARGIN, 22, { width: mm(MEASURE) })),
    text('since', '{attr.since}', { ...label(8, col('ink')), align: 'center' },
      at('#title', 'below', 0, 3, { width: mm(MEASURE) })),
    ...mount(26, 64, 96, 96),
    text('address', '{attr.address}', { fontFamily: SERIF, italic: true,
      fontSize: pt(10), lineHeight: 1.35, color: col('ink'), align: 'center' },
    at('page', 'top-left', MARGIN, 172, { width: mm(MEASURE) })),
  ] } } };

// The inside pages open on a painting across the measure, the kicker and the title in white.
const opener = (id, height) => ({ ...bare, id, advancedDesign: { enabled: true,
  minHeight: mm(height + 20), slot: { elements: [
    ...mount(MARGIN, 14, MEASURE, height),
    text('kicker', '{attr.kicker}', label(7.5, col('ink')),
      at('page', 'top-left', MARGIN, 18 + height)),
    text('title', '{titleText}', { fontFamily: DISPLAY, fontSize: pt(24), lineHeight: 1,
      textTransform: 'uppercase', color: col('white') },
    at('#kicker', 'below', 0, 1.5, { width: mm(MEASURE) })),
  ] } } });

// The back: the bakery's story in brown, the hours on a white card.
const back = { ...bare, id: 'back', advancedDesign: { enabled: true, minHeight: mm(14),
  slot: { elements: [
    text('title', '{titleText}', { fontFamily: DISPLAY, fontSize: pt(24), lineHeight: 1,
      textTransform: 'uppercase', color: col('white') }, at('container', 'top-left')),
  ] } } };

// #region dishes: a dish and its price on a tab stop, dotted to the right margin
const dish = { id: 'dish', name: 'Dish', textAlign: 'left',
  tabStops: [{ position: 'end', align: 'end', leader: '. ' }],
  spaceBetween: pt(LEAD / 3), marginTop: pt(LEAD / 2) };
// The story on the back: half a line between paragraphs.
const story = { id: 'story', name: 'Story', spaceBetween: pt(LEAD / 2) };
// #endregion

// #region panel: the day's bake on green, its type knocked out in white
const calloutStyles = [
  { id: 'bake', background: col('green'), marginTop: pt(LEAD), marginBottom: pt(0),
    padding: { top: mm(4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: { fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('whiteOut'),
      boldColor: col('whiteOut'), italicColor: col('whiteOut'), textAlign: 'left',
      firstLineIndent: pt(0) } },
  // The hours: brown type on a card of white ink, the colour printed over the white.
  { id: 'hours', background: col('white'), marginTop: pt(LEAD), marginBottom: pt(0),
    padding: { top: mm(4), right: mm(5), bottom: mm(4), left: mm(5) },
    body: { fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
      boldColor: col('ink'), textAlign: 'left', firstLineIndent: pt(0),
      tabStops: [{ position: 'end', align: 'end' }] } },
];
// #endregion

// #region folio: a folded kraft card on an oak counter, in daylight
const folio = {
  tilt: 20, yaw: -12,
  paper: { type: 'cardStock', grammage: 250, texture: 'felt', shade: kraft },
  binding: { type: 'folded', cover: 'pages' },
  surface: { type: 'oak' },
  lighting: { environment: 'daylight', intensity: 1.1 },
};
// #endregion

const config = () => ({
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
    backgroundColor: col('kraft'), margins: { top: mm(14), bottom: mm(14), left: mm(MARGIN),
      right: mm(MARGIN) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: SERIF, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), textAlign: 'left', firstLineIndent: pt(0),
    hyphenation: { enabled: false }, avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: DISPLAY, fontWeight: 400, color: col('white'), levels: [
    { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'any' } },
    { level: 2, fontSize: pt(12), lineHeight: pt(LEAD), letterSpacing: pt(1.2),
      textTransform: 'uppercase', marginTop: pt(LEAD), marginBottom: pt(0) }] },
  headingStyles: [cover, opener('wide', 54), opener('square', 56), back],
  paragraphStyles: [dish, story], calloutStyles,
  print: PRINT,
  header: { elements: [] }, footer: { elements: [] }, folio,
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Horno Alto"
---

# Horno Alto {style="cover" photo="loaf" since="Panadería y café · desde 1987" address="Calle del Pozo 14 · de martes a domingo, de siete a siete"}

# Del horno {style="wide" photo="pastries" kicker="Pan y bollería"}

## Pan

:::paragraphs{style="dish"}
**Hogaza de masa madre**, 800 g, trigo y centeno :tab **4,80**\
*Tres días de la masa madre a la corteza, al horno a las cinco cada mañana*

**Centeno con semillas**, 600 g, pipas, lino y calabaza :tab **4,20**\
*Denso y oscuro, mejor en rebanadas finas; aguanta una semana*

**Pan de aceite**, 500 g :tab **3,60**\
*El de las tostadas*

**Pan del día**, pregunta en el mostrador :tab **3,90**
:::

## Bollería

:::paragraphs{style="dish"}
**Cruasán de mantequilla** :tab **1,80**\
*Laminado en dos días con mantequilla asturiana*

**Caracola de canela**, glaseada :tab **2,40**

**Tarta de almendra**, la porción :tab **3,20**\
*Almendra molida, ralladura de limón, sin harina*

**Trenza de queso y membrillo** :tab **2,60**
:::

# En el mostrador {style="square" photo="coffee" kicker="Café y desayunos"}

## Café

:::paragraphs{style="dish"}
**Café solo** :tab **1,40**

**Cortado** :tab **1,60**

**Café con leche**, taza grande :tab **2,10**

**Chocolate**, espeso, para mojar :tab **2,80**
:::

## Desayunos

:::paragraphs{style="dish"}
**Tostada con tomate y aceite** :tab **3,20**

**Tostada con mantequilla y mermelada de albaricoque** :tab **3,00**

**Cruasán y café** :tab **3,00**
:::

:::callout{type="bake"}
**La hornada de hoy.** Pan de calabaza y nueces, desde las once hasta que se acabe. Pídelo en rebanada, templado y con mantequilla.
:::

# Desde 1987 {style="back"}

:::paragraphs{style="story"}
El horno del cuarto de atrás lo levantó el padre de Rosa Alto el año en que abrió la panadería, con ladrillo y con el barro del río que pasa bajo el pueblo. Todavía cuece cada hogaza. Rosa lleva hoy la panadería con su hijo Pablo, que volvió de tres años en una panadería de Lyon con un cruasán del que no paraba de hablar.

Cocemos con harina de dos molinos de la provincia, mantequilla asturiana y huevos de la granja de la carretera de Sigüenza. Lo que no se vende a las siete va al albergue de la calle Mayor.
:::

:::callout{type="hours"}
**De martes a viernes** :tab 7.00 – 19.00\
**Sábados y domingos** :tab 8.00 – 19.00\
**Lunes** :tab cerrado
:::

:::paragraphs{style="story"}
*Calle del Pozo 14 · 949 214 387 · Cortamos hogazas enteras por encargo.*
:::
`; // content.<lang>.md, inlined by the Cookbook

const painting = (id, [w, h], altText) => ({ id, typeId: 'painting', kind: 'bitmap',
  createdAt: 0, updatedAt: 0, bitmap: { fileId: `${id}.jpg`, format: 'jpeg', width: w,
    height: h }, altText });
const resourceTypes = [{ id: 'painting', name: '', captionPrefix: '', numberingTemplate: '' }];
const resources = [
  painting('loaf', [700, 683], t({ en: 'A round sourdough loaf with a floured, cross-cut crust, '
    + 'painted in gouache.', es: 'Una hogaza redonda de masa madre con la corteza enharinada '
    + 'y cortada en cruz, pintada al gouache.' })),
  painting('pastries', [900, 396], t({ en: 'A croissant, a glazed cinnamon roll and a slice of '
    + 'almond cake.', es: 'Un cruasán, una caracola de canela glaseada y una porción de tarta '
    + 'de almendra.' })),
  painting('coffee', [600, 600], t({ en: 'A white cup of milky coffee on a saucer, a spoon '
    + 'beside it.', es: 'Una taza blanca de café con leche en su plato, con la cucharilla.' })),
];
await Promise.all([loadImage('loaf.jpg', asset('loaf-700.jpg')),
  loadImage('pastries.jpg', asset('pastries-900.jpg')),
  loadImage('coffee.jpg', asset('coffee-600.jpg'))]);

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'Alfa Slab One': ['400'], Lora: ['400', '400i', '700'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown, resources }, { ...config(), resourceTypes },
  kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Horno Alto · a bakery menu in white ink on kraft',
  es: 'Horno Alto · una carta de panadería en tinta blanca sobre kraft' }) });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes,
  profileBaseUrl: 'https://postext.dev/icc/' }), `${RECIPE}.pdf`);

// #region preflight: what the press check says of the white
// A white ink on white paper prints nothing you can see, and the preflight warns of it
// (whiteInkOnWhite). On kraft it does not fire; the findings left say which special ink the
// job carries and that the press lays the white first.
const findings = preflightDocument(doc);
const report = document.createElement('p');
report.textContent = `Preflight: ${findings.map((f) => f.kind === 'inkPressOrder'
  ? `inkPressOrder (first: ${f.first.join(', ')})` : `${f.kind}${f.ink ? ` (${f.ink})` : ''}`)
  .join('; ') || 'no findings'}`;
document.querySelector(`[data-postext-pdf="${RECIPE}.pdf"]`).after(report);
// #endregion

// The card in the hand, open on the inside, so the white reads against the brown.
const stage = document.createElement('section');
stage.id = 'folio';
stage.ariaLabel = t({ en: 'The menu in 3D', es: 'La carta en 3D' });
stage.style.cssText = 'height: min(78vh, 720px); margin: 0 auto; max-width: 1280px';
document.getElementById('pages').before(stage);
createFolioFromDocument(stage, doc, { at: 2,
  appearance: { textureBaseUrl: 'https://postext.dev/folio/textures' } });

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## Variants

### Una coberta de llibreta

Canvia la carta per un títol i un dibuix de filets blancs a la portada: el paper, la tinta i la taula de tintes es queden com estan.

### Dues passades de blanc

La impremta pot fer dues passades de blanc perquè blanquegi més sobre un kraft fosc. Demana-ho a la comanda; l'arxiu és el mateix, amb una sola planxa de blanc.

## Errors freqüents

- Una tinta blanca en una pàgina amb paper blanc o sense definir no deixa res visible. Defineix `page.backgroundColor` amb el suport, en CMYK al 0 %, i la revisió deixa d'avisar.
- Una imatge impresa directament sobre el kraft, sense blanc a sota, deixa veure el bru en tots els tons clars. Posa una caixa del blanc sota cada imatge que hagi de conservar els colors, com fan aquí els paspartús.
- La lletra blanca sobre un color no s'ha de sobreimprimir. Amb el valor per defecte s'imprimeix sota el color i desapareix.

## Crèdits

- Recepta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Imatges: A sourdough loaf, on the cover: Generated With Diffusion Models, original
- Imatges: Three pastries: Generated With Diffusion Models, original
- Imatges: A cup of coffee: Generated With Diffusion Models, original
- Tipus de lletra: Alfa Slab One (OFL-1.1), Lora (OFL-1.1)
- Codi: MIT · Contingut d'exemple: CC-BY-4.0

## Relacionades

- [Núm. 052 · Carta de bistrot: preus en una tabulació](https://postext.dev/ca/cookbook/bistro-menu.md): Una carta de bistrot de dues cares: preus en una tabulació al marge dret, vins en una taula sense filets i un filet de llautó a cada costat de cada títol. · Nivell 2 (Intermedi) · Fulls solts i efímers
- [Núm. 188 · Or en calent sobre una coberta blava](https://postext.dev/ca/cookbook/gold-foil-poetry-cover.md): L'or en calent com a tinta plana amb acabat: planxa pròpia al PDF, brillantor a Folio, i cartolina blava i paper crema sense tinta. · Nivell 3 (Avançat) · Poesia
- [Núm. 195 · Un llibre túnel de vint fulls de fondària](https://postext.dev/ca/cookbook/forest-tunnel-book.md): Dinou finestres rodones troquelades amb dieCuts, cadascuna més petita que l’anterior: des de la coberta es veu a través de vint plans fins a un cérvol. · Nivell 3 (Avançat) · Fulls solts i efímers
