# Mayakovsky's stepped verse, typed and set

> A whole Mayakovsky poem of 1929 in four red and black pages: every step typed with a plus sign, numbered by tens, and a closing sentence in a red field.

- HTML version: https://postext.dev/en/cookbook/stepped-verse-lesenka
- Recipe Nº 206 · Type & text · Level 2 (Intermediate) · Outputs: Canvas, PDF
- Genres: Poetry
- Requires postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · tested with 1.100.0, postext-pdf 1.100.0 on 2026-12-02
- Pages: [1](https://postext.dev/cookbook/stepped-verse-lesenka/en/p01.webp?v=1fb3da9a), [2](https://postext.dev/cookbook/stepped-verse-lesenka/en/p02.webp?v=1fb3da9a), [3](https://postext.dev/cookbook/stepped-verse-lesenka/en/p03.webp?v=1fb3da9a), [4](https://postext.dev/cookbook/stepped-verse-lesenka/en/p04.webp?v=1fb3da9a)
- Open in Sandbox: https://postext.dev/en/sandbox#recipe=stepped-verse-lesenka&lang=en (.postext: https://postext.dev/cookbook/stepped-verse-lesenka/en/stepped-verse-lesenka.postext)
- Last updated: 2026-12-02
- Other languages: [es](https://postext.dev/es/cookbook/stepped-verse-lesenka.md), [ca](https://postext.dev/ca/cookbook/stepped-verse-lesenka.md), [de](https://postext.dev/de/cookbook/stepped-verse-lesenka.md), [el](https://postext.dev/el/cookbook/stepped-verse-lesenka.md), [fr](https://postext.dev/fr/cookbook/stepped-verse-lesenka.md), [it](https://postext.dev/it/cookbook/stepped-verse-lesenka.md), [pt](https://postext.dev/pt/cookbook/stepped-verse-lesenka.md), [ru](https://postext.dev/ru/cookbook/stepped-verse-lesenka.md), [zh](https://postext.dev/zh/cookbook/stepped-verse-lesenka.md), [ja](https://postext.dev/ja/cookbook/stepped-verse-lesenka.md), [ar](https://postext.dev/ar/cookbook/stepped-verse-lesenka.md)

## In short

A famous Soviet poem whose lines go down the page like a staircase. Each step starts where the one above it ends, and the pages are printed in red and black like the posters of its time.

## What you'll build

*Стихи о советском паспорте* (*Verses on My Soviet Passport*, 1929), complete, on four pages of 170 × 260 mm. Mayakovsky broke his lines into steps, each one starting where the last one stopped, and the Complete Works count every step as a line. The poem runs 43, 43 and 29 steps to a page in Golos Text at 12.5 on 14.6 pt, with the phrases that name the passport in heavy red. The last sentence stands in a red field at the foot of page 4. The cover, the folio tabs and the field are flat shapes in black, red and raw paper, after El Lissitzky's layouts for Mayakovsky.

**This recipe answers:**

- How do I set stepped verse, Mayakovsky's lesenka, so each step starts where the last one ended?
- How do I set poetry: one line per verse, stanza gaps, hanging indents for wrapped lines, no hyphenation?

## The short answer

Each step on its own line, led by a plus sign.

```js
// script.js, lines 46–66
// A line of verse typed as the book prints it, its steps marked +:
//   К любым
//   + чертям с матерями
//   + катись
// A step starts a word space after the end of the step above, so the steps keep the rhyme's
// line whole whatever the face or the size. They are lines: nothing joins them or divides
// them, and they are not hyphenated. A step that would run past the measure moves back until
// it fits; one wider than the whole measure turns over, `hang` in from its own start.
// align=start on the fence sets the poem flush left; by default it is centred.
const LOCALE = 'ru';
const verse = { turnover: 'hang', hang: em(2), tighten: true }; // config().bodyText.verse
const paragraphStyles = [
  { id: 'step', fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    textAlign: 'left', indent: mm(38), firstLineIndent: pt(0),
    marginTop: pt(0), marginBottom: pt(0) },
  { id: 'shout', fontFamily: DISPLAY, fontWeight: 900, fontSize: pt(29), lineHeight: pt(27),
    color: col('paper'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(0),
    marginBottom: pt(0) },
  { id: 'colophon', fontSize: pt(7.6), lineHeight: pt(10), color: col('paper'),
    textAlign: 'left', firstLineIndent: pt(0), hyphenation: { enabled: false } },
];
```

## Ingredients

**Teaches**

- [Verse line by line](https://postext.dev/en/docs/document-format-directives.md#verse): :::verse sets a poem as it is written: one line of verse a line of Markdown, blank lines between stanzas, leading spaces as indents; an overlong line turns over with a hanging indent or flush right behind a bracket, never parted from its line at a page break, and short stanzas can be kept whole.
- [Cyrillic languages as the document language](https://postext.dev/en/docs/cyrillic-layout.md#starting-a-book-in-cyrillic): locale 'ru', 'uk', 'be', 'bg', 'sr', 'mk', 'kk', 'ky', 'tt', 'ba', 'tg' or 'mn' gives a book the hyphenation, captions, table titles, notes, number words, sheet formats and spine lettering of its language.
- [Text, rules and boxes in page designs](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers): The drawing elements shared by headers, footers, openers and part pages: text with an optional pill, horizontal and vertical rules, and filled or framed boxes painted in array order.

**Also uses**

- [Words kept together at line ends](https://postext.dev/en/docs/cyrillic-layout.md#words-kept-together)
- [Line numbers](https://postext.dev/en/docs/configuration-notes-references.md#line-numbers)
- [Designed openers](https://postext.dev/en/docs/configuration-headings.md#span-and-advanced-design)
- [Heading styles](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Heading attributes](https://postext.dev/en/docs/document-format.md#heading-attributes)
- [Covers, title pages and colophons](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Character styles](https://postext.dev/en/docs/document-format-inline.md#character-styles)
- [Paragraph styles](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles)
- [Pinned boxes and badges](https://postext.dev/en/docs/configuration-callouts.md#the-callout-container)
- [Callout boxes](https://postext.dev/en/docs/configuration-callouts.md#callout-styles)
- [Trim size](https://postext.dev/en/docs/configuration-page-layout.md#page-size-presets)
- [Document metadata](https://postext.dev/en/docs/document-format.md#frontmatter)
- [Semantic colour palette](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette)
- [PDF export](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs)
- [Fonts embedded in the PDF](https://postext.dev/en/docs/configuration-pdf-output.md#why-a-font-provider)
- [Paper colour](https://postext.dev/en/docs/configuration-page-layout.md#page)
- [Page and column breaks](https://postext.dev/en/docs/document-format-directives.md#pagebreak)
- [Heads by page role](https://postext.dev/en/docs/configuration-headers-footers.md#text-elements)
- [Line breaks in titles](https://postext.dev/en/docs/document-format-directives.md#line-breaks-in-titles)
- [Unnumbered chapters](https://postext.dev/en/docs/configuration-styles.md#heading-styles)

**Config at a glance**

- [`bodyText`](https://postext.dev/en/docs/configuration-text.md#body-text), [`calloutStyles`](https://postext.dev/en/docs/configuration-callouts.md#callout-styles), [`characterStyles`](https://postext.dev/en/docs/configuration-styles.md#character-styles), [`colorPalette`](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette), [`footer`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`header`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`headingStyles`](https://postext.dev/en/docs/configuration-styles.md#heading-styles), [`headings`](https://postext.dev/en/docs/configuration-headings.md#headings), [`layout`](https://postext.dev/en/docs/configuration-page-layout.md#layout), [`lineNumbers`](https://postext.dev/en/docs/configuration-notes-references.md#line-numbers), [`locale`](https://postext.dev/en/docs/configuration-language.md#hyphenation), [`page`](https://postext.dev/en/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles)

**APIs**

- [`buildDocumentWithFonts`](https://postext.dev/en/docs/configuration-programmatic-usage.md#loading-fonts-before-layout), [`decompressWoff2`](https://postext.dev/en/docs/configuration-pdf-output.md#browser-font-provider-fontsource--woff2), [`renderPageToCanvas`](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap), [`renderToPdf`](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs)

**Typefaces**

- Golos Text (OFL-1.1), Sofia Sans Extra Condensed (OFL-1.1)

## Method

### 1 · Type every step with a plus sign

The code is [the short answer](https://postext.dev/en/cookbook/stepped-verse-lesenka.md#the-short-answer) above. Inside a [`:::verse`](https://postext.dev/en/docs/document-format-directives.md#verse) fence, the first step of a line is typed as it is and each of the others starts with `+ `. The engine places it a word space after the end of the step above. Nothing has to be counted in spaces or tabs, so another face or size moves the whole staircase with it. A step that would cross the measure moves back until it fits; only a step wider than the measure itself turns over, and it hangs below its own start.

### 2 · Raise the voice in red

```js
// script.js, lines 70–70
const characterStyles = [{ id: 'loud', name: 'Loud', fontWeight: 900, color: col('red') }];
```

The books Lissitzky designed for Mayakovsky shout with weight and colour. A [character style](https://postext.dev/en/docs/configuration-styles.md#character-styles) does it here: `:span[Но эту…]{style="loud"}` takes Golos Text 900 and the red, and since the next step is measured from its end, the staircase stays true.

### 3 · Number every tenth step

```js
// script.js, lines 74–76
const lineNumbers = { enabled: true, count: 'verse', restart: 'document', interval: 10,
  position: 'left', gap: mm(-32), // the column starts at the trim: 32 mm in from its edge
  fontFamily: DISPLAY, fontWeight: 900, fontSize: pt(13), color: col('red') };
```

[`lineNumbers`](https://postext.dev/en/docs/configuration-notes-references.md#line-numbers) counts the lines of a poem, and a step is a line. The poem is written as one fence a page, so `lineStart=44` and `lineStart=87` go on with the count. The column starts at the trim, which lets the red field bleed; the paragraph style indents the verse 38 mm and a negative `gap` brings the numbers in.

### 4 · Draw the cover with paths

```js
// script.js, lines 80–99
const P = [60, 78]; // the passport's top corner
const flat = { pages: 'opener' }; // the shapes: in the header slot, for the cover alone
const cover = { id: 'cover', numbered: false, breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, slot: { elements: [
    text('year', '{attr.year}', 28, 'ink', at('page', 'top-right', -14, 15)),
    text('one', '{attr.one}', 52, 'ink', at('page', 'top-left', 14, 182)),
    text('two', '{attr.two}', 52, 'red', { ...at('#one', 'right-of', 3, 17) }),
    text('three', '{attr.three}', 118, 'ink', at('page', 'bottom-left', 14, -12)),
  ] } } };
const coverShapes = [
  poly('field', 'ink', [[0, 0], [124, 0], [0, 176]], flat),
  disc('sun', 'paper', 88, 92, 52, flat),
  bar('ray', 'ink', -6, 180, 190, 3, flat),
  bar('passport', 'red', ...P, 74, 100, flat),
  disc('seal', 'paper', ...on(...P, 37, 39), 17, flat),
  disc('eye', 'ink', ...on(...P, 37, 39), 9, flat),
  ...[48, 36, 24].map((len, i) =>
    bar(`line-${i}`, 'paper', ...on(...P, 13, 68 + 9 * i), len, 4, flat)),
  text('author', '{author}', 26, 'paper', at('page', 'top-left', 14, 15), flat),
];
```

[Path elements](https://postext.dev/en/docs/configuration-headers-footers.md#path-elements) take points in millimetres through a `viewBox` the size of the page. Paths are not rotated, so `bar` works out its four corners on a slant of 17 degrees. The shapes live in the header slot with `pages: 'opener'`, since a heading's design is clipped at the foot of the text area. The title steps too: *о советском* is anchored to the right of *Стихи*.

### 5 · Set the folio in a thumb tab

```js
// script.js, lines 103–113
const tab = (parity, edge, x) => [
  { kind: 'box', id: `tab-${parity}`, parity, pages: 'body', style: { backgroundColor: col('ink') },
    placement: { ...at('page', edge, 0, 22), size: { width: mm(13), height: mm(20) } } },
  text(`folio-${parity}`, '{pageNumber}', 26, 'paper', at('page', edge, x, 28),
    { parity, pages: 'body' }),
];
const header = { elements: [...coverShapes, ...tab('even', 'top-left', 4.6),
  ...tab('odd', 'top-right', -4.6)] };
const LINES = 43; // three pages of 43, 43 and 29 steps, and five in the red field
const margins = { top: mm(22), bottom: mm(H - 22 - (LINES * LEAD * 25.4) / 72 - 0.1),
  left: mm(0), right: mm(0) };
```

A black box flush with the fore-edge carries the page number, left on versos and right on rectos, in memory of the cut thumb index of *For the Voice*. `pages: 'body'` keeps it off the cover.

### 6 · Close in a red field

```js
// script.js, lines 117–121
const box = (id, y, top, bottom) => ({ id, placement: 'fixed', background: col('red'),
  fixed: { anchor: { to: 'page', edge: 'bottom-left' }, offset: { x: mm(0), y: mm(y) } },
  stripe: { enabled: false },
  padding: { top: mm(top), right: mm(14), bottom: mm(bottom), left: mm(14) } });
const calloutStyles = [box('finale', -20.6, 10, 5), box('colophon', 0, 2, 8)];
```

The last five steps are a `:::callout` of their own, fixed to the foot of the page and as wide as it. The fence inside takes the `shout` style: Sofia Sans Extra Condensed 900 at 29 pt. The colophon is a second box under it, and the strip of paper between the two is the white line of a poster.

## The whole recipe

One file, composed from the recipe's folder with the sample text and the Cookbook's shared kit inlined; it builds its own page. To run it, put it in a `<script type="module">` on an empty page, or paste it into the JS panel of a new CodePen (as a module). It imports postext from esm.sh, so there is nothing to install or build.

- Source folder: https://github.com/drnachio/postext/tree/main/cookbook/stepped-verse-lesenka

### script.js

```js
// ═══ Postext Cookbook · Nº 206 · Mayakovsky in steps: the lesenka as he printed it ═════
// https://postext.dev/en/cookbook/stepped-verse-lesenka
// Code: MIT · Text: V. Mayakovsky, Стихи о советском паспорте, 1929 (PD; PSS, vol. 10)
// Fonts: Sofia Sans Extra Condensed, Golos Text (SIL OFL 1.1) · Needs postext ≥ 1.100.0
import { buildDocumentWithFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the colophon ('en' | 'es' | 'ru')
const RECIPE = 'stepped-verse-lesenka';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Two inks on a raw paper, as the Constructivists printed: black, vermilion, no third.
const palette = {
  ink: '#171412', // the verse, the fields
  red: '#c9281b', // the passport, the loud steps, the last page
  paper: '#f0e7d6', // an unbleached stock
};
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: 'red (defaults)', value: { hex: palette.red, model: 'hex' } },
];
const [TEXT, DISPLAY] = ['Golos Text', 'Sofia Sans Extra Condensed'];
const [BODY, LEAD] = [12.5, 14.6]; // pt
const [W, H] = [170, 260]; // mm: the sheet 70 × 108/16 of GOST 5773
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, size, color, placement, extra = {}) => ({ kind: 'text', id, content,
  fontFamily: DISPLAY, fontWeight: 900, fontSize: pt(size), lineHeight: 0.8, color: col(color),
  textTransform: 'uppercase', placement, ...extra });
// A flat shape in millimetres of the page: a polygon from its points, a disc from its radius.
const shape = (id, color, d, extra = {}) => ({ kind: 'path', id, d, viewBox: [W, H],
  fill: col(color), ...extra, placement: { ...at('page', 'top-left'),
    size: { width: mm(W), height: mm(H) } } });
const poly = (id, color, points, extra) =>
  shape(id, color, `M${points.map((p) => p.join(' ')).join('L')}Z`, extra);
const disc = (id, color, x, y, r, extra) => shape(id, color,
  `M${x - r} ${y}A${r} ${r} 0 1 1 ${x + r} ${y}A${r} ${r} 0 1 1 ${x - r} ${y}Z`, extra);
// A bar laid along a slant: `len` from (x, y) on the passport's own axes, `wide` across it.
const [UX, UY] = [Math.cos(-0.3), Math.sin(-0.3)]; // the slant: 17 degrees
const bar = (id, color, x, y, len, wide, extra) => poly(id, color, [[x, y],
  [x + len * UX, y + len * UY], [x + len * UX - wide * UY, y + len * UY + wide * UX],
  [x - wide * UY, y + wide * UX]].map((p) => p.map((n) => Math.round(n * 100) / 100)), extra);
const on = (x, y, u, v) => [x + u * UX - v * UY, y + u * UY + v * UX]; // a point on those axes

// #region answer: each step on its own line, led by a plus sign
// A line of verse typed as the book prints it, its steps marked +:
//   К любым
//   + чертям с матерями
//   + катись
// A step starts a word space after the end of the step above, so the steps keep the rhyme's
// line whole whatever the face or the size. They are lines: nothing joins them or divides
// them, and they are not hyphenated. A step that would run past the measure moves back until
// it fits; one wider than the whole measure turns over, `hang` in from its own start.
// align=start on the fence sets the poem flush left; by default it is centred.
const LOCALE = 'ru';
const verse = { turnover: 'hang', hang: em(2), tighten: true }; // config().bodyText.verse
const paragraphStyles = [
  { id: 'step', fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    textAlign: 'left', indent: mm(38), firstLineIndent: pt(0),
    marginTop: pt(0), marginBottom: pt(0) },
  { id: 'shout', fontFamily: DISPLAY, fontWeight: 900, fontSize: pt(29), lineHeight: pt(27),
    color: col('paper'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(0),
    marginBottom: pt(0) },
  { id: 'colophon', fontSize: pt(7.6), lineHeight: pt(10), color: col('paper'),
    textAlign: 'left', firstLineIndent: pt(0), hyphenation: { enabled: false } },
];
// #endregion

// #region loud: the words the poem shouts, in red and in the black weight
const characterStyles = [{ id: 'loud', name: 'Loud', fontWeight: 900, color: col('red') }];
// #endregion

// #region numbers: every tenth step in the margin, as the Complete Works count them
const lineNumbers = { enabled: true, count: 'verse', restart: 'document', interval: 10,
  position: 'left', gap: mm(-32), // the column starts at the trim: 32 mm in from its edge
  fontFamily: DISPLAY, fontWeight: 900, fontSize: pt(13), color: col('red') };
// #endregion

// #region cover: a passport thrown at the page, drawn with paths
const P = [60, 78]; // the passport's top corner
const flat = { pages: 'opener' }; // the shapes: in the header slot, for the cover alone
const cover = { id: 'cover', numbered: false, breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: { enabled: true, slot: { elements: [
    text('year', '{attr.year}', 28, 'ink', at('page', 'top-right', -14, 15)),
    text('one', '{attr.one}', 52, 'ink', at('page', 'top-left', 14, 182)),
    text('two', '{attr.two}', 52, 'red', { ...at('#one', 'right-of', 3, 17) }),
    text('three', '{attr.three}', 118, 'ink', at('page', 'bottom-left', 14, -12)),
  ] } } };
const coverShapes = [
  poly('field', 'ink', [[0, 0], [124, 0], [0, 176]], flat),
  disc('sun', 'paper', 88, 92, 52, flat),
  bar('ray', 'ink', -6, 180, 190, 3, flat),
  bar('passport', 'red', ...P, 74, 100, flat),
  disc('seal', 'paper', ...on(...P, 37, 39), 17, flat),
  disc('eye', 'ink', ...on(...P, 37, 39), 9, flat),
  ...[48, 36, 24].map((len, i) =>
    bar(`line-${i}`, 'paper', ...on(...P, 13, 68 + 9 * i), len, 4, flat)),
  text('author', '{author}', 26, 'paper', at('page', 'top-left', 14, 15), flat),
];
// #endregion

// #region pages: the folio in a black thumb tab at the fore-edge
const tab = (parity, edge, x) => [
  { kind: 'box', id: `tab-${parity}`, parity, pages: 'body', style: { backgroundColor: col('ink') },
    placement: { ...at('page', edge, 0, 22), size: { width: mm(13), height: mm(20) } } },
  text(`folio-${parity}`, '{pageNumber}', 26, 'paper', at('page', edge, x, 28),
    { parity, pages: 'body' }),
];
const header = { elements: [...coverShapes, ...tab('even', 'top-left', 4.6),
  ...tab('odd', 'top-right', -4.6)] };
const LINES = 43; // three pages of 43, 43 and 29 steps, and five in the red field
const margins = { top: mm(22), bottom: mm(H - 22 - (LINES * LEAD * 25.4) / 72 - 0.1),
  left: mm(0), right: mm(0) };
// #endregion

// #region finale: the last sentence in a red field across the foot of the last page
const box = (id, y, top, bottom) => ({ id, placement: 'fixed', background: col('red'),
  fixed: { anchor: { to: 'page', edge: 'bottom-left' }, offset: { x: mm(0), y: mm(y) } },
  stripe: { enabled: false },
  padding: { top: mm(top), right: mm(14), bottom: mm(bottom), left: mm(14) } });
const calloutStyles = [box('finale', -20.6, 10, 5), box('colophon', 0, 2, 8)];
// #endregion

const config = () => ({
  locale: LOCALE, // written out, never LANG: the poem is Russian in every edition
  colorPalette, lineNumbers, paragraphStyles, characterStyles, calloutStyles, header,
  footer: { elements: [] },
  page: { sizePreset: '70x108/16', dpi: 150, backgroundColor: col('paper'), margins },
  layout: { layoutType: 'single' }, // the default is two columns
  bodyText: { fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    textAlign: 'left', verse },
  headings: { fontFamily: DISPLAY, fontWeight: 900, levels: [{ level: 1 }] },
  headingStyles: [cover],
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The poem (content.text.en.md), then the colophon (content.<lang>.md).
const markdown = [String.raw`---
title: "Стихи о советском паспорте"
author: "Владимир Маяковский"
---

# Стихи \\ о советском \\ паспорте {style="cover" one="Стихи" two="о советском" three="паспорте" year="1929"}

:::pagebreak

:::verse{style="step" align=start lineStart=1}
Я волком бы
+ выгрыз
+ бюрократизм.
К мандатам
+ почтения нету.
К любым
+ чертям с матерями
+ катись
любая бумажка.
+ :span[Но эту…]{style="loud"}
По длинному фронту
+ купе
+ и кают
чиновник
+ учтивый
+ движется.
Сдают паспорта,
+ и я
+ сдаю
мою
+ :span[пурпурную книжицу.]{style="loud"}
К одним паспортам —
+ улыбка у рта.
К другим —
+ отношение плевое.
С почтеньем
+ берут, например,
+ паспорта
с двухспальным
+ английским левою.
Глазами
+ доброго дядю выев,
не переставая
+ кланяться,
берут,
+ как будто берут чаевые,
паспорт
+ американца.
На польский —
+ глядят,
+ как в афишу коза.
На польский —
+ выпяливают глаза
:::

:::pagebreak

:::verse{style="step" align=start lineStart=44}
в тугой
+ полицейской слоновости —
откуда, мол,
+ и что это за
географические новости?
И не повернув
+ головы качан
и чувств
+ никаких
+ не изведав,
берут,
+ не моргнув,
+ паспорта датчан
и разных
+ прочих
+ шведов.
И вдруг,
+ как будто
+ ожогом,
+ рот
скривило
+ господину.
Это
+ господин чиновник
+ берет
мою
+ :span[краснокожую паспортину.]{style="loud"}
Берет —
+ как бомбу,
+ берет —
+ как ежа,
как бритву
+ обоюдоострую,
берет,
+ как гремучую
+ в 20 жал
змею
+ двухметроворостую.
Моргнул
+ многозначаще
+ глаз носильщика,
хоть вещи
+ снесет задаром вам.
:::

:::pagebreak

:::verse{style="step" align=start lineStart=87}
Жандарм
+ вопросительно
+ смотрит на сыщика,
сыщик
+ на жандарма.
С каким наслажденьем
+ жандармской кастой
я был бы
+ исхлестан и распят
за то,
+ что в руках у меня
+ молоткастый,
:span[серпастый]{style="loud"}
+ :span[советский паспорт.]{style="loud"}
Я волком бы
+ выгрыз
+ бюрократизм.
К мандатам
+ почтения нету.
К любым
+ чертям с матерями
+ катись
любая бумажка.
+ :span[Но эту…]{style="loud"}
Я
+ достаю
+ из широких штанин
дубликатом
+ бесценного груза.
:::

:::callout{type="finale"}
:::verse{style="shout" align=start lineStart=116}
Читайте,
+ завидуйте,
+ я —
+ гражданин
Советского Союза.
:::
:::
`, String.raw`:::callout{type="colophon"}
:::paragraphs{style="colophon"}
Text: V. V. Mayakovsky, Complete Works, vol. 10 (Moscow, 1958), public domain, from Russian Wikisource. The red steps are this edition’s. Set in Golos Text and Sofia Sans Extra Condensed (SIL OFL).
:::
:::
`].join('\n\n');

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // every face the pages use, loaded before the build
  'Golos Text': ['400', '900'], // TEXT: the poem and its loud steps
  'Sofia Sans Extra Condensed': ['900'], // DISPLAY: the cover, the numbers, the last sentence
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config(), kitCyrillicFonts(FONTS));
showPages(doc, { title: 'Стихи о советском паспорте' });
offerPdf(() => renderToPdf(doc, { fontProvider: cyrillicPdfProvider }), `${RECIPE}.pdf`);

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · cyrillic v1 ── Cyrillic faces · postext.dev/cookbook
// Fontsource ships a family's Cyrillic letters in files of their own:
// `cyrillic` holds the Russian, Ukrainian, Belarusian, Bulgarian, Serbian and
// Macedonian alphabets, the stress mark and №; `cyrillic-ext` the letters of
// Kazakh, Kyrgyz, Tatar, Bashkir, Tajik and Mongolian. The fonts block loads
// latin, latin-ext and greek; this one adds these.

/** The unicode-ranges Fontsource's stylesheets declare the two files with (a
 *  function: the kit runs after the pen's code). */
function cyrillicRanges() {
  return {
    cyrillic: 'U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116',
    'cyrillic-ext': 'U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F',
  };
}

/** The Cyrillic files `text` needs that `meta`'s family ships. */
function cyrillicSubsetsFor(text, meta) {
  return [[/[́Ѐ-џҐґҰұ№]/u, 'cyrillic'],
    [/[Ѡ-ҏҒ-үҲ-ԯᲀ-ᲊ₴ⷠ-ⷿꙀ-ꚟ]/u, 'cyrillic-ext']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** kitFonts(FONTS) for a pen in Cyrillic: the fonts block's files, then the
 *  Cyrillic ones `text` needs. A family without them fails, so that no page
 *  is set in a fallback face unseen; list in `latin` the families that set
 *  Latin text alone. */
function kitCyrillicFonts(FONTS = {}, latin = []) {
  return { ...kitFonts(FONTS), resolve: async (family, weight, style, request = {}) => {
    const files = await fontsourceResolver(family, weight, style, request);
    const meta = await fontsourceMeta(family);
    if (!files || latin.includes(family)) return files;
    if (/\p{Script=Cyrillic}/u.test(request.text ?? '') && !meta?.subsets?.includes('cyrillic')) {
      throw new Error(`${family} has no Cyrillic letters at Fontsource`);
    }
    const at = await fontsourceAt(fontsourceId(family));
    return [...files, ...cyrillicSubsetsFor(request.text ?? '', meta).map((subset) => ({
      source: `${at}files/${fontsourceId(family)}-${subset}-${weight}-${style}.woff2`,
      unicodeRange: cyrillicRanges()[subset],
    }))];
  } };
}

/** fontsourceProvider (the pdf block) with the Cyrillic files a face's
 *  letters need, after its others, as the screen added them. */
async function cyrillicPdfProvider(family, weight, style, request) {
  const first = await fontsourceProvider(family, weight, style, request);
  const files = Array.isArray(first) ? first : [first];
  const meta = await fontsourceMeta(family);
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const subsets = cyrillicSubsetsFor(text, meta);
  if (!subsets.length) return first;
  const s = style === 'italic' && !meta.styles.includes('italic') ? 'normal' : style;
  const w = (await fontsourceWeights(family, s)).reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const at = await fontsourceAt(fontsourceId(family));
  const more = await Promise.all(subsets.map(async (subset, i) => {
    const url = `${at}files/${fontsourceId(family)}-${subset}-${w}-${s}.woff2`;
    const res = await fetch(url);
    if (!res.ok) throw new Error(`Fontsource file ${url} (${res.status})`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: cyrillicRanges()[subset], order: files.length + i });
  }));
  return [...files, ...more];
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## Pitfalls

- A line that really begins with a plus sign is written `\+`.
- At a larger size the steps of a long line run out of room and the last ones move back, which looks like a mistake. The sentence in the red field needs 123 mm at 29 pt; check the longest line before you enlarge it.

## Credits

- Recipe: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: Стихи о советском паспорте, 1929, complete, after the Complete Works in thirteen volumes (vol. 10, 1958) in the transcription of ru.wikisource: Vladimir Mayakovsky ([source](https://ru.wikisource.org/wiki/Стихи_о_советском_паспорте_(Маяковский))), public domain
- Text: The colophon: Postext Cookbook, original
- Type: Golos Text (OFL-1.1), Sofia Sans Extra Condensed (OFL-1.1)
- Code: MIT · Sample content: MIT

## Related

- [Nº 062 · Shaped verse: Herbert’s Easter Wings, centred line by line](https://postext.dev/en/cookbook/shaped-verse.md): George Herbert’s Easter Wings and The Altar set as centred body text, a paragraph to each line of verse, so the lengths of the lines draw the two figures. · Level 1 (Basic) · Poetry
- [Nº 015 · Poems set line by line](https://postext.dev/en/cookbook/poetry-collection.md): Each poem is a :::verse block written as printed: the 1918 indents are leading spaces, turnovers hang 2 em past their line, blank lines part stanzas. · Level 2 (Intermediate) · Poetry
- [Nº 044 · Critical edition: line numbers and line-keyed notes](https://postext.dev/en/cookbook/critical-edition-line-numbers.md): Milton’s Lycidas in the 1645 text: lineNumbers prints every fifth line number in the side column, and each note opens on its line number, set as a chip. · Level 3 (Advanced) · Poetry
