Pular para o conteúdo principal
Receita número 19

Receitas · Capítulo 5 · Estrutura do livro

Partes em cores com um único atributo

Num guia de campo de bolso, cada :::part redefine uma cor da paleta, que tinge a página divisória, o verso pintado, a aba lateral e a linha do sumário.

p. 2–3 de 10

  • Amostra em inglês: ainda sem edição em português
  • Refile 150 × 200 mm
  • 1 coluna
  • Alegreya 10,5/14,5
  • Barlow Condensed
  • Zilla Slab
  • 10 páginas
  • Nível
  • Postext 1.57.1
  • Diagramado em 70 ms
  • 245 linhas de código

Em poucas palavras

Um guia de bolso de aves do estuário em duas partes, uma marrom e outra verde. Mostra como uma única cor por parte tinge a página de abertura, as abas, os números de página e a linha do sumário.

O que você vai compor

Birds of the Estuary é um guia de campo de bolso em duas partes, uma para cada hábitat. Os lodaçais saem em marrom de lama e os juncais em verde-junco, e cada cor é escrita uma vez só, no :::part que abre o hábitat. Cada página divisória é um campo de cor com sangria, com um numeral romano de 150 pt e a lista das espécies do hábitat em creme. O verso da folha é pintado na mesma cor, com a aba da parte em negativo no corte. Nas páginas de espécies, a aba lateral, o fólio, o antetítulo, o fio sob o nome científico, as marcas de campo em negrito, os marcadores e o rótulo da prancha assumem a cor da parte. O sumário abre sob uma faixa com uma vista do estuário e dá a cada parte uma tarja na cor, com o número da página divisória. A capa, a faixa e as quatro pranchas são pinturas geradas com modelos de difusão, carregadas como bitmaps JPEG; a paleta de uma parte não alcança as imagens, por isso as cores delas são as delas mesmas.

Esta receita responde a

  • Como divido um livro em partes ou seções, cada uma com sua cor e sua página divisória?
  • Como oculto os cabeços nas aberturas e nas páginas em branco, ou pinto uma página par em branco com a cor da parte?
  • Como acrescento um sumário que se atualiza sozinho (pontilhados, números de página, autores, linhas de parte)?
  • Como dou cor aos termos-chave (em negrito ou itálico) no texto ou dentro dos boxes?

A resposta curta

script.js · linhas 53–86no código completo
// In the Markdown:  :::part{number="I" title="The \\ Mudflats" palette="band=#8c5e24"}
// Every colour below that is linked to 'band' takes #8c5e24 until the next part.
const parts = { // passed to the config as `parts`
  // A divider opens on a recto by default. The break after it goes to the next recto too, so
  // the back of the leaf stays blank and versoDesign paints it (gotcha: verso-design-breakafter).
  breakAfter: { parity: 'odd' },
  margins: { top: mm(125) }, // the fence's text starts low, under the title
  design: { elements: [ // the divider: its container is the whole trim
    box('field', col('band'), { ...at('top-left', 0, 0, 'bleed'), ...fill }),
    text('part', t({ en: 'Part', es: 'Parte' }), { ...label, fontSize: pt(10),
      letterSpacing: pt(2.4), color: col('paper') },
    at('top-left', MARGIN.inner, MARGIN.top)), // a recto: the inner margin is on the left
    // Roman for the parts, Arabic for the species. {numberRoman} re-formats number="I" (or
    // "1"); the species design prints {number}, from numberingTemplate '{1}'.
    text('numeral', '{numberRoman}', { ...display, fontSize: pt(150), lineHeight: 0.9,
      color: col('paper') }, below('part', 0)),
    // The \\ in the title breaks the line here; the contents and the heads get one line.
    text('title', '{titleText}', { ...display, fontSize: pt(46), lineHeight: 0.98,
      color: col('paper') }, below('numeral', 2, { width: mm(MEASURE) })),
    rule('rule', col('paper'), 1, below('title', 7, { width: mm(14) })),
  ] },
  // The back of the leaf: the same band, edge to edge, the part's tab in reverse at the
  // fore-edge (a verso's is on the left) and its name at the foot.
  versoDesign: { elements: [
    box('field', col('band'), { ...at('top-left', 0, 0, 'bleed'), ...fill }),
    text('tab', '{partNumber}', { ...label, fontSize: pt(9), color: col('band'), align: 'center',
      box: { backgroundColor: col('paper') } }, { ...at('top-left', 0, TAB.y), size: TAB.size }),
    text('name', '{partTitle}', { ...label, fontSize: pt(9), letterSpacing: pt(2.4),
      color: col('paper') }, at('bottom-left', MARGIN.outer, -MARGIN.bottom)),
  ] },
  // The fence's list of species, in the paper colour on the band.
  bodyStyle: { fontSize: pt(11), color: col('paper'), textAlign: 'left', numberColor: col('paper'),
    orderedLists: { fontFamily: 'Barlow Condensed', separator: '', gap: mm(4) } },
};

