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
+1 -1
View File
File diff suppressed because one or more lines are too long
+85 -85
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -198,6 +198,8 @@
</aside> </aside>
</div> </div>
<footer class="template-modal-foot media-modal-foot"> <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-refresh" class="ghost-btn" type="button">Обновить список</button>
<button id="media-modal-cancel" class="ghost-btn" type="button">Отмена</button> <button id="media-modal-cancel" class="ghost-btn" type="button">Отмена</button>
</footer> </footer>
+8
View File
@@ -80,3 +80,11 @@ Workflow `.gitea/workflows/ci.yml` квалифицирует точный commi
## Проверка ## Проверка
`node --test test/multisite.test.mjs` проверяет изоляцию контента, медиа, рендера и ссылок предпросмотра, секреты, конфликт направлений, перезапуск и авторизацию. `python3 -m unittest discover -s infra/ci -p 'test_*.py'` проверяет формат пакета и запрет runtime-файлов. `node --test test/multisite.test.mjs` проверяет изоляцию контента, медиа, рендера и ссылок предпросмотра, секреты, конфликт направлений, перезапуск и авторизацию. `python3 -m unittest discover -s infra/ci -p 'test_*.py'` проверяет формат пакета и запрет runtime-файлов.
## Пользовательские настройки интерфейса
`GET/PATCH /api/user/preferences` использует текущую авторизованную сессию; идентификатор пользователя не принимается из запроса. Файл: `<CMS_PROJECTS_ROOT>/.user-meta/<sha256(principal)>.json`, права 0600. Каталог находится в существующем persistent mount, вне корней сайтов, публикации и ZIP-бэкапов. В режиме без авторизации используется отдельный локальный профиль.
Схема: `schemaVersion: 1`, `appearance: {theme, accent}`, `gui: {modals: {"media-library": {width, height}}}`. PATCH объединяет независимые поля последовательно на пользователя; запись атомарная. `null` у ключа модального окна сбрасывает его размер. Тема из прежнего localStorage импортируется один раз при отсутствии серверного профиля.
Файловый менеджер использует общий `createModalSizeController`: края/углы мышью, Shift + стрелки при фокусе на шапке. Сохраняется завершённый resize. Подгонка под меньший экран не перезаписывает предпочтительный размер. Геометрия общая для сайтов текущего пользователя; контент менеджера по-прежнему изолирован по сайту. Ошибка записи отображается с повтором, закрытие окна не блокируется.
+1 -1
View File
@@ -61,7 +61,7 @@ def main():
files=tracked_payload() files=tracked_payload()
for name in files: for name in files:
if name.endswith(('.js','.mjs')): run(['node','--check',name]) if name.endswith(('.js','.mjs')): run(['node','--check',name])
run(['node','--test','test/multisite.test.mjs','test/publication.test.mjs','test/backup.test.mjs']) run(['node','--test','test/multisite.test.mjs','test/publication.test.mjs','test/backup.test.mjs','test/user-preferences.test.mjs'])
run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py']) run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py'])
# The ordinary release cannot change its build, dependency or deployment foundation. # The ordinary release cannot change its build, dependency or deployment foundation.
foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']} foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']}
+8
View File
@@ -4,6 +4,7 @@ import { dirname, join, resolve, posix, relative } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { randomBytes } from "node:crypto"; import { randomBytes } from "node:crypto";
import { createSiteApplication } from "./site-app.mjs"; import { createSiteApplication } from "./site-app.mjs";
import { UserPreferencesStore } from "./user-preferences.mjs";
const cmsRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const cmsRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const projectsRoot = resolve(process.env.CMS_PROJECTS_ROOT || join(cmsRoot, "projects")); const projectsRoot = resolve(process.env.CMS_PROJECTS_ROOT || join(cmsRoot, "projects"));
@@ -150,6 +151,7 @@ function json(res, status, payload) {
} }
await mkdir(projectsRoot, { recursive: true }); await mkdir(projectsRoot, { recursive: true });
const auth = await application(defaultId); const auth = await application(defaultId);
const userPreferences = new UserPreferencesStore(projectsRoot);
const server = createServer(async (req, res) => { const server = createServer(async (req, res) => {
try { try {
const url = new URL(req.url, "http://cms.local"); const url = new URL(req.url, "http://cms.local");
@@ -160,6 +162,12 @@ const server = createServer(async (req, res) => {
const expected = new URL(process.env.CMS_BASE_URL || `http://${req.headers.host}`).origin; const expected = new URL(process.env.CMS_BASE_URL || `http://${req.headers.host}`).origin;
if (req.headers["sec-fetch-site"] === "cross-site" || (origin && origin !== expected)) throw fail("Недопустимый источник запроса", 403); if (req.headers["sec-fetch-site"] === "cross-site" || (origin && origin !== expected)) throw fail("Недопустимый источник запроса", 403);
} }
if (url.pathname === "/api/user/preferences") {
const principal = auth.authEnabled ? (req.cmsUser?.sub ? `oidc:${req.cmsUser.sub}` : null) : 'local:no-auth';
if (req.method === 'GET') return json(res, 200, { ok: true, ...await userPreferences.read(principal) });
if (req.method === 'PATCH') return json(res, 200, { ok: true, ...await userPreferences.patch(principal, await body(req), { ifAbsent: req.headers['if-none-match'] === '*' }) });
throw fail('Метод не поддерживается', 405);
}
if (url.pathname === "/api/sites") { if (url.pathname === "/api/sites") {
if (req.method === "GET") return json(res, 200, { ok: true, sites: await siteList() }); if (req.method === "GET") return json(res, 200, { ok: true, sites: await siteList() });
if (req.method === "POST") return json(res, 201, { ok: true, project: await createSite(await body(req)) }); if (req.method === "POST") return json(res, 201, { ok: true, project: await createSite(await body(req)) });
+1
View File
@@ -3166,6 +3166,7 @@ async function handle(req, res) {
} }
return { return {
handle, handleAuthRoute, authorizeRequest, handle, handleAuthRoute, authorizeRequest,
authEnabled: authConfig.enabled,
config: () => structuredClone(projectConfig), config: () => structuredClone(projectConfig),
publicConfig: publicProjectConfig, publicConfig: publicProjectConfig,
root: repoRoot, root: repoRoot,
+67
View File
@@ -0,0 +1,67 @@
import { createHash, randomBytes } from 'node:crypto';
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
const fail = () => Object.assign(new Error('Некорректные настройки интерфейса'), { status: 400 });
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const defaults = () => ({ schemaVersion: 1, appearance: { theme: 'dark', accent: null }, gui: { modals: {} } });
export function validatePreferencesPatch(patch) {
if (!object(patch) || Object.keys(patch).some(k => !['appearance', 'gui'].includes(k))) throw fail();
if (patch.appearance !== undefined) {
const a = patch.appearance;
if (!object(a) || Object.keys(a).some(k => !['theme', 'accent'].includes(k))) throw fail();
if (a.theme !== undefined && !['dark', 'light'].includes(a.theme)) throw fail();
if (a.accent !== undefined && a.accent !== null && (typeof a.accent !== 'string' || !/^#[a-f\d]{6}$/i.test(a.accent))) throw fail();
}
if (patch.gui !== undefined) {
if (!object(patch.gui) || Object.keys(patch.gui).some(k => k !== 'modals') || !object(patch.gui.modals)) throw fail();
for (const [key, size] of Object.entries(patch.gui.modals)) {
if (!/^[a-z][a-z0-9-]{0,63}$/.test(key) || ['constructor', 'prototype'].includes(key)) throw fail();
if (size === null) continue;
if (!object(size) || Object.keys(size).length !== 2 || !Number.isInteger(size.width) || !Number.isInteger(size.height) || size.width < 100 || size.height < 100 || size.width > 10000 || size.height > 10000) throw fail();
}
}
return patch;
}
/** Private per-principal metadata, outside all sites, exports and publish roots. */
export class UserPreferencesStore {
#root; #queues = new Map();
constructor(projectsRoot) { this.#root = join(projectsRoot, '.user-meta'); }
#key(principal) {
if (typeof principal !== 'string' || !principal) throw Object.assign(new Error('Требуется вход'), { status: 401 });
return createHash('sha256').update(principal).digest('hex');
}
async read(principal) {
const key = this.#key(principal);
try {
const document = JSON.parse(await readFile(join(this.#root, `${key}.json`), 'utf8'));
if (document.schemaVersion !== 1) throw new Error('Unsupported GUI metadata version');
validatePreferencesPatch({ appearance: document.appearance, gui: document.gui });
return { preferences: document, exists: true };
} catch (error) { if (error.code === 'ENOENT') return { preferences: defaults(), exists: false }; throw error; }
}
async patch(principal, patch, { ifAbsent = false } = {}) {
validatePreferencesPatch(patch);
const key = this.#key(principal);
const pending = (this.#queues.get(key) || Promise.resolve()).then(async () => {
const current = await this.read(principal);
if (ifAbsent && current.exists) return current;
const next = current.preferences;
Object.assign(next.appearance, patch.appearance);
if (next.appearance.accent) next.appearance.accent = next.appearance.accent.toLowerCase();
for (const [id, size] of Object.entries(patch.gui?.modals || {})) {
if (size === null) delete next.gui.modals[id]; else next.gui.modals[id] = size;
}
if (Object.keys(next.gui.modals).length > 64) throw fail();
await mkdir(this.#root, { recursive: true, mode: 0o700 });
const path = join(this.#root, `${key}.json`), temporary = `${path}.${randomBytes(8).toString('hex')}.tmp`;
try { await writeFile(temporary, JSON.stringify(next, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); await rename(temporary, path); }
finally { await rm(temporary, { force: true }); }
return { preferences: next, exists: true };
});
const settled = pending.catch(() => {});
this.#queues.set(key, settled);
try { return await pending; } finally { if (this.#queues.get(key) === settled) this.#queues.delete(key); }
}
}
+10 -1
View File
@@ -187,13 +187,22 @@ test('independent sites, rendering, secrets and publication ownership', async t
await t.test('cross-origin registry mutations are refused',async()=>{ await t.test('cross-origin registry mutations are refused',async()=>{
const response=await fetch(base+'/api/sites',{method:'POST',headers:{origin:'https://untrusted.invalid','content-type':'application/json'},body:JSON.stringify({id:'attack',copyFrom:'nodedc'})});assert.equal(response.status,403); const response=await fetch(base+'/api/sites',{method:'POST',headers:{origin:'https://untrusted.invalid','content-type':'application/json'},body:JSON.stringify({id:'attack',copyFrom:'nodedc'})});assert.equal(response.status,403);
}); });
await t.test('GUI preferences persist outside sites and reject cross-origin writes', async () => {
assert.equal((await api('/api/user/preferences')).exists, false);
await api('/api/user/preferences','PATCH',{gui:{modals:{'media-library':{width:1200,height:800}}}});
await api('/api/user/preferences','PATCH',{appearance:{theme:'light'}});
const response = await fetch(base+'/api/user/preferences',{method:'PATCH',headers:{origin:'https://untrusted.invalid','content-type':'application/json'},body:'{}'});
assert.equal(response.status,403);
assert.equal((await api('/api/sites')).sites.length,2);
});
await stop(); await start(); await stop(); await start();
await t.test('registry and edits survive server restart',async()=>{ await t.test('registry and edits survive server restart',async()=>{
assert.equal((await api('/api/user/preferences')).preferences.gui.modals['media-library'].width,1200);
assert.equal((await api('/api/sites')).sites.length,2);assert.equal((await api('/s/mission-core/api/page/home')).title,'Mission edited');assert.equal((await api('/s/nodedc/api/page/home')).title,'Agent edited'); assert.equal((await api('/api/sites')).sites.length,2);assert.equal((await api('/s/mission-core/api/page/home')).title,'Mission edited');assert.equal((await api('/s/nodedc/api/page/home')).title,'Agent edited');
}); });
await stop();await start(true); await stop();await start(true);
await t.test('registry, scoped content and preview retain authentication',async()=>{ await t.test('registry, scoped content and preview retain authentication',async()=>{
for(const path of ['/api/sites','/s/mission-core/api/page/home','/s/mission-core/api/project/backup','/s/mission-core/api/media/download?path=assets/proof.txt']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);} for(const path of ['/api/user/preferences','/api/sites','/s/mission-core/api/page/home','/s/mission-core/api/project/backup','/s/mission-core/api/media/download?path=assets/proof.txt']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);}
assert.equal((await fetch(base+'/s/mission-core/api/project/backup',{method:'POST',redirect:'manual'})).status,401); assert.equal((await fetch(base+'/s/mission-core/api/project/backup',{method:'POST',redirect:'manual'})).status,401);
assert.equal((await fetch(base+'/s/mission-core/index.html',{redirect:'manual'})).status,302); assert.equal((await fetch(base+'/s/mission-core/index.html',{redirect:'manual'})).status,302);
assert.equal((await fetch(base+'/healthz')).status,200); assert.equal((await fetch(base+'/healthz')).status,200);
+33
View File
@@ -0,0 +1,33 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { UserPreferencesStore } from '../server/user-preferences.mjs';
test('user GUI metadata is isolated, durable, private and merges independent writes', async t => {
const root = await mkdtemp(join(tmpdir(), 'cms-user-meta-')); t.after(() => rm(root, { recursive: true, force: true }));
const store = new UserPreferencesStore(root);
assert.equal((await store.read('alice')).exists, false);
await Promise.all([
store.patch('alice', { appearance: { theme: 'light', accent: '#AABBCC' } }),
store.patch('alice', { gui: { modals: { 'media-library': { width: 1250, height: 800 } } } }),
store.patch('bob', { gui: { modals: { 'media-library': { width: 640, height: 480 } } } }),
]);
const restarted = new UserPreferencesStore(root);
const alice = (await restarted.read('alice')).preferences;
assert.equal(alice.appearance.theme, 'light'); assert.equal(alice.appearance.accent, '#aabbcc');
assert.deepEqual(alice.gui.modals['media-library'], {width:1250,height:800});
assert.equal((await restarted.read('bob')).preferences.gui.modals['media-library'].width, 640);
assert.deepEqual((await restarted.patch('alice', { appearance: { theme: 'dark' } }, { ifAbsent: true })).preferences, alice);
const files = await readdir(join(root,'.user-meta')); assert.equal(files.length, 2);
for (const file of files) {
assert.match(file, /^[a-f\d]{64}\.json$/);
assert.equal((await stat(join(root,'.user-meta',file))).mode & 0o777, 0o600);
assert.ok(JSON.parse(await readFile(join(root,'.user-meta',file))).gui);
}
for (const patch of [{ user: 'bob' }, { gui: { modals: { '../evil': {width:900,height:600} } } }, { gui: {modals: {'media-library': {width:1e7,height:800}}} }, {appearance:{accent:'red'}}, JSON.parse('{"gui":{"modals":{"__proto__":null}}}')]) {
await assert.rejects(store.patch('alice', patch), {status:400});
}
await assert.rejects(store.read(''), { status: 401 });
assert.deepEqual((await store.read('alice')).preferences, alice);
});
+5 -2
View File
@@ -5,7 +5,10 @@
"packages": { "packages": {
"nodedc-tokens-0.6.0-mission.2.tgz": "11386a46868f8e7dafa2743770d15dc201e1df46d036921f03475c15a7351b9c", "nodedc-tokens-0.6.0-mission.2.tgz": "11386a46868f8e7dafa2743770d15dc201e1df46d036921f03475c15a7351b9c",
"nodedc-ui-core-0.7.0-mission.2.tgz": "6360deed064a7c3c5af9538fac38a31f9937d4521153705375c431e7afd56fe8", "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"
} }
} }
+2
View File
@@ -95,6 +95,8 @@
</aside> </aside>
</div> </div>
<footer class="template-modal-foot media-modal-foot"> <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-refresh" class="ghost-btn" type="button">Обновить список</button>
<button id="media-modal-cancel" class="ghost-btn" type="button">Отмена</button> <button id="media-modal-cancel" class="ghost-btn" type="button">Отмена</button>
</footer> </footer>
+3 -3
View File
@@ -8,7 +8,7 @@
"dependencies": { "dependencies": {
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.2.tgz", "@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-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", "@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.2.tgz",
"esbuild": "0.28.1", "esbuild": "0.28.1",
"react": "19.2.7", "react": "19.2.7",
@@ -499,8 +499,8 @@
}, },
"node_modules/@nodedc/ui-dom": { "node_modules/@nodedc/ui-dom": {
"version": "0.7.0", "version": "0.7.0",
"resolved": "file:vendor/nodedc-ui-dom-0.7.0-mission.2.tgz", "resolved": "file:vendor/nodedc-ui-dom-0.7.0-modal.1.tgz",
"integrity": "sha512-Cs2lKY7bvmiFOZ7X1FplqBeVqTq+1uWORUQIC+LIRDsdB84gZ2VpPqgB0yE/QsaW8FXKk9BmbfgzNVsYh2NVWw==", "integrity": "sha512-aG7ZLz63g5j9Ln4o0eWHgCyo9GKSw1PRFQBFuQiMk8LodRMfQHvKLh50TMMbMhLdCXqmvbAEonAMUpM/QqyJaw==",
"dependencies": { "dependencies": {
"@nodedc/ui-core": "0.7.0" "@nodedc/ui-core": "0.7.0"
} }
+1 -1
View File
@@ -9,7 +9,7 @@
"dependencies": { "dependencies": {
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.2.tgz", "@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-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", "@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.2.tgz",
"react": "19.2.7", "react": "19.2.7",
"react-dom": "19.2.7", "react-dom": "19.2.7",
+12
View File
@@ -449,6 +449,18 @@ dialog.site-dialog p {
gap: var(--nodedc-space-4); gap: var(--nodedc-space-4);
min-height: 20rem; 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 { .media-main {
min-width: 0; min-width: 0;
overflow: hidden; overflow: hidden;
+16 -2
View File
@@ -4,7 +4,8 @@ import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom"; import { flushSync } from "react-dom";
import { Select, Switch, ColorField, RangeControl, ProgressBar, Dropdown, IconButton, Icon, StatusBadge } from "@nodedc/ui-react"; import { Select, Switch, ColorField, RangeControl, ProgressBar, Dropdown, IconButton, Icon, StatusBadge } from "@nodedc/ui-react";
import { installPreferences } from "./preferences.mjs"; 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 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); const clone = (name) => $(`#ds-${name}`).content.firstElementChild.cloneNode(true);
function addClass(node, name) { function addClass(node, name) {
@@ -330,7 +331,19 @@ function initModals() {
overlay.removeAttribute("role"); overlay.removeAttribute("role");
overlay.removeAttribute("aria-modal"); overlay.removeAttribute("aria-modal");
const controller = createModalController({ overlay, dialog, closeOnBackdrop: false, closeOnEscape: false, lockBodyScroll: false }); 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")) { for (const dialog of all("dialog.site-dialog")) {
const overlay = document.createElement("div"); const overlay = document.createElement("div");
@@ -400,6 +413,7 @@ function refresh() {
if (open && !binding.controller.isOpen()) { if (open && !binding.controller.isOpen()) {
document.body.append(binding.overlay); document.body.append(binding.overlay);
binding.controller.open(); binding.controller.open();
binding.sizeController?.refresh();
} }
else if (!open && binding.controller.isOpen()) binding.controller.close(); else if (!open && binding.controller.isOpen()) binding.controller.close();
} }
+58
View File
@@ -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
View File
@@ -3,15 +3,12 @@ import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom"; import { flushSync } from "react-dom";
import { applyNodedcTheme, missionDarkTheme, missionLightTheme, clearNodedcAccent } from "@nodedc/ui-dom"; import { applyNodedcTheme, missionDarkTheme, missionLightTheme, clearNodedcAccent } from "@nodedc/ui-dom";
import { UserProfileMenu, FeatureSettingsWindow, SettingsCard, Select, ColorField, Button } from "@nodedc/ui-react"; import { UserProfileMenu, FeatureSettingsWindow, SettingsCard, Select, ColorField, Button } from "@nodedc/ui-react";
import { guiPreferences } from './gui-preferences.mjs';
const h = React.createElement; const h = React.createElement;
const storageKey = "dc-cms.ui-preferences.v1";
const defaults = { theme: "dark", accent: null }; const defaults = { theme: "dark", accent: null };
function normalize(value) { function normalize(value) {
return { theme: value?.theme === "light" ? "light" : "dark", accent: /^#[\da-f]{6}$/i.test(value?.accent || "") ? value.accent.toLowerCase() : null }; 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) { function apply(preferences) {
const accent = preferences.accent?.match(/[\da-f]{2}/gi).map(v => parseInt(v, 16)); const accent = preferences.accent?.match(/[\da-f]{2}/gi).map(v => parseInt(v, 16));
clearNodedcAccent(document.documentElement); clearNodedcAccent(document.documentElement);
@@ -24,19 +21,15 @@ function Preferences({ initial }) {
const [preferences, setPreferences] = useState(initial); const [preferences, setPreferences] = useState(initial);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [session, setSession] = useState(null); const [session, setSession] = useState(null);
const [storageError, setStorageError] = useState(false); const [storageStatus, setStorageStatus] = useState(guiPreferences.status);
useEffect(() => { useEffect(() => {
const controller = new AbortController(); const controller = new AbortController();
fetch("/api/me", { credentials: "same-origin", signal: controller.signal }).then(r => r.ok ? r.json() : null).then(setSession).catch(() => {}); 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); } }; const unsubscribe = guiPreferences.subscribe((document, status) => { const value = normalize(document.appearance); apply(value); setPreferences(value); setStorageStatus(status); });
window.addEventListener("storage", sync); return () => { controller.abort(); unsubscribe(); };
return () => { controller.abort(); window.removeEventListener("storage", sync); };
}, []); }, []);
function update(patch) { function update(patch) {
const value = normalize({ ...preferences, ...patch }); guiPreferences.update({ appearance: patch });
apply(value);
setPreferences(value);
try { localStorage.setItem(storageKey, JSON.stringify(value)); setStorageError(false); } catch { setStorageError(true); }
} }
const user = session?.user; const user = session?.user;
const name = user?.name || user?.username || "Профиль"; const name = user?.name || user?.username || "Профиль";
@@ -48,12 +41,13 @@ function Preferences({ initial }) {
footer: h(Button, { onClick: () => update(defaults), tone: "neutral" }, "Сбросить оформление") }, 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("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(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() { export function installPreferences() {
const preferences = read(); const preferences = guiPreferences.value.appearance;
apply(preferences); apply(preferences);
flushSync(() => createRoot(document.querySelector("#cms-profile")).render(h(Preferences, { initial: preferences }))); flushSync(() => createRoot(document.querySelector("#cms-profile")).render(h(Preferences, { initial: preferences })));
} }
Binary file not shown.