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

Рецепты · Глава 1 · Страница и сетка

Вестник сообщества: главная статья и заметки

Вестник садового общества в полторы колонки: главная статья в широкой и продолжается на странице 2; разрывы колонок ведут заметки в узкую.

На этой странице
  • Образец на английском: русского издания пока нет
  • Обрезной формат 210 × 297 мм
  • Полторы колонки, средник 8 мм
  • Work Sans 9,4/13,4
  • Courier Prime
  • Titan One
  • 2 страницы
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 55 мс
  • Строк кода: 168

Коротко

Вестник клуба садоводов на двух страницах. Главная статья занимает широкую колонку и продолжается на странице 2, а короткие новости стоят в узкой колонке рядом.

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

Весенний номер The Allotment Gazette, вестника вымышленного общества садоводов, на двух сторонах листа A4. Соломенная полоса несёт название шрифтом Titan One в две строки, ряд всходов по низу и томатный ярлык с номером выпуска и сезоном. Ниже страница делится на колонки 113 и 57 мм. Главная статья, о трёх новых компостных отсеках, занимает широкую колонку под планом участка, нарисованным кодом, и останавливается на плашке «Continued on page 2». В узкой колонке пять заметок, каждую открывают плашки-капсулы. Страница 2 подхватывает статью под заголовком продолжения и ставит график температуры по центру колонки. Дальше абзац о грядке идёт рядом с её рисунком у правого края колонки. Восемь объявлений заполняют узкую колонку.

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

  • Как сделать полосу в полторы колонки: широкая колонка текста и узкая боковая?
  • Можно ли в Postext набрать три и более колонок или обтекание изображения текстом?
  • Как разместить две колонки внутри врезки (колонка текста рядом с колонкой рисунка)?
  • Как сделать плашки в строке: клавиши, теги, банки слов для упражнений?

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

script.js · строки 33–49в полном коде
const layout = {
  layoutType: 'oneAndHalf', // the narrow column sits on the right and takes text (the
  // defaults of sideColumnSide and sideColumnRole; 'floats' would keep text out of it)
  sideColumnPercent: 32, // 57 mm of the 178 mm measure
  gutterWidth: mm(8), // the wide column keeps the other 113 mm
  columnRule: { enabled: true, color: col('rule') }, // a 0.5 pt hairline in the gutter
};
// The text runs down the wide column, then the narrow one, then the next page's wide
// column. A :::columnbreak sends the next block on to the following column, so the
// Markdown decides what each column holds:
//   ## Shared compost bays open by the top gate      ← the lead, in the wide column
//   … :chip[Continued on page 2]{style="jump"}
//   :::columnbreak                                    ← the briefs open the narrow column
//   ## In brief {style="rail"}
//   …
//   :::columnbreak                                    ← from the last column: next page
//   :chip[Continued from page 1]{style="jump"}        ← the lead goes on in the wide column

Ингредиенты

Возможности
Полторы колонкиРазрывы страниц и колонокПлашки в строкеОбтекание иллюстраций и врезок текстомСтили заголовковРазмещение рисунковВрезкиРисунки точно здесьЛинейка между колонкамиМетаданные документаОформленные начальные полосыАтрибуты заголовковКолонтитулы и колонцифрыКолонтитулы по роли страницыСтили абзацевСобственные типы ресурсовИсточники и авторыСемантическая палитраСтраницы на холстеРисунки и таблицы как ресурсы
Шрифты
Work Sans, Titan One, Courier Prime (SIL OFL 1.1)
Материалы
  • The site plan, the temperature chart, the square-metre bed and the row of seedlings under the nameplate, drawn in code in the page's palette (Ignacio Ferro, CC BY 4.0)

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

#1 · Markdown заполняет каждую колонку

Настройки вёрстки — в разделе «Короткий ответ» выше. В вёрстке oneAndHalf узкая колонка по умолчанию принимает текст, и он идёт по широкой, затем по узкой, затем по широкой следующей страницы (типы вёрстки). :::columnbreak завершает колонку там, где стоит (директивы): после плашки «Continued on page 2» он открывает узкую колонку для заметок, а после последней заметки, в последней колонке страницы, — страницу 2. В этом номере обе колонки страницы 1 подогнаны так, что кончаются на одной линии сетки, в 275 мм от верхнего края, поэтому без любого из разрывов страницы не изменятся. Разрывы понадобятся, когда сменится текст. Удалите второй абзац главной статьи, и без первого разрыва «In brief» начнётся в широкой колонке на 247 мм, под плашкой, а первая заметка перейдёт в узкую, где её вторая половина заново разобьётся на строки по 57 мм.

#2 · Собрать шапку из метаданных