Ingredientes

Tipografia
Alegreya, Zilla Slab, Barlow Condensed (SIL OFL 1.1)
Materiais
  • cover-1152.jpg
  • curlew-1200.jpg
  • redshank-1200.jpg
  • reedling-1200.jpg
  • strip-1536.jpg
  • warbler-1200.jpg
  • The cover: a curlew on the estuary mud, reeds in front (Generated With Diffusion Models, original)
  • The contents strip: a curlew and a redshank on the mud, the reedbed beyond (Generated With Diffusion Models, original)
  • Plate 1: Eurasian curlew (Generated With Diffusion Models, original)
  • Plate 2: common redshank (Generated With Diffusion Models, original)
  • Plate 3: bearded reedling (Generated With Diffusion Models, original)
  • Plate 4: common reed warbler (Generated With Diffusion Models, original)

Preparo

#1 · Uma entrada da paleta para as partes redefinirem

script.js · linhas 16–29no código completo
const palette = {
  ink: '#1f2624', // text: a green-tinted near-black
  band: '#3c4b4f', // the house slate, before any part; each :::part brings its own
  paper: '#f6f3ea', // the page, and the type set on a band
  rule: '#d5d1c4', // hairlines
  muted: '#61675f', // running heads, Latin names, the colophon
};
// The paletteId is the link a part's palette="band=#…" follows, in text and designs alike.
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' } },
];

Uma parte redefine entradas da paleta pelo id, de modo que tudo o que deve mudar com o hábitat fica vinculado a uma só entrada, band. O valor próprio dela, um cinza-ardósia, só aparece fora das partes (no antetítulo da capa e no título da nota sob o sumário), e nenhuma outra cor da configuração tem o mesmo hex. col() dá a cada cor o paletteId, e é esse id que a redefinição de uma parte segue, tanto nos estilos de texto quanto nos elementos de design.

#2 · Uma página divisória, o verso e a lista

O código deste passo é a resposta curta logo acima. Um :::part abre uma página divisória numa página ímpar, e parts.design a diagrama sobre todo o refile. O Markdown entre as marcas do bloco começa a 125 mm da borda superior, abaixo do título: algumas linhas sobre o hábitat no estilo de parágrafo habitat e, depois, a lista das espécies em bodyStyle. versoDesign pinta o verso da folha (o campo e a aba em negativo) só quando essa página fica em branco, e breakAfter: { parity: 'odd' } a mantém em branco ao mandar a primeira espécie para a próxima página ímpar. {numberRoman} imprime o number="I" da parte em algarismo romano ("1" daria o mesmo I), enquanto as espécies são numeradas de 1 a 4 em algarismos arábicos. O \\ do título quebra a linha só na página divisória; o sumário e os cabeços compõem o título numa linha só.

#3 · Os destaques do texto acompanham a parte

