本文へスキップ
レシピ番号44

レシピ集 · 第2章 · 文字と本文

校訂版:行番号と行に対応する注

1645年版の本文によるミルトンの『Lycidas』。スクリプトが行を数えて5行ごとに傍らのボックスを加え、各注はチップで組んだ行番号から始まります。

このページの内容
ジャンル
詩歌
出力
Canvas
レベル
上級
Postext
Postext 1.9.2で検証済み
1.4.1以上が必要
ライセンス
2026年9月28日更新
コードMIT · 本文CC BY 4.0

1ページ(全9ページ)

  • 英語の見本:日本語版はまだありません
  • 仕上がり138 × 216 mm
  • 1段半組み, 段間4 mm
  • Linden Hill 10.5/14.5
  • Imbue
  • Libre Franklin
  • 9ページ
  • レベル
  • Postext 1.9.2
  • 組版時間26 ms
  • コード189行

かんたんな説明

ミルトンの詩の学術的な校訂版です。5行ごとに余白に行番号が入り、詩のあとの注は、説明する行をその番号で指し示します。

できあがり

ミルトンがエドワード・キングに捧げた哀歌『Lycidas』を、1645年の『Poems』の本文と綴りのまま、138 × 216 mmの小さな校訂版として組みます。最初のページは月桂樹の小枝の下で始まり、背の高いImbueのキャピタルで組んだ表題の下に、ミルトンが1645年に加えた前書きが入ります。続く193行は1行ずつ組まれ、詩節のあいだは1行あけ、短い行は字下げします。5行ごとに、小口側の幅6 mmの段に月桂樹の緑で行番号が入ります。奇数ページでは詩行の右、偶数ページでは左です。詩行には注の合印を付けません。注は詩のあとの2ページを埋め、各注はその行の番号から始まります。番号は余白の番号と同じ緑のLibre Franklinです。

このレシピが答える質問

  • 詩の5行ごとに余白へ行番号を付け、注をその行番号に対応させるには?
  • 詩を組むには(1行に1詩行、連の間のアキ、折り返した行のぶら下げインデント、ハイフネーションなし)?
  • 脚注を付けるには?
  • 幅の広い本文の段と幅の狭いサイド段からなる1段半のレイアウトにするには?
  • 空行を入れても効かないとき、2つのブロックの間に縦のスペースを追加するには?

手短な答え

script.js · 31–61行コード全体で見る
// The poem is written one line of verse to a line of Markdown, with a blank line between
// verse paragraphs and two spaces before a short line. numberVerse() gives each line a
// paragraph of its own and, after every fifth, a side box that holds its number. A side box
// stands where the text has reached at its fence, under the line it follows; a top padding
// of minus one line lifts the number back onto that line. Fenced before its line instead,
// the number of a line that opens a page slides up beside the last line of the page before
// (gotcha: side-box-starts-at-fence).
const EVERY = 5;
const rows = (...lines) => lines.join('\n');
function numberVerse(markdown) {
  return markdown.replace(/^:::paragraphs\{style="verse"\}\n([\s\S]*?)\n:::$/gm, (_, poem) => {
    let n = 0;
    return poem.split('\n').map((line) => {
      if (!line.trim()) return ':::space{lines=1}'; // one blank line of the grid
      n += 1;
      const style = line.startsWith('  ') ? 'short' : 'verse';
      const verse = rows(`:::paragraphs{style="${style}"}`, line.trim(), ':::');
      if (n % EVERY) return verse;
      return rows(verse, '', ':::callout{type="lineno" span="side"}',
        ':::paragraphs{style="number"}', n, ':::', ':::');
    }).join('\n\n');
  });
}
const lineno = { id: 'lineno', backgroundEnabled: false, // no box: only the number shows
  padding: { top: pt(-LEAD), right: pt(0), bottom: pt(0), left: pt(0) } };
// The number: right-aligned, so the numbers share a right edge, and at the verse's leading,
// so it sits on the baseline of its line.
const number = { id: 'number', fontFamily: LABEL, fontSize: pt(7.5), lineHeight: pt(LEAD),
  color: col('laurel'), textAlign: 'right' };
// Hook-up: calloutStyles: [lineno], paragraphStyles: [number, …] and
// buildDocument({ markdown: numberVerse(markdown) }, config()).

材料

種類
Linden Hill, Imbue, Libre Franklin (SIL OFL 1.1)
素材
  • laurel-1040.jpg
  • The sprig of bay laurel on the first page, a watercolour (Generated With Diffusion Models, オリジナル)

作り方

#1 · レイアウトの前に行を数える

この手順のコードは上の手短な答えにあります。Postextは行に番号を振らないので、ビルドの前にnumberVerse()がMarkdownの中で行を数えます。この関数は各行をそれぞれ独立した段落にし、5行ごとに番号を収めた:::callout{type="lineno" span="side"}を加えます。傍らのボックスは、そのフェンスの位置まで本文が進んだ高さでサイド段に置かれ始めるので、このボックスは直前の行の下から始まります。スタイルの上パディングをマイナス1行(−14.5 pt)にして、番号をその行の横まで引き上げ、ボックスの高さをなくしています(囲みスタイル)。ボックスのフェンスを行の前に置くと、たいていのページでは行と同じ高さに並びますが、番号を振る行がページの先頭に来ると、ボックスは前のページの最終行の横まで滑り上がってしまいます。ボックスの中ではnumberの段落スタイルが数字を右にそろえるので、番号の右端がそろいます。行送りを詩と同じ14.5 ptにしているので、各番号はその行のベースラインに乗ります。

#2 · 幅6ミリの溝

script.js · 65–81行コード全体で見る
const PT = 25.4 / 72; // mm in a point
const [TRIM_W, TRIM_H] = [138, 216]; // mm
const [TOP, INNER] = [21, 20]; // mm
const LINES = 34; // lines of verse to a page
const BOTTOM = TRIM_H - TOP - LINES * LEAD * PT; // 21.08 mm
const [MEASURE, GUTTER, CHANNEL] = [80, 4, 6]; // mm: the longest line of Lycidas is 78.1 mm
const OUTER = TRIM_W - INNER - MEASURE - GUTTER - CHANNEL; // 28 mm beyond the numbers
const layout = {
  layoutType: 'oneAndHalf',
  sideColumnRole: 'floats', // the side column takes side boxes, never text
  sideColumnSide: 'outer', // right of the verse on a recto, left of it on a verso
  // 6 of 90 mm. The zero is Libre Franklin's widest figure, so '100' (4.9 mm) is the widest number.
  sideColumnPercent: (CHANNEL / (MEASURE + GUTTER + CHANNEL)) * 100,
  gutterWidth: mm(GUTTER),
};
const page = { sizePreset: 'custom', width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
  margins: { top: mm(TOP), bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER), mirror: true } };

