# Prosa justificada sem repetições nas bordas da linha

> Uma página de Dickens composta duas vezes numa medida estreita: a primeira prova aponta e marca cada repetição, a segunda a pesa na quebra de linhas.

- Versão HTML: https://postext.dev/pt/cookbook/prose-without-stacks
- Receita Nº 184 · Tipo e texto · Nível 2 (Intermediário) · Saídas: Canvas
- Gêneros: Ficção, teatro e prosa literária
- Requer postext ≥ 1.73.0 · testada com 1.73.0 em 2026-11-10
- Páginas: [1](https://postext.dev/cookbook/prose-without-stacks/en/p01.webp?v=74376510), [2](https://postext.dev/cookbook/prose-without-stacks/en/p02.webp?v=74376510), [3](https://postext.dev/cookbook/prose-without-stacks/en/p03.webp?v=74376510), [4](https://postext.dev/cookbook/prose-without-stacks/en/p04.webp?v=74376510), [1](https://postext.dev/cookbook/prose-without-stacks/en/p05.webp?v=74376510), [2](https://postext.dev/cookbook/prose-without-stacks/en/p06.webp?v=74376510), [3](https://postext.dev/cookbook/prose-without-stacks/en/p07.webp?v=74376510), [4](https://postext.dev/cookbook/prose-without-stacks/en/p08.webp?v=74376510)
- Abrir no Sandbox: https://postext.dev/pt/sandbox#recipe=prose-without-stacks&lang=en (.postext: https://postext.dev/cookbook/prose-without-stacks/en/prose-without-stacks.postext)
- Última atualização: 2026-11-10
- Outros idiomas: [en](https://postext.dev/en/cookbook/prose-without-stacks.md), [es](https://postext.dev/es/cookbook/prose-without-stacks.md), [ca](https://postext.dev/ca/cookbook/prose-without-stacks.md), [de](https://postext.dev/de/cookbook/prose-without-stacks.md), [fr](https://postext.dev/fr/cookbook/prose-without-stacks.md), [it](https://postext.dev/it/cookbook/prose-without-stacks.md), [zh](https://postext.dev/zh/cookbook/prose-without-stacks.md), [ja](https://postext.dev/ja/cookbook/prose-without-stacks.md), [ar](https://postext.dev/ar/cookbook/prose-without-stacks.md)

## Em poucas palavras

Quando duas linhas seguidas terminam ou começam com a mesma palavra, o olho pode pular para a linha errada. O livro é composto duas vezes: uma mostra onde isso acontece, a outra quebra as linhas para que não aconteça.

## O que você vai compor

Duas provas de uma página de bolso de 115 × 180 mm com o início de *A Christmas Carol*, justificado em Spectral numa medida de 83 mm. Uma medida estreita deixa poucas saídas para o algoritmo de quebra, e em cinco lugares duas linhas seguidas terminam ou começam com a mesma palavra: *sole* sobre *sole*, *his* sobre *his*, *No* sobre *No*. A primeira prova é composta com `stacks: 'warn'`. Ela não muda nenhuma quebra, aponta cada repetição, marca as duas palavras com uma faixa vermelho-clara e as lista numa tira depois do colofão. A segunda é composta com `'avoid'`, e quatro das cinco desaparecem. A edição espanhola compõe do mesmo jeito o início de *¡Adiós, Cordera!*, de Clarín.

**Esta receita responde a:**

- Como evito que duas linhas seguidas terminem ou comecem com a mesma palavra?

## A resposta curta

```js
// script.js, linhas 41–58
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
  hyphenation: { enabled: true }, optimalLineBreaking: true, // stacks need the K–P breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A stack: two lines in a row that end on the same word or the same last characters
  // (“sole” over “sole”), or that start alike (“The” over “the”). 'warn' reports each one
  // and changes nothing; 'avoid' adds stackPenalty to the demerits of every break that
  // makes one, so the breaker sets the paragraph another way where the spacing allows.
  stacks: 'avoid', // the first proof sets 'warn' (see proofs)
  // Three characters by default; the Spanish rule counts a repeated syllable (co-/co-).
  stackMinCharacters: t({ en: 3, es: 2 }),
  // Default 3000, the cost of two hyphens in a row; a monosyllable (“his”, “lo”) costs twice.
  // 3000 kept two stacks of the first proof per edition: 10000 trades them for looser lines.
  stackPenalty: 10000,
  maxWordSpacing: 2, // the default: past it a line is never set, stack or not
};
```

## Ingredientes

**Ensina**

- [Repetições no início e no fim da linha](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo): Encontra duas linhas seguidas que terminam ou começam com a mesma palavra ou os mesmos caracteres e as aponta (bodyText.stacks: 'warn') ou faz a quebra de linhas compor o parágrafo de outro jeito ('avoid', ao custo stackPenalty).
- [Quebra de linha ótima (Knuth–Plass)](https://postext.dev/pt/docs/justification.md#knuth-plass-o-parágrafo-inteiro-de-uma-vez): Quebra cada parágrafo como um todo para igualar o espaçamento entre palavras, dentro dos limites definidos, em vez de preencher linha por linha.

**Também usa**

- [Hifenização e idioma do documento](https://postext.dev/pt/docs/justification.md#idiomas-compatíveis)
- [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)
- [Tipografia do texto](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo)
- [Aberturas desenhadas](https://postext.dev/pt/docs/configuration-headings.md#largura-e-design-avançado)
- [Imagens nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-imagem)
- [Atributos de título](https://postext.dev/pt/docs/document-format.md#atributos-de-título)
- [Cabeços e fólios](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [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)
- [Boxes](https://postext.dev/pt/docs/configuration-callouts.md#estilos-de-boxe)
- [Estilos de parágrafo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)
- [Paleta de cores semântica](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores)
- [Destaques](https://postext.dev/pt/docs/document-format-inline.md#destaques)
- [Figuras e tabelas como recursos](https://postext.dev/pt/docs/document-format-resources.md#recursos)

**A configuração em resumo**

- [`bodyText`](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo), [`calloutStyles`](https://postext.dev/pt/docs/configuration-callouts.md#estilos-de-boxe), [`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), [`markStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-destaque), [`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)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#carregar-as-fontes-antes-da-diagramação), [`registerResourceImage`](https://postext.dev/pt/docs/architecture.md#superfície-da-api), [`renderPageToCanvas`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#renderizar-uma-página-como-bitmap)

**Tipos**

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

## Preparo

### 1 · Primeiro apontar, depois pesar

```js
// script.js, linhas 41–58
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
  hyphenation: { enabled: true }, optimalLineBreaking: true, // stacks need the K–P breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A stack: two lines in a row that end on the same word or the same last characters
  // (“sole” over “sole”), or that start alike (“The” over “the”). 'warn' reports each one
  // and changes nothing; 'avoid' adds stackPenalty to the demerits of every break that
  // makes one, so the breaker sets the paragraph another way where the spacing allows.
  stacks: 'avoid', // the first proof sets 'warn' (see proofs)
  // Three characters by default; the Spanish rule counts a repeated syllable (co-/co-).
  stackMinCharacters: t({ en: 3, es: 2 }),
  // Default 3000, the cost of two hyphens in a row; a monosyllable (“his”, “lo”) costs twice.
  // 3000 kept two stacks of the first proof per edition: 10000 trades them for looser lines.
  stackPenalty: 10000,
  maxWordSpacing: 2, // the default: past it a line is never set, stack or not
};
```

Há repetição quando duas linhas seguidas terminam com a mesma palavra ou com os mesmos últimos caracteres, ou começam igual. `stackMinCharacters` define quantos caracteres são necessários: três por padrão, contando os espaços, sem contar acentos nem maiúsculas, de modo que *The* sobre *the* conta. `'warn'` só aponta, e assim quem compõe vê onde um texto se repete. `'avoid'` soma `stackPenalty` aos deméritos de cada quebra que criaria uma repetição, e o algoritmo de Knuth–Plass procura outra forma de quebrar o parágrafo. Ele precisa de `optimalLineBreaking`: a quebra linha a linha não tem deméritos aos quais somar nada.

Os manuais de composição em espanhol contam a repetição entre os vícios de composição, ao lado dos rios e das escadas de hifens. Ao voltar à margem esquerda, o olho pode se prender à palavra repetida na linha errada e ler uma linha duas vezes ou pular outra; na margem direita, a repetição soa como eco. A regra espanhola alcança também a sílaba repetida, não só a palavra, e por isso a edição espanhola fixa `stackMinCharacters` em 2.

A penalidade padrão, 3000, é o que custam dois hifens seguidos, e uma palavra repetida de uma só sílaba custa o dobro. Nesta medida, 3000 deixava duas repetições em cada edição, porque a alternativa era uma linha mais aberta do que o algoritmo aceita. Com 10000 ele aceita essas linhas. `maxWordSpacing` fica no valor padrão, 2: com um limite mais apertado o algoritmo não tinha outra quebra para escolher e `'avoid'` não mudava nada.

### 2 · Marcar as repetições no texto

```js
// script.js, linhas 173–201
// A warning names its first line by its place in the source. The repeated edge of that
// line and the next is found in each line's stretch of the source and the whole word
// around it wrapped in :mark[…]: a band under ordinary text, so the breaks stay the same.
const LETTER = /[\p{L}\p{N}’-]/u;
const edgeOf = (text, n, end) => { // the words at a line's edge holding its first/last n
  const s = text.replace(end ? /[^\p{L}\p{N}]+$/u : /^[^\p{L}\p{N}]+/u, '');
  const cut = end ? s.lastIndexOf(' ', s.length - n) + 1 : s.indexOf(' ', n);
  return end ? s.slice(cut) : s.slice(0, cut < 0 ? undefined : cut);
};
function markStacks(source, doc, stacks) {
  const lines = doc.blocks.flatMap((b) => b.lines.map((line, i) => [line, b.lines[i + 1]]));
  const spans = new Map(); // start → end of each marked word in the source
  for (const w of stacks) {
    const pair = lines.find(([line]) => line.sourceStart === w.sourceStart);
    for (const line of pair?.[1] ? pair : []) {
      const piece = edgeOf(line.text.trim(), w.text.length, w.edge === 'end');
      const range = source.slice(line.sourceStart, line.sourceEnd);
      let from = line.sourceStart
        + (w.edge === 'end' ? range.lastIndexOf(piece) : range.indexOf(piece));
      if (from < line.sourceStart) continue;
      let to = from + piece.length; // a piece of a hyphenated word takes the whole word
      while (from > 0 && LETTER.test(source[from - 1])) from--;
      while (to < source.length && LETTER.test(source[to])) to++;
      if (!/[*_[\]\n]/.test(source.slice(from, to))) spans.set(from, to);
    }
  }
  return [...spans].sort(([x], [y]) => y - x).reduce((md, [from, to]) => `${md.slice(0, from)}`
    + `:mark[${md.slice(from, to)}]{style="stack"}${md.slice(to)}`, source);
}
```

Cada aviso dá a posição da sua primeira linha no texto-fonte, então o script encontra essa linha e a seguinte no documento composto, pega a borda repetida de cada uma e envolve a palavra inteira em `:mark[…]`. Uma marca pinta uma faixa sob o texto comum e não mexe nas quebras. Só se marcam palavras inteiras: uma marca em parte de uma palavra muda a forma como essa palavra se divide, e aí as linhas já não quebram onde o aviso foi encontrado.

![Page 2.](https://postext.dev/cookbook/prose-without-stacks/en/p02.webp?v=74376510)

*Primeira prova, página 2: sole sobre sole no fim da linha, depois even sobre event e The sobre the no início.*

### 3 · Duas provas de um mesmo texto

```js
// script.js, linhas 205–224
const quote = (s) => t({ en: `“${s}”`, es: `«${s}»` });
const SIDE = { end: t({ en: 'end', es: 'final' }), start: t({ en: 'start', es: 'principio' }) };
const tally = (n) => t({ en: `${n} stack${n === 1 ? '' : 's'}`,
  es: `${n} repetici${n === 1 ? 'ón' : 'ones'}` });
const byPage = (stacks) => Object.entries(Object.groupBy(stacks, (w) => w.pageIndex + 1))
  .map(([page, list]) => `${t({ en: 'p.', es: 'pág.' })} ${page}: ${list.map((w) =>
    `${quote(w.text)} (${SIDE[w.edge]})`).join(', ')}.`);
const slip = (mode, stacks) => ['', `:::callout{type="proof" title="${mode === 'warn'
  ? t({ en: 'First proof', es: 'Primeras pruebas' })
  : t({ en: 'Second proof', es: 'Segundas pruebas' })}"}`,
`${t({ en: 'Set with', es: 'Compuesto con' })} stacks: '${mode}' · ${tally(stacks.length)}.`,
...byPage(stacks).flatMap((line) => ['', line]), ':::', ''].join('\n');
const build = (md, stacks) => buildDocumentWithFonts({ markdown: md, resources },
  { ...config, bodyText: { ...bodyText, stacks } }, kitFonts(FONTS));
async function proof(mode) {
  const plain = await build(markdown, mode); // pass 1: where the stacks are
  const stacks = (plain.contentWarnings ?? []).filter((w) => w.kind === 'stack');
  return build(markStacks(markdown, plain, stacks) + slip(mode, stacks), mode); // pass 2
}
const docs = { warn: await proof('warn'), avoid: await proof('avoid') };
```

Cada prova é composta duas vezes. A primeira composição encontra as repetições. A segunda compõe o mesmo texto com as marcas e uma tira acrescentada depois do colofão, que cai assim na última página. O pen deixa de fora das páginas publicadas a primeira composição de cada prova, o texto sem marcas: `capture.doc` lista as duas composições marcadas, `[1, 3]`.

![Page 2.](https://postext.dev/cookbook/prose-without-stacks/en/p06.webp?v=74376510)

*Segunda prova, página 2: os mesmos parágrafos quebrados de outro jeito. Só resta even sobre event.*

A repetição que fica na edição inglesa é *even* sobre *event*: as duas palavras compartilham as três primeiras letras, e qualquer outra quebra daquele parágrafo custava mais. Em espanhol, com dois caracteres, a primeira prova encontra cinco repetições, entre elas *co* de *con* sobre *como* e *ar* de *levantar* sobre *vacilar*, e a segunda nenhuma.

### 4 · A abertura sobre o texto

```js
// script.js, linhas 62–77
const PICTURE = { width: MEASURE, height: 11 * LINE }; // 83 × 52 mm, the painting's 3:2
const at = (to, edge, y, size) => ({ anchor: { to, edge }, offset: { x: mm(0), y: mm(y) },
  ...(size && { size }) });
const opener = {
  enabled: true, minHeight: pt(16 * LEAD), // the text starts on the seventeenth line
  slot: { elements: [
    { kind: 'image', id: 'art', resourceId: '{attr.art}', fit: 'cover', placement: at('container',
      'top', 0, { width: mm(PICTURE.width), height: mm(PICTURE.height) }) },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: LABEL, fontWeight: 600,
      fontSize: pt(8.5), letterSpacing: pt(1.7), color: col('accent'), align: 'left',
      placement: at('container', 'top-left', PICTURE.height + 5.5) },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, italic: true,
      fontWeight: 500, fontSize: pt(27), lineHeight: 1.05, color: col('ink'), align: 'left',
      placement: at('#kicker', 'below', 1.5, { width: mm(MEASURE), height: 'auto' }) },
  ] },
};
```

O atributo `art` do título nomeia a pintura, então um só estilo serve às duas edições. `minHeight` reserva dezesseis linhas e o texto começa na décima sétima, na mesma grade das páginas seguintes.

### 5 · Cabeços e fólio no pé

```js
// script.js, linhas 81–93
const head = (id, content, parity, edge, x, extra = {}, y = 10.5) => ({ kind: 'text', id,
  content, parity, pages: 'body', fontFamily: LABEL, fontWeight: 500, fontSize: pt(8),
  letterSpacing: pt(1.2), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(y) } }, ...extra });
const folio = { fontFamily: TEXT, letterSpacing: pt(0), color: col('ink') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-author', '{author}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{title}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'odd', 'bottom-right', -OUTER,
  { ...folio, pages: 'opener' }, -11)] }; // the opener's folio sits at the foot
```

O autor vai no verso e o título no recto, cada um ao lado do seu fólio. Na abertura os cabeços somem e o fólio desce para o pé.

## 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/prose-without-stacks

### script.js

```js
// ═══ Postext Cookbook · Nº 184 · Prose without stacks ═════════════════════════════
// https://postext.dev/en/cookbook/prose-without-stacks
// Code: MIT · Text: Dickens, 1843; Clarín, 1893 (public domain) · Paintings: diffusion model
// Fonts: Spectral, Spectral SC, Cormorant Garamond (SIL OFL 1.1) · Needs postext ≥ 1.73.0
//
// A pocket edition set twice from the same text. The first proof keeps the line breaks the
// breaker finds and reports every stack (two lines in a row that end or start alike); the
// second weighs each stack in the breaker's demerits and sets the paragraph another way.
// Each proof marks its stacks in the text and lists them on a slip after the colophon.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'prose-without-stacks';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a proofreader's red pencil over a warm book ink
const palette = {
  ink: '#241f1b', // text: a warm near-black
  accent: '#8e2f1d', // kicker, the slip's stripe and label: the red of a proof pencil
  mark: '#f4cfc2', // the band under a stacked word, pale enough for ink on top
  tint: '#f5efe6', // the slip's background
  rule: '#d2c8bb', // hairlines
  muted: '#6b6158', // running heads, colophon
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [TEXT, LABEL, DISPLAY] = ['Spectral', 'Spectral SC', 'Cormorant Garamond'];
const [BODY, LEAD] = [9.6, 13.4]; // pt
const LINE = (LEAD * 25.4) / 72; // mm: one line, 4.73
const [TRIM_W, TRIM_H, TOP, INNER, OUTER, LINES] = [115, 180, 17, 15, 17, 30];
const MEASURE = TRIM_W - INNER - OUTER; // 83 mm: about 50 characters, a narrow pocket measure

// #region answer: stacks reported in the first proof and weighed in the second
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
  hyphenation: { enabled: true }, optimalLineBreaking: true, // stacks need the K–P breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A stack: two lines in a row that end on the same word or the same last characters
  // (“sole” over “sole”), or that start alike (“The” over “the”). 'warn' reports each one
  // and changes nothing; 'avoid' adds stackPenalty to the demerits of every break that
  // makes one, so the breaker sets the paragraph another way where the spacing allows.
  stacks: 'avoid', // the first proof sets 'warn' (see proofs)
  // Three characters by default; the Spanish rule counts a repeated syllable (co-/co-).
  stackMinCharacters: t({ en: 3, es: 2 }),
  // Default 3000, the cost of two hyphens in a row; a monosyllable (“his”, “lo”) costs twice.
  // 3000 kept two stacks of the first proof per edition: 10000 trades them for looser lines.
  stackPenalty: 10000,
  maxWordSpacing: 2, // the default: past it a line is never set, stack or not
};
// #endregion

// #region opener: the painting over the measure, kicker and title under it
const PICTURE = { width: MEASURE, height: 11 * LINE }; // 83 × 52 mm, the painting's 3:2
const at = (to, edge, y, size) => ({ anchor: { to, edge }, offset: { x: mm(0), y: mm(y) },
  ...(size && { size }) });
const opener = {
  enabled: true, minHeight: pt(16 * LEAD), // the text starts on the seventeenth line
  slot: { elements: [
    { kind: 'image', id: 'art', resourceId: '{attr.art}', fit: 'cover', placement: at('container',
      'top', 0, { width: mm(PICTURE.width), height: mm(PICTURE.height) }) },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: LABEL, fontWeight: 600,
      fontSize: pt(8.5), letterSpacing: pt(1.7), color: col('accent'), align: 'left',
      placement: at('container', 'top-left', PICTURE.height + 5.5) },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, italic: true,
      fontWeight: 500, fontSize: pt(27), lineHeight: 1.05, color: col('ink'), align: 'left',
      placement: at('#kicker', 'below', 1.5, { width: mm(MEASURE), height: 'auto' }) },
  ] },
};
// #endregion

// #region heads: the author on the verso, the title on the recto, a drop folio on the opener
const head = (id, content, parity, edge, x, extra = {}, y = 10.5) => ({ kind: 'text', id,
  content, parity, pages: 'body', fontFamily: LABEL, fontWeight: 500, fontSize: pt(8),
  letterSpacing: pt(1.2), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(y) } }, ...extra });
const folio = { fontFamily: TEXT, letterSpacing: pt(0), color: col('ink') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-author', '{author}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{title}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'odd', 'bottom-right', -OUTER,
  { ...folio, pages: 'opener' }, -11)] }; // the opener's folio sits at the foot
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }), // each edition's hyphenation patterns
  colorPalette,
  page: { width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
    margins: { top: mm(TOP), bottom: mm(TRIM_H - TOP - LINES * LINE), left: mm(INNER),
      right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText,
  headings: { fontFamily: DISPLAY, color: col('ink'), levels: [{ level: 1,
    breakBefore: { enabled: true, parity: 'odd' }, marginBottom: pt(0),
    advancedDesign: opener }] },
  // The band under a stacked word: painted under ordinary text, so the lines stay as set.
  markStyles: [{ id: 'stack', name: t({ en: 'Stack', es: 'Repetición' }), background: col('mark'),
    color: col('ink'), paddingX: em(0.1), paddingTop: em(0.02), paddingBottom: em(0.08) }],
  calloutStyles: [{ id: 'proof', title: t({ en: 'Proof', es: 'Prueba' }),
    background: col('tint'), stripe: { enabled: true, side: 'top', width: pt(2.5),
      color: col('accent') },
    padding: { top: mm(2.5), right: mm(3.5), bottom: mm(2.5), left: mm(3.5) },
    titleStyle: { fontFamily: LABEL, fontSize: pt(8), fontWeight: 600, letterSpacing: pt(1.2),
      color: col('accent') },
    body: { fontFamily: TEXT, fontSize: pt(8.2), lineHeight: pt(11.2), color: col('ink'),
      textAlign: 'left', firstLineIndent: pt(0), boldColor: col('ink'),
      italicColor: col('ink') } }],
  paragraphStyles: [{ id: 'colophon', fontFamily: TEXT, fontSize: pt(7.2), lineHeight: pt(10),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
  header, footer,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// #region art: the opener's painting, one per edition: a JPEG in assets/, no lettering
const ART = t({ en: 'carol', es: 'cordera' }); // the heading's art="…" attribute
const resources = [{ id: ART, typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${ART}-1100.jpg`, format: 'jpeg', width: 1100, height: 733 },
  altText: t({
    en: 'A Victorian counting-house on a foggy evening: through the open door an old man in '
      + 'black counts coins at a high desk by a small fire, and a clerk writes by one candle.',
    es: 'Un prado en cuesta de Asturias: una vaca rubia echada en la hierba, dos niños '
      + 'abrazados a un poste del telégrafo y, abajo, un tren que sale de la trinchera.' }) }];
const ARTS = { carol: asset('carol-1100.jpg'), cordera: asset('cordera-1100.jpg') };
await loadImage(`${ART}-1100.jpg`, ARTS[ART]);
// #endregion
const markdown = String.raw`---
title: "A Christmas Carol"
author: "Charles Dickens"
---

# Marley’s Ghost {kicker="Stave One" art="carol"}

Marley was dead: to begin with. There is no doubt whatever about that. The register of his burial was signed by the clergyman, the clerk, the undertaker, and the chief mourner. Scrooge signed it: and Scrooge’s name was good upon ‘Change, for anything he chose to put his hand to. Old Marley was as dead as a door-nail.

Mind! I don’t mean to say that I know, of my own knowledge, what there is particularly dead about a door-nail. I might have been inclined, myself, to regard a coffin-nail as the deadest piece of ironmongery in the trade. But the wisdom of our ancestors is in the simile; and my unhallowed hands shall not disturb it, or the Country’s done for. You will therefore permit me to repeat, emphatically, that Marley was as dead as a door-nail.

Scrooge knew he was dead? Of course he did. How could it be otherwise? Scrooge and he were partners for I don’t know how many years. Scrooge was his sole executor, his sole administrator, his sole assign, his sole residuary legatee, his sole friend, and sole mourner. And even Scrooge was not so dreadfully cut up by the sad event, but that he was an excellent man of business on the very day of the funeral, and solemnised it with an undoubted bargain.

The mention of Marley’s funeral brings me back to the point I started from. There is no doubt that Marley was dead. This must be distinctly understood, or nothing wonderful can come of the story I am going to relate. If we were not perfectly convinced that Hamlet’s Father died before the play began, there would be nothing more remarkable in his taking a stroll at night, in an easterly wind, upon his own ramparts, than there would be in any other middle-aged gentleman rashly turning out after dark in a breezy spot—say Saint Paul’s Churchyard for instance—literally to astonish his son’s weak mind.

Scrooge never painted out Old Marley’s name. There it stood, years afterwards, above the warehouse door: Scrooge and Marley. The firm was known as Scrooge and Marley. Sometimes people new to the business called Scrooge Scrooge, and sometimes Marley, but he answered to both names. It was all the same to him.

Oh! But he was a tight-fisted hand at the grind-stone, Scrooge! a squeezing, wrenching, grasping, scraping, clutching, covetous, old sinner! Hard and sharp as flint, from which no steel had ever struck out generous fire; secret, and self-contained, and solitary as an oyster. The cold within him froze his old features, nipped his pointed nose, shrivelled his cheek, stiffened his gait; made his eyes red, his thin lips blue; and spoke out shrewdly in his grating voice. A frosty rime was on his head, and on his eyebrows, and his wiry chin. He carried his own low temperature always about with him; he iced his office in the dog-days; and didn’t thaw it one degree at Christmas.

External heat and cold had little influence on Scrooge. No warmth could warm, no wintry weather chill him. No wind that blew was bitterer than he, no falling snow was more intent upon its purpose, no pelting rain less open to entreaty. Foul weather didn’t know where to have him. The heaviest rain, and snow, and hail, and sleet, could boast of the advantage over him in only one respect. They often “came down” handsomely, and Scrooge never did.

Nobody ever stopped him in the street to say, with gladsome looks, “My dear Scrooge, how are you? When will you come to see me?” No beggars implored him to bestow a trifle, no children asked him what it was o’clock, no man or woman ever once in all his life inquired the way to such and such a place, of Scrooge. Even the blind men’s dogs appeared to know him; and when they saw him coming on, would tug their owners into doorways and up courts; and then would wag their tails as though they said, “No eye at all is better than an evil eye, dark master!”

But what did Scrooge care! It was the very thing he liked. To edge his way along the crowded paths of life, warning all human sympathy to keep its distance, was what the knowing ones call “nuts” to Scrooge.

:::paragraphs{style="colophon"}
Charles Dickens, *A Christmas Carol*, London, 1843: the opening of Stave One, from Project Gutenberg eBook #46 (public domain) · Set in Spectral, Spectral SC and Cormorant Garamond (SIL Open Font License) · Painting made for this page with a diffusion model.
:::
`; // content.<lang>.md, inlined by the Cookbook

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

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// #region marks: each stack the build reported, marked on both of its lines
// A warning names its first line by its place in the source. The repeated edge of that
// line and the next is found in each line's stretch of the source and the whole word
// around it wrapped in :mark[…]: a band under ordinary text, so the breaks stay the same.
const LETTER = /[\p{L}\p{N}’-]/u;
const edgeOf = (text, n, end) => { // the words at a line's edge holding its first/last n
  const s = text.replace(end ? /[^\p{L}\p{N}]+$/u : /^[^\p{L}\p{N}]+/u, '');
  const cut = end ? s.lastIndexOf(' ', s.length - n) + 1 : s.indexOf(' ', n);
  return end ? s.slice(cut) : s.slice(0, cut < 0 ? undefined : cut);
};
function markStacks(source, doc, stacks) {
  const lines = doc.blocks.flatMap((b) => b.lines.map((line, i) => [line, b.lines[i + 1]]));
  const spans = new Map(); // start → end of each marked word in the source
  for (const w of stacks) {
    const pair = lines.find(([line]) => line.sourceStart === w.sourceStart);
    for (const line of pair?.[1] ? pair : []) {
      const piece = edgeOf(line.text.trim(), w.text.length, w.edge === 'end');
      const range = source.slice(line.sourceStart, line.sourceEnd);
      let from = line.sourceStart
        + (w.edge === 'end' ? range.lastIndexOf(piece) : range.indexOf(piece));
      if (from < line.sourceStart) continue;
      let to = from + piece.length; // a piece of a hyphenated word takes the whole word
      while (from > 0 && LETTER.test(source[from - 1])) from--;
      while (to < source.length && LETTER.test(source[to])) to++;
      if (!/[*_[\]\n]/.test(source.slice(from, to))) spans.set(from, to);
    }
  }
  return [...spans].sort(([x], [y]) => y - x).reduce((md, [from, to]) => `${md.slice(0, from)}`
    + `:mark[${md.slice(from, to)}]{style="stack"}${md.slice(to)}`, source);
}
// #endregion

// #region proofs: the same text twice, 'warn' then 'avoid', each with its stacks marked
const quote = (s) => t({ en: `“${s}”`, es: `«${s}»` });
const SIDE = { end: t({ en: 'end', es: 'final' }), start: t({ en: 'start', es: 'principio' }) };
const tally = (n) => t({ en: `${n} stack${n === 1 ? '' : 's'}`,
  es: `${n} repetici${n === 1 ? 'ón' : 'ones'}` });
const byPage = (stacks) => Object.entries(Object.groupBy(stacks, (w) => w.pageIndex + 1))
  .map(([page, list]) => `${t({ en: 'p.', es: 'pág.' })} ${page}: ${list.map((w) =>
    `${quote(w.text)} (${SIDE[w.edge]})`).join(', ')}.`);
const slip = (mode, stacks) => ['', `:::callout{type="proof" title="${mode === 'warn'
  ? t({ en: 'First proof', es: 'Primeras pruebas' })
  : t({ en: 'Second proof', es: 'Segundas pruebas' })}"}`,
`${t({ en: 'Set with', es: 'Compuesto con' })} stacks: '${mode}' · ${tally(stacks.length)}.`,
...byPage(stacks).flatMap((line) => ['', line]), ':::', ''].join('\n');
const build = (md, stacks) => buildDocumentWithFonts({ markdown: md, resources },
  { ...config, bodyText: { ...bodyText, stacks } }, kitFonts(FONTS));
async function proof(mode) {
  const plain = await build(markdown, mode); // pass 1: where the stacks are
  const stacks = (plain.contentWarnings ?? []).filter((w) => w.kind === 'stack');
  return build(markStacks(markdown, plain, stacks) + slip(mode, stacks), mode); // pass 2
}
const docs = { warn: await proof('warn'), avoid: await proof('avoid') };
// #endregion

const TITLE = t({ en: 'Prose without stacks', es: 'Prosa sin repeticiones' });
const show = (key) => showPages(docs[key], { title: `${TITLE} · stacks: '${key}'` });
const button = (key) => Object.assign(document.createElement('button'),
  { type: 'button', textContent: key, onclick: () => show(key) });
document.getElementById('pt-actions').prepend(button('warn'), button('avoid'));
show('warn');

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

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

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

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

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

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

## Variações

### Contar só palavras longas

Três caracteres é o padrão. Com cinco, palavras curtas como *his* e *No* deixam de contar como repetição, e o algoritmo mantém em volta delas as quebras mais apertadas.

```diff
-  stackMinCharacters: t({ en: 3, es: 2 }),
+  stackMinCharacters: 5,
```

### Compor o livro com a penalidade padrão

O padrão mantém o espaçamento mais apertado e aceita duas repetições por edição onde evitá-las abriria mais uma linha.

```diff
-  stackPenalty: 10000,
+  stackPenalty: 3000,
```

## Erros comuns

- **Aviso de diagramação: Repetição** (`stack`). Duas linhas seguidas de um parágrafo, na mesma coluna, terminam com a mesma palavra ou os mesmos últimos bodyText.stackMinCharacters caracteres (3 por padrão, espaços incluídos), ou começam igual: «…de um» sobre «…com um». Acentos e maiúsculas não contam, e só há repetições nas escritas que separam as palavras com espaços. Com bodyText.stacks em 'warn' todas são assinaladas; em 'avoid', as que a quebra de linha manteve porque nenhuma composição dentro do espaçamento entre palavras as evitava por menos que bodyText.stackPenalty. O motor regista cada uma em doc.contentWarnings com o texto repetido, a borda (fim ou início), as duas linhas e a página. Solução: Ponha bodyText.stacks em 'avoid': a quebra de linha compõe o parágrafo de outro modo onde o espaçamento entre palavras permite. Uma repetição que fica custa mais a evitar que bodyText.stackPenalty: aumente a penalização para a trocar por linhas mais soltas, ou reescreva uma das duas linhas. Num port de um livro existente mantenha 'warn': o port reproduz as quebras do original. ([Documentação](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo))

- As repetições são procuradas nas linhas já quebradas. Se você mudar o formato, o corpo ou o texto, a primeira prova encontra outras: leia os avisos de cada composição e não copie posições de uma anterior.
- As repetições são contadas dentro de um parágrafo e só em escritas que separam as palavras com espaços: dois parágrafos que começam com *Scrooge* não fazem repetição, e um texto em chinês ou japonês nunca aponta nenhuma.

## Créditos

- Receita: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: A Christmas Carol (1843), the opening of Stave One, from Project Gutenberg eBook #46, with typographic quotes and dashes: Charles Dickens ([fonte](https://www.gutenberg.org/ebooks/46)), domínio público
- Texto: ¡Adiós, Cordera!, the opening of the story, from El Señor y lo demás son cuentos (Madrid, 1919), with « » quotation marks: Leopoldo Alas, Clarín ([fonte](https://es.wikisource.org/wiki/%C2%A1Adi%C3%B3s,_Cordera!)), domínio público
- Imagens: Painting: Scrooge's counting-house on a foggy Christmas Eve: Generated With Diffusion Models, original
- Imagens: Painting: Rosa, Pinín and the Cordera by the telegraph pole: Generated With Diffusion Models, original
- Tipos: Spectral (OFL-1.1), Spectral SC (OFL-1.1), Cormorant Garamond (OFL-1.1)
- Código: MIT · Conteúdo de exemplo: CC-BY-4.0

## Relacionadas

- [Nº 104 · Uma novela catalã, hifenizada pelas regras do IEC](https://postext.dev/pt/cookbook/catalan-pocket-novella.md): El transplantat, de Oller, completo num livro de bolso de 32 páginas: sílabas catalãs pelo IEC, l·l quebrado como il- | lusió e uma gravura por capítulo. · Nível 2 (Intermediário) · Ficção, teatro e prosa literária
- [Nº 016 · Espanhol justificado num romance de bolso](https://postext.dev/pt/cookbook/spanish-pocket-novel.md): O início de Marianela em edição de bolso: hifenização espanhola, espaços abaixo de 1,7×, sem linhas curtas, capitular elevada e o mapa como Figura 1. · Nível 2 (Intermediário) · Ficção, teatro e prosa literária
- [Nº 180 · Destaques por cor em um livro de leituras](https://postext.dev/pt/cookbook/colour-coded-study-highlights.md): Um livro de leituras de história cujas palavras-chave levam três cores (verde para termos, âmbar para datas, azul para nomes) vindas de três markStyles. · Nível 2 (Intermediário) · Livros didáticos
