本文へスキップ
レシピ番号54

レシピ集 · 第10章 · 出力と組み込み

1つのパレットで文書全体の色を変える

設定の各色がパレットの項目にリンクしているので、パレットを差し替えるだけで、音楽祭のプログラムを赤、ティール、紫、砂色のどれでも組めます。

1ページ(全2ページ)

  • 英語の見本:日本語版はまだありません
  • 仕上がり200 × 200 mm
  • 2段, 段間6 mm
  • Plus Jakarta Sans 9.4/13.4
  • Syne
  • 2ページ
  • レベル
  • Postext 1.57.1
  • 組版時間3 ms
  • コード178行

かんたんな説明

音楽祭の正方形のちらしを、4つの配色で見せます。新しい色の組み合わせを選ぶだけで、文書の色をすべて一度に変える方法がわかります。

できあがり

『Riverside Music Week』のプログラムです。川沿いの町で開かれる架空の音楽祭で、200mm角のちらしに印刷します。表面は上半分に色の地があり、Syne 800の46ptの表題と、淡い角丸のバーで描いた波形が載ります。その下では左そろえの2段で1週間を日ごとに並べ、各催しに太字の時刻と料金のチップが付きます。裏面はキャプションバーの下に色のタイルのグリッドで1週間を示し、続いて火曜から金曜を並べ、帯の下のチケットの囲みと奥付で終わります。ページの上では、CodePenのサンプルが赤、ティール、紫、砂色の4つの校正刷りを表示します。色は役割で名付けた7つのパレット項目と、帯の色にした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は淡い塗りです。各配色はこの4つを設定し、3つのニュートラルカラーは共有します。白に対するコントラスト比は、ティールの帯が3.3:1、砂色の帯が2.1:1で、帯の上の白い文字にも、紙の上の帯の色の文字にも低すぎます。この2つのパレットはonBandをインキの色にし、4つとも太字と見出しを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、ノンブルはbandのピル形の上にonBandです。retint()はmain-colorも帯の色に向けます。この設定はすべての色を指定しているので、これらのページでは何も変わりませんが、あとで色を指定せずに加えたスタイルは、青ではなく帯の色になります。チケットの囲みは独自の太字の色がないので、パレットidごとbodyText.boldColorを受け継ぎ、その太字も配色とともに変わります。

#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 }),
  ] },
};

冒頭部分はデザインスロットで、天の縁から裁ち落としにしたボックス1つ、波形を描く角丸のバー29本、3つのテキスト要素を収めます。テキスト要素は見出し自身のテキストを表題にし、キッカーとリードを見出しの属性から取ります。バーはSVGではなくボックスなので、その塗りもパレットに従うtintへのリンクの1つです。SVGなら配色ごとに描き直し、登録し直す必要があります。帯のボックスだけなら、本文は帯の2.4mm下のグリッド行から始まります。minHeightは天の余白から18行、85.1mmを確保し、最初の行を帯の7mm下に移します。

#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"}も同じように解決されます。催しの一覧のチップも同じ2つの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()を呼び、それが配色の項目をただ1つの設定オブジェクトのcolorPaletteに代入してから、ビルドし直します。エンジンは設定を一度解決し、その結果をそのオブジェクトに対してキャッシュします。postext 1.25からは、ビルドのたびに、オブジェクトがそのときと同じ内容かをまず確かめるので、その場で加えた変更は解決し直されます。リンクはすべて追従します。本文、リスト、チップ、キャプションバー、そして帯、波形、柱、ノンブルのピル形、「Table 1」です。パレットがまた変わっても、4つの校正刷りはそれぞれの色を保ちます。どの文書も、組んだときの色を保っているからです。サンプルは校正刷りを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) };

#本の部ごとに色を変える

1つの文書の中で部ごとに変わる色については、ひとつの属性で部ごとに色を変えるを参照してください。

よくあるつまずき

  • 画像は描いたときの色のままです。SVGや写真はパレットに従わないので、波形はデザインのボックスで作っています。
  • パレットにないidは、横に書いたhexに戻ります。paletteIdを打ち間違えると、その色はどの配色でもハウスカラーの赤のままになります。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Syne (SIL OFL 1.1) · Plus Jakarta Sans (SIL OFL 1.1)
Sandbox