Persist user GUI preferences and resize the shared media modal
DC CMS qualification / qualify (push) Successful in 2m22s

This commit is contained in:
DCCONSTRUCTIONS
2026-11-13 17:56:23 +03:00
parent ff90b633d9
commit 5d56f5fe21
19 changed files with 321 additions and 110 deletions
+8 -14
View File
@@ -3,15 +3,12 @@ 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 storageKey = "dc-cms.ui-preferences.v1";
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 read() {
try { return normalize(JSON.parse(localStorage.getItem(storageKey))); } catch { return { ...defaults }; }
}
function apply(preferences) {
const accent = preferences.accent?.match(/[\da-f]{2}/gi).map(v => parseInt(v, 16));
clearNodedcAccent(document.documentElement);
@@ -24,19 +21,15 @@ function Preferences({ initial }) {
const [preferences, setPreferences] = useState(initial);
const [open, setOpen] = useState(false);
const [session, setSession] = useState(null);
const [storageError, setStorageError] = useState(false);
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 sync = event => { if (event.key === storageKey || event.key === null) { const value = read(); apply(value); setPreferences(value); } };
window.addEventListener("storage", sync);
return () => { controller.abort(); window.removeEventListener("storage", sync); };
const unsubscribe = guiPreferences.subscribe((document, status) => { const value = normalize(document.appearance); apply(value); setPreferences(value); setStorageStatus(status); });
return () => { controller.abort(); unsubscribe(); };
}, []);
function update(patch) {
const value = normalize({ ...preferences, ...patch });
apply(value);
setPreferences(value);
try { localStorage.setItem(storageKey, JSON.stringify(value)); setStorageError(false); } catch { setStorageError(true); }
guiPreferences.update({ appearance: patch });
}
const user = session?.user;
const name = user?.name || user?.username || "Профиль";
@@ -48,12 +41,13 @@ function Preferences({ initial }) {
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" }, storageError ? "Настройки действуют в этой вкладке. Браузер не разрешил сохранить их для следующего входа." : "Изменения сохраняются автоматически в этом браузере.")
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 = read();
const preferences = guiPreferences.value.appearance;
apply(preferences);
flushSync(() => createRoot(document.querySelector("#cms-profile")).render(h(Preferences, { initial: preferences })));
}