sideColumnRole: 'floats'にすると、oneAndHalfレイアウトの狭い段には傍らのボックスだけが入り、本文は入りません(レイアウトの種類)。sideColumnPercentは版面に対する割合なので、CodePenのサンプルはミリ単位から換算しています。90 mmのうちの6 mmで、いちばん幅のある番号が収まります。Libre Franklinの数字はプロポーショナルで、7.5 ptではゼロが最も幅広く(1が1.2 mmに対して1.8 mm)、詩の中でいちばん幅のある番号は4.9 mmの100です。180と190は4.8 mmです。'outer'は左右対称の余白に従うので、番号は奇数ページでは詩行の右に、偶数ページでは左に立ちます。奇数ページでは、番号の右端は上にあるノンブルと同じ端にそろいます。詩の段は80 mmで、いちばん長い31行目より1.9 mm広いので、どの行も折り返しません。

#3 · 詩の各行を1つの段落に

script.js · 85–91行コード全体で見る
const verseStyles = [
  // Ragged, like all the text here (bodyText). A line too long for the measure would turn
  // over and hang 2 em in; none does at 80 mm.
  { id: 'verse', hangingIndent: em(2) },
  // Milton's short lines: a one-line paragraph, so the first-line indent moves all of it.
  { id: 'short', firstLineIndent: em(2) },
];

PostextはMarkdownの段落内の行をつなげて組むので、詩の各行はそれぞれ独立した段落にする必要があります。numberVerse()は各行を、詩のスタイルを持つ:::paragraphsコンテナーに入れます(段落スタイル)。1つのスタイルで行の字下げと折り返し行のぶら下げを両立させることはできないので、4行目をはじめとするミルトンの14の短い行には専用のスタイルを与えています。1行だけの段落では、2 emの1行目の字下げが行全体を動かします。詩節のあいだの空行は:::space{lines=1}、つまりグリッドの1行になります。ページの先頭では省かれるので(:::space)、2ページは版面の先頭で15行目から始まり、14行目と15行目のあいだの詩節の区切りは見えません(「よくあるつまずき」を参照)。

#4 · 月桂樹、表題、前書き

script.js · 95–121行コード全体で見る
const OPENER_LINES = 20; // of the page's 34: the first verse paragraph, 14 lines, takes the rest
const at = (id, edge, y) => ({ anchor: { to: id, edge }, offset: { x: mm(0), y: mm(y) } });
const title = (size, tracking, placement) => ({ kind: 'text', id: 'title', content: '{titleText}',
  // lineHeight is a multiple of the size (gotcha: design-lineheight-multiple).
  fontFamily: DISPLAY, fontWeight: 300, fontSize: pt(size), lineHeight: 1,
  letterSpacing: pt(tracking), textTransform: 'uppercase', color: col('ink'), placement });
const opener = { enabled: true, minHeight: pt(OPENER_LINES * LEAD), slot: { elements: [
  // An image element reserves no height (gotcha: opener-image-no-reserve): the kicker, title
  // and headnote under it reach down 20 lines. minHeight is a floor at the same depth, so a
  // shorter headnote leaves the verse on line 21.
  { kind: 'image', id: 'laurel', resourceId: 'laurel',
    placement: { anchor: { to: 'page', edge: 'top-right' }, size: { width: mm(104) } } },
  { kind: 'text', id: 'kicker', content: '{author}', fontFamily: LABEL, fontWeight: 500,
    fontSize: pt(8), letterSpacing: pt(1.6), textTransform: 'uppercase', color: col('laurel'),
    placement: at('container', 'top-left', 50) },
  title(66, 2, at('#kicker', 'below', 1)),
  // # Lycidas {headnote="In this Monody …"}. Design text wraps ragged and has no inline
  // italics (gotcha: design-text-no-inline-marks); at 64 mm no word stands alone.
  { kind: 'text', id: 'headnote', content: '{attr.headnote}', fontFamily: TEXT, italic: true,
    fontSize: pt(9.5), lineHeight: 13 / 9.5, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { ...at('#title', 'below', 3), size: { width: mm(64) } } },
] } };
// Restated: any headings object drops the H1 break (gotcha: headings-drop-h1-break). span
// 'page' paints the laurel above the text block, where a column clips its design. With the
// default marginBottom the verse would start on line 22 and send line 14 to page 2.
const poem = { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: opener, marginBottom: pt(0) };

第1レベルの見出しは、見出し自身の文字の代わりにデザインを印字します(幅と詳細デザイン)。{author}はフロントマターから、前書きは見出しの行に付けた属性# Lycidas {headnote="In this Monody …"}から取ります(見出しの属性)。月桂樹は画像要素で高さを確保しないので、章扉の深さはその下の文字で決まります。版面の上端から50 mm下のキッカー、表題、4行の前書きで、ページの34行のうち20行分まで下がり、残りを最初の詩節14行が占めます。minHeightは同じ深さの下限です。前書きを3行に削っても詩は21行目から始まります。下限がなければ20行目まで上がります。marginBottom: pt(0)で、見出しの既定の余白をこのあきに入れないようにしています。余白が入ると詩は22行目から始まり、14行目が2ページに送られてしまいます。このレベルをページ幅で組んでいるのは、段の中に置いたデザインは段の上端(仕上がりから21 mm下)で切り取られ、月桂樹は仕上がりの端から始まるからです。

#5 · 行番号に対応する注

script.js · 125–144行コード全体で見る
const NOTE = 8.6; // pt: the notes, and the note on the text
const noteStyles = [
  { id: 'textnote', fontSize: pt(NOTE), lineHeight: pt(NOTE * 1.33) },
  // The note on the text ends on the grid, 2.4 mm below its last line; half a line more
  // leaves one blank line before the first note.
  { id: 'note', fontSize: pt(NOTE), lineHeight: pt(NOTE * 1.33), hangingIndent: em(1.6),
    marginTop: pt(LEAD / 2) },
  { id: 'colophon', fontFamily: LABEL, fontSize: pt(7), lineHeight: pt(9.5), color: col('muted'),
    marginTop: pt(LEAD) },
];
// :chip[8]{style="line"}: Linden Hill has no bold, so the number changes face and colour.
// The chip has no fill, outline or side padding, so nothing is drawn around the number.
const chipStyles = [{ id: 'line', backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0),
  fontFamily: LABEL, fontSize: em(0.9), color: col('laurel') }];
// # Notes {style="notes"} opens the next page under the title's capitals, smaller. A heading
// style keeps the level's break unless it sets its own (gotcha: style-inherits-break). Its
// design stays in the column, so the title lines up with the notes on either page.
const notesHead = { id: 'notes', span: 'column', breakBefore: { enabled: true, parity: 'any' },
  advancedDesign: { enabled: true,
    slot: { elements: [title(30, 1, at('container', 'top-left', 0))] } } };

注は行番号に対応させるので、詩行には合印を付けません。注は注釈として詩のあとに続き、詩のページの行を奪いません。各注は:chip[8]{style="line"}と書いた行番号で始まり、続いて説明する語句がイタリックで、閉じ角かっこがそのあとに入ります。チップには塗りも輪郭も左右のパディングもないので、変わるのは書体と色だけです。月桂樹の緑の7.7 pt Libre Franklinです(チップスタイル)。Linden Hillにはボールドがないので、番号は書体を変えることで目立たせます。注のスタイルは2行目以降を1.6 em字下げし、左側に番号がくっきり見えるようにしています。注は詩と同じく行末不ぞろいで組みます。# Notes {style="notes"}は8ページへ改ページし、その表題を章扉と同じキャピタルの30 ptで組みます。

