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

Receitas · Capítulo 9 · Publicações completas

Capa de revista e sumário por seções

Uma capa com foto cujas chamadas pendem do nome da revista e um sumário gerado com uma faixa de cor por seção. Cada seção é uma parte sem página própria.

  • Amostra em inglês: ainda sem edição em português
  • Refile 230 × 300 mm
  • 2 colunas, medianiz de 6 mm
  • Spectral 9,5/13,5
  • Bodoni Moda
  • Jost
  • 6 páginas
  • Nível
  • Postext 1.57.1
  • Diagramado em 194 ms
  • 249 linhas de código

Em poucas palavras

A capa e as primeiras páginas de uma revista de comida e campo, com foto na capa e um sumário. Mostra como dar a cada seção uma cor própria, que se mantém em todas as páginas.

O que você vai compor

Seis páginas de 230 × 300 mm de uma edição de FALLOW, revista trimestral imaginária de comida e terra. Na capa, um vale toscano sangrado sob o nome da revista em Bodoni de 118 pt, e três chamadas sobre um painel de papel, cada chapéu na cor da seção, com o preço e o código de barras no canto. A página 2 traz o sumário gerado: uma aba colorida por seção e, sob ela, o título, a página e o olho de cada matéria. A coluna da direita leva a carta da editora, os colaboradores e o expediente. Vêm depois três seções, em terracota, oliva e vinho. Cada matéria abre com uma imagem sangrada no alto da página e um painel na cor da seção subindo sobre ela, e as abas de fólio, os marcadores e os boxes usam essa cor. Quem define a cor é a linha :::part acima de cada matéria, que não abre página divisória.

Esta receita responde a

  • Como faço uma capa, uma falsa folha de rosto, uma folha de rosto e um colofão?
  • Como acrescento um sumário que se atualiza sozinho (pontilhados, números de página, autores, linhas de parte)?
  • Como divido um livro em partes ou seções, cada uma com sua cor e sua página divisória?
  • Como dou a cada capítulo sua própria foto, cor ou variante de abertura?

A resposta curta

script.js · linhas 39–74no código completo
const MASTHEAD = TRIM.width - MARGIN.inner - MARGIN.outer; // the word spans the text block
const PANEL = 84; // mm: the cover lines' panel, a column of paper over the photograph
const SEAM = 0.3; // mm: each box overlaps the one above, so no hairline of photo shows
// A cover line: a kicker in its section's colour over a line in Bodoni, on paper boxes of one
// width. Chained with 'below' they read as one panel, and a longer line pushes the rest down.
const sheet = (top, bottom) => ({ backgroundColor: col('paper'),
  padding: { top: mm(top), right: mm(5), bottom: mm(bottom), left: mm(5) } });
