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

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

Букварь со слогами-плашками

Урок букваря на букву M: звуки каждого слова плашками цвета его гласной и сетка слов с картинками, в каждой ячейке акварель.

с. 37 · 1 из 3

  • Образец на английском: русского издания пока нет
  • Обрезной формат 210 × 260 мм
  • 1 колонка
  • Andika 11/15
  • DynaPuff
  • Playpen Sans
  • 3 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 52 мс
  • Строк кода: 180

Коротко

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

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

Урок 12 из Letter by Letter, вымышленного английского букваря по фонетическому методу: три страницы на звук m. Начальная полоса ставит Mm шрифтом DynaPuff кеглем 190 пт на кремовую полосу рядом с двумя предметами на m, monkey (обезьяна) и moon (луна). Каждое слово разбито на звуки, и каждый звук — плашка цвета гласной слова: a красная, e оранжевая, i бирюзовая, o синяя, u фиолетовая. Плашка m залита, остальные контурные, и ребёнок видит, где в map и в gum стоит звук урока. Страница 38 ставит шесть слов с картинками в скруглённой сетке, по акварели в ячейке, а ниже три строки для обводки. Акварели созданы диффузионными моделями; полоса, значки и строки для обводки нарисованы в коде. На странице 39 четыре предложения кеглем 24 пт, врезка слов для раскраски и записка для родителей и воспитателей.

Испанская версия — другой урок, а не перевод: урок 7 из Letra a letra на ту же букву. Испанскому учат по открытым слогам (ma, me, mi, mo, mu), поэтому плашки содержат слоги, {mi·mo·sa}. Английских слов из этих слогов нет, а английские буквари идут звук за звуком, поэтому английский урок складывает звуки коротких слов, {m·a·p}, и группирует их в рифмующиеся семьи (-at, -an, -ug, -op). Оба урока выходят из одного пена: те же стили плашек, та же функция syllables(), та же сетка, строки для обводки и врезки.

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

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

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

script.js · строки 27–48в полном коде
// A word's syllables are chips with nothing between them, so their boxes touch and the white
// border draws the seam. Across a word space a chip keeps at least `gap`: 0.5 em sets the
// words of a 24 pt row 4.2 mm apart, where the space alone leaves 2.3 mm. Inside a sentence
// the '-frase' twins keep no gap, so the word space alone parts a chip from the word before.
// A 24 pt chip, padding and border included, is 10.4 mm tall (gotcha: chip-overlap).
const syllable = { fontFamily: TEXT, bold: true, borderWidth: pt(1), borderColor: col('paper'),
  paddingX: em(0.26), paddingY: em(0.05), gap: em(0.5) };
const chipStyles = [
  ...'aeiou'.split('').flatMap((v) => [ // one pair per vowel
    { ...syllable, id: v, background: col(v), color: col('paper') }, // a syllable with m
    { ...syllable, id: `${v}-borde`, background: col('paper'), color: col(v), borderColor: col(v) },
  ]).flatMap((style) => [style, { ...style, id: `${style.id}-frase`, gap: em(0) }]),
  { ...syllable, id: 'pinta', bold: false, background: col('paper'), color: col('ink'),
    borderColor: col('ink'), borderWidth: pt(0.8) }, // an outline for the child to colour in
];
const vowel = (s) => s.normalize('NFD').toLowerCase().match(/[aeiou]/)[0]; // 'mú' → 'u'
const chipOf = (s, v, end) => `:chip[${s}]{style="${v}${/m/i.test(s) ? '' : '-borde'}${end}"}`;
// {mi·mo·sa} → :chip[mi]{style="i"}:chip[mo]{style="o"}:chip[sa]{style="a-borde"}, and a word
// written after another word, as in 'me {mi·ma}.', takes the '-frase' twins. A piece with no
// vowel, the m and the p of the English {m·a·p}, takes the vowel of its word.
const syllables = (text) => text.replace(/(\p{L} )?\{([\p{L}·]+)\}/gu, (_, before = '', word) =>
  before + word.split('·').map((s) => chipOf(s, vowel(s + word), before && '-frase')).join(''));

Ингредиенты

