brendmanager/src/site.js

140 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Страницы для продакта (BRM-31): документы docs/*.md как читаемые страницы.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { t } from "./i18n.js";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const DOCS = path.join(HERE, "../docs");
const SAMPLES = path.join(HERE, "../design/brand-visual");
// Документы, видимые с главной; остальные файлы docs/ тоже открываются, но не в списке.
export const DOC_LIST = [
["brand-core", "Ядро бренда"],
["positioning", "Позиционирование"],
["positioning-brief", "Бриф по позиционированию"],
["positioning-en", "Позиционирование (английский)"],
["visual-system", "Визуальная система"],
["niche-report", "Отчёт по нише"],
["audit", "Аудит"],
["brand-one-pager", "Бренд на одной странице"],
["glossary", "Словарь текстов"],
];
const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const inline = (s) => esc(s)
.replace(/`([^`]+)`/g, "<code>$1</code>")
.replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>")
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" rel="noopener">$1</a>');
export function renderMarkdown(md) {
const lines = md.replace(/\r/g, "").split("\n");
const out = [];
let list = null, i = 0, para = [];
const flush = () => { if (para.length) out.push("<p>" + inline(para.join(" ")) + "</p>"); para = []; };
const close = () => { if (list) { out.push(`</${list}>`); list = null; } };
while (i < lines.length) {
const l = lines[i];
let m;
if (/^\s*$/.test(l)) { flush(); close(); i++; continue; }
if ((m = l.match(/^(#{1,6})\s+(.*)$/))) { flush(); close(); out.push(`<h${m[1].length}>${inline(m[2])}</h${m[1].length}>`); i++; continue; }
if (l.startsWith("|") && /^\|[\s:|-]+\|?\s*$/.test(lines[i + 1] ?? "")) {
flush(); close();
const cells = (r) => r.trim().replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim()));
out.push("<table><thead><tr>" + cells(l).map((c) => `<th>${c}</th>`).join("") + "</tr></thead><tbody>");
i += 2;
while (i < lines.length && lines[i].startsWith("|")) { out.push("<tr>" + cells(lines[i]).map((c) => `<td>${c}</td>`).join("") + "</tr>"); i++; }
out.push("</tbody></table>");
continue;
}
if ((m = l.match(/^\s*([-*]|\d+\.)\s+(.*)$/))) {
flush();
const tag = /\d/.test(m[1]) ? "ol" : "ul";
if (list !== tag) { close(); out.push(`<${tag}>`); list = tag; }
out.push(`<li>${inline(m[2])}</li>`); i++; continue;
}
if (/^---+$/.test(l.trim())) { flush(); close(); out.push("<hr>"); i++; continue; }
close(); para.push(l.trim()); i++;
}
flush(); close();
return out.join("\n");
}
// BRM-35: состояние документа — docs/status.json: { имя: { state: draft|approved, date: ГГГГ-ММ-ДД } }.
export function readStatus(file = path.join(DOCS, "status.json")) {
try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return {}; }
}
const isDay = (d) => /^\d{4}-\d{2}-\d{2}$/.test(d ?? "");
export function stateLabel(entry, lang = "ru") {
const date = isDay(entry?.date) ? entry.date.split("-").reverse().join(".") : "";
if (entry?.state === "approved" && date) return t(lang, "home.state.approved", { date });
return date ? t(lang, "home.state.draft", { date }) : t(lang, "home.state.draft.nodate");
}
export function docList(lang = "ru", status = readStatus()) {
return docNames().map(([name]) => ({
name,
title: t(lang, "home.doc." + name),
approved: status[name]?.state === "approved" && isDay(status[name]?.date),
label: stateLabel(status[name], lang),
}));
}
export function homePage(lang = "ru", status = readStatus()) {
const docs = `<p>${esc(t(lang, "home.docs.note"))}</p>\n<ul>\n` + docList(lang, status)
.map((d) => `<li><a href="/docs/${d.name}">${esc(d.title)}</a> — <span class="st ${d.approved ? "ok" : "draft"}">${esc(d.label)}</span></li>`)
.join("\n") + "\n</ul>";
return fs.readFileSync(path.join(HERE, "../public/index.html"), "utf8")
.replace("<!--docs-->", docs)
.replace("<!--check-visual-->", `<li>${esc(t(lang, "home.check.visual"))}</li>`);
}
// BRM-35: палитра, шрифты и образцы визуальной системы — картинками, а не именами файлов.
export const SAMPLE_KINDS = ["telegram-post", "telegram-cover", "linkedin-post", "linkedin-cover"];
export const SAMPLE_VARIANTS = ["plain", "photo"];
export function palette(md) {
return [...md.matchAll(/^\|\s*([^|`]+?)\s*\|\s*`(#[0-9A-Fa-f]{6})`\s*\|\s*([^|]+?)\s*\|\s*$/gm)].map((m) => ({ name: m[1], code: m[2], use: m[3] }));
}
export function sampleFile(name) {
if (!/^[\w-]+\.(png|svg)$/.test(name)) return null;
const file = path.join(SAMPLES, name);
if (!fs.existsSync(file)) return null;
return { buf: fs.readFileSync(file), mime: name.endsWith(".png") ? "image/png" : "image/svg+xml" };
}
function showcase(md, lang) {
const sw = palette(md).map((c) => `<figure class="sw"><div style="background:${c.code}"></div><figcaption><b>${esc(c.name)}</b> <code>${c.code}</code><br>${esc(c.use)}</figcaption></figure>`).join("");
const samples = SAMPLE_KINDS.map((k) => `<h4>${esc(t(lang, "vs.kind." + k))}</h4><div class="row">` + SAMPLE_VARIANTS.map((v) => {
const cap = `${t(lang, "vs.kind." + k)}, ${t(lang, "vs.variant." + v)}`;
return `<figure class="smp"><a href="/design/brand-visual/${k}-${v}.png"><img loading="lazy" src="/design/brand-visual/${k}-${v}.png" alt="${esc(cap)}"></a><figcaption>${esc(t(lang, "vs.variant." + v))}</figcaption></figure>`;
}).join("") + "</div>").join("\n");
return `<section class="vs"><h2>${esc(t(lang, "vs.title"))}</h2><p>${esc(t(lang, "vs.intro"))}</p>
<h3>${esc(t(lang, "vs.palette"))}</h3><div class="row">${sw}</div>
<h3>${esc(t(lang, "vs.fonts"))}</h3>
<p class="fh">${esc(t(lang, "vs.sample.head"))}</p><p><small>${esc(t(lang, "vs.font.head"))}</small></p>
<p class="fb">${esc(t(lang, "vs.sample.body"))}</p><p><small>${esc(t(lang, "vs.font.body"))}</small></p>
<h3>${esc(t(lang, "vs.samples"))}</h3>
${samples}</section>`;
}
const VS_HEAD = `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=PT+Sans&family=PT+Serif:wght@700&display=swap">
<style>.row{display:flex;flex-wrap:wrap;gap:12px}figure{margin:0}.sw{width:140px;font-size:13px}.sw div{height:72px;border-radius:8px;border:1px solid #ccc}.smp{flex:1 1 300px;max-width:390px;font-size:13px;color:#555}.smp img{width:100%;border:1px solid #ccc;border-radius:6px;display:block}.fh{font:700 30px/1.2 "PT Serif",Georgia,serif;margin:8px 0 0}.fb{font:18px/1.5 "PT Sans",Arial,sans-serif;margin:12px 0 0}small{color:#666}h4{margin:18px 0 6px}</style>`;
export function docPage(name, lang = "ru") {
if (!/^[\w-]+$/.test(name)) return null;
const file = path.join(DOCS, name + ".md");
if (!fs.existsSync(file)) return null;
const md = fs.readFileSync(file, "utf8");
const title = md.match(/^#\s+(.*)$/m)?.[1] ?? name;
const visual = name === "visual-system";
let body = renderMarkdown(md);
if (visual) {
const at = body.indexOf("<h2>");
body = at < 0 ? body + showcase(md, lang) : body.slice(0, at) + showcase(md, lang) + "\n" + body.slice(at);
}
return `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}</title>
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:820px;margin:auto;padding:16px;color:#222}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:4px 8px;text-align:left}code{background:#f2f2f2;padding:0 3px}.st{display:inline-block;border-radius:10px;padding:0 8px;font-size:14px;background:#fff3d6;color:#6b4a00}.st.ok{background:#dff5e3;color:#14532d}</style>${visual ? VS_HEAD : ""}</head><body>
<p><a href="/">${esc(t(lang, "doc.back"))}</a> · <span class="st ${readStatus()[name]?.state === "approved" ? "ok" : "draft"}">${esc(stateLabel(readStatus()[name], lang))}</span></p>
${body}
</body></html>`;
}
export const docNames = () => DOC_LIST.filter(([n]) => fs.existsSync(path.join(DOCS, n + ".md")));