Files

377 lines
12 KiB
JavaScript
Raw Permalink 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.
import { concepts, tokensFor, cssVars } from "../concepts/registry.js";
const $ = (s) => document.querySelector(s);
const defaults = {
concept: "dock",
second: "ledger",
page: "dashboard",
theme: "light",
density: "compact",
size: "desktop",
locale: "ru",
compare: false,
accents: {},
};
let state = { ...defaults };
try {
state = {
...defaults,
...JSON.parse(localStorage.getItem("anidev.lab") || "{}"),
};
} catch {}
const strings = {
page: ["Экран", "Page"],
theme: ["Тема", "Theme"],
accent: ["Акцент", "Accent"],
density: ["Плотность", "Density"],
viewport: ["Размер", "Viewport"],
compare: ["Сравнить", "Compare"],
second: ["Вторая концепция", "Second concept"],
note: [
"Демонстрационные данные · Изменения сохраняются только в этом браузере · Ctrl/⌘ K — команды",
"Demo data · Changes are stored in this browser only · Ctrl/⌘ K — commands",
],
research: ["Исследование и решения", "Research & decisions"],
status: [
"Концепции на рассмотрении — финальная не выбрана",
"Explorations in review — no final concept selected",
],
};
const requested = new URLSearchParams(location.search);
if (requested.get("concept") === "dock") {
state.concept = "dock";
state.compare = false;
state.density = "compact";
delete state.accents.dock;
}
if (
[...document.querySelector("#page").options].some(
(o) => o.value === requested.get("page"),
)
)
state.page = requested.get("page");
function render() {
const en = state.locale === "en";
document.documentElement.lang = state.locale;
$("#concepts").innerHTML = concepts
.map(
(c, i) =>
`<button class="concept" data-concept="${c.id}" aria-pressed="${c.id === state.concept}"><span class="swatch" style="--swatch-bg:${c.bg};--swatch-ink:${c.ink};--swatch-line:${c.line}"></span><span class="concept-info"><b>${c.name}</b><small>0${i + 1}</small></span><span class="concept-caption">${en ? c.en : c.tag}</span></button>`,
)
.join("");
$("#second").innerHTML = concepts
.map(
(c) =>
`<option value="${c.id}" ${c.id === state.second ? "selected" : ""}>${c.name}</option>`,
)
.join("");
for (const key of ["page", "theme", "density"])
$("#" + key).value = state[key];
$("#compare").checked = state.compare;
$("#compare-label").hidden = !state.compare;
$("#pane-b").hidden = !state.compare;
$("#workspace").classList.toggle("comparing", state.compare);
$("#workspace").dataset.device = state.size;
const c = concepts.find((c) => c.id === state.concept);
$("#accent").value =
state.accents[c.id] ||
(state.theme === "dark" ? c.darkAccent || c.accent : c.accent);
$("#current-name").textContent = c.name;
$("#current-desc").textContent = en ? c.descEn : c.desc;
$("#heading-a").textContent = state.compare ? "A / " + c.name : "";
$("#heading-b").textContent =
"B / " + concepts.find((c) => c.id === state.second).name;
$("#dimensions").textContent = {
desktop: en ? "Desktop / fluid" : "Desktop / по ширине",
tablet: "768 × 900",
mobile: "390 × 844",
}[state.size];
document
.querySelectorAll("[data-size]")
.forEach((b) =>
b.setAttribute("aria-pressed", b.dataset.size === state.size),
);
document
.querySelectorAll("[data-i]")
.forEach((e) => (e.textContent = strings[e.dataset.i][en ? 1 : 0]));
$("#locale").textContent = en ? "RU" : "EN";
$("#export").textContent = en ? "Export system" : "Экспорт системы";
$("h1").innerHTML = en
? "One product.<br><span>Six perspectives.</span>"
: "Один продукт.<br><span>Шесть точек зрения.</span>";
$(".intro-copy").innerHTML = en
? "Working interfaces for infrastructure.<br>Explore the character. Inspect the details.<br>You choose the final direction."
: "Рабочие интерфейсы для инфраструктуры.<br>Исследуйте характер, проверьте детали.<br>Финальное направление выбираете вы.";
const labels = en
? [
"Dashboard",
"Users",
"Settings",
"Authentication",
"Components",
"Tokens",
"Account",
"Security",
"Devices and sessions",
"Applications",
"Appearance",
"Sign-in states",
]
: [
"Dashboard",
"Пользователи",
"Настройки",
"Авторизация",
"Компоненты",
"Токены",
"Аккаунт",
"Безопасность",
"Устройства и сеансы",
"Приложения",
"Оформление",
"Состояния входа",
];
[...$("#page").options].forEach((o, i) => (o.text = labels[i]));
[...$("#theme").options].forEach(
(o, i) => (o.text = (en ? ["Light", "Dark"] : ["Светлая", "Тёмная"])[i]),
);
[...$("#density").options].forEach(
(o, i) =>
(o.text = (
en
? ["Normal", "Compact", "Relaxed"]
: ["Обычная", "Компактная", "Свободная"]
)[i]),
);
for (const side of ["a", "b"]) {
if (side === "b" && !state.compare) continue;
const concept = side === "a" ? state.concept : state.second;
const params = new URLSearchParams({
concept,
page: state.page,
theme: state.theme,
density: state.density,
locale: state.locale,
});
if (state.accents[concept]) params.set("accent", state.accents[concept]);
const src = "frame.html?" + params;
if ($("#preview-" + side).getAttribute("src") !== src)
$("#preview-" + side).src = src;
}
try {
localStorage.setItem("anidev.lab", JSON.stringify(state));
} catch {}
}
$("#concepts").addEventListener("click", (e) => {
const b = e.target.closest("[data-concept]");
if (b) {
state.concept = b.dataset.concept;
render();
}
});
for (const key of ["page", "theme", "density", "second"])
$("#" + key).addEventListener("change", (e) => {
state[key] = e.target.value;
render();
});
$("#accent").addEventListener("change", (e) => {
state.accents[state.concept] = e.target.value;
render();
});
$("#compare").addEventListener("change", (e) => {
state.compare = e.target.checked;
render();
});
document.querySelectorAll("[data-size]").forEach(
(b) =>
(b.onclick = () => {
state.size = b.dataset.size;
render();
}),
);
$("#locale").onclick = () => {
state.locale = state.locale === "ru" ? "en" : "ru";
render();
};
function notice(text) {
$("#notice").textContent = text;
$("#notice").style.display = "block";
setTimeout(() => ($("#notice").style.display = "none"), 4500);
}
// Uncompressed ZIP, UTF-8 filenames, CRC32: no runtime or export dependency.
function zip(files) {
const enc = new TextEncoder();
let offset = 0;
const chunks = [],
central = [];
const u16 = (v, n) => {
v.push(n & 255, (n >>> 8) & 255);
},
u32 = (v, n) => {
u16(v, n);
u16(v, n >>> 16);
};
for (const [name, content] of Object.entries(files)) {
const bytes = enc.encode(content),
nb = enc.encode(name);
let crc = -1;
for (const b of bytes) {
crc ^= b;
for (let k = 0; k < 8; k++)
crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
}
crc = (crc ^ -1) >>> 0;
const h = [];
u32(h, 0x04034b50);
u16(h, 20);
u16(h, 0x800);
u16(h, 0);
u16(h, 0);
u16(h, 0);
u32(h, crc);
u32(h, bytes.length);
u32(h, bytes.length);
u16(h, nb.length);
u16(h, 0);
h.push(...nb);
chunks.push(new Uint8Array(h), bytes);
const c = [];
u32(c, 0x02014b50);
u16(c, 20);
u16(c, 20);
u16(c, 0x800);
u16(c, 0);
u16(c, 0);
u16(c, 0);
u32(c, crc);
u32(c, bytes.length);
u32(c, bytes.length);
u16(c, nb.length);
u16(c, 0);
u16(c, 0);
u16(c, 0);
u16(c, 0);
u32(c, 0);
u32(c, offset);
c.push(...nb);
central.push(new Uint8Array(c));
offset += h.length + bytes.length;
}
const size = central.reduce((n, c) => n + c.length, 0),
end = [];
u32(end, 0x06054b50);
u16(end, 0);
u16(end, 0);
u16(end, central.length);
u16(end, central.length);
u32(end, size);
u32(end, offset);
u16(end, 0);
return new Blob([...chunks, ...central, new Uint8Array(end)], {
type: "application/zip",
});
}
$("#export").onclick = async () => {
const button = $("#export");
button.disabled = true;
try {
const c = concepts.find((c) => c.id === state.concept),
accent =
state.accents[c.id] ||
(state.theme === "dark" ? c.darkAccent || c.accent : c.accent);
const files = {};
const paths = [
"components/system.css",
"components/account-pages.js",
"patterns/demo-identity.js",
"concepts/registry.js",
"playground/frame.html",
"playground/frame.js",
"tokens/schema.json",
"components/CONTRACT.md",
"patterns/UX.md",
"patterns/IDENTITY.md",
"prompts/SSO.md",
"prompts/README.md",
"layouts/README.md",
"DESIGN.md",
"ANTI-SLOP.md",
];
const fetched = await Promise.all(
paths.map(async (p) => {
const r = await fetch("../" + p);
if (!r.ok) throw Error(p);
return [p, await r.text()];
}),
);
for (const [p, t] of fetched) files[p] = t;
for (const theme of ["light", "dark"]) {
const tokens = tokensFor(
c.id,
theme,
state.accents[c.id] || undefined,
state.density,
);
files[`tokens/${theme}.json`] = JSON.stringify(tokens, null, 2);
files[`tokens/${theme}.css`] = `:root {\n${cssVars(tokens)}\n}\n`;
}
files["selection.json"] = JSON.stringify(
{
version: "0.1.0",
status: "candidate-export",
concept: c.id,
page: state.page,
accent,
customAccent: state.accents[c.id] || null,
density: state.density,
theme: state.theme,
locale: state.locale,
},
null,
2,
);
const exportParams = new URLSearchParams({
concept: c.id,
page: state.page,
density: state.density,
theme: state.theme,
locale: state.locale,
});
if (state.accents[c.id]) exportParams.set("accent", state.accents[c.id]);
files["index.html"] =
`<!doctype html><meta charset="utf-8"><title>Anidev ${c.name}</title><script>location.replace('playground/frame.html?${exportParams}')<\/script>`;
files["README.md"] =
`# Anidev / ${c.name}\nCandidate export, not final approval.\nServe this folder over HTTP (for example python -m http.server 8080).\nOpen index.html.\nUse tokens/light.css or tokens/dark.css and components/system.css in any framework.\nSemantic token JSON is the source of values.\nNo upstream implementation is bundled. Final Skill follows user concept selection.\n`;
const url = URL.createObjectURL(zip(files)),
a = document.createElement("a");
a.href = url;
a.download = `anidev-${c.id}.zip`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 30000);
notice(
state.locale === "ru"
? "Экспортирована кандидатная система: " + c.name
: "Candidate system exported: " + c.name,
);
} catch (e) {
notice("Export error: " + e.message);
} finally {
button.disabled = false;
}
};
render();
addEventListener("message", (event) => {
if (
event.origin === location.origin &&
[
document.querySelector("#preview-a").contentWindow,
document.querySelector("#preview-b").contentWindow,
].includes(event.source) &&
event.data?.type === "anidev-theme" &&
["light", "dark"].includes(event.data.theme)
) {
state.theme = event.data.theme;
render();
}
});