8ページ。各注はその行の緑の番号で始まります。1〜7ページの詩には合印がありません。

#6 · 奇偶で分ける柱

script.js · 148–169行コード全体で見る
const HEAD = 13; // mm from the trim to the running heads' baseline
// A design text's first baseline sits 0.8 of a line below the top of its box: 0.96 em at the
// default lineHeight of 1.2, which the running heads keep.
const BASE = 1.2 * 0.8;
const head = (id, parity, content, x, size = 7.5, extra = {}) => ({ kind: 'text', id, parity,
  content, pages: 'body', fontFamily: LABEL, fontWeight: 500, fontSize: pt(size),
  letterSpacing: pt(1.3), textTransform: 'uppercase', color: col('muted'), ...extra,
  placement: { anchor: { to: 'page', edge: parity === 'even' ? 'top-left' : 'top-right' },
    offset: { x: mm(x), y: mm(HEAD - BASE * size * PT) } } });
const folio = { fontFamily: TEXT, fontWeight: 400, letterSpacing: pt(0), color: col('ink') };
const header = { elements: [
  head('verso-folio', 'even', '{pageNumber}', OUTER, 10, folio),
  head('verso-head', 'even', '{author}', OUTER + 9),
  head('recto-head', 'odd', '{chapterTitle}', -(OUTER + 9)), // LYCIDAS, then NOTES
  head('recto-folio', 'odd', '{pageNumber}', -OUTER, 10, folio),
] };
// The two openers carry their folio at the foot instead, at the outer edge of the text block.
const drop = (parity, edge, x) => ({ ...head(`drop-${parity}`, parity, '{pageNumber}', 0, 10,
  folio), pages: 'opener', placement: { anchor: { to: 'page', edge },
  offset: { x: mm(x), y: mm(-12) } } });
const footer = { elements: [drop('odd', 'bottom-right', -OUTER),
  drop('even', 'bottom-left', OUTER)] };

各要素はページに固定し、parityとpages: 'body'で絞り込みます(テキスト要素)。偶数ページには著者名が、奇数ページには{chapterTitle}が入ります。注はそれ自身の見出しで始まるので、柱は詩の上ではLYCIDAS、注の上ではNOTESになります。ノンブルは版面の小口側の端に立ちます。冒頭の2ページ、1ページと8ページでは、代わりにページの下に入ります。

レシピの全体

Sandbox
// ═══ Postext Cookbook · Nº 044 · Critical edition: line numbers and line-keyed notes ═══
// https://postext.dev/en/cookbook/critical-edition-line-numbers
// Code: MIT · Text: Milton, Poems (1645) (PD) · Notes: CC BY 4.0 · Laurel: diffusion models
// Fonts: Linden Hill, Imbue, Libre Franklin (SIL OFL 1.1) · Needs postext ≥ 1.4.1
// Lycidas in the spelling of 1645, with a number beside every fifth line and two pages of
// notes keyed to those numbers, so the verse carries no note markers.
import {
  buildDocument, renderPageToCanvas, clearMeasurementCache, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en')
const RECIPE = 'critical-edition-line-numbers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Black text on white, and one laurel green for the apparatus.
const palette = {
  ink: '#1b1b1b', // the text
  laurel: '#3c5a3e', // line numbers, note numbers, the kicker
  muted: '#6a706a', // running heads, the colophon
  paper: '#ffffff',
};
// col(id) carries the hex beside the id, because design slots paint the hex
// (gotcha: palette-skips-designs).
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' } }));
const [TEXT, DISPLAY, LABEL] = ['Linden Hill', 'Imbue', 'Libre Franklin'];
const LEAD = 14.5; // pt: the leading of the verse, and the grid every page keeps

// #region answer: count the lines, and after every fifth set its number in the margin
// The poem is written one line of verse to a line of Markdown, with a blank line between
// verse paragraphs and two spaces before a short line. numberVerse() gives each line a
// paragraph of its own and, after every fifth, a side box that holds its number. A side box
// stands where the text has reached at its fence, under the line it follows; a top padding
// of minus one line lifts the number back onto that line. Fenced before its line instead,
// the number of a line that opens a page slides up beside the last line of the page before
// (gotcha: side-box-starts-at-fence).
const EVERY = 5;
const rows = (...lines) => lines.join('\n');
function numberVerse(markdown) {
  return markdown.replace(/^:::paragraphs\{style="verse"\}\n([\s\S]*?)\n:::$/gm, (_, poem) => {
    let n = 0;
    return poem.split('\n').map((line) => {
      if (!line.trim()) return ':::space{lines=1}'; // one blank line of the grid
      n += 1;
      const style = line.startsWith('  ') ? 'short' : 'verse';
      const verse = rows(`:::paragraphs{style="${style}"}`, line.trim(), ':::');
      if (n % EVERY) return verse;
      return rows(verse, '', ':::callout{type="lineno" span="side"}',
        ':::paragraphs{style="number"}', n, ':::', ':::');
    }).join('\n\n');
  });
}
const lineno = { id: 'lineno', backgroundEnabled: false, // no box: only the number shows
  padding: { top: pt(-LEAD), right: pt(0), bottom: pt(0), left: pt(0) } };
// The number: right-aligned, so the numbers share a right edge, and at the verse's leading,
// so it sits on the baseline of its line.
const number = { id: 'number', fontFamily: LABEL, fontSize: pt(7.5), lineHeight: pt(LEAD),
  color: col('laurel'), textAlign: 'right' };
// Hook-up: calloutStyles: [lineno], paragraphStyles: [number, …] and
// buildDocument({ markdown: numberVerse(markdown) }, config()).
// #endregion

// #region page: a poetry trim, and a channel for the numbers at the fore-edge
const PT = 25.4 / 72; // mm in a point
const [TRIM_W, TRIM_H] = [138, 216]; // mm
const [TOP, INNER] = [21, 20]; // mm
const LINES = 34; // lines of verse to a page
const BOTTOM = TRIM_H - TOP - LINES * LEAD * PT; // 21.08 mm
const [MEASURE, GUTTER, CHANNEL] = [80, 4, 6]; // mm: the longest line of Lycidas is 78.1 mm
const OUTER = TRIM_W - INNER - MEASURE - GUTTER - CHANNEL; // 28 mm beyond the numbers
const layout = {
  layoutType: 'oneAndHalf',
  sideColumnRole: 'floats', // the side column takes side boxes, never text
  sideColumnSide: 'outer', // right of the verse on a recto, left of it on a verso
  // 6 of 90 mm. The zero is Libre Franklin's widest figure, so '100' (4.9 mm) is the widest number.
  sideColumnPercent: (CHANNEL / (MEASURE + GUTTER + CHANNEL)) * 100,
  gutterWidth: mm(GUTTER),
};
const page = { sizePreset: 'custom', width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
  margins: { top: mm(TOP), bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER), mirror: true } };
// #endregion

// #region verse: a paragraph per line, ragged, and the short lines set in
const verseStyles = [
  // Ragged, like all the text here (bodyText). A line too long for the measure would turn
  // over and hang 2 em in; none does at 80 mm.
  { id: 'verse', hangingIndent: em(2) },
  // Milton's short lines: a one-line paragraph, so the first-line indent moves all of it.
  { id: 'short', firstLineIndent: em(2) },
];
// #endregion

