feat(covergen): генератор обложек-плейсхолдеров для постов
Инструмент в tools/covergen: SVG 1200x630, детерминированный от слага (FNV-1a -> mulberry32 -> палитра), 5 стилей (poster, bauhaus, constructivist, aurora, paper), типографика с переносом и подбором кегля, аудит геометрии и WCAG-контраста, CLI для одной обложки и для манифеста. Без зависимостей, node >= 18, 12 тестов (node --test) — проходят в этой раскладке. Документация и объём работ по встраиванию в сайт: docs/covergen.md, задача #1.
@@ -0,0 +1,80 @@
|
||||
# Генератор обложек-плейсхолдеров для постов (`tools/covergen`)
|
||||
|
||||
Задача на внедрение: **#1** в этом репозитории (Gitea issues).
|
||||
|
||||
## Что это
|
||||
|
||||
Небольшой генератор SVG-обложек без зависимостей: из названия поста получается картинка
|
||||
1200×630 (или любого размера), **детерминированная** от слага. Одинаковый вход всегда даёт
|
||||
одну и ту же обложку, поэтому пересборка сайта не перекрашивает старые посты.
|
||||
|
||||
Схема повторяет плейсхолдеры BookOrbit (`client/src/features/book/lib/placeholder/`):
|
||||
seed → палитра → типографика → SVG-шаблон стиля.
|
||||
|
||||
## Где лежит
|
||||
|
||||
```
|
||||
tools/covergen/
|
||||
├── bin/covergen.js CLI (одна обложка или манифест)
|
||||
├── lib/palette.js FNV-1a + mulberry32 → палитра из слага
|
||||
├── lib/typeset.js ширина строки без canvas, перенос, подбор кегля, XML-экранирование
|
||||
├── lib/styles/index.js 5 стилей: poster, bauhaus, constructivist, aurora, paper
|
||||
├── lib/render.js сборка SVG, дефолты, валидация
|
||||
├── lib/audit.js аудит геометрии и WCAG-контраста
|
||||
├── test/covergen.test.js 12 тестов (node --test)
|
||||
└── examples/ posts.json + по одному примеру на стиль
|
||||
```
|
||||
|
||||
## Запуск
|
||||
|
||||
Зависимостей нет, нужен Node.js ≥ 18 (на bigbox — 22).
|
||||
|
||||
```bash
|
||||
cd tools/covergen
|
||||
node --test # 12 тестов
|
||||
|
||||
node bin/covergen.js \
|
||||
--title "Смысловая пустота" \
|
||||
--subtitle "2026-11-14 · текст" \
|
||||
--tags "дизайн,типографика" \
|
||||
--slug smysl --style poster --out /tmp/smysl.svg --audit
|
||||
```
|
||||
|
||||
Пакетно из манифеста (его же удобно собирать из front matter):
|
||||
|
||||
```bash
|
||||
node bin/covergen.js --manifest examples/posts.json --outdir static/covers --audit
|
||||
```
|
||||
|
||||
Параметры: `--title` (обязателен), `--subtitle`, `--author`, `--tags "a,b"`, `--slug`
|
||||
(seed, по умолчанию из title), `--style auto|poster|bauhaus|constructivist|aurora|paper`,
|
||||
`--width`/`--height` (по умолчанию 1200×630), `--out`, `--png`, `--audit`.
|
||||
`--style auto` выбирает стиль хэшем слага — стабильно для каждого поста.
|
||||
|
||||
## Что дальше (объём работ по задаче #1)
|
||||
|
||||
1. `scripts/gen-covers.mjs` — собрать манифест из `content/` (front matter: `title`, `date`,
|
||||
`slug`, `tags`; опционально `cover_style`), вызвать генератор, положить
|
||||
`static/covers/<slug>.svg` и `static/covers/<slug>.png` (1200×630 для `og:image`).
|
||||
Не перегенерировать, если файл уже есть и манифест не менялся.
|
||||
2. `layouts/partials/cover.html` — `<img src="/covers/<slug>.svg">` с fallback.
|
||||
3. `<head>`: `og:image` → PNG, плюс `og:image:width/height` 1200/630; в списках — та же
|
||||
обложка меньшего размера (единое соотношение, без «прыжков» высоты).
|
||||
4. CI: шаг «Generate covers» перед `hugo` в `.gitea/workflows/deploy.yml`.
|
||||
SVG — обязателен; PNG — если в образе есть `resvg`/`rsvg-convert`, иначе через
|
||||
headless-chromium (`chromium --headless=new --screenshot=... file:///abs/cover.svg`).
|
||||
5. README/`docs/` — как перегенерировать обложки и как зафиксировать стиль поста
|
||||
(`cover_style: bauhaus` во front matter).
|
||||
|
||||
Критерии готовности — в задаче #1.
|
||||
|
||||
## Ограничения и известные места
|
||||
|
||||
- Соцсети не принимают SVG: для `og:image` нужен PNG.
|
||||
- Шрифты не встраиваются: SVG ссылается на системные семейства
|
||||
(`Inter/Helvetica/Arial`, `Georgia/serif`, monospace). Для одинакового вида на всех
|
||||
машинах либо ставить эти шрифты в CI-образе, либо перевести `lib/styles/index.js`
|
||||
на встроенный subset — это отдельное решение, не блокирует запуск.
|
||||
- `--audit` проверяет: текст не выходит за кадр, кегль ≥ 12 px, `fill-opacity` ≥ 0.45,
|
||||
контраст ≥ 4.5 (WCAG AA). Возвращает код 1 при замечаниях — годится как гейт в CI.
|
||||
- Примеры в `examples/` — это эталон вида; при правке стилей их стоит перегенерировать.
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
*.log
|
||||
covers/
|
||||
@@ -0,0 +1,111 @@
|
||||
# covergen — детерминированные обложки-плейсхолдеры для постов
|
||||
|
||||
Генератор SVG-обложек без зависимостей: одна команда → картинка 1200×630 (или любой размер),
|
||||
детерминированная от слага. Одинаковый вход всегда даёт одну и ту же обложку, поэтому
|
||||
пересборка сайта не «перекрашивает» статьи.
|
||||
|
||||
Сделано по мотивам плейсхолдеров BookOrbit (`client/src/features/book/lib/placeholder/`):
|
||||
палитра из хэша seed → типографика под длину заголовка → SVG-шаблон стиля.
|
||||
|
||||
## Установка
|
||||
|
||||
Зависимостей нет, нужен только Node.js ≥ 18.
|
||||
|
||||
```bash
|
||||
git clone <repo> covergen && cd covergen
|
||||
node --test # 11 тестов
|
||||
```
|
||||
|
||||
## Использование
|
||||
|
||||
```bash
|
||||
# одна обложка
|
||||
node bin/covergen.js \
|
||||
--title "Смысловая пустота" \
|
||||
--subtitle "2026-11-14 · текст" \
|
||||
--tags "дизайн,типографика" \
|
||||
--slug smysl \
|
||||
--style poster \
|
||||
--out covers/smysl.svg
|
||||
```
|
||||
|
||||
```bash
|
||||
# пакетно из манифеста (например, сгенерированного из front matter Hugo)
|
||||
node bin/covergen.js --manifest posts.json --outdir static/covers
|
||||
```
|
||||
|
||||
```json
|
||||
[
|
||||
{ "slug": "smysl", "title": "Смысловая пустота", "subtitle": "2026-11-14 · текст", "tags": ["дизайн"] },
|
||||
{ "slug": "backup", "title": "Бэкап, который восстанавливается", "subtitle": "2026-09-12 · бэкапы", "author": "Евгений Стороженко" }
|
||||
]
|
||||
```
|
||||
|
||||
Параметры: `--title` (обязателен), `--subtitle`, `--author`, `--tags "a,b"`, `--slug` (seed;
|
||||
по умолчанию из title), `--style` (`auto` или один из стилей), `--width`/`--height`
|
||||
(по умолчанию 1200×630), `--out`, `--png`, `--audit`.
|
||||
|
||||
`--png` дополнительно рендерит PNG — нужен `resvg` или `rsvg-convert` в PATH (см. ниже).
|
||||
Без них SVG создаётся, а в stderr уходит предупреждение (код возврата остаётся 0).
|
||||
|
||||
`--audit` проверяет готовый SVG без рендера: что текст не выходит за кадр, кегль не мельче
|
||||
12 px, `fill-opacity` не ниже 0.45 и контраст палитры не ниже 4.5 (WCAG AA). Печатает
|
||||
`audit ok — <файл>: текста N, контраст X` и возвращает код 1 при замечаниях — удобно как
|
||||
гейт в CI.
|
||||
|
||||
## Стили
|
||||
|
||||
| Стиль | Как выглядит | Когда уместен |
|
||||
| --- | --- | --- |
|
||||
| `poster` | тёмный градиент, тонкая рамка, крупный заголовок по центру | универсальный, лучше всего для длинных заголовков |
|
||||
| `bauhaus` | круг/плашка/треугольник, заголовок слева снизу | технические заметки, «дизайнерские» посты |
|
||||
| `constructivist` | диагональные плашки, наклонный заголовок капсом | манифесты, резкие темы |
|
||||
| `aurora` | мягкие радиальные пятна, серифный заголовок | лонгриды, эссе |
|
||||
| `paper` | светлое поле, линейки, сериф | текст, документация, ретро |
|
||||
|
||||
`--style auto` выбирает стиль хэшем слага — стабильно для каждого поста.
|
||||
|
||||
## Как это работает
|
||||
|
||||
1. `lib/palette.js`: FNV-1a хэш слага → `mulberry32` rng → семейство цветов, сдвиг оттенка,
|
||||
акцент. Никакого `Math.random()` — только seed.
|
||||
2. `lib/typeset.js`: грубая оценка ширины строки (без canvas), перенос по словам, подбор кегля
|
||||
от максимума к минимуму, подрезка длинных слов многоточием, экранирование XML.
|
||||
3. `lib/styles/index.js`: пять SVG-шаблонов, каждый получает палитру, готовые строки и uid для
|
||||
уникальных id градиентов.
|
||||
4. `lib/render.js`: собирает документ, дефолты и валидация входа.
|
||||
|
||||
## Встраивание в Hugo
|
||||
|
||||
Два варианта, оба без сервера.
|
||||
|
||||
**A. Предгенерация в репозитории (проще).** Скрипт собирает манифест из front matter
|
||||
(`title`, `date`, `tags`, `slug`) и кладёт обложки в `static/covers/<slug>.svg`; в шаблоне
|
||||
используется `resources.Get`/прямой путь. Плюс: обложка — обычный статический файл, работает
|
||||
с любым CDN.
|
||||
|
||||
**B. Hugo-пайплайн.** `resources.FromString` + шаблон-обёртка вокруг вывода генератора — дольше
|
||||
и хрупче, зато без коммита артефактов. Для блога с десятками постов вариант A предпочтительнее.
|
||||
|
||||
**og:image.** Соцсети не принимают SVG. Для `og:image` нужен PNG 1200×630:
|
||||
|
||||
```bash
|
||||
# любой из вариантов
|
||||
resvg --use-fonts-dir /usr/share/fonts cover.svg cover.png
|
||||
rsvg-convert -o cover.png cover.svg
|
||||
# либо headless-chromium (медленнее, но без установки пакетов)
|
||||
chromium --headless=new --no-sandbox --window-size=1200,630 \
|
||||
--screenshot=cover.png file:///abs/path/cover.svg
|
||||
```
|
||||
|
||||
Рекомендуется генерировать SVG и PNG на этапе CI и складывать в `static/covers/`.
|
||||
|
||||
## Тесты
|
||||
|
||||
```bash
|
||||
node --test
|
||||
```
|
||||
|
||||
Покрыто: детерминированность (байт-в-байт), разные палитры для разных seed, все стили дают
|
||||
корректный SVG заданного размера, экранирование `<script>`/`&`, перенос и подрезка длинных
|
||||
заголовков, стабильность хэша.
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
const { render, STYLE_NAMES } = require('../lib/render');
|
||||
const { audit } = require('../lib/audit');
|
||||
const { paletteFor } = require('../lib/palette');
|
||||
|
||||
const USAGE = `covergen — детерминированные обложки-плейсхолдеры для постов
|
||||
|
||||
Одна обложка:
|
||||
covergen --title "Смысловая пустота" [--subtitle "2026-11-14 · текст"]
|
||||
[--author "Евгений Стороженко"] [--tags "hugo,дизайн"] [--slug smysl]
|
||||
[--style auto|${STYLE_NAMES.join('|')}] [--width 1200] [--height 630]
|
||||
[--out covers/smysl.svg] [--png] [--audit]
|
||||
|
||||
Пакетно из манифеста:
|
||||
covergen --manifest posts.json --outdir static/covers [--png]
|
||||
|
||||
Манифест: [{"slug":"...","title":"...","subtitle":"...","author":"...","tags":["a","b"]}]
|
||||
|
||||
--png дополнительно рендерит PNG (нужен resvg или rsvg-convert в PATH).
|
||||
--audit проверяет геометрию текста и контраст (WCAG >= 4.5) и печатает отчёт.
|
||||
`;
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {};
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const token = argv[i];
|
||||
if (!token.startsWith('--')) continue;
|
||||
const key = token.slice(2);
|
||||
const next = argv[i + 1];
|
||||
if (next === undefined || next.startsWith('--')) {
|
||||
args[key] = true;
|
||||
} else {
|
||||
args[key] = next;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function slugify(value) {
|
||||
return String(value)
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 80) || 'cover';
|
||||
}
|
||||
|
||||
function toPng(svgPath, wanted) {
|
||||
if (!wanted) return null;
|
||||
const pngPath = svgPath.replace(/\.svg$/i, '.png');
|
||||
const resvg = spawnSync('resvg', ['--use-fonts-dir', '/usr/share/fonts', svgPath, pngPath], { encoding: 'utf8' });
|
||||
if (resvg.status === 0) return pngPath;
|
||||
const rsvg = spawnSync('rsvg-convert', ['-o', pngPath, svgPath], { encoding: 'utf8' });
|
||||
if (rsvg.status === 0) return pngPath;
|
||||
process.stderr.write('covergen: PNG не создан — нет resvg/rsvg-convert в PATH (SVG готов)\n');
|
||||
return null;
|
||||
}
|
||||
|
||||
function writeCover(input, outPath) {
|
||||
const svg = render(input);
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, svg, 'utf8');
|
||||
return { outPath, svg };
|
||||
}
|
||||
|
||||
function runAudit({ svg, outPath }, input) {
|
||||
const width = Math.max(320, Number(input.width) || 1200);
|
||||
const height = Math.max(320, Number(input.height) || 630);
|
||||
const slug = String(input.slug || input.title || '').toLowerCase();
|
||||
const { issues, stats } = audit(svg, { width, height, palette: paletteFor(slug) });
|
||||
const label = `${path.basename(outPath)}: текста ${stats.texts}, контраст ${stats.minContrast}`;
|
||||
if (issues.length === 0) {
|
||||
process.stdout.write(`audit ok — ${label}\n`);
|
||||
return true;
|
||||
}
|
||||
process.stderr.write(`audit FAIL — ${label}\n`);
|
||||
for (const issue of issues) process.stderr.write(` ${issue.type}: ${issue.detail}\n`);
|
||||
return false;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
|
||||
if (args.help || args.h) {
|
||||
process.stdout.write(USAGE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (args.manifest) {
|
||||
const manifestPath = path.resolve(String(args.manifest));
|
||||
const outdir = path.resolve(String(args.outdir ?? 'covers'));
|
||||
const posts = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||
if (!Array.isArray(posts)) throw new Error('manifest должен быть массивом объектов');
|
||||
|
||||
const written = [];
|
||||
let auditOk = true;
|
||||
for (const post of posts) {
|
||||
const slug = slugify(post.slug || post.title);
|
||||
const outPath = path.join(outdir, `${slug}.svg`);
|
||||
const cover = writeCover({ ...post, slug }, outPath);
|
||||
written.push(outPath);
|
||||
if (args.audit) auditOk = runAudit(cover, { ...post, slug }) && auditOk;
|
||||
const png = toPng(outPath, Boolean(args.png));
|
||||
if (png) written.push(png);
|
||||
}
|
||||
process.stdout.write(`${written.join('\n')}\n`);
|
||||
return auditOk ? 0 : 1;
|
||||
}
|
||||
|
||||
if (!args.title) {
|
||||
process.stderr.write(USAGE);
|
||||
return 2;
|
||||
}
|
||||
|
||||
const slug = slugify(args.slug || args.title);
|
||||
const outPath = path.resolve(String(args.out ?? path.join('covers', `${slug}.svg`)));
|
||||
const cover = writeCover({ ...args, slug, tags: args.tags }, outPath);
|
||||
const written = [cover.outPath];
|
||||
const auditOk = args.audit ? runAudit(cover, { ...args, slug }) : true;
|
||||
const png = toPng(outPath, Boolean(args.png));
|
||||
if (png) written.push(png);
|
||||
process.stdout.write(`${written.join('\n')}\n`);
|
||||
return auditOk ? 0 : 1;
|
||||
}
|
||||
|
||||
try {
|
||||
process.exitCode = main();
|
||||
} catch (error) {
|
||||
process.stderr.write(`covergen: ${error.message}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Детерминированные обложки: палитра из слага">
|
||||
|
||||
<defs>
|
||||
<radialGradient id="a1vml" cx="0.2" cy="0.15" r="0.7">
|
||||
<stop offset="0" stop-color="hsl(44 79% 59%)" stop-opacity="0.55"/><stop offset="1" stop-color="hsl(44 79% 59%)" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="a2vml" cx="0.85" cy="0.8" r="0.65">
|
||||
<stop offset="0" stop-color="hsl(66 69% 38%)" stop-opacity="0.5"/><stop offset="1" stop-color="hsl(66 69% 38%)" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<rect width="1200" height="630" fill="hsl(2 53% 20%)"/>
|
||||
<rect width="1200" height="630" fill="url(#a1vml)"/>
|
||||
<rect width="1200" height="630" fill="url(#a2vml)"/>
|
||||
<line x1="600" y1="179" x2="600" y2="185" stroke="hsl(44 79% 59%)" stroke-width="3"/>
|
||||
<text x="600" y="310" text-anchor="middle" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(2 24% 96%)">Детерминированные обложки:</text><text x="600" y="378" text-anchor="middle" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(2 24% 96%)">палитра из слага</text>
|
||||
<text x="600" y="567" text-anchor="middle" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="19" fill="hsl(2 18% 74%)" letter-spacing="1">#hugo #svg</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Бэкап, который действительно восстанавливается">
|
||||
|
||||
<rect width="1200" height="630" fill="hsl(268 24% 96%)"/>
|
||||
<rect x="54" y="54" width="1092" height="522" fill="none" stroke="hsl(268 45% 15%)" stroke-opacity="0.18"/>
|
||||
<line x1="108" y1="88" x2="1092" y2="88" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/><line x1="108" y1="189" x2="1092" y2="189" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/><line x1="108" y1="529" x2="1092" y2="529" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/><line x1="108" y1="567" x2="1092" y2="567" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/>
|
||||
<text x="108" y="214" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(268 45% 15%)">Бэкап, который действительно</text><text x="108" y="282" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(268 45% 15%)">восстанавливается</text>
|
||||
<text x="108" y="504" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="18" fill="hsl(268 45% 15%)" fill-opacity="0.75" letter-spacing="3">2026-09-12 · БЭКАПЫ</text>
|
||||
<text x="108" y="592" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="16" fill="hsl(268 45% 15%)" fill-opacity="0.6">Евгений Стороженко</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Как я перестал бояться DPI-багов">
|
||||
|
||||
<defs>
|
||||
<clipPath id="clipuju"><rect width="1200" height="630"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#clipuju)">
|
||||
<rect width="1200" height="630" fill="hsl(32 69% 15%)"/>
|
||||
<circle cx="984" cy="164" r="189" fill="hsl(200 88% 65%)" opacity="0.92"/>
|
||||
<rect x="0" y="277" width="552" height="63" fill="hsl(222 82% 45%)" opacity="0.85"/>
|
||||
<polygon points="72,0 288,0 72,139" fill="hsl(32 18% 74%)" opacity="0.5"/>
|
||||
<rect x="96" y="378" width="120" height="4" fill="hsl(200 88% 65%)"/>
|
||||
</g>
|
||||
<text x="96" y="467" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="69" font-weight="800" fill="hsl(32 24% 96%)">Как я перестал бояться</text><text x="96" y="542" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="69" font-weight="800" fill="hsl(32 24% 96%)">DPI-багов</text>
|
||||
<text x="96" y="580" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="19" fill="hsl(32 18% 74%)" letter-spacing="2">#linux #сети</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Мониторинг, который не будит ночью">
|
||||
|
||||
<rect width="1200" height="630" fill="hsl(21 58% 12%)"/>
|
||||
<polygon points="0,391 1200,176 1200,290 0,504" fill="hsl(63 84% 64%)" opacity="0.9"/>
|
||||
<polygon points="0,542 1200,353 1200,378 0,567" fill="hsl(85 74% 47%)" opacity="0.75"/>
|
||||
<circle cx="1032" cy="113" r="69" fill="hsl(21 18% 74%)" opacity="0.35"/>
|
||||
<g transform="translate(96 214) rotate(-4)" id="title1zoz"><text x="0" y="0" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="66" font-weight="800" fill="hsl(21 24% 96%)" text-transform="uppercase">МОНИТОРИНГ, КОТОРЫЙ НЕ</text><text x="0" y="71" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="66" font-weight="800" fill="hsl(21 24% 96%)" text-transform="uppercase">БУДИТ НОЧЬЮ</text></g>
|
||||
<text x="96" y="592" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="18" fill="hsl(21 18% 74%)" letter-spacing="4">2026-10-19 · ИНФРАСТРУКТУРА</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Детерминированные обложки: палитра из слага">
|
||||
|
||||
<defs>
|
||||
<radialGradient id="a1vml" cx="0.2" cy="0.15" r="0.7">
|
||||
<stop offset="0" stop-color="hsl(44 79% 59%)" stop-opacity="0.55"/><stop offset="1" stop-color="hsl(44 79% 59%)" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="a2vml" cx="0.85" cy="0.8" r="0.65">
|
||||
<stop offset="0" stop-color="hsl(66 69% 38%)" stop-opacity="0.5"/><stop offset="1" stop-color="hsl(66 69% 38%)" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<rect width="1200" height="630" fill="hsl(2 53% 20%)"/>
|
||||
<rect width="1200" height="630" fill="url(#a1vml)"/>
|
||||
<rect width="1200" height="630" fill="url(#a2vml)"/>
|
||||
<line x1="600" y1="179" x2="600" y2="185" stroke="hsl(44 79% 59%)" stroke-width="3"/>
|
||||
<text x="600" y="310" text-anchor="middle" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(2 24% 96%)">Детерминированные обложки:</text><text x="600" y="378" text-anchor="middle" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(2 24% 96%)">палитра из слага</text>
|
||||
<text x="600" y="567" text-anchor="middle" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="19" fill="hsl(2 18% 74%)" letter-spacing="1">#hugo #svg</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Как я перестал бояться DPI-багов">
|
||||
|
||||
<defs>
|
||||
<clipPath id="clipuju"><rect width="1200" height="630"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#clipuju)">
|
||||
<rect width="1200" height="630" fill="hsl(32 69% 15%)"/>
|
||||
<circle cx="984" cy="164" r="189" fill="hsl(200 88% 65%)" opacity="0.92"/>
|
||||
<rect x="0" y="277" width="552" height="63" fill="hsl(222 82% 45%)" opacity="0.85"/>
|
||||
<polygon points="72,0 288,0 72,139" fill="hsl(32 18% 74%)" opacity="0.5"/>
|
||||
<rect x="96" y="378" width="120" height="4" fill="hsl(200 88% 65%)"/>
|
||||
</g>
|
||||
<text x="96" y="467" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="69" font-weight="800" fill="hsl(32 24% 96%)">Как я перестал бояться</text><text x="96" y="542" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="69" font-weight="800" fill="hsl(32 24% 96%)">DPI-багов</text>
|
||||
<text x="96" y="580" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="19" fill="hsl(32 18% 74%)" letter-spacing="2">#linux #сети</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Мониторинг, который не будит ночью">
|
||||
|
||||
<rect width="1200" height="630" fill="hsl(21 58% 12%)"/>
|
||||
<polygon points="0,391 1200,176 1200,290 0,504" fill="hsl(63 84% 64%)" opacity="0.9"/>
|
||||
<polygon points="0,542 1200,353 1200,378 0,567" fill="hsl(85 74% 47%)" opacity="0.75"/>
|
||||
<circle cx="1032" cy="113" r="69" fill="hsl(21 18% 74%)" opacity="0.35"/>
|
||||
<text x="96" y="257" transform="rotate(-4 96 257)" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="66" font-weight="800" fill="hsl(21 24% 96%)">МОНИТОРИНГ, КОТОРЫЙ НЕ</text><text x="96" y="328" transform="rotate(-4 96 328)" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="66" font-weight="800" fill="hsl(21 24% 96%)">БУДИТ НОЧЬЮ</text>
|
||||
<text x="96" y="592" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="18" fill="hsl(21 18% 74%)" letter-spacing="4">2026-10-19 · ИНФРАСТРУКТУРА</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Бэкап, который действительно восстанавливается">
|
||||
|
||||
<rect width="1200" height="630" fill="hsl(268 24% 96%)"/>
|
||||
<rect x="54" y="54" width="1092" height="522" fill="none" stroke="hsl(268 45% 15%)" stroke-opacity="0.18"/>
|
||||
<line x1="108" y1="88" x2="1092" y2="88" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/><line x1="108" y1="189" x2="1092" y2="189" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/><line x1="108" y1="529" x2="1092" y2="529" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/><line x1="108" y1="567" x2="1092" y2="567" stroke="hsl(268 45% 15%)" stroke-opacity="0.28" stroke-width="1"/>
|
||||
<text x="108" y="214" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(268 45% 15%)">Бэкап, который действительно</text><text x="108" y="282" font-family="Georgia, "Times New Roman", "DejaVu Serif", serif" font-size="63" fill="hsl(268 45% 15%)">восстанавливается</text>
|
||||
<text x="108" y="504" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="18" fill="hsl(268 45% 15%)" fill-opacity="0.75" letter-spacing="3">2026-09-12 · БЭКАПЫ</text>
|
||||
<text x="108" y="592" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="16" fill="hsl(268 45% 15%)" fill-opacity="0.6">Евгений Стороженко</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Смысловая пустота">
|
||||
|
||||
<defs>
|
||||
<linearGradient id="bg1pbe" x1="0" y1="0" x2="0.6" y2="1">
|
||||
<stop offset="0" stop-color="hsl(21 71% 17%)"/><stop offset="1" stop-color="hsl(33 71% 12%)"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="1200" height="630" fill="url(#bg1pbe)"/>
|
||||
<rect x="66" y="66" width="1068" height="498" fill="none" stroke="hsl(63 88% 53%)" stroke-opacity="0.55" stroke-width="2"/>
|
||||
<rect x="66" y="220" width="144" height="5" fill="hsl(63 88% 53%)"/>
|
||||
<text x="600" y="340" text-anchor="middle" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="82" font-weight="700" fill="hsl(21 24% 96%)" letter-spacing="-0.5">Смысловая пустота</text>
|
||||
<text x="600" y="528" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="20" fill="hsl(21 18% 74%)" letter-spacing="3">2026-11-14 · ТЕКСТ</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,7 @@
|
||||
[
|
||||
{ "slug": "smysl", "title": "Смысловая пустота", "subtitle": "2026-11-14 · текст", "tags": ["дизайн", "типографика"], "style": "poster" },
|
||||
{ "slug": "dpi", "title": "Как я перестал бояться DPI-багов", "subtitle": "2026-11-02 · сети", "tags": ["linux", "сети"], "style": "bauhaus" },
|
||||
{ "slug": "monitoring", "title": "Мониторинг, который не будит ночью", "subtitle": "2026-10-19 · инфраструктура", "tags": ["prometheus", "алерты"], "style": "constructivist" },
|
||||
{ "slug": "covers", "title": "Детерминированные обложки: палитра из слага", "subtitle": "2026-09-28 · hugo", "tags": ["hugo", "svg"], "style": "aurora" },
|
||||
{ "slug": "backup", "title": "Бэкап, который действительно восстанавливается", "subtitle": "2026-09-12 · бэкапы", "author": "Евгений Стороженко", "style": "paper" }
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="Смысловая пустота">
|
||||
|
||||
<defs>
|
||||
<linearGradient id="bg1pbe" x1="0" y1="0" x2="0.6" y2="1">
|
||||
<stop offset="0" stop-color="hsl(21 71% 17%)"/><stop offset="1" stop-color="hsl(33 71% 12%)"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="1200" height="630" fill="url(#bg1pbe)"/>
|
||||
<rect x="66" y="66" width="1068" height="498" fill="none" stroke="hsl(63 88% 53%)" stroke-opacity="0.55" stroke-width="2"/>
|
||||
<rect x="66" y="220" width="144" height="5" fill="hsl(63 88% 53%)"/>
|
||||
<text x="600" y="340" text-anchor="middle" font-family="Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif" font-size="82" font-weight="700" fill="hsl(21 24% 96%)" letter-spacing="-0.5">Смысловая пустота</text>
|
||||
<text x="600" y="528" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace" font-size="20" fill="hsl(21 18% 74%)" letter-spacing="3">2026-11-14 · ТЕКСТ</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,116 @@
|
||||
'use strict';
|
||||
|
||||
const { measure } = require('./typeset');
|
||||
|
||||
/** "hsl(212 62% 16%)" -> [r,g,b] 0..255 */
|
||||
function hslToRgb(value) {
|
||||
const m = /hsl\(\s*([\d.]+)\s+([\d.]+)%\s+([\d.]+)%\s*\)/i.exec(String(value));
|
||||
if (!m) {
|
||||
const hex = /^#([0-9a-f]{6})$/i.exec(String(value));
|
||||
if (hex) {
|
||||
const n = parseInt(hex[1], 16);
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
}
|
||||
throw new Error(`unsupported color: ${value}`);
|
||||
}
|
||||
const h = Number(m[1]) / 360;
|
||||
const s = Number(m[2]) / 100;
|
||||
const l = Number(m[3]) / 100;
|
||||
if (s === 0) return [l * 255, l * 255, l * 255];
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
const hue = (t) => {
|
||||
let x = t;
|
||||
if (x < 0) x += 1;
|
||||
if (x > 1) x -= 1;
|
||||
if (x < 1 / 6) return p + (q - p) * 6 * x;
|
||||
if (x < 1 / 2) return q;
|
||||
if (x < 2 / 3) return p + (q - p) * (2 / 3 - x) * 6;
|
||||
return p;
|
||||
};
|
||||
return [hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255];
|
||||
}
|
||||
|
||||
function luminance(color) {
|
||||
const [r, g, b] = hslToRgb(color).map((channel) => {
|
||||
const c = channel / 255;
|
||||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||||
});
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
|
||||
/** WCAG-контраст: 1..21 */
|
||||
function contrastRatio(a, b) {
|
||||
const la = luminance(a);
|
||||
const lb = luminance(b);
|
||||
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
|
||||
}
|
||||
|
||||
function attr(attrs, name) {
|
||||
const m = new RegExp(`${name}="([^"]*)"`).exec(attrs);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
/** Все <text> элементы с координатами и содержимым. */
|
||||
function textNodes(svg) {
|
||||
const nodes = [];
|
||||
const re = /<text([^>]*)>([\s\S]*?)<\/text>/g;
|
||||
let match;
|
||||
while ((match = re.exec(svg)) !== null) {
|
||||
const [, attrs, rawContent] = match;
|
||||
nodes.push({
|
||||
x: Number(attr(attrs, 'x') ?? 0),
|
||||
y: Number(attr(attrs, 'y') ?? 0),
|
||||
size: Number(attr(attrs, 'font-size') ?? 16),
|
||||
anchor: attr(attrs, 'text-anchor') ?? 'start',
|
||||
fill: attr(attrs, 'fill') ?? '#000000',
|
||||
fillOpacity: Number(attr(attrs, 'fill-opacity') ?? 1),
|
||||
text: rawContent.replace(/<[^>]*>/g, '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'"),
|
||||
});
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Геометрический и контрастный аудит готового SVG.
|
||||
* @returns {{issues: {type: string, detail: string}[], stats: {texts: number, minContrast: number}}}
|
||||
*/
|
||||
function audit(svg, { width, height, palette, margin = 4, minContrast = 4.5, minFont = 12 }) {
|
||||
const issues = [];
|
||||
const nodes = textNodes(svg);
|
||||
|
||||
const bgContrast = contrastRatio(palette.ink, palette.bg);
|
||||
if (bgContrast < minContrast) {
|
||||
issues.push({ type: 'contrast', detail: `ink/bg = ${bgContrast.toFixed(2)} < ${minContrast}` });
|
||||
}
|
||||
|
||||
for (const node of nodes) {
|
||||
const textWidth = measure(node.text, node.size);
|
||||
const half = node.anchor === 'middle' ? textWidth / 2 : node.anchor === 'end' ? textWidth : 0;
|
||||
const left = node.x - half;
|
||||
const right = node.x + (node.anchor === 'middle' ? textWidth / 2 : node.anchor === 'end' ? 0 : textWidth);
|
||||
const baseline = node.y;
|
||||
if (baseline - node.size * 0.85 < margin) {
|
||||
issues.push({ type: 'overflow-top', detail: `"${node.text.slice(0, 24)}" y=${baseline} size=${node.size}` });
|
||||
}
|
||||
if (baseline > height - margin) {
|
||||
issues.push({ type: 'overflow-bottom', detail: `"${node.text.slice(0, 24)}" y=${baseline}` });
|
||||
}
|
||||
if (left < -margin || right > width + margin) {
|
||||
issues.push({
|
||||
type: 'overflow-x',
|
||||
detail: `"${node.text.slice(0, 24)}" box=[${Math.round(left)},${Math.round(right)}] canvas=${width}`,
|
||||
});
|
||||
}
|
||||
if (node.size < minFont) {
|
||||
issues.push({ type: 'font-too-small', detail: `"${node.text.slice(0, 24)}" size=${node.size}` });
|
||||
}
|
||||
if (node.fillOpacity < 0.45) {
|
||||
issues.push({ type: 'faint-text', detail: `"${node.text.slice(0, 24)}" fill-opacity=${node.fillOpacity}` });
|
||||
}
|
||||
}
|
||||
|
||||
return { issues, stats: { texts: nodes.length, minContrast: Number(bgContrast.toFixed(2)) } };
|
||||
}
|
||||
|
||||
module.exports = { audit, contrastRatio, textNodes, hslToRgb };
|
||||
@@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Детерминированная палитра: строка (slug/title) -> стабильный набор цветов.
|
||||
* Одинаковый вход всегда даёт одинаковую обложку, поэтому картинка не «мигает»
|
||||
* между сборками сайта.
|
||||
*/
|
||||
|
||||
function hash(input) {
|
||||
// FNV-1a 32-bit
|
||||
let h = 0x811c9dc5;
|
||||
const s = String(input ?? '');
|
||||
for (let i = 0; i < s.length; i += 1) {
|
||||
h ^= s.charCodeAt(i);
|
||||
h = Math.imul(h, 0x01000193) >>> 0;
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
function rng(seed) {
|
||||
let a = seed >>> 0;
|
||||
return function next() {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function hsl(h, s, l) {
|
||||
return `hsl(${((h % 360) + 360) % 360} ${s}% ${l}%)`;
|
||||
}
|
||||
|
||||
/** Базовая пара «фон + акцент» из нескольких семейств, чтобы обложки не сливались. */
|
||||
const FAMILIES = [
|
||||
{ h: 212, s: 62, l: 16 }, // глубокий синий
|
||||
{ h: 268, s: 48, l: 18 }, // индиго
|
||||
{ h: 160, s: 42, l: 15 }, // тёмно-зелёный
|
||||
{ h: 12, s: 58, l: 17 }, // ржаво-красный
|
||||
{ h: 34, s: 64, l: 15 }, // охра
|
||||
{ h: 320, s: 42, l: 17 }, // винно-розовый
|
||||
{ h: 194, s: 58, l: 14 }, // бирюза
|
||||
{ h: 96, s: 32, l: 14 }, // оливковый
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {string} seed
|
||||
* @returns {{bg:string,bg2:string,ink:string,muted:string,accent:string,accent2:string,family:number}}
|
||||
*/
|
||||
function paletteFor(seed) {
|
||||
const r = rng(hash(seed));
|
||||
const family = FAMILIES[Math.floor(r() * FAMILIES.length)];
|
||||
const hueShift = Math.round((r() - 0.5) * 26);
|
||||
const h = family.h + hueShift;
|
||||
const sat = family.s + Math.round((r() - 0.5) * 14);
|
||||
const light = family.l + Math.round((r() - 0.5) * 6);
|
||||
const accentHue = r() < 0.5 ? h + 168 : h + 42;
|
||||
return {
|
||||
bg: hsl(h, sat, light),
|
||||
bg2: hsl(h + 12, sat, light - 5),
|
||||
ink: hsl(h, 24, 96),
|
||||
muted: hsl(h, 18, 74),
|
||||
accent: hsl(accentHue, Math.min(88, sat + 26), Math.max(48, 58 + Math.round((r() - 0.5) * 16))),
|
||||
accent2: hsl(accentHue + 22, Math.min(82, sat + 16), Math.max(38, 44 + Math.round((r() - 0.5) * 12))),
|
||||
family: FAMILIES.indexOf(family),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { hash, rng, paletteFor, hsl };
|
||||
@@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
const { paletteFor, hash } = require('./palette');
|
||||
const { STYLES } = require('./styles');
|
||||
|
||||
const STYLE_NAMES = Object.keys(STYLES);
|
||||
|
||||
/**
|
||||
* @param {{title:string, subtitle?:string, author?:string, tags?:string[], slug?:string,
|
||||
* style?:string, width?:number, height?:number, background?:string}} input
|
||||
* @returns {string} SVG-документ
|
||||
*/
|
||||
function render(input) {
|
||||
const title = String(input.title ?? '').trim();
|
||||
if (!title) throw new Error('title is required');
|
||||
|
||||
const seed = String(input.slug || title).toLowerCase();
|
||||
const styleName = input.style && input.style !== 'auto'
|
||||
? input.style
|
||||
: STYLE_NAMES[hash(seed) % STYLE_NAMES.length];
|
||||
const style = STYLES[styleName];
|
||||
if (!style) {
|
||||
throw new Error(`unknown style "${styleName}", available: ${STYLE_NAMES.join(', ')}`);
|
||||
}
|
||||
|
||||
const width = Math.max(320, Math.min(4000, Number(input.width) || 1200));
|
||||
const height = Math.max(320, Math.min(4000, Number(input.height) || 630));
|
||||
const tags = Array.isArray(input.tags)
|
||||
? input.tags.map((tag) => String(tag).trim()).filter(Boolean)
|
||||
: String(input.tags ?? '').split(',').map((tag) => tag.trim()).filter(Boolean);
|
||||
|
||||
const body = style({
|
||||
width,
|
||||
height,
|
||||
title,
|
||||
subtitle: input.subtitle ?? '',
|
||||
author: input.author ?? '',
|
||||
tags,
|
||||
palette: paletteFor(seed),
|
||||
uid: (hash(seed) % 99991).toString(36),
|
||||
});
|
||||
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeAttr(title)}">
|
||||
${body}
|
||||
</svg>
|
||||
`;
|
||||
}
|
||||
|
||||
function escapeAttr(value) {
|
||||
return String(value).replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
module.exports = { render, STYLE_NAMES };
|
||||
@@ -0,0 +1,129 @@
|
||||
'use strict';
|
||||
|
||||
const { esc, fit } = require('../typeset');
|
||||
|
||||
const SERIF = 'Georgia, "Times New Roman", "DejaVu Serif", serif';
|
||||
const SANS = 'Inter, "Helvetica Neue", Helvetica, Arial, "DejaVu Sans", sans-serif';
|
||||
const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "DejaVu Sans Mono", monospace';
|
||||
|
||||
function tagsLine(ctx) {
|
||||
return (ctx.tags ?? []).slice(0, 3).map((tag) => `#${tag}`).join(' ');
|
||||
}
|
||||
|
||||
/** Крупный плакатный заголовок по центру, тонкая рамка, подпись снизу. */
|
||||
function poster(ctx) {
|
||||
const { width: w, height: h, palette: p, uid } = ctx;
|
||||
const pad = Math.round(w * 0.1);
|
||||
const title = fit(ctx.title, { maxWidth: w - pad * 2, maxLines: 4, size: Math.round(h * 0.13), min: 22 });
|
||||
const blockH = title.lines.length * title.lineHeight;
|
||||
const top = Math.round((h - blockH) / 2 - h * 0.02);
|
||||
const lines = title.lines
|
||||
.map((line, i) => `<text x="${w / 2}" y="${top + title.fontSize + i * title.lineHeight}" text-anchor="middle" font-family="${SANS}" font-size="${title.fontSize}" font-weight="700" fill="${p.ink}" letter-spacing="-0.5">${esc(line)}</text>`)
|
||||
.join('');
|
||||
return `
|
||||
<defs>
|
||||
<linearGradient id="bg${uid}" x1="0" y1="0" x2="0.6" y2="1">
|
||||
<stop offset="0" stop-color="${p.bg}"/><stop offset="1" stop-color="${p.bg2}"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="${w}" height="${h}" fill="url(#bg${uid})"/>
|
||||
<rect x="${pad * 0.55}" y="${pad * 0.55}" width="${w - pad * 1.1}" height="${h - pad * 1.1}" fill="none" stroke="${p.accent}" stroke-opacity="0.55" stroke-width="2"/>
|
||||
<rect x="${pad * 0.55}" y="${top - Math.round(h * 0.06)}" width="${Math.round(w * 0.12)}" height="5" fill="${p.accent}"/>
|
||||
${lines}
|
||||
<text x="${w / 2}" y="${h - pad * 0.85}" text-anchor="middle" font-family="${MONO}" font-size="${Math.round(h * 0.032)}" fill="${p.muted}" letter-spacing="3">${esc((ctx.subtitle ?? '').toUpperCase())}</text>`;
|
||||
}
|
||||
|
||||
/** Геометрия баухауса: круг, прямоугольник, диагональ; заголовок слева снизу. */
|
||||
function bauhaus(ctx) {
|
||||
const { width: w, height: h, palette: p, uid } = ctx;
|
||||
const title = fit(ctx.title, { maxWidth: w * 0.72, maxLines: 3, size: Math.round(h * 0.11), min: 20 });
|
||||
const baseline = h - Math.round(h * 0.14);
|
||||
const lines = title.lines
|
||||
.map((line, i) => `<text x="${Math.round(w * 0.08)}" y="${baseline - (title.lines.length - 1 - i) * title.lineHeight}" font-family="${SANS}" font-size="${title.fontSize}" font-weight="800" fill="${p.ink}">${esc(line)}</text>`)
|
||||
.join('');
|
||||
return `
|
||||
<defs>
|
||||
<clipPath id="clip${uid}"><rect width="${w}" height="${h}"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#clip${uid})">
|
||||
<rect width="${w}" height="${h}" fill="${p.bg}"/>
|
||||
<circle cx="${Math.round(w * 0.82)}" cy="${Math.round(h * 0.26)}" r="${Math.round(h * 0.3)}" fill="${p.accent}" opacity="0.92"/>
|
||||
<rect x="0" y="${Math.round(h * 0.44)}" width="${Math.round(w * 0.46)}" height="${Math.round(h * 0.1)}" fill="${p.accent2}" opacity="0.85"/>
|
||||
<polygon points="${Math.round(w * 0.06)},0 ${Math.round(w * 0.24)},0 ${Math.round(w * 0.06)},${Math.round(h * 0.22)}" fill="${p.muted}" opacity="0.5"/>
|
||||
<rect x="${Math.round(w * 0.08)}" y="${Math.round(h * 0.6)}" width="${Math.round(w * 0.1)}" height="4" fill="${p.accent}"/>
|
||||
</g>
|
||||
${lines}
|
||||
<text x="${Math.round(w * 0.08)}" y="${Math.round(h * 0.92)}" font-family="${MONO}" font-size="${Math.round(h * 0.03)}" fill="${p.muted}" letter-spacing="2">${esc(tagsLine(ctx) || (ctx.subtitle ?? ''))}</text>`;
|
||||
}
|
||||
|
||||
/** Конструктивизм: диагональная плашка и наклонный заголовок. */
|
||||
function constructivist(ctx) {
|
||||
const { width: w, height: h, palette: p, uid } = ctx;
|
||||
const title = fit(ctx.title, { maxWidth: w * 0.68, maxLines: 3, size: Math.round(h * 0.105), min: 20 });
|
||||
const originX = Math.round(w * 0.08);
|
||||
// Первая строка садится так, чтобы весь блок из 3 строк оставался в кадре даже с наклоном.
|
||||
const originY = Math.round(h * 0.34) + Math.round(title.lineHeight * 0.6);
|
||||
const lines = title.lines
|
||||
.map((line, i) => {
|
||||
const y = originY + i * title.lineHeight;
|
||||
return `<text x="${originX}" y="${y}" transform="rotate(-4 ${originX} ${y})" font-family="${SANS}" font-size="${title.fontSize}" font-weight="800" fill="${p.ink}">${esc(line.toUpperCase())}</text>`;
|
||||
})
|
||||
.join('');
|
||||
return `
|
||||
<rect width="${w}" height="${h}" fill="${p.bg}"/>
|
||||
<polygon points="0,${Math.round(h * 0.62)} ${w},${Math.round(h * 0.28)} ${w},${Math.round(h * 0.46)} 0,${Math.round(h * 0.8)}" fill="${p.accent}" opacity="0.9"/>
|
||||
<polygon points="0,${Math.round(h * 0.86)} ${w},${Math.round(h * 0.56)} ${w},${Math.round(h * 0.6)} 0,${Math.round(h * 0.9)}" fill="${p.accent2}" opacity="0.75"/>
|
||||
<circle cx="${Math.round(w * 0.86)}" cy="${Math.round(h * 0.18)}" r="${Math.round(h * 0.11)}" fill="${p.muted}" opacity="0.35"/>
|
||||
${lines}
|
||||
<text x="${originX}" y="${Math.round(h * 0.94)}" font-family="${MONO}" font-size="${Math.round(h * 0.028)}" fill="${p.muted}" letter-spacing="4">${esc((ctx.subtitle ?? '').toUpperCase())}</text>`;
|
||||
}
|
||||
|
||||
/** Мягкие радиальные пятна: «северное сияние» на тёмном фоне. */
|
||||
function aurora(ctx) {
|
||||
const { width: w, height: h, palette: p, uid } = ctx;
|
||||
const title = fit(ctx.title, { maxWidth: w * 0.78, maxLines: 4, size: Math.round(h * 0.1), min: 20 });
|
||||
const blockH = title.lines.length * title.lineHeight;
|
||||
const top = Math.round((h - blockH) / 2);
|
||||
const lines = title.lines
|
||||
.map((line, i) => `<text x="${w / 2}" y="${top + title.fontSize + i * title.lineHeight}" text-anchor="middle" font-family="${SERIF}" font-size="${title.fontSize}" fill="${p.ink}">${esc(line)}</text>`)
|
||||
.join('');
|
||||
return `
|
||||
<defs>
|
||||
<radialGradient id="a1${uid}" cx="0.2" cy="0.15" r="0.7">
|
||||
<stop offset="0" stop-color="${p.accent}" stop-opacity="0.55"/><stop offset="1" stop-color="${p.accent}" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="a2${uid}" cx="0.85" cy="0.8" r="0.65">
|
||||
<stop offset="0" stop-color="${p.accent2}" stop-opacity="0.5"/><stop offset="1" stop-color="${p.accent2}" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<rect width="${w}" height="${h}" fill="${p.bg}"/>
|
||||
<rect width="${w}" height="${h}" fill="url(#a1${uid})"/>
|
||||
<rect width="${w}" height="${h}" fill="url(#a2${uid})"/>
|
||||
<line x1="${w * 0.5}" y1="${top - title.lineHeight}" x2="${w * 0.5}" y2="${top - title.lineHeight + 6}" stroke="${p.accent}" stroke-width="3"/>
|
||||
${lines}
|
||||
<text x="${w / 2}" y="${h - Math.round(h * 0.1)}" text-anchor="middle" font-family="${SANS}" font-size="${Math.round(h * 0.03)}" fill="${p.muted}" letter-spacing="1">${esc(tagsLine(ctx))}</text>`;
|
||||
}
|
||||
|
||||
/** Минимализм: линейки, серифный заголовок, автор внизу. */
|
||||
function paper(ctx) {
|
||||
const { width: w, height: h, palette: p } = ctx;
|
||||
const pad = Math.round(w * 0.09);
|
||||
const title = fit(ctx.title, { maxWidth: w - pad * 2, maxLines: 4, size: Math.round(h * 0.1), min: 20 });
|
||||
const lines = title.lines
|
||||
.map((line, i) => `<text x="${pad}" y="${Math.round(h * 0.34) + i * title.lineHeight}" font-family="${SERIF}" font-size="${title.fontSize}" fill="${p.bg}">${esc(line)}</text>`)
|
||||
.join('');
|
||||
const rules = [0.14, 0.3, 0.84, 0.9]
|
||||
.map((y) => `<line x1="${pad}" y1="${Math.round(h * y)}" x2="${w - pad}" y2="${Math.round(h * y)}" stroke="${p.bg}" stroke-opacity="0.28" stroke-width="1"/>`)
|
||||
.join('');
|
||||
return `
|
||||
<rect width="${w}" height="${h}" fill="${p.ink}"/>
|
||||
<rect x="${pad * 0.5}" y="${pad * 0.5}" width="${w - pad}" height="${h - pad}" fill="none" stroke="${p.bg}" stroke-opacity="0.18"/>
|
||||
${rules}
|
||||
${lines}
|
||||
<text x="${pad}" y="${Math.round(h * 0.8)}" font-family="${SANS}" font-size="${Math.round(h * 0.028)}" fill="${p.bg}" fill-opacity="0.75" letter-spacing="3">${esc((ctx.subtitle ?? '').toUpperCase())}</text>
|
||||
<text x="${pad}" y="${Math.round(h * 0.94)}" font-family="${MONO}" font-size="${Math.round(h * 0.026)}" fill="${p.bg}" fill-opacity="0.6">${esc(ctx.author ?? '')}</text>`;
|
||||
}
|
||||
|
||||
const STYLES = { poster, bauhaus, constructivist, aurora, paper };
|
||||
|
||||
module.exports = { STYLES, SERIF, SANS, MONO };
|
||||
@@ -0,0 +1,75 @@
|
||||
'use strict';
|
||||
|
||||
/** Экранирование текста для SVG/XML. */
|
||||
function esc(value) {
|
||||
return String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/** Грубая оценка ширины строки: без canvas, пропорционально кеглю. */
|
||||
function measure(text, fontSize, tracking = 0) {
|
||||
let width = 0;
|
||||
for (const ch of String(text)) {
|
||||
if (ch === ' ') width += 0.29;
|
||||
else if ('iljI.,:;!|\'’'.includes(ch)) width += 0.26;
|
||||
else if ('mwMWШЩЖЮ'.includes(ch)) width += 0.82;
|
||||
else if (ch === ch.toUpperCase() && ch !== ch.toLowerCase()) width += 0.62;
|
||||
else if (/[А-Яа-яЁё]/.test(ch)) width += 0.54;
|
||||
else width += 0.52;
|
||||
}
|
||||
return width * fontSize + Math.max(0, [...String(text)].length - 1) * tracking;
|
||||
}
|
||||
|
||||
function clampLine(line, fontSize, maxWidth, tracking) {
|
||||
if (measure(line, fontSize, tracking) <= maxWidth) return line;
|
||||
let clipped = line;
|
||||
while (clipped.length > 1 && measure(`${clipped}…`, fontSize, tracking) > maxWidth) {
|
||||
clipped = clipped.slice(0, -1);
|
||||
}
|
||||
return `${clipped.trimEnd()}…`;
|
||||
}
|
||||
|
||||
/** Перенос по словам под заданную ширину при известном кегле. */
|
||||
function wrap(text, fontSize, maxWidth, tracking = 0, maxLines = 6) {
|
||||
const words = String(text ?? '').split(/\s+/).filter(Boolean);
|
||||
if (words.length === 0) return [];
|
||||
const lines = [];
|
||||
let current = '';
|
||||
for (const word of words) {
|
||||
const candidate = current ? `${current} ${word}` : word;
|
||||
if (measure(candidate, fontSize, tracking) <= maxWidth || !current) {
|
||||
current = candidate;
|
||||
} else {
|
||||
lines.push(current);
|
||||
current = word;
|
||||
if (lines.length === maxLines - 1) break;
|
||||
}
|
||||
}
|
||||
if (current) lines.push(current);
|
||||
if (lines.length > maxLines) lines.length = maxLines;
|
||||
// каждую строку подрезаем: одиночное длинное слово иначе выезжает за поле
|
||||
return lines.map((line) => clampLine(line, fontSize, maxWidth, tracking));
|
||||
}
|
||||
|
||||
/**
|
||||
* Подбор кегля: уменьшает размер, пока текст не влезет в maxWidth и maxLines.
|
||||
* @returns {{lines: string[], fontSize: number, lineHeight: number}}
|
||||
*/
|
||||
function fit(text, { maxWidth, maxLines = 4, size, min = 18, leading = 1.08, tracking = 0 }) {
|
||||
let fontSize = size;
|
||||
for (; fontSize > min; fontSize -= 1) {
|
||||
const lines = wrap(text, fontSize, maxWidth, tracking, maxLines);
|
||||
const longest = Math.max(...lines.map((line) => measure(line, fontSize, tracking)), 0);
|
||||
if (lines.length <= maxLines && longest <= maxWidth) {
|
||||
return { lines, fontSize, lineHeight: Math.round(fontSize * leading) };
|
||||
}
|
||||
}
|
||||
const lines = wrap(text, min, maxWidth, tracking, maxLines);
|
||||
return { lines, fontSize: min, lineHeight: Math.round(min * leading) };
|
||||
}
|
||||
|
||||
module.exports = { esc, measure, wrap, fit };
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "covergen",
|
||||
"version": "0.1.0",
|
||||
"description": "Детерминированные SVG-обложки-плейсхолдеры для постов",
|
||||
"license": "MIT",
|
||||
"bin": { "covergen": "bin/covergen.js" },
|
||||
"scripts": {
|
||||
"test": "node --test",
|
||||
"example": "node bin/covergen.js --manifest examples/posts.json --outdir examples"
|
||||
},
|
||||
"engines": { "node": ">=18" },
|
||||
"private": true
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const { render, STYLE_NAMES } = require('../lib/render');
|
||||
const { paletteFor, hash, rng } = require('../lib/palette');
|
||||
const { wrap, measure, esc, fit } = require('../lib/typeset');
|
||||
|
||||
test('одинаковый slug даёт байт-в-байт одинаковую обложку', () => {
|
||||
const a = render({ title: 'Смысловая пустота', slug: 'smysl', style: 'poster' });
|
||||
const b = render({ title: 'Смысловая пустота', slug: 'smysl', style: 'poster' });
|
||||
assert.equal(a, b);
|
||||
});
|
||||
|
||||
test('разные slug дают разные палитры', () => {
|
||||
assert.notEqual(paletteFor('odin').bg, paletteFor('dva').bg);
|
||||
});
|
||||
|
||||
test('auto подбирает стиль детерминированно', () => {
|
||||
const first = render({ title: 'Тест', slug: 'abc', style: 'auto' });
|
||||
const second = render({ title: 'Тест', slug: 'abc', style: 'auto' });
|
||||
assert.equal(first, second);
|
||||
assert.match(first, /<svg[^>]*width="1200" height="630"/);
|
||||
});
|
||||
|
||||
test('каждый стиль рендерит валидный по структуре SVG и заданные размеры', () => {
|
||||
for (const style of STYLE_NAMES) {
|
||||
const svg = render({ title: 'Заголовок', subtitle: '2026-11-14 · текст', slug: `s-${style}`, style, width: 900, height: 500 });
|
||||
assert.ok(svg.startsWith('<?xml'), style);
|
||||
assert.ok(svg.includes('<svg'), style);
|
||||
assert.ok(svg.trimEnd().endsWith('</svg>'), style);
|
||||
assert.equal((svg.match(/<svg/g) ?? []).length, 1, `${style}: один корневой svg`);
|
||||
assert.ok(svg.includes('width="900" height="500"'), style);
|
||||
// баланс тегов в теле
|
||||
const opens = (svg.match(/<(defs|g|text|rect|circle|polygon|line|linearGradient|radialGradient|clipPath)\b/g) ?? []).length;
|
||||
const closes = (svg.match(/<\/(defs|g|text|rect|circle|polygon|line|linearGradient|radialGradient|clipPath)>/g) ?? []).length;
|
||||
assert.ok(opens > 0 && closes > 0, style);
|
||||
}
|
||||
});
|
||||
|
||||
test('спецсимволы экранируются, XML не ломается', () => {
|
||||
const svg = render({ title: 'AT&T <script>alert("x")</script>', slug: 'escape', style: 'poster' });
|
||||
assert.ok(!svg.includes('<script>'));
|
||||
assert.ok(svg.includes('&'));
|
||||
assert.ok(svg.includes('<script>'));
|
||||
});
|
||||
|
||||
test('длинный заголовок переносится и не выходит за ширину', () => {
|
||||
const long = 'Очень длинный заголовок статьи про детерминированные обложки и типографику в статических сайтах';
|
||||
const fitted = fit(long, { maxWidth: 600, maxLines: 4, size: 80, min: 18 });
|
||||
assert.ok(fitted.lines.length <= 4);
|
||||
for (const line of fitted.lines) assert.ok(measure(line, fitted.fontSize) <= 600 + 1);
|
||||
});
|
||||
|
||||
test('wrap обрезает слишком длинное слово с многоточием', () => {
|
||||
const lines = wrap('a'.repeat(200), 40, 200, 0, 2);
|
||||
assert.equal(lines.length, 1);
|
||||
assert.ok(lines[0].endsWith('…'));
|
||||
});
|
||||
|
||||
test('hash и rng детерминированы', () => {
|
||||
assert.equal(hash('abc'), hash('abc'));
|
||||
assert.notEqual(hash('abc'), hash('abd'));
|
||||
const r1 = rng(42);
|
||||
const r2 = rng(42);
|
||||
assert.equal(r1(), r2());
|
||||
});
|
||||
|
||||
test('пустой тег не превращается в решётку', () => {
|
||||
const svg = render({ title: 'Тест', tags: ['', ' '], slug: 'tags', style: 'bauhaus' });
|
||||
assert.ok(!svg.includes('# '));
|
||||
});
|
||||
|
||||
test('esc экранирует все опасные символы', () => {
|
||||
assert.equal(esc(`&<>"'`), '&<>"'');
|
||||
});
|
||||
|
||||
test('неизвестный стиль — понятная ошибка', () => {
|
||||
assert.throws(() => render({ title: 'x', style: 'nope' }), /unknown style/);
|
||||
});
|
||||
|
||||
test('аудит: все стили × размеры × сиды проходят без замечаний', () => {
|
||||
const { audit } = require('../lib/audit');
|
||||
const sizes = [[1200, 630], [600, 900], [1920, 1080]];
|
||||
const long = 'Очень длинный заголовок поста про детерминированные обложки и типографику';
|
||||
for (const style of STYLE_NAMES) {
|
||||
for (const [width, height] of sizes) {
|
||||
for (const slug of ['a', 'seed-x', 'очень-длинный-слаг-поста']) {
|
||||
const svg = render({ title: long, subtitle: '2026-11-14 · текст', author: 'Автор', tags: ['hugo'], slug, style, width, height });
|
||||
const result = audit(svg, { width, height, palette: paletteFor(slug) });
|
||||
assert.deepEqual(result.issues, [], `${style} ${width}x${height} ${slug}`);
|
||||
assert.ok(result.stats.minContrast >= 4.5, `${style}: контраст ${result.stats.minContrast}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||