Коротко
Страница, сделанная как арабские книги, печатавшиеся в Каире в XIX веке: основной текст посередине, короткие примечания к нему в узкой колонке у края, вся страница обведена линейками.
Что получится
Шесть страниц, набранных так, как Булакская типография и её каирские преемники печатали комментарий в XIX веке. Объяснение Ибн Акиля к первым стихам «Альфии», грамматики Ибн Малика в тысячу строк, идёт в основной колонке, стихи красным; на внешнем поле стоит хашия, короткие глоссы, каждая из которых открывается поясняемыми словами текста и стоит рядом с нужным местом. Двойная линейка обрамляет полосу набора, с плашкой вверху для главы и колонцифры, а одинарная отделяет текст от поля. На настоящей булакской странице хашия обходит текст с трёх сторон; Postext ставит её с одной, и рецепт об этом говорит.
Рецепт отвечает на вопросы
- Как сверстать булакскую страницу, где комментарий обрамляет текст?
Короткий ответ
// The text runs in the main column of a column-and-a-half layout; the side column, on the
// outer side, takes only boxes with span 'side'. A gloss is written before the passage it
// explains and starts level with its first line, on the page where that passage goes on
// (sideAtColumnEnd: 'after'). A column rule parts the two, as the jadwal of a Bulaq page does.
const layout = { layoutType: 'oneAndHalf', sideColumnRole: 'floats', sideColumnSide: 'outer',
sideColumnPercent: 31, gutterWidth: mm(7),
columnRule: { enabled: true, color: col('rule'), lineWidth: pt(0.6) } };
// A gloss is a callout with no box: the margin's own face, its lemma bold in the rubric.
const hashiya = { id: 'hashiya', span: 'side', sideAtColumnEnd: 'after',
backgroundEnabled: false, borderRadius: pt(0),
padding: { top: pt(0), right: pt(0), bottom: pt(0), left: pt(0) },
stripe: { enabled: false }, border: { enabled: false },
body: { fontFamily: NASKH, fontSize: pt(10), lineHeight: pt(16), color: col('ink'),
boldColor: col('rubric'), textAlign: 'justify', firstLineIndent: pt(0),
paragraphSpacing: true } };
Ингредиенты
- Возможности
- Примечания на поляхТекст, линейки и рамки в дизайне страницыТекст справа налевоПолторы колонкиКолонка на полях для плавающих объектовЛинейка между колонкамиКниги с переплётом справаАрабские шрифтыАрабский как язык документаАрабские стихи (бейт в двух полустишиях)Цифры номеров, которые ставит движокОбложки, титулы и колофоныСтили заголовковАтрибуты заголовковКолонтитулы и колонцифрыЦвет бумагиСтили абзацевАбзацы в другом направленииСемантическая палитраЭкспорт в PDF
- Также применяет
- ВрезкиОформленные начальные полосыКолонтитулы по роли страницыШрифты, встроенные в PDFКолонтитулы разделов
- Шрифты
- Amiri, Aref Ruqaa (SIL OFL 1.1)
- Материалы
- Нет: все иллюстрации рисует код
Порядок работы
#1 · Хашия в собственной боковой колонке
Код приведён выше, в коротком ответе. Вёрстка в полторы колонки, где боковая принимает только плавающие объекты, не пускает комментарий в поток текста: каждая глосса — :::callout{type="hashiya" span="side"}, записанная перед поясняемым местом, и начинается она вровень с его первой строкой; sideAtColumnEnd: 'after' держит её рядом с этим местом, когда оно переходит на следующую страницу (вёрстка). У врезки нет ни фона, ни рамки, ни внутренних отступов, поэтому она читается как текст на поле, а поясняемые слова набраны полужирным, который boldColor делает красным. sideColumnSide: 'outer' ставит колонку у внешнего края обеих страниц: на чётной странице, которая в книге с правым переплётом лежит справа, это правый край.

#2 · Рамка для каждой стороны разворота
// Page-level design elements are physical: the frame follows the margins of each side of
// the spread. In a book bound on the right the even page is the right-hand one, its spine
// on its left, so its inner margin is the left one. A heading's design is set in the flow
// and mirrored with the page (inFlow): there 'left' is the sheet's right.
const frame = (parity, withBand = true, inFlow = false) => {
const left = (parity === 'even') !== inFlow ? M.inner : M.outer;
const width = TRIM.width - M.inner - M.outer;
const box = (id, inset, thickness) => ({ kind: 'box', id: `${id}-${parity}`, parity,
style: { borderColor: col('rule'), borderWidth: pt(thickness) },
placement: { anchor: { to: 'page', edge: 'top-left' },
offset: { x: mm(left - 4 + inset), y: mm(M.top - 13 + inset) },
size: { width: mm(width + 8 - 2 * inset),
height: mm(TRIM.height - M.top - M.bottom + 17 - 2 * inset) } } });
return [box('outer', 0, 1.4), box('inner', 1.3, 0.4), ...(withBand ? [
{ kind: 'rule', id: `band-${parity}`, parity, direction: 'horizontal', thickness: pt(0.4),
color: col('rule'), placement: { anchor: { to: 'page', edge: 'top-left' },
offset: { x: mm(left - 2.7), y: mm(M.top - 4) },
size: { width: mm(width + 5.4) } } }] : [])];
};
// The chapter centred in the band, the folio at its outer end. The frame stands off the
// sheet's centre by half the difference of the margins, towards the outer edge.
const SHIFT = (M.inner - M.outer) / 2; // mm
const band = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
parity, pages: 'body', fontFamily: NASKH, fontWeight: 700, fontSize: pt(10.5),
color: col('ink'),
placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(M.top - 11) } }, ...extra });
const header = { elements: [...frame('even'), ...frame('odd'),
band('head-even', '{chapterTitle}', 'even', 'top', SHIFT),
band('head-odd', '{chapterTitle}', 'odd', 'top', -SHIFT),
band('folio-even', '{pageNumber}', 'even', 'top-right', -(M.outer + 1), { pages: 'all' }),
band('folio-odd', '{pageNumber}', 'odd', 'top-left', M.outer + 1, { pages: 'all' })] };
Рамка — три элемента оформления страницы в верхнем колонтитуле: два прямоугольника с обводкой без заливки, с промежутком 1,3 мм, и линейка под плашкой с колонтитулом. Элементы страницы физические, поэтому рамка построена дважды, по разу на чётность, от полей своей стороны (порядок страниц и правый переплёт). Колонцифра стоит у внешнего конца плашки на каждой странице, включая начальные; название главы центрировано и на начальной полосе опущено: там под ним стоит сам заголовок.
#3 · Титул внутри той же рамки
const line = (id, content, y, style) => ({ kind: 'text', id, content, align: 'center',
overflow: 'wrap', color: col('ink'),
// Centred in the frame: the title page is an odd page set in the mirrored flow.
placement: { anchor: { to: 'page', edge: 'top' }, offset: { x: mm(SHIFT), y: mm(y) },
size: { width: mm(110) } }, ...style });
const titlePage = { id: 'title', span: 'page', runningChapter: false,
breakBefore: { enabled: true, parity: 'any' }, header: { elements: [] },
footer: { elements: [] },
advancedDesign: { enabled: true, slot: { elements: [...frame('odd', false, true),
line('book', '{titleText}', 64, { fontFamily: RUQAA, fontWeight: 700, fontSize: pt(40),
lineHeight: 1.3, color: col('rubric') }),
line('on', '{attr.on}', 88, { fontFamily: NASKH, fontWeight: 700, fontSize: pt(17) }),
{ kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.75), color: col('rubric'),
placement: { anchor: { to: 'page', edge: 'top' }, offset: { x: mm(SHIFT), y: mm(104) },
size: { width: mm(30) } } },
line('margin', '{attr.margin}', 112, { fontFamily: NASKH, fontSize: pt(13) }),
line('latin', '{attr.latin}', 196, { fontFamily: NASKH, fontSize: pt(9), italic: true,
color: col('muted') }),
] } } };
Титул использует ту же рамку без плашки. Оформление заголовка стоит в потоке и зеркалится вместе со страницей, поэтому там рамка построена с переставленными сторонами (inFlow): её левая сторона — правая сторона листа. Строки титула берутся из атрибутов заголовка, on и margin, поэтому весь титул — одна строка Markdown, а латинская строка под ними меняется вместе с языковой версией.
Рецепт целиком
// ═══ Postext Cookbook · Nº 114 · A Bulaq page: the text framed by its commentary ════════
// https://postext.dev/en/cookbook/bulaq-framed-page
// Code: MIT · Text: Ibn ʿAqīl, Sharḥ; Ibn Mālik, Alfiyya, ar.wikisource (PD) · Pictures: none
// Fonts: Amiri, Aref Ruqaa (SIL OFL 1.1) · Needs postext ≥ 1.28.0
import { buildDocument, withLoadedFonts, renderPageToCanvas } from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'bulaq-framed-page';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Black and a brown-red on a toned paper: the two inks of a Cairo press around 1900.
const palette = {
ink: '#1d1915', // text and frame rules
rubric: '#8e3020', // the accent: lemmas of the glosses, the matn, titles
rule: '#3a312a', // the frame
muted: '#6a6056', // the note on the text
paper: '#f6efe0', // a toned paper
};
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: 'rubric (defaults)', value: { hex: palette.rubric, model: 'hex' } },
];
const NASKH = 'Amiri'; // the text, the matn and the glosses
const RUQAA = 'Aref Ruqaa'; // the title page and the chapter title
const TRIM = { width: 170, height: 240 }; // mm
const M = { top: 34, bottom: 24, inner: 20, outer: 15 }; // mm: the type area inside the frame
// #region answer: the commentary's column beside the text, both inside one ruled frame
// The text runs in the main column of a column-and-a-half layout; the side column, on the
// outer side, takes only boxes with span 'side'. A gloss is written before the passage it
// explains and starts level with its first line, on the page where that passage goes on
// (sideAtColumnEnd: 'after'). A column rule parts the two, as the jadwal of a Bulaq page does.
const layout = { layoutType: 'oneAndHalf', sideColumnRole: 'floats', sideColumnSide: 'outer',
sideColumnPercent: 31, gutterWidth: mm(7),
columnRule: { enabled: true, color: col('rule'), lineWidth: pt(0.6) } };
// A gloss is a callout with no box: the margin's own face, its lemma bold in the rubric.
const hashiya = { id: 'hashiya', span: 'side', sideAtColumnEnd: 'after',
backgroundEnabled: false, borderRadius: pt(0),
padding: { top: pt(0), right: pt(0), bottom: pt(0), left: pt(0) },
stripe: { enabled: false }, border: { enabled: false },
body: { fontFamily: NASKH, fontSize: pt(10), lineHeight: pt(16), color: col('ink'),
boldColor: col('rubric'), textAlign: 'justify', firstLineIndent: pt(0),
paragraphSpacing: true } };
// #endregion
// #region frame: a double rule round the type area and a band for the running head
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Поставьте комментарий у корешка
Некоторые типографии ставили хашию у корешка, и тогда более широкое внешнее поле остаётся за текстом.
-const layout = { layoutType: 'oneAndHalf', sideColumnRole: 'floats', sideColumnSide: 'outer',
+const layout = { layoutType: 'oneAndHalf', sideColumnRole: 'floats', sideColumnSide: 'inner',#Обведите каждую глоссу
Тонкая рамка вокруг каждой глоссы, как в некоторых более поздних каирских изданиях, — это обводка самой врезки.
- stripe: { enabled: false }, border: { enabled: false },
+ stripe: { enabled: false }, border: { enabled: true, width: pt(0.4), color: col('rule') },Частые ошибки
Подводный камень
Помечайте арабскую книгу 'ar', а не LANG
Издания рецепта — en и es, но арабский образец в обоих арабский: `locale: LANG` набрал бы его слева направо, поставил бы переплёт слева, пронумеровал бы страницы 1 2 3 и подписал бы рисунки Figure или Figura. Начиная с postext 1.30 тег — это ещё и язык, на котором формируется текст (измеряется, рисуется и встраивается): под английским или испанским тегом начертание вроде Markazi Text не рисует арабских форм своих кавычек-ёлочек и точек, и строки разрываются иначе. Пишите тег сами: 'ar' (арабско-индийские цифры, нормы Машрика), регион, например 'ar-EG' или 'ar-SA', либо 'ar-MA', 'ar-DZ' или 'ar-TN' для издания Магриба с европейскими цифрами. Латинская страница, которая лишь цитирует арабский, сохраняет свою локаль. Текст справа налево →
Подводный камень
Арабским шрифтам нужен файл arabic, через блок arabic
Fontsource отдаёт Amiri, Noto Naskh Arabic или Scheherazade New по файлу на набор знаков, и арабские буквы лежат в файле arabic. loadFonts загружает только latin (и latin-ext), поэтому на экране арабский берётся из системного шрифта и измеряется неверно, а fontsourceProvider отдаёт PDF тот же файл latin, и печатаются пустые квадраты. Укажите блок arabic набора kit, вызовите loadArabicFonts(FONTS, markdown) после loadFonts, перечислив в FONTS все насыщенности арабского набора, и передайте renderToPdf fontProvider: arabicPdfProvider. Арабские шрифты →
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Ibn ʿAqīl’s commentary on the opening of the Alfiyya, with Ibn Mālik’s verses, as ar.wikisource gives it (revision 521625), without the modern editor’s footnotes · Ibn ʿAqīl, Ibn Mālik · общественное достояние
- The glosses in the margin, the title page, the note on the text and the colophon · Postext Cookbook · оригинал
- Шрифты
- Amiri (SIL OFL 1.1) · Aref Ruqaa (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


