Files
DC_CMS/ui/src/preferences.mjs
T
2026-11-13 17:56:23 +03:00

54 lines
4.6 KiB
JavaScript

import React, { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { applyNodedcTheme, missionDarkTheme, missionLightTheme, clearNodedcAccent } from "@nodedc/ui-dom";
import { UserProfileMenu, FeatureSettingsWindow, SettingsCard, Select, ColorField, Button } from "@nodedc/ui-react";
import { guiPreferences } from './gui-preferences.mjs';
const h = React.createElement;
const defaults = { theme: "dark", accent: null };
function normalize(value) {
return { theme: value?.theme === "light" ? "light" : "dark", accent: /^#[\da-f]{6}$/i.test(value?.accent || "") ? value.accent.toLowerCase() : null };
}
function apply(preferences) {
const accent = preferences.accent?.match(/[\da-f]{2}/gi).map(v => parseInt(v, 16));
clearNodedcAccent(document.documentElement);
applyNodedcTheme(document.documentElement, { ...(preferences.theme === "light" ? missionLightTheme : missionDarkTheme), accent });
}
function themeAccent() {
return "#" + getComputedStyle(document.documentElement).getPropertyValue("--nodedc-accent-rgb").trim().split(/\s+/).map(v => Number(v).toString(16).padStart(2, "0")).join("");
}
function Preferences({ initial }) {
const [preferences, setPreferences] = useState(initial);
const [open, setOpen] = useState(false);
const [session, setSession] = useState(null);
const [storageStatus, setStorageStatus] = useState(guiPreferences.status);
useEffect(() => {
const controller = new AbortController();
fetch("/api/me", { credentials: "same-origin", signal: controller.signal }).then(r => r.ok ? r.json() : null).then(setSession).catch(() => {});
const unsubscribe = guiPreferences.subscribe((document, status) => { const value = normalize(document.appearance); apply(value); setPreferences(value); setStorageStatus(status); });
return () => { controller.abort(); unsubscribe(); };
}, []);
function update(patch) {
guiPreferences.update({ appearance: patch });
}
const user = session?.user;
const name = user?.name || user?.username || "Профиль";
const actions = [{ id: "appearance", label: "Настройки интерфейса", icon: "settings", onSelect: () => setOpen(true) }];
if (session?.authEnabled) actions.push({ id: "logout", label: "Выйти", icon: "external", href: "/auth/logout" });
return h(React.Fragment, null,
h(UserProfileMenu, { displayName: name, subtitle: user?.email || undefined, avatarUrl: user?.picture || undefined, triggerLabel: "Профиль", triggerIcon: "inbox", actions }),
h(FeatureSettingsWindow, { open, title: "Настройки", subtitle: "Интерфейс CMS", identity: { title: name, subtitle: "NODE.DC CMS", avatarLabel: name, avatarUrl: user?.picture || undefined }, sections: [{ id: "appearance", label: "Оформление", icon: "settings", group: "Общие" }], activeSection: "appearance", onSectionChange: () => {}, onClose: () => setOpen(false),
footer: h(Button, { onClick: () => update(defaults), tone: "neutral" }, "Сбросить оформление") },
h("div", {className:"cms-preferences-fields"}, h(SettingsCard, { title: "Тема", description: "Светлый или тёмный интерфейс", actions: h("div", { className: "cms-preference-controls" }, h(Select, { label: "Тема интерфейса", value: preferences.theme, options: [{ value: "dark", label: "Тёмная" }, { value: "light", label: "Светлая" }], onChange: theme => update({ theme }) })) }),
h(SettingsCard, { title: "Акцентный цвет", description: "Цвет активных элементов", actions: h("div", { className: "cms-preference-controls" }, h(ColorField, { label: "Акцентный цвет", value: preferences.accent || themeAccent(), onChange: accent => update({ accent }) })) })),
h("p", { className: "nodedc-description", role: "status" }, storageStatus === 'error' ? "Не удалось сохранить настройки на сервере. Изменения остаются в этой вкладке." : storageStatus === 'saved' ? "Оформление и размеры окон сохраняются в профиле пользователя." : "Синхронизация настроек…"),
storageStatus === 'error' ? h(Button, { onClick: () => guiPreferences.pending.length ? guiPreferences.flush() : guiPreferences.load() }, "Повторить") : null
)
);
}
export function installPreferences() {
const preferences = guiPreferences.value.appearance;
apply(preferences);
flushSync(() => createRoot(document.querySelector("#cms-profile")).render(h(Preferences, { initial: preferences })));
}