# Apêndices em duas colunas com corpo menor

> Um manual de fruticultura em uma coluna cujos apêndices mudam de projeto: uma parte nomeia um estilo de capítulo, um apêndice nomeia o seu e o posfácio volta.

- Versão HTML: https://postext.dev/pt/cookbook/appendices-in-two-columns
- Receita Nº 187 · Estrutura do livro · Nível 2 (Intermediário) · Saídas: Canvas
- Gêneros: Manuais, guias e obras de referência
- Requer postext ≥ 1.79.0 · testada com 1.79.0 em 2026-11-12
- Páginas: [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)
- Abrir no Sandbox: https://postext.dev/pt/sandbox#recipe=appendices-in-two-columns&lang=en (.postext: https://postext.dev/cookbook/appendices-in-two-columns/en/appendices-in-two-columns.postext)
- Última atualização: 2026-11-12
- Outros idiomas: [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), [it](https://postext.dev/it/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)

## Em poucas palavras

Os capítulos do livro são compostos em uma coluna larga. A partir dos apêndices, o texto corre em duas colunas de letra menor, e um apêndice em três. O tamanho da página e o idioma do livro não mudam em nenhum momento.

## O que você vai compor

Um pequeno manual para quem cultiva macieiras num vale frio, de 150 × 220 mm, escrito em seis documentos Markdown e diagramado como um só livro. Os dois capítulos da parte I são compostos em uma coluna justificada de Source Serif 4. A parte II, os apêndices, muda de projeto: uma tabela de porta-enxertos e um calendário mês a mês em duas colunas em bandeira e corpo menor, matéria que o produtor lê no galpão com o livro aberto sobre a bancada, e uma lista de variedades em três colunas sem serifa. O posfácio volta ao projeto do próprio livro sem página divisória. Formato, margens, hifenização e idioma são os mesmos em todas as páginas.

**Esta receita responde a:**

- Como dou aos apêndices de um livro outro projeto gráfico, como duas colunas em corpo menor?
- Como divido um livro em partes ou seções, cada uma com sua cor e sua página divisória?

## A resposta curta

```js
// script.js, linhas 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.
```

## Ingredientes

**Ensina**

- [Estilos de capítulo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-capítulo): Conjuntos de ajustes com nome (config.chapterStyles) que um capítulo adota com chapterStyle: no seu front matter, ou todos os capítulos de uma parte com :::part{style="…"}: mudam as colunas, as margens, a letra, os títulos e os cabeços, e o formato, o idioma e os outros ajustes do livro inteiro continuam sendo os do livro.
- [Páginas de abertura de parte](https://postext.dev/pt/docs/configuration-styles.md#o-contêiner-part): Um :::part abre uma página divisória projetada (e o seu verso) com número, título e, se quiser, a lista de capítulos, acima dos capítulos que ela agrupa.

**Também usa**

- [Livros compostos capítulo a capítulo](https://postext.dev/pt/docs/configuration-bundles.md#diagramar-e-renderizar-um-pacote)
- [Uma ou duas colunas](https://postext.dev/pt/docs/configuration-page-layout.md#tipos-de-layout)
- [Três ou mais colunas](https://postext.dev/pt/docs/configuration-page-layout.md#tipos-de-layout)
- [Aberturas desenhadas](https://postext.dev/pt/docs/configuration-headings.md#largura-e-design-avançado)
- [Cabeços e fólios](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Cabeços por seção](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Cabeços por tipo de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-texto)
- [Margens espelhadas](https://postext.dev/pt/docs/configuration-page-layout.md#margens-espelhadas)
- [Textos, fios e caixas nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Viúvas, órfãs e linhas curtas](https://postext.dev/pt/docs/configuration-page-flow.md#órfãs-viúvas-linhas-curtas-e-regras-de-manter-junto)
- [Paleta de cores semântica](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores)
- [Faixa de capítulo em largura total](https://postext.dev/pt/docs/configuration-headings.md#largura-e-design-avançado)
- [Cor do papel](https://postext.dev/pt/docs/configuration-page-layout.md#página)
- [Estilos de parágrafo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)

**A configuração em resumo**

- [`bodyText`](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo), [`chapterStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-capítulo), [`colorPalette`](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores), [`footer`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`header`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`headings`](https://postext.dev/pt/docs/configuration-headings.md#títulos), [`layout`](https://postext.dev/pt/docs/configuration-page-layout.md#diagramação), [`locale`](https://postext.dev/pt/docs/configuration-language.md#hifenização), [`page`](https://postext.dev/pt/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo), [`parts`](https://postext.dev/pt/docs/configuration-styles.md#partes)

**API**

- [`buildBundle`](https://postext.dev/pt/docs/configuration-bundles.md#diagramar-e-renderizar-um-pacote), [`prepareFonts`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#carregar-as-fontes-antes-da-diagramação), [`renderPageToCanvas`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#renderizar-uma-página-como-bitmap), [`withLoadedFonts`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#carregar-as-fontes-antes-da-diagramação)

**Tipos**

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

## Preparo

### 1 · Um estilo guarda só o que muda

O código é [a resposta curta](https://postext.dev/pt/cookbook/appendices-in-two-columns.md#a-resposta-curta) logo acima. Um estilo de capítulo tem um id, um nome para o Sandbox e um `config` que é mesclado sobre as configurações do livro, como acontece com a camada de um idioma. Os objetos se mesclam chave a chave e as listas entrada a entrada, pelo `id` ou pelo `level`. Assim, `smallOpener` nomeia um único elemento da abertura, o título, e lhe dá um corpo menor; o fio abaixo dele e todo o resto ficam como o livro os define. O estilo de apêndice define duas colunas, um corpo de texto menor, linhas em bandeira e espaço entre as entradas, e nada mais.

Algumas configurações pertencem ao livro inteiro: o formato, a resolução e a encadernação de `page`, o idioma e a direção da escrita, os algarismos, as fontes, a impressão e a saída em PDF. Um estilo que defina alguma delas é ignorado nesse ponto e gera um aviso `chapterStyleBookSetting`, de modo que os apêndices mantêm o formato de 150 mm e a hifenização em inglês britânico dos capítulos.

### 2 · A parte nomeia o estilo

```js
// script.js, linhas 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 }));
```

O terceiro documento começa com `:::part{number="II" title="Appendices" style="appendix"}`, e todos os capítulos dali até a parte seguinte são compostos no estilo de apêndice. O quinto nomeia seu próprio estilo no front matter, `chapterStyle: "reference"`, que prevalece sobre o da parte. Num livro, só o front matter do primeiro documento vale para o livro; um documento posterior mantém apenas a linha `chapterStyle:`.

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

*Apêndice C: o estilo próprio do capítulo, três colunas sem serifa, no lugar das duas da parte.*

### 3 · Uma página divisória, e uma parte sem ela

```js
// script.js, linhas 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) }),
  ] },
};
```

Cada `:::part` abre uma página divisória com o número e o título da parte sobre uma faixa verde. O posfácio começa com `:::part{title="Afterword" page=false}`: nenhuma página divisória é impressa e, como a parte não nomeia estilo, seu capítulo volta a ser composto com as configurações do livro. Uma parte com `page=false` serve para as páginas finais que seguem os apêndices sem interrupção.

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

*A página divisória da parte II.*

### 4 · Uma abertura em dois tamanhos

```js
// script.js, linhas 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) } } },
] } };
```

A abertura ocupa toda a largura da página; nos apêndices, portanto, ela passa por cima das duas colunas e o texto começa embaixo, em duas. Os estilos de apêndice e de consulta reduzem o título a 16 pt e o rebaixamento a 24 mm pelo id do elemento: a matéria do fim do livro ocupa menos espaço, e seus títulos continuam bem maiores que o texto.

### 5 · Cabeços do livro

```js
// script.js, linhas 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) })] };
```

O título do livro vai na página par e o do capítulo na ímpar. Nenhum estilo os altera, então os cabeços são iguais em todas as partes do livro.

## A receita completa

Um único arquivo, composto a partir da pasta da receita com o texto de exemplo e o kit comum das Receitas já incluídos; ele monta a própria página. Para executá-lo, coloque-o em um `<script type="module">` de uma página vazia ou cole-o no painel JS de um pen novo do CodePen (como módulo). Ele importa o postext do esm.sh, então não há nada para instalar nem compilar.

- Pasta da receita: 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 ───────────────────────────────────────────────────────────────────────
```

## Variações

### Pedir a um estilo uma configuração do livro

Um estilo que define o formato ou o idioma é ignorado nessas chaves. A composição gera um aviso `chapterStyleBookSetting` para cada uma, e os apêndices mantêm o formato do livro.

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

### Reaproveitar o projeto em outro livro

A ferramenta de linha de comando grava o projeto gráfico de um livro, com os estilos de capítulo, num arquivo de projeto, e compõe outro livro com ele usando `--design`. Veja [o comando design](https://postext.dev/pt/docs/command-line.md#design).

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

## Erros comuns

- A linha `:::part` precisa abrir o capítulo, antes do título. Uma linha de parte colocada depois que o texto do capítulo já começou gera `partStyleMidChapter`, e o estilo só começa no capítulo seguinte.
- Um nome de estilo que não existe em `chapterStyles` gera `chapterStyleUnknown`, e aquele capítulo é composto com as configurações do livro.

## Créditos

- Receita: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Tipos: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Código: MIT · Conteúdo de exemplo: CC-BY-4.0

## Relacionadas

- [Nº 019 · Partes em cores com um único atributo](https://postext.dev/pt/cookbook/parts-in-colour.md): Num guia de campo de bolso, cada :::part redefine uma cor da paleta, que tinge a página divisória, o verso pintado, a aba lateral e a linha do sumário. · Nível 3 (Avançado) · Manuais, guias e obras de referência
- [Nº 007 · Um livro feito de capítulos separados](https://postext.dev/pt/cookbook/book-from-chapters.md): buildBundle junta cinco arquivos Markdown num livro: cada capítulo abre em página ímpar, e páginas, capítulos e figuras seguem numerados de arquivo em arquivo. · Nível 3 (Avançado) · Manuais, guias e obras de referência
- [Nº 031 · Pós-textuais de tese: apêndice, glossário e índice](https://postext.dev/pt/cookbook/thesis-back-matter.md): As últimas páginas de uma tese em preto e branco: apêndice com letra, glossário em duas colunas, referências APA e índice montado a partir de marcas no texto. · Nível 3 (Avançado) · Artigos e trabalhos acadêmicos