script.js · linhas 90–108no código completo
const bodyText = {
  fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('band'), // the field marks: **Bill**, **Voice.**
  italicColor: col('ink'), referenceColor: col('ink'),
  firstLineIndent: mm(4), indentAfterHeading: false,
  // Tighter than the 0.6–2 defaults. runtMinCharacters counts word spaces, not letters:
  // 45 are about 20 letters of Alegreya (the default 20, about 9); a shorter last line is a runt.
  minWordSpacing: 0.75, maxWordSpacing: 1.7, runtMinCharacters: 45,
};
const unorderedLists = { bulletChar: '•', color: col('band'), // the field marks' bullets
  marginTop: pt(0), marginBottom: pt(0) };
// The plates are numbered with the species, and their label is in the part's colour.
const resourceTypes = [{ id: 'plate', numberingTemplate: '{n}', resetOn: 'never',
  counterFormat: 'decimal', ...t({
    en: { name: 'Plate', namePlural: 'Plates', shortLabel: 'Pl.', captionPrefix: 'Plate' },
    es: { name: 'Lámina', namePlural: 'Láminas', shortLabel: 'Lám.', captionPrefix: 'Lámina' },
  }) }];
const captionStyle = { fontSize: pt(8.5), labelColor: col('band'), descriptionItalic: true,
  gap: mm(1.8) };

De um :::part até o seguinte, toda cor de texto igual ao valor próprio de band assume o valor da parte (o contêiner :::part). Aqui são as marcas de campo em negrito, os marcadores e os rótulos das pranchas. O texto corrido e os itálicos ficam na cor da tinta. As pranchas são um tipo de recurso próprio, com o rótulo Plate e uma numeração que nunca reinicia, por isso contam de 1 a 4 junto com as espécies.

#4 · A abertura de cada espécie

script.js · linhas 112–123no código completo
const species = { enabled: true, slot: { elements: [
  text('kicker', '{number} · {attr.status}', { ...label, fontSize: pt(8.5),
    letterSpacing: pt(1.7), color: col('band') }, at('top-left', 0, 1, 'container')),
  // 'cm' is a unit symbol: it keeps its lower case, so the size is not set in capitals.
  text('size', '{attr.size}', { ...label, textTransform: 'none', fontSize: pt(8.5),
    letterSpacing: pt(0.5), color: col('muted') }, at('top-right', 0, 1, 'container')),
  text('name', '{titleText}', { ...display, fontSize: pt(22), lineHeight: 1.05,
    color: col('ink') }, below('kicker', 1.5, { width: 'fill' })),
  text('latin', '{attr.latin}', { fontFamily: 'Alegreya', italic: true, fontSize: pt(11.5),
    color: col('ink') }, below('name', 0.8)),
  rule('rule', col('band'), 0.75, below('latin', 2, { width: mm(MEASURE) })),
] } };

A abertura de cada espécie imprime três atributos do título: status no antetítulo, depois do número, size à direita do antetítulo e latin sob o nome. O antetítulo e o fio sob o nome científico ficam vinculados a band, por isso um só design serve aos dois hábitats. O título não define quebra de página própria: cada espécie começa depois de um :::pagebreak, ou depois da quebra que vem após a parte, e assim sua página conta como página de texto e leva os cabeços. O tamanho sai sem as maiúsculas do rótulo, porque cm é um símbolo de unidade.

#5 · Uma tarja por parte no sumário

script.js · linhas 127–145no código completo
const contents = {
  levels: [{ level: 1, fontFamily: 'Zilla Slab', fontSize: pt(12), fontWeight: 600,
    numberFontFamily: 'Barlow Condensed', numberFontWeight: 600, numberColor: col('muted'),
    numberWidth: mm(5), numberGap: mm(3), marginTop: pt(4) }],
  pageNumber: { fontFamily: 'Barlow Condensed', fontSize: pt(10), fontWeight: 600, width: mm(7) },
  leader: { char: '. ' },
  subtitle: { enabled: true, attr: 'latin', fontFamily: 'Alegreya', fontSize: pt(9.5),
    color: col('muted') }, // the Latin name, in italic by default
  // A part row lays out this design with the part's number, title, page and palette.
  parts: { height: mm(8.5), marginTop: pt(LEAD), design: { elements: [
    box('row', col('band'), { ...at('top-left', 0, 0, 'container'), ...fill }),
    text('part', t({ en: 'Part {number}', es: 'Parte {number}' }), { ...label, fontSize: pt(8),
      letterSpacing: pt(1.6), color: col('paper') }, at('left', 3, 0, 'container')),
    text('title', '{titleText}', { ...display, fontSize: pt(12), color: col('paper') },
      at('left', 20, 0, 'container')),
    text('page', '{pageNumber}', { ...label, fontSize: pt(10), color: col('paper'),
      align: 'right' }, at('right', -2.5, 0, 'container')),
  ] } },
};

