# Appendici su due colonne in corpo minore

> Un manuale di frutticoltura a una colonna con appendici di altro progetto: una parte nomina uno stile di capitolo, un’appendice il suo, la postfazione torna.

- Versione HTML: https://postext.dev/it/cookbook/appendices-in-two-columns
- Ricetta Nº 187 · Struttura del libro · Livello 2 (Intermedio) · Output: Canvas
- Generi: Manuali, guide e opere di consultazione
- Richiede postext ≥ 1.79.0 · provata con 1.79.0 il 2026-11-12
- Pagine: [1](https://postext.dev/cookbook/appendices-in-two-columns/en/p01.webp?v=a5470155), [2](https://postext.dev/cookbook/appendices-in-two-columns/en/p02.webp?v=a5470155), [4](https://postext.dev/cookbook/appendices-in-two-columns/en/p04.webp?v=a5470155), [6](https://postext.dev/cookbook/appendices-in-two-columns/en/p06.webp?v=a5470155), [7](https://postext.dev/cookbook/appendices-in-two-columns/en/p07.webp?v=a5470155), [8](https://postext.dev/cookbook/appendices-in-two-columns/en/p08.webp?v=a5470155), [9](https://postext.dev/cookbook/appendices-in-two-columns/en/p09.webp?v=a5470155), [10](https://postext.dev/cookbook/appendices-in-two-columns/en/p10.webp?v=a5470155)
- Apri nella Sandbox: https://postext.dev/it/sandbox#recipe=appendices-in-two-columns&lang=en (.postext: https://postext.dev/cookbook/appendices-in-two-columns/en/appendices-in-two-columns.postext)
- Ultimo aggiornamento: 2026-11-12
- Altre lingue: [en](https://postext.dev/en/cookbook/appendices-in-two-columns.md), [es](https://postext.dev/es/cookbook/appendices-in-two-columns.md), [ca](https://postext.dev/ca/cookbook/appendices-in-two-columns.md), [de](https://postext.dev/de/cookbook/appendices-in-two-columns.md), [fr](https://postext.dev/fr/cookbook/appendices-in-two-columns.md), [pt](https://postext.dev/pt/cookbook/appendices-in-two-columns.md), [zh](https://postext.dev/zh/cookbook/appendices-in-two-columns.md), [ja](https://postext.dev/ja/cookbook/appendices-in-two-columns.md), [ar](https://postext.dev/ar/cookbook/appendices-in-two-columns.md)

## In breve

I capitoli del libro sono composti su una colonna larga. Dalle appendici in poi il testo scorre su due colonne di carattere più piccolo, e un’appendice su tre. Il formato della pagina e la lingua del libro non cambiano mai.

## Che cosa comporrai

Un piccolo manuale per chi coltiva meli in una valle fredda, di 150 × 220 mm, scritto in sei documenti Markdown e impaginato come un solo libro. I due capitoli della parte I sono composti su una colonna giustificata in Source Serif 4. La parte II, le appendici, cambia progetto grafico: una tabella dei portinnesti e un calendario mese per mese su due colonne in bandiera e in corpo minore, materia che si legge nel capanno con il libro aperto sul banco da lavoro, e un elenco di varietà su tre colonne in un carattere senza grazie. La postfazione torna al progetto del libro senza pagina di parte. Formato, margini, sillabazione e lingua sono gli stessi in ogni pagina.

**Questa ricetta risponde a:**

- Come do alle appendici di un libro un altro progetto grafico, ad esempio due colonne in corpo minore?
- Come divido un libro in parti o sezioni, ognuna con il suo colore e la sua pagina di parte?

## La risposta breve

```js
// script.js, righe 29–48
const smallOpener = { minHeight: mm(24), slot: { elements: [{ id: 'title', fontSize: pt(16) }] } };
// In the Markdown:  :::part{number="II" title="Appendices" style="appendix"}  sets every
// chapter from there to the next part; a chapter's own  chapterStyle: reference  wins.
const chapterStyles = [
  { id: 'appendix', name: t({ en: 'Appendix', es: 'Apéndice' }), config: {
    layout: { layoutType: 'double', gutterWidth: mm(6) },
    bodyText: { fontSize: pt(8.8), lineHeight: pt(11.6), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(4) },
    // Lists merge entry by entry on their id or level: only what is named here changes.
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
  { id: 'reference', name: t({ en: 'Reference list', es: 'Lista de consulta' }), config: {
    layout: { layoutType: 'multiple', columnCount: 3, gutterWidth: mm(4.5) },
    bodyText: { fontFamily: SANS, fontSize: pt(7.8), lineHeight: pt(10.4), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(3.5), boldColor: col('accent') },
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
];
// The trim, the language and the fonts stay the book's: a style that sets page.width or
// locale is ignored there, with a chapterStyleBookSetting warning.
```

## Ingredienti

**Insegna**

- [Stili dei capitoli](https://postext.dev/it/docs/configuration-styles.md#stili-dei-capitoli): Insiemi di impostazioni con un nome (config.chapterStyles) che un capitolo adotta con chapterStyle: nel front matter, o tutti i capitoli di una parte con :::part{style="…"}: cambiano colonne, margini, caratteri, titoli e testatine, mentre il formato, la lingua e le altre impostazioni di tutto il libro restano quelle del libro.
- [Pagine di parte](https://postext.dev/it/docs/configuration-styles.md#il-contenitore-part): Un :::part apre una pagina di parte progettata (e il suo verso) con numero, titolo e un elenco facoltativo dei capitoli, prima dei capitoli che raggruppa.

**Usa anche**

- [Libri costruiti capitolo per capitolo](https://postext.dev/it/docs/configuration-bundles.md#impaginare-e-disegnare-un-pacchetto)
- [Una o due colonne](https://postext.dev/it/docs/configuration-page-layout.md#tipi-di-impaginazione)
- [Tre o più colonne](https://postext.dev/it/docs/configuration-page-layout.md#tipi-di-impaginazione)
- [Aperture progettate](https://postext.dev/it/docs/configuration-headings.md#estensione-e-grafica-avanzata)
- [Testatine e folio](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Testatine per sezione](https://postext.dev/it/docs/configuration-styles.md#stili-dei-titoli)
- [Testatine secondo il ruolo della pagina](https://postext.dev/it/docs/configuration-headers-footers.md#elementi-di-testo)
- [Margini speculari](https://postext.dev/it/docs/configuration-page-layout.md#margini-speculari)
- [Testo, filetti e riquadri nei progetti di pagina](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Vedove, orfane e righe corte](https://postext.dev/it/docs/configuration-page-flow.md#orfane-vedove-righe-finali-corte-e-regole-di-tenuta)
- [Tavolozza di colori semantica](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori)
- [Fascia di capitolo a tutta larghezza](https://postext.dev/it/docs/configuration-headings.md#estensione-e-grafica-avanzata)
- [Colore della carta](https://postext.dev/it/docs/configuration-page-layout.md#pagina)
- [Stili di paragrafo](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo)

**La configurazione in breve**

- [`bodyText`](https://postext.dev/it/docs/configuration-text.md#testo-corrente), [`chapterStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-dei-capitoli), [`colorPalette`](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori), [`footer`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`header`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`headings`](https://postext.dev/it/docs/configuration-headings.md#titoli), [`layout`](https://postext.dev/it/docs/configuration-page-layout.md#impaginazione), [`locale`](https://postext.dev/it/docs/configuration-language.md#sillabazione), [`page`](https://postext.dev/it/docs/configuration-page-layout.md#pagina), [`paragraphStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo), [`parts`](https://postext.dev/it/docs/configuration-styles.md#parti)

**API**

- [`buildBundle`](https://postext.dev/it/docs/configuration-bundles.md#impaginare-e-disegnare-un-pacchetto), [`prepareFonts`](https://postext.dev/it/docs/configuration-programmatic-usage.md#caricare-i-font-prima-dellimpaginazione), [`renderPageToCanvas`](https://postext.dev/it/docs/configuration-programmatic-usage.md#rasterizzare-una-pagina), [`withLoadedFonts`](https://postext.dev/it/docs/configuration-programmatic-usage.md#caricare-i-font-prima-dellimpaginazione)

**Caratteri**

- Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)

## Preparazione

### 1 · Uno stile contiene solo ciò che cambia

Il codice è [la risposta breve](https://postext.dev/it/cookbook/appendices-in-two-columns.md#la-risposta-breve) qui sopra. Uno stile di capitolo ha un id, un nome per il Sandbox e un `config` che si fonde con le impostazioni del libro come fa il livello di una lingua. Gli oggetti si fondono chiave per chiave e le liste voce per voce, in base al loro `id` o `level`: così `smallOpener` nomina un solo elemento dell’apertura, il titolo, e gli dà un corpo più piccolo; il filetto sotto e tutto il resto restano come li ha il libro. Lo stile di appendice fissa due colonne, un corpo del testo più piccolo, righe in bandiera e spazio tra le voci, e nient’altro.

Alcune impostazioni appartengono al libro intero: formato, risoluzione e legatura di `page`, lingua e direzione di scrittura, cifre, font, stampa e PDF. Uno stile che ne fissa una viene ignorato su quel punto e solleva un avviso `chapterStyleBookSetting`: le appendici mantengono così il formato di 150 mm e la sillabazione in inglese britannico dei capitoli.

### 2 · La parte nomina lo stile

```js
// script.js, righe 264–266
// Only the first document's front matter is the book's; a later one keeps its chapterStyle.
const chapters = [front, rootstocks, appendices, calendar, varieties, afterword]
  .map((markdown) => ({ markdown }));
```

Il terzo documento si apre con `:::part{number="II" title="Appendices" style="appendix"}`, e ogni capitolo da lì fino alla parte successiva è composto nello stile di appendice. Il quinto nomina un proprio stile nel suo front matter, `chapterStyle: "reference"`, che prevale su quello della parte. In un libro solo il front matter del primo documento vale per il libro; uno successivo conserva soltanto la riga `chapterStyle:`.

![Opening page 9: Appendix C · Varieties for a short season.](https://postext.dev/cookbook/appendices-in-two-columns/en/p09.webp?v=a5470155)

*Appendice C: lo stile proprio del capitolo, tre colonne senza grazie, al posto delle due della parte.*

### 3 · Una pagina di parte, e una parte senza

```js
// script.js, righe 52–66
const text = (id, content, family, size, extra) => ({ kind: 'text', id, content, align: 'left',
  fontFamily: family, fontSize: pt(size), color: col('ink'), overflow: 'wrap', ...extra });
const at = (to, edge, x, y, width) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(width && { size: { width: mm(width), height: 'auto' } }) });
const parts = {
  breakBefore: { parity: 'any' }, // the book is short: a part opens on the next page
  design: { elements: [ // the container is the trim: the margins are measured from its edges
    { kind: 'box', id: 'band', style: { backgroundColor: col('leaf') },
      placement: { ...at('page', 'top-left', 0, 0), size: { width: 'fill', height: mm(96) } } },
    text('number', '{number}', SERIF, 40, { fontWeight: 600, color: col('paper'),
      placement: at('page', 'top-left', MARGIN.inner, 46, MEASURE) }),
    text('title', '{titleText}', SERIF, 24, { fontWeight: 600, color: col('paper'),
      placement: at('#number', 'below', 0, 2, MEASURE) }),
  ] },
};
```

Ogni `:::part` apre una pagina di parte con il numero e il titolo della parte su una banda verde. La postfazione si apre con `:::part{title="Afterword" page=false}`: non viene stampata nessuna pagina di parte e, poiché la parte non nomina uno stile, il suo capitolo torna a essere composto con le impostazioni del libro. Una parte con `page=false` si presta alle pagine finali che seguono le appendici senza stacco.

![Part title page 6: II Appendices.](https://postext.dev/cookbook/appendices-in-two-columns/en/p06.webp?v=a5470155)

*La pagina di parte della parte II.*

### 4 · Un’apertura in due misure

```js
// script.js, righe 70–75
const opener = { enabled: true, minHeight: mm(40), slot: { elements: [
  text('title', '{titleText}', SERIF, 22, { fontWeight: 600, lineHeight: 1.12,
    placement: at('container', 'top-left', 0, 8, MEASURE - 10) }),
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.5), color: col('accent'),
    placement: { ...at('#title', 'below', 0, 4), size: { width: mm(14) } } },
] } };
```

L’apertura occupa tutta la larghezza della pagina, quindi nelle appendici passa sopra le due colonne e il testo comincia sotto, su due. Gli stili di appendice e di consultazione riducono il titolo a 16 pt e l’abbassamento a 24 mm tramite l’id dell’elemento: la materia in fondo al libro occupa meno spazio, e i suoi titoli restano ben più grandi del testo.

### 5 · Testatine dal libro

```js
// script.js, righe 79–91
const head = (id, content, parity, edge, x, extra = {}) => text(id, content, SANS, 7.5, {
  parity, pages: 'body', fontWeight: 600, letterSpacing: pt(1.2), textTransform: 'uppercase',
  color: col('muted'), overflow: 'clip', placement: at('page', edge, x, 12, 90), ...extra });
const folio = { fontWeight: 700, color: col('ink') };
const right = { align: 'right' };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', MARGIN.outer, folio),
  head('verso-title', '{title}', 'even', 'top-left', MARGIN.outer + 9), // the book's title
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(MARGIN.outer + 9), right),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -MARGIN.outer, { ...folio, ...right }),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'bottom', 0, {
  ...folio, align: 'center', pages: 'opener', placement: at('page', 'bottom', 0, -14, 20) })] };
```

Il titolo del libro va sul verso e quello del capitolo sul recto. Nessuno stile le cambia, quindi le testatine sono uguali in ogni parte del libro.

## La ricetta completa

Un unico file, composto a partire dalla cartella della ricetta con il testo di esempio e il kit comune del Ricettario già inclusi; costruisce la propria pagina. Per eseguirlo, mettilo in uno `<script type="module">` di una pagina vuota, oppure incollalo nel pannello JS di un nuovo pen di CodePen (come modulo). Importa postext da esm.sh: non c’è niente da installare né da compilare.

- Cartella della ricetta: https://github.com/drnachio/postext/tree/main/cookbook/appendices-in-two-columns

### script.js

```js
// ═══ Postext Cookbook · Nº 187 · Appendices in two columns ═══════════════════════════════
// https://postext.dev/en/cookbook/appendices-in-two-columns
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.79.0
// A growers' handbook in six Markdown documents: the chapters in one column, the appendices
// in two columns of smaller type, one appendix in three, and an afterword back in one.
import {
  buildBundle, prepareFonts, withLoadedFonts, renderPageToCanvas,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'appendices-in-two-columns';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: russet for the accent, leaf green for the part pages
const palette = { ink: '#211f1b', accent: '#8e3b24', leaf: '#46603a', muted: '#6c665c',
  rule: '#cfc6b6', paper: '#fffdf8' };
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.accent })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const [SERIF, SANS] = ['Source Serif 4', 'Source Sans 3'];
const TRIM = { width: 150, height: 220 }; // mm, a handbook for the shed shelf
const MARGIN = { top: 22, bottom: 24, inner: 19, outer: 15 }; // mirrored
const MEASURE = TRIM.width - MARGIN.inner - MARGIN.outer; // 116 mm
const LEAD = 14; // pt, the book's leading

// #region answer: two chapter styles; a part names one, a chapter names the other
const smallOpener = { minHeight: mm(24), slot: { elements: [{ id: 'title', fontSize: pt(16) }] } };
// In the Markdown:  :::part{number="II" title="Appendices" style="appendix"}  sets every
// chapter from there to the next part; a chapter's own  chapterStyle: reference  wins.
const chapterStyles = [
  { id: 'appendix', name: t({ en: 'Appendix', es: 'Apéndice' }), config: {
    layout: { layoutType: 'double', gutterWidth: mm(6) },
    bodyText: { fontSize: pt(8.8), lineHeight: pt(11.6), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(4) },
    // Lists merge entry by entry on their id or level: only what is named here changes.
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
  { id: 'reference', name: t({ en: 'Reference list', es: 'Lista de consulta' }), config: {
    layout: { layoutType: 'multiple', columnCount: 3, gutterWidth: mm(4.5) },
    bodyText: { fontFamily: SANS, fontSize: pt(7.8), lineHeight: pt(10.4), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(3.5), boldColor: col('accent') },
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
];
// The trim, the language and the fonts stay the book's: a style that sets page.width or
// locale is ignored there, with a chapterStyleBookSetting warning.
// #endregion

// #region parts: a divider page for each :::part, none where the fence says page=false
const text = (id, content, family, size, extra) => ({ kind: 'text', id, content, align: 'left',
  fontFamily: family, fontSize: pt(size), color: col('ink'), overflow: 'wrap', ...extra });
const at = (to, edge, x, y, width) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(width && { size: { width: mm(width), height: 'auto' } }) });
const parts = {
  breakBefore: { parity: 'any' }, // the book is short: a part opens on the next page
  design: { elements: [ // the container is the trim: the margins are measured from its edges
    { kind: 'box', id: 'band', style: { backgroundColor: col('leaf') },
      placement: { ...at('page', 'top-left', 0, 0), size: { width: 'fill', height: mm(96) } } },
    text('number', '{number}', SERIF, 40, { fontWeight: 600, color: col('paper'),
      placement: at('page', 'top-left', MARGIN.inner, 46, MEASURE) }),
    text('title', '{titleText}', SERIF, 24, { fontWeight: 600, color: col('paper'),
      placement: at('#number', 'below', 0, 2, MEASURE) }),
  ] },
};
// #endregion

// #region opener: the chapter title and a short rule, the text sunk under them
const opener = { enabled: true, minHeight: mm(40), slot: { elements: [
  text('title', '{titleText}', SERIF, 22, { fontWeight: 600, lineHeight: 1.12,
    placement: at('container', 'top-left', 0, 8, MEASURE - 10) }),
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.5), color: col('accent'),
    placement: { ...at('#title', 'below', 0, 4), size: { width: mm(14) } } },
] } };
// #endregion

// #region running-heads: the book on the verso, the chapter on the recto, folios outside
const head = (id, content, parity, edge, x, extra = {}) => text(id, content, SANS, 7.5, {
  parity, pages: 'body', fontWeight: 600, letterSpacing: pt(1.2), textTransform: 'uppercase',
  color: col('muted'), overflow: 'clip', placement: at('page', edge, x, 12, 90), ...extra });
const folio = { fontWeight: 700, color: col('ink') };
const right = { align: 'right' };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', MARGIN.outer, folio),
  head('verso-title', '{title}', 'even', 'top-left', MARGIN.outer + 9), // the book's title
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(MARGIN.outer + 9), right),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -MARGIN.outer, { ...folio, ...right }),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'bottom', 0, {
  ...folio, align: 'center', pages: 'opener', placement: at('page', 'bottom', 0, -14, 20) })] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }), colorPalette, chapterStyles, parts, header, footer,
  page: { sizePreset: 'custom', width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150,
    backgroundColor: col('paper'), margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom),
      left: mm(MARGIN.inner), right: mm(MARGIN.outer), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: SERIF, fontSize: pt(10.5), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4.5), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: SANS, color: col('accent'), fontWeight: 600, levels: [
    // span 'page': in the appendices' columns the opener still runs across the page.
    { level: 1, breakBefore: { enabled: true, parity: 'any' }, span: 'page',
      advancedDesign: opener },
    { level: 2, fontSize: pt(11), lineHeight: pt(LEAD), marginTop: pt(LEAD),
      marginBottom: pt(0) },
  ] },
  paragraphStyles: [{ id: 'colophon', fontFamily: SANS, fontSize: pt(7.5), lineHeight: pt(10),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const front = String.raw`---
title: "Apples for a Cold Valley"
author: "Elena Arrieta"
---

:::part{number="I" title="The orchard"}
:::

# Choosing the ground

An apple tree planted today will still be bearing when the person who planted it has stopped climbing ladders. The choice of ground is the one decision that cannot be put right later, and in a valley where the frost comes in September and stays until May it decides more than the choice of variety does.

## Cold air runs downhill

On a still night the air that cools against the ground grows heavy and slides down the slope, the way water would, and pools wherever the land stops falling: in the valley floor, behind a hedge, against a wall at the bottom of a field. Two trees a hundred metres apart can see five degrees of difference on a May morning, and five degrees is the gap between a crop and a tree in flower that sets nothing.

Plant on the slope, never in the hollow below it. A third of the way up is usually the warmest band, above the frost pocket and below the wind. If the orchard has to sit low, leave a gap in the bottom hedge so the cold air can drain away instead of backing up into the trees.

## Facing the sun

A slope that faces south or south-west warms first in spring and ripens the wood in autumn, and ripe wood is what carries a tree through a hard winter. A north slope delays blossom by a week or more, which can save it from a late frost, but the fruit may not colour before the first snow. In this valley the south-west slopes above the river have always carried the old orchards, and the farmhouses below them sit just above the line where the fog settles.

## Soil and water

Apples want deep soil that drains. A tree will put up with poor ground, but it will not put up with its roots standing in water through the winter: the roots die back, the bark at the collar rots, and the tree goes yellow the following summer for no reason anyone can see. Dig a hole sixty centimetres deep in March and fill it with water. If the water is still there the next day, the ground needs draining or the tree needs a mound to stand on.

Heavy clay holds water and cold; it also holds nutrients, and an apple on clay crops for a long time once it is established. Light sand warms early and drains well but dries out in August, when the fruit is swelling. Most valley soils sit somewhere between the two, and the rootstock, the subject of the next chapter, does more to match a tree to its soil than any amount of digging.
`; // the book's front matter, Part I and the first chapter
const rootstocks = String.raw`# Rootstocks and spacing

An apple does not come true from seed. Every named variety is grafted: a bud or a shoot of the variety is joined to the roots of another apple, and those roots decide how large the tree will grow, how soon it will crop and how well it stands cold, wet or drought. The variety decides the fruit. The rootstock decides almost everything else.

## Small trees, early fruit

Most rootstocks in use today come from the research station at East Malling, in Kent, and carry its initial: M9, M26, MM106. The lower the vigour, the sooner the tree bears and the smaller it stays. A tree on M9 may give a few apples in its second summer and will stand about two and a half metres tall, small enough to prune and pick from the ground. It pays for that with a weak root system: it needs a stake for the whole of its life and good soil to grow in.

## Large trees, long lives

A tree on a vigorous rootstock such as MM111 or M25 takes five or six years to crop and grows into a tree that needs a ladder, but it roots deep, finds water in a dry summer and will stand in grass without help. These are the trees of the old orchards on the slopes, some of them older than the farmhouses. Where sheep graze under the branches, or where nobody will water a young tree in August, a vigorous stock is the safer choice.

## The cold

Hardiness belongs to the rootstock as much as to the variety. The Malling stocks were raised for English winters, and in a valley that drops below minus twenty-five some of them suffer. The Budagovsky stocks, bred in central Russia, were raised for that cold: Bud 9 makes a tree the size of one on M9 and comes through winters that kill M9 roots. Seedlings of Antonovka, an old Russian apple, give a full-sized tree that is hardier still.

## How far apart

Spacing follows from the rootstock. Trees on M9 can stand a metre and a half apart in rows three and a half metres wide; on MM106, four metres apart; on M25, eight or more. The appendices give the figures for each stock and the work of each month, set close so that they can be read in the shed with the book open on the bench.
`;
const appendices = String.raw`:::part{number="II" title="Appendices" style="appendix"}
:::

# Appendix A · Rootstocks at a glance

Heights are those of a mature tree on average soil, kept by ordinary pruning. Spacing is between trees in the row; rows need at least a metre more than the height of the trees.

**M27.** The most dwarfing of the common stocks. A tree of a metre and a half to two metres, often in fruit in its second year. It needs a stake for life, rich soil and regular watering. Suited to pots and to a few trees in a garden, not to an orchard on poor ground. Spacing: one metre.

**M9.** Dwarfing, two to three metres. The stock of most modern orchards: early and heavy cropping, fruit of good size. Brittle roots that need a stake for life; sensitive to drought, woolly aphid and fireblight. Its roots can be killed in the hardest winters. Spacing: one and a half metres.

**Bud 9.** Raised at Michurinsk, in Russia. A tree of the size of one on M9 that stands much harder winters. Needs a stake and good soil, like M9. Spacing: one and a half metres.

**M26.** Semi-dwarfing, about three metres. Hardier than M9 and more anchored, though it needs a stake while young. Does badly in wet soil, where the collar rots. Spacing: two and a half metres.

**MM106.** Semi-vigorous, three and a half to four and a half metres. Resists woolly aphid, crops in its third or fourth year and stands on its own after the first years. Prone to collar rot on wet clay, and it grows late into autumn, which leaves the wood soft when the first hard frost arrives. Spacing: four metres.

**MM111.** Vigorous, four and a half to five and a half metres. Deep roots that tolerate drought and light soils; resists woolly aphid. Slow to crop but long-lived. Spacing: five metres.

**M25.** Very vigorous, six metres and more: a full standard tree for a grazed orchard. Crops after five or six years and lives for generations. Spacing: eight metres.

**Antonovka seedling.** Full size and the hardiest of all, grown from the seed of the Russian apple. Trees vary, as seedlings do. Spacing: eight metres.
`; // opens Part II in the 'appendix' style
const calendar = String.raw`# Appendix B · The orchard year

The months are those of this valley, where the last frost can come in late May and the first in late September. Higher up, everything moves a week or two later.

**January.** Prune on days when the wood is not frozen, starting with the oldest trees. Check the guards round young trunks: voles work under snow, and hares strip bark when the ground is white.

**February.** Finish the winter pruning of standards. Take scion wood for grafting from last summer's shoots, label it and keep it wrapped and cool until April.

**March.** Plant bare-root trees as soon as the soil can be worked and is not sticky. Stake trees on dwarfing stocks the day they go in.

**April.** Graft when the buds of the rootstock begin to open. Keep a thermometer in the lowest part of the orchard and watch the forecast: open blossom is killed at about minus two.

**May.** Blossom, a week later on the north slopes. Leave the grass long under the trees until the bees have finished. On a clear, still night after a cold day, expect frost before dawn.

**June.** After the natural drop at the end of the month, thin the fruit to one per cluster, and to one every fifteen centimetres on young trees.

**July.** Water young trees in dry spells, a full bucket each, once a week.

**August.** Summer-prune cordons and espaliers once the new shoots are woody at the base. Pick the early varieties when they part from the spur with a lift and a twist.

**September.** The main picking begins. Handle the fruit as you would eggs, and store only sound apples, in a cool, dark, airy place.

**October.** Finish picking before the hard frosts. Rake up fallen leaves where scab was bad: the fungus spends the winter in them.

**November.** Plant and move trees while the soil is still warm. Paint the trunks of young trees white against the winter sun, which warms the bark by day and lets it crack at night.

**December.** Go through the store once a week and take out anything that has started to rot.
`;
const varieties = String.raw`---
chapterStyle: "reference"
---

# Appendix C · Varieties for a short season

Varieties that ripen before the first hard frost and stand a valley winter, in order of picking.

**Yellow Transparent.** From the Baltic; reached America in 1870. Pale, soft, picked in early August. Will not keep: for sauce within the week.

**Duchess of Oldenburg.** Russian, known since the eighteenth century. Striped, sharp, picked in August. A cooking apple from a very hardy tree.

**Antonovka.** Russian and very old. Large, green, sour and scented. Cooks to a froth; keeps until Christmas. The hardiest tree on this list.

**Wealthy.** Raised from seed in Minnesota by Peter Gideon in the 1860s. Red, crisp, for eating in September.

**Lobo.** A McIntosh seedling released at Ottawa in 1930. Dark red, soft, sweet. Picked in mid-September.

**McIntosh.** Found as a seedling in Ontario in 1811. Scented, white-fleshed, tender. Hardy, but scab spots the fruit in wet summers.

**Fameuse.** Also called Snow, for its white flesh. Grown in Quebec since the eighteenth century. Probably a parent of McIntosh.

**Liberty.** From the Geneva station in New York, 1978. Bred to resist scab: the tree for an orchard that is never sprayed.

**Honeycrisp.** Minnesota, released in 1991. Very crisp and juicy; keeps for months. Cracks and spots on some soils.

**Haralson.** Minnesota, 1922. Tart, firm, for cooking and eating. One of the hardiest trees that carry a good keeper.

**Belle de Boskoop.** Dutch, from 1856. Russeted, sharp, large. Keeps until March. A triploid: plant two other varieties to pollinate it, and do not use its pollen for them.

**Northern Spy.** New York, about 1800. Slow to start cropping, then excellent. Firm, aromatic, the best keeper on the list.
`; // chapterStyle: reference, in its front matter
const afterword = String.raw`:::part{title="Afterword" page=false}
:::

# The valley in March

The snow goes from the south slopes first, and for a week or two the orchards above the river stand on bare brown ground while the valley floor is still white. That is the time to walk the rows with a pair of secateurs and a notebook, before the buds break.

Most of the trees in this valley were planted by people who never ate from them at their best. The old standards on M25 and on seedling roots took ten years to crop well and then cropped for sixty. The small trees on M9 that now stand in rows below them will be in full bearing by their fifth summer and finished by their twenty-fifth. Neither is the right choice for every grower. A family that wants apples soon and has a small plot will plant dwarf trees and replant them; a farm that grazes sheep and thinks in generations will plant standards and leave them to the next owner.

What matters in either case is the ground under the tree and the air around it. A tree on the right slope, in soil that drains, on a rootstock that suits the place, will forgive a great deal of bad pruning.

:::paragraphs{style="colophon"}
Set in Source Serif 4 and Source Sans 3. Text: original, CC BY 4.0.
:::
`; // a part with page=false and no style
// #region chapters: six documents in reading order; each part's style runs to the next part
// Only the first document's front matter is the book's; a later one keeps its chapterStyle.
const chapters = [front, rootstocks, appendices, calendar, varieties, afterword]
  .map((markdown) => ({ markdown }));
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'Source Serif 4': ['400', '400i', '600'], 'Source Sans 3': ['300', '400', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const all = chapters.map((chapter) => chapter.markdown).join('\n');
await prepareFonts(all, config, kitFonts(FONTS));
const docs = await withLoadedFonts(() => buildBundle({ chapters, config }),
  { ...kitFonts(FONTS), text: all });
const TITLE = t({ en: 'Apples for a Cold Valley', es: 'Manzanos para un valle frío' });
showPages(docs, { title: TITLE });

// ─── 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 ───────────────────────────────────────────────────────────────────────
```

## Varianti

### Chiedere a uno stile un’impostazione del libro

Uno stile che fissa il formato o la lingua viene ignorato per quelle chiavi. La composizione solleva un avviso `chapterStyleBookSetting` per ciascuna, e le appendici mantengono il formato del libro.

```diff
   { id: 'appendix', name: t({ en: 'Appendix', es: 'Apéndice' }), config: {
+    page: { width: mm(170) }, locale: 'fr',
     layout: { layoutType: 'double', gutterWidth: mm(6) },
```

### Riusare il progetto grafico in un altro libro

Lo strumento a riga di comando scrive il progetto grafico di un libro, stili di capitolo compresi, in un file di progetto, e con `--design` compone un altro libro secondo quel progetto. Vedi [il comando design](https://postext.dev/it/docs/command-line.md#design).

```bash
postext design apples.postext -o handbook.postext
postext pdf pears/ --design handbook.postext -o pears.pdf
```

## Errori frequenti

- La riga `:::part` deve aprire il capitolo, prima del suo titolo. Una riga di parte messa dopo l’inizio del testo del capitolo solleva `partStyleMidChapter`, e lo stile parte dal capitolo successivo.
- Un nome di stile che `chapterStyles` non contiene solleva `chapterStyleUnknown`, e quel capitolo è composto con le impostazioni del libro.

## Crediti

- Ricetta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Caratteri: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Codice: MIT · Contenuto di esempio: CC-BY-4.0

## Ricette correlate

- [Nº 019 · Parti a colori da un solo attributo](https://postext.dev/it/cookbook/parts-in-colour.md): Guida tascabile dove ogni :::part imposta una voce della tavolozza, e pagina di parte, verso dipinto, linguette, segni e riga d’indice ne prendono il colore. · Livello 3 (Avanzato) · Manuali, guide e opere di consultazione
- [Nº 007 · Un libro da capitoli separati](https://postext.dev/it/cookbook/book-from-chapters.md): buildBundle compone cinque file Markdown come un solo libro: ogni capitolo si apre su un recto e i numeri di pagina, capitolo e figura proseguono tra i file. · Livello 3 (Avanzato) · Manuali, guide e opere di consultazione
- [Nº 031 · Apparati finali di una tesi: appendice, glossario e indice](https://postext.dev/it/cookbook/thesis-back-matter.md): Le ultime pagine di una tesi in bianco e nero: appendice con lettera, glossario su due colonne, bibliografia APA e un indice costruito dai segni nel testo. · Livello 3 (Avanzato) · Articoli scientifici e testi accademici