script.js · строки 53–75в полном коде
const BEARING = 0.6; // mm: Titan One's left side bearing at 60 pt (T 0.42, G 0.63, L/H 0.85)
const DRILL = { id: 'drill', typeId: 'drawing', kind: 'svg', createdAt: 0, updatedAt: 0,
  svg: { fileId: 'drill.svg', width: 2100, height: 80 } }; // drawn by the design, not the text
const masthead = { enabled: true,
  minHeight: pt(10 * LEAD), // ten grid lines: the text starts one line clear of the band
  slot: { elements: [
    // The band is 62 mm deep. The column rule starts under the masthead, where the text does.
    { kind: 'box', id: 'band', style: { backgroundColor: col('straw') },
      placement: { ...at('page', 'top-left'), size: { width: mm(210), height: mm(62) } } },
    { kind: 'image', id: 'drill', resourceId: 'drill', // seedlings along the band's foot
      placement: { ...at('page', 'top-left', 0, 54), size: { width: mm(210), height: mm(8) } } },
    { kind: 'text', id: 'society', content: '{subtitle}', ...caps(8, 'leaf'), align: 'left',
      placement: { ...at('page', 'top-left', SIDE, 12), size: { width: mm(150) } } },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(60),
      lineHeight: 0.9, // 54 pt from line to line
      color: col('leaf'), align: 'left', overflow: 'wrap', // two lines in 178 mm
      placement: { ...at('page', 'top-left', SIDE - BEARING, 17), size: { width: mm(178) } } },
    // {attr.issue} comes from the H1 line, {publishDate} from the frontmatter.
    { kind: 'text', id: 'tab', content: '{attr.issue} · {publishDate}', ...caps(9, 'paper'),
      align: 'right', box: { backgroundColor: col('tomato'),
        padding: { top: mm(1.8), right: mm(3.2), bottom: mm(1.6), left: mm(3.2) } },
      placement: at('page', 'top-right', -SIDE, 44) },
  ] } };

H1 берёт стиль заголовка, дизайн которого рисует шапку, а span: 'page' ставит этот дизайн над обеими колонками. {titleText} кеглем 60 пт разбивается на две строки в своём прямоугольнике 178 мм. Ярлык соединяет {attr.issue}, записанный в строке H1, и {publishDate} из метаданных (текстовые элементы). Без minHeight шапка зарезервировала бы место до низа полосы, 62 мм от верхнего края, и текст начался бы на следующей линии сетки, 62,5 мм, вплотную к полосе. minHeight в десять линий сетки начинает его на 67 мм.

#3 · Пометить заметки плашками

script.js · строки 79–89в полном коде
const chip = (id, look) => ({ id, fontFamily: LABEL, bold: true,
  fontSize: pt(7.7), // in points: em(0.82) is 7.7 pt in the text, 6.6 pt on the 8 pt jump lines
  borderWidth: pt(0), borderRadius: em(1), // a radius past half the height draws a pill
  paddingX: em(0.5), paddingY: em(0.14), ...look }); // em: of the chip's own size
const chipStyles = [
  chip('tag', { background: col('tomato'), color: col('paper') }), // the first is the default
  chip('free', { background: col('marigold'), color: col('ink') }),
  chip('when', { backgroundEnabled: false, borderWidth: pt(0.8), borderColor: col('leaf'),
    color: col('leaf') }),
  chip('jump', { background: col('straw'), color: col('ink') }),
];

Объявление chipStyles заменяет встроенную бледно-голубую плашку, а плашка без style берёт первую из них (стили плашек). Радиус больше половины высоты рисует капсулу. Плашка никогда не разрывается внутри, поэтому строка разбивается только на пробеле до или после неё, и дата вроде «Sat 11 April» остаётся на одной строке. Теги набраны в Markdown прописными, потому что настройки регистра у стилей плашек нет. Вертикальный отступ рисуется за пределами строки, и сетка 13,4 пт сохраняется.

#4 · Пустить текст рядом с рисунком

script.js · строки 93–98в полном коде
// wrap sets the drawing at that side of its column, width of it, and the text after the
// ::resource line runs beside it at the measure left over, then under it at full width:
//   #### Sixteen squares by the gate {style="kicker"}
//   ::resource{id="bed"}                     ← 51 mm at the right of the 113 mm column
//   The demonstration bed by the gate is 1.2 metres square …   ← beside it, then under it
const WRAP = { wrap: 'right', width: 0.45 }; // a body line of white between it and the text

wrap: 'right' ставит рисунок грядки у правого края колонки 113 мм, шириной 45 % от неё (51 мм), а абзац после строки ::resource идёт рядом на оставшихся 57 мм, на строку текста отступив от рисунка и его подписи (обтекание). Верх рисунка стоит вровень с первой строкой абзаца, и каждая строка остаётся на сетке 13,4 пт. Более длинный абзац продолжился бы под рисунком на все 113 мм, одним абзацем; заголовок или другой рисунок, пришедший, пока рисунок ещё стоит рядом с текстом, ушёл бы под него. Заголовок четвёртого уровня над ним берёт стиль, который меняет только цвет на зелёный листьев.