:::toc dá uma linha a cada :::part e diagrama nela toc.parts.design com o número, o título, a página divisória e a paleta dessa parte (sumário), de modo que a mesma caixa sai marrom para os lodaçais e verde para os juncais. Cada espécie sob a tarja mostra o número, uma linha pontilhada e a página, com o nome científico do atributo latin na linha de baixo.

#6 · A parte nos cabeços e na aba

script.js · linhas 149–162no código completo
const head = (id, content, parity, placement, style = {}) => ({ ...text(id, content, { ...label,
  fontSize: pt(8), letterSpacing: pt(1.4), color: col('muted'), overflow: 'clip', ...style },
placement), parity, pages: 'body' }); // dividers are 'part' pages, their versos 'blank'
const folio = { fontSize: pt(9), fontWeight: 700, color: col('band') };
const tab = (parity, edge) => head(`tab-${parity}`, '{partNumber}', parity,
  { ...at(edge, 0, TAB.y), size: TAB.size },
  { fontSize: pt(9), color: col('paper'), align: 'center', box: { backgroundColor: col('band') } });
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', at('top-left', MARGIN.outer, HEAD.y), folio),
  head('verso-title', '{title}', 'even', at('top-left', MARGIN.outer + HEAD.gap, HEAD.y)),
  head('recto-title', '{partTitle}', 'odd', at('top-right', -(MARGIN.outer + HEAD.gap), HEAD.y)),
  head('recto-folio', '{pageNumber}', 'odd', at('top-right', -MARGIN.outer, HEAD.y), folio),
  tab('even', 'top-left'), tab('odd', 'top-right'), // on the fore-edge, left on a verso
] };

Com pages: 'body', os cabeços saem só nas páginas de texto. As páginas divisórias são páginas part e os versos pintados, páginas blank; a capa e o sumário abrem com um título na largura da página, o que faz deles páginas de abertura. O cabeço da página par imprime {title}, o título do front matter, e assim o nome do livro fica no Markdown. O da página ímpar imprime {partTitle} numa linha só, e a aba no corte imprime {partNumber} sobre uma caixa cujo fundo fica vinculado a band.

A receita completa

Sandbox
// ═══ Postext Cookbook · Nº 019 · Parts in colour from one attribute ═══════════════════════
// https://postext.dev/en/cookbook/parts-in-colour
// Code: MIT · Text: original (CC BY 4.0) · Pictures: diffusion models
// Fonts: Alegreya, Zilla Slab, Barlow Condensed (SIL OFL 1.1) · Needs postext ≥ 1.57.0
// A pocket field guide to two habitats. Each :::part names its own 'band' colour, and every
// colour linked to 'band' takes it: the divider and its verso, the tab, the field marks.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'parts-in-colour';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: 'band' is the entry the parts override; the others keep their value
const palette = {
  ink: '#1f2624', // text: a green-tinted near-black
  band: '#3c4b4f', // the house slate, before any part; each :::part brings its own
  paper: '#f6f3ea', // the page, and the type set on a band
  rule: '#d5d1c4', // hairlines
  muted: '#61675f', // running heads, Latin names, the colophon
};
// The paletteId is the link a part's palette="band=#…" follows, in text and designs alike.
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: 150, height: 200 }; // a pocket guide
const MARGIN = { top: 22, bottom: 20, inner: 19, outer: 21 }; // mirrored; room for a thumb
const MEASURE = TRIM.width - MARGIN.inner - MARGIN.outer; // 110 mm, about 70 characters
const LEAD = 14.5; // body leading in pt: the baseline grid
const STRIP = 44; // the contents' picture strip, from the top edge (mm)
const HEAD = { y: 12, gap: 8 }; // running heads from the top edge; folio to title (mm)
const TAB = { y: 26, size: { width: mm(8), height: mm(24) } }; // the thumb tab, at the fore-edge
const TITLE_DROP = 6; // mm from the foot of the contents strip to the title's box
const BOOK = t({ en: 'Birds of the Estuary', es: 'Aves del estuario' });
const label = { fontFamily: 'Barlow Condensed', fontWeight: 600, textTransform: 'uppercase' };
const display = { fontFamily: 'Zilla Slab', fontWeight: 700 };
const at = (edge, x, y, to = 'page') => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const below = (id, y, size) => ({ ...at('below', 0, y, `#${id}`), ...(size && { size }) });
const fill = { size: { width: 'fill', height: 'fill' } };
const text = (id, content, style, placement) => ({ kind: 'text', id, content, overflow: 'wrap',
  align: 'left', ...style, placement });