// #region opener: the laurel, the title in tall capitals, and the headnote of 1645
const OPENER_LINES = 20; // of the page's 34: the first verse paragraph, 14 lines, takes the rest
const at = (id, edge, y) => ({ anchor: { to: id, edge }, offset: { x: mm(0), y: mm(y) } });
const title = (size, tracking, placement) => ({ kind: 'text', id: 'title', content: '{titleText}',
  // lineHeight is a multiple of the size (gotcha: design-lineheight-multiple).
  fontFamily: DISPLAY, fontWeight: 300, fontSize: pt(size), lineHeight: 1,
  letterSpacing: pt(tracking), textTransform: 'uppercase', color: col('ink'), placement });
const opener = { enabled: true, minHeight: pt(OPENER_LINES * LEAD), slot: { elements: [
  // An image element reserves no height (gotcha: opener-image-no-reserve): the kicker, title
  // and headnote under it reach down 20 lines. minHeight is a floor at the same depth, so a
  // shorter headnote leaves the verse on line 21.
  { kind: 'image', id: 'laurel', resourceId: 'laurel',
    placement: { anchor: { to: 'page', edge: 'top-right' }, size: { width: mm(104) } } },
  { kind: 'text', id: 'kicker', content: '{author}', fontFamily: LABEL, fontWeight: 500,
    fontSize: pt(8), letterSpacing: pt(1.6), textTransform: 'uppercase', color: col('laurel'),
    placement: at('container', 'top-left', 50) },
  title(66, 2, at('#kicker', 'below', 1)),
  // # Lycidas {headnote="In this Monody …"}. Design text wraps ragged and has no inline
  // italics (gotcha: design-text-no-inline-marks); at 64 mm no word stands alone.
  { kind: 'text', id: 'headnote', content: '{attr.headnote}', fontFamily: TEXT, italic: true,
    fontSize: pt(9.5), lineHeight: 13 / 9.5, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { ...at('#title', 'below', 3), size: { width: mm(64) } } },
] } };
// Restated: any headings object drops the H1 break (gotcha: headings-drop-h1-break). span
// 'page' paints the laurel above the text block, where a column clips its design. With the
// default marginBottom the verse would start on line 22 and send line 14 to page 2.
const poem = { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
  advancedDesign: opener, marginBottom: pt(0) };
// #endregion

// #region notes: each note opens on its line number, a chip in the label face
const NOTE = 8.6; // pt: the notes, and the note on the text
const noteStyles = [
  { id: 'textnote', fontSize: pt(NOTE), lineHeight: pt(NOTE * 1.33) },
  // The note on the text ends on the grid, 2.4 mm below its last line; half a line more
  // leaves one blank line before the first note.
  { id: 'note', fontSize: pt(NOTE), lineHeight: pt(NOTE * 1.33), hangingIndent: em(1.6),
    marginTop: pt(LEAD / 2) },
  { id: 'colophon', fontFamily: LABEL, fontSize: pt(7), lineHeight: pt(9.5), color: col('muted'),
    marginTop: pt(LEAD) },
];
// :chip[8]{style="line"}: Linden Hill has no bold, so the number changes face and colour.
// The chip has no fill, outline or side padding, so nothing is drawn around the number.
const chipStyles = [{ id: 'line', backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0),
  fontFamily: LABEL, fontSize: em(0.9), color: col('laurel') }];
// # Notes {style="notes"} opens the next page under the title's capitals, smaller. A heading
// style keeps the level's break unless it sets its own (gotcha: style-inherits-break). Its
// design stays in the column, so the title lines up with the notes on either page.
const notesHead = { id: 'notes', span: 'column', breakBefore: { enabled: true, parity: 'any' },
  advancedDesign: { enabled: true,
    slot: { elements: [title(30, 1, at('container', 'top-left', 0))] } } };
// #endregion

// #region heads: the author on the verso, the section on the recto, folios at the fore-edge
const HEAD = 13; // mm from the trim to the running heads' baseline
// A design text's first baseline sits 0.8 of a line below the top of its box: 0.96 em at the
// default lineHeight of 1.2, which the running heads keep.
const BASE = 1.2 * 0.8;
const head = (id, parity, content, x, size = 7.5, extra = {}) => ({ kind: 'text', id, parity,
  content, pages: 'body', fontFamily: LABEL, fontWeight: 500, fontSize: pt(size),
  letterSpacing: pt(1.3), textTransform: 'uppercase', color: col('muted'), ...extra,
  placement: { anchor: { to: 'page', edge: parity === 'even' ? 'top-left' : 'top-right' },
    offset: { x: mm(x), y: mm(HEAD - BASE * size * PT) } } });
const folio = { fontFamily: TEXT, fontWeight: 400, letterSpacing: pt(0), color: col('ink') };
const header = { elements: [
  head('verso-folio', 'even', '{pageNumber}', OUTER, 10, folio),
  head('verso-head', 'even', '{author}', OUTER + 9),
  head('recto-head', 'odd', '{chapterTitle}', -(OUTER + 9)), // LYCIDAS, then NOTES
  head('recto-folio', 'odd', '{pageNumber}', -OUTER, 10, folio),
] };
// The two openers carry their folio at the foot instead, at the outer edge of the text block.
const drop = (parity, edge, x) => ({ ...head(`drop-${parity}`, parity, '{pageNumber}', 0, 10,
  folio), pages: 'opener', placement: { anchor: { to: 'page', edge },
  offset: { x: mm(x), y: mm(-12) } } });
const footer = { elements: [drop('odd', 'bottom-right', -OUTER),
  drop('even', 'bottom-left', OUTER)] };
// #endregion

