Коротко
Разворот муниципального справочника: кто чем заведует, в виде схемы из рамок с линиями, и где находится каждая служба, рядами картинок. Страницы собраны из нескольких повторяемых блоков, а сколько их, решает Markdown.
Что получится
Разворот из справочника служб Вальделомы, вымышленного города с 8400 жителями. Левая страница — схема управления мэрией: мэр и совет в красной рамке, четыре отдела в зелёных, а службы каждого отдела в бледных рамках под ним, соединённые зелёными линиями с точкой или стрелкой на конце. Правая страница показывает, где находятся службы: две панели по три акварели, под каждой название, адрес и часы работы, и рамка службы по работе с жителями. Ничего не нарисовано вручную. Шаблон хранит три модуля (отдел, панель с фото и объявление), и каждая страница ставит их друг под друга столько, сколько есть в её Markdown; линии идут за рамками туда, куда их ставит текст.
Рецепт отвечает на вопросы
- Как собрать оргсхему и фотосетку из готовых модулей, с линиями от шаблона?
Короткий ответ
// The page template draws the head of the chart and a group that takes the page's modules;
// the module draws one area: its box, a grid of its services and the lines between them.
const area = {
id: 'area', role: 'module',
frames: [
{ name: 'concejalia', style: 'area', width: mm(84), placement: at('container', 'top-left') },
{ name: 'servicio', style: 'servicio' }, // repeated: one per :::frame{slot="servicio"}
],
groups: [{ name: 'servicios', kind: 'grid', columns: 3, columnGap: mm(4), rowGap: mm(4),
repeat: { frames: ['servicio'] }, // rowAlign 'stretch': a row's boxes are one height
placement: { ...at('#concejalia', 'below', 0, 7), size: { width: 'fill', height: 'fill' } } }],
decoration: { elements: [
// From the area down to each of its services: a tree with a bar over the row.
line({ id: 'rama', routing: 'tree', from: { to: '#concejalia', side: 'bottom' },
to: { to: '#servicio[*]', side: 'top' }, endCap: 'dot', capSize: mm(1.8) }),
// From the mayor's box, a frame of the page, to this area: the spine and its branch.
line({ id: 'tronco', routing: 'elbow', width: pt(1.8),
from: { to: '#alcaldia', side: 'bottom', at: 0.06 }, to: { to: '#concejalia', side: 'left' },
endCap: 'arrow', capSize: mm(2.6) }),
] },
};
const chart = {
id: 'organigrama',
frames: [
{ name: 'titulo', takes: 'h1', width: mm(W), placement: at('container', 'top-left') },
{ name: 'entradilla', flow: true, width: mm(W) },
{ name: 'alcaldia', style: 'alcaldia', width: mm(96) },
],
groups: [{ name: 'cabeza', kind: 'stack', gap: mm(6),
frames: ['titulo', 'entradilla', 'alcaldia'] },
{ name: 'areas', modules: true, gap: mm(6), placement: { ...at('#alcaldia', 'below', SPINE, 9),
size: { width: mm(W - SPINE), height: 'fill' } } }],
};
Ингредиенты
- Возможности
- Модули друг под другом на страницеСоединительные линии между фреймамиСетки с повтором набора фреймовМакетные страницыФреймы, которые растут в группеОформление, привязанное к фреймамВрезкиЗеркальные поляКолонтитулы и колонцифрыРисунки и таблицы как ресурсыСемантическая палитраСтраницы на холстеЭкспорт в PDF
- Также применяет
- Нумерованные ярлыки врезокРисунки точно здесьШрифты, встроенные в PDFСобственные типы ресурсов
- Шрифты
- Public Sans, Source Serif 4 (SIL OFL 1.1)
- Материалы
biblioteca-900.jpgcentro-mayores-900.jpgmercado-900.jpgmusica-900.jpgpiscina-900.jpgpolideportivo-900.jpg- The reading room of a town library, in watercolour. (Generated With Diffusion Models, оригинал)
- Children with violins and a piano at a music school, in watercolour. (Generated With Diffusion Models, оригинал)
- Older people playing cards and painting at a day centre, in watercolour. (Generated With Diffusion Models, оригинал)
- A covered pool under a timber roof, in watercolour. (Generated With Diffusion Models, оригинал)
- Children playing basketball in a sports hall, in watercolour. (Generated With Diffusion Models, оригинал)
- A Saturday market under the arcades of a town square, in watercolour. (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · По модулю на отдел
// The page template draws the head of the chart and a group that takes the page's modules;
// the module draws one area: its box, a grid of its services and the lines between them.
const area = {
id: 'area', role: 'module',
frames: [
{ name: 'concejalia', style: 'area', width: mm(84), placement: at('container', 'top-left') },
{ name: 'servicio', style: 'servicio' }, // repeated: one per :::frame{slot="servicio"}
],
groups: [{ name: 'servicios', kind: 'grid', columns: 3, columnGap: mm(4), rowGap: mm(4),
repeat: { frames: ['servicio'] }, // rowAlign 'stretch': a row's boxes are one height
placement: { ...at('#concejalia', 'below', 0, 7), size: { width: 'fill', height: 'fill' } } }],
decoration: { elements: [
// From the area down to each of its services: a tree with a bar over the row.
line({ id: 'rama', routing: 'tree', from: { to: '#concejalia', side: 'bottom' },
to: { to: '#servicio[*]', side: 'top' }, endCap: 'dot', capSize: mm(1.8) }),
// From the mayor's box, a frame of the page, to this area: the spine and its branch.
line({ id: 'tronco', routing: 'elbow', width: pt(1.8),
from: { to: '#alcaldia', side: 'bottom', at: 0.06 }, to: { to: '#concejalia', side: 'left' },
endCap: 'arrow', capSize: mm(2.6) }),
] },
};
const chart = {
id: 'organigrama',
frames: [
{ name: 'titulo', takes: 'h1', width: mm(W), placement: at('container', 'top-left') },
{ name: 'entradilla', flow: true, width: mm(W) },
{ name: 'alcaldia', style: 'alcaldia', width: mm(96) },
],
groups: [{ name: 'cabeza', kind: 'stack', gap: mm(6),
frames: ['titulo', 'entradilla', 'alcaldia'] },
{ name: 'areas', modules: true, gap: mm(6), placement: { ...at('#alcaldia', 'below', SPINE, 9),
size: { width: mm(W - SPINE), height: 'fill' } } }],
};
Шаблон с role: 'module' — модуль: несколько фреймов, групп и украшений, которые будут повторяться. На странице схемы есть группа с modules: true, и каждый :::module{template="area"} её Markdown ставит ещё один отдел под предыдущим, с зазором 6 мм. Фреймы модуля получают имя экземпляра, area[1].concejalia, area[2].concejalia…, поэтому две его соединительные линии описаны один раз: rama, tree от низа отдела к каждой службе его сетки (#servicio[*]), и tronco, elbow от точки у левого края рамки мэра (at: 0.06) к левой стороне отдела. #alcaldia — фрейм страницы, а не модуля: модуль хранит конец линии, а вёрстка находит его на странице, поэтому четыре линии с изгибом делят первый отрезок и читаются как один ствол со стрелкой к каждому отделу. Службы — сетка в три колонки, которая повторяет один фрейм servicio, поэтому отдел с двумя службами рисует две рамки, и у дерева два отвода.
#2 · Панели с карточками фото
const gallery = {
id: 'galeria', role: 'module',
frames: [
{ name: 'cabecera', takes: 'h2', placement: at('container', 'top-left', 4, 4) },
{ name: 'foto', style: 'marco' }, // the photo of a card
{ name: 'pie', style: 'ficha', placement: at('#foto', 'below', 0, 2.5) }, // and its words
],
groups: [{ name: 'fotos', kind: 'grid', columns: 3, columnGap: mm(5), rowGap: mm(6),
rowAlign: 'start', repeat: { frames: ['foto', 'pie'] },
placement: { ...at('#cabecera', 'below', 0, 3), size: { width: mm(W - 8), height: 'fill' } } }],
// The module's own ground: a tint as large as the module, whatever its rows.
decoration: { elements: [{ kind: 'box', id: 'suelo',
placement: { ...at('container', 'top-left'), size: { width: 'fill', height: 'fill' } },
style: { backgroundColor: col('tint'), borderRadius: mm(3) } }] },
};
// A notice box as a module of its own: one frame whose tab grows out of the box (joined).
const notice = { id: 'aviso', role: 'module', frames: [{ name: 'texto', style: 'aviso',
placement: at('container', 'top-left', 0, 7) }] };
const places = {
id: 'centros',
frames: [
{ name: 'titulo', takes: 'h1', width: mm(W), placement: at('container', 'top-left') },
{ name: 'entradilla', flow: true, width: mm(W) },
{ name: 'colofon', style: 'colofon', optional: true, width: mm(W),
placement: at('container', 'bottom-left', 0, 8) },
],
groups: [{ name: 'cabeza', kind: 'stack', gap: mm(5), frames: ['titulo', 'entradilla'] },
{ name: 'galerias', modules: true, gap: mm(7), placement: { ...at('#entradilla', 'below', 0, 7),
size: { width: mm(W), height: 'fill' } } }],
};
Панель — тоже модуль: фрейм заголовка, который берёт заголовок ## модуля, и сетка, повторяющая набор из двух фреймов, фото и слов под ним. Каждый :::frame{slot="foto"} — одна карточка, а :::frame{slot="pie"} внутри него относится к словам этой карточки. Подложка — украшение модуля, прямоугольник величиной с модуль, поэтому она растёт вместе с рядами и самой длинной подписью. Служба по работе с жителями — третий модуль, одна рамка с ярлыком joined: ярлык и рамка образуют один контур с одной заливкой.
#3 · Картинки в том размере, в каком печатаются
const ART = {
biblioteca: t({ es: 'La sala de lectura de la biblioteca, con estanterías de madera y vecinos '
+ 'de todas las edades leyendo en mesas largas.',
en: 'The library reading room, with wooden shelves and neighbours of every age reading at '
+ 'long tables.' }),
musica: t({ es: 'Un aula de la escuela de música: niños con violines, una profesora y una niña '
+ 'al piano.',
en: 'A room of the music school: children with violins, a teacher and a girl at the piano.' }),
'centro-mayores': t({ es: 'El centro de día: mayores jugando a las cartas y pintando junto a '
+ 'una puerta al jardín.',
en: 'The day centre: older people playing cards and painting beside a door to the garden.' }),
piscina: t({ es: 'La piscina cubierta bajo un techo de madera, con nadadores en las calles y un '
+ 'socorrista.',
en: 'The covered pool under a timber roof, with swimmers in the lanes and a lifeguard.' }),
polideportivo: t({ es: 'La pista del polideportivo, con niños jugando al baloncesto y gradas a '
+ 'un lado.',
en: 'The sports hall court, with children playing basketball and stands along one side.' }),
mercado: t({ es: 'El mercado de los sábados en los soportales de la plaza, con el ayuntamiento '
+ 'al fondo.',
en: 'The Saturday market under the arcades of the square, with the town hall behind.' }),
};
const resources = await Promise.all(Object.entries(ART).map(async ([id, altText]) => {
const fileId = `${id}-900.jpg`;
await loadImage(fileId, asset(fileId));
return { id, typeId: 'foto', kind: 'bitmap', caption: '', altText, createdAt: 0, updatedAt: 0,
bitmap: { fileId, format: 'jpeg', width: 900, height: 600, resolution: 400 } };
}));
Шесть акварелей по 900 × 600 px объявлены с 400 ppi, то есть шириной 57 мм, примерно с колонку сетки, поэтому сетка их никогда не увеличивает. Альтернативный текст стоит здесь в скрипте, потому что картинки в обеих версиях одинаковы; подпись, меняющаяся с языком, была бы строкой ::caption в Markdown.
#4 · Один зелёный для линий и рамок
const palette = {
ink: '#1f2b2a', // text
green: '#1d6b57', // the lines of the chart, the areas' boxes, the headings
mayor: '#a8452e', // the box at the head of the chart
tint: '#e6f1ec', // the services' boxes and the galleries' ground
rule: '#b9cbc3', // the hairline round a service
muted: '#5c6b67', // running heads and the colophon
paper: '#ffffff',
};
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: 'green (defaults)', value: { hex: palette.green, model: 'hex' } },
];
Соединительные линии, рамки отделов и заголовки панелей берут green, запись палитры, поэтому город с другим цветом меняет одно значение hex. Рамке мэра достаётся единственный тёплый цвет разворота, туда читатель смотрит сначала.
Рецепт целиком
// ═══ Postext Cookbook · Nº 162 · An org chart and a photo grid built from modules ═══
// https://postext.dev/en/cookbook/org-chart-from-modules
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Public Sans, Source Serif 4 (SIL OFL 1.1) · Needs postext ≥ 1.65.0
import {
buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('es' | 'en')
const RECIPE = 'org-chart-from-modules';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: an ink, the town's green for the lines and the areas, a warm mayor's box
const palette = {
ink: '#1f2b2a', // text
green: '#1d6b57', // the lines of the chart, the areas' boxes, the headings
mayor: '#a8452e', // the box at the head of the chart
tint: '#e6f1ec', // the services' boxes and the galleries' ground
rule: '#b9cbc3', // the hairline round a service
muted: '#5c6b67', // running heads and the colophon
paper: '#ffffff',
};
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: 'green (defaults)', value: { hex: palette.green, model: 'hex' } },
];
// #endregion
const SANS = 'Public Sans', SERIF = 'Source Serif 4';
const PAGE = { w: 210, h: 297, top: 22, bottom: 22, inner: 18, outer: 15 }; // mm, mirrored
const W = PAGE.w - PAGE.inner - PAGE.outer; // the type area's width: 177 mm
const SPINE = 12; // mm: the room on the left of the areas where the chart's spine runs down
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const line = (more) => ({ kind: 'connector', color: col('green'), width: pt(1.2), radius: mm(2.5),
...more });
// #region answer: a module per area of the town hall, stacked by the page's modules group
// The page template draws the head of the chart and a group that takes the page's modules;
// the module draws one area: its box, a grid of its services and the lines between them.
const area = {
id: 'area', role: 'module',
frames: [
{ name: 'concejalia', style: 'area', width: mm(84), placement: at('container', 'top-left') },
{ name: 'servicio', style: 'servicio' }, // repeated: one per :::frame{slot="servicio"}
],
groups: [{ name: 'servicios', kind: 'grid', columns: 3, columnGap: mm(4), rowGap: mm(4),
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Службы в две колонки
При columns: 2 службы каждого отдела стоят по две в ряд; дерево ведёт перекладину только над первым рядом, поэтому оставьте его для отделов с двумя или четырьмя службами.
- groups: [{ name: 'servicios', kind: 'grid', columns: 3, columnGap: mm(4), rowGap: mm(4),
+ groups: [{ name: 'servicios', kind: 'grid', columns: 2, columnGap: mm(4), rowGap: mm(4),#Скруглить углы ствола
radius скругляет изгибы ломаных линий и дерева: вспомогательная line() даёт каждой линии 2,5 мм; с radius: mm(0) схема поворачивает под прямым углом.
Частые ошибки
- Пункт сетки — собственное ограждение: слова карточки относятся к ней, только если их
:::frame{slot="pie"}записан внутри:::frame{slot="foto"}этой карточки. - Соединительная линия модуля, которая называет фрейм страницы, рисуется только на страницах, где этот фрейм есть; на другой странице её пропускают, и журнал перевёрстки пишет
connectorDropped. - Присоединённый ярлык сидит на краю рамки и берёт её заливку: задайте его словам тёмный
color, потому что белая надпись на бледной рамке не читается.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- A guide to the council services of Valdeloma, an invented town, written for this recipe in Spanish and English · Postext Cookbook · CC BY 4.0
- Изображения
- The reading room of a town library, in watercolour. · Generated With Diffusion Models · оригинал
- Children with violins and a piano at a music school, in watercolour. · Generated With Diffusion Models · оригинал
- Older people playing cards and painting at a day centre, in watercolour. · Generated With Diffusion Models · оригинал
- A covered pool under a timber roof, in watercolour. · Generated With Diffusion Models · оригинал
- Children playing basketball in a sports hall, in watercolour. · Generated With Diffusion Models · оригинал
- A Saturday market under the arcades of a town square, in watercolour. · Generated With Diffusion Models · оригинал
- Шрифты
- Public Sans (SIL OFL 1.1) · Source Serif 4 (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