const box = (id, color, placement) => ({ kind: 'box', id, style: { backgroundColor: color },
  placement });

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

#Acrescente um terceiro hábitat

Um bloco antes da primeira espécie do sapal acrescenta uma terceira cor, com sua página divisória, seu verso pintado e sua linha no sumário, e a configuração fica como está. Tire também a nota sob o sumário, porque a terceira tarja e suas espécies precisam do espaço.

+:::part{number="III" title="The \\ Saltmarsh" palette="band=#6b4a7a"}
+:::
+
+# Common Shelduck {latin="Tadorna tadorna" size="58–67 cm" status="Resident"}

#Deixe a espécie de frente para a página divisória

Sem a quebra para a próxima página ímpar, a primeira espécie começa no verso da página divisória, e não sobra nenhum verso em branco para versoDesign pintar.

-  breakAfter: { parity: 'odd' },

Erros comuns

Erro comum

parts.versoDesign precisa de parts.breakAfter com paridade 'odd'

O verso de uma página divisória de parte só é pintado quando parts.breakAfter { enabled: true, parity: 'odd' } deixa esse verso em branco. Páginas de abertura de parte →

Erro comum

A página 1 é ímpar: planeje com os números físicos

A página 1 fica à direita e a 2 é a primeira página par, então planeje as páginas duplas com os números físicos de página: uma abertura em página par fica de frente para a ímpar que vem depois dela. Quebras de página e de coluna →

  • Uma parte recolore o texto comparando valores: qualquer cor de texto igual ao valor próprio de band muda com a parte, mesmo que esteja vinculada a outra entrada ou a nenhuma. Reserve esse hex só para band.
  • A aba imprime {partNumber}, que fica vazio fora de uma parte, por isso uma página de texto antes do primeiro :::part recebe uma aba cinza-ardósia vazia. Mantenha todas as páginas de texto dentro de alguma parte.
  • As imagens e as amostras de cor no texto mantêm as cores escritas nelas. As pranchas daqui tiram as cores do hábitat de HABITAT, no código, por isso uma cor nova num :::part precisa ser posta lá também.

Créditos

Texto
Texto original, CC BY 4.0
Imagens
  • The cover: a curlew on the estuary mud, reeds in front · Generated With Diffusion Models · original
  • The contents strip: a curlew and a redshank on the mud, the reedbed beyond · Generated With Diffusion Models · original
  • Plate 1: Eurasian curlew · Generated With Diffusion Models · original
  • Plate 2: common redshank · Generated With Diffusion Models · original
  • Plate 3: bearded reedling · Generated With Diffusion Models · original
  • Plate 4: common reed warbler · Generated With Diffusion Models · original
Fontes
Alegreya (SIL OFL 1.1) · Zilla Slab (SIL OFL 1.1) · Barlow Condensed (SIL OFL 1.1)
Sandbox