#5 · Отцентрировать узкий график

script.js · строки 102–114в полном коде
const drawing = (id, w, h, placement = {}) => ({ id, typeId: 'drawing', kind: 'svg',
  svg: { fileId: `${id}.svg`, width: w * 10, height: h * 10 }, // mm × 10: fitted to the column
  placement: { position: 'here', ...placement }, // drawn where ::resource{id} stands
  caption: CAPTIONS[id][0], note: CAPTIONS[id][1], altText: CAPTIONS[id][2],
  createdAt: 0, updatedAt: 0 });
// width is a fraction of the column and align where the figure sits in it: the text above
// and below never moves into the white either side.
const HEAT = { width: 0.62, align: 'center' };
const resources = () => [drawing('plan', 114, 56.5), drawing('heat', 68, 40, HEAT),
  drawing('bed', 50, 50, WRAP), DRILL];
// Newsletter drawings carry no "Figure 1": an empty prefix prints no label.
const resourceTypes = [{ id: 'drawing', name: 'Drawing', shortLabel: 'Drawing',
  captionPrefix: '', numberingTemplate: '', resetOn: 'never', counterFormat: 'decimal' }];

width: 0.62 набирает график шириной 70,1 мм в колонке 113 мм, а align: 'center' оставляет по 21,5 мм бумаги с каждой стороны (размещение). Текст выше и ниже сохраняет полную ширину и никогда не затекает в этот пробел. Рисунки относятся к типу ресурсов с пустым captionPrefix, поэтому каждая подпись начинается собственными полужирными словами, без «Figure 1» перед ними.

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

Sandbox
// ═══ Postext Cookbook · Nº 042 · Community newsletter: lead story and briefs ═════
// https://postext.dev/en/cookbook/community-newsletter
// Code: MIT · Text: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: Work Sans, Titan One, Courier Prime (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts,
} from 'https://esm.sh/postext';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: garden colours, every one linked by id
// ink: text · leaf: nameplate and headlines · tomato, the accent: tags, tab, column heads ·
// straw: the band · marigold: second tag · tint: pale greens · rule: hairlines · muted: notes
const palette = { ink: '#1d211c', leaf: '#2f6b3a', tomato: '#c43f2a', straw: '#f2d492',
  marigold: '#e2b33c', tint: '#eef4e8', rule: '#cfd3c6', muted: '#5f6659', paper: '#fbfaf5' };
// Each colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [ // defaults link to 'main-color': point it at the leaf, never blue
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'leaf (defaults)', value: { hex: palette.leaf, model: 'hex' } },
];
// #endregion
const [TEXT, DISPLAY, LABEL] = ['Work Sans', 'Titan One', 'Courier Prime'];
const SIDE = 16; // mm: the side margins of one A4 sheet, printed on both sides
const LEAD = 13.4; // body leading in pt: the baseline grid
const caps = (size, colour) => ({ fontFamily: LABEL, fontSize: pt(size), fontWeight: 700,
  textTransform: 'uppercase', letterSpacing: pt(size * 0.12), color: col(colour) });
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });

// #region answer: a wide column for the lead, a narrow one for the briefs, one flow
const layout = {
  layoutType: 'oneAndHalf', // the narrow column sits on the right and takes text (the
  // defaults of sideColumnSide and sideColumnRole; 'floats' would keep text out of it)
  sideColumnPercent: 32, // 57 mm of the 178 mm measure
  gutterWidth: mm(8), // the wide column keeps the other 113 mm
  columnRule: { enabled: true, color: col('rule') }, // a 0.5 pt hairline in the gutter
};
// The text runs down the wide column, then the narrow one, then the next page's wide
// column. A :::columnbreak sends the next block on to the following column, so the
// Markdown decides what each column holds:
//   ## Shared compost bays open by the top gate      ← the lead, in the wide column
//   … :chip[Continued on page 2]{style="jump"}
//   :::columnbreak                                    ← the briefs open the narrow column
//   ## In brief {style="rail"}
//   …
//   :::columnbreak                                    ← from the last column: next page

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

Варианты

#Поставить заметки слева

Широкая колонка всё равно читается первой, поэтому тот же Markdown ставит главную статью справа, а заметки слева.

   layoutType: 'oneAndHalf',
+  sideColumnSide: 'left',

#Поставить заметки во всю ширину

Основной текст идёт самое большее в две колонки. Первая полоса газеты ставит четыре заметки внизу страницы во врезке с :::columns{count=4}.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • The site plan, the temperature chart, the square-metre bed and the row of seedlings under the nameplate, drawn in code in the page's palette · Ignacio Ferro · CC BY 4.0
Шрифты
Work Sans (SIL OFL 1.1) · Titan One (SIL OFL 1.1) · Courier Prime (SIL OFL 1.1)
Sandbox