Шрифты
Andika, DynaPuff, Playpen Sans (SIL OFL 1.1)
Материалы
  • man-640.jpg
  • mano-640.jpg
  • manzana-480.jpg
  • mapa-640.jpg
  • mariposa-660.jpg
  • mat-640.jpg
  • mesa-640.jpg
  • mimosa-640.jpg
  • mono-640.jpg
  • moon-480.jpg
  • mop-640.jpg
  • mud-640.jpg
  • mug-640.jpg
  • muneca-640.jpg
  • A watercolour of the butterfly on the opener (Generated With Diffusion Models, оригинал)
  • A watercolour of the apple on the opener (Generated With Diffusion Models, оригинал)
  • A watercolour of the hand in the picture grid (Generated With Diffusion Models, оригинал)
  • A watercolour of the map in the picture grid of both units (Generated With Diffusion Models, оригинал)
  • A watercolour of the table in the picture grid (Generated With Diffusion Models, оригинал)
  • A watercolour of the mimosa sprig in the picture grid (Generated With Diffusion Models, оригинал)
  • A watercolour of the monkey: in the picture grid of the Spanish unit and on the opener of the English one (Generated With Diffusion Models, оригинал)
  • A watercolour of the doll in the picture grid (Generated With Diffusion Models, оригинал)
  • A watercolour of the moon on the opener of the English unit (Generated With Diffusion Models, оригинал)
  • A watercolour of the mat in the picture grid of the English unit (Generated With Diffusion Models, оригинал)
  • A watercolour of the man in the picture grid of the English unit (Generated With Diffusion Models, оригинал)
  • A watercolour of the mug in the picture grid of the English unit (Generated With Diffusion Models, оригинал)
  • A watercolour of the mop in the picture grid of the English unit (Generated With Diffusion Models, оригинал)
  • A watercolour of the mud in the picture grid of the English unit (Generated With Diffusion Models, оригинал)
  • The cream band, the activity icons and the tracing rows, drawn in code in the page’s palette (Ignacio Ferro, MIT)

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

#1 · Стиль плашки на гласную и функция, которая пишет плашки

Короткий ответ строит 21 стиль плашек, раскладывая один объект syllable. На каждую гласную есть залитый стиль для m, контурный стиль для остальных звуков, двойник -frase к каждому из этих десяти и pinta, контур, который ребёнок закрашивает. syllables() превращает {m·a·p} в три :chip[…] без промежутков, поэтому звуки слова касаются, а шов рисует белая рамка. Плашка берёт цвет своей гласной, а кусок без гласной, здесь m и p, берёт гласную слова, поэтому map красное от начала до конца. Через межсловный пробел плашка держит не меньше своего gap, и 0,5 em ставит слова строки кеглем 24 пт в 4,2 мм друг от друга, а один пробел оставляет 2,3 мм. Внутри предложения этот промежуток почти удвоил бы пробел перед новым словом, поэтому слово, идущее за другим, берёт двойники -frase, чей gap, равный 0, оставляет пробел 2,3 мм как есть. В испанской версии куски — слоги, {mi·mo·sa}, и у каждого своя гласная.

#2 · Интерлиньяж с местом для плашек

script.js · строки 144–154в полном коде
  // A 24 pt chip is 10.4 mm tall: at 30 pt (10.6 mm) leading the chips of two sentences would
  // stand 0.1 mm apart, so every line the child reads has 45 pt, and the syllables 60 pt.
  paragraphStyles: [
    { id: 'consigna', fontFamily: LABEL, fontSize: pt(10), lineHeight: pt(GRID),
      color: col('muted') }, // the instruction under each activity
    { id: 'fila', fontSize: pt(34), lineHeight: pt(4 * GRID), textAlign: 'center' },
    { id: 'palabras', fontSize: pt(24), lineHeight: pt(3 * GRID), textAlign: 'center' },
    { id: 'lectura', fontSize: pt(24), lineHeight: pt(3 * GRID) },
    { id: 'colofon', fontSize: pt(7.5), lineHeight: pt(10), // Andika: Playpen has no italic
      color: col('muted'), marginTop: pt(GRID) },
  ],

Вертикальные отступы и рамка плашки рисуются за пределами строки и интерлиньяж не увеличивают, поэтому плашка выше шага строк заезжает на плашки строки ниже. Плашка кегля 24 пт имеет высоту 10,4 мм; при интерлиньяже 30 пт (10,6 мм) плашки двух предложений стояли бы в 0,1 мм друг от друга. Строки, которые читает ребёнок, получают 45 пт, а строки 34 пт первого упражнения — 60 пт, то есть три и четыре строки сетки 15 пт, на которой набраны задания.

#3 · Картинка в каждой ячейке