const small = { ...label, fontSize: pt(8), letterSpacing: pt(1.6), color: col('ink') };
const coverLine = (n, colour, above = n === 1 ? '#masthead' : `#line${n - 1}`) => [
  text(`kicker${n}`, `{attr.kicker${n}}`, { ...small, color: col(colour),
    box: sheet(n === 1 ? 5 : 4, 1.5) },
  { ...at(above, 'below', 0, n === 1 ? 8 : -SEAM), size: { width: mm(PANEL) } }),
  text(`line${n}`, `{attr.line${n}}`, { ...bodoni, italic: true, fontSize: pt(15),
    lineHeight: 1.12, color: col('ink'), box: sheet(0, n === 3 ? 5 : 0) }, // line 3 ends the panel
  { ...at(`#kicker${n}`, 'below', 0, -SEAM), size: { width: mm(PANEL) } }),
];
const cover = { enabled: true, slot: { elements: [
  { kind: 'image', id: 'photo', resourceId: 'cover', // the JPEG is cropped to the trim, 23 : 30
    placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: 'fill' } } },
  text('strap', '{subtitle}', small, at('page', 'top-left', MARGIN.inner, 12)), // a recto
  text('issue', '{attr.issue}', { ...small, align: 'right' },
    at('page', 'top-right', -MARGIN.outer, 12)),
  text('masthead', '{titleText}', { ...bodoni, fontWeight: 900, fontSize: pt(118),
    lineHeight: 0.86, // set tight: the masthead is capitals, with no descenders
    letterSpacing: pt(1), textTransform: 'uppercase', align: 'center', color: col('ink') },
  { ...at('#strap', 'below', 0, 6), size: { width: mm(MASTHEAD) } }),
  ...coverLine(1, 'olive'), ...coverLine(2, 'terracotta'), ...coverLine(3, 'wine'),
  // The price and a made-up barcode sit in the corner, anchored to the page, not the words.
  text('price', '{attr.price}', { ...small, fontSize: pt(7), box: sheet(1, 1.5) },
    { ...at('page', 'bottom-right', -MARGIN.outer, -12), size: { width: mm(32) } }),
  { kind: 'image', id: 'barcode', resourceId: 'barcode',
    placement: { ...at('#price', 'above', 0, SEAM), size: { width: mm(32) } } },
] } };
// hook-up: headingStyles gets { id: 'cover', numbered: false, toc: false, advancedDesign: cover,
// footer: { elements: [] } }, with no folio; the Markdown's first line is
// # Fallow {style="cover" issue="…" price="…" kicker1="…" line1="…" … kicker3="…" line3="…"}

Ingredientes

