Merge remote-tracking branch 'origin/main'
This commit is contained in:
@@ -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>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { createModalController, createModalSizeController, renderPathBar } from '@nodedc/ui-dom';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import '@nodedc/ui-dom/styles.css';
|
||||
import { Button, Description, Icon } 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 path = useRef<HTMLDivElement>(null);
|
||||
const saved = useRef({ width: 800, height: 500 });
|
||||
useEffect(() => {
|
||||
renderPathBar(path.current!, [{label:'Файлы',path:'',kind:'folder'},{label:'Изображения',path:'images',kind:'folder'},{label:'example.png',path:'images/example.png',kind:'file',current:true}], {onNavigate: () => {}, icon: kind => { const span=document.createElement('span'); span.innerHTML=renderToStaticMarkup(<Icon name={kind}/>); return span.firstElementChild!; }});
|
||||
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 ref={path}/></div>
|
||||
<footer className="nodedc-window__footer"><Button onClick={() => modal.current?.close()}>Закрыть</Button></footer>
|
||||
</div></div>, document.body)}</>;
|
||||
}
|
||||
+15
-1
@@ -110,7 +110,7 @@ assets; the existing Git-to-canonical-runner deployment foundation is unchanged.
|
||||
CMS visual follow-up, 2026-11-05: flat theme edges, neutral white default accent,
|
||||
UserProfileMenu with a session avatar and inbox glyph, FeatureSettingsWindow,
|
||||
ColorField, pill-shaped split Select, and the canonical six-dot DragHandle.
|
||||
UI preferences belong to browser-local storage; site content and deployment
|
||||
UI preferences belong to authenticated per-user server metadata; site content and deployment
|
||||
credentials stay in the existing CMS model. Immutable npm snapshots retain
|
||||
package semver and are identified by source commit plus archive SHA-256.
|
||||
|
||||
@@ -146,3 +146,17 @@ 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. Медиатека остаётся привязанной к сайту, геометрия — к пользователю.
|
||||
|
||||
## CMS: строка пути файлов
|
||||
|
||||
CMS подключает `renderPathBar` и его stylesheet из ui-dom, source `1326ec6`,
|
||||
immutable archive `nodedc-ui-dom-0.7.0-modal.2.tgz`. Адаптер передаёт пути
|
||||
выбранного сайта, стандартный Icon и callback перехода в папку. Общий компонент
|
||||
владеет компактной строкой Finder, разделителями и нейтральными иконками.
|
||||
Сетка файлов, поиск и фильтрация по нескольким типам остаются доменной логикой
|
||||
CMS; переключатели используют общий IconButton. Проверены выбор глубокого
|
||||
пути, переход в каталог, dark/light и узкое окно 390 px.
|
||||
|
||||
+7
-1
@@ -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.
|
||||
@@ -561,4 +563,8 @@ The shared theme supports `edges: "flat"` for borderless surfaces, including por
|
||||
|
||||
## Viewport UI — правило владельца 14.11.2026
|
||||
|
||||
Все элементы интерфейса с подложкой внутри viewport используют общий Glass V4: карты, BIM, LAS/облака точек, 3DGS, PlayCanvas, камеры и replay. Поиск, action rail, информационные плашки и меню относятся к этому правилу независимо от движка. Обычные панели вне viewport остаются matte. См. [контракт, применение и проверку](VIEWPORT_UI.md).
|
||||
Все элементы интерфейса с подложкой внутри viewport используют общий Glass V4: карты, BIM, LAS/облака точек, 3DGS, PlayCanvas, камеры и replay. Поиск, отдельные кнопки прозрачного action rail, информационные плашки и меню относятся к этому правилу независимо от движка. Обычные панели вне viewport остаются matte. См. [контракт, применение и проверку](VIEWPORT_UI.md).
|
||||
|
||||
## PathBar (DOM)
|
||||
|
||||
`renderPathBar(target, items, {icon, onNavigate})` — компактная строка пути в стиле Finder: нейтральные иконки папок, текст и разделители `›`, без pill-кнопок. Подключается `@nodedc/ui-dom/styles.css`. Папки — клавиатурно доступные кнопки; конечный файл — текст с `aria-current`. Длинный путь прокручивается по горизонтали. Consumer передаёт пути и существующий Icon, хранение и навигация остаются в приложении. Живой пример: «Размер DOM-окна».
|
||||
|
||||
+3
-2
@@ -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"
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
"version": "0.7.0",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist"
|
||||
"dist",
|
||||
"styles.css"
|
||||
],
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -11,7 +12,8 @@
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./styles.css": "./styles.css"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
|
||||
@@ -3,6 +3,8 @@ export * from "./applicationWorkspace.js";
|
||||
export * from "./floating.js";
|
||||
export * from "./mediaSource.js";
|
||||
export * from "./modal.js";
|
||||
export * from "./modalSize.js";
|
||||
export * from "./pathBar.js";
|
||||
export * from "./select.js";
|
||||
export * from "./shareLink.js";
|
||||
export * from "./toolbar.js";
|
||||
|
||||
@@ -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); }
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export type PathBarItem = { label: string; path: string; kind: 'folder' | 'file'; current?: boolean };
|
||||
/** Compact Finder-style path row. Navigation and icon source belong to the app. */
|
||||
export function renderPathBar(target: HTMLElement, items: PathBarItem[], options: { onNavigate: (path: string) => void; icon: (kind: 'folder' | 'file') => Node }) {
|
||||
target.classList.add('nodedc-path-bar');
|
||||
target.setAttribute('role', 'navigation'); target.setAttribute('aria-label', 'Путь к файлу');
|
||||
const nodes: Node[] = [];
|
||||
items.forEach((item, index) => {
|
||||
if (index) { const separator = document.createElement('span'); separator.className = 'nodedc-path-bar__separator'; separator.textContent = '›'; separator.setAttribute('aria-hidden', 'true'); nodes.push(separator); }
|
||||
const part = document.createElement(item.kind === 'folder' ? 'button' : 'span');
|
||||
part.className = 'nodedc-path-bar__item'; part.title = item.path || item.label;
|
||||
if (item.current) part.setAttribute('aria-current', 'location');
|
||||
const icon = document.createElement('span'); icon.className = 'nodedc-path-bar__icon'; icon.setAttribute('aria-hidden', 'true'); icon.append(options.icon(item.kind));
|
||||
const text = document.createElement('span'); text.textContent = item.label;
|
||||
part.append(icon, text);
|
||||
if (part instanceof HTMLButtonElement) { part.type = 'button'; part.addEventListener('click', () => options.onNavigate(item.path)); }
|
||||
nodes.push(part);
|
||||
});
|
||||
target.replaceChildren(...nodes);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
.nodedc-path-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-1);
|
||||
overflow-x: auto;
|
||||
flex: none;
|
||||
padding: var(--nodedc-space-2) var(--nodedc-space-3);
|
||||
color: var(--nodedc-text-secondary);
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
background: var(--nodedc-surface-group);
|
||||
}
|
||||
.nodedc-path-bar__item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--nodedc-space-1);
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: inherit;
|
||||
font-family: inherit;
|
||||
font-size: var(--nodedc-font-size-sm);
|
||||
line-height: 1.5;
|
||||
}
|
||||
button.nodedc-path-bar__item { cursor: pointer; }
|
||||
button.nodedc-path-bar__item:hover { color: var(--nodedc-text-primary); }
|
||||
button.nodedc-path-bar__item:focus-visible { outline: 2px solid var(--nodedc-text-primary); outline-offset: 2px; }
|
||||
.nodedc-path-bar__icon { display: inline-flex; color: var(--nodedc-text-primary); }
|
||||
.nodedc-path-bar__icon svg { width: 14px; height: 14px; }
|
||||
.nodedc-path-bar__separator { flex: none; color: var(--nodedc-text-muted); }
|
||||
@@ -424,7 +424,9 @@
|
||||
],
|
||||
"domPackage": "@nodedc/ui-dom",
|
||||
"domExports": [
|
||||
"createModalController"
|
||||
"createModalController",
|
||||
"createModalSizeController",
|
||||
"fitModalSize"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-overlay",
|
||||
@@ -441,7 +443,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.",
|
||||
@@ -1448,6 +1451,26 @@
|
||||
"Content is descriptive, never a menu or interactive form.",
|
||||
"No new app-local tooltip geometry or layer management."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "path-bar",
|
||||
"status": "baseline",
|
||||
"package": "@nodedc/ui-dom",
|
||||
"exports": [
|
||||
"renderPathBar",
|
||||
"PathBarItem"
|
||||
],
|
||||
"domContract": [
|
||||
"nodedc-path-bar"
|
||||
],
|
||||
"summary": "Compact Finder-style path navigation with neutral folder icons, separators and native folder buttons.",
|
||||
"behavior": [
|
||||
"Application supplies items, icon factory and navigation callback.",
|
||||
"Current location uses aria-current; long paths scroll without wrapping."
|
||||
],
|
||||
"rules": [
|
||||
"Use ui-dom/styles.css, theme tokens and textContent labels; no application-local breadcrumb pills."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
});
|
||||
Reference in New Issue
Block a user