script.js · строки 96–109в полном коде
const PICTURE_WORDS = t({ en: ['m·a·p', 'm·a·t', 'm·a·n', 'm·u·g', 'm·o·p', 'm·u·d'],
  es: ['ma·no', 'ma·pa', 'me·sa', 'mi·mo·sa', 'mo·no', 'mu·ñe·ca'] });
const tableStyles = [{ id: 'dibujos', borderRadius: mm(5), // the frame and its fills, rounded
  headerBackgroundEnabled: false, // a header row added later would print grey (#f0f0f0)
  bodyBackgroundEnabled: true, bodyBackground: col('cream'), // cream tiles…
  rules: 'grid', borderColor: col('paper'), borderWidth: pt(4), // …parted by white rules
  bodyFontSize: pt(20), cellPadding: mm(3) }]; // the words' chips are 20 pt
const cells = (row) => PICTURE_WORDS.slice(row * 3, row * 3 + 3)
  .map((word) => ({ content: syllables(`{${word}}`), align: 'center' }));
let grid = { columnWidths: [1, 1, 1], rows: [cells(0), cells(1)] };
PICTURE_WORDS.forEach((word, k) => { // the picture above the word, 0.72 of the cell's width
  const resourceId = word.replaceAll('·', '').replace('ñ', 'n');
  grid = setCellImage(grid, { row: Math.floor(k / 3), col: k % 3 }, { resourceId, width: 0.72 });
});

setCellImage ставит картинку над текстом ячейки в доле внутренней ширины ячейки, здесь 0,72 (36,5 мм), и строка растёт под неё. Каждая картинка — JPEG на белом, умноженный на кремовый цвет плиток, поэтому она лежит на плитке без рамки. Под картинкой слово в звуковых плашках. Ячейка таблицы принимает разметку плашек, как любой абзац. Стиль таблиц dibujos скругляет рамку и заливки на 5 мм и делит кремовые плитки белыми линейками 4 пт.

#4 · Строка пустого места перед врезкой

script.js · строки 157–169в полном коде
  calloutStyles: [
    { id: 'colorea', background: col('cream'), borderRadius: mm(4),
      marginTop: pt(0), // the :::space before the box is the whole gap above it
      padding: { top: mm(4), right: mm(5), bottom: mm(5), left: mm(5) },
      titleStyle: { fontFamily: LABEL, fontSize: pt(15), fontWeight: 700, color: col('ink') },
      body: { fontFamily: LABEL, fontSize: pt(10), lineHeight: pt(GRID), color: col('muted') } },
    { id: 'familia', backgroundEnabled: false,
      stripe: { enabled: true, side: 'top', width: pt(2.5), color: col('rule') },
      padding: { top: mm(3), right: mm(0), bottom: mm(0), left: mm(0) },
      titleStyle: { fontFamily: LABEL, fontSize: pt(8.5), fontWeight: 700, color: col('ink'),
        ...tag },
      body: { fontSize: pt(10.5), lineHeight: pt(GRID) } },
  ],

Markdown ставит :::space{lines=1} между последним предложением и врезкой для раскраски, одну строку 15 пт (5,3 мм). marginTop врезки равен 0, поэтому эта строка и есть весь промежуток; без неё врезка начиналась бы сразу под строкой последнего предложения. :::space в начале врезки отбрасывается, поэтому врезка начинается со строки задания и плашек цветового ключа, а собственный :::space идёт после них, между ключом и раскраской.

#5 · Начальная полоса буквы

script.js · строки 60–79в полном коде
const THINGS = t({ en: ['monkey', 'moon'], es: ['mariposa', 'manzana'] }); // ids and labels
const BAND = 104; // mm: the depth of the band's drawing; its wave dips to 101.9 mm
// The opener reserves seventeen grid lines, the first grid line past the foot of the band's
// image, so the first activity title stands on the grid like the others: two lines under
// the band, its instruction right under it.
const opener = { enabled: true, minHeight: pt(17 * GRID),
  slot: { elements: [
    picture('band', 'banda', at(0, 0, { width: mm(210), height: mm(BAND) })),
    words('unit', '{attr.unit}', LABEL, 9, 700, 'paper', at(SIDE, 12.5), { ...tag,
      box: { backgroundColor: col('ink'), borderRadius: mm(3),
        padding: { top: mm(1.2), right: mm(2.8), bottom: mm(1.2), left: mm(2.8) } } }),
    words('kicker', '{attr.kicker}', LABEL, 8.5, 600, 'muted', // level with the pill's text
      { anchor: { to: '#unit', edge: 'right-of' }, offset: { x: mm(4), y: mm(1.4) } }, tag),
    words('letter', '{titleText}', DISPLAY, 190, 700, 'ink', at(SIDE - 3, 19), { lineHeight: 1 }),
    words('name', '{attr.name}', LABEL, 20, 600, 'ink', at(SIDE + 1, 76)),
    picture('first', THINGS[0], at(146, 12, { width: mm(40) })),
    picture('second', THINGS[1], at(151, 53, { width: mm(30) })),
    ...[45.5, 84.5].map((y, k) => words(THINGS[k], THINGS[k], LABEL, 10, 600, 'muted',
      at(146, y, { width: mm(40) }), { align: 'center' })), // its name under each picture
  ] } };

