Add reusable centered DOM modal resizing with preference adapter

This commit is contained in:
DCCONSTRUCTIONS
2026-11-13 17:52:26 +03:00
parent 661ca2afd2
commit 1ec17b3098
9 changed files with 147 additions and 4 deletions
+2
View File
@@ -1,4 +1,5 @@
import { OperationalTypographyDemo } from "./OperationalTypographyDemo";
import { ModalSizeExample } from './ModalSizeExample';
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { applyGlassMaterial, applyNodedcTheme, defaultGlassMaterial, type GlassMaterialSettings, type NodedcTheme, type RgbTuple } from "@nodedc/ui-core";
import { createTemplateFeatures, getPageTemplate, pageTemplates, type PageTemplateDefinition } from "@nodedc/page-patterns";
@@ -1542,6 +1543,7 @@ export function CatalogApp() {
<SettingsCard align="center" role="status" title="Настройки применены" description="Проверьте подключение устройства." />
</Preview>
<Preview title="Операционная типографика" note="единый размер во всех состояниях"><OperationalTypographyDemo /></Preview>
<Preview title="Размер DOM-окна" note="геометрия с сохранением в приложении"><ModalSizeExample /></Preview>
<Preview title="Главная и окружение" note="единые компоненты · сохранение в памяти каталога">
<EnvironmentCatalogDemo />
</Preview>
+21
View File
@@ -0,0 +1,21 @@
import { createPortal } from 'react-dom';
import { useEffect, useRef } from 'react';
import { createModalController, createModalSizeController } from '@nodedc/ui-dom';
import { Button, Description } from '@nodedc/ui-react';
export function ModalSizeExample() {
const overlay = useRef<HTMLDivElement>(null), dialog = useRef<HTMLDivElement>(null);
const modal = useRef<ReturnType<typeof createModalController> | null>(null);
const saved = useRef({ width: 800, height: 500 });
useEffect(() => {
const size = createModalSizeController({ dialog: dialog.current!, initialSize: saved.current, onSizeCommit: value => { saved.current = value; } });
modal.current = createModalController({ overlay: overlay.current!, dialog: dialog.current!, onOpenChange: open => { if (open) size.refresh(); } });
return () => { modal.current?.destroy(); size.destroy(); };
}, []);
return <><Button onClick={() => modal.current?.open()}>Окно с сохранением размера</Button>
{createPortal(<div ref={overlay} hidden><div ref={dialog} className="nodedc-glass" aria-labelledby="modal-size-example-title">
<header className="nodedc-window__head"><h2 id="modal-size-example-title" className="nodedc-window__title">Размер модального окна</h2></header>
<div className="nodedc-window__body"><Description>Перетаскивание за края и углы. Для клавиатуры: фокус на шапке, Shift + стрелки. Повторное открытие сохраняет размер; уменьшение экрана не меняет предпочтение.</Description></div>
<footer className="nodedc-window__footer"><Button onClick={() => modal.current?.close()}>Закрыть</Button></footer>
</div></div>, document.body)}</>;
}
+4
View File
@@ -146,3 +146,7 @@ content cards. Collection entries and native JSON disclosures adopt the shared
GlassSurface group material. No local palette, field colors or business logic
are introduced. The prior soft-canvas composition is superseded in THEMING and
the living catalog; soft itself remains available for recessed non-form areas.
## CMS: размеры модальных окон
CMS подключает `createModalSizeController` из immutable ui-dom package, без копии resize-кода. Тонкий адаптер связывает `media-library` с серверным пользовательским GUI JSON; оформление и размеры записываются через аутентифицированный API. Медиатека остаётся привязанной к сайту, геометрия — к пользователю.
+2
View File
@@ -133,6 +133,8 @@ Modeless Inspector закрывается независимо от резуль
Для modeless Inspector доступен `draggable`: окно двигается за header, не блокирует приложение и ограничивается viewport. Modal-окна не становятся draggable автоматически.
DOM: `createModalSizeController({dialog, initialSize, minimum, onSizeCommit})` дополняет `createModalController` изменением размера за восемь краёв/углов. Шапка получает клавиатурный resize через Shift + стрелки. `setSize` восстанавливает сохранённый размер, `refresh` подгоняет окно после открытия. Подгонка под экран и pointercancel не записывают новое предпочтение. Контроллер не меняет modal/focus contract; приложение хранит размер отдельно для текущего пользователя. Живой пример: «Размер DOM-окна».
## WorkspaceWindow
`WorkspaceWindow` — modeless-окно внутри рабочей сцены приложения. Оно рендерится непосредственно в переданном workspace, не использует portal и не может перекрыть шапку, навигацию или соседние панели за пределами этого workspace.
+3 -2
View File
@@ -11,7 +11,7 @@
"scripts": {
"build": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react && npm run build --workspace @nodedc/ui-catalog",
"build:packages": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react",
"check": "npm run test:typography && npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock && npm run test:flat-theme && npm run test:mission-theme",
"check": "npm run test:typography && npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock && npm run test:flat-theme && npm run test:mission-theme && npm run test:modal-size",
"dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog",
"serve": "node server/catalog-server.mjs",
"validate:registry": "node scripts/validate-registry.mjs",
@@ -49,7 +49,8 @@
"test:typography": "node --test scripts/operational-typography.test.mjs",
"prebuild": "npm run test:typography",
"test:flat-theme": "node --test scripts/flat-theme.test.mjs",
"test:mission-theme": "node --test scripts/mission-theme.test.mjs"
"test:mission-theme": "node --test scripts/mission-theme.test.mjs",
"test:modal-size": "node --test scripts/modal-size.test.mjs"
},
"engines": {
"node": ">=20"
+1
View File
@@ -3,6 +3,7 @@ export * from "./applicationWorkspace.js";
export * from "./floating.js";
export * from "./mediaSource.js";
export * from "./modal.js";
export * from "./modalSize.js";
export * from "./select.js";
export * from "./shareLink.js";
export * from "./toolbar.js";
+69
View File
@@ -0,0 +1,69 @@
export type ModalSize = { width: number; height: number };
export function fitModalSize(size: ModalSize, viewport: ModalSize, minimum: ModalSize = { width: 320, height: 200 }): ModalSize {
const fit = (value: number, available: number, min: number) => Math.max(Math.min(min, Math.max(1, available - 32)), Math.min(value, Math.max(1, available - 32)));
return { width: fit(size.width, viewport.width, minimum.width), height: fit(size.height, viewport.height, minimum.height) };
}
/** Resize a centered DOM modal without changing its focus/layer controller.
* Persistence belongs to the consumer; only completed user gestures commit.
*/
export function createModalSizeController({ dialog, initialSize, minimum, onSizeCommit }: {
dialog: HTMLElement; initialSize: ModalSize; minimum?: ModalSize; onSizeCommit?: (size: ModalSize) => void;
}) {
const head = dialog.querySelector<HTMLElement>('.nodedc-window__head');
const previous = { width: dialog.style.width, height: dialog.style.height, maxHeight: dialog.style.maxHeight, tab: head?.getAttribute('tabindex'), title: head?.getAttribute('title') };
let desired = { ...initialSize };
let gesture: { id: number; x: number; y: number; edge: string; size: ModalSize; before: ModalSize } | null = null;
const viewport = () => ({ width: window.innerWidth, height: window.innerHeight });
const visible = () => dialog.getClientRects().length > 0;
const apply = (size = desired) => {
const fitted = fitModalSize(size, viewport(), minimum);
dialog.style.width = `${fitted.width}px`;
dialog.style.height = `${fitted.height}px`;
dialog.style.maxHeight = 'calc(100dvh - 2rem)';
return fitted;
};
const handles = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw'].map(edge => {
const handle = document.createElement('div');
handle.className = 'nodedc-window__resize'; handle.dataset.edge = edge; handle.setAttribute('aria-hidden', 'true');
handle.addEventListener('pointerdown', event => {
if (event.button !== 0 || gesture) return;
const rect = dialog.getBoundingClientRect();
gesture = { id: event.pointerId, x: event.clientX, y: event.clientY, edge, size: { width: rect.width, height: rect.height }, before: desired };
handle.setPointerCapture(event.pointerId); event.preventDefault();
});
dialog.append(handle); return handle;
});
const move = (event: PointerEvent) => {
if (!gesture || event.pointerId !== gesture.id) return;
const { size, edge, x, y } = gesture;
desired = apply({ width: size.width + (event.clientX - x) * (edge.includes('e') ? 2 : edge.includes('w') ? -2 : 0), height: size.height + (event.clientY - y) * (edge.includes('s') ? 2 : edge.includes('n') ? -2 : 0) });
event.preventDefault();
};
const end = (event: PointerEvent) => {
if (!gesture || event.pointerId !== gesture.id) return;
const before = gesture.before; gesture = null;
if (event.type === 'pointercancel') { desired = before; apply(); return; }
if (desired.width !== before.width || desired.height !== before.height) onSizeCommit?.({ ...desired });
};
const key = (event: KeyboardEvent) => {
if (event.target !== head || !event.shiftKey || !event.key.startsWith('Arrow')) return;
event.preventDefault();
const size = fitModalSize(desired, viewport(), minimum);
desired = apply({ width: size.width + (event.key === 'ArrowRight' ? 20 : event.key === 'ArrowLeft' ? -20 : 0), height: size.height + (event.key === 'ArrowDown' ? 20 : event.key === 'ArrowUp' ? -20 : 0) });
onSizeCommit?.({ ...desired });
};
const refresh = () => { if (visible() && !gesture) apply(); };
if (head) { head.tabIndex = 0; head.title = 'Размер окна: Shift + стрелки. Мышью — за край или угол.'; head.addEventListener('keydown', key); }
window.addEventListener('pointermove', move); window.addEventListener('pointerup', end); window.addEventListener('pointercancel', end); window.addEventListener('resize', refresh);
apply();
return {
refresh,
setSize(size: ModalSize) { if (!gesture) { desired = { ...size }; apply(); } },
destroy() {
window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', end); window.removeEventListener('pointercancel', end); window.removeEventListener('resize', refresh);
head?.removeEventListener('keydown', key); handles.forEach(handle => handle.remove());
for (const name of ['width', 'height', 'maxHeight'] as const) dialog.style[name] = previous[name];
if (head) for (const [name, value] of [['tabindex', previous.tab], ['title', previous.title]]) { if (value == null) head.removeAttribute(name!); else head.setAttribute(name!, value); }
},
};
}
+5 -2
View File
@@ -420,7 +420,9 @@
],
"domPackage": "@nodedc/ui-dom",
"domExports": [
"createModalController"
"createModalController",
"createModalSizeController",
"fitModalSize"
],
"domContract": [
"nodedc-overlay",
@@ -437,7 +439,8 @@
"modal-only body scroll lock",
"optional bounded dragging for modeless inspectors",
"move toggle: preserve mounted contents and current size; remove dimming, backdrop close, scroll lock and focus trap; header drag and eight invisible resize regions",
"Escape and Tab belong to the focused or topmost visible modal; parent windows do not dismiss behind nested settings."
"Escape and Tab belong to the focused or topmost visible modal; parent windows do not dismiss behind nested settings.",
"DOM modal resizing shares eight canonical edge handles, centered viewport bounds and keyboard Shift+arrow control; onSizeCommit runs only for completed user changes."
],
"rules": [
"headerActionsPlacement=before-close places context actions between the move toggle and close in both visual and keyboard order; the default preserves existing consumers.",
+40
View File
@@ -0,0 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { fitModalSize, createModalSizeController } from '../packages/ui-dom/dist/modalSize.js';
test('modal dimensions fit narrow and desktop screens without mutating preference', () => {
const requested = { width: 1600, height: 900 };
assert.deepEqual(fitModalSize(requested, { width: 375, height: 667 }), { width: 343, height: 635 });
assert.deepEqual(fitModalSize(requested, { width: 1920, height: 1080 }), requested);
assert.deepEqual(requested, { width: 1600, height: 900 });
});
test('only completed gestures commit; viewport fitting and cancellation preserve preference', () => {
class Element extends EventTarget {
style = { width: '', height: '', maxHeight: '' }; dataset = {}; attributes = new Map(); children = [];
setAttribute(k,v) { this.attributes.set(k,v); } getAttribute(k) { return this.attributes.get(k) ?? null; } removeAttribute(k) { this.attributes.delete(k); }
append(value) { this.children.push(value); } remove() {} setPointerCapture() {}
getClientRects() { return [1]; } getBoundingClientRect() { return { width: parseFloat(this.style.width), height: parseFloat(this.style.height) }; }
querySelector() { return head; }
}
const head = new Element(), dialog = new Element(), commits = [];
const oldWindow = globalThis.window, oldDocument = globalThis.document;
globalThis.window = Object.assign(new EventTarget(), { innerWidth: 1600, innerHeight: 1000 });
globalThis.document = { createElement: () => new Element() };
const dispatch = (target, type, values) => target.dispatchEvent(Object.assign(new Event(type, { cancelable: true }), values));
try {
const controller = createModalSizeController({ dialog, initialSize: { width: 800, height: 500 }, onSizeCommit: s => commits.push(s) });
const edge = dialog.children.find(node => node.dataset.edge === 'se');
dispatch(edge, 'pointerdown', {button: 0, pointerId: 1, clientX: 500, clientY: 500});
dispatch(window, 'pointermove', {pointerId: 1, clientX: 650, clientY: 600});
assert.equal(commits.length, 0);
dispatch(window, 'pointerup', {pointerId: 1});
assert.deepEqual(commits, [{width: 1100, height: 700}]);
window.innerWidth = 500; window.innerHeight = 400; window.dispatchEvent(new Event('resize'));
assert.equal(dialog.style.width, '468px'); assert.equal(commits.length, 1);
window.innerWidth = 1600; window.innerHeight = 1000; window.dispatchEvent(new Event('resize'));
assert.equal(dialog.style.width, '1100px');
dispatch(edge, 'pointerdown', {button: 0, pointerId: 2, clientX: 500, clientY: 500});
dispatch(window, 'pointermove', {pointerId: 2, clientX: 650, clientY: 600});
dispatch(window, 'pointercancel', {pointerId: 2}); assert.equal(dialog.style.width, '1100px'); assert.equal(commits.length, 1);
controller.destroy(); assert.equal(dialog.style.width, '');
} finally { globalThis.window = oldWindow; globalThis.document = oldDocument; }
});