# 附录改排小字号双栏

> 一本单栏排的果农手册，附录换了一套设计：篇指定一种章样式，其中一篇附录指定自己的样式，后记再回到全书的设计。

- HTML版本: https://postext.dev/zh/cookbook/appendices-in-two-columns
- 食谱 No. 187 · 图书结构 · 难度 2 (中级) · 输出: Canvas
- 体裁: 手册、指南与参考书
- 需要 postext ≥ 1.79.0 · 已用 1.79.0 测试，日期 2026-11-12
- 页面: [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)
- 在沙盒中打开: https://postext.dev/zh/sandbox#recipe=appendices-in-two-columns&lang=en (.postext: https://postext.dev/cookbook/appendices-in-two-columns/en/appendices-in-two-columns.postext)
- 最后更新: 2026-11-12
- 其他语言: [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), [pt](https://postext.dev/pt/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)

## 简单来说

全书各章排成一栏宽栏。从附录开始，正文改成两栏较小的字，其中一篇附录排成三栏。全书的开本和语言始终不变。

## 成品一览

一本写给寒冷山谷中苹果种植者的小手册，开本 150 × 220 mm，由六个 Markdown 文档写成，排成一本书。第一篇的两章排成一栏两端对齐的 Source Serif 4。第二篇是附录，换了一套设计：砧木表和逐月农事历排成两栏齐左的小字，果农会在工具棚里把书摊在工作台上查这类内容；品种表则排成三栏无衬线字。后记不加篇名页，回到全书自己的设计。开本、页边距、断词和语言在每一页都相同。

**这份食谱回答的问题:**

- 怎样让书的附录或其中一篇换一套设计，比如改排小字号双栏？
- 怎样把书分成若干篇或部分，每篇有自己的颜色和隔页？

## 简短回答

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

## 用料

**讲解**

- [章样式](https://postext.dev/zh/docs/configuration-styles.md#章样式): 带名字的设置组（config.chapterStyles）：某一章在前置元数据里写 chapterStyle: 就采用它，或者用 :::part{style="…"} 让一篇里的所有章采用它。分栏、页边距、字体、标题和书眉都可以改变，而开本、语言和其他全书设置仍属于整本书。
- [篇页](https://postext.dev/zh/docs/configuration-styles.md#part容器): :::part开启一个设计过的篇页（及其背面），带编号、标题和可选的章列表，排在它所统领的各章之前。

**还用到**

- [逐章构建的书](https://postext.dev/zh/docs/configuration-bundles.md#排版和渲染文件包)
- [单栏或双栏](https://postext.dev/zh/docs/configuration-page-layout.md#版式类型)
- [三栏及以上](https://postext.dev/zh/docs/configuration-page-layout.md#版式类型)
- [设计过的章首页](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [书眉与页码](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [分节书眉](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [按页面角色显示书眉](https://postext.dev/zh/docs/configuration-headers-footers.md#文本元素)
- [对称页边距](https://postext.dev/zh/docs/configuration-page-layout.md#对称页边距)
- [页面设计中的文字、线条和框](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [段末孤行、段首孤行与孤字](https://postext.dev/zh/docs/configuration-page-flow.md#段首孤行段末孤行孤字与不拆分规则)
- [语义调色板](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板)
- [通栏章首色带](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [纸张颜色](https://postext.dev/zh/docs/configuration-page-layout.md#页面)
- [段落样式](https://postext.dev/zh/docs/configuration-styles.md#段落样式)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration-text.md#正文), [`chapterStyles`](https://postext.dev/zh/docs/configuration-styles.md#章样式), [`colorPalette`](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板), [`footer`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`header`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`headings`](https://postext.dev/zh/docs/configuration-headings.md#标题), [`layout`](https://postext.dev/zh/docs/configuration-page-layout.md#版式), [`locale`](https://postext.dev/zh/docs/configuration-language.md#断词), [`page`](https://postext.dev/zh/docs/configuration-page-layout.md#页面), [`paragraphStyles`](https://postext.dev/zh/docs/configuration-styles.md#段落样式), [`parts`](https://postext.dev/zh/docs/configuration-styles.md#篇)

**API**

- [`buildBundle`](https://postext.dev/zh/docs/configuration-bundles.md#排版和渲染文件包), [`prepareFonts`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#排版前加载字体), [`renderPageToCanvas`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#把页面渲染为位图), [`withLoadedFonts`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#排版前加载字体)

**字体**

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

## 做法

### 1 · 样式只写要改的部分

代码见上文[简短回答](https://postext.dev/zh/cookbook/appendices-in-two-columns.md#简短回答)。章样式有一个 id、一个在 Sandbox 里显示的名称，以及一份 `config`，它像语言层一样合并到全书的设置之上。对象逐键合并，列表按 `id` 或 `level` 逐项合并，所以 `smallOpener` 只点名章首的一个元素，也就是标题，把它的字号改小；标题下的线条和其他一切都保持全书的设置。附录样式只设定双栏、较小的正文字号、齐左排的行和条目间距，别的都不动。

有些设置属于整本书：`page` 中的开本、分辨率和装订，语言和书写方向，数字，字体，印刷和 PDF 输出。样式里设了其中任何一项，这一项都会被忽略，并发出 `chapterStyleBookSetting` 警告。所以附录仍是 150 mm 宽的开本，也仍按英式英语断词，与各章相同。

### 2 · 由篇指定样式

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

第三个文档以 `:::part{number="II" title="Appendices" style="appendix"}` 开头，从这一章到下一篇之前的每一章都按附录样式排。第五个文档在自己的 front matter 里写了 `chapterStyle: "reference"`，指定自己的样式，它优先于篇的样式。在一本书里，只有第一个文档的 front matter 属于全书；之后的文档只保留其中的 `chapterStyle:` 一行。

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

*附录 C：该章自己的样式是三栏无衬线字，取代了篇的双栏。*

### 3 · 有篇名页的篇，和没有篇名页的篇

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

每个 `:::part` 都会开出一张篇名页，篇号和篇名印在一条绿色色带上。后记以 `:::part{title="Afterword" page=false}` 开头：不印篇名页；这一篇也没有指定样式，所以它的章又按全书的设置来排。`page=false` 的篇适合紧接在附录之后的书后内容。

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

*第二篇的篇名页。*

### 4 · 一种章首，两种尺寸

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

章首横跨整个版面，所以在附录里它跨过两栏，正文从它下方开始分两栏排。附录样式和参考样式通过元素的 id，把标题缩到 16 pt，把章首下沉缩到 24 mm：书后的内容占地更少，标题仍比正文大得多。

### 5 · 书眉沿用全书

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

左页书眉是书名，右页书眉是章名。没有哪个样式改动它们，所以书中各篇的书眉都一样。

## 完整食谱

一个文件，由食谱文件夹合成，示例文本和排版食谱的公共工具包都已内联；它自己排出页面。要运行它，把它放进空白页面的`<script type="module">`，或粘贴到新建CodePen的JS面板里（设为模块）。它从esm.sh导入postext，不需要安装或构建。

- 食谱文件夹: 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 ───────────────────────────────────────────────────────────────────────
```

## 变化

### 让样式改整本书的设置

样式若设了开本或语言，这些键会被忽略。每个键都会引发一条 `chapterStyleBookSetting` 警告，附录仍保持全书的开本。

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

### 在另一本书中复用这套设计

命令行工具可以把一本书的设计连同章样式写进一个设计文件，再用 `--design` 让另一本书按这套设计排版。见 [design 命令](https://postext.dev/zh/docs/command-line.md#design)。

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

## 常见问题

- `:::part` 这一行必须放在章的开头、标题之前。章的正文开始之后才出现的篇行会引发 `partStyleMidChapter`，样式要到下一章才生效。
- `chapterStyles` 中没有的样式名会引发 `chapterStyleUnknown`，该章按全书的设置排。

## 致谢

- 食谱: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 字体: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- 代码: MIT · 示例内容: CC-BY-4.0

## 相关食谱

- [No. 019 · 用一个属性给各篇配色](https://postext.dev/zh/cookbook/parts-in-colour.md): 一本袖珍野外指南，每个:::part设定一个调色板条目，它的篇名页、涂色的背面、书口色标、识别特征和目录行都印成这种颜色。 · 难度 3 (高级) · 手册、指南与参考书
- [No. 007 · 由分开的各章合成一本书](https://postext.dev/zh/cookbook/book-from-chapters.md): buildBundle把五个Markdown文件排成一本书：每章从右页开始，页码、章号和图号在文件之间接续。 · 难度 3 (高级) · 手册、指南与参考书
- [No. 031 · 论文后置部分：附录、术语表和索引](https://postext.dev/zh/cookbook/thesis-back-matter.md): 一篇黑白论文的最后几页：用字母编号的附录、两栏术语表、APA参考文献，以及由正文中的标记生成的索引。 · 难度 3 (高级) · 论文与学术出版物
