En pocas palabras
Un librito de tres ensayos sobre caminar. El autor y el año de cada ensayo se escriben una vez y luego aparecen donde el libro los necesita, como en el índice.
Lo que vas a componer
Nueve páginas de Afoot, una antología de bolsillo con tres ensayos sobre caminar, de Hazlitt (1822), Thoreau (1862) y Stevenson (1876), en su inglés original. Una pintura de un brezal al atardecer, un JPEG generado con modelos de difusión, ocupa la cubierta. El índice da a cada ensayo un numeral en rojo óxido, el título en Gloock, una línea de puntos espaciados hasta su página y, debajo, el nombre del autor en cursiva morada. Cada ensayo se abre con su numeral y su título, una firma en mayúsculas espaciadas y la revista y el año en que se publicó por primera vez. Las páginas pares llevan en la cabecera el autor; las impares, el título del ensayo. El título de cada ensayo lleva como atributos el autor, el año y la revista, y la apertura, las cabeceras y el índice los toman de ahí, así que para añadir un cuarto ensayo no hay que tocar la configuración.
Esta receta responde a
- ¿Cómo añado un índice que se actualice solo (líneas de puntos, números de página, autores, filas de parte)?
- ¿Cómo añado a una apertura una línea de autor, una entradilla o un primer párrafo con capitular?
- ¿Cómo pongo cabeceras: el título del libro en la página izquierda, el del capítulo en la derecha y el folio por fuera?
La respuesta corta
// Each essay's heading carries its credits, and every {attr.…} below reads them:
// # Walking {author="Henry David Thoreau" year="1862" source="The Atlantic Monthly"}
// (a value cannot hold { or }, and one with " goes in single quotes; gotcha: attr-values)
// 1 · The opener: inside a heading's design, {attr.author} is that heading's attribute.
const byline = [
text('byline', '{attr.author}', { ...label, fontSize: pt(8), letterSpacing: pt(1.6),
color: col('heather') }, below('title', 5)),
text('dateline', '{attr.source}, {attr.year}', { fontFamily: 'Spectral', italic: true,
fontSize: pt(9.5), color: col('muted'), align: 'left' }, below('byline', 1.2)),
];
// 2 · The verso running head (head() is in the running-heads region): in the page header,
// {attr.author} is the attribute of the essay the page belongs to.
const versoAuthor = head('verso-author', '{attr.author}', 'even',
at('page', 'top-left', MARGIN.outer + HEAD.gap, HEAD.y));
// 3 · The contents: toc.subtitle prints the attribute it names as a line under each title.
// 'author' and italic are the defaults; attr is written out so it can become 'source'.
const authorLine = { enabled: true, attr: 'author', fontFamily: 'Spectral', fontSize: pt(10),
color: col('heather') };
// Hooked up below: byline → the opener, versoAuthor → header, authorLine → toc.subtitle.
// A heading without author="…" gets an empty byline and running head and no line in the
// contents, and the build gives no warning: check every heading.
Ingredientes
- Funciones
- Índice generalAtributos de títuloCabeceras y foliosAperturas diseñadasTítulos numeradosEstilos de títuloCapítulos sin númeroCubiertas, portadas y colofonesImágenes en los diseños de páginaAnclaje de elementos de diseñoVerso línea a líneaMárgenes simétricosEstilos de párrafoRecuadros fijos e insigniasRecuadrosEspacio vertical explícitoMetadatos del documentoPaleta de color semánticaFiguras y tablas como recursosPáginas en un canvas
- Tipografía
- Spectral, Gloock, Hanken Grotesk (SIL OFL 1.1)
- Recursos
cover-1200.jpg- La cubierta: un brezal y colinas al atardecer, una pintura (Generated With Diffusion Models, original)
Elaboración
#1 · Numerar los ensayos y bajar su texto
const opener = { enabled: true,
// The hairline ends 7 mm above the foot of this reserve, so the text starts on the same grid
// line under every opener whose title fits on one line (SINK = 14 holds a two-line title).
minHeight: pt(SINK * LEAD),
slot: { elements: [
// {number} prints the essay's number as numberingTemplate '{1:I}' writes it: I, II, III.
text('number', '{number}', { ...gloock, fontSize: pt(34), lineHeight: 1, color: col('rust') },
at('container', 'top-left', 0, 8)),
text('title', '{titleText}', { ...gloock, fontSize: pt(26), lineHeight: 1.08,
color: col('ink') }, below('number', 3, { width: 'fill' })),
...byline,
{ kind: 'rule', id: 'rule', thickness: pt(0.5), color: col('rule'),
placement: below('dateline', 6) }, // a horizontal rule runs to the column's edge
] } };
const essays = { level: 1, numberingTemplate: '{1:I}', advancedDesign: opener,
marginBottom: pt(0), // the heading's default margin would add to minHeight
// The cover and contents styles inherit this break (gotcha: style-inherits-break).
breakBefore: { enabled: true, parity: 'any' } }; // 'any': each piece opens on the next page
El numberingTemplate: '{1:I}' del nivel numera los ensayos I, II y III, y {number} imprime el numeral sobre el título (apertura a toda página y diseño avanzado). minHeight reserva 12 líneas de 14 pt y el filete fino acaba 7 mm por encima de ese límite, así que, con un título de una línea, el texto empieza a 79 mm del borde superior en todas las aperturas. Una segunda línea del encabezado, a 26 pt, añade 9,9 mm y baja el texto una línea de la rejilla; con SINK = 14, el texto empieza a la misma altura bajo títulos de una y de dos líneas. El marginBottom: pt(0) del nivel impide que el margen por defecto del título se sume a esa reserva.
#2 · Un índice que se rellena solo
const ENTRY = 15; // pt: the essay titles in the contents
const contents = { // passed to the config as `toc`
// An entry's numeral takes the title's face and size and stands on its baseline.
levels: [{ level: 1, fontFamily: 'Gloock', fontSize: pt(ENTRY), color: col('ink'),
numberFontWeight: 400, // Gloock has one weight
numberColor: col('rust'), numberWidth: mm(8), numberGap: mm(3), marginBottom: pt(LEAD) }],
pageNumber: { fontFamily: 'Hanken Grotesk', fontSize: pt(8.5), fontWeight: 600,
color: col('muted'), width: mm(6) }, // the leader dots take this face and colour too
leader: { char: '. ', gap: mm(2) }, // spaced dots, right-aligned so they line up
subtitle: authorLine,
};
:::toc en el Markdown imprime una entrada por cada título incluido, con el número, el texto del título, la línea de puntos, la etiqueta de la página y, gracias a subtitle, el autor. buildDocument vuelve a componer el libro hasta que las etiquetas de página dejen de cambiar, así que, si un ensayo cambia de título o de extensión, el índice se actualiza (índice general). El numeral de cada entrada toma la fuente y el cuerpo del título, salvo que numberFontFamily o numberFontSize digan otra cosa, y se apoya en la línea base de la primera línea del encabezado con cualquier cuerpo. Un libro con partes añade además una fila por cada :::part, con el diseño de toc.parts.design, como en Partes en color.
#3 · El autor en la página par, el ensayo en la impar
// Each head: the label face, the pages of its parity, never an opener (pages: 'body'), where
// the byline names the author. A function declaration, so the answer above can call it.
function head(id, content, parity, placement, look = {}) {
return { ...text(id, content, { ...label, fontSize: pt(7.5), letterSpacing: pt(1.3),
color: col('muted'), ...look }, placement), parity, pages: 'body' };
}
const folio = { color: col('ink') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', at('page', 'top-left', MARGIN.outer, HEAD.y), folio),
versoAuthor,
head('recto-title', '{chapterTitle}', 'odd',
at('page', 'top-right', -(MARGIN.outer + HEAD.gap), HEAD.y), { align: 'right' }),
head('recto-folio', '{pageNumber}', 'odd', at('page', 'top-right', -MARGIN.outer, HEAD.y),
{ ...folio, align: 'right' }),
] };
const footer = { elements: [{ ...head('drop-folio', '{pageNumber}', 'all', // an opener's folio
at('container', 'top', 0, 9), { ...folio, align: 'center' }), pages: 'opener' }] };
Cada cabecera se ancla a la página, a 11 mm del borde superior, y parity elige el lado: el folio se alinea con el borde exterior del texto, y el nombre o el título queda 7 mm más adentro. El pages: 'body' de head() deja las cabeceras fuera de las aperturas, donde la firma ya nombra al autor, y el elemento del pie con pages: 'opener' imprime allí el folio, centrado bajo el texto (elementos de texto). {chapterTitle} imprime el título del ensayo sin su numeral.
#4 · La cubierta y el índice no cuentan
// Unnumbered, so the first essay is I; unlisted; and with no running heads or folio. They
// inherit the level's page break, 'any' (gotcha: style-inherits-break).
const bare = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
const cover = { enabled: true, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'cover',
placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } } },
text('title', '{titleText}', { ...gloock, fontSize: pt(80), lineHeight: 1, color: col('ink') },
at('page', 'top-left', MARGIN.inner, 22)), // page 1 is a recto: the inner margin is left
text('subtitle', '{subtitle}', { fontFamily: 'Spectral', italic: true, fontSize: pt(14),
color: col('ink'), align: 'left' }, below('title', 1)),
text('authors', '{attr.authors}', { ...label, fontSize: pt(8.5), letterSpacing: pt(2),
color: col('heather') }, below('subtitle', 5)),
text('imprint', '{attr.imprint}', { ...label, fontSize: pt(7.5), letterSpacing: pt(1.8),
color: col('paper') }, at('page', 'bottom-left', MARGIN.inner, -12)),
] } };
// span: 'page' in a one-column book: a design kept in its column is cut at the column's foot,
// which would leave a band of paper under the dusk.
const coverStyle = { id: 'cover', ...bare, span: 'page', advancedDesign: cover };
const contentsOpener = { enabled: true, slot: { elements: [ // {title}, {subtitle}: frontmatter
text('kicker', '{title} · {subtitle}', { ...label, fontSize: pt(8), letterSpacing: pt(1.6),
color: col('heather') }, at('container', 'top-left', 0, 8)),
text('title', '{titleText}', { ...gloock, fontSize: pt(26), color: col('ink') },
below('kicker', 2.5)),
] } };
Con numbered: false, la cubierta y el índice no hacen avanzar el contador, así que Hazlitt es el I, y toc: false los deja fuera de la lista (estilos de encabezado). Los dos estilos heredan el breakBefore del nivel, con paridad 'any', y por eso el índice sigue a la cubierta en la página 2 sin ningún :::pagebreak. El estilo de la cubierta ocupa toda la página aunque el libro tenga una sola columna, porque un diseño que se queda en la columna se corta al pie de esta y dejaría 22 mm de papel por debajo del paisaje.
#5 · Cada color escrito con su enlace a la paleta
const palette = {
ink: '#241f26', // text: a plum-tinted near-black
paper: '#f7f2e8', // the page
heather: '#6b4468', // the bylines and the authors in the contents
rust: '#a4502a', // the essay numbers
rule: '#d5cabd', // hairlines
muted: '#6d6570', // running heads, datelines, page numbers in the contents
};
// col() links a colour to its palette entry; the hex is the value the entry holds.
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' } })),
// The engine's defaults link to 'main-color': point it at the ink, so nothing prints blue.
{ id: 'main-color', name: 'ink (defaults)', value: { hex: palette.ink, model: 'hex' } },
];
col() escribe el valor hexadecimal de cada color junto a su paletteId, y el motor sigue ese enlace: las firmas, las cabeceras y la cubierta toman lo que colorPalette guarde bajo ese identificador, así que otra paleta con los mismos identificadores cambia el color de todo el libro. Con main-color en el color de la tinta, los valores por defecto que la configuración no redefine salen en ese color y no en el azul del motor, #295AA3.
La receta completa
// ═══ Postext Cookbook · Nº 030 · Anthology with bylines ═══════════════════════════════
// https://postext.dev/en/cookbook/anthology-with-bylines
// Code: MIT · Text: Hazlitt, Thoreau, Stevenson (public domain) · Cover: diffusion models
// Fonts: Spectral, Gloock, Hanken Grotesk (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'anthology-with-bylines';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: heather for the credits, rust for the numbers, plum ink on warm paper
const palette = {
ink: '#241f26', // text: a plum-tinted near-black
paper: '#f7f2e8', // the page
heather: '#6b4468', // the bylines and the authors in the contents
rust: '#a4502a', // the essay numbers
rule: '#d5cabd', // hairlines
muted: '#6d6570', // running heads, datelines, page numbers in the contents
};
// col() links a colour to its palette entry; the hex is the value the entry holds.
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' } })),
// The engine's defaults link to 'main-color': point it at the ink, so nothing prints blue.
{ id: 'main-color', name: 'ink (defaults)', value: { hex: palette.ink, model: 'hex' } },
];
// #endregion
const TRIM = { width: 135, height: 180 }; // a pocket book, 3 : 4
const MARGIN = { top: 20, bottom: 22, inner: 19, outer: 15 }; // mirrored
const LEAD = 14; // body leading in pt: the baseline grid
const SINK = 12; // grid lines an essay opener reserves above its first line of text
const HEAD = { y: 11, gap: 7 }; // running heads: mm from the top edge, folio to words
const label = { fontFamily: 'Hanken Grotesk', fontWeight: 600, textTransform: 'uppercase',
align: 'left' }; // design text is centred by default
// One weight, no italic; 'wrap' breaks a long title onto a second line.
const gloock = { fontFamily: 'Gloock', overflow: 'wrap', align: 'left' };
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const below = (id, y, size) => ({ ...at(`#${id}`, 'below', 0, y), ...(size && { size }) });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, ...look, placement });
// #region answer: one set of heading attributes, read in three places
// Each essay's heading carries its credits, and every {attr.…} below reads them:
// # Walking {author="Henry David Thoreau" year="1862" source="The Atlantic Monthly"}
// (a value cannot hold { or }, and one with " goes in single quotes; gotcha: attr-values)
// 1 · The opener: inside a heading's design, {attr.author} is that heading's attribute.
const byline = [
El script.js compuesto funciona tal cual: pégalo como script de módulo en cualquier página o abre la receta en CodePen. Carpeta de la receta en GitHub ↗ (se abre en una nueva pestaña)
Variantes
#Indicar dónde se publicó cada ensayo
toc.subtitle imprime cualquier atributo del encabezado, así que el mismo Markdown puede poner bajo cada título la revista en la que se publicó por primera vez.
-const authorLine = { enabled: true, attr: 'author', fontFamily: 'Spectral', fontSize: pt(10),
+const authorLine = { enabled: true, attr: 'source', fontFamily: 'Spectral', fontSize: pt(10),#Poner el título del libro en la página par
Muchos libros ponen su propio título en las páginas pares y el del capítulo en las impares; {title} lo toma del frontmatter del Markdown e imprime AFOOT.
-const versoAuthor = head('verso-author', '{attr.author}', 'even',
+const versoAuthor = head('verso-author', '{title}', 'even',#Abrir cada ensayo en página impar
Con la paridad 'odd', Stevenson pasa a la página 9, tras una página 8 en blanco. Los dos estilos de los preliminares necesitan entonces su propio 'any'; si no, el índice hereda 'odd' y se abre en la página 3, tras una página par en blanco.
- breakBefore: { enabled: true, parity: 'any' } }; // 'any': each piece opens on the next page
+ breakBefore: { enabled: true, parity: 'odd' } };
-const bare = { numbered: false, toc: false, header: { elements: [] }, footer: { elements: [] } };
+const bare = { numbered: false, toc: false, breakBefore: { enabled: true, parity: 'any' },
+ header: { elements: [] }, footer: { elements: [] } };Errores frecuentes
Error frecuente
Valores de atributo: sin { ni }; comillas simples si llevan "
Un valor de atributo termina en la llave de cierre, así que no puede contener { ni }. Un valor que lleve comillas dobles va entre comillas simples; el signo de dólar no da problemas. Atributos de título →
Error frecuente
Un estilo de título hereda el salto de página de su nivel
Una entrada de headingStyles toma de su nivel de título todo lo que no fija, también breakBefore. Un índice o un colofón con estilo sobre un H1 tras un :::pagebreak hereda la paridad 'odd' y cae detrás de una página en blanco. Dale a ese estilo breakBefore: { enabled: false }. Estilos de título →
- Hazlitt cita versos en mitad de sus frases. Los versos van en un bloque
:::verse{style="verse" align=start}, una línea de Markdown por verso, entrados 8 mm, y la frase que continúa después va en un estilorunon, sin sangría. Una cita en bloque de Markdown no sirve aquí: sus líneas se unen como las de un párrafo y los versos saldrían seguidos, como prosa. - Un atributo que falta en un título no imprime nada ni da aviso. Sin
author="…", la firma y la cabecera par de ese ensayo salen vacías y su línea bajo el título desaparece del índice.
Créditos
- Receta
- Ignacio Ferro
- Texto
- «On Going a Journey» (1822), desde la primera línea hasta «I sing for joy», en Table Talk: Essays on Men and Manners · William Hazlitt · dominio público
- «Walking» (1862), sus cinco primeros párrafos · Henry David Thoreau · dominio público
- «Walking Tours» (1876), el comienzo de su primer párrafo y el segundo entero, en Virginibus Puerisque · Robert Louis Stevenson · dominio público
- La nota sobre los textos y el colofón · Ignacio Ferro · CC BY 4.0
- Imágenes
- La cubierta: un brezal y colinas al atardecer, una pintura · Generated With Diffusion Models · original
- Fuentes
- Spectral (SIL OFL 1.1) · Gloock (SIL OFL 1.1) · Hanken Grotesk (SIL OFL 1.1)
- Código
- MIT, como Postext
Editar este texto ↗ (se abre en una nueva pestaña)Carpeta de la receta en GitHub ↗ (se abre en una nueva pestaña)


