Em poucas palavras
Um livrinho de três ensaios sobre caminhar. O autor e o ano de cada ensaio são digitados uma vez e depois aparecem onde o livro precisa deles, como no sumário.
O que você vai compor
Nove páginas de Afoot, uma antologia de bolso com três ensaios sobre caminhar, de Hazlitt (1822), Thoreau (1862) e Stevenson (1876). Uma pintura de uma charneca ao entardecer ocupa a capa, um JPEG gerado com modelos de difusão. O sumário dá a cada ensaio um numeral vermelho-ferrugem, um título em Gloock, uma linha de pontos espaçados até a página e, embaixo, o nome do autor em itálico cor de urze. Cada ensaio abre com o numeral e o título, uma assinatura em maiúsculas espaçadas e uma linha com a revista e o ano da primeira publicação. As páginas pares levam o nome do autor, as ímpares o título do ensaio. O título de cada ensaio carrega o autor, o ano e a procedência como atributos, e a abertura, os cabeços e o sumário os imprimem a partir dali, de modo que um quarto ensaio não exige nenhuma mudança na configuração.
Esta receita responde a
- Como acrescento um sumário que se atualiza sozinho (pontilhados, números de página, autores, linhas de parte)?
- Como acrescento a uma abertura uma linha de autor, uma linha fina ou um primeiro parágrafo com capitular?
- Como configuro os cabeços: título do livro na página esquerda, título do capítulo na direita e fólio do lado de fora?
A resposta curta
// 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
- Funcionalidades
- SumárioAtributos de títuloCabeços e fóliosAberturas desenhadasTítulos numeradosEstilos de títuloCapítulos sem númeroCapas, folhas de rosto e colofõesImagens nos designs de páginaAncoragem de elementos de designVerso linha a linhaMargens espelhadasEstilos de parágrafoBoxes fixos e selosBoxesEspaço vertical explícitoMetadados do documentoPaleta de cores semânticaFiguras e tabelas como recursosPáginas em um canvas
- Tipografia
- Spectral, Gloock, Hanken Grotesk (SIL OFL 1.1)
- Materiais
cover-1200.jpg- The cover: a heath and hills at dusk, a painting (Generated With Diffusion Models, original)
Preparo
#1 · Numere os ensaios e rebaixe o 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
O numberingTemplate: '{1:I}' do nível numera os ensaios I, II e III, e {number} imprime o numeral acima do título (span e design avançado). minHeight reserva 12 linhas de 14 pt e o fio fino termina 7 mm acima disso, por isso, sob um título de uma linha, o texto começa a 79 mm da borda superior em todas as aberturas. Uma segunda linha de título em 26 pt acrescenta 9,9 mm e empurra o texto uma linha da grade para baixo; com SINK = 14, títulos de uma e de duas linhas começam o texto na mesma linha. marginBottom: pt(0) impede que a margem padrão do título se some à reserva.
#2 · Deixe o sumário se preencher sozinho
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 no Markdown imprime uma entrada por título listado: número, título, linha de pontos, rótulo da página e, por meio de subtitle, o autor. buildDocument diagrama o livro de novo até os rótulos de página pararem de mudar, por isso um ensaio renomeado ou mais longo atualiza o sumário (sumário). O numeral de uma entrada usa a fonte e o corpo do título, a menos que numberFontFamily ou numberFontSize digam outra coisa, e fica apoiado na linha de base da primeira linha do título em qualquer corpo. Um livro com partes também ganha uma linha para cada :::part, desenhada por toc.parts.design, como em Partes em cores.
#3 · Autor na página par, ensaio na ímpar
// 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 cabeço é ancorado à página, a 11 mm da borda superior, e parity escolhe o lado: o fólio se alinha com a borda externa do texto e o nome ou o título fica 7 mm mais para dentro. O pages: 'body' em head() mantém os cabeços fora das aberturas, onde a assinatura já nomeia o autor, e o pages: 'opener' do rodapé imprime ali um fólio no pé (elementos de texto). {chapterTitle} imprime o título do ensaio sem o numeral.
#4 · Deixe a capa e o sumário fora da contagem
// 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)),
] } };
Com numbered: false, a capa e o sumário não avançam o contador, por isso Hazlitt é o I, e toc: false os mantém fora da lista (estilos de título). Os dois estilos herdam o breakBefore do nível, com paridade 'any', e é por isso que o sumário vem logo depois da capa, na página 2, sem um :::pagebreak. O estilo da capa ocupa a página inteira num livro de uma coluna porque um design mantido na coluna é cortado no pé da coluna, o que deixaria 22 mm de papel abaixo da paisagem.
#5 · Escreva cada cor por extenso com o seu vínculo à 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() escreve o hex de cada cor ao lado do paletteId, e o motor segue esse vínculo: as assinaturas, os cabeços e a capa usam o que colorPalette guarda sob esse id, de modo que outra paleta com os mesmos ids muda a cor do livro inteiro. Apontar main-color para a cor da tinta cobre todos os valores padrão que a configuração não redefine, que de outro modo sairiam no azul do motor, #295AA3.
A receita 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 = [
O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)
Variações
#Indique onde cada ensaio saiu primeiro
toc.subtitle imprime qualquer atributo do título, por isso o mesmo Markdown pode listar, sob cada título, a revista em que o ensaio saiu pela primeira vez.
-const authorLine = { enabled: true, attr: 'author', fontFamily: 'Spectral', fontSize: pt(10),
+const authorLine = { enabled: true, attr: 'source', fontFamily: 'Spectral', fontSize: pt(10),#Ponha o título do livro na página par
Muitos livros põem o próprio título na página par e o do capítulo na ímpar; {title} o lê do front matter do Markdown e imprime AFOOT.
-const versoAuthor = head('verso-author', '{attr.author}', 'even',
+const versoAuthor = head('verso-author', '{title}', 'even',#Abra cada ensaio numa página ímpar
Com a paridade 'odd', Stevenson passa para a página 9, depois de uma página 8 em branco. Os dois estilos dos elementos pré-textuais precisam então de um 'any' próprio; senão, o sumário herda 'odd' e abre na página 3, depois de uma página par em branco.
- 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: [] } };Erros comuns
Erro comum
Valores de atributo: sem { ou }; aspas simples se tiver "
Um valor de atributo termina na chave de fechamento, por isso não pode conter { nem }. Um valor que contém aspas duplas vai entre aspas simples; o cifrão não causa problema. Atributos de título →
Erro comum
Um estilo de título herda a quebra de página do seu nível
Uma entrada de headingStyles recebe do seu nível de título todos os campos que não define, inclusive breakBefore. Um sumário ou um colofão com estilo sobre um H1 depois de um :::pagebreak herda a paridade 'odd' e cai depois de uma página em branco. Dê a esse estilo breakBefore: { enabled: false }. Estilos de título →
- Hazlitt cita versos no meio das frases. Os versos vão num bloco
:::verse{style="verse" align=start}, uma linha de Markdown por verso, recuados 8 mm, e a frase que continua depois dele vai num estilorunon, sem recuo. Uma citação em bloco do Markdown não serve aqui: as linhas dela são unidas como as de um parágrafo, e os versos sairiam corridos, como prosa. - Um atributo que falta num título não imprime nada e não gera aviso. Sem
author="…", a assinatura e o cabeço par de um ensaio saem vazios, e a linha dele sob o título some do sumário.
Créditos
- Receita
- Ignacio Ferro
- Texto
- “On Going a Journey” (1822), from its first line to “I sing for joy”, in Table Talk: Essays on Men and Manners · William Hazlitt · domínio público
- “Walking” (1862), its first five paragraphs · Henry David Thoreau · domínio público
- “Walking Tours” (1876), the opening of its first paragraph and the whole of its second, in Virginibus Puerisque · Robert Louis Stevenson · domínio público
- The note on the texts and the colophon · Ignacio Ferro · CC BY 4.0
- Imagens
- The cover: a heath and hills at dusk, a painting · Generated With Diffusion Models · original
- Fontes
- Spectral (SIL OFL 1.1) · Gloock (SIL OFL 1.1) · Hanken Grotesk (SIL OFL 1.1)
- Código
- MIT, como o Postext
Editar este texto ↗ (abre em uma nova aba)Pasta da receita no GitHub ↗ (abre em uma nova aba)