Mm — текст заголовка ({titleText}); номер урока, серия и имя под буквой — атрибуты той же строки. Полоса, обезьяна и луна — изображения. Полоса высотой 104 мм, и начальная полоса резервирует страницу до первой линии сетки под её низом, поэтому название первого упражнения начинается на 118,5 мм, на сетке и в 16,6 мм под нижней точкой волны (101,9 мм).

#6 · Значки рядом с названиями упражнений

script.js · строки 83–92в полном коде
const ICON = 9; // mm
const H2 = { level: 2, marginBottom: pt(0), // two grid lines per title, and two above it
  lineHeight: pt(2 * GRID), marginTop: pt(2 * GRID) };
const activity = (id, icon) => ({ id, advancedDesign: { enabled: true, slot: { elements: [
  picture('icon', icon, { anchor: { to: 'container', edge: 'top-left' },
    size: { width: mm(ICON), height: mm(ICON) } }),
  words('title', '{titleText}', LABEL, 15, 700, 'ink', { anchor: { to: '#icon',
    edge: 'right-of' }, offset: { x: mm(3) }, size: { width: mm(140), height: mm(ICON) } },
  { verticalAlign: 'middle' }), // centred on the icon
] } } });

Каждое название упражнения указывает стиль заголовка, например ## Read the sentences {style="lee"}, и стиль рисует значок с названием, центрированным рядом с ним. Названия остаются заголовками второго уровня, поэтому отступы задаёт уровень H2: две линии сетки lineHeight на название и ещё две marginTop над ним.

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

Sandbox
// ═══ Postext Cookbook · Nº 060 · Early reader with syllable chips ════════════════
// https://postext.dev/en/cookbook/reading-primer-syllables
// Code: MIT · Text: original (CC BY 4.0) · Pictures: diffusion models · Icons: drawn in code
// Fonts: Andika, DynaPuff, Playpen Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage, setCellImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'reading-primer-syllables';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#242832', paper: '#ffffff', muted: '#5f6470', // text; instructions
  cream: '#f6f0e3', rule: '#d3c9b6', // the band, the tiles and the pictures' ground; guides
  // The vowel code: a syllable takes its vowel's colour. White on these fills measures
  // 3.2–4.9:1, above WCAG's 3:1 for large text: the vowel chips are bold, 20 pt or more.
  a: '#d9482b', e: '#dd740c', i: '#1f9a8f', o: '#3f6fd8', u: '#9152cf' };
// Every colour is linked to its palette entry by id.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults are linked to 'main-color': point it at the ink.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.ink })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, LABEL] = ['Andika', 'DynaPuff', 'Playpen Sans']; // Andika: one-storey a
const [TOP, SIDE, GRID] = [18, 20, 15]; // mm, mm, pt: every activity starts on the 15 pt grid

// #region answer: one chip style per vowel, and {ma·má} in the text written out as chips
// A word's syllables are chips with nothing between them, so their boxes touch and the white
// border draws the seam. Across a word space a chip keeps at least `gap`: 0.5 em sets the
// words of a 24 pt row 4.2 mm apart, where the space alone leaves 2.3 mm. Inside a sentence
// the '-frase' twins keep no gap, so the word space alone parts a chip from the word before.
// A 24 pt chip, padding and border included, is 10.4 mm tall (gotcha: chip-overlap).
const syllable = { fontFamily: TEXT, bold: true, borderWidth: pt(1), borderColor: col('paper'),
  paddingX: em(0.26), paddingY: em(0.05), gap: em(0.5) };
