Files
anidev-design-system/playground/gallery.js
T

339 lines
10 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.
import { concepts, tokensFor, cssVars } from "../concepts/registry.js";
const $ = (s) => document.querySelector(s);
const design = concepts[0];
const defaults = {
concept: "dock",
page: "dashboard",
theme: "light",
density: "compact",
size: "desktop",
locale: "ru",
accents: {},
};
let saved = {};
try {
saved = JSON.parse(localStorage.getItem("anidev.lab") || "{}") || {};
} catch {}
const state = {
...defaults,
...Object.fromEntries(
["page", "theme", "density", "size", "locale"].map((k) => [
k,
saved[k] || defaults[k],
]),
),
accents: {},
};
if (/^#[0-9a-f]{6}$/i.test(saved.accents?.dock || ""))
state.accents.dock = saved.accents.dock;
const requested = new URLSearchParams(location.search);
const pages = [...$("#page").options].map((o) => o.value);
if (pages.includes(requested.get("page"))) state.page = requested.get("page");
if (!pages.includes(state.page)) state.page = "dashboard";
if (["light", "dark"].includes(requested.get("theme")))
state.theme = requested.get("theme");
if (!["light", "dark"].includes(state.theme)) state.theme = "light";
if (!["compact", "normal", "relaxed"].includes(state.density))
state.density = "compact";
if (!["desktop", "tablet", "mobile"].includes(state.size))
state.size = "desktop";
if (!["ru", "en"].includes(state.locale)) state.locale = "ru";
const strings = {
page: ["Экран", "Page"],
theme: ["Тема", "Theme"],
accent: ["Акцент", "Accent"],
density: ["Плотность", "Density"],
viewport: ["Размер", "Viewport"],
note: [
"Демонстрационные данные · Изменения сохраняются только в этом браузере · Ctrl/⌘ K — команды",
"Demo data · Changes are stored in this browser only · Ctrl/⌘ K — commands",
],
research: ["Исследование и решения", "Research & decisions"],
status: ["Dock · утверждённый дизайн", "Dock · approved design"],
};
function render() {
const en = state.locale === "en";
document.documentElement.lang = state.locale;
for (const key of ["page", "theme", "density"])
$("#" + key).value = state[key];
$("#workspace").dataset.device = state.size;
$("#accent").value =
state.accents.dock ||
(state.theme === "dark" ? design.darkAccent : design.accent);
$("#current-name").textContent = design.name;
$("#current-desc").textContent = en ? design.descEn : design.desc;
$("#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").textContent = "Dock";
$(".intro-copy").textContent = en
? "The Anidev interface system. Components, states and working patterns."
: "Система интерфейсов Anidev. Компоненты, состояния и рабочие сценарии.";
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]),
);
const params = new URLSearchParams({
concept: "dock",
page: state.page,
theme: state.theme,
density: state.density,
locale: state.locale,
});
if (state.accents.dock) params.set("accent", state.accents.dock);
const src = "frame.html?" + params;
if ($("#preview-a").getAttribute("src") !== src) $("#preview-a").src = src;
try {
localStorage.setItem("anidev.lab", JSON.stringify(state));
} catch {}
}
for (const key of ["page", "theme", "density"])
$("#" + key).addEventListener("change", (e) => {
state[key] = e.target.value;
render();
});
$("#accent").addEventListener("change", (e) => {
state.accents.dock = e.target.value;
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: "approved-design",
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}\nApproved Dock design.\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. Reusable Skill packaging is tracked separately.\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
: "Design system exported: " + c.name,
);
} catch (e) {
notice("Export error: " + e.message);
} finally {
button.disabled = false;
}
};
render();
addEventListener("message", (event) => {
if (
event.origin === location.origin &&
event.source === $("#preview-a").contentWindow &&
event.data?.type === "anidev-theme" &&
["light", "dark"].includes(event.data.theme)
) {
state.theme = event.data.theme;
render();
}
});