const config = () => ({ // a factory: configs are cached by identity (gotcha: config-cache-identity)
  colorPalette, page, layout, header, footer,
  bodyText: { // every paragraph sits in a styled container and takes these as defaults
    fontFamily: TEXT, fontSize: pt(10.5), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    // Ragged throughout, verse and notes alike, so nothing is hyphenated
    // (gotcha: ragged-no-hyphenation).
    textAlign: 'left', firstLineIndent: pt(0),
  },
  // The designs print the titles, but each heading's own text is still measured, in this face.
  // Left at the default, the page would fetch Open Sans 700 for text it never paints.
  headings: { fontFamily: DISPLAY, fontWeight: 300, levels: [poem] },
  headingStyles: [notesHead],
  paragraphStyles: [...verseStyles, number, ...noteStyles],
  calloutStyles: [lineno],
  chipStyles,
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
Markdownの見本 · 211行 · content.en.mdtitle: "Lycidas" author: "John Milton" --- # Lycidas {headnote="In this Monody the Author bewails a learned Friend, unfortunatly drown’d in his Passage from Chester on the Irish Seas, 1637. And by occasion foretels the ruine of our corrupted Clergy then in their height."} :::paragraphs{style="verse"} Yet once more, O ye Laurels, and once more Ye Myrtles brown, with Ivy never-sear, I com to pluck your Berries harsh and crude, And with forc’d fingers rude, Shatter your leaves before the mellowing year. Bitter constraint, and sad occasion dear, Compels me to disturb your season due: For *Lycidas* is dead, dead ere his prime, Young *Lycidas*, and hath not left his peer: Who would not sing for *Lycidas?* he knew Himself to sing, and build the lofty rhyme. He must not flote upon his watry bear Unwept, and welter to the parching wind, Without the meed of som melodious tear. Begin then, Sisters of the sacred well, That from beneath the seat of *Jove* doth spring, Begin, and somwhat loudly sweep the string. Hence with denial vain, and coy excuse, So may som gentle Muse With lucky words favour my destin’d Urn, And as he passes turn, And bid fair peace be to my sable shrowd. For we were nurst upon the self-same hill, Fed the same flock, by fountain, shade, and rill. Together both, ere the high Lawns appear’d Under the opening eye-lids of the morn, We drove a field, and both together heard What time the Gray-fly winds her sultry horn, Batt’ning our flocks with the fresh dews of night, Oft till the Star that rose, at Ev’ning, bright Toward Heav’ns descent had slop’d his westering wheel. Mean while the Rural ditties were not mute, Temper’d to th’ Oaten Flute, Rough *Satyrs* danc’d, and *Fauns* with clov’n heel, From the glad sound would not be absent long, And old *Damœtas* lov’d to hear our song. But O the heavy change, now thou art gon, Now thou art gon, and never must return! Thee Shepherd, thee the Woods, and desert Caves, With wilde Thyme and the gadding Vine o’regrown, And all their echoes mourn. The Willows, and the Hazle Copses green, Shall now no more be seen, Fanning their joyous Leaves to thy soft layes. As killing as the Canker to the Rose, Or Taint-worm to the weanling Herds that graze, Or Frost to Flowers, that their gay wardrop wear, When first the White thorn blows; Such, *Lycidas*, thy loss to Shepherds ear. Where were ye Nymphs when the remorseless deep Clos’d o’re the head of your lov’d *Lycidas*? For neither were ye playing on the steep, Where your old *Bards*, the famous *Druids* ly, Nor on the shaggy top of *Mona* high, Nor yet where Deva spreads her wisard stream: Ay me, I fondly dream! Had ye bin there—for what could that have don? What could the Muse her self that *Orpheus* bore, The Muse her self, for her inchanting son Whom Universal nature did lament, When by the rout that made the hideous roar, His goary visage down the stream was sent, Down the swift *Hebrus* to the *Lesbian* shore. Alas! What boots it with uncessant care To tend the homely slighted Shepherds trade, And strictly meditate the thankles Muse, Were it not better don as others use, To sport with *Amaryllis* in the shade, Or with the tangles of *Neæra*’s hair? Fame is the spur that the clear spirit doth raise (That last infirmity of Noble mind) To scorn delights, and live laborious dayes; But the fair Guerdon when we hope to find, And think to burst out into sudden blaze, Comes the blind *Fury* with th’ abhorred shears, And slits the thin spun life. But not the praise, *Phœbus* repli’d, and touch’d my trembling ears; *Fame* is no plant that grows on mortal soil, Nor in the glistering foil Set off to th’ world, nor in broad rumour lies, But lives and spreds aloft by those pure eyes, And perfet witnes of all judging *Jove*; As he pronounces lastly on each deed, Of so much fame in Heav’n expect thy meed. O Fountain *Arethuse*, and thou honour’d flood, Smooth-sliding *Mincius*, crown’d with vocall reeds, That strain I heard was of a higher mood: But now my Oate proceeds, And listens to the Herald of the Sea That came in *Neptune*’s plea, He ask’d the Waves, and ask’d the Fellon winds, What hard mishap hath doom’d this gentle swain? And question’d every gust of rugged wings That blows from off each beaked Promontory, They knew not of his story, And sage *Hippotades* their answer brings, That not a blast was from his dungeon stray’d, The Ayr was calm, and on the level brine, Sleek *Panope* with all her sisters play’d. It was that fatall and perfidious Bark Built in th’ eclipse, and rigg’d with curses dark, That sunk so low that sacred head of thine. Next *Camus*, reverend Sire, went footing slow, His Mantle hairy, and his Bonnet sedge, Inwrought with figures dim, and on the edge Like to that sanguine flower inscrib’d with woe. Ah! Who hath reft (quoth he) my dearest pledge? Last came, and last did go, The Pilot of the *Galilean* lake, Two massy Keyes he bore of metals twain, (The Golden opes, the Iron shuts amain) He shook his Miter’d locks, and stern bespake, How well could I have spar’d for thee young swain. Anow of such as for their bellies sake, Creep and intrude, and climb into the fold? Of other care they little reck’ning make, Then how to scramble at the shearers feast, And shove away the worthy bidden guest. Blind mouthes! that scarce themselves know how to hold A Sheep-hook, or have learn’d ought els the least That to the faithfull Herdmans art belongs! What recks it them? What need they? They are sped; And when they list, their lean and flashy songs Grate on their scrannel Pipes of wretched straw, The hungry Sheep look up, and are not fed, But swoln with wind, and the rank mist they draw, Rot inwardly, and foul contagion spread: Besides what the grim Woolf with privy paw Daily devours apace, and nothing sed, But that two-handed engine at the door, Stands ready to smite once, and smite no more. Return *Alpheus*, the dread voice is past, That shrunk thy streams; Return *Sicilian* Muse, And call the Vales, and bid them hither cast Their Bels, and Flourets of a thousand hues. Ye valleys low where the milde whispers use, Of shades and wanton winds, and gushing brooks, On whose fresh lap the swart Star sparely looks, Throw hither all your quaint enameld eyes, That on the green terf suck the honied showres, And purple all the ground with vernal flowres. Bring the rathe Primrose that forsaken dies. The tufted Crow-toe, and pale Gessamine, The white Pink, and the Pansie freakt with jeat, The glowing Violet. The Musk-rose, and the well attir’d Woodbine, With Cowslips wan that hang the pensive hed, And every flower that sad embroidery wears: Bid *Amaranthus* all his beauty shed, And Daffadillies fill their cups with tears, To strew the Laureat Herse where *Lycid* lies. For so to interpose a little ease, Let our frail thoughts dally with false surmise. Ay me! Whilst thee the shores and sounding Seas Wash far away, where ere thy bones are hurld, Whether beyond the stormy *Hebrides*, Where thou perhaps under the whelming tide Visit’st the bottom of the monstrous world; Or whether thou to our moist vows deny’d, Sleep’st by the fable of *Bellerus* old, Where the great vision of the guarded Mount Looks toward *Namancos* and *Bayona*’s hold; Look homeward Angel now, and melt with ruth. And, O ye *Dolphins*, waft the haples youth. Weep no more, woful Shepherds weep no more, For *Lycidas* your sorrow is not dead, Sunk though he be beneath the watry floar, So sinks the day-star in the Ocean bed, And yet anon repairs his drooping head, And tricks his beams, and with new-spangled Ore, Flames in the forehead of the morning sky: So *Lycidas* sunk low, but mounted high, Through the dear might of him that walk’d the waves; Where other groves, and other streams along, With *Nectar* pure his oozy Lock’s he laves, And hears the unexpressive nuptiall Song, In the blest Kingdoms meek of joy and love. There entertain him all the Saints above, In solemn troops, and sweet Societies That sing, and singing in their glory move, And wipe the tears for ever from his eyes. Now *Lycidas* the Shepherds weep no more; Hence forth thou art the Genius of the shore, In thy large recompense, and shalt be good To all that wander in that perilous flood. Thus sang the uncouth Swain to th’ Okes and rills, While the still morn went out with Sandals gray, He touch’d the tender stops of various Quills, With eager thought warbling his Dorick lay: And now the Sun had stretch’d out all the hills, And now was dropt into the Western bay; At last he rose, and twitch’d his Mantle blew: To morrow to fresh Woods, and Pastures new. :::
`; // content.<lang>.md, inlined by the Cookbook: the poem const notes = String.raw`# Notes {style="notes"}
Markdownの見本 · 72行 · content.notes.en.md :::paragraphs{style="textnote"} *The text* is that of *Poems of Mr. John Milton* (London, 1645), pages 57 to 65. Lycidas had first been printed, without the headnote, in *Justa Edovardo King naufrago* (Cambridge, 1638), the volume of elegies for King. Spelling and capitals follow 1645, and so does the italic of names in the poem. A verse paragraph that 1645 marks by indenting its first line is marked here by a blank line; the short lines are indented. The notes are keyed to the line numbers in the margin. ::: :::paragraphs{style="note"} :chip[1]{style="line"} *Yet once more*] Hebrews 12.26, ‘Yet once more I shake not the earth only, but also heaven.’ :chip[1–2]{style="line"} *Laurels … Myrtles … Ivy*] evergreens and poets’ crowns: the laurel is Apollo’s, the myrtle Venus’s, the ivy Bacchus’s. :chip[3]{style="line"} *crude*] unripe (Latin *crudus*). The berries are picked before their season, as King died before his. :chip[8]{style="line"} *Lycidas*] Edward King (1612–1637), fellow of Christ’s College, Cambridge, drowned on 10 August 1637 when his ship, bound from Chester for Dublin, struck a rock off the Welsh coast. Lycidas is a herdsman in Theocritus, *Idyll* 7, and in Virgil, *Eclogue* 9. :chip[12]{style="line"} *flote … bear*] float … bier. :chip[15]{style="line"} *Sisters of the sacred well*] the Muses, who dance round the spring and the altar of Zeus on Helicon in the first lines of Hesiod’s *Theogony*. :chip[23]{style="line"} *the self-same hill*] Christ’s College, Cambridge, where Milton studied from 1625 to 1632 and King from 1626. :chip[36]{style="line"} *Damœtas*] a herdsman in Theocritus and Virgil. Some commentators see in him a tutor of Christ’s, William Chappell or Joseph Mede; neither identification is certain. :chip[53–55]{style="line"} *Druids … Mona … Deva*] the Druids’ island is Anglesey, *Mona* in Tacitus, *Annals* 14.30; the Dee (*Deva*) reaches the sea below Chester, where King sailed. Its shifting course was read as an omen for England and Wales, hence *wisard*. :chip[58]{style="line"} *the Muse her self that Orpheus bore*] Calliope. The women of Thrace tore Orpheus apart, and his head, still singing, went down the Hebrus and over the sea to Lesbos (Ovid, *Metamorphoses* 11.1–55). :chip[64]{style="line"} *uncessant*] unceasing; so 1638, 1645 and 1673. :chip[70–71]{style="line"} *That last infirmity of Noble mind*] Tacitus, *Histories* 4.6: the desire for glory is the last thing even the wise put off. :chip[75]{style="line"} *the blind Fury*] Atropos, the Fate who cuts the thread of life; Milton makes her a Fury, and blind. :chip[77]{style="line"} *touch’d my trembling ears*] Apollo plucks the poet’s ear in Virgil, *Eclogue* 6.3–4, to call him back from kings and battles to pastoral. :chip[85–86]{style="line"} *Arethuse … Mincius*] the fountain of Syracuse and the river of Mantua: the country of Theocritus and the country of Virgil. :chip[96]{style="line"} *Hippotades*] Aeolus, son of Hippotes, keeper of the winds. :chip[103]{style="line"} *Camus*] the god of the Cam, who stands for Cambridge; he walks as slowly as his river flows. :chip[106]{style="line"} *that sanguine flower*] the hyacinth, sprung from the blood of Hyacinthus, whose petals were said to carry AI, a cry of grief (Ovid, *Metamorphoses* 10.215). :chip[109]{style="line"} *The Pilot of the Galilean lake*] St Peter, the fisherman given the keys of heaven (Matthew 16.19), mitred here as the first bishop. :chip[114–117]{style="line"} *Anow … Then*] enough … than. :chip[119]{style="line"} *Blind mouthes*] Ruskin, in *Sesame and Lilies* (1865): a bishop is one who sees and a pastor one who feeds, so a blind mouth is a clergyman who does neither. :chip[128]{style="line"} *the grim Woolf*] usually read as the Church of Rome, which was making converts at the court of Charles I. :chip[130]{style="line"} *that two-handed engine*] no reading has settled it. Readers have proposed the sword of the archangel Michael, the axe laid to the root of the trees in Matthew 3.10, the two Houses of Parliament and St Peter’s two keys. :chip[132]{style="line"} *Alpheus*] the river said to run under the sea from Greece and rise in Arethusa’s fountain (line 85). Called on here, it brings the poem back to pastoral after St Peter’s speech. :chip[138]{style="line"} *the swart Star*] Sirius, the Dog Star of the hottest weeks, which scorches what it looks on. :chip[156]{style="line"} *Hebrides*] King’s body was never found. :chip[160–162]{style="line"} *Bellerus … the guarded Mount … Namancos*] Bellerus is made from Bellerium, the Roman name of Land’s End. From St Michael’s Mount the archangel looks out over the sea to Galicia, where Mercator’s atlas marks Namancos, near the castle of Bayona. :chip[164]{style="line"} *Dolphins*] like the dolphin that carried the singer Arion to shore at Taenarum (Herodotus 1.24). :chip[176]{style="line"} *unexpressive nuptiall Song*] the song past expressing at the marriage of the Lamb (Revelation 19.7–9). :chip[183]{style="line"} *Genius of the shore*] the guardian spirit of a place: King will keep those who cross the sea he drowned in. :chip[193]{style="line"} *fresh Woods*] in the spring of 1638 Milton left England for Italy. ::: :::paragraphs{style="colophon"} Set in Linden Hill, Imbue and Libre Franklin (SIL Open Font License). Text of 1645, public domain. Notes, CC BY 4.0; laurel painted with diffusion models. :::
`; // content.notes.<lang>.md: the notes // #region art: a sprig of bay laurel with its unripe berries, a watercolour in assets/ // The JPEG is cut to the sprig's 104 × 74 mm frame on white paper and declared at its pixels. const resources = [{ id: 'laurel', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0, bitmap: { fileId: 'laurel-1040.jpg', format: 'jpeg', width: 1040, height: 740 }, altText: 'A sprig of bay laurel with a cluster of unripe berries, entering from the corner.' }]; await loadImage(resources[0].bitmap.fileId, asset(resources[0].bitmap.fileId)); // #endregion // ─── 3 · Fonts ────────────────────────────────────────────────────────────── // Loaded before the first build (gotcha: fonts-first). Linden Hill has no bold, Imbue no italic. const FONTS = { 'Linden Hill': ['400', '400i'], Imbue: ['300'], 'Libre Franklin': ['400', '500'] }; // ─── 4 · Build & show ─────────────────────────────────────────────────────── await loadFonts(FONTS, markdown + notes); const source = `${numberVerse(markdown)}\n\n${notes}`; const doc = await buildWithFonts(() => buildDocument({ markdown: source, resources }, config()), source); showPages(doc, { title: 'Lycidas · with line numbers and notes' });
キット · core, fonts, viewer, images:全レシピ共通 · 270行// ─── 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 v1 ── the same in every recipe · postext.dev/cookbook ──────── // Postext measures text with the faces the browser has loaded, and caches the // widths, so every face must be ready before the first build. Faces come from // Fontsource: the same static files the PDF embeds, so screen and PDF agree. /** faces = { 'Family Name': ['400', '400i', '700'] }. `text` is the sample: * letters beyond Latin-1 (č, ł, ő…) also load the latin-ext files. With * `optional`, a face Fontsource does not ship is skipped instead of failing. * Resolves to the number of faces added. */ async function loadFonts(faces, text = '', { optional = false } = {}) { kitStatus('Loading fonts…'); const ranges = { 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', }; const subsets = /[Ā-˿Ḁ-ỿ]/.test(text) ? ['latin', 'latin-ext'] : ['latin']; const jobs = []; let added = 0; for (const [family, specs] of Object.entries(faces)) { const id = fontsourceId(family); const meta = optional ? await fontsourceMeta(family) : null; for (const spec of new Set(specs)) { const weight = parseInt(spec, 10); const style = spec.endsWith('i') ? 'italic' : 'normal'; if (hasFace(family, weight, style)) continue; if (optional && !(meta?.weights.includes(weight) && meta.styles.includes(style))) continue; for (const subset of subsets) { const url = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/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().then((ready) => { document.fonts.add(ready); added++; }, () => { if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`); })); } } } await Promise.all(jobs).catch((error) => { kitFail(error); throw error; }); return added; } /** Runs `build` (a buildDocument or buildBundle call) and checks the faces * the pages use. A regular face missing from FONTS is loaded with a warning; * bold and italic variants are loaded when the family ships them. Then the * measurement caches are cleared and the build runs again. */ async function buildWithFonts(build, text = '') { const tried = new Set(); for (let round = 0; round < 3; round++) { kitStatus('Laying out…'); await new Promise(requestAnimationFrame); // let the status paint first const result = await Promise.resolve().then(build).catch((error) => { kitFail(error); throw error; }); const wanted = { base: {}, variants: {} }; for (const { font, base } of [result].flat().flatMap(fontStringsOf)) { const { family, weight, style } = parseFont(font); const key = `${family}|${weight}|${style}`; if (tried.has(key) || hasFace(family, weight, style)) continue; tried.add(key); (wanted[base ? 'base' : 'variants'][family] ??= []).push(`${weight}${style === 'italic' ? 'i' : ''}`); } if (Object.keys(wanted.base).length) { console.warn(`[cookbook] FONTS does not list ${JSON.stringify(wanted.base)}: loading them.`); } const added = await loadFonts(wanted.base, text) + await loadFonts(wanted.variants, text, { optional: true }); if (added === 0) return result; clearMeasurementCache(); } throw new Error('The fonts did not settle after three builds.'); } /** Every font string of the layout. `base` marks a block's own face; its * bold, italic and bold-italic variants are listed whether or not used. */ function fontStringsOf(doc) { const found = new Map(); const walk = (node) => { if (!node || typeof node !== 'object') return; if (Array.isArray(node)) { node.forEach(walk); return; } for (const [key, value] of Object.entries(node)) { if (typeof value === 'string' && /fontString$/i.test(key)) { found.set(value, found.get(value) || key === 'fontString'); } else if (value && typeof value === 'object') walk(value); } }; walk(doc.pages); walk(doc.blocks); return [...found].map(([font, base]) => ({ font, base })); } /** '700 37.5px Open Sans' / 'italic 400 13px "Source Serif 4"' → { family, weight, style }. * A string with no weight ('95.8px Young Serif', from a design text) is 400. */ function parseFont(font) { const m = /^(?:(italic|oblique)\s+)?(?:small-caps\s+)?(?:(\d+|bold|normal)\s+)?[\d.]+px\s+(.+)$/.exec(font.trim()); if (!m) throw new Error(`Unexpected font string: ${font}`); const weight = m[2] === 'bold' ? 700 : !m[2] || m[2] === 'normal' ? 400 : Number(m[2]); return { family: m[3].replace(/^["']|["']$/g, ''), weight, style: m[1] ? 'italic' : 'normal' }; } /** True when a loaded FontFace covers exactly this family, weight and style * (document.fonts.check() is also true for families nobody declared). */ 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; } /** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */ function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); } /** The weights and styles a family ships ({ weights: [400, 700], styles: ['normal', 'italic'] }), or null. */ function fontsourceMeta(family) { fontsourceMeta.cache ??= new Map(); const id = fontsourceId(family); if (!fontsourceMeta.cache.has(id)) { fontsourceMeta.cache.set(id, fetch(`https://api.fontsource.org/v1/fonts/${id}`) .then((res) => (res.ok ? res.json() : null), () => null)); } return fontsourceMeta.cache.get(id); } // ─── Kit · viewer v1 ── the same in every recipe · postext.dev/cookbook ─────── /** Shows the pages as facing spreads on a dark desk: the first page is a * recto on its own, then verso | recto pairs, as in a bound book. Pages * are painted when they scroll near the screen. */ function showPages(docs, { title, width = 460 } = {}) { 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, { 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 · images v1 ── recipes with pictures · postext.dev/cookbook ────────── /** Registers a photo or PNG for the canvas and keeps its bytes for the PDF. * fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */ async function loadImage(fileId, url) { const res = await fetch(url); if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`); const bytes = new Uint8Array(await res.arrayBuffer()); registerResourceImage(fileId, await createImageBitmap(new Blob([bytes]))); (loadImage.bytes ??= new Map()).set(fileId, bytes); } /** Registers SVG markup (drawn in code, or fetched) as a vector image. */ async function loadSvg(fileId, svg) { const img = new Image(); img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`; await img.decode(); registerResourceImage(fileId, img); (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg)); } /** renderToPdf({ resourceBytes: imageBytes }) */ function imageBytes(fileId) { return loadImage.bytes?.get(fileId); } /** renderToHtml({ resourceImageUrl: imageUrl }) */ function imageUrl(fileId) { const bytes = imageBytes(fileId); if (!bytes) return undefined; imageUrl.urls ??= new Map(); if (!imageUrl.urls.has(fileId)) { const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg'; imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type }))); } return imageUrl.urls.get(fileId); } // ─── /Kit ───────────────────────────────────────────────────────────────────────

組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#10行ごとに番号を振る

長い詩はしばしば10行ごとに番号を振ります。幅6 mmの段は変えなくてかまいません。

-const EVERY = 5;
+const EVERY = 10;

#番号をいつも詩行の右に置く

サイド段を右に固定すると、番号はどのページでも詩行の右に立ちます。偶数ページでは番号がのど側に来ます。

-  sideColumnSide: 'outer', // right of the verse on a recto, left of it on a verso
+  sideColumnSide: 'right', // right of the verse on every page

よくあるつまずき

つまずき

サイド段の囲みは、囲みを開く位置の次のブロックと同じ高さから始まる

postext 1.4.1では、span: 'side'の囲みは、囲みを開く位置で本文が達した高さの次のグリッド行から、すでにある囲みがあればその下に、サイド段に置かれます。注釈は説明する段落の直前で開いてください。段落のあとで開くと、注釈は次の段落の横から始まります。段の末尾を越える囲みは、上の囲みが許す範囲で、下端が段の末尾にそろうまで上にずれます。それでも収まらない囲みは、次のページのサイド段まで待ちます。 欄外の注 →

つまずき

行末不ぞろいのテキストはハイフネーションされない

ハイフネーションが効くのは両端そろえのテキストだけです。左そろえのテキストは語と語の間で改行するため、幅の狭い左そろえの段では行末の凹凸が大きくなります。その箇所を両端そろえにするか、行長を広げてください。 ハイフネーションと文書の言語 →

つまずき

行末不ぞろいのテキストはラントを検査されない

optimalLineBreaking、avoidRunts、runtPenalty、runtMinCharactersはKnuth–Plassの改行処理に働きますが、postext 1.4.1がこれを使うのは両端そろえのテキストだけです。左そろえの段落は1行ずつ改行されるため、これらの設定にかかわらず短い一語で終わることがあります。左そろえのテキストの最終行を読み、ラントで終わる段落は書き換えてください。 ウィドウ、オーファン、ラント →

つまずき

属性値には{も}も書けない。"を含む値は一重引用符で囲む

属性値は閉じ波かっこで終わるため、{や}を含められません。二重引用符を含む値は一重引用符で囲みます。ドル記号は問題ありません。 見出しの属性 →

つまずき

デザインのテキストではインラインの^sup^や**bold**が使えない

デザインのテキスト要素はプレーンテキストを印字するため、属性内の^1^や**bold**はそのまま出ます。Unicodeの上付き数字(¹ ² ³はlatinサブセットに含まれます)を使うか、別のウェイトの要素をもう1つ置いてください。 ページデザインのテキスト・罫・ボックス →

つまずき

章扉の画像は確保する高さに数えられない

postext 1.4.1では、詳細デザインの見出しは、確保する高さを画像抜きで計測します。テキスト、罫、箱はページに固定していても数えられますが、ページの頭に裁ち落としで置いた写真のような画像は何も確保しないため、本文がその上から始まることがあります。minHeightを本文が始まるべき位置に設定してください。 デザインした章扉 →

つまずき

見出しスタイルはその階層の改ページを受け継ぐ

headingStylesの項目は、指定しなかったフィールドをすべて見出しの階層から受け継ぎ、breakBeforeも例外ではありません。:::pagebreakのあとのH1に付けた目次や奥付のスタイルはparity 'odd'を受け継ぎ、白ページの後ろに置かれます。こうしたスタイルにはbreakBefore: { enabled: false }を指定してください。 見出しスタイル →

つまずき

headingsオブジェクトを渡すとH1の改ページが消える

既定ではH1は奇数ページへ改ページします(always-odd)。ところがheadingsオブジェクトを渡すと中身にかかわらずこの既定がリセットされ、章は改ページせずに続けて組まれ、span: 'page'も効かなくなります。どの設定でもheadings.levels[0].breakBefore: { enabled: true, parity }を書き直してください。 奇数ページから始まる章 →

つまずき

パレットを差し替えても、デザイン要素と参照色は変わらない

postext 1.4.1はcolorPaletteをテキストのスタイル(本文、見出し、リスト、キャプション、表、囲み)には反映しますが、ヘッダー、フッター、章扉、部扉の要素と、bodyText.referenceColorには反映しません。これらはpaletteIdの横に書いた16進の色のままです。画面用のダーク版や色替えのためにパレットを差し替えるときは、ビルドの前に、リンクしたすべての色をcolorPaletteから書き直してください。 セマンティックカラーパレット →

つまずき

デザインのテキストのlineHeightは倍率で、寸法ではない

デザインのスロットでは、テキスト要素のlineHeightはフォントサイズに掛ける倍率です(lineHeight: 1.05)。postext 1.4.1ではpt(15)のような寸法を指定しても拒否されず、章扉の高さがNaNと計測されて、minHeightを含め確保する高さが警告なしに失われ、本文がタイトルに重なって組まれます。 ページデザインのテキスト・罫・ボックス →

つまずき

設定はオブジェクトの同一性でキャッシュされる。毎回新しいオブジェクトを作る

エンジンは解決済みの設定をオブジェクトの同一性でキャッシュします。そのため、設定をその場で書き換えて再ビルドすると前の結果が再利用されます。ビルドのたびに新しいオブジェクトを作ってください。レシピの設定がファクトリー関数config()になっているのはこのためです。 キャンバス上のページ →

つまずき

レイアウトの前にすべてのフォントを読み込む

レイアウトはブラウザーが読み込んだフォントで文字を計測し、その幅をキャッシュします。最初のビルドのあとに届いたフォントがあると改行位置が狂い、PDFも画面と一致しなくなります。すべてのウェイトとスタイルを先に読み込み、遅れて届いたときは再ビルドの前にclearMeasurementCache()を呼んでください。 レイアウト前のフォント読み込み →

  • 傍らのボックスのフェンスは段落全体のあとに置くので、番号を振る行が折り返すと、番号は折り返した行の横に付きます。80 mmなら『Lycidas』の行はどれも折り返しません。行長を狭めるときは、番号を振る行を確かめてください。
  • :::spaceはページの先頭で省かれるので、1ページから2ページへの変わり目にあたる14行目と15行目のあいだの詩節の区切りは見えません。すべての区切りを見せる必要がある版なら、1645年版のように、各詩節の最初の行を字下げしてください。
  • 傍らのボックスについてのカードは、注釈が段落の1行目と同じ高さから始まるよう、フェンスを段落の前に置くように勧めています。行番号は逆に、フェンスを行のあとに置き、マイナスのパディングで引き上げます。前に置くと、ページの先頭の行の番号が前のページの最終行の横まで滑り上がってしまいます(手順1)。

クレジット

レシピ
Ignacio Ferro
本文
  • Lycidas, with its headnote, in the text of Poems of Mr. John Milton (1645), pages 57–65, from the proofread Wikisource transcription of the 1927 facsimile; checked against H. C. Beeching’s Oxford text (Project Gutenberg eBook 1745) · John Milton · パブリックドメイン
  • The note on the text, the notes and the colophon · Ignacio Ferro · CC BY 4.0
画像
  • The sprig of bay laurel on the first page, a watercolour · Generated With Diffusion Models · オリジナル
フォント
Linden Hill (SIL OFL 1.1) · Imbue (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)
Sandbox