# Dorure à chaud sur une couverture bleu nuit

> La dorure comme ton direct avec une finition : sa propre plaque dans le PDF, l’éclat dans Folio, et une carte bleue et un vélin crème sans encre.

- Version HTML: https://postext.dev/fr/cookbook/gold-foil-poetry-cover
- Recette Nº 188 · Sortie et intégration · Niveau 3 (Avancé) · Sorties: Canvas, PDF
- Genres: Poésie
- Nécessite postext ≥ 1.85.1, postext-pdf ≥ 1.85.1 · testée avec 1.85.1, postext-pdf 1.85.1 le 2026-11-13
- Pages: [1](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p01.webp?v=8f5ad26a), [2](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p02.webp?v=8f5ad26a), [3](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p03.webp?v=8f5ad26a), [4](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p04.webp?v=8f5ad26a), [5](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p05.webp?v=8f5ad26a), [6](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p06.webp?v=8f5ad26a), [7](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p07.webp?v=8f5ad26a), [8](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p08.webp?v=8f5ad26a), [9](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p09.webp?v=8f5ad26a), [10](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p10.webp?v=8f5ad26a), [11](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p11.webp?v=8f5ad26a), [12](https://postext.dev/cookbook/gold-foil-poetry-cover/en/p12.webp?v=8f5ad26a)
- PDF: https://postext.dev/cookbook/gold-foil-poetry-cover/en/gold-foil-poetry-cover.pdf?v=8f5ad26a
- Ouvrir dans le Sandbox: https://postext.dev/fr/sandbox#recipe=gold-foil-poetry-cover&lang=en (.postext: https://postext.dev/cookbook/gold-foil-poetry-cover/en/gold-foil-poetry-cover.postext)
- Dernière mise à jour: 2026-11-13
- Autres langues: [en](https://postext.dev/en/cookbook/gold-foil-poetry-cover.md), [es](https://postext.dev/es/cookbook/gold-foil-poetry-cover.md), [ca](https://postext.dev/ca/cookbook/gold-foil-poetry-cover.md), [de](https://postext.dev/de/cookbook/gold-foil-poetry-cover.md), [it](https://postext.dev/it/cookbook/gold-foil-poetry-cover.md), [pt](https://postext.dev/pt/cookbook/gold-foil-poetry-cover.md), [zh](https://postext.dev/zh/cookbook/gold-foil-poetry-cover.md), [ja](https://postext.dev/ja/cookbook/gold-foil-poetry-cover.md), [ar](https://postext.dev/ar/cookbook/gold-foil-poetry-cover.md)

## En bref

Un petit recueil de poèmes à couverture bleu foncé, aux lettres dorées marquées dans la carte. Dedans, filets et cadres sont dorés aussi. La vue 3D montre l’éclat de l’or, et le fichier d’impression le garde à part pour l’imprimeur.

## Ce que vous allez composer

Une plaquette de cinq poèmes de Gerard Manley Hopkins, au format 140 × 216 mm, brochée. La couverture et le feuillet qui la suit sont une carte bleu foncé dorée à chaud, sans rien d’autre : un double cadre, le titre en capitales Cinzel, le nom du poète et la table des matières. À l’intérieur, sur un vélin crème, les poèmes s’impriment en quadrichromie, un nocturne peint fait face au deuxième poème, et chaque filet de la page est doré : le double filet sous le titre courant, le court filet sous chaque titre, celui qui accompagne le folio. Le titre vient du premier poème, où le monde brille « like shining from shook foil ». Folio tourne le livre fermé vers la lumière, et l’or s’y lit comme du métal.

**Cette recette répond à:**

- Comment dorer la couverture et les filets d’un livre, et livrer la dorure sur une plaque à part ?
- Comment prévisualiser la reliure, la couverture, le papier et l’éclairage d’un livre avant de l’envoyer à l’impression ?

## La réponse courte

```js
// script.js, lignes 21–46
// Gold foil: a spot ink whose finish says what it is. The canvas paints its hex, Folio lights
// it as metal, and a CMYK or PDF/X file puts it on a Separation of its own named 'Gold foil',
// the artwork the foil block is etched from.
const foil = { hex: '#c9a24a', model: 'spot', spot: { name: 'Gold foil',
  cmyk: { c: 15, m: 30, y: 75, k: 10 }, finish: { kind: 'foil', sheen: 'gloss' } } };
// The two stocks are the paper's own colours, not inks: authored in CMYK at 0 % they paint
// on screen and put nothing on any plate. The blue card is a palette value of its own, so a
// section can turn the page blue (palette: { paper: … } in its heading style).
const stock = (hex) => ({ hex, model: 'cmyk', cmyk: { c: 0, m: 0, y: 0, k: 0 } });
const palette = {
  ink: { hex: '#232530', model: 'hex' }, // the poems: a warm near-black in process
  muted: { hex: '#6c6558', model: 'hex' }, // the attributions and the colophon
  foil,
  paper: stock('#f6f0e3'), // cream wove, inside
  card: stock('#1d2a4d'), // deep-blue card, the cover and the opener leaf
};
const col = (id) => ({ ...palette[id], paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, value]) => ({ id, name: id, value })),
  { id: 'main-color', name: 'foil (defaults)', value: foil },
];
// Every blue page takes this: the paper turns to the card, and the head and foot go.
const onCard = { numbered: false, toc: false, palette: { paper: palette.card.hex },
  header: { elements: [] }, footer: { elements: [] } };
// The press file: PDF/X-4, the foil on its plate, the cream and the blue on none.
const PRINT = { standard: 'pdfx4', outputProfile: 'fogra51' };
```

## Ingrédients

**Enseigne**

- [Encres spéciales](https://postext.dev/fr/docs/special-inks-die-cuts.md#finitions): Un ton direct doté d’une finition : métallisé, dorure à chaud, fluorescent, blanc couvrant ou vernis. Il sort sur une plaque à lui, le canvas peut en montrer le brillant ou une carte des finitions, et Folio l’éclaire.
- [PDF en CMJN et en niveaux de gris](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#génération-pdf-configuration): Les couleurs portent un modèle (hex, rgb, cmyk, hsl), et le PDF peut être forcé en CMJN ou en niveaux de gris pour l’imprimeur ou une épreuve.

**Utilise aussi**

- [Visionneuse de livre en 3D (Folio)](https://postext.dev/fr/docs/configuration-html-folio-epub.md#un-livre-en-3d-postext-folio)
- [Papier, reliure, bureau et lumière (Folio)](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#visionneuse-folio-configuration)
- [Un autre papier pour une suite de pages](https://postext.dev/fr/docs/document-format-directives.md#paper)
- [Palette de couleurs sémantique](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs)
- [Vers ligne à ligne](https://postext.dev/fr/docs/document-format-directives.md#verse)
- [Table des matières](https://postext.dev/fr/docs/configuration-notes-references.md#table-des-matières)
- [Styles de titre](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Couvertures, pages de titre et colophons](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Ouvertures composées](https://postext.dev/fr/docs/configuration-headings.md#étendue-et-maquette-avancée)
- [Texte, filets et boîtes dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Images dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-image)
- [Titres courants et folios](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Export PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)
- [Pages sur un canvas](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap)
- [Attributs de titre](https://postext.dev/fr/docs/document-format.md#attributs-de-titre)
- [Couleur du papier](https://postext.dev/fr/docs/configuration-page-layout.md#page)
- [Styles de paragraphe](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)
- [Couleurs par partie](https://postext.dev/fr/docs/configuration-styles.md#le-conteneur-part)
- [Polices intégrées au PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#pourquoi-un-fournisseur-de-polices)
- [Figures et tableaux comme ressources](https://postext.dev/fr/docs/document-format-resources.md#ressources)
- [Géométrie de section](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Titres courants par section](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Tons directs et table des encres](https://postext.dev/fr/docs/configuration-pdf-output.md#tons-directs)
- [Chapitres non numérotés](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)

**La configuration en un coup d’œil**

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`folio`](https://postext.dev/fr/docs/configuration-html-folio-epub.md#apparence), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headingStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe), [`print`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#production-pour-limpression-configuration), [`toc`](https://postext.dev/fr/docs/configuration-notes-references.md#table-des-matières)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page), [`createFolioFromDocument`](https://postext.dev/fr/docs/configuration-html-folio-epub.md#un-livre-en-3d-postext-folio), [`decompressWoff2`](https://postext.dev/fr/docs/configuration-pdf-output.md#fournisseur-de-polices-dans-le-navigateur-fontsource--woff2), [`registerResourceImage`](https://postext.dev/fr/docs/architecture.md#surface-de-lapi), [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), [`renderToPdf`](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)

**Caractères**

- Cormorant Garamond (OFL-1.1), Cinzel (OFL-1.1), Cormorant SC (OFL-1.1)

## Préparation

### 1 · La dorure est un ton direct avec une finition

Le code est dans [la réponse courte](https://postext.dev/fr/cookbook/gold-foil-poetry-cover.md#la-réponse-courte) plus haut. `finish: { kind: 'foil' }` fait du ton direct une encre spéciale ([finitions](https://postext.dev/fr/docs/special-inks-die-cuts.md#finitions)). La mise en page voit une couleur et rien ne bouge ; le canvas peint son hex, Folio l’éclaire comme un métal, et le fichier PDF/X-4 met chaque élément doré sur une seule `Separation` nommée `Gold foil`, d’après laquelle le graveur fait le cliché en laiton. La dorure défonce ce qui se trouve dessous, comme sous la presse à dorer.

### 2 · Les papiers sont des couleurs qui n’impriment aucune encre

```js
// script.js, lignes 190–323
// :::paper{type=cardStock grammage=300}     pages 1–4: the cover leaf and the opener leaf
// # Shook Foil {style="cover"}  # Shook Foil {style="opener"}  # Contents {style="contents"}
// :::
// # God's Grandeur  …  # Spring             pages 5–10: cream wove, the poems
// :::paper{type=cardStock grammage=300}     pages 11–12: the back cover leaf
// # Colophon {style="colophon"}  # Shook Foil {style="back"}
// :::
const markdown = String.raw`---
title: "Shook Foil"
author: "Gerard Manley Hopkins"
---

:::paper{type=cardStock grammage=300}
# Shook Foil {style="cover" kicker="Five poems" years="1877 · 1879"}

# Shook Foil {style="opener" note="Five poems written in Wales and at Oxford, first printed in 1918, after the poet’s death"}

# Contents {style="contents"}

:::toc
:::

# God’s Grandeur {sub="St Beuno’s, 1877"}

:::verse{style="verse"}
The world is charged with the grandeur of God.
  It will flame out, like shining from shook foil;
  It gathers to a greatness, like the ooze of oil
Crushed. Why do men then now not reck his rod?
Generations have trod, have trod, have trod;
  And all is seared with trade; bleared, smeared with toil;
  And wears man’s smudge and shares man’s smell: the soil
Is bare now, nor can foot feel, being shod.

And for all this, nature is never spent;
  There lives the dearest freshness deep down things;
And though the last lights off the black West went
  Oh, morning, at the brown brink eastward, springs —
Because the Holy Ghost over the bent
  World broods with warm breast and with ah! bright wings.
:::

# Nocturne {style="plate"}

# The Starlight Night {sub="St Beuno’s, 1877"}

:::verse{style="verse"}
Look at the stars! look, look up at the skies!
  O look at all the fire-folk sitting in the air!
  The bright boroughs, the circle-citadels there!
Down in dim woods the diamond delves! the elves’-eyes!
The grey lawns cold where gold, where quickgold lies!
  Wind-beat whitebeam! airy abeles set on a flare!
  Flake-doves sent floating forth at a farmyard scare! —
Ah well! it is all a purchase, all is a prize.

Buy then! bid then! — What? — Prayer, patience, alms, vows.
Look, look: a May-mess, like on orchard boughs!
  Look! March-bloom, like on mealed-with-yellow sallows!
These are indeed the barn; withindoors house
  The shocks. This piece-bright paling shuts the spouse
    Christ home, Christ and his mother and all his hallows.
:::

# Pied Beauty {sub="1877"}

:::verse{style="verse"}
Glory be to God for dappled things —
  For skies of couple-colour as a brinded cow;
    For rose-moles all in stipple upon trout that swim;
Fresh-firecoal chestnut-falls; finches’ wings;
  Landscape plotted and pieced — fold, fallow, and plough;
    And áll trádes, their gear and tackle and trim.

All things counter, original, spare, strange;
  Whatever is fickle, freckled (who knows how?)
    With swift, slow; sweet, sour; adazzle, dim;
He fathers-forth whose beauty is past change:
                    Praise him.
:::

# The Windhover {sub="To Christ our Lord"}

:::verse{style="verse"}
I caught this morning morning’s minion, king-
  dom of daylight’s dauphin, dapple-dawn-drawn Falcon, in his riding
  Of the rolling level underneath him steady air, and striding
High there, how he rung upon the rein of a wimpling wing
In his ecstasy! then off, off forth on swing,
  As a skate’s heel sweeps smooth on a bow-bend: the hurl and gliding
  Rebuffed the big wind. My heart in hiding
Stirred for a bird, — the achieve of, the mastery of the thing!

Brute beauty and valour and act, oh, air, pride, plume, here
  Buckle! AND the fire that breaks from thee then, a billion
Times told lovelier, more dangerous, O my chevalier!

  No wonder of it: shéer plód makes plough down sillion
Shine, and blue-bleak embers, ah my dear,
  Fall, gall themselves, and gash gold-vermilion.
:::

# Spring {sub="May 1877"}

:::verse{style="verse"}
Nothing is so beautiful as Spring —
  When weeds, in wheels, shoot long and lovely and lush;
  Thrush’s eggs look little low heavens, and thrush
Through the echoing timber does so rinse and wring
The ear, it strikes like lightnings to hear him sing;
  The glassy peartree leaves and blooms, they brush
  The descending blue; that blue is all in a rush
With richness; the racing lambs too have fair their fling.

What is all this juice and all this joy?
  A strain of the earth’s sweet being in the beginning
In Eden garden. — Have, get, before it cloy,
  Before it cloud, Christ, lord, and sour with sinning,
Innocent mind and Mayday in girl and boy,
  Most, O maiden’s child, thy choice and worthy the winning.
:::

:::paper{type=cardStock grammage=300}
# Colophon {style="colophon"}

:::paragraphs{style="colophon"}
The poems follow *Poems of Gerard Manley Hopkins*, edited by Robert Bridges (London, 1918), Project Gutenberg eBook #22403; they are in the public domain.

Set in Cormorant Garamond, Cinzel and Cormorant SC (SIL Open Font License). The nocturne was generated with diffusion models. Cover, opener and rules stamped in gold foil.
:::

# Shook Foil {style="back"}
:::
`; // content.<lang>.md, inlined by the Cookbook
```

La carte bleue et le vélin crème sont des couleurs de la palette définies en CMJN à 0 % sur chaque canal : l’écran et Folio peignent le support, et aucune plaque n’en reçoit un point. Le PDF de la couverture a donc la plaque de la dorure et quatre plaques de quadrichromie vides. Chaque page bleue prend la carte dans son style de titre (`palette: { paper: … }` dans `onCard`), et les deux blocs `:::paper` donnent à Folio le grammage et la raideur de la carte sur le feuillet de couverture et celui qui le suit.

### 3 · La couverture est un cadre et quatre lignes

```js
// script.js, lignes 63–78
// Two frames, a hairline inside a heavier rule: foil holds a 0.3 pt line on smooth card.
const frame = (id, inset, thickness) => ({ kind: 'box', id, style: { borderColor: col('foil'),
  borderWidth: pt(thickness) }, placement: at('page', 'top-left', inset, inset,
  { width: mm(TRIM_W - 2 * inset), height: mm(TRIM_H - 2 * inset) }) });
const flush = { span: 'page', margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const cover = { ...onCard, ...flush, id: 'cover', advancedDesign: { enabled: true,
  minHeight: mm(TRIM_H), slot: { elements: [
    frame('outer', 9, 1.6), frame('inner', 11.5, 0.4),
    text('kicker', '{attr.kicker}', caps(8.5), at('page', 'top', 0, 46)),
    text('title', '{titleText}', { ...caps(40, col('foil'), 0.06), lineHeight: 1.05 },
      at('page', 'top', 0, 62, { width: mm(100) })),
    rule('rule', 112, 22, 0.8),
    text('poet', '{author}', { fontFamily: 'Cormorant SC', fontSize: pt(15), fontWeight: 500,
      letterSpacing: pt(1.5), color: col('foil') }, at('page', 'top', 0, 120)),
    text('years', '{attr.years}', caps(8), at('page', 'top', 0, 186)),
  ] } } };
```

La dorure tient un trait fin : le cadre est donc un filet de 1,6 pt doublé d’un filet de 0,4 pt 2,5 mm à l’intérieur, chacun la bordure d’un bloc dans la couleur de la dorure. Tout ce qui est sur la couverture est doré : aucune autre encre ne touche la carte, et c’est ainsi qu’on commande une couverture dorée à un atelier de reliure.

### 4 · À l’intérieur, les filets sont dorés et les poèmes à l’encre

```js
// script.js, lignes 104–127
const poem = { enabled: true, minHeight: mm(23), slot: { elements: [
  text('title', '{titleText}', { ...caps(13, col('ink'), 0.1), lineHeight: 1.2 },
    at('container', 'top', 0, 6, { width: mm(90) })),
  { ...rule('rule', 3.5, 12, 0.8, '#title', 'below') },
  text('sub', '{attr.sub}', { fontFamily: 'Cormorant Garamond', italic: true, fontSize: pt(11),
    color: col('muted') }, at('#rule', 'below', 0, 3)),
] } };
const HEAD_Y = 12; // mm from the top edge to the running heads
const headText = (id, content, parity, edge, x) => text(id, content, { ...caps(7.5,
  col('muted'), 0.18), align: edge.endsWith('left') ? 'left' : 'right', parity },
at('page', edge, x, HEAD_Y));
const header = { elements: [
  // The double rule across the text block, a thick and a thin line 1 mm apart.
  { ...rule('head-a', HEAD_Y + 5.5, TRIM_W - INNER - OUTER, 0.9, 'container', 'top'),
    placement: at('page', 'top', 0, HEAD_Y + 5, { width: mm(TRIM_W - INNER - OUTER) }) },
  { ...rule('head-b', 0, 0, 0.3), placement: at('page', 'top', 0, HEAD_Y + 6.2,
    { width: mm(TRIM_W - INNER - OUTER) }) },
  headText('verso', '{title}', 'even', 'top-left', OUTER),
  headText('recto', '{chapterTitle}', 'odd', 'top-right', -OUTER),
] };
const footer = { elements: [
  text('folio', '{pageNumber}', caps(9, col('ink'), 0.05), at('page', 'bottom', 0, -13)),
  rule('folio-l', -12, 6, 0.6, 'page', 'bottom'), // a short foil rule under the folio
] };
```

Le titre courant est posé sur un double filet, un trait de 0,9 pt et un trait de 0,3 pt 1,2 mm en dessous, de la largeur du bloc de texte. La maquette du titre de poème ajoute un filet de 12 mm sous le titre, et le pied de page un filet de 6 mm sous le folio. Le texte reste dans le noir chaud : un petit corps doré se bouche sous la presse.

### 5 · Folio tourne la couverture vers la lumière

```js
// script.js, lignes 152–158
const folio = {
  tilt: 24, yaw: -16,
  paper: { type: 'bookWove', grammage: 100, shade: '#ffffff' }, // the colour is the page's
  binding: { type: 'paperback', cover: 'pages' },
  surface: { type: 'walnut' },
  lighting: { environment: 'studio', intensity: 1.1 },
};
```

La dorure ne se voit comme telle que lorsqu’elle reflète quelque chose. L’environnement `studio` a des boîtes à lumière claires et diffuses, et une inclinaison de 24° avec le livre tourné de 16° fait passer leur reflet sur le titre. Sous la lampe, plus faible, le même or devient un ocre terne.

## La recette complète

Un seul fichier, composé à partir du dossier de la recette avec le texte d’exemple et le kit commun des Recettes déjà inclus ; il construit sa propre page. Pour l’exécuter, placez-le dans un `<script type="module">` d’une page vide ou collez-le dans le panneau JS d’un nouveau pen CodePen (en tant que module). Il importe postext depuis esm.sh : il n’y a rien à installer ni à compiler.

- Dossier de la recette: https://github.com/drnachio/postext/tree/main/cookbook/gold-foil-poetry-cover

### script.js

```js
// ═══ Postext Cookbook · Nº 188 · Gold foil on a deep-blue cover ═══════════════════════
// https://postext.dev/en/cookbook/gold-foil-poetry-cover
// Code: MIT · Text: Hopkins, Bécquer (public domain) · Nocturne: diffusion models
// Fonts: Cormorant Garamond, Cinzel, Cormorant SC (SIL OFL 1.1) · Needs postext ≥ 1.85.1
//
// A poetry chapbook with a hot-foil cover. The cover, the opener and the contents are set
// in gold foil alone on deep-blue card; inside, on cream paper, the poems print in four
// colours and every rule of the page is foil. Folio lights the foil; the PDF gives it a
// plate of its own for the block-maker.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
import { createFolioFromDocument } from 'https://esm.sh/postext-folio';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'gold-foil-poetry-cover';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: the foil is a spot colour with a finish; the stocks print no ink at all
// Gold foil: a spot ink whose finish says what it is. The canvas paints its hex, Folio lights
// it as metal, and a CMYK or PDF/X file puts it on a Separation of its own named 'Gold foil',
// the artwork the foil block is etched from.
const foil = { hex: '#c9a24a', model: 'spot', spot: { name: 'Gold foil',
  cmyk: { c: 15, m: 30, y: 75, k: 10 }, finish: { kind: 'foil', sheen: 'gloss' } } };
// The two stocks are the paper's own colours, not inks: authored in CMYK at 0 % they paint
// on screen and put nothing on any plate. The blue card is a palette value of its own, so a
// section can turn the page blue (palette: { paper: … } in its heading style).
const stock = (hex) => ({ hex, model: 'cmyk', cmyk: { c: 0, m: 0, y: 0, k: 0 } });
const palette = {
  ink: { hex: '#232530', model: 'hex' }, // the poems: a warm near-black in process
  muted: { hex: '#6c6558', model: 'hex' }, // the attributions and the colophon
  foil,
  paper: stock('#f6f0e3'), // cream wove, inside
  card: stock('#1d2a4d'), // deep-blue card, the cover and the opener leaf
};
const col = (id) => ({ ...palette[id], paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, value]) => ({ id, name: id, value })),
  { id: 'main-color', name: 'foil (defaults)', value: foil },
];
// Every blue page takes this: the paper turns to the card, and the head and foot go.
const onCard = { numbered: false, toc: false, palette: { paper: palette.card.hex },
  header: { elements: [] }, footer: { elements: [] } };
// The press file: PDF/X-4, the foil on its plate, the cream and the blue on none.
const PRINT = { standard: 'pdfx4', outputProfile: 'fogra51' };
// #endregion

const [TRIM_W, TRIM_H] = [140, 216]; // mm: a chapbook
const [TOP, FOOT, INNER, OUTER] = [24, 24, 18, 18]; // mm, mirrored
const LEAD = 14.2; // pt
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, overflow: 'wrap',
  align: 'center', placement, ...look });
const caps = (size, color = col('foil'), spacing = 0.2) => ({ fontFamily: 'Cinzel',
  fontSize: pt(size), letterSpacing: pt(size * spacing), color });
const rule = (id, y, width, thickness = 0.6, to = 'page', edge = 'top') => ({ kind: 'rule', id,
  direction: 'horizontal', color: col('foil'), thickness: pt(thickness),
  placement: at(to, edge, 0, y, { width: mm(width) }) });

// #region cover: a frame of foil rules, the title and a rule between the names
// Two frames, a hairline inside a heavier rule: foil holds a 0.3 pt line on smooth card.
const frame = (id, inset, thickness) => ({ kind: 'box', id, style: { borderColor: col('foil'),
  borderWidth: pt(thickness) }, placement: at('page', 'top-left', inset, inset,
  { width: mm(TRIM_W - 2 * inset), height: mm(TRIM_H - 2 * inset) }) });
const flush = { span: 'page', margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) } };
const cover = { ...onCard, ...flush, id: 'cover', advancedDesign: { enabled: true,
  minHeight: mm(TRIM_H), slot: { elements: [
    frame('outer', 9, 1.6), frame('inner', 11.5, 0.4),
    text('kicker', '{attr.kicker}', caps(8.5), at('page', 'top', 0, 46)),
    text('title', '{titleText}', { ...caps(40, col('foil'), 0.06), lineHeight: 1.05 },
      at('page', 'top', 0, 62, { width: mm(100) })),
    rule('rule', 112, 22, 0.8),
    text('poet', '{author}', { fontFamily: 'Cormorant SC', fontSize: pt(15), fontWeight: 500,
      letterSpacing: pt(1.5), color: col('foil') }, at('page', 'top', 0, 120)),
    text('years', '{attr.years}', caps(8), at('page', 'top', 0, 186)),
  ] } } };
// #endregion

// #region opener: the opener leaf and the contents, in foil on the blue card
const opener = { ...onCard, id: 'opener', breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, minHeight: mm(120), slot: { elements: [
    rule('top', 52, 60, 0.4, 'page'),
    text('title', '{titleText}', { ...caps(24, col('foil'), 0.08) }, at('page', 'top', 0, 66)),
    text('note', '{attr.note}', { fontFamily: 'Cormorant Garamond', italic: true,
      fontSize: pt(12.5), lineHeight: 1.3, color: col('foil') },
    at('page', 'top', 0, 84, { width: mm(80) })),
    rule('foot', 108, 60, 0.4, 'page'),
  ] } } };
const contentsPage = { ...onCard, id: 'contents', breakBefore: { enabled: true, parity: 'any' },
  advancedDesign: { enabled: true, minHeight: mm(30), slot: { elements: [
    text('title', '{titleText}', caps(10), at('container', 'top', 0, 8)),
    rule('rule', 16, 14, 0.6, 'container'),
  ] } } };
// The contents in foil: its entries, leaders and page numbers from the poems' headings.
const toc = { levels: [{ level: 1, fontFamily: 'Cormorant Garamond', fontSize: pt(12.5),
  color: col('foil'), marginBottom: pt(LEAD * 0.6) }],
pageNumber: { fontFamily: 'Cinzel', fontSize: pt(9), color: col('foil'), width: mm(8) },
leader: { char: '. ', gap: mm(2) } };
// #endregion

// #region rules: inside, every rule is foil: a double rule over the head, a rule per poem
const poem = { enabled: true, minHeight: mm(23), slot: { elements: [
  text('title', '{titleText}', { ...caps(13, col('ink'), 0.1), lineHeight: 1.2 },
    at('container', 'top', 0, 6, { width: mm(90) })),
  { ...rule('rule', 3.5, 12, 0.8, '#title', 'below') },
  text('sub', '{attr.sub}', { fontFamily: 'Cormorant Garamond', italic: true, fontSize: pt(11),
    color: col('muted') }, at('#rule', 'below', 0, 3)),
] } };
const HEAD_Y = 12; // mm from the top edge to the running heads
const headText = (id, content, parity, edge, x) => text(id, content, { ...caps(7.5,
  col('muted'), 0.18), align: edge.endsWith('left') ? 'left' : 'right', parity },
at('page', edge, x, HEAD_Y));
const header = { elements: [
  // The double rule across the text block, a thick and a thin line 1 mm apart.
  { ...rule('head-a', HEAD_Y + 5.5, TRIM_W - INNER - OUTER, 0.9, 'container', 'top'),
    placement: at('page', 'top', 0, HEAD_Y + 5, { width: mm(TRIM_W - INNER - OUTER) }) },
  { ...rule('head-b', 0, 0, 0.3), placement: at('page', 'top', 0, HEAD_Y + 6.2,
    { width: mm(TRIM_W - INNER - OUTER) }) },
  headText('verso', '{title}', 'even', 'top-left', OUTER),
  headText('recto', '{chapterTitle}', 'odd', 'top-right', -OUTER),
] };
const footer = { elements: [
  text('folio', '{pageNumber}', caps(9, col('ink'), 0.05), at('page', 'bottom', 0, -13)),
  rule('folio-l', -12, 6, 0.6, 'page', 'bottom'), // a short foil rule under the folio
] };
// #endregion

// The nocturne on its own page, in a foil frame.
const plate = { id: 'plate', numbered: false, toc: false, header: { elements: [] },
  footer: { elements: [] }, advancedDesign: { enabled: true,
    minHeight: mm(TRIM_H - TOP - FOOT), slot: { elements: [
      { kind: 'image', id: 'art', resourceId: 'nocturne',
        placement: at('page', 'top', 0, 30, { width: mm(92), height: mm(144.9) }) },
      { kind: 'box', id: 'frame', style: { borderColor: col('foil'), borderWidth: pt(1.2) },
        placement: at('page', 'top', 0, 27, { width: mm(98), height: mm(150.9) }) },
    ] } } };

// The colophon and the back cover go back to the blue card.
const colophon = { ...onCard, id: 'colophon', breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, minHeight: mm(118), slot: { elements: [
    rule('rule', 112, 14, 0.6) ] } } };
const back = { ...onCard, ...flush, id: 'back', breakBefore: { enabled: true, parity: 'even' },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H), slot: { elements: [
    frame('outer', 9, 1.6), frame('inner', 11.5, 0.4),
    text('title', '{titleText}', caps(10), at('page', 'top', 0, 98)),
    rule('rule', 106, 10, 0.6),
  ] } } };

// #region folio: a paperback in the hand, under studio lights that catch the foil
const folio = {
  tilt: 24, yaw: -16,
  paper: { type: 'bookWove', grammage: 100, shade: '#ffffff' }, // the colour is the page's
  binding: { type: 'paperback', cover: 'pages' },
  surface: { type: 'walnut' },
  lighting: { environment: 'studio', 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: 300,
    backgroundColor: col('paper'),
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Cormorant Garamond', fontSize: pt(12.2), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: pt(0), hyphenation: { enabled: true },
    avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: 'Cinzel', fontWeight: 400, color: col('ink'), levels: [
    { level: 1, breakBefore: { enabled: true, parity: 'any' }, advancedDesign: poem }] },
  headingStyles: [cover, opener, contentsPage, plate, colophon, back,
    // A short poem runs on under the one before it.
    { id: 'run-on', breakBefore: { enabled: false }, marginTop: pt(LEAD) }],
  paragraphStyles: [
    { id: 'verse', fontFamily: 'Cormorant Garamond', fontSize: pt(12.2), lineHeight: pt(LEAD) },
    { id: 'colophon', fontFamily: 'Cormorant Garamond', italic: true, fontSize: pt(10.5),
      lineHeight: pt(13.5), color: col('foil'), italicColor: col('foil'), textAlign: 'center',
      firstLineIndent: pt(0) },
  ],
  toc,
  print: PRINT,
  header, footer, folio,
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// #region content: blue card around the cream leaves, as the binder gathers them
// :::paper{type=cardStock grammage=300}     pages 1–4: the cover leaf and the opener leaf
// # Shook Foil {style="cover"}  # Shook Foil {style="opener"}  # Contents {style="contents"}
// :::
// # God's Grandeur  …  # Spring             pages 5–10: cream wove, the poems
// :::paper{type=cardStock grammage=300}     pages 11–12: the back cover leaf
// # Colophon {style="colophon"}  # Shook Foil {style="back"}
// :::
const markdown = String.raw`---
title: "Shook Foil"
author: "Gerard Manley Hopkins"
---

:::paper{type=cardStock grammage=300}
# Shook Foil {style="cover" kicker="Five poems" years="1877 · 1879"}

# Shook Foil {style="opener" note="Five poems written in Wales and at Oxford, first printed in 1918, after the poet’s death"}

# Contents {style="contents"}

:::toc
:::

# God’s Grandeur {sub="St Beuno’s, 1877"}

:::verse{style="verse"}
The world is charged with the grandeur of God.
  It will flame out, like shining from shook foil;
  It gathers to a greatness, like the ooze of oil
Crushed. Why do men then now not reck his rod?
Generations have trod, have trod, have trod;
  And all is seared with trade; bleared, smeared with toil;
  And wears man’s smudge and shares man’s smell: the soil
Is bare now, nor can foot feel, being shod.

And for all this, nature is never spent;
  There lives the dearest freshness deep down things;
And though the last lights off the black West went
  Oh, morning, at the brown brink eastward, springs —
Because the Holy Ghost over the bent
  World broods with warm breast and with ah! bright wings.
:::

# Nocturne {style="plate"}

# The Starlight Night {sub="St Beuno’s, 1877"}

:::verse{style="verse"}
Look at the stars! look, look up at the skies!
  O look at all the fire-folk sitting in the air!
  The bright boroughs, the circle-citadels there!
Down in dim woods the diamond delves! the elves’-eyes!
The grey lawns cold where gold, where quickgold lies!
  Wind-beat whitebeam! airy abeles set on a flare!
  Flake-doves sent floating forth at a farmyard scare! —
Ah well! it is all a purchase, all is a prize.

Buy then! bid then! — What? — Prayer, patience, alms, vows.
Look, look: a May-mess, like on orchard boughs!
  Look! March-bloom, like on mealed-with-yellow sallows!
These are indeed the barn; withindoors house
  The shocks. This piece-bright paling shuts the spouse
    Christ home, Christ and his mother and all his hallows.
:::

# Pied Beauty {sub="1877"}

:::verse{style="verse"}
Glory be to God for dappled things —
  For skies of couple-colour as a brinded cow;
    For rose-moles all in stipple upon trout that swim;
Fresh-firecoal chestnut-falls; finches’ wings;
  Landscape plotted and pieced — fold, fallow, and plough;
    And áll trádes, their gear and tackle and trim.

All things counter, original, spare, strange;
  Whatever is fickle, freckled (who knows how?)
    With swift, slow; sweet, sour; adazzle, dim;
He fathers-forth whose beauty is past change:
                    Praise him.
:::

# The Windhover {sub="To Christ our Lord"}

:::verse{style="verse"}
I caught this morning morning’s minion, king-
  dom of daylight’s dauphin, dapple-dawn-drawn Falcon, in his riding
  Of the rolling level underneath him steady air, and striding
High there, how he rung upon the rein of a wimpling wing
In his ecstasy! then off, off forth on swing,
  As a skate’s heel sweeps smooth on a bow-bend: the hurl and gliding
  Rebuffed the big wind. My heart in hiding
Stirred for a bird, — the achieve of, the mastery of the thing!

Brute beauty and valour and act, oh, air, pride, plume, here
  Buckle! AND the fire that breaks from thee then, a billion
Times told lovelier, more dangerous, O my chevalier!

  No wonder of it: shéer plód makes plough down sillion
Shine, and blue-bleak embers, ah my dear,
  Fall, gall themselves, and gash gold-vermilion.
:::

# Spring {sub="May 1877"}

:::verse{style="verse"}
Nothing is so beautiful as Spring —
  When weeds, in wheels, shoot long and lovely and lush;
  Thrush’s eggs look little low heavens, and thrush
Through the echoing timber does so rinse and wring
The ear, it strikes like lightnings to hear him sing;
  The glassy peartree leaves and blooms, they brush
  The descending blue; that blue is all in a rush
With richness; the racing lambs too have fair their fling.

What is all this juice and all this joy?
  A strain of the earth’s sweet being in the beginning
In Eden garden. — Have, get, before it cloy,
  Before it cloud, Christ, lord, and sour with sinning,
Innocent mind and Mayday in girl and boy,
  Most, O maiden’s child, thy choice and worthy the winning.
:::

:::paper{type=cardStock grammage=300}
# Colophon {style="colophon"}

:::paragraphs{style="colophon"}
The poems follow *Poems of Gerard Manley Hopkins*, edited by Robert Bridges (London, 1918), Project Gutenberg eBook #22403; they are in the public domain.

Set in Cormorant Garamond, Cinzel and Cormorant SC (SIL Open Font License). The nocturne was generated with diffusion models. Cover, opener and rules stamped in gold foil.
:::

# Shook Foil {style="back"}
:::
`; // content.<lang>.md, inlined by the Cookbook
// #endregion
const resources = [{ id: 'nocturne', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: 'nocturne.jpg', format: 'jpeg', width: 600, height: 945 },
  altText: t({ en: 'A night meadow under a sky of stars: tall poplars, a stone wall, a thin '
    + 'moon over the hills and a lit window in the valley.',
  es: 'Un prado de noche bajo un cielo de estrellas: chopos altos, una tapia de piedra, una '
    + 'luna fina sobre los montes y una ventana encendida en el valle.' }) }];
await loadImage('nocturne.jpg', asset('nocturne-600.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Cormorant Garamond': ['400', '400i'],
  Cinzel: ['400'],
  'Cormorant SC': ['500'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Shook Foil · a chapbook with a gold-foil cover',
  es: 'Rimas · un cuaderno con portada en oro en caliente' }) });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes,
  profileBaseUrl: 'https://postext.dev/icc/' }), `${RECIPE}.pdf`);

// The book in the hand: the cover, closed, turning its foil to the lamp.
const stage = document.createElement('section');
stage.id = 'folio';
stage.ariaLabel = t({ en: 'The chapbook in 3D', es: 'El cuaderno en 3D' });
stage.style.cssText = 'height: min(78vh, 720px); margin: 0 auto; max-width: 1280px';
document.getElementById('pages').before(stage);
createFolioFromDocument(stage, doc, {
  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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Dorer à l’argent

Changez le hex et le CMJN de substitution ; la finition et la plaque restent.

```diff
-const foil = { hex: '#c9a24a', model: 'spot', spot: { name: 'Gold foil',
-  cmyk: { c: 15, m: 30, y: 75, k: 10 }, finish: { kind: 'foil', sheen: 'gloss' } } };
+const foil = { hex: '#b8bcc2', model: 'spot', spot: { name: 'Silver foil',
+  cmyk: { c: 20, m: 12, y: 10, k: 25 }, finish: { kind: 'foil', sheen: 'gloss' } } };
```

### Imprimer l’or en encre métallisée

Une encre métallisée coûte moins cher qu’un cliché de dorure et s’imprime avec les autres encres ; Folio la montre satinée.

```diff
-  cmyk: { c: 15, m: 30, y: 75, k: 10 }, finish: { kind: 'foil', sheen: 'gloss' } } };
+  cmyk: { c: 15, m: 30, y: 75, k: 10 }, finish: { kind: 'metallic' } } };
```

## Erreurs fréquentes

- Un papier de couleur donné dans `page.backgroundColor` avec un hex ordinaire s’imprime comme un aplat de quadrichromie sur toute la page. Définissez le support en CMJN à 0 %, comme ici, quand la couleur est celle du papier.
- Les filets de moins de 0,25 pt et les caractères de moins de 8 pt se bouchent à la dorure. Gardez l’or pour les filets et les titres.

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texte: Six poems by Gerard Manley Hopkins, from Poems (1918), Project Gutenberg eBook #22403: Gerard Manley Hopkins ([source](https://www.gutenberg.org/ebooks/22403)), domaine public
- Texte: Seven rimas by Gustavo Adolfo Bécquer, from his Obras (1871): Gustavo Adolfo Bécquer, domaine public
- Images: The nocturne facing the second poem, a gouache: Generated With Diffusion Models, original
- Caractères: Cormorant Garamond (OFL-1.1), Cinzel (OFL-1.1), Cormorant SC (OFL-1.1)
- Code: MIT · Contenu d’exemple: CC-BY-4.0

## Recettes liées

- [Nº 102 · Un zine agrafé avec une feuille de couverture en carte](https://postext.dev/fr/cookbook/saddle-stitched-card-cover.md): Deux blocs :::paper mettent une carte saumon en feuille extérieure d’un zine de huit pages, que postext-folio montre agrafé autour de pages en papier journal. · Niveau 2 (Intermédiaire) · Magazines et fanzines
- [Nº 101 · Un nuancier, chaque feuillet sur son papier](https://postext.dev/fr/cookbook/paper-swatch-book.md): Chaque feuillet d’un catalogue de papetier est un bloc :::paper ; postext-folio le dessine avec la teinte, le grammage, la surface et la rigidité de son papier. · Niveau 2 (Intermédiaire) · Catalogues
- [Nº 024 · PDF pour l’imprimeur : fond perdu, traits de coupe, PDF/X](https://postext.dev/fr/cookbook/print-ready-pdf.md): Un dépliant d’exposition à 3 mm de fond perdu, avec traits de coupe, exporté en PDF/X-4 sur FOGRA51, avec masters d’impression et contrôle en amont sans erreur. · Niveau 3 (Avancé) · Feuilles volantes et éphémères
