Files
Harvey_Team_Page/scripts/generate-content.mjs
T
FastD 9e7b1e3430 Serve planet and mascots from src/assets
- Move served planet (animated webp, posters, 300 frames) and team mascots into src/assets/
- Use relative paths (assets/...) that work in file://, on the dev server and with docroot=src
- Screenshot pipeline writes to src/assets/projects
- Halo audit: report and measurements, ticker ring fix, shadow rules in DESIGN.md and spec.md
2026-11-10 18:42:12 +03:00

202 lines
9.0 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.
// generate-content.mjs — читает content/projects/*.md и content/team/*.md,
// парсит frontmatter (без внешних зависимостей) и пишет src/data/{projects,team}.js
// как window.HMT_* = [...] для статической страницы (vanilla, без сборки).
//
// Запуск: node scripts/generate-content.mjs
// Пользователь заполняет .md в след. сессиях → повторный запуск подтянет правки.
import { readFileSync, readdirSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { basename, join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const PROJ_DIR = join(ROOT, 'content', 'projects');
const TEAM_DIR = join(ROOT, 'content', 'team');
const OUT = join(ROOT, 'src', 'data');
// ---- minimal frontmatter parser: `---\n key: value\n ---` ----
// Supports: scalar `key: value`, inline list `key: [a, b]`,
// block list `key:` + indented `- a` lines, block map `key:` + indented ` sub: v`.
function parseFrontmatter(path) {
const raw = readFileSync(path, 'utf8').replace(/^\uFEFF/, '');
const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
const meta = {};
const body = m ? m[2] : raw;
if (m) {
const lines = m[1].split(/\r?\n/);
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (!line.trim() || line.trimStart().startsWith('#')) { i++; continue; }
const idx = line.indexOf(':');
if (idx < 0) { i++; continue; }
const key = line.slice(0, idx).trim();
const val = line.slice(idx + 1).trim();
if (val === '') {
// block value: look ahead at indented lines
const block = [];
let j = i + 1;
while (j < lines.length) {
const nxt = lines[j];
const trimmed = nxt.trim();
const indent = nxt.match(/^\s*/)[0].length;
if (!trimmed || indent === 0) break;
block.push(trimmed);
j++;
}
if (block.length) {
i = j;
if (block[0].startsWith('-')) {
meta[key] = block.map((b) => b.slice(1).trim().replace(/^['"]|['"]$/g, ''));
} else {
const map = {};
for (const b of block) {
const bi = b.indexOf(':');
if (bi > 0) map[b.slice(0, bi).trim()] = coerce(b.slice(bi + 1).trim());
}
meta[key] = map;
}
continue;
}
}
meta[key] = coerce(val);
i++;
}
}
return { meta, body: body.trim() };
}
// coerce a value: keep one-line scalar; leave nested to JSON-in-frontmatter caller.
function coerce(v) {
if (v === undefined) return '';
if (typeof v !== 'string') return v;
const t = v.trim();
if (t === '') return '';
if (/^(true|false)$/i.test(t)) return t.toLowerCase() === 'true';
if (/^-?\d+$/.test(t)) return Number(t);
if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
// array-ish literal: ["a", "b"] or [a, b]
if (t.startsWith('[') && t.endsWith(']')) {
const inner = t.slice(1, -1).trim();
if (!inner) return [];
return inner.split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, ''));
}
// ponytail: scalars are NOT comma-split — prose contains commas
// («Проект студии — описание, платформы и метрики…» became an array that way).
return t;
}
// toList: only the fields that ARE lists accept `a, b` scalar form.
function toList(v) {
if (Array.isArray(v)) return v;
const t = coerce(v);
if (Array.isArray(t)) return t;
if (typeof t !== 'string' || t === '') return [];
return t.includes(',') ? t.split(',').map((s) => s.trim()).filter(Boolean) : [t];
}
// Пути в .md относительны docroot (assets/…) — работают в file://, на dev-server и на хостинге.
// Отдаваемые ассеты лежат внутри src/assets/, сырьё — в Work_files/.
function sitePath(p) {
return String(p == null ? '' : p).trim();
}
// Публичная часть кейса. В content/*.md рядом с публичным текстом живут рабочие пометки
// («поле заполняет заказчик», «ждём кадр от команды», локальные пути на диск). В окно проекта
// уходит только то, что можно показать клиенту: «О проекте…» и «Факты о разработке».
const PUBLIC_SECTIONS = [/^О проекте/i, /^Факты о разработке/i];
function publicDetail(body) {
const out = [];
for (const part of String(body).split(/^##\s+/m)) {
const nl = part.indexOf('\n');
const title = (nl === -1 ? part : part.slice(0, nl)).trim();
const text = (nl === -1 ? '' : part.slice(nl + 1)).trim();
if (text && PUBLIC_SECTIONS.some((re) => re.test(title))) {
out.push('## ' + title + '\n\n' + text);
}
}
return out.join('\n\n');
}
function slugToName(slug) {
return slug
.split(/[-_]/)
.map((w) => (w ? w.charAt(0).toUpperCase() + w.slice(1) : w))
.join(' ');
}
function loadProjects() {
if (!existsSync(PROJ_DIR)) return [];
// Порядок показа = порядок объектов на арте планеты (§10.11 / D18): грузовик World Wide
// Wheels → жёлтый герой Moba → зелёная фишка BattleCaps → корабль TITANS (aquatherium).
// Выпущенные игры (bukvika, associations) — явным хвостом после арт-четвёрки. Не алфавит
// readdirSync: карточки в #work и плашка на планете должны идти в одном порядке.
const ART_ORDER = ['ww-wheels', 'moba', 'battlecaps', 'aquatherium', 'bukvika', 'associations', 'first-step-radio'];
const out = [];
for (const f of readdirSync(PROJ_DIR).filter((x) => x.endsWith('.md') && !x.startsWith('_'))) {
const { meta, body } = parseFrontmatter(join(PROJ_DIR, f));
const slug = meta.slug || basename(f, '.md');
const p = {
slug,
title: meta.title || slugToName(slug),
status: meta.status || '',
badge: meta.badge || '',
platforms: toList(meta.platforms),
stack: toList(meta.stack),
genre: String(meta.genre || ''),
link: meta.link || '',
play: meta.play || '',
video: meta.video || '',
images: toList(meta.images).map(sitePath),
metrics: (meta.metrics && typeof meta.metrics === 'object') ? meta.metrics : '',
summary: coerce(meta.summary),
detail: publicDetail(body),
};
out.push(p);
}
const rank = new Map(ART_ORDER.map((s, i) => [s, i]));
return out.sort((a, b) => (rank.get(a.slug) ?? ART_ORDER.length) - (rank.get(b.slug) ?? ART_ORDER.length));
}
function loadTeam() {
if (!existsSync(TEAM_DIR)) return [];
const roster = [
{ slug: 'timur', name: 'Тимур', role: 'Frontend · стратегия разработки' },
{ slug: 'maria', name: 'Мария', role: 'Product Manager' },
{ slug: 'den', name: 'Ден', role: '3D · Animation · Visualization' },
{ slug: 'kolya', name: 'Коля', role: 'Backend · network setup' },
{ slug: 'sergey', name: 'Сергей', role: 'Strategy · analytics · planning' },
];
const out = [];
for (const f of readdirSync(TEAM_DIR).filter((x) => x.endsWith('.md') && !x.startsWith('_'))) {
const { meta, body } = parseFrontmatter(join(TEAM_DIR, f));
const slug = meta.slug || basename(f, '.md');
// merge with fallback roster so names/roles survive a placeholder .md
const fallback = roster.find((r) => r.slug === slug) || { slug, name: slugToName(slug), role: '' };
out.push({
slug,
name: meta.name || fallback.name,
role: meta.role || fallback.role,
photo: sitePath(meta.photo), // реальное фото — только в расширенном профиле (окно по клику)
mascot: sitePath(meta.mascot), // «мордочка» на карточке (плейсхолдер команды)
city: String(meta.city || ''),
bio: meta.bio || body,
initials: (meta.name || fallback.name).split(/\s+/).map((w) => w[0]).join('').slice(0, 2).toUpperCase(),
});
}
// client-approved order: roster index, not readdirSync alphabet
const rank = new Map(roster.map((r, i) => [r.slug, i]));
return out.sort((a, b) => (rank.get(a.slug) ?? roster.length) - (rank.get(b.slug) ?? roster.length));
}
function writeJs(path, varname, data) {
mkdirSync(dirname(path), { recursive: true });
const json = JSON.stringify(data, null, 2);
writeFileSync(path, `// AUTO-GENERATED from content/ — do not edit. Run: node scripts/generate-content.mjs\nwindow.${varname} = ${json};\n`);
console.log(`wrote ${path} (${data.length} item(s))`);
}
writeJs(join(OUT, 'projects.js'), 'HMT_PROJECTS', loadProjects());
writeJs(join(OUT, 'team.js'), 'HMT_TEAM', loadTeam());
console.log('done.');