# マヤコフスキーの階段詩を打ち、組む

> マヤコフスキーの1929年の詩を全篇、赤と黒の4ページに。階段の各段はプラス記号で打ち、10段ごとに番号を振り、最後の一文を赤い地に大きく組みます。

- HTML版: https://postext.dev/ja/cookbook/stepped-verse-lesenka
- レシピ No. 206 · 文字と本文 · 難易度 2 (中級) · 出力: Canvas, PDF
- ジャンル: 詩歌
- 必要なもの postext ≥ 1.100.0, postext-pdf ≥ 1.100.0 · テスト環境 1.100.0, postext-pdf 1.100.0 ／テスト日 2026-12-02
- ページ: [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)
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=stepped-verse-lesenka&lang=en (.postext: https://postext.dev/cookbook/stepped-verse-lesenka/en/stepped-verse-lesenka.postext)
- 最終更新: 2026-12-02
- 他の言語: [en](https://postext.dev/en/cookbook/stepped-verse-lesenka.md), [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), [ar](https://postext.dev/ar/cookbook/stepped-verse-lesenka.md)

## かんたんな説明

詩の行が階段のようにページを下りていく、ソ連の有名な詩です。どの段も上の段が終わったところから始まり、ページは当時のポスターのように赤と黒で刷られています。

## できあがり

『ソヴィエトのパスポートの詩』（*Стихи о советском паспорте*、1929年）の全篇を、170 × 260 mmの4ページに組みます。マヤコフスキーは詩行を段に割り、どの段も前の段が止まったところから始めました。全集は一段を一行と数えます。本文はGolos Text 12.5 pt、行送り14.6 ptで、各ページ43段、43段、29段。パスポートを指す語句は極太の赤です。最後の一文は4ページの下の赤い地に置きます。表紙もノンブルのタブも赤い地も、黒と赤と紙の色だけの平らな図形で、リシツキーがマヤコフスキーのために作った紙面にならいました。

**このレシピが答える問い:**

- マヤコフスキーの階段詩（レーセンカ）を、各段が前の段の終わりから始まるように組むには？
- 詩を組むには（1行に1詩行、連の間のアキ、折り返した行のぶら下げインデント、ハイフネーションなし）？

## 手短な答え

```js
// script.js, 行 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 } },
];
```

## 材料

**学べること**

- [行ごとの詩](https://postext.dev/ja/docs/document-format-directives.md#verse): :::verseは詩を書いたとおりに組みます。Markdownの1行が詩の1行、連のあいだは空行、行頭の空白は字下げです。長すぎる行はぶら下げるか角括弧の後ろで行末側に寄せて折り返し、頁の区切りで元の行と離れず、短い連は分けずに保てます。
- [文書の言語としてのキリル文字の諸言語](https://postext.dev/ja/docs/cyrillic-layout.md#キリル文字の本の始め方): localeを'ru'、'uk'、'be'、'bg'、'sr'、'mk'、'kk'、'ky'、'tt'、'ba'、'tg'、'mn'のいずれかにすると、その言語のハイフネーション、キャプション、表題、注、数詞、全紙判型、背文字の向きになります。
- [ページデザインのテキスト・罫・ボックス](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル): ヘッダー、フッター、章扉、部扉で共通の描画要素です。ピル形の背景を付けられるテキスト、水平と垂直の罫、塗りまたは枠線のボックスがあり、配列の順に描かれます。

**ほかに使うもの**

- [行末で分けない語](https://postext.dev/ja/docs/cyrillic-layout.md#分けない語)
- [行番号](https://postext.dev/ja/docs/configuration-notes-references.md#行番号)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [表紙、扉、奥付](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [文字スタイル](https://postext.dev/ja/docs/document-format-inline.md#文字スタイル)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [固定位置の囲みとバッジ](https://postext.dev/ja/docs/configuration-callouts.md#calloutコンテナー)
- [囲み](https://postext.dev/ja/docs/configuration-callouts.md#囲みスタイル)
- [仕上がりサイズ](https://postext.dev/ja/docs/configuration-page-layout.md#ページサイズのプリセット)
- [文書のメタデータ](https://postext.dev/ja/docs/document-format.md#フロントマター)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [改ページと改段](https://postext.dev/ja/docs/document-format-directives.md#pagebreak)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [タイトル内の改行](https://postext.dev/ja/docs/document-format-directives.md#タイトル内の改行)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`calloutStyles`](https://postext.dev/ja/docs/configuration-callouts.md#囲みスタイル), [`characterStyles`](https://postext.dev/ja/docs/configuration-styles.md#文字スタイル), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headingStyles`](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`lineNumbers`](https://postext.dev/ja/docs/configuration-notes-references.md#行番号), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), [`decompressWoff2`](https://postext.dev/ja/docs/configuration-pdf-output.md#ブラウザー向けフォントプロバイダーfontsource--woff2), [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`renderToPdf`](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)

**書体**

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

## 作り方

### 1 · 段をプラス記号で打つ

コードは上の[手短な答え](https://postext.dev/ja/cookbook/stepped-verse-lesenka.md#手短な答え)です。[`:::verse`](https://postext.dev/ja/docs/document-format-directives.md#verse)の囲みの中で、詩行の最初の段はそのまま、残りの段は`+ `で始めます。組版エンジンはその段を、上の段の終わりから語間ひとつ置いて始めます。空白やタブを数える必要がないので、書体や大きさを変えると階段全体がついてきます。行長からはみ出る段は収まるところまで戻り、行長そのものより広い段だけが折り返して、自分の頭の下にぶら下がります。

### 2 · 赤で声を上げる

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

リシツキーがマヤコフスキーのために作った本は、太さと色で叫びます。ここでは[文字スタイル](https://postext.dev/ja/docs/configuration-styles.md#文字スタイル)がその役です。`:span[Но эту…]{style="loud"}`はGolos Text 900と赤になり、次の段はその終わりから測られるので、階段は狂いません。

### 3 · 10段ごとに番号を振る

```js
// script.js, 行 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/ja/docs/configuration-notes-references.md#行番号)は詩の行を数え、一段は一行です。詩はページごとに囲みを一つにし、`lineStart=44`と`lineStart=87`で数えを続けます。段組みは裁ち落としの線から始め、赤い地を裁ち切りにします。段落スタイルが詩を38 mm下げ、負の`gap`が番号を内側へ寄せます。

### 4 · 表紙をパスで描く

```js
// script.js, 行 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),
];
```

`viewBox`をページと同じ大きさにすると、[パス](https://postext.dev/ja/docs/configuration-headers-footers.md#パス要素)の点をミリで書けます。パスは回転しないので、`bar`が17度の傾きで四隅を計算します。図形は`pages: 'opener'`で柱の枠に置きます。見出しのデザインは版面の下端で切れるからです。題名も段になり、*о советском*は*Стихи*の右に留めてあります。

### 5 · ノンブルをタブに入れる

```js
// script.js, 行 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) };
```

小口に接した黒い箱がノンブルを載せます。偶数ページは左、奇数ページは右で、『声のために』の抜きの見出しを思い出させます。`pages: 'body'`で表紙には出しません。

### 6 · 赤い地で終える

```js
// script.js, 行 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)];
```

最後の5段は独立した`:::callout`で、ページの下に固定し、ページと同じ幅にします。中の囲みは`shout`スタイル、Sofia Sans Extra Condensed 900の29 ptです。奥付はその下の二つ目の箱で、間に残る紙の帯がポスターの白い線になります。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: 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 ───────────────────────────────────────────────────────────────────────
```

## よくあるつまずき

- 本当にプラス記号で始まる行は`\+`と書きます。
- 大きくすると長い行の段が収まらず、最後の段が戻って間違いのように見えます。赤い地の一文は29 ptで123 mm必要です。大きくする前に一番長い行を確かめてください。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- テキスト: Стихи о советском паспорте, 1929, complete, after the Complete Works in thirteen volumes (vol. 10, 1958) in the transcription of ru.wikisource: Vladimir Mayakovsky ([出典](https://ru.wikisource.org/wiki/Стихи_о_советском_паспорте_(Маяковский))), パブリックドメイン
- テキスト: The colophon: Postext Cookbook, オリジナル
- 書体: Golos Text (OFL-1.1), Sofia Sans Extra Condensed (OFL-1.1)
- コード: MIT · サンプルの内容: MIT

## 関連レシピ

- [No. 062 · 形の詩：ハーバートの『Easter Wings』を1行ずつ中央に](https://postext.dev/ja/cookbook/shaped-verse.md): ジョージ・ハーバートの『Easter Wings』と『The Altar』を、詩の1行を1段落として本文で中央そろえに組み、行の長さで2つの形を描きます。 · 難易度 1 (初級) · 詩歌
- [No. 015 · 詩を1行ずつ組む](https://postext.dev/ja/cookbook/poetry-collection.md): 各詩は印刷されるとおりに書いた:::verseブロックです。1918年版のインデントは行頭の空白、折り返しはその行から2 emぶら下げ、連の間は空行で区切ります。 · 難易度 2 (中級) · 詩歌
- [No. 044 · 校訂版：行番号と行に対応する注](https://postext.dev/ja/cookbook/critical-edition-line-numbers.md): 1645年版の本文によるミルトンの『Lycidas』。lineNumbersが詩の行を数えて5行ごとの番号をサイド段に印字し、各注はチップで組んだ行番号から始まります。 · 難易度 3 (上級) · 詩歌
