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

Рецепты · Глава 2 · Шрифт и текст

Цветной код выделений в учебной хрестоматии

Хрестоматия по истории с тремя цветами выделений (термины зелёные, даты янтарные, имена голубые): три markStyles из палитры.

На этой странице
  • Образец на английском: русского издания пока нет
  • Обрезной формат 170 × 240 мм
  • 1 колонка
  • Source Serif 4 10,5/14,5
  • Source Sans 3
  • 4 страницы
  • Уровень
  • Postext 1.65.0
  • Свёрстано за 127 мс
  • Строк кода: 164

Коротко

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

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

Второй текст темы школьной хрестоматии Readings in Early Modern History («Чтения по истории раннего Нового времени»): четыре полосы 170 × 240 мм о том, как книгопечатание распространилось из Майнца по Европе между 1450 и 1550 годами. Редакторы отметили текст так, как это сделал бы аккуратный ученик, кодом, который не меняется во всей книге: термины на зелёной полоске, даты на янтарной, люди и места на бледно-голубой. Легенда под заголовком поясняет код самими тремя цветами, а в глоссарии на последней полосе каждая статья начинается зелёным термином. Выделения — полоски под обычным текстом, поэтому строки разрываются, переносятся и выключаются так, словно их нет.

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

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

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

script.js · строки 37–52в полном коде
// :mark[Mainz]{style="name"} in the text picks a style by id. The band is painted under
// words that stay ordinary text, so the lines break, hyphenate and justify as if the
// mark were not there, and a mark that runs over a line end gets a band on each line.
const band = (id, name) => ({
  id, name,
  background: col(id), // pale enough for ink at full contrast on top
  color: col('ink'), // the words keep the colour of the text
  // borderRadius: 0 is the default (square ends, as a highlighter pen leaves them)
  paddingX: em(0.12), // the band reaches a little past the first and the last letter
  paddingTop: em(0.04), paddingBottom: em(0.1), // and down past the descenders
});
const markStyles = [
  band('term', t({ en: 'Key term', es: 'Término clave' })),
  band('date', t({ en: 'Date', es: 'Fecha' })),
  band('name', t({ en: 'Name', es: 'Nombre' })),
];

Ингредиенты

Шрифты
Source Serif 4, Source Sans 3 (SIL OFL 1.1)
Материалы
  • press-1400.jpg
  • The printing workshop on the opening page, a painting (Generated With Diffusion Models, оригинал)

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

#1 · Один стиль для каждого рода слов

Код — в разделе Короткий ответ выше. markStyles объявляет три именованных стиля, а текст выбирает один на каждое выделение: :mark[Johann Fust]{style="name"}, :mark[1455]{style="date"}, :mark[colophon]{style="term"} (выделение маркером). Стиль называет то, что он означает (name — то, что видит редактор), поэтому Markdown записывает, почему слово выделено, а не в какой цвет. Измените цвет стиля, и вместе с ним изменится каждая дата в книге. Концы прямые, как по умолчанию с postext 1.52 (стили выделения): текстовыделитель оставляет прямые концы, а скруглённая полоска читается как плашка.

#2 · Три оттенка из палитры

script.js · строки 14–29в полном коде
const palette = {
  ink: '#1f1c19', // text: a warm near-black
  accent: '#8a3220', // kickers, rules, numbers: an iron-gall red
  tint: '#f5f0e7', // the key's background
  rule: '#d3cabc', // hairlines
  muted: '#6b645b', // running heads, colophon
  paper: '#ffffff',
  term: '#cce8c8', // key terms: a pale green
  date: '#fbe0a1', // dates: amber
  name: '#cfe0f4', // people and places: a pale blue
};
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' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

Три полоски — записи палитры, как краска текста и акцент, поэтому читатель, открывший книгу в Sandbox, перекрасит код одним образцом. Они бледные, близкие по светлоте к заливке врезки, поэтому контраст текста на них не ниже 12,6:1, и различимы, когда встречаются в одной строке, как в “In 1517 Martin Luther” на полосе 3. Выделение не занимает места: paddingX заходит на 0,12 em в пробел рядом с фразой, а paddingBottom опускает полоску под нижние выносные элементы, и обе рисуются там, где место уже есть.

#3 · Начальная полоса: картина над заголовком

script.js · строки 56–81в полном коде
const opener = {
  enabled: true,
  minHeight: mm(122), // the floor of the opener: the key starts on the same line
  marginBottom: pt(0),
  slot: {
    elements: [
      { kind: 'image', id: 'press', resourceId: 'press', fit: 'cover',
        placement: { anchor: { to: 'page', edge: 'top-left' },
          size: { width: mm(170), height: mm(96) } } },
      { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: SANS,
        fontSize: pt(8.5), fontWeight: 700, letterSpacing: pt(1.6),
        textTransform: 'uppercase', color: col('accent'), align: 'left',
        placement: { anchor: { to: 'container', edge: 'top-left' },
          offset: { x: mm(0), y: mm(82) } } },
      { kind: 'text', id: 'title', content: '{titleText}', fontFamily: SERIF,
        fontSize: pt(26), lineHeight: 1.08, fontWeight: 700, color: col('ink'), align: 'left',
        placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { x: mm(0), y: mm(2) },
          size: { width: mm(126), height: 'auto' } } },
      { kind: 'text', id: 'standfirst', content: '{attr.standfirst}', fontFamily: SERIF,
        italic: true, fontSize: pt(10.5), lineHeight: LEAD / 10.5, color: col('ink'),
        align: 'left',
        placement: { anchor: { to: '#title', edge: 'below' }, offset: { x: mm(0), y: mm(3) },
          size: { width: mm(118), height: 'auto' } } },
    ],
  },
};

Заголовок первого уровня печатает оформление. Картина привязана к странице и уходит под обрез вверху и с обоих боков, 170 на 96 мм, с fit: 'cover'. Рубрика и вводка берутся из атрибутов строки заголовка (атрибуты заголовка), а легенда идёт следом обычной :::callout, пункты списка в которой начинаются с трёх выделений. minHeight задаёт глубину: легенда начинается с одной и той же строки при любой длине заголовка.

#4 · Колонтитулы по чётности

script.js · строки 85–106в полном коде
const head = (id, content, parity, edge, x, extra = {}) => ({
  kind: 'text', id, content, parity, pages: 'body',
  fontFamily: SANS, fontSize: pt(7.5), fontWeight: 600, letterSpacing: pt(1.2),
  textTransform: 'uppercase', color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(13) } },
  ...extra,
});
const folio = { fontWeight: 700, color: col('ink') };
const header = {
  elements: [
    head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
    head('verso-title', '{title}', 'even', 'top-left', OUTER + 9),
    head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 9)),
    head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
  ],
};
const footer = {
  elements: [head('drop-folio', '{pageNumber}', 'all', 'top', 0, {
    ...folio, pages: 'opener',
    placement: { anchor: { to: 'container', edge: 'top' }, offset: { x: mm(0), y: mm(9) } },
  })],
};

На левой полосе — название серии, на правой — название текста; оба отобраны через parity и убраны с начальной полосы через pages: 'body' (текстовые элементы). На начальной колонцифра стоит внизу.

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

Sandbox
// ═══ Postext Cookbook · Nº 180 · Colour-coded highlights in a study reader ════════
// https://postext.dev/en/cookbook/colour-coded-study-highlights
// Code: MIT · Text: original (CC BY 4.0) · Picture: painting made for the recipe
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.65.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
} from 'https://esm.sh/postext';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, three of them for the highlighter
const palette = {
  ink: '#1f1c19', // text: a warm near-black
  accent: '#8a3220', // kickers, rules, numbers: an iron-gall red
  tint: '#f5f0e7', // the key's background
  rule: '#d3cabc', // hairlines
  muted: '#6b645b', // running heads, colophon
  paper: '#ffffff',
  term: '#cce8c8', // key terms: a pale green
  date: '#fbe0a1', // dates: amber
  name: '#cfe0f4', // people and places: a pale blue
};
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' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const OUTER = 20; // outer margin in mm: the running heads align to it
const LEAD = 14.5; // body leading in pt
const SANS = 'Source Sans 3';
const SERIF = 'Source Serif 4';

// #region answer: three highlight styles, one per kind of word, linked to the palette
// :mark[Mainz]{style="name"} in the text picks a style by id. The band is painted under
// words that stay ordinary text, so the lines break, hyphenate and justify as if the
// mark were not there, and a mark that runs over a line end gets a band on each line.
const band = (id, name) => ({
  id, name,
  background: col(id), // pale enough for ink at full contrast on top
  color: col('ink'), // the words keep the colour of the text
  // borderRadius: 0 is the default (square ends, as a highlighter pen leaves them)
  paddingX: em(0.12), // the band reaches a little past the first and the last letter
  paddingTop: em(0.04), paddingBottom: em(0.1), // and down past the descenders
});
const markStyles = [

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

Варианты

#Скруглите концы полосок

Радиус в пятую часть кегля даёт мягкие концы фломастера.

-  // borderRadius: 0 is the default (square ends, as a highlighter pen leaves them)
+  borderRadius: em(0.2), // soft ends, as a felt-tip pen leaves them

#Дайте каждой строке свою полоску

При decorationBreak: 'clone' выделение, которое переходит через конец строки, получает отступы с обоих концов каждой части, как на полосе 3, где “pamphlets” разрывается после “pam-”.

   paddingX: em(0.12), // the band reaches a little past the first and the last letter
+  decorationBreak: 'clone', // each line piece gets a whole band

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

  • Один лишь цвет не переживёт чёрно-белую копию, а многие тексты доходят до класса именно так. Глоссарий ещё и выделяет термины жирным; если читатели будут копировать страницы, дайте одному из трёх видов второй собственный признак.
  • Вместо стиля, id которого нет в markStyles, берётся первый, без ошибки на странице (Sandbox его отмечает). Делайте id короткими и проверяйте написание в тексте.

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

Рецепт
Ignacio Ferro
Текст
  • The reading, its key, the review questions and the colophon · Ignacio Ferro · CC BY 4.0
Изображения
  • The printing workshop on the opening page, a painting · Generated With Diffusion Models · оригинал
Шрифты
Source Serif 4 (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
Sandbox