Files
Harvey_Team_Page/scripts/generate-content.mjs
T
FastD 0ac596086a Release wave: no data collection, contact by email, deploy from src/
- Remove the request form, consent checkbox, honeypot, success dialog,
  form.js, analytics.js, the Yandex Metrica id and the cookie banner (D23).
- Contact is a mailto card to harveymonsterteam@gmail.com; privacy.html
  rewritten for "no data collected"; Google Fonts replaced by four
  self-hosted WOFF2 files, so the page makes no third-party request.
- Drop `summary` from the case contract: the project dialog shows the case
  body only, the planet plaque uses tagline, and a project without shots
  opens one honest slot instead of three fake ones.
- Restore the original voice and punctuation in 12 cards, strip internal
  wording from published copy, fix stale counts (20 projects, 5 releases).
- Deploy = contents of src/: api/ moved to archive/api/, new release gate
  scripts/check-release.mjs, deploy guide docs/deploy.md.
- Sync docs: AGENTS.md (D23, D8, R4 closed, structure), design/spec.md
  section 10.31, DESIGN.md, PRODUCT.md, INDEX.md, inventory.
2026-11-15 17:34:40 +03:00

210 lines
9.6 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) {
// CRLF → LF on read: смешанные концы строк в content/ иначе уезжают \r в src/data/*.js.
const raw = readFileSync(path, 'utf8').replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
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).
// Дальше — выпущенные игры, затем малые игры в разработке в порядке описания студии (2026-11-14)
// и зонтичный «Узурон». Не алфавит readdirSync: карточки в #work и плашка на планете идут в одном порядке.
const ART_ORDER = [
'ww-wheels', 'moba', 'battlecaps', 'aquatherium',
'bukvika', 'associations', 'first-step-radio', 'numbers', 'eye-trainer',
'hockey', 'tricky-blocks', 'photo-pairs', 'nornik',
'reaction-trainer', 'towers-balance', '3d-pairs', 'cube-2048', 'tetroll',
'crazy-grannies', 'uzuron',
];
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),
media: String(meta.media || ''), // 'portrait' — скриншоты 9:16: карточка и окно дают бокс выше
metrics: (meta.metrics && typeof meta.metrics === 'object') ? meta.metrics : '',
tagline: coerce(meta.tagline), // одна строка карточки + сводка в плашке планеты (D23)
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.');