Перейти к основному содержанию
Рецепт номер 54

Рецепты · Глава 10 · Вывод и интеграция

Перекрасить документ через одну палитру

Каждый цвет конфигурации связан с записью палитры, поэтому смена палитры печатает программу фестиваля красной, бирюзовой, фиолетовой или песочной.

  • Образец на английском: русского издания пока нет
  • Обрезной формат 200 × 200 мм
  • 2 колонки, средник 6 мм
  • Plus Jakarta Sans 9,4/13,4
  • Syne
  • 2 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 3 мс
  • Строк кода: 178

Коротко

Квадратная листовка музыкального фестиваля в четырёх цветовых схемах. Показывает, как сменить все цвета документа разом, выбрав новый набор.

Что получится

Программа Riverside Music Week, вымышленного фестиваля в городке у реки, квадратная листовка со стороной 200 мм. На первой странице цветное поле занимает верхнюю половину, на нём заглавие Syne 800 кегля 46 пт и волна из бледных скруглённых столбиков; ниже в двух колонках с флаговым краем расписана неделя по дням, у каждого события жирное время и плашка с ценой. На обороте неделя показана сеткой цветных клеток под полосой подписи, затем идут дни со вторника по пятницу, а в конце врезка о билетах под полоской и выходные сведения. Над страницами пен показывает четыре пробы: красную, бирюзовую, фиолетовую и песочную. Их цвета взяты из семи записей палитры, названных по роли, и main-color, равного цвету полосы. Щёлкните пробу, и весь документ соберётся заново в этой палитре.

Рецепт отвечает на вопросы

  • Как сделать, чтобы заголовки, полужирный текст и маркеры не были синими?
  • Как выделить цветом ключевые термины (полужирным или курсивом) в тексте или во врезках?
  • Как добавить образцы цвета в текст, подписи или примечания к таблицам?

Короткий ответ

script.js · строки 25–37в полном коде
// 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;
}

Ингредиенты

Шрифты
Syne, Plus Jakarta Sans (SIL OFL 1.1)
Материалы
Нет: все иллюстрации рисует код

Порядок работы

#1 · Назовите цвета по их работе

script.js · строки 14–21в полном коде
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 заливает цветные поля, onBand красит набранное на них, deep — акцент для текста на белой бумаге, tint — светлая заливка. Каждая схема задаёт эти четыре, а три нейтральных у всех общие. Бирюзовая полоса даёт на белом 3,3:1, песочная 2,1:1: слишком мало для белого текста на полосе или для текста её цвета на бумаге. Эти две палитры ставят в onBand цвет текста, а все четыре набирают жирный шрифт и заголовки цветом deep, более тёмным оттенком, который даёт на белом от 5,99:1 (песочный) до 8,40:1 (фиолетовый).

#2 · Свяжите всё, что движок напечатал бы синим

script.js · строки 68–94в полном коде
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) } } });

Синий движка — запись палитры main-color (#295AA3), и значения по умолчанию отправляют к ней заголовки, жирный шрифт, курсив, ссылки, маркеры и колонтитул. Здесь у каждого свой id палитры: время и ключевые слова жирным deep, курсив цветом текста, маркеры band, а на странице 2 колонтитул deep и колонцифра onBand на плашке band. retint() направляет на полосу и main-color; эта конфигурация задаёт каждый цвет, поэтому на этих страницах ничего не меняется, но стиль, добавленный позже без цвета, возьмёт цвет полосы, а не синий. Врезка о билетах своего цвета жирного не задаёт, поэтому наследует bodyText.boldColor вместе с id палитры, и её жирный меняется со схемой.

#3 · Нарисуйте графику прямоугольниками оформления

script.js · строки 48–64в полном коде
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 }),
  ] },
};

Начальная полоса — слот оформления с прямоугольником под верхний обрез, 29 скруглёнными столбиками волны и тремя текстовыми элементами: заглавие из самого заголовка, надзаголовок и лид из его атрибутов. Столбики — прямоугольники, а не SVG, поэтому их заливка — ещё одна связь с tint, которая следует за палитрой; SVG пришлось бы перерисовывать и регистрировать заново для каждой схемы. Сам по себе прямоугольник полосы начал бы текст с линии сетки в 2,4 мм под полосой; minHeight, 18 строк или 85,1 мм ниже верхнего поля, занимает больше и сдвигает первую строку на 7 мм под полосу.

#4 · Пусть палитра заливает таблицу

script.js · строки 176–199в полном коде
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] }))]),
  ] } } }];

Сетка — ресурс-таблица, вне конфигурации. Её заливки ячеек всё равно несут id палитры, и движок находит их в палитре документа, когда верстает таблицу; так же находятся :swatch{color="band"} и :swatch{color="tint"} в обозначениях примечания к таблице. Плашки в списках берут те же два id, поэтому залитая клетка, плашка рядом с временем и образец в обозначениях совпадают в каждой схеме.

#5 · Смените палитру и соберите заново

script.js · строки 236–265в полном коде
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);

Каждая кнопка вызывает retint(), которая присваивает записи схемы colorPalette единственного объекта конфигурации, и собирает документ заново. Движок разбирает конфигурацию один раз и кеширует результат по этому объекту; начиная с postext 1.25 каждая сборка сначала проверяет, что объект читается так же, как тогда, поэтому изменение на месте разбирается снова. За палитрой следуют все связи: текст, списки, плашки и полоса подписи, а с ними цветное поле, волна, колонтитул, плашка колонцифры и «Table 1». Четыре пробы сохраняют свои цвета, когда палитра меняется снова, потому что каждый документ хранит цвета, с которыми свёрстан. Пен собирает их через buildDocumentWithFonts; к моменту щелчка шрифты загружены, и хватает buildDocument.

Рецепт целиком

Sandbox
// ═══ 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',

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Оставить жирный цветом текста

Акцент остаётся заголовкам, маркерам и плашкам, а время и ключевые слова набираются цветом текста.

-  boldColor: col('deep'), referenceColor: col('deep'), textAlign: 'left', firstLineIndent: pt(0) };
+  boldColor: col('ink'), referenceColor: col('deep'), textAlign: 'left', firstLineIndent: pt(0) };

#Дать каждой части книги свой цвет

Цвета, которые меняются внутри одного документа от части к части, показывает рецепт Цветные части через один атрибут.

Частые ошибки

  • Картинка сохраняет цвета, которыми нарисована. SVG или фотография за палитрой не следует, поэтому волна сделана из прямоугольников оформления.
  • Id, которого в палитре нет, заменяется записанным рядом hex. Ошибитесь в paletteId, и этот цвет останется фирменным красным во всех схемах.

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Шрифты
Syne (SIL OFL 1.1) · Plus Jakarta Sans (SIL OFL 1.1)
Sandbox