Tipografia
Spectral, Bodoni Moda, Jost (SIL OFL 1.1)
Materiais
  • castellina-cover-1150.jpg
  • castellina-farm-1530.jpg
  • fields-1610.jpg
  • flasks-1920.jpg
  • harvest-1840.jpg
  • Castellina in Chianti (the cover and its copy in the contents) (Rowan Heuvel, CC0 1.0)
  • Castellina in Chianti, a detail (the feature's photograph) (Rowan Heuvel, CC0 1.0)
  • Plants in beakers (the Field notes opener) (chuttersnap, CC0 1.0)
  • Harvesting the wheat crop (the Kitchen opener) (meriç tuna, CC0 1.0)
  • Fields from above near Castellina in Chianti (the feature's opener) (Generated With Diffusion Models, original)
  • The cover's barcode, drawn in code (Ignacio Ferro, MIT)

Preparo

#1 · Pendurar a capa no nome da revista

O código é a resposta curta acima. Só a foto, as duas linhas do alto e o preço são ancorados à página. Todo o resto se ancora a outro elemento (posicionamento de elementos): o nome da revista sob a linha superior, o primeiro chapéu 8 mm abaixo do nome e, daí em diante, cada chamada sob o chapéu e cada chapéu sob a chamada anterior. Assim, uma chamada mais longa ou um nome maior empurra para baixo o que está sob ele em vez de imprimir por cima. Cada chapéu e cada chamada têm a própria caixa de papel, de 84 mm de largura, e as seis caixas empilhadas formam o painel, que cresce com o texto. Toda caixa depois da primeira se sobrepõe 0,3 mm (SEAM) à de cima, e o código de barras ao preço da mesma forma, porque no canvas dois fundos que apenas se tocam deixam aparecer entre eles um fio finíssimo da foto. Uma revista não tem falsa folha de rosto nem folha de rosto: o nome vai na capa, e o número, a estação e o expediente vão no sumário. Para os elementos pré-textuais de um livro, veja Páginas iniciais com fólios romanos e depois a página 1.

#2 · Fazer de cada seção uma parte sem página

script.js · linhas 78–87no código completo
const parts = { page: false }; // a :::part now only sets the section's title and palette
const story = (id, picture) => ({ id, numbered: false, advancedDesign: opener(picture) });
const headingStyles = () => [
  { id: 'cover', numbered: false, toc: false, advancedDesign: cover,
    footer: { elements: [] } }, // no folio on the cover (the header is empty everywhere)
  { id: 'contents', numbered: false, toc: false, advancedDesign: contentsOpener,
    footer: folioLine('{title}', '{publishDate}') }, // no section yet: the issue instead
  // One opener for every story; the style names its picture, the part its colour.
  story('grain', 'flasks'), story('rest', 'fields'), story('bread', 'harvest'),
];

Com parts.page: false, uma linha como :::part{title="Features" palette="band=#5d6a2b"} não abre página divisória e só define o título e a paleta da seção a partir do bloco seguinte (o contêiner :::part). O H1 de cada matéria usa um estilo de título com numbered: false, e por isso o sumário o lista sem número. O estilo escolhe a imagem da abertura, e a cor vem da parte.

#3 · Ligar todas as cores de seção a uma só entrada

script.js · linhas 14–27no código completo
const palette = {
  ink: '#1c1a16', // text: a warm near-black
  paper: '#fbf8f1', // the page, and type set on colour
  band: '#8b6a3e', // the house earth; each :::part fence brings its own 'band'
  muted: '#6b6358', // credits and the standfirsts in the contents
  olive: '#5d6a2b', terracotta: '#a3472a', wine: '#7a2c3a', // as in the :::part fences: edit both
};
// A part overrides by id: col() writes the id beside the hex, and the designs follow it.
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 substitui entradas da paleta pelo id, de modo que tudo o que muda com a seção fica ligado a band: o painel da abertura, a aba do fólio, os marcadores e os números das listas, o olho de citação, e o fio e o título do boxe de dados. No texto, a substituição é feita pelo valor: qualquer cor cujo hex seja igual ao hex base de band (#8b6a3e) assume a da seção, e por isso nenhuma outra entrada usa esse hex. Nos elementos de design é o contrário: a substituição feita por uma parte chega a eles pelo paletteId, e por isso col() escreve o id ao lado do hex.

#4 · Deixar o sumário se agrupar sozinho

script.js · linhas 91–124no código completo
const mid = at('container', 'left', 0, -1); // the row's middle, 1 mm up: air above the title
const contents = { // passed to the config as `toc`
  levels: [{ level: 1, fontFamily: 'Bodoni Moda', fontSize: pt(17), fontWeight: 600,
    marginBottom: pt(2 * LEAD) }], // in ink, on the body's 13.5 pt leading
  pageNumber: { fontSize: pt(26), width: mm(14) }, // in the levels' Bodoni
  leader: { enabled: false }, subtitle: { enabled: true, attr: 'standfirst', // in italic
    fontFamily: 'Spectral', fontSize: pt(10), color: col('muted') },
  // A part row is a design as wide as the column; its 'band' takes the part's palette. No
  // {pageNumber} in it: each story under the tab prints its own page.
  parts: { height: pt(2 * LEAD), design: { elements: [ // two grid lines (the default: 2 em)
    { kind: 'rule', id: 'line', thickness: pt(0.75), color: col('band'), // behind the tab
      placement: { ...mid, size: { width: 'fill' } } },
    text('tab', '{titleText}', { ...label, fontSize: pt(8), letterSpacing: pt(1.6),
      color: col('paper'), box: { backgroundColor: col('band'),
        padding: { top: mm(1.2), right: mm(2.4), bottom: mm(1.2), left: mm(2.4) } } },
    mid),
  ] } },
};
// The colophon closes the contents page; the Markdown calls it with :::paragraphs.
const colophon = { id: 'colophon', fontFamily: 'Jost', fontSize: pt(7), lineHeight: pt(10),
  color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) };
const air = { padding: { bottom: mm(9) } }; // empty padding counts: the columns start lower
const contentsOpener = { enabled: true, slot: { elements: [
  { kind: 'rule', id: 'rule', thickness: pt(1), color: col('ink'),
    placement: { ...at('container', 'top-left'), size: { width: 'fill' } } },
  text('kicker', '{titleText}', { ...label, fontSize: pt(9), letterSpacing: pt(1.8),
    color: col('band') }, at('#rule', 'below', 0, 5)),
  text('issue', '{attr.issue}', { ...bodoni, italic: true, fontSize: pt(44), lineHeight: 1.05,
    color: col('ink') }, at('#kicker', 'below', 0, 2)),
  text('strap', '{subtitle}', { fontFamily: 'Spectral', italic: true, fontSize: pt(11),
    color: col('muted'), align: 'left' }, at('#issue', 'below', 0, 1.5)),
  text('number', '{attr.number}', { ...bodoni, fontWeight: 900, fontSize: pt(160), lineHeight: 1,
    align: 'right', color: col('band'), box: air }, at('container', 'top-right', 0, 4)),
] } };

:::toc lista as matérias e dá a cada :::part uma faixa diagramada com toc.parts.design e a paleta dessa parte (sumário), de modo que um único desenho de faixa imprime três abas em três cores. O fio e a aba pendem de mid, o meio da faixa erguido 1 mm, o que mantém a aba longe do título de baixo. Sem linha de pontos, entre cada título e a página (3, 4 e 6) fica só o branco, e subtitle.attr põe embaixo, em itálico, o atributo standfirst da abertura. O expediente que fecha a coluna da direita é um estilo de parágrafo, Jost de 7 pt em muted, que o Markdown aplica com :::paragraphs{style="colophon"}.

#5 · Dar a todas as matérias a mesma abertura

script.js · linhas 128–152no código completo
const PHOTO = 150; // mm from the top edge to the foot of the picture
const FOOT = PHOTO - MARGIN.top; // the same foot from the container, which starts at the margin
const LIFT = 34; // mm: how far the panel rises into the picture
const WIDE = 136; // mm: the panel's width
const panel = (top, bottom) => ({ backgroundColor: col('band'),
  padding: { top: mm(top), right: mm(6), bottom: mm(bottom), left: mm(6) } });
const below = (id) => ({ ...at(`#${id}`, 'below', 0, -SEAM), size: { width: mm(WIDE) } });
const opener = (resourceId) => ({ enabled: true, slot: { elements: [
  { kind: 'image', id: 'picture', resourceId, // fitted, never cropped: each file is 230 : 150
    placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(PHOTO) } } },
  text('credit', '{attr.credit}', { ...small, fontSize: pt(6.5), color: col('muted'),
    letterSpacing: pt(0.6), align: 'right' }, at('container', 'top-right', 0, FOOT + 2)),
  text('section', '{partTitle}', { ...label, fontSize: pt(8.5), letterSpacing: pt(1.7),
    color: col('paper'), box: panel(6, 2) }, { ...at('container', 'top-left', 0, FOOT - LIFT),
    size: { width: mm(WIDE) } }),
  text('title', '{titleText}', { ...bodoni, fontWeight: 700, fontSize: pt(32), lineHeight: 1.02,
    color: col('paper'), box: panel(0, 3) }, below('section')),
  text('standfirst', '{attr.standfirst}', { fontFamily: 'Spectral', italic: true,
    fontSize: pt(11.5), lineHeight: 1.35, overflow: 'wrap', align: 'left',
    color: col('paper'), box: panel(0, 6) }, below('title')),
  // The panel and the byline reach below the picture's foot, so they set where the story
  // starts; the byline's empty padding keeps the first line 5 mm under it.
  text('byline', '{attr.byline}', { ...small, fontSize: pt(7.5), letterSpacing: pt(1.3),
    box: { padding: { top: mm(4), bottom: mm(5) } } }, at('#standfirst', 'below')),
] } });

A imagem sangra pelo alto da página e desce 150 mm. Um painel em band sobe 34 mm sobre o pé dela. O painel são três caixas de texto de 136 mm de largura, cada uma encadeada below (abaixo) da anterior, com o nome da seção vindo de {partTitle}, o título e o olho. O painel e a assinatura descem além do pé da imagem, por isso a matéria começa sob o elemento mais baixo, a assinatura, cujo preenchimento inferior vazio de 5 mm mantém a primeira linha pelo menos a essa distância.

#6 · Pôr o nome da seção no fólio

script.js · linhas 156–171no código completo
const TAB = 6.5; // mm: the tab's side; the words beside it take its height and centre on it
const folioLine = (first, second) => ({ elements: [['even', 'left', 1], ['odd', 'right', -1]]
  .flatMap(([parity, side, s]) => {
    const inward = s > 0 ? 'right-of' : 'left-of'; // from the outer edge towards the gutter
    const beside = (id, content, style, to, gap) => text(id, content, { ...style, align: side },
      { ...at(to, inward, s * gap), size: { height: mm(TAB) } }); // text centres vertically
    return [
      text(`tab-${parity}`, '{pageNumber}', { ...label, fontSize: pt(8), color: col('paper'),
        align: 'center', box: { backgroundColor: col('band') } },
      { ...at('page', `bottom-${side}`, s * MARGIN.outer, -11),
        size: { width: mm(TAB), height: mm(TAB) } }),
      beside(`first-${parity}`, first, { ...small, color: col('band') }, `#tab-${parity}`, 3),
      beside(`second-${parity}`, second, { fontFamily: 'Spectral', italic: true,
        fontSize: pt(8), color: col('muted') }, `#first-${parity}`, 2.5),
    ].map((element) => ({ ...element, parity })); // no pages filter: openers get folios too
  }) });

O número da página fica num quadrado de band de 6,5 mm, no pé e do lado externo. O nome da seção se ancora ao lado dele, em direção à medianiz, e o título da matéria ao lado do nome; as três caixas têm 6,5 mm de altura e o texto centralizado na vertical, e assim compartilham o mesmo eixo. Revistas também numeram as páginas de abertura, por isso o rodapé não tem filtro pages. O estilo de título da capa esvazia o rodapé, e o do sumário põe o nome da revista e a estação da edição ({title} e {publishDate}) onde iriam a seção e a matéria.

A receita completa

Sandbox
// ═══ Postext Cookbook · Nº 023 · Magazine cover and sectioned contents ═══════════════
// https://postext.dev/en/cookbook/magazine-cover-and-contents
// Code: MIT · Text: original (CC BY 4.0) · Photos: R. Heuvel, chuttersnap, m. tuna (CC0), diffusion
// Fonts: Spectral, Bodoni Moda, Jost (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 = 'magazine-cover-and-contents';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: one house colour, 'band', that every section overrides
const palette = {
  ink: '#1c1a16', // text: a warm near-black
  paper: '#fbf8f1', // the page, and type set on colour
  band: '#8b6a3e', // the house earth; each :::part fence brings its own 'band'
  muted: '#6b6358', // credits and the standfirsts in the contents
  olive: '#5d6a2b', terracotta: '#a3472a', wine: '#7a2c3a', // as in the :::part fences: edit both
};
// A part overrides by id: col() writes the id beside the hex, and the designs follow it.
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: 230, height: 300 }; // an independent-magazine trim, in mm
const MARGIN = { top: 22, bottom: 20, inner: 16, outer: 14 }; // mirrored
const LEAD = 13.5; // body leading in pt: the baseline grid
const caps = { fontFamily: 'Jost', fontWeight: 600, textTransform: 'uppercase' }; // the label face
const label = { ...caps, align: 'left' }; // design text is centred by default
const bodoni = { fontFamily: 'Bodoni Moda', overflow: 'wrap', align: 'left' };
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, placement, ...look });

// #region answer: the cover, one design slot whose words hang from each other
const MASTHEAD = TRIM.width - MARGIN.inner - MARGIN.outer; // the word spans the text block
const PANEL = 84; // mm: the cover lines' panel, a column of paper over the photograph
const SEAM = 0.3; // mm: each box overlaps the one above, so no hairline of photo shows
// A cover line: a kicker in its section's colour over a line in Bodoni, on paper boxes of one
// width. Chained with 'below' they read as one panel, and a longer line pushes the rest down.
const sheet = (top, bottom) => ({ backgroundColor: col('paper'),
  padding: { top: mm(top), right: mm(5), bottom: mm(bottom), left: mm(5) } });
const small = { ...label, fontSize: pt(8), letterSpacing: pt(1.6), color: col('ink') };
const coverLine = (n, colour, above = n === 1 ? '#masthead' : `#line${n - 1}`) => [
  text(`kicker${n}`, `{attr.kicker${n}}`, { ...small, color: col(colour),

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

#Compor o nome da revista na cor da casa

O nome da revista assume o marrom-terra do grande 14 do sumário.

-    textTransform: 'uppercase', align: 'center', color: col('ink') },
+    textTransform: 'uppercase', align: 'center', color: col('band') },

#Abrir cada seção numa página divisória

Para partes com página própria, e um número de página em cada faixa de parte do sumário, veja Partes em cor a partir de um só atributo.

Erros comuns

Erro comum

Um flutuante 'top' vai para a página seguinte à sua citação, a menos que possa encabeçar a página que o cita

Por padrão um flutuante nunca fica acima da própria referência, então um flutuante 'top' na largura da página citado na página N abre a página N+1. Com placement.citingPage: true no recurso ou no defaultPlacement do seu tipo (ou layout.floatsAtCitingPage para o livro todo, desde o postext 1.25) ele encabeça a página N, e o texto acima da referência desce para baixo dele, quando cabe dentro de layout.maxTopFraction e a linha que o cita continua nessa página. Nunca encabeça a primeira página de um capítulo nem uma página depois de uma quebra forçada: ali continua abrindo a página seguinte, e 'auto' ou 'bottom' podem ocupar o pé da página que o cita. Posicionamento de figuras →

Erro comum

Bitmaps tiram o tamanho de impressão de uma resolução: declare-a, não calcule pixels de impressão

Um bitmap sem resolução é colocado a um pixel por pixel da diagramação na resolução do documento, então uma foto de 2400 px mede 406 mm de largura numa página de 150 dpi. Declare os pixels reais do arquivo e dê à imagem sua resolução (bitmap.resolution: 300), ou ajuste layout.bitmapResolution para todos os bitmaps: um valor de ppi, ou 'file' para ler o que o arquivo informa. A coluna continua limitando a imagem. Figuras e tabelas como recursos →

  • Um elemento de imagem encaixa a imagem dentro da caixa e nunca a corta. Corte antes cada JPEG no formato da caixa, 23 : 30 para a capa e 230 × 150 mm para as aberturas, ou a imagem encolhe e deixa faixas brancas nas bordas.
  • No texto, uma parte muda toda cor cujo hex seja igual ao hex base de band, esteja ela ligada a band ou não. Reserve esse hex para o que deve mudar com a seção.
  • As matérias estão ajustadas às páginas nos dois idiomas: algumas frases do Caderno de campo em espanhol foram encurtadas para que ele caiba numa página, e uma frase da reportagem em inglês perdeu três palavras para que as duas colunas da página 4 terminem na mesma altura. Depois de editar, confira que nenhuma matéria passe umas linhas para uma página nova e que todas as páginas, exceto a última de cada matéria, terminem niveladas.

Créditos

Texto
Texto original, CC BY 4.0
Imagens
  • Castellina in Chianti (the cover and its copy in the contents) · Rowan Heuvel · CC0 1.0
  • Castellina in Chianti, a detail (the feature's photograph) · Rowan Heuvel · CC0 1.0
  • Plants in beakers (the Field notes opener) · chuttersnap · CC0 1.0
  • Harvesting the wheat crop (the Kitchen opener) · meriç tuna · CC0 1.0
  • Fields from above near Castellina in Chianti (the feature's opener) · Generated With Diffusion Models · original
  • The cover's barcode, drawn in code · Ignacio Ferro · MIT
Fontes
Spectral (SIL OFL 1.1) · Bodoni Moda (SIL OFL 1.1) · Jost (SIL OFL 1.1)
Sandbox