# Prosa justificada sin repeticiones en los bordes de línea

> Una página de Clarín compuesta dos veces en una medida estrecha: las primeras pruebas señalan cada repetición; las segundas la pesan en el corte de líneas.

- Versión HTML: https://postext.dev/es/cookbook/prose-without-stacks
- Receta N.º 184 · Texto y tipografía · Nivel 2 (Intermedio) · Salidas: Canvas
- Géneros: Narrativa, teatro y prosa literaria
- Requiere postext ≥ 1.73.0 · probada con 1.73.0 el 2026-11-10
- Páginas: [1](https://postext.dev/cookbook/prose-without-stacks/es/p01.webp?v=5acadaf9), [2](https://postext.dev/cookbook/prose-without-stacks/es/p02.webp?v=5acadaf9), [3](https://postext.dev/cookbook/prose-without-stacks/es/p03.webp?v=5acadaf9), [4](https://postext.dev/cookbook/prose-without-stacks/es/p04.webp?v=5acadaf9), [1](https://postext.dev/cookbook/prose-without-stacks/es/p05.webp?v=5acadaf9), [2](https://postext.dev/cookbook/prose-without-stacks/es/p06.webp?v=5acadaf9), [3](https://postext.dev/cookbook/prose-without-stacks/es/p07.webp?v=5acadaf9), [4](https://postext.dev/cookbook/prose-without-stacks/es/p08.webp?v=5acadaf9)
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=prose-without-stacks&lang=es (.postext: https://postext.dev/cookbook/prose-without-stacks/es/prose-without-stacks.postext)
- Última actualización: 2026-11-10
- Otros idiomas: [en](https://postext.dev/en/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), [pt](https://postext.dev/pt/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)

## En pocas palabras

Cuando dos líneas seguidas acaban o empiezan con la misma palabra, la vista puede saltar a la línea equivocada. El libro se compone dos veces: una enseña dónde pasa y otra corta las líneas para que no pase.

## Lo que vas a componer

Dos pruebas de una página de bolsillo de 115 × 180 mm con el comienzo de *¡Adiós, Cordera!*, de Clarín, justificado en Spectral sobre una medida de 83 mm. Una medida estrecha deja al cortador de líneas pocas salidas, y en cinco sitios dos líneas seguidas acaban o empiezan igual: *con* sobre *como*, *lo* sobre *los*, *levantar* sobre *vacilar*. Las primeras pruebas se componen con `stacks: 'warn'`: no cambian ningún corte, avisan de cada repetición, marcan las dos palabras con una banda rojo pálido y las listan en una papeleta tras el colofón. Las segundas se componen con `'avoid'`, y las cinco desaparecen. La edición inglesa compone igual el comienzo de *A Christmas Carol*.

**Esta receta responde a:**

- ¿Cómo evito que dos líneas seguidas acaben o empiecen con la misma palabra?

## La respuesta corta

```js
// script.js, líneas 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

**Enseña**

- [Repeticiones a principio y final de línea](https://postext.dev/es/docs/configuration-text.md#texto-base): Encuentra dos líneas seguidas que terminan o empiezan con la misma palabra o los mismos caracteres, y las señala (bodyText.stacks: 'warn') o hace que el corte de líneas componga el párrafo de otra manera ('avoid', al coste stackPenalty).
- [Corte de líneas óptimo (Knuth–Plass)](https://postext.dev/es/docs/justification.md#knuth-plass-ver-el-párrafo-completo): Corta cada párrafo en su conjunto para igualar el espacio entre palabras, dentro de los límites fijados, en lugar de llenar línea a línea.

**También usa**

- [Separación silábica e idioma del documento](https://postext.dev/es/docs/justification.md#idiomas-admitidos)
- [Viudas, huérfanas y líneas cortas](https://postext.dev/es/docs/configuration-page-flow.md#huérfanas-viudas-líneas-cortas-y-reglas-de-cohesión)
- [Tipografía del texto](https://postext.dev/es/docs/configuration-text.md#texto-base)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Imágenes en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-imagen)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Cabeceras y folios](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Márgenes simétricos](https://postext.dev/es/docs/configuration-page-layout.md#márgenes-simétricos-espejo)
- [Recuadros](https://postext.dev/es/docs/configuration-callouts.md#estilos-de-recuadro)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Marcas de resaltado](https://postext.dev/es/docs/document-format-inline.md#marcas-de-resaltado)
- [Figuras y tablas como recursos](https://postext.dev/es/docs/document-format-resources.md#recursos)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`calloutStyles`](https://postext.dev/es/docs/configuration-callouts.md#estilos-de-recuadro), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`markStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-resaltado), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), [`registerResourceImage`](https://postext.dev/es/docs/architecture.md#api-pública), [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits)

**Tipografías**

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

## Elaboración

### 1 · Primero avisar, después pesar

```js
// script.js, líneas 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
};
```

Hay repetición cuando dos líneas seguidas acaban en la misma palabra o en los mismos últimos caracteres, o empiezan igual. `stackMinCharacters` fija cuántos caracteres hacen falta: tres por omisión, con los espacios, sin contar tildes ni mayúsculas, de modo que *Los* sobre *los* cuenta. `'warn'` solo avisa, y así ve quien compone dónde se repite un texto. `'avoid'` suma `stackPenalty` a los deméritos de cada corte que produciría una repetición, y el cortador de Knuth–Plass busca otra forma de partir el párrafo. Necesita `optimalLineBreaking`: el cortador voraz no tiene deméritos a los que sumar nada.

Los manuales de composición en español cuentan la repetición entre los vicios de composición, junto a los ríos y las escaleras de guiones. Al volver al margen izquierdo, la vista puede engancharse a la palabra repetida en la línea equivocada y leer dos veces una línea o saltarse otra; en el margen derecho, la repetición suena a eco. La norma española alcanza también a la sílaba repetida, no solo a la palabra, y por eso la edición española fija `stackMinCharacters` en 2.

La penalización por omisión, 3000, es lo que cuestan dos guiones seguidos, y una palabra repetida de una sola sílaba cuesta el doble. En esta medida, 3000 dejaba dos repeticiones en cada edición, porque la alternativa era una línea más abierta de lo que el cortador acepta. Con 10000 acepta esas líneas. `maxWordSpacing` se queda en su valor por omisión, 2: con un límite más estrecho el cortador no tenía otro corte que elegir y `'avoid'` no cambiaba nada.

### 2 · Marcar las repeticiones en el texto

```js
// script.js, líneas 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 da la posición en el texto fuente de su primera línea, así que el script busca esa línea y la siguiente en el documento compuesto, toma el borde repetido de cada una y envuelve la palabra entera en `:mark[…]`. Una marca pinta una banda bajo el texto normal y no toca los cortes. Solo se marcan palabras enteras: una marca sobre media palabra cambia cómo se divide esa palabra, y entonces las líneas ya no se cortan donde se encontró el aviso.

![Página 2. Primeras pruebas, página 2: bandas rojo pálido bajo con y como al principio de dos líneas y bajo lo y los, al principio de otras dos.](https://postext.dev/cookbook/prose-without-stacks/es/p02.webp?v=5acadaf9)

*Primeras pruebas, página 2: con sobre como y lo sobre los, al principio de línea.*

### 3 · Dos pruebas de un mismo texto

```js
// script.js, líneas 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 prueba se compone dos veces. La primera composición encuentra las repeticiones. La segunda compone el mismo texto con las marcas y una papeleta añadida tras el colofón, de modo que la papeleta cae en la última página. El pen deja fuera de las páginas publicadas la primera composición de cada prueba, el texto sin marcar: `capture.doc` lista las dos composiciones marcadas, `[1, 3]`.

![Página 2.](https://postext.dev/cookbook/prose-without-stacks/es/p06.webp?v=5acadaf9)

*Segundas pruebas, página 2: los mismos párrafos cortados de otra manera, sin ninguna repetición.*

En la edición inglesa, con tres caracteres, queda una: *even* sobre *event*, que comparten sus tres primeras letras, porque cualquier otro corte de ese párrafo costaba más.

### 4 · La apertura sobre el texto

```js
// script.js, líneas 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' }) },
  ] },
};
```

El atributo `art` del título nombra la pintura, así que un solo estilo sirve a las dos ediciones. `minHeight` reserva dieciséis líneas y el texto empieza en la decimoséptima, sobre la misma retícula que las páginas siguientes.

### 5 · Titulillos y folio caído

```js
// script.js, líneas 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
```

El autor va en la página par y el título en la impar, cada uno junto a su folio. En la apertura no hay titulillos y el folio baja al pie.

## La receta completa

Un solo archivo, compuesto a partir de la carpeta de la receta con el texto de ejemplo y el kit común del Recetario ya incluidos; construye su propia página. Para ejecutarlo, ponlo en un `<script type="module">` de una página vacía o pégalo en el panel JS de un pen nuevo de CodePen (como módulo). Importa postext desde esm.sh, así que no hay nada que instalar ni compilar.

- Carpeta de la receta: 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 = 'es'; // @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: "¡Adiós, Cordera!"
author: "Leopoldo Alas, Clarín"
---

# ¡Adiós, Cordera! {kicker="Cuento" art="cordera"}

¡Eran tres: siempre los tres! Rosa, Pinín y la Cordera.

El prao Somonte era un recorte triangular de terciopelo verde tendido, como una colgadura, cuesta abajo por la loma. Uno de sus ángulos, el inferior, lo despuntaba el camino de hierro de Oviedo a Gijón. Un palo del telégrafo, plantado allí como pendón de conquista, con sus jícaras blancas y sus alambres paralelos, a derecha e izquierda, representaba para Rosa y Pinín el ancho mundo desconocido, misterioso, temible, eternamente ignorado. Pinín, después de pensarlo mucho, cuando a fuerza de ver días y días el poste tranquilo, inofensivo, campechano, con ganas, sin duda, de aclimatarse en la aldea y parecerse todo lo posible a un árbol seco, fué atreviéndose con él, llevó la confianza al extremo de abrazarse al leño y trepar hasta cerca de los alambres. Pero nunca llegaba a tocar la porcelana de arriba, que le recordaba las jícaras que había visto en la rectoral de Puao. Al verse tan cerca del misterio sagrado, le acometía un pánico de respeto, y se dejaba resbalar de prisa hasta tropezar con los pies en el césped.

Rosa, menos audaz, pero más enamorada de lo desconocido, se contentaba con arrimar el oído al palo del telégrafo, y minutos, y hasta cuartos de hora, pasaba escuchando los formidables rumores metálicos que el viento arrancaba a las fibras del pino seco en contacto con el alambre. Aquellas vibraciones, a veces intensas como las del diapasón, que, aplicado al oído, parece que quema con su vertiginoso latir, eran para Rosa los papeles que pasaban, las cartas que se escribían por los hilos, el lenguaje incomprensible que lo ignorado hablaba con lo ignorado; ella no tenía curiosidad por entender lo que los de allá, tan lejos, decían a los del otro extremo del mundo. ¿Qué le importaba? Su interés estaba en el ruido por el ruido mismo, por su timbre y su misterio.

La Cordera, mucho más formal que sus compañeros, verdad es que, relativamente, de edad también mucho más madura, se abstenía de toda comunicación con el mundo civilizado, y miraba de lejos el palo del telégrafo, como lo que era para ella, efectivamente, como cosa muerta, inútil, que no le servía siquiera para rascarse. Era una vaca que había vivido mucho. Sentada horas y horas, pues, experta en pastos, sabía aprovechar el tiempo, meditaba más que comía, gozaba del placer de vivir en paz, bajo el cielo gris y tranquilo de su tierra, como quien alimenta el alma, que también tienen los brutos; y si no fuera profanación, podría decirse que los pensamientos de la vaca matrona, llena de experiencia, debían de parecerse todo lo posible a las más sosegadas y doctrinales odas de Horacio.

Asistía a los juegos de los pastorcicos encargados de llindarla, como una abuela. Si pudiera, se sonreiría al pensar que Rosa y Pinín tenían por misión en el prado cuidar de que ella, la Cordera, no se extralimitase, no se metiese por la vía del ferrocarril ni saltara a la heredad vecina. ¡Qué había de saltar! ¡Qué se había de meter!

Pastar de cuando en cuando, no mucho, cada día menos, pero con atención, sin perder el tiempo en levantar la cabeza por curiosidad necia, escogiendo sin vacilar los mejores bocados, y, después, sentarse sobre el cuarto trasero con delicia, a rumiar la vida, a gozar el deleite del no padecer, del dejarse existir: esto era lo que ella tenía que hacer, y todo lo demás aventuras peligrosas. Ya no recordaba cuándo le había picado la mosca.

«El xatu (el toro), los saltos locos por las praderas adelante... ¡todo eso estaba tan lejos!»

Aquella paz sólo se había turbado en los días de prueba de la inauguración del ferrocarril. La primera vez que la Cordera vió pasar el tren, se volvió loca. Saltó la sebe de lo más alto del Somonte, corrió por prados ajenos, y el terror duró muchos días, renovándose, más o menos violento, cada vez que la máquina asomaba por la trinchera vecina. Poco a poco se fué acostumbrando al estrépito inofensivo. Cuando llegó a convencerse de que era un peligro que pasaba, una catástrofe que amenazaba sin dar, redujo sus precauciones a ponerse en pie y a mirar de frente, con la cabeza erguida, al formidable monstruo; más adelante no hacía más que mirarle, sin levantarse, con antipatía y desconfianza; acabó por no mirar al tren siquiera.

En Pinín y Rosa la novedad del ferrocarril produjo impresiones más agradables y persistentes. Si al principio era una alegría loca, algo mezclada de miedo supersticioso, una excitación nerviosa, que les hacía prorrumpir en gritos, gestos, pantomimas descabelladas, después fué un recreo pacífico, suave, renovado varias veces al día. Tardó mucho en gastarse aquella emoción de contemplar la marcha vertiginosa, acompañada del viento, de la gran culebra de hierro, que llevaba dentro de sí tanto ruido y tantas castas de gentes desconocidas, extrañas.

:::paragraphs{style="colophon"}
Leopoldo Alas, Clarín, «¡Adiós, Cordera!», en *El Señor y lo demás son cuentos*, Madrid, 1919: comienzo del cuento, según el texto de Wikisource (dominio público) · Compuesto en Spectral, Spectral SC y Cormorant Garamond (SIL Open Font License) · Pintura de un modelo de difusión, hecha para esta página.
:::
`; // 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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Contar solo palabras largas

Con cinco caracteres, palabras cortas como *lo* o *los* dejan de contar como repetición, y el cortador mantiene los cortes más apretados alrededor de ellas.

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

### Componer con la penalización por omisión

La penalización por omisión aprieta más el espaciado y acepta dos repeticiones por edición donde evitarlas abriría más una línea.

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

## Errores frecuentes

- **Aviso de maquetación: Repetición** (`stack`). Dos líneas seguidas de un párrafo, en una misma columna, terminan con la misma palabra o los mismos últimos bodyText.stackMinCharacters caracteres (3 por defecto, espacios incluidos), o empiezan igual: «…en la» sobre «…de la». No cuentan las tildes ni las mayúsculas, y solo hay repeticiones en las escrituras que separan las palabras con espacios. Con bodyText.stacks en 'warn' se informa de todas; en 'avoid', de las que el corte de líneas mantuvo porque ninguna composición dentro del espaciado entre palabras las evitaba por menos que bodyText.stackPenalty. El motor anota cada una en doc.contentWarnings con el texto repetido, el extremo (final o comienzo), las dos líneas y su página. Solución: Pon bodyText.stacks en 'avoid': el corte de líneas compone el párrafo de otro modo donde el espaciado entre palabras lo permite. Una repetición que sigue cuesta más de evitar que bodyText.stackPenalty: sube la penalización para cambiarla por líneas más sueltas, o reescribe una de las dos líneas. En un port de un libro existente deja 'warn': el port reproduce los cortes del original. ([Documentación](https://postext.dev/es/docs/configuration-text.md#texto-base))

- Las repeticiones se buscan en las líneas ya cortadas. Si cambias el formato, el cuerpo o el texto, las primeras pruebas encuentran otras, así que lee los avisos de cada composición y no copies posiciones de una anterior.
- Las repeticiones se cuentan dentro de un párrafo y solo en escrituras que separan las palabras con espacios: dos párrafos que empiezan con *Rosa* no hacen repetición, y un texto en chino o en japonés nunca avisa de ninguna.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: Cuento de Navidad (A Christmas Carol, 1843), el comienzo de la primera estrofa, del eBook n.º 46 de Project Gutenberg, con comillas y rayas tipográficas: Charles Dickens ([fuente](https://www.gutenberg.org/ebooks/46)), dominio público
- Texto: ¡Adiós, Cordera!, el comienzo del cuento, de El Señor y lo demás son cuentos (Madrid, 1919), con comillas « »: Leopoldo Alas, Clarín ([fuente](https://es.wikisource.org/wiki/%C2%A1Adi%C3%B3s,_Cordera!)), dominio público
- Imágenes: Pintura: el despacho de Scrooge en una Nochebuena de niebla: Generated With Diffusion Models, original
- Imágenes: Pintura: Rosa, Pinín y la Cordera junto al poste del telégrafo: Generated With Diffusion Models, original
- Tipografías: Spectral (OFL-1.1), Spectral SC (OFL-1.1), Cormorant Garamond (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 104 · Una novela corta en catalán, con la división del IEC](https://postext.dev/es/cookbook/catalan-pocket-novella.md): El transplantat de Oller, completo, en un bolsillo de 32 páginas: sílabas catalanas según el IEC, l·l cortada como il- | lusió y un grabado por capítulo. · Nivel 2 (Intermedio) · Narrativa, teatro y prosa literaria
- [N.º 016 · Español justificado en una novela de bolsillo](https://postext.dev/es/cookbook/spanish-pocket-novel.md): El comienzo de Marianela en edición de bolsillo: separación silábica del español, espacios de menos de 1,7×, capitular alzada y el plano como Figura 1. · Nivel 2 (Intermedio) · Narrativa, teatro y prosa literaria
- [N.º 180 · Resaltados por colores en un libro de lecturas](https://postext.dev/es/cookbook/colour-coded-study-highlights.md): Un libro de lecturas de historia con tres colores de resaltado (verde para términos, ámbar para fechas, azul para nombres) definidos en markStyles. · Nivel 2 (Intermedio) · Libros de texto
