Files
Harvey_Team_Page/scripts/generate-content.mjs
T
FastD 28a48aec0f Team photos, sectioned bios, one-block footer, release stamp 20261124
- team: sergey.webp added, timur.webp and den.webp replaced from team shots
  (256x256 webp q88, 13.8-19.9 KB); raw sources in Work_files/raw/
- content/team: fullname in frontmatter, bios split into sections
  (Опыт / Образование / Сильные стороны / Личное); profile dialog title
  takes fullname, body no longer repeats name, role or city
- team dialog: h2 and list styles, avatar pinned to the top, bio left-aligned
  on <=767 (list markers were centred)
- footer: links and legal in one zone, no separate strip under a hairline;
  brand and meta bottom-aligned; same layout on privacy.html
- release: ?v=20261124 on all five script URLs; check-release PASS, 349 files
- docs: AGENTS.md, design/spec.md, docs/project-inventory.md,
  docs/ads-readiness.md, src/assets/team/README.md
2026-11-24 20:10:55 +03:00

269 lines
13 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,
fullname: String(meta.fullname || ''), // имя в заголовке окна профиля: «Ден» на карточке, «Текгюл Кемал-Дениз» в окне
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))`);
}
// ---- SEO: статический каталог для поиска (виден без JS) ----
// Карточки рисует JS из data/*.js, поэтому в HTML нет текста проектов. Поисковик без
// рендера видит пустой блок. Генератор кладёт тот же каталог текстом в <noscript>
// между маркерами в src/index.html — один источник (content/*.md), ноль расхождений.
const SEO_START = '<!-- SEO:CATALOG:START -->';
const SEO_END = '<!-- SEO:CATALOG:END -->';
function escHtml(s) {
return String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
}
// Тот же мини-рендер markdown, что в main.js: «## » → h4, «- » → ul, абзац → p.
function detailToHtml(md) {
const out = [];
let list = false;
const closeList = () => { if (list) { out.push('</ul>'); list = false; } };
for (const rawLine of String(md || '').split('\n')) {
const line = rawLine.trim();
if (!line) { closeList(); continue; }
const h = line.match(/^#{2,4}\s+(.+)/);
if (h) { closeList(); out.push('<h4>' + escHtml(h[1]) + '</h4>'); continue; }
const li = line.match(/^[-*]\s+(.+)/);
if (li) { if (!list) { out.push('<ul>'); list = true; } out.push('<li>' + escHtml(li[1]) + '</li>'); continue; }
closeList();
out.push('<p>' + escHtml(line) + '</p>');
}
closeList();
return out.join('\n');
}
function seoCatalog(projects) {
const items = projects.map((p) => {
const meta = [p.badge, (p.platforms || []).join(' · '), (p.stack || []).join(' · ')].filter(Boolean).join(' · ');
return '<article>\n<h3>' + escHtml(p.title) + '</h3>\n' +
(meta ? '<p><strong>' + escHtml(meta) + '</strong></p>\n' : '') +
(p.tagline ? '<p>' + escHtml(p.tagline) + '</p>\n' : '') +
(p.detail ? detailToHtml(p.detail) + '\n' : '') +
'</article>';
}).join('\n');
return '<noscript>\n<p class="lead">Карточки проектов открываются с включённым JavaScript. Ниже — тот же каталог текстом.</p>\n' +
'<div class="seo-catalog">\n' + items + '\n</div>\n</noscript>';
}
function injectSeoCatalog(projects) {
const page = join(ROOT, 'src', 'index.html');
const html = readFileSync(page, 'utf8');
const a = html.indexOf(SEO_START);
const b = html.indexOf(SEO_END);
if (a < 0 || b < a) { console.log('seo: маркеры не найдены, пропуск'); return; }
const eol = html.includes('\r\n') ? '\r\n' : '\n';
const block = seoCatalog(projects).replace(/\n/g, eol);
const next = html.slice(0, a + SEO_START.length) + eol + block + eol + ' ' + html.slice(b);
writeFileSync(page, next);
console.log(`seo: каталог текстом — ${projects.length} карточек`);
}
const projects = loadProjects();
writeJs(join(OUT, 'projects.js'), 'HMT_PROJECTS', projects);
writeJs(join(OUT, 'team.js'), 'HMT_TEAM', loadTeam());
injectSeoCatalog(projects);
console.log('done.');