const chipStyles = [
  ...'aeiou'.split('').flatMap((v) => [ // one pair per vowel
    { ...syllable, id: v, background: col(v), color: col('paper') }, // a syllable with m
    { ...syllable, id: `${v}-borde`, background: col('paper'), color: col(v), borderColor: col(v) },
  ]).flatMap((style) => [style, { ...style, id: `${style.id}-frase`, gap: em(0) }]),
  { ...syllable, id: 'pinta', bold: false, background: col('paper'), color: col('ink'),
    borderColor: col('ink'), borderWidth: pt(0.8) }, // an outline for the child to colour in
];
const vowel = (s) => s.normalize('NFD').toLowerCase().match(/[aeiou]/)[0]; // 'mú' → 'u'
const chipOf = (s, v, end) => `:chip[${s}]{style="${v}${/m/i.test(s) ? '' : '-borde'}${end}"}`;
// {mi·mo·sa} → :chip[mi]{style="i"}:chip[mo]{style="o"}:chip[sa]{style="a-borde"}, and a word
// written after another word, as in 'me {mi·ma}.', takes the '-frase' twins. A piece with no
// vowel, the m and the p of the English {m·a·p}, takes the vowel of its word.
const syllables = (text) => text.replace(/(\p{L} )?\{([\p{L}·]+)\}/gu, (_, before = '', word) =>
  before + word.split('·').map((s) => chipOf(s, vowel(s + word), before && '-frase')).join(''));

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

Варианты

#Скруглите плашки до пилюль

Радиус больше половины высоты плашки ограничен этой половиной, поэтому большое значение рисует круглые концы. Плашка из одной буквы выходит почти кругом, а швы внутри слова становятся выемками.

-  paddingX: em(0.26), paddingY: em(0.05), gap: em(0.5) };
+  paddingX: em(0.26), paddingY: em(0.05), gap: em(0.5), borderRadius: em(1) };

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

Подводный камень

Плашки выше шага строк касаются следующей строки

Плашка, рамка которой выше шага строк, касается плашек следующей строки (предупреждение chipOverlap). Уменьшите её вертикальные внутренние отступы, обводку или кегль либо увеличьте интерлиньяж. Плашки в строке →

Подводный камень

:::space пропадает вверху врезки или колонки

:::space пропадает вверху колонки, группы :::columns, врезки без заголовка, в которой есть другое содержимое, и продолжения разделённой врезки. Начиная с postext 1.5 врезка из одного :::space имеет высоту, которую он просит (рамка для ответа, место для записи), а отбивка сразу под заголовком врезки на столько же опускает начало текста. Чтобы начать врезку без заголовка с отбивки, дайте ей заголовок или первую строку и добавьте отбивку после них. Явный вертикальный отступ →

Проверка Sandbox · chipOverlap

Плашки касаются следующей строки

Причина. Рамка стиля плашки выше шага строк, поэтому плашки в соседних строках соприкасаются.

Решение. Уменьшите вертикальные отступы, контур или размер плашки либо увеличьте интерлиньяж. Документация →

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • A watercolour of the butterfly on the opener · Generated With Diffusion Models · оригинал
  • A watercolour of the apple on the opener · Generated With Diffusion Models · оригинал
  • A watercolour of the hand in the picture grid · Generated With Diffusion Models · оригинал
  • A watercolour of the map in the picture grid of both units · Generated With Diffusion Models · оригинал
  • A watercolour of the table in the picture grid · Generated With Diffusion Models · оригинал
  • A watercolour of the mimosa sprig in the picture grid · Generated With Diffusion Models · оригинал
  • A watercolour of the monkey: in the picture grid of the Spanish unit and on the opener of the English one · Generated With Diffusion Models · оригинал
  • A watercolour of the doll in the picture grid · Generated With Diffusion Models · оригинал
  • A watercolour of the moon on the opener of the English unit · Generated With Diffusion Models · оригинал
  • A watercolour of the mat in the picture grid of the English unit · Generated With Diffusion Models · оригинал
  • A watercolour of the man in the picture grid of the English unit · Generated With Diffusion Models · оригинал
  • A watercolour of the mug in the picture grid of the English unit · Generated With Diffusion Models · оригинал
  • A watercolour of the mop in the picture grid of the English unit · Generated With Diffusion Models · оригинал
  • A watercolour of the mud in the picture grid of the English unit · Generated With Diffusion Models · оригинал
  • The cream band, the activity icons and the tracing rows, drawn in code in the page’s palette · Ignacio Ferro · MIT
Шрифты
Andika (SIL OFL 1.1) · DynaPuff (SIL OFL 1.1) · Playpen Sans (SIL OFL 1.1)
Sandbox