Persist user GUI preferences and resize the shared media modal
DC CMS qualification / qualify (push) Successful in 2m22s
DC CMS qualification / qualify (push) Successful in 2m22s
This commit is contained in:
@@ -5,7 +5,10 @@
|
||||
"packages": {
|
||||
"nodedc-tokens-0.6.0-mission.2.tgz": "11386a46868f8e7dafa2743770d15dc201e1df46d036921f03475c15a7351b9c",
|
||||
"nodedc-ui-core-0.7.0-mission.2.tgz": "6360deed064a7c3c5af9538fac38a31f9937d4521153705375c431e7afd56fe8",
|
||||
"nodedc-ui-dom-0.7.0-mission.2.tgz": "0884b595d78909047e79a266eaa8e0bcc5461f38e4c8e81076272107bb8c4a75",
|
||||
"nodedc-ui-react-0.7.0-mission.2.tgz": "cecf33a767e4c998e8c5cbcc70b20936844460424790d0a81aefa847c45f662e"
|
||||
"nodedc-ui-react-0.7.0-mission.2.tgz": "cecf33a767e4c998e8c5cbcc70b20936844460424790d0a81aefa847c45f662e",
|
||||
"nodedc-ui-dom-0.7.0-modal.1.tgz": "6e2d74f3b8e9aa797477ea82252f1e43d5efc041abceea3cd4319ba13d62969e"
|
||||
},
|
||||
"packageSourceCommits": {
|
||||
"nodedc-ui-dom-0.7.0-modal.1.tgz": "1ec17b30981e6f084ba288a530ee08280ab1f2a6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,6 +95,8 @@
|
||||
</aside>
|
||||
</div>
|
||||
<footer class="template-modal-foot media-modal-foot">
|
||||
<span id="media-size-status" class="nodedc-description" role="status">Размер окна сохраняется в профиле</span>
|
||||
<button id="media-size-retry" class="ghost-btn" type="button" hidden>Повторить</button>
|
||||
<button id="media-refresh" class="ghost-btn" type="button">Обновить список</button>
|
||||
<button id="media-modal-cancel" class="ghost-btn" type="button">Отмена</button>
|
||||
</footer>
|
||||
|
||||
Generated
+3
-3
@@ -8,7 +8,7 @@
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.2.tgz",
|
||||
"@nodedc/ui-core": "file:vendor/nodedc-ui-core-0.7.0-mission.2.tgz",
|
||||
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-mission.2.tgz",
|
||||
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-modal.1.tgz",
|
||||
"@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.2.tgz",
|
||||
"esbuild": "0.28.1",
|
||||
"react": "19.2.7",
|
||||
@@ -499,8 +499,8 @@
|
||||
},
|
||||
"node_modules/@nodedc/ui-dom": {
|
||||
"version": "0.7.0",
|
||||
"resolved": "file:vendor/nodedc-ui-dom-0.7.0-mission.2.tgz",
|
||||
"integrity": "sha512-Cs2lKY7bvmiFOZ7X1FplqBeVqTq+1uWORUQIC+LIRDsdB84gZ2VpPqgB0yE/QsaW8FXKk9BmbfgzNVsYh2NVWw==",
|
||||
"resolved": "file:vendor/nodedc-ui-dom-0.7.0-modal.1.tgz",
|
||||
"integrity": "sha512-aG7ZLz63g5j9Ln4o0eWHgCyo9GKSw1PRFQBFuQiMk8LodRMfQHvKLh50TMMbMhLdCXqmvbAEonAMUpM/QqyJaw==",
|
||||
"dependencies": {
|
||||
"@nodedc/ui-core": "0.7.0"
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
"dependencies": {
|
||||
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.2.tgz",
|
||||
"@nodedc/ui-core": "file:vendor/nodedc-ui-core-0.7.0-mission.2.tgz",
|
||||
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-mission.2.tgz",
|
||||
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-modal.1.tgz",
|
||||
"@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.2.tgz",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
|
||||
@@ -449,6 +449,18 @@ dialog.site-dialog p {
|
||||
gap: var(--nodedc-space-4);
|
||||
min-height: 20rem;
|
||||
}
|
||||
.media-modal > .nodedc-window__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.media-modal .media-browser { flex: 1; min-height: 12rem; }
|
||||
.media-modal .media-main { display: flex; flex-direction: column; min-height: 0; }
|
||||
.media-modal .media-columns { flex: 1; min-height: 0; }
|
||||
.media-modal .media-column { max-height: none; }
|
||||
.media-modal .media-preview-panel { overflow: auto; }
|
||||
.media-modal-foot { flex-wrap: wrap; }
|
||||
#media-size-status { margin-inline-end: auto; }
|
||||
.media-main {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -4,7 +4,8 @@ import { createRoot } from "react-dom/client";
|
||||
import { flushSync } from "react-dom";
|
||||
import { Select, Switch, ColorField, RangeControl, ProgressBar, Dropdown, IconButton, Icon, StatusBadge } from "@nodedc/ui-react";
|
||||
import { installPreferences } from "./preferences.mjs";
|
||||
import { createApplicationWorkspaceController, createModalController } from "@nodedc/ui-dom";
|
||||
import { createApplicationWorkspaceController, createModalController, createModalSizeController } from "@nodedc/ui-dom";
|
||||
import { guiPreferences } from './gui-preferences.mjs';
|
||||
const h = React.createElement, $ = (s, r = document) => r.querySelector(s), all = (s, r = document) => [...r.querySelectorAll(s)];
|
||||
const clone = (name) => $(`#ds-${name}`).content.firstElementChild.cloneNode(true);
|
||||
function addClass(node, name) {
|
||||
@@ -330,7 +331,19 @@ function initModals() {
|
||||
overlay.removeAttribute("role");
|
||||
overlay.removeAttribute("aria-modal");
|
||||
const controller = createModalController({ overlay, dialog, closeOnBackdrop: false, closeOnEscape: false, lockBodyScroll: false });
|
||||
modalBindings.push({ overlay, dialog, controller });
|
||||
let sizeController;
|
||||
if (overlay.id === 'media-modal') {
|
||||
sizeController = createModalSizeController({ dialog, initialSize: guiPreferences.modalSize('media-library') || { width: 1280, height: 820 }, minimum: { width: 640, height: 480 }, onSizeCommit: size => guiPreferences.setModalSize('media-library', size) });
|
||||
guiPreferences.subscribe((document, status) => {
|
||||
const size = document.gui.modals['media-library'];
|
||||
if (size) sizeController.setSize(size);
|
||||
const message = $('#media-size-status');
|
||||
message.textContent = status === 'error' ? 'Не удалось сохранить размер окна.' : status === 'saving' ? 'Сохранение размера…' : 'Размер окна сохраняется в профиле';
|
||||
$('#media-size-retry').hidden = status !== 'error';
|
||||
});
|
||||
$('#media-size-retry').addEventListener('click', () => guiPreferences.pending.length ? guiPreferences.flush() : guiPreferences.load());
|
||||
}
|
||||
modalBindings.push({ overlay, dialog, controller, sizeController });
|
||||
}
|
||||
for (const dialog of all("dialog.site-dialog")) {
|
||||
const overlay = document.createElement("div");
|
||||
@@ -400,6 +413,7 @@ function refresh() {
|
||||
if (open && !binding.controller.isOpen()) {
|
||||
document.body.append(binding.overlay);
|
||||
binding.controller.open();
|
||||
binding.sizeController?.refresh();
|
||||
}
|
||||
else if (!open && binding.controller.isOpen()) binding.controller.close();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
const defaults = () => ({ schemaVersion: 1, appearance: { theme: 'dark', accent: null }, gui: { modals: {} } });
|
||||
function merge(document, patch) {
|
||||
const next = structuredClone(document);
|
||||
Object.assign(next.appearance, patch.appearance);
|
||||
for (const [id, size] of Object.entries(patch.gui?.modals || {})) {
|
||||
if (size === null) delete next.gui.modals[id]; else next.gui.modals[id] = size;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
/** Application-owned GUI metadata. The server derives identity from the session. */
|
||||
export class UserGuiPreferences {
|
||||
value = defaults(); status = 'loading'; listeners = new Set(); pending = []; running = false;
|
||||
constructor() { this.ready = this.load(); }
|
||||
subscribe(listener) { this.listeners.add(listener); listener(this.value, this.status); return () => this.listeners.delete(listener); }
|
||||
notify() { for (const listener of this.listeners) listener(this.value, this.status); }
|
||||
async request(method = 'GET', patch, headers = {}) {
|
||||
const response = await fetch('/api/user/preferences', { method, credentials: 'same-origin', headers: { 'content-type': 'application/json', ...headers }, body: patch ? JSON.stringify(patch) : undefined });
|
||||
if (!response.ok) throw new Error('Не удалось сохранить настройки интерфейса');
|
||||
return response.json();
|
||||
}
|
||||
async load() {
|
||||
try {
|
||||
let result = await this.request();
|
||||
// One-time import of the previous browser-only appearance. Atomic create
|
||||
// prevents a second browser from replacing existing account preferences.
|
||||
let legacy;
|
||||
try { legacy = JSON.parse(localStorage.getItem('dc-cms.ui-preferences.v1')); } catch {}
|
||||
if (!result.exists && legacy) {
|
||||
const appearance = { theme: legacy.theme === 'light' ? 'light' : 'dark', accent: /^#[a-f\d]{6}$/i.test(legacy.accent || '') ? legacy.accent : null };
|
||||
result = await this.request('PATCH', { appearance }, { 'if-none-match': '*' });
|
||||
}
|
||||
try { localStorage.removeItem('dc-cms.ui-preferences.v1'); } catch {}
|
||||
this.value = this.pending.reduce(merge, result.preferences); this.status = 'saved';
|
||||
} catch { this.status = 'error'; }
|
||||
this.notify();
|
||||
}
|
||||
update(patch) {
|
||||
this.pending.push(structuredClone(patch)); this.value = merge(this.value, patch); this.status = 'saving'; this.notify();
|
||||
void this.flush();
|
||||
}
|
||||
async flush() {
|
||||
await this.ready;
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
try {
|
||||
while (this.pending.length) {
|
||||
this.status = 'saving'; this.notify();
|
||||
const result = await this.request('PATCH', this.pending[0]);
|
||||
this.pending.shift(); this.value = this.pending.reduce(merge, result.preferences);
|
||||
}
|
||||
this.status = 'saved';
|
||||
} catch { this.status = 'error'; }
|
||||
finally { this.running = false; this.notify(); }
|
||||
}
|
||||
modalSize(id) { return this.value.gui.modals[id]; }
|
||||
setModalSize(id, size) { this.update({ gui: { modals: { [id]: { width: Math.round(size.width), height: Math.round(size.height) } } } }); }
|
||||
}
|
||||
export const guiPreferences = new UserGuiPreferences();
|
||||
+8
-14
@@ -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 })));
|
||||
}
|
||||
|
||||
BIN
Binary file not shown.
Reference in New Issue
Block a user