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.
This commit is contained in:
@@ -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 };
|
||||
Reference in New Issue
Block a user