In breve
Un pieghevole quadrato per un festival musicale, mostrato in quattro combinazioni di colori. Mostra come cambiare in un colpo solo tutti i colori del documento scegliendo un nuovo gruppo di colori.
Che cosa comporrai
Il programma di Riverside Music Week, un festival immaginario in una città sul fiume, stampato come pieghevole quadrato di 200 mm. La prima pagina ha un campo di colore sulla metà superiore, con il titolo in Syne 800 a 46 pt e una forma d’onda di barre arrotondate chiare; sotto, due colonne in bandiera elencano la settimana giorno per giorno, ogni evento con un orario in grassetto e un chip del prezzo. Il retro disegna la settimana come una griglia di tessere colorate sotto una barra della didascalia, poi elenca i giorni da «Tuesday» a «Friday» e chiude con un riquadro dei biglietti sotto una banda e il colophon. Sopra le pagine il pen mostra quattro prove, in rosso, petrolio, viola e sabbia. I loro colori vengono da sette voci della tavolozza, ognuna con un nome che ne indica il ruolo, più main-color impostato sul colore della fascia. Fai clic su una prova e tutto il documento si ricompone con quella tavolozza.
Questa ricetta risponde a
- Come evito che titoli, parole in grassetto e punti elenco escano in blu?
- Come coloro i termini chiave (in grassetto o in corsivo) nel testo o dentro i riquadri?
- Come aggiungo campioni di colore come legenda nel testo, nelle didascalie o nelle note di tabella?
La risposta breve
// col(id) links a colour to a palette entry. The link decides what is printed, in text, lists,
// boxes, chips, captions, table fills, swatches, design slots and references alike; the hex
// beside it (the house red's) only fills the field a colour must have.
const col = (id) => ({ hex: HOUSE[id], model: 'hex', paletteId: id });
const entries = (hexes) => Object.entries(hexes).map(([id, hex]) => ({ id, name: id,
value: { hex, model: 'hex' } })); // the shape of config.colorPalette
// A colourway is a palette. retint() writes it into the one config; the next build sees the
// change and sets the whole programme in the new colours.
function retint(way) {
const palette = { ...NEUTRALS, ...COLOURWAYS[way] };
config.colorPalette = entries({ ...palette, 'main-color': palette.band }); // defaults: band
return config;
}
Ingredienti
- Funzionalità
- Tavolozza di colori semanticaGrassetto, corsivo e i loro coloriCampioni di coloreChip in lineaRiempimenti delle celleStile delle didascalieAperture progettateFascia di capitolo a tutta larghezzaTesto, filetti e riquadri nei progetti di paginaElenchi puntati e liste di controlloRiquadriTestatine e folioTestatine secondo il ruolo della paginaAttributi dei titoliFigure e tabelle come risorsePagine su un canvas
- Usa anche
- Citazioni che collocano le figureFigura e Tabella nella tua linguaStili di paragrafoTipi di risorsa personalizzatiA capo nei titoli
- Tipo
- Syne, Plus Jakarta Sans (SIL OFL 1.1)
- Risorse
- Nessuna: ogni immagine è disegnata nel codice
Preparazione
#1 · Nomina i colori per il lavoro che fanno
const NEUTRALS = { ink: '#1d1d1f', muted: '#5f5f66', paper: '#ffffff' };
const COLOURWAYS = { // band: colour fields · onBand: type on them · deep: accent type on paper
red: { band: '#d7263d', onBand: '#ffffff', deep: '#b3122a', tint: '#fcdfe3' },
teal: { band: '#2a9d8f', onBand: '#1d1d1f', deep: '#17695f', tint: '#d8eeeb' },
violet: { band: '#6a4c93', onBand: '#ffffff', deep: '#5b3f86', tint: '#e7dff0' },
sand: { band: '#f4a261', onBand: '#1d1d1f', deep: '#a14a16', tint: '#fde4cf' },
}; // white on teal is 3.3:1 and on sand 2.1:1, so those two set their band type in ink
const HOUSE = { ...NEUTRALS, ...COLOURWAYS.red }; // the house edition: red
band riempie i campi di colore, onBand colora il testo composto sopra di essi, deep è l’accento per il testo sulla carta bianca e tint il fondo chiaro. Ogni variante imposta questi quattro e condivide i tre neutri. Sul bianco la fascia petrolio misura 3,3:1 e quella sabbia 2,1:1, troppo poco per un testo bianco sulla fascia o per un testo del colore della fascia sulla carta. Queste due tavolozze impostano onBand in nero, e tutte e quattro compongono grassetti e titoli in deep, una tonalità più scura che misura tra 5,99:1 (sabbia) e 8,40:1 (viola) sul bianco.
#2 · Collega tutto ciò che il motore stamperebbe in blu
const bodyText = { fontFamily: SANS, fontSize: pt(BODY), lineHeight: pt(LEAD),
color: col('ink'), italicColor: col('ink'), // bold: the times, key terms, boxes (inherited)
boldColor: col('deep'), referenceColor: col('deep'), textAlign: 'left', firstLineIndent: pt(0) };
const headings = { fontFamily: DISPLAY, color: col('deep'), levels: [
// The programme opens on a recto.
{ level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
marginTop: pt(0), marginBottom: pt(0), advancedDesign: opener },
{ level: 2, fontSize: pt(12.5), lineHeight: lines(1), marginTop: lines(1), marginBottom: pt(0) },
] };
const unorderedLists = { color: col('band'), indent: mm(3.6), gap: mm(1.4),
marginTop: pt(0), marginBottom: pt(0) };
const chip = { fontSize: pt(7.5), bold: true, borderWidth: pt(0), borderRadius: mm(1.6),
paddingX: mm(1.3), paddingY: pt(0.9), gap: mm(1) };
const chipStyles = [ // band = a ticket, tint = free: the same code as the grid overleaf
{ id: 'ticket', background: col('band'), color: col('onBand'), ...chip },
{ id: 'free', background: col('tint'), color: col('deep'), ...chip,
borderWidth: pt(0.6), borderColor: col('band') }, // the outline keeps it off the white
];
const corner = (edge, y) => ({ anchor: { to: 'page', edge }, offset: { x: mm(OUTER), y: mm(y) } });
const furniture = (id, content, edge, y, style) => ({ elements: [{ kind: 'text', id, content,
parity: 'even', pages: 'body', overflow: 'wrap', placement: corner(edge, y), ...style }] });
const header = furniture('head', '{title} · {subtitle}', 'top-left', 12, // page 2's head
{ ...caps(7.5), color: col('deep') });
const footer = furniture('folio', '{pageNumber}', 'bottom-left', -12, { fontFamily: SANS,
fontSize: pt(8), fontWeight: 700, color: col('onBand'), box: { backgroundColor: col('band'),
borderRadius: mm(2.4), padding: { top: mm(0.9), right: mm(2.4), bottom: mm(0.9),
left: mm(2.4) } } });
Il blu del motore è una voce della tavolozza, main-color (#295AA3), e i suoi valori predefiniti vi collegano titoli, grassetto, corsivo, rimandi, punti elenco e testatina. Qui ognuno di essi usa un id della tavolozza: orari e termini chiave in grassetto deep, corsivi in nero, punti elenco in band, e a pagina 2 una testatina in deep e il numero di pagina in onBand su una pillola band. retint() collega anche main-color alla fascia; poiché questa configurazione imposta ogni colore, su queste pagine non cambia nulla, ma uno stile aggiunto più tardi senza colore prende la fascia invece del blu. Il riquadro dei biglietti non imposta un colore proprio per il grassetto, quindi eredita bodyText.boldColor con il suo id della tavolozza, e il suo grassetto cambia con la variante.
#3 · Disegna la grafica con i riquadri del progetto grafico
const text = (id, content, x, y, width, style) => ({ kind: 'text', id, content, align: 'left',
overflow: 'wrap', color: col('onBand'), placement: { anchor: { to: 'page', edge: 'top-left' },
offset: { x: mm(x), y: mm(y) }, size: { width: mm(width) } }, ...style });
const opener = { enabled: true,
minHeight: lines(18), // 85.1 mm: text 7 mm under the band (2.4 mm with the band box alone)
slot: { elements: [
{ kind: 'box', id: 'band', style: { backgroundColor: col('band') },
placement: { anchor: { to: 'bleed', edge: 'top-left' },
size: { width: 'fill', height: mm(BAND) } } },
...waveform(), // boxes filled with col('tint'): one more link the palette decides
text('kicker', '{attr.kicker}', INNER, 14, 150, caps(8)),
text('title', '{titleText}', INNER, 20, TRIM - INNER - OUTER, { fontFamily: DISPLAY,
fontSize: pt(46), fontWeight: 800, lineHeight: 0.92 }),
text('standfirst', '{attr.standfirst}', INNER, 71, 92, { fontFamily: SANS, fontSize: pt(10),
lineHeight: 1.36 }),
] },
};
L’apertura è uno slot di progetto grafico che contiene un riquadro al vivo sul bordo superiore, 29 barre arrotondate per la forma d’onda e tre elementi di testo: il testo stesso del titolo come titolo, e l’occhiello e il sommario dai suoi attributi. Le barre sono riquadri e non un SVG, quindi il loro fondo è un altro collegamento a tint che segue la tavolozza; un SVG andrebbe ridisegnato e registrato di nuovo per ogni variante. Da solo, il riquadro della fascia farebbe partire il testo sulla riga di griglia 2,4 mm sotto la fascia; minHeight, 18 righe o 85,1 mm sotto il margine superiore, riserva di più e sposta la prima riga a 7 mm sotto di essa.
#4 · Lascia che la palette riempia la tabella
const DAYS = t({ en: ['Sat 12', 'Sun 13', 'Mon 14', 'Tue 15', 'Wed 16', 'Thu 17', 'Fri 18'],
es: ['Sáb 12', 'Dom 13', 'Lun 14', 'Mar 15', 'Mié 16', 'Jue 17', 'Vie 18'] });
const WEEK = [ // t: a ticketed concert, f: a free event, one mark a day from Saturday
[t({ en: 'Quay Stage', es: 'Escenario del Muelle' }), 't.f.fft'],
[t({ en: 'Iron Bridge steps', es: 'Escalinata del Puente' }), 'f.....f'],
[t({ en: 'Market Hall', es: 'Mercado de Abastos' }), '.f...f.'],
[t({ en: 'St Clare’s Cloister', es: 'Claustro de Santa Clara' }), '.t.....'],
[t({ en: 'Tannery Yard', es: 'Patio de la Curtiduría' }), '...t...'],
[t({ en: 'Boathouse', es: 'Casa de las Barcas' }), '.ft..t.'],
];
const fill = { t: col('band'), f: col('tint') }; // cell fills are palette links too
const resources = [{ id: 'week', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
placement: { position: 'top', span: 'page' }, // cited on page 1, it heads page 2
caption: t({ en: 'The week at a glance', es: 'La semana de un vistazo' }),
note: t({ en: ':swatch{color="band"} ticketed concert :swatch{color="tint"} free event',
es: ':swatch{color="band"} concierto con entrada :swatch{color="tint"} acto gratuito' }),
altText: t({ en: 'A grid of six venues by seven days; filled squares mark the events.',
es: 'Una cuadrícula de seis escenarios por siete días; los cuadros rellenos son los actos.' }),
table: { model: { headerRowCount: 1, columnWidths: [2.6, 1, 1, 1, 1, 1, 1, 1], rows: [
[{ content: '', isHeader: true, background: col('paper') }, ...DAYS.map((day) => ({
content: day, isHeader: true, align: 'center' }))],
...WEEK.map(([venue, marks]) => [{ content: venue, align: 'right' }, ...[...marks].map((m) =>
(m === '.' ? { content: '' } : { content: '', background: fill[m] }))]),
] } } }];
La griglia è una risorsa tabella, fuori dalla configurazione. I suoi fondi di cella usano comunque id della tavolozza, e il motore li risolve dalla tavolozza del documento quando impagina la tabella; allo stesso modo si risolvono i :swatch{color="band"} e :swatch{color="tint"} della legenda nella nota della tabella. I chip negli elenchi usano gli stessi due id, così un quadrato pieno, il chip accanto a un orario e il campione della legenda concordano in ogni variante.
#5 · Cambia palette e ricomponi
const NAMES = t({ en: { red: 'Red', teal: 'Teal', violet: 'Violet', sand: 'Sand' },
es: { red: 'Rojo', teal: 'Verde azulado', violet: 'Violeta', sand: 'Arena' } });
document.getElementById('pages').insertAdjacentHTML('beforebegin', `<section id="editions">
<div class="desk"><header><p class="kicker">${t({ en: 'Riverside Music Week · proofs',
es: 'Música en la Ribera · pruebas' })}</p><h2>${TITLE}</h2></header><canvas id="live"
role="img"></canvas><div class="buttons" role="group"></div></div></section>`);
const paint = (canvas, doc) => renderPageToCanvas(doc.pages[0], doc, canvas,
{ scale: (canvas.clientWidth * Math.min(devicePixelRatio, 2)) / doc.pages[0].width });
const buttons = Object.keys(COLOURWAYS).map((way) => {
const button = document.querySelector('#editions .buttons')
.appendChild(Object.assign(document.createElement('button'), { type: 'button' }));
button.innerHTML = `<canvas></canvas><span>${NAMES[way]}<i>${['band', 'deep', 'tint']
.map((id) => `<b style="background:${COLOURWAYS[way][id]}"></b>`).join('')}</i></span>`;
paint(button.firstChild, docs[way]);
// The same config with another palette on every click; the fonts are loaded by now.
button.onclick = () => show(way, buildDocument({ markdown, resources }, retint(way)));
return [way, button];
});
const live = document.getElementById('live');
let shown; // the document on the live page
function show(way, doc) {
paint(live, (shown = doc));
live.ariaLabel = `${NAMES[way]}, ${t({ en: 'page 1', es: 'página 1' })}`;
for (const [id, button] of buttons) button.ariaPressed = String(id === way);
showPages(doc, { title: `${TITLE} · ${NAMES[way]}` });
}
show('red', docs.red);
new ResizeObserver(() => { // canvases are bitmaps: repaint them at the desk's new size
paint(live, shown); buttons.forEach(([way, button]) => paint(button.firstChild, docs[way]));
}).observe(live);
Ogni pulsante chiama retint(), che assegna le voci della variante a colorPalette sull’unico oggetto di configurazione, e ricompone. Il motore risolve una configurazione una volta e mette in cache il risultato associandolo a quell’oggetto; da postext 1.25 ogni composizione controlla prima che l’oggetto si legga ancora come allora, quindi una modifica fatta sul posto viene risolta di nuovo. Ogni collegamento segue: il testo, gli elenchi, i chip e la barra della didascalia, e con loro la fascia, la forma d’onda, la testatina, la pillola del numero di pagina e «Table 1». Le quattro prove mantengono i loro colori quando la tavolozza cambia ancora, perché ogni documento conserva i colori con cui è stato impaginato. Il pen le compone con buildDocumentWithFonts; quando si fa clic su un pulsante i caratteri sono già caricati, e basta buildDocument.
La ricetta completa
// ═══ Postext Cookbook · Nº 054 · Retint a whole document from one palette ═══════════
// https://postext.dev/en/cookbook/live-palette-retint
// Code: MIT · Text: original (CC BY 4.0) · Artwork: design boxes generated in code (CC BY 4.0)
// Fonts: Syne, Plus Jakarta Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
buildDocument, buildDocumentWithFonts, renderPageToCanvas, defaultResourceTypes,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'live-palette-retint';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: three neutrals every edition shares, four entries each colourway sets
const NEUTRALS = { ink: '#1d1d1f', muted: '#5f5f66', paper: '#ffffff' };
const COLOURWAYS = { // band: colour fields · onBand: type on them · deep: accent type on paper
red: { band: '#d7263d', onBand: '#ffffff', deep: '#b3122a', tint: '#fcdfe3' },
teal: { band: '#2a9d8f', onBand: '#1d1d1f', deep: '#17695f', tint: '#d8eeeb' },
violet: { band: '#6a4c93', onBand: '#ffffff', deep: '#5b3f86', tint: '#e7dff0' },
sand: { band: '#f4a261', onBand: '#1d1d1f', deep: '#a14a16', tint: '#fde4cf' },
}; // white on teal is 3.3:1 and on sand 2.1:1, so those two set their band type in ink
const HOUSE = { ...NEUTRALS, ...COLOURWAYS.red }; // the house edition: red
// #endregion
// #region answer: every colour is a link to a palette entry; retint() swaps the palette
// col(id) links a colour to a palette entry. The link decides what is printed, in text, lists,
// boxes, chips, captions, table fills, swatches, design slots and references alike; the hex
// beside it (the house red's) only fills the field a colour must have.
const col = (id) => ({ hex: HOUSE[id], model: 'hex', paletteId: id });
const entries = (hexes) => Object.entries(hexes).map(([id, hex]) => ({ id, name: id,
value: { hex, model: 'hex' } })); // the shape of config.colorPalette
// A colourway is a palette. retint() writes it into the one config; the next build sees the
// change and sets the whole programme in the new colours.
function retint(way) {
const palette = { ...NEUTRALS, ...COLOURWAYS[way] };
config.colorPalette = entries({ ...palette, 'main-color': palette.band }); // defaults: band
return config;
}
// #endregion
const [DISPLAY, SANS, BODY, LEAD] = ['Syne', 'Plus Jakarta Sans', 9.4, 13.4]; // pt: 33 lines
const [TRIM, TOP, BOTTOM, INNER, OUTER, GUTTER] = [200, 22, 22, 17, 15, 6]; // mm: square, mirrored
const BAND = 100; // mm, trim top to the colour field's foot ('bleed' is the trim: no cut lines)
const lines = (n) => pt(n * LEAD);
const caps = (size) => ({ fontFamily: SANS, fontSize: pt(size), fontWeight: 700,
letterSpacing: pt(size * 0.16), textTransform: 'uppercase' });
// #region opener: the colour field, a waveform of palette-linked boxes, the title on top
const text = (id, content, x, y, width, style) => ({ kind: 'text', id, content, align: 'left',
/* The proof desk above the pages: the live page, and the four colourways as buttons.
Sizes are in container units, so the desk keeps its 4:3 shape at any width up to 1120 px. */
#editions {
container-type: inline-size; max-width: 1120px; margin: 0 auto; background: #16181d;
color: #b9bcc4; font: 400 13px/1.4 "Plus Jakarta Sans", system-ui, sans-serif;
}
#editions .desk {
box-sizing: border-box; display: grid; aspect-ratio: 4 / 3; padding: 4cqw;
grid-template: 'page head' auto 'page ways' minmax(0, 1fr) / 67cqw minmax(0, 1fr);
gap: 2.6cqw 3.5cqw;
}
#editions header { grid-area: head; }
#editions .kicker {
margin: 0 0 0.8cqw; font-size: max(10px, 1cqw); font-weight: 700; letter-spacing: .18em;
text-transform: uppercase; color: #8d9098;
}
#editions h2 { margin: 0; font: 800 2.2cqw/1.1 Syne, sans-serif; color: #f4f1ea; }
#live {
grid-area: page; display: block; width: 67cqw; height: 67cqw; background: #fff;
box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 2.4cqw 4.8cqw -1.8cqw rgb(0 0 0 / .85);
}
#editions .buttons {
grid-area: ways; display: grid; grid-template-rows: repeat(4, minmax(0, 1fr)); gap: 1.3cqw;
}
#editions button {
display: flex; align-items: center; gap: 1.6cqw; padding: 0; border: 0; background: none;
color: #f4f1ea; font: 700 1.7cqw/1.15 Syne, sans-serif; text-align: left; cursor: pointer;
}
#editions button canvas {
flex: none; width: 11cqw; height: 11cqw; background: #fff;
outline: 2px solid transparent; outline-offset: 0.45cqw; transition: outline-color .15s;
}
#editions button[aria-pressed="true"] canvas { outline-color: #f4f1ea; }
#editions button:hover canvas, #editions button:focus-visible canvas { outline-color: #8d9098; }
#editions button:focus-visible { outline: none; }
#editions button i { display: flex; gap: 0.5cqw; margin-top: 0.8cqw; }
#editions button b {
width: 1.4cqw; height: 1.4cqw; border-radius: 50%;
box-shadow: inset 0 0 0 1px rgb(255 255 255 / .14);
}
@container (max-width: 640px) {
#editions .desk {
aspect-ratio: auto; padding: 24px 16px; gap: 18px;
grid-template: 'head' auto 'page' auto 'ways' auto / minmax(0, 1fr);
}
#editions h2 { font-size: 24px; }
#live { width: 100%; height: auto; aspect-ratio: 1; }
#editions .buttons { grid-template: auto / repeat(4, minmax(0, 1fr)); gap: 10px; }
Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)
Varianti
#Tieni il grassetto in nero
Lascia l’accento a titoli, punti elenco e chip, e componi orari e termini chiave nel colore del testo.
- boldColor: col('deep'), referenceColor: col('deep'), textAlign: 'left', firstLineIndent: pt(0) };
+ boldColor: col('ink'), referenceColor: col('deep'), textAlign: 'left', firstLineIndent: pt(0) };#Dai a ogni parte di un libro il suo colore
Per colori che cambiano in un unico documento, parte per parte, vedi Parti a colori da un solo attributo.
Errori frequenti
- Un’immagine mantiene i colori con cui è stata disegnata. Un SVG o una fotografia non seguono la tavolozza, ed è per questo che la forma d’onda è fatta di riquadri grafici.
- Un id che la tavolozza non contiene ripiega sull’esadecimale scritto accanto. Sbaglia a scrivere un
paletteIde quel colore resta nel rosso della casa in ogni variante.
Crediti
- Ricetta
- Ignacio Ferro
- Testo
- Testo originale, CC BY 4.0
- Font
- Syne (SIL OFL 1.1) · Plus Jakarta Sans (SIL OFL 1.1)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)


