9 Commits
34 changed files with 509 additions and 76 deletions
+2 -2
View File
@@ -11,8 +11,8 @@
},
"dependencies": {
"@nodedc/page-patterns": "0.1.0",
"@nodedc/ui-core": "0.7.1",
"@nodedc/ui-react": "0.7.1",
"@nodedc/ui-core": "0.7.4",
"@nodedc/ui-react": "0.7.10",
"cesium": "1.147.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
+23 -3
View File
@@ -57,6 +57,7 @@ import {
ShareLinkModal,
SplitPane,
SortableItem,
SortableList,
SortableScope,
SettingsCard,
Switch,
@@ -64,6 +65,7 @@ import {
TextField,
ToastCard,
ToastStack,
ToastObserver,
Toolbar,
NavigationCube,
UserProfileMenu,
@@ -235,7 +237,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
{
title: "Состояние и доступ",
note: "Вся платформа",
icons: ["check", "alert", "info", "info-plain", "activity", "lock", "key", "shield", "circle", "eye", "eye-off"],
icons: ["check", "alert", "info", "info-plain", "activity", "lock", "unlock", "key", "shield", "circle", "eye", "eye-off", "star"],
},
{
title: "Сущности",
@@ -250,6 +252,7 @@ const iconGroups: Array<{ title: string; note: string; icons: IconName[] }> = [
];
const iconLabels: Record<IconName, string> = {
star: "Избранное",
pipette: "Пипетка",
ruler: "Линейка", section: "Секущая плоскость", isolate: "Изолировать элемент",
power: "Питание",
@@ -290,6 +293,7 @@ const iconLabels: Record<IconName, string> = {
layers: "Слои",
list: "Список задач",
lock: "Закрыто",
unlock: "Открыто",
mail: "Приглашение",
minimize: "Свернуть",
network: "Связи",
@@ -359,6 +363,7 @@ export function CatalogApp() {
const [applicationSaveState, setApplicationSaveState] = useState<ApplicationDraftSaveState>("idle");
const [applicationError, setApplicationError] = useState("");
const [toasts, setToasts] = useState<ToastItem[]>([]);
const [observedToasts, setObservedToasts] = useState<ToastItem[]>([]);
const toastSequenceRef = useRef(0);
const [sessionProfile, setSessionProfile] = useState<FoundrySessionProfile | null>(null);
const [foundrySettingsOpen, setFoundrySettingsOpen] = useState(false);
@@ -404,6 +409,9 @@ export function CatalogApp() {
const [strokeColor, setStrokeColor] = useState("#2b2b36");
const [strokeOpacity, setStrokeOpacity] = useState(100);
const [treeDemoOpen,setTreeDemoOpen]=useState(false);
const [gridOrder,setGridOrder]=useState(["Первое изображение","Второе изображение","Третье изображение"]);
const [detailFloating,setDetailFloating]=useState(false);
const [detailRect,setDetailRect]=useState<import("@nodedc/ui-react").WindowRect>();
const [treeDemoRect,setTreeDemoRect]=useState({left:32,top:96,width:380,height:480});
const [treeSelected,setTreeSelected]=useState<string|null>('cells');
const [treeVisible,setTreeVisible]=useState(true);
@@ -1466,6 +1474,7 @@ export function CatalogApp() {
<div className="catalog-form">
<TextField label="Название проекта" hint="обязательно" value={projectName} onChange={(event) => setProjectName(event.target.value)} />
<TextAreaField label="Описание" value={notes} onChange={(event) => setNotes(event.target.value)} />
<TextAreaField appearance="plain" label="" aria-label="Текст заметки" value={notes} onChange={(event) => setNotes(event.target.value)} />
</div>
</Preview>
<Preview title="Действия" note="общая геометрия" className="catalog-preview--compact">
@@ -1547,6 +1556,7 @@ export function CatalogApp() {
</ResourceList>
<Button onClick={()=>setTreeDemoOpen(true)}>Дерево объектов · изменяемый размер</Button>
<DragDropRoot onDragEnd={()=>{}}><DraggableItem id="whole-material-tile">{({activator})=><Button {...activator.attributes} {...activator.listeners}>Перенос за всю плитку</Button>}</DraggableItem></DragDropRoot>
<SortableList handleSurface="control" layout="grid" className="catalog-sortable-grid" items={gridOrder} getId={item=>item} onReorder={setGridOrder}>{(item,{handle})=><GlassSurface padding="sm">{handle}<Icon name="image"/><Description>{item}</Description></GlassSurface>}</SortableList>
<SettingsCard title="Устройства не обнаружены" description="Подключите устройство, чтобы оно появилось в списке." />
<SettingsCard align="center" role="status" title="Настройки применены" description="Проверьте подключение устройства." />
</Preview>
@@ -1649,6 +1659,7 @@ export function CatalogApp() {
eyebrow="MAP / SETTINGS"
title="Настройки карты"
description="Theme-aware application panel"
headerActions={<IconButton label="Настройки панели" onClick={() => setInspectorOpen(true)}><Icon name="settings" /></IconButton>}
onClose={() => setSidePanelDemoOpen(false)}
>
<Inspector variant="panel" sections={environmentSections.slice(0, 3).map(section=>({...section,action:{label:`Действие секции ${section.label}`,icon:<Icon name="edit"/>,onAction:()=>setInspectorOpen(true)}}))} defaultOpen={[environmentSections[0]?.id ?? ""]} singleOpen />
@@ -1793,6 +1804,7 @@ export function CatalogApp() {
</div>
</SettingsCard>
<SettingsCard eyebrow="LIVE STATES" title="Проверка стека" description="Кнопки используют тот же bottom-right viewport, что и реальные save/update flows.">
<Description>Последняя передача приложению: {observedToasts.map(item => item.title).join(', ') || 'нет уведомлений'}</Description>
<div className="catalog-inline catalog-inline--wrap">
<Button onClick={() => pushToast("success", "Изменения сохранены", "Статус автоматически исчезнет.")}>Success</Button>
<Button onClick={() => pushToast("info", "Профиль применён", "Application использует выбранную версию.")}>Info</Button>
@@ -1858,6 +1870,8 @@ export function CatalogApp() {
<div className="catalog-icon-catalog">
<Preview title="Размеры и поверхности" note="glyph 16 px" className="catalog-preview--wide">
<div className="catalog-window-actions-demo">
<IconButton surface="none" label="В избранное" aria-pressed="false"><Icon name="star" /></IconButton>
<IconButton surface="none" label="Убрать из избранного" aria-pressed="true"><Icon name="star" fill="currentColor" /></IconButton>
<IconButton label="Камера включена" aria-pressed="true"><Icon name="camera" /></IconButton>
<IconButton label="План"><Icon name="plan" /></IconButton>
<IconButton label="Добавить"><Icon name="plus" /></IconButton>
@@ -2194,6 +2208,7 @@ export function CatalogApp() {
<UserProfileMenu
triggerLabel="Профиль"
triggerIcon="inbox"
headerAction={{label: 'Правая панель', pressed: sidePanelDemoOpen, onSelect: () => setSidePanelDemoOpen(open => !open)}}
displayName={sessionProfile?.user?.displayName || "Профиль"}
subtitle={sessionProfile?.user?.email || "NODE.DC Foundry"}
avatarUrl={sessionProfile?.user?.avatarUrl || undefined}
@@ -2380,6 +2395,7 @@ export function CatalogApp() {
) : null}
<Window open={treeDemoOpen} title="Объекты сцены" placement="end" resizable draggable rect={treeDemoRect} onRectCommit={setTreeDemoRect} onClose={()=>setTreeDemoOpen(false)}>
<div className="nodedc-viewport-surface" data-glass-context="scene"><IconButton label="Проверить fullscreen внутри окна" onClick={event=>{const viewport=event.currentTarget.parentElement!;void (document.fullscreenElement===viewport?document.exitFullscreen():viewport.requestFullscreen());}}><Icon name="expand"/></IconButton><Description>Окно и дерево сохраняются при развороте этого viewport и возврате.</Description></div>
<Tree defaultExpandedDepth={2} renderActions={node=><Dropdown width={320} trigger={({setTriggerRef,show,open})=><IconButton ref={setTriggerRef} label={`Информация: ${node.label}`} aria-expanded={open} onMouseEnter={show} onClick={show}><Icon name="info-plain" size={14}/></IconButton>}><Description>{node.label}</Description></Dropdown>} label="Пример дерева объектов: стрелка раскрывает, глазик меняет видимость без прокрутки" selected={treeSelected} selectedIds={treeSelectedIds} onSelect={(id,gesture)=>{setTreeSelected(id);setTreeSelectedIds(old=>gesture.shiftKey?gesture.rangeIds:gesture.metaKey?(old.includes(id)?old.filter(key=>key!==id):[...old,id]):gesture.ctrlKey?[...new Set([...old,id])]:[id]);}} onVisibilityChange={(_,visible)=>setTreeVisible(visible)} nodes={[{id:'scene',label:'Сцена',children:[{id:'model',label:'Модель',children:[{id:'cells',label:'Ячейки / внутренний блок',visible:treeVisible},{id:'panel',label:'Боковая панель корпуса / длинное название детали'}]}]}]}/>
</Window>
<Window
@@ -2396,6 +2412,8 @@ export function CatalogApp() {
<Window
open={createModuleOpen}
floating={detailFloating} onFloatingChange={setDetailFloating}
rect={detailRect} onRectCommit={setDetailRect}
title="Создать модуль"
headerActionsPlacement="before-close"
headerActions={<IconButton label="Очистить форму" onClick={() => {setCreateModuleName("");setCreateModuleSlug("");}}><Icon name="trash"/></IconButton>}
@@ -2493,7 +2511,7 @@ export function CatalogApp() {
<FoundrySettingsModal open={foundrySettingsOpen} isAdmin={isFoundryAdmin} onClose={() => setFoundrySettingsOpen(false)} />
<FeatureSettingsWindow open={featureSettingsDemoOpen} title="Настройки модуля" subtitle="Настройки и меню доступны также в полноэкранном просмотре"
<FeatureSettingsWindow open={featureSettingsDemoOpen} title="Настройки модуля" subtitle="При откреплении окно использует стекло viewport; настройки доступны в полноэкранном просмотре"
identity={{ title: 'Модуль', subtitle: 'Пример общего компонента', avatarLabel: 'DC' }}
sections={[{ id: 'general', label: 'Основное', icon: 'settings' }, ...Array.from({length:16}, (_,i)=>({id:`details-${i}`,label:`Раздел ${i+1}`,group:'Сведения'}))]}
activeSection={featureSettingsDemoSection} onSectionChange={setFeatureSettingsDemoSection}
@@ -2632,7 +2650,9 @@ export function CatalogApp() {
onClose={() => setConfirmOpen(false)}
onConfirm={() => setConfirmOpen(false)}
/>
<ToastStack items={toasts} onDismiss={dismissToast} />
<ToastObserver onPresent={setObservedToasts}>
<ToastStack items={toasts} onDismiss={dismissToast} />
</ToastObserver>
</>
);
}
+1 -1
View File
@@ -8,7 +8,7 @@ export function EditorDockExample({inWindow=false}:{inWindow?:boolean}){
return <>{!inWindow&&<><Button onClick={()=>setModal(true)}>Сцена в модальном окне</Button><Window open={modal} title="Просмотр сцены" onClose={()=>setModal(false)}><EditorDockExample inWindow/></Window></>}<Button onClick={()=>{setPurpose('edit');setOpen({objects:true,materials:true});setEditing(true);}}>Открыть редактор сцены</Button><Button onClick={()=>{setPurpose('view');setEditing(true);}}>Отдельное окно просмотра</Button><div style={{height:480}}>
<EditorWorkspace editing={editing} purpose={purpose} title={purpose==='view'?'Просмотр сцены':'Редактор сцены'} subtitle="Общая оконная система" onBack={()=>setEditing(false)} headerActions={purpose==='view'?<Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button>:undefined}>
<EditorDockLayout value={layout} onChange={setLayout} enabled={editing} primary={<div style={{display:'grid',height:'100%',placeContent:'center'}}><Description>Закреплённая сцена · откреплённые инструменты используют scene Glass V4</Description><Button onClick={()=>setOpen({objects:true,materials:true})}>Показать инструменты</Button></div>}
tools={[{id:'objects',title:'Объекты',label:'Объекты',open:open.objects,onClose:()=>setOpen(v=>({...v,objects:false})),content:<Description>Сцена → Модель → Детали</Description>},
tools={[{id:'objects',title:'Объекты',label:'Объекты',open:open.objects,onClose:()=>setOpen(v=>({...v,objects:false})),content:<Description>Сцена → Модель → Детали. Захват шапки — без рамки; Tab и стрелки — клавиатурное управление.</Description>},
{id:'materials',title:'Материалы',label:'Материалы',minimumSize:{width:380,height:280},footer:<Button width="full" onClick={()=>setColor('#292929')}>Сбросить настройки</Button>,open:open.materials,onClose:()=>setOpen(v=>({...v,materials:false})),content:<Inspector sections={[{id:"color",label:"Цвет без обводки и пипетка",content:<ControlRow label="Цвет"><ColorField label="Цвет материала" value={color} onChange={setColor}/></ControlRow>}]} defaultOpen={["color"]} header={<Description>Минимум 380 × 280. Пипетка берёт цвет с экрана после нажатия; Escape отменяет выбор. Нижняя кнопка не прокручивается.</Description>}/>}]}/>
</EditorWorkspace>
</div></>;
+2
View File
@@ -2307,3 +2307,5 @@ textarea {
.catalog-theme-fields { display: grid; gap: var(--nodedc-space-4); }
.catalog-viewport-actions {position:absolute;top:var(--nodedc-space-3);right:var(--nodedc-space-3);display:flex;gap:var(--nodedc-space-2);padding:var(--nodedc-space-2);}
.catalog-sortable-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:var(--nodedc-space-3,12px)}
+25 -1
View File
@@ -46,7 +46,7 @@ Icon-only action по умолчанию круглый. Квадратная к
## Field
FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
FieldFrame объединяет label, control, hint и description. `labelPlacement="below"` ставит компактную приглушённую подпись под контролом в заголовке; доступное имя контрола остаётся прежним. TextField/TextAreaField реализуют стандартные текстовые поля. `appearance="plain"` сохраняет вид обычного текста без подложки и позволяет сразу поставить каретку; при пустой подписи нужен `aria-label`. TextAreaField в этом режиме растёт по содержимому и ширине окна, нативные выделение, вставка и undo сохраняются. Автозаполнение браузера сохраняет материал поля, цвет текста и каретки текущей темы; синяя системная заливка не используется. Клавиатурный фокус остаётся видимым.
Приложение не должно вручную собирать label и input, если подходит Field. Ошибка и validation state будут расширением этого контракта, а не локальным классом приложения.
@@ -129,6 +129,8 @@ Window — единая механика открытия modal и правой
Содержание, сохранение и запросы принадлежат приложению.
Отсоединённое центральное окно автоматически получает `data-glass-context="scene"` и каноническое стекло viewport. Подтверждение несохранённого профиля использует `allowFloating={false}` и отдельные действия отмены, отказа и сохранения.
`WindowFooterActions` размещает группу действий справа, в том числе когда это единственная группа в footer. На узком экране действия переносятся внутри окна. Вспомогательный текст footer может оставаться слева.
Modeless Inspector закрывается независимо от результата автосохранения. Приложение сначала закрывает controlled `Window`, затем завершает сохранение асинхронно; сбой сообщает через компактный `ToastStack` с tone `error`, сохраняя draft текущего просмотра. Нельзя удерживать окно открытым, выводить внутри него browser-default `p`/heading или увеличивать текст ошибки до title-размера.
@@ -294,6 +296,13 @@ setup-команды, сохранение, API и права принадлеж
## SettingsCard и Switch
В `UserProfileMenu` необязательный `headerAction={{label, onSelect}}` отделяет
действие средней иконки от меню профиля. Аватар и текст профиля сохраняют меню.
`ToastObserver onPresent` сообщает приложению новые и изменённые завершённые
уведомления из вложенных `ToastStack`; хранение, даты и история принадлежат
приложению. `ToastStack observe={false}` исключает повторную регистрацию
сообщений, уже записанных сервером. Отображение и таймеры не изменяются.
`SettingsCard` фиксирует нейтральную структуру админской группы: eyebrow/title/description/actions/body. `Switch` покрывает компактное включение/видимость внутри таких групп. Данные секции, сохранение и права остаются в consumer.
Промежуточный loading-контейнер не должен обнулять вертикальный ритм тела
@@ -341,6 +350,8 @@ Reduced motion отключает анимацию. На узком экране
## ApplicationSidePanel
Перед кнопкой закрытия можно разместить действия через `headerActions`. Кнопка `UserProfileMenu.headerAction` принимает `pressed` и `controls` для связи с выдвижной панелью.
`ApplicationSidePanel` — правая application-level пара к `AdminNavigationPanel`.
Она использует ту же ширину `332–352 px`, радиус, theme-aware surface, тень и
круглые действия, но появляется справа налево. `ApplicationShell` размещает её
@@ -451,6 +462,8 @@ StatusBadge `variant="indicator"` отображает только одну л
React `Window` (including `FeatureSettingsWindow`) and `Dropdown` (including Select and ColorField) mount into the active native fullscreen element, falling back to document.body. Menu geometry remains viewport-fixed. Consumers must let an open dialog/menu handle Escape before restoring the fullscreen viewer.
A window containing the fullscreen viewport keeps its original portal host and mounted content. Escape restores that viewport first; Tab stays within its visible controls. Newly opened child windows and menus still mount inside fullscreen.
### Scene window and accordion actions
`WorkspaceWindow resizeIndicator={false}` скрывает только видимый уголок. Размер по-прежнему меняется перетаскиванием правого нижнего угла или стрелками при фокусе на ручке; фокус остаётся видимым.
@@ -613,3 +626,14 @@ ColorField screen sampling (owner direction, 2026-11-14): the shared palette inc
Floating EditorDockLayout tools honor minimumSize on restore, all eight resize edges and keyboard resize. If the available viewport is smaller, they fit that viewport; Inspector fields stack below a 330px content width instead of clipping. Tool footer is separate from the scrolling body; a Button width="full" is the canonical adaptive bottom action. The catalog's scene editor example demonstrates minimum size, a ColorField and fixed reset footer.
EditorDockLayout: every floating or actively detached tool uses context="scene" Glass V4 (shared scene tint/blur); docking removes that context and retains tiled surface/corner rules. Applies to hierarchy, layers, settings and any other editor tool. No application tint/blur overrides.
### Remembered detail windows and sortable image grids
`Window.floating/onFloatingChange` lets the host persist modal/floating mode by
window kind alongside `rect/onRectCommit`. See WINDOWS_AND_LAYERS.md.
`SortableList` and `SortableScope` accept `layout="grid"`; rectangular sorting
keeps the shared drag handle and activation threshold. The default stays vertical.
Для ручки поверх фотографии используйте `DragHandle surface="control"` или `SortableList handleSurface="control"`: видимый круг с общим стеклом внутри `nodedc-viewport-controls`. Bare-ручка остаётся вариантом по умолчанию для обычных строк.
Window `headerLayout="adaptive"` keeps contextual actions on one trailing row. The complete title moves below actions before clipping. The measured action width sets the minimum for all resize edges, keyboard resizing and restored layout; only an undersized device viewport allows horizontal action scrolling. `expanded` temporarily opens media at a moderate viewport-fitted size while retaining modal/floating presentation. Users can resize the expanded window; restoration returns the previous geometry without changing the regular rectangle. `expandedRect` / `onExpandedRectCommit` persist the user’s separate expanded position and dimensions; first expansion uses a moderate 960×800 ceiling within 80%/82% of the viewport.
+5
View File
@@ -0,0 +1,5 @@
# Favorites
Use the registered `star` icon in an IconButton with `aria-pressed`. The unset state is outline-only; the selected glyph uses `fill="currentColor"`. Keep the same hit target in both states. Place a card favorite action in its upper trailing corner, independent of opening the card. Persist the domain value at its owner; filtering favorites must not change it.
For a star without a surrounding disc, use `IconButton surface="none"`. The shared component owns the transparent surface and foreground; applications only position it. Keyboard focus and the hit target remain unchanged.
+8
View File
@@ -55,3 +55,11 @@ hover, focus, disabled и pending принадлежат кнопке. `activity
BIM controls use `ruler` (dimension line with extension lines/arrows), `section` (model intersected by a plane), `isolate` (temporary visibility/glasses), `perspective`/`orthographic` (projection cubes), and `fit-view` (frame extents). `info-plain` is an unframed i for compact tree actions next to the visibility eye; use 14 px for both glyphs. They share the canonical stroke and accessible control behavior.
Semantic references: [Revit measurement](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-Model/files/GUID-65EA44EC-C777-4C97-8718-5783C3A80B0A.htm), [temporary hide/isolate](https://help.autodesk.com/cloudhelp/2014/ENU/Revit-LT/files/GUID-A5E51D5E-8E18-4834-8A2F-8B4E3E6379A1.htm), [section box](https://help.autodesk.com/cloudhelp/2024/ENU/Revit-GetStarted/files/GUID-C9EA51CB-3214-4BD8-AD55-3BEB1CCD15B6.htm). Glyphs are original monochrome NODE.DC vectors; this does not claim copied Autodesk artwork or full Section Box functionality.
### Блокировка в дереве
`lock` / `unlock` показывают закрытый / открытый замок. Компактное действие
дерева использует прозрачную кнопку без `aria-pressed` и без белой активной
подложки; доступное имя описывает действие «Разблокировать» / «Заблокировать».
Состояние передаётся формой замка. Уменьшение glyph не уменьшает область нажатия.
+8
View File
@@ -95,3 +95,11 @@ height must not leave a visible head with its stem hidden below terrain.
Motion never recreates the Cesium viewer or any provider. A renderer teardown
stops its single animation frame loop.
## Визуальные настройки и профили · 17.11.2026
`MapVisualSettings` дополнен необязательными полями `MapSceneEffects`: небо/солнце/луна, цвет света и тени, детализация рельефа, разрешение, FXAA, HDR/exposure/tonemapper, Bloom и HBAO. `DEFAULT_MAP_SCENE_EFFECTS` соответствует исходным значениям Cesium 1.147. Отсутствующие поля не меняют поведение других потребителей. Применение обновляет живую сцену; viewer, camera, providers, тайловые маршруты и доменные объекты не пересоздаются. HBAO включается только при поддержке графического контекста.
Для большого набора настроек используется `FeatureSettingsWindow`, слева разделы; контролы — `Checker`, `RangeControl` с exactValueBounds, `ColorField`, `Select`. Настройки спутниковой подложки не являются цветокоррекцией BIM/гауссов; OSM style не меняет их материалы. HDR exposure/tonemapper действует только при включённом HDR. Нативные API сверены с исходниками 1.147 и [Cesium PostProcessStageCollection](https://cesium.com/learn/cesiumjs/ref-doc/PostProcessStageCollection.html).
Профили сохраняет host через revision/atomic JSON. Снимок содержит только визуальные настройки и слои; не копирует камеру, размещение, токены, routing или cache intent. Применение профиля не меняет пространственный контекст. Выбор доступен в модалке и в стеклянном меню слоёв (`Dropdown surfaceClassName="nodedc-viewport-surface"`).
+2
View File
@@ -17,3 +17,5 @@
Миграция начинается с BIM-карты/viewer и Центра наблюдения. Общий action scope охватывает существующие scene/map/replay controls; оставшиеся собственные подложки переводятся на тот же surface contract. Не создавать глобальную непрозрачную плашку вокруг всех viewports.
Уточнение 15.11.2026: все откреплённые панели `EditorDockLayout` (иерархия, слои, настройки и другие инструменты) автоматически получают `data-glass-context="scene"`. Материал действует уже во время отрыва/перетаскивания и после восстановления плавающего положения. Повторная стыковка возвращает материал и наружные углы tiled-панелей. Приложение не задаёт свои tint/blur/opacity.
Уточнение 17.11.2026: `Dropdown surfaceClassName="nodedc-viewport-surface"` получает тот же scene Glass V4 на самой portal-поверхности. Это применяется к меню слоёв карт; не добавлять под ним непрозрачную карточку. Настройки большого объёма открываются через `FeatureSettingsWindow` с навигацией слева, а не через отдельный draggable inspector.
+14
View File
@@ -171,3 +171,17 @@ Tool minimumSize governs floating and docked geometry alike, including restored
The primary scene owns an isolated stacking context so its toolbars stay behind floating tools. A tool outer shell clips without scrolling; only its body scrolls, keeping header/footer fixed even when a field receives focus.
ColorField spectrum has no decorative perimeter stroke; retain its visible sampling marker and keyboard focus. UserProfileMenu variant=header owns its HeaderProfile surface; consumers must not wrap it in another HeaderProfile.
## Focus of movable headers
Window, WorkspaceWindow and EditorDockLayout share the same drag-header focus contract. A pointer grab never inherits a keyboard focus ring or filled header from the previously focused input. Headers have no perimeter outline in any theme; keyboard focus uses the canonical contrasting surface. Pointer capture, focus ownership, Arrow/Shift+Arrow movement/resizing, Enter/Space docking and Escape cancellation remain unchanged. Check both direct grabbing and input → Tab → grabbing, in docked/floating and fullscreen contexts.
## Remembered presentation
Entity/detail windows persist presentation **by window kind**, not title or entity ID.
The application stores `floating` and `rect` in its durable user preferences;
`Window` consumes `floating`/`onFloatingChange` and `rect`/`onRectCommit`.
Opening the next entity restores the same mode, position and size. Return to modal
keeps the last floating rectangle for the next detachment. Viewport fitting does
not overwrite saved geometry. Switching view/edit keeps the same mounted Window.
Confirmation dialogs remain modal (`allowFloating=false`) and never inherit it.
+7 -7
View File
@@ -28,8 +28,8 @@
"version": "0.7.0",
"dependencies": {
"@nodedc/page-patterns": "0.1.0",
"@nodedc/ui-core": "0.7.1",
"@nodedc/ui-react": "0.7.1",
"@nodedc/ui-core": "0.7.4",
"@nodedc/ui-react": "0.7.10",
"cesium": "1.147.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
@@ -2494,7 +2494,7 @@
},
"packages/map-cesium-react": {
"name": "@nodedc/map-cesium-react",
"version": "0.1.2",
"version": "0.1.4",
"dependencies": {
"cesium": "1.147.0"
},
@@ -2516,7 +2516,7 @@
},
"packages/ui-core": {
"name": "@nodedc/ui-core",
"version": "0.7.1",
"version": "0.7.4",
"dependencies": {
"@nodedc/tokens": "0.6.0"
}
@@ -2525,17 +2525,17 @@
"name": "@nodedc/ui-dom",
"version": "0.7.0",
"dependencies": {
"@nodedc/ui-core": "0.7.1"
"@nodedc/ui-core": "0.7.4"
}
},
"packages/ui-react": {
"name": "@nodedc/ui-react",
"version": "0.7.1",
"version": "0.7.10",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@nodedc/ui-core": "0.7.1",
"@nodedc/ui-core": "0.7.4",
"lucide-react": "^0.468.0"
},
"devDependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@nodedc/map-cesium-react",
"version": "0.1.2",
"version": "0.1.4",
"description": "Shared credential-free Cesium adapter for NODE.DC Map Page consumers.",
"type": "module",
"main": "./dist/index.js",
@@ -15,6 +15,7 @@ import type {
MapProviderId,
MapRuntimeState,
} from "./contracts.js";
import {applyMapSceneEffects} from "./sceneEffects.js";
import { advanceGhostPins } from "./ghostPins.js";
import {
parseProviderEndpoint,
@@ -495,7 +496,9 @@ function applyPresentation(
buildings.maximumScreenSpaceError =
settings.buildings_maximum_screen_space_error;
buildings.style = new Cesium.Cesium3DTileStyle({
color: `color('${settings.buildings_color}', ${settings.buildings_opacity})`,
color: settings.buildings_style_default
? `Boolean(\${feature['cesium#color']}) ? color(\${feature['cesium#color']}, ${settings.buildings_opacity}) : color('#ffffff', ${settings.buildings_opacity})`
: `color('${settings.buildings_color}', ${settings.buildings_opacity})`,
});
}
runtime.ghostPins.show = layers.targets;
@@ -541,9 +544,9 @@ function applyPresentation(
}
viewer.shadows = settings.shadows_enabled;
const sunDate = Cesium.JulianDate.toDate(Cesium.JulianDate.now());
sunDate.setUTCHours(
clamp(Math.round(settings.sun_hour), 0, 24),
0,
if (!settings.sun_time_current) sunDate.setUTCHours(
Math.floor(clamp(settings.sun_hour, 0, 24)),
Math.round((settings.sun_hour % 1) * 60),
0,
0,
);
@@ -556,6 +559,7 @@ function applyPresentation(
2,
);
viewer.scene.light = sun;
applyMapSceneEffects(runtime, settings);
viewer.scene.requestRender();
}
+29 -1
View File
@@ -112,7 +112,7 @@ export type MapLayerVisibility = {
targets: boolean;
};
export type MapVisualSettings = {
export type MapVisualSettings = Partial<MapSceneEffects> & {
atmosphere_enabled: boolean;
atmosphere_hue: number;
atmosphere_saturation: number;
@@ -120,6 +120,7 @@ export type MapVisualSettings = {
fog_enabled: boolean;
fog_density: number;
sun_enabled: boolean;
sun_time_current?: boolean;
sun_hour: number;
sun_intensity: number;
shadows_enabled: boolean;
@@ -134,6 +135,7 @@ export type MapVisualSettings = {
globe_color: string;
background_color: string;
terrain_exaggeration: number;
buildings_style_default?: boolean;
buildings_color: string;
buildings_opacity: number;
buildings_maximum_screen_space_error: number;
@@ -155,6 +157,32 @@ export type MapVisualSettings = {
camera_animation_enabled: boolean;
};
/** Optional controls preserve presentation in existing hosts until explicitly supplied. */
export type MapSceneEffects = {
skybox_enabled: boolean;
sun_visible: boolean;
moon_visible: boolean;
ground_atmosphere_enabled: boolean;
sun_color: string;
shadow_darkness: number;
shadow_soft: boolean;
terrain_maximum_screen_space_error: number;
resolution_scale: number;
fxaa_enabled: boolean;
hdr_enabled: boolean;
exposure: number;
tonemapper: "PBR_NEUTRAL" | "ACES" | "FILMIC" | "REINHARD" | "MODIFIED_REINHARD";
bloom_enabled: boolean;
bloom_contrast: number;
bloom_brightness: number;
bloom_sigma: number;
bloom_step_size: number;
ao_enabled: boolean;
ao_intensity: number;
ao_bias: number;
ao_length_cap: number;
};
export type MapCacheIntent = {
enabled: boolean;
no_overwrite: boolean;
+3
View File
@@ -23,6 +23,7 @@ export type {
MapRuntimeConfiguration,
MapRuntimeState,
MapVisualSettings,
MapSceneEffects,
} from "./contracts.js";
export {
advanceGhostPins,
@@ -38,3 +39,5 @@ export {
readSafeErrorCode,
withProviderState,
} from "./runtime.js";
export {DEFAULT_MAP_SCENE_EFFECTS} from "./sceneEffects.js";
@@ -0,0 +1,38 @@
import type {MapSceneContext, MapSceneEffects, MapVisualSettings} from './contracts.js';
/** Native Cesium 1.147 defaults; adding a settings window does not change the scene. */
export const DEFAULT_MAP_SCENE_EFFECTS: Readonly<MapSceneEffects> = Object.freeze({
skybox_enabled:true, sun_visible:true, moon_visible:true, ground_atmosphere_enabled:true,
sun_color:'#ffffff', shadow_darkness:0.3, shadow_soft:false,
terrain_maximum_screen_space_error:2, resolution_scale:1, fxaa_enabled:false,
hdr_enabled:false, exposure:1, tonemapper:'PBR_NEUTRAL',
bloom_enabled:false, bloom_contrast:128, bloom_brightness:-0.3, bloom_sigma:2, bloom_step_size:1,
ao_enabled:false, ao_intensity:3, ao_bias:0.1, ao_length_cap:0.26,
});
/** Mutates visual properties only: never touches sources, camera, cache or domain objects. */
export function applyMapSceneEffects({Cesium,viewer}:Pick<MapSceneContext,'Cesium'|'viewer'>,s:MapVisualSettings):void {
const scene=viewer.scene, stages=scene.postProcessStages;
if(s.skybox_enabled!==undefined && scene.skyBox)scene.skyBox.show=s.skybox_enabled;
if(s.sun_visible!==undefined && scene.sun)scene.sun.show=s.sun_visible;
if(s.moon_visible!==undefined && scene.moon)scene.moon.show=s.moon_visible;
if(s.ground_atmosphere_enabled!==undefined)scene.globe.showGroundAtmosphere=s.ground_atmosphere_enabled;
if(s.sun_color!==undefined)scene.light.color=Cesium.Color.fromCssColorString(s.sun_color)??Cesium.Color.WHITE;
if(s.shadow_darkness!==undefined)viewer.shadowMap.darkness=s.shadow_darkness;
if(s.shadow_soft!==undefined)viewer.shadowMap.softShadows=s.shadow_soft;
if(s.terrain_maximum_screen_space_error!==undefined)scene.globe.maximumScreenSpaceError=s.terrain_maximum_screen_space_error;
if(s.resolution_scale!==undefined)viewer.resolutionScale=s.resolution_scale;
if(s.fxaa_enabled!==undefined)stages.fxaa.enabled=s.fxaa_enabled;
if(s.hdr_enabled!==undefined)scene.highDynamicRange=s.hdr_enabled;
if(s.exposure!==undefined)stages.exposure=s.exposure;
if(s.tonemapper!==undefined)stages.tonemapper=Cesium.Tonemapper[s.tonemapper];
if(s.bloom_enabled!==undefined)stages.bloom.enabled=s.bloom_enabled;
if(s.bloom_contrast!==undefined)stages.bloom.uniforms.contrast=s.bloom_contrast;
if(s.bloom_brightness!==undefined)stages.bloom.uniforms.brightness=s.bloom_brightness;
if(s.bloom_sigma!==undefined)stages.bloom.uniforms.sigma=s.bloom_sigma;
if(s.bloom_step_size!==undefined)stages.bloom.uniforms.stepSize=s.bloom_step_size;
if(s.ao_enabled!==undefined)stages.ambientOcclusion.enabled=s.ao_enabled && Cesium.PostProcessStageLibrary.isAmbientOcclusionSupported(scene);
if(s.ao_intensity!==undefined)stages.ambientOcclusion.uniforms.intensity=s.ao_intensity;
if(s.ao_bias!==undefined)stages.ambientOcclusion.uniforms.bias=s.ao_bias;
if(s.ao_length_cap!==undefined)stages.ambientOcclusion.uniforms.lengthCap=s.ao_length_cap;
}
@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {applyMapSceneEffects,DEFAULT_MAP_SCENE_EFFECTS} from '../dist/sceneEffects.js';
function context(supported=true){
const viewer={resolutionScale:1,shadowMap:{},scene:{skyBox:{},sun:{},moon:{},globe:{},light:{},postProcessStages:{fxaa:{},bloom:{uniforms:{}},ambientOcclusion:{uniforms:{}}}}};
const Cesium={Color:{fromCssColorString:value=>value,WHITE:'white'},Tonemapper:{ACES:'ACES',PBR_NEUTRAL:'PBR_NEUTRAL'},PostProcessStageLibrary:{isAmbientOcclusionSupported:()=>supported}};
return {viewer,Cesium};
}
test('optional effects leave legacy consumers unchanged',()=>{
const c=context(),before=structuredClone(c.viewer);applyMapSceneEffects(c,{});assert.deepEqual(c.viewer,before);
});
test('effects apply live and reset without changing camera or providers',()=>{
const c=context();c.viewer.camera={position:'unchanged'};c.viewer.terrainProvider={id:'cache'};
applyMapSceneEffects(c,{...DEFAULT_MAP_SCENE_EFFECTS,bloom_enabled:true,bloom_contrast:64,hdr_enabled:true,exposure:2,tonemapper:'ACES',ao_enabled:true,ao_intensity:6,sun_visible:false,resolution_scale:.7});
const {scene}=c.viewer;
assert.equal(scene.postProcessStages.bloom.enabled,true);assert.equal(scene.postProcessStages.bloom.uniforms.contrast,64);
assert.equal(scene.postProcessStages.ambientOcclusion.uniforms.intensity,6);assert.equal(scene.postProcessStages.ambientOcclusion.enabled,true);
assert.equal(scene.highDynamicRange,true);assert.equal(scene.postProcessStages.exposure,2);assert.equal(scene.postProcessStages.tonemapper,'ACES');
assert.equal(scene.sun.show,false);assert.equal(c.viewer.resolutionScale,.7);
applyMapSceneEffects(c,DEFAULT_MAP_SCENE_EFFECTS);
assert.equal(scene.postProcessStages.bloom.enabled,false);assert.equal(scene.highDynamicRange,false);assert.equal(scene.sun.show,true);
assert.deepEqual(c.viewer.camera,{position:'unchanged'});assert.deepEqual(c.viewer.terrainProvider,{id:'cache'});
});
test('unsupported ambient occlusion stays off',()=>{
const c=context(false);applyMapSceneEffects(c,{ao_enabled:true});assert.equal(c.viewer.scene.postProcessStages.ambientOcclusion.enabled,false);
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@nodedc/ui-core",
"version": "0.7.1",
"version": "0.7.4",
"type": "module",
"files": [
"dist",
+64 -3
View File
@@ -364,7 +364,8 @@
color: var(--nodedc-text-primary);
}
.nodedc-icon-button[aria-pressed="true"] {
.nodedc-icon-button[aria-pressed="true"],
.nodedc-header__profile .nodedc-icon-button[aria-pressed="true"] {
background: var(--nodedc-glass-control-active);
color: var(--nodedc-glass-control-active-text);
}
@@ -1632,6 +1633,8 @@ textarea.nodedc-field__control {
.nodedc-app-shell__end-panel {
right: var(--nodedc-app-page-pad);
width: var(--nodedc-app-nav-width);
transform: translateX(calc(100% + var(--nodedc-app-page-pad)));
transition: transform var(--nodedc-app-navigation-motion), visibility 0s linear 440ms;
visibility: hidden;
pointer-events: none;
}
@@ -1642,6 +1645,8 @@ textarea.nodedc-field__control {
}
.nodedc-app-shell[data-end-panel-open="true"] .nodedc-app-shell__end-panel {
transform: translateX(0);
transition-delay: 0s;
visibility: visible;
pointer-events: auto;
}
@@ -3002,7 +3007,7 @@ textarea.nodedc-field__control {
.nodedc-workspace-window__head:focus-visible {
background: var(--nodedc-focus-surface);
box-shadow: inset 0 0 0 1px rgb(var(--nodedc-accent-rgb) / 0.22);
box-shadow: none;
}
.nodedc-workspace-window[data-maximized="true"] .nodedc-workspace-window__head {
@@ -4637,7 +4642,7 @@ textarea.nodedc-field__control {
.nodedc-editor-dock :is(.nodedc-editor-dock__tool,.nodedc-editor-dock__primary)[data-dock-corners~="bottom-left"] {border-bottom-left-radius:var(--nodedc-radius-panel);}
.nodedc-editor-dock__tool>.nodedc-window__head {flex:none;cursor:grab;touch-action:none;user-select:none;}
.nodedc-editor-dock__tool>.nodedc-window__head:active {cursor:grabbing;}
.nodedc-editor-dock__tool>.nodedc-window__head:focus-visible {outline:2px solid var(--nodedc-text-primary);outline-offset:-3px;}
.nodedc-editor-dock__tool>.nodedc-window__head:focus-visible :is(.nodedc-window__title,.nodedc-window__subtitle,.nodedc-window__actions,.nodedc-window__close,.nodedc-icon-button) {color:inherit;}
.nodedc-editor-dock__body {flex:1;min-height:0;min-width:0;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;padding:0 var(--nodedc-space-3) var(--nodedc-space-3);}
.nodedc-editor-dock__tool .nodedc-inspector {width:100%;max-width:none;}
@@ -4828,6 +4833,7 @@ textarea.nodedc-field__control {
The DOM surface class is for existing semantic overlays, never the renderer. */
.nodedc-toolbar-wrap[data-scope="viewport"] .nodedc-toolbar__button:not([data-active="true"]),
.nodedc-viewport-surface[data-glass-context="scene"],
.nodedc-dropdown-surface.nodedc-viewport-surface,
:is(.nodedc-viewport-controls, .nodedc-scene-controls) :is(.nodedc-icon-button:not([aria-pressed="true"]), .nodedc-button:is([data-variant="secondary"], [data-variant="ghost"]):not([aria-pressed="true"]), .nodedc-select__toggle, .nodedc-segmented, .nodedc-workspace-window__action:not([aria-pressed="true"])) {
background: rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
color: var(--nodedc-text-primary);
@@ -4858,3 +4864,58 @@ textarea.nodedc-field__control {
.nodedc-range[data-variant="rail"] input[type="range"] { top: 50%; height: max(100%, 24px); transform: translateY(-50%); }
.nodedc-range-rail:has(input:focus-visible) .nodedc-range-rail__value { text-decoration: underline; text-underline-offset: 2px; }
.nodedc-range-rail[data-disabled] { opacity: var(--nodedc-disabled-opacity, 0.5); }
/* Shared move handles: no browser perimeter or pointer-inherited focus flash.
Keyboard navigation retains the canonical focus surface in every window. */
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex] {
outline: 0;
box-shadow: none;
}
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex]:focus-visible {
outline: 0;
box-shadow: none;
background: var(--nodedc-focus-surface);
}
[data-nodedc-edges="flat"] :is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex]:focus-visible {
background: var(--nodedc-text-primary);
color: var(--nodedc-canvas);
}
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex]:focus-visible :is(.nodedc-window__title, .nodedc-window__subtitle, .nodedc-workspace-window__title, .nodedc-workspace-window__subtitle) {
color: inherit;
}
[data-nodedc-edges] :is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex][data-pointer-focus="true"],
:is(.nodedc-window__head, .nodedc-workspace-window__head)[tabindex][data-pointer-focus="true"] {
outline: 0;
box-shadow: none;
background: transparent;
color: var(--nodedc-text-primary);
}
/* Directly editable detail copy: no permanent field plate. */
.nodedc-field--unlabelled > .nodedc-field__label-row {display:none;}
.nodedc-field--plain {gap:0;}
.nodedc-field--plain .nodedc-field__control {
min-height:0; padding:0; border-radius:var(--nodedc-radius-control-compact);
background:transparent; box-shadow:none; color:inherit; font:inherit; line-height:inherit;
}
.nodedc-field--plain .nodedc-field__control:focus-visible {background:var(--nodedc-focus-surface);}
.nodedc-field--plain textarea.nodedc-field__control {resize:none;overflow:hidden;}
.nodedc-drag-handle[data-surface="control"] {background:var(--nodedc-glass-control-bg);color:var(--nodedc-text-primary);}
:is(.nodedc-viewport-controls,.nodedc-scene-controls) .nodedc-drag-handle[data-surface="control"] {
background:rgb(var(--nodedc-modal-glass-tint-rgb) / var(--nodedc-scene-glass-opacity));
backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation));
-webkit-backdrop-filter:blur(var(--nodedc-scene-glass-blur)) saturate(var(--nodedc-modal-glass-saturation));
}
.nodedc-drag-handle[data-surface="control"]:hover {background:var(--nodedc-glass-control-hover);}
/* An adaptive action row defines the minimum resizable width. */
.nodedc-window[data-header-layout="adaptive"]>.nodedc-window__head>.nodedc-window__actions{flex-wrap:nowrap;width:max-content;max-width:100%;justify-self:end;overflow-x:auto}
.nodedc-window[data-header-stacked="true"]>.nodedc-window__head{grid-template-columns:minmax(0,1fr)}
.nodedc-window[data-header-stacked="true"]>.nodedc-window__head>.nodedc-window__actions{grid-row:1}
.nodedc-window[data-header-stacked="true"]>.nodedc-window__head>.nodedc-window__titles{grid-row:2}
.nodedc-window[data-header-layout="adaptive"]>.nodedc-window__head>.nodedc-window__actions>*{flex-shrink:0}
@media (prefers-reduced-motion: reduce) {
.nodedc-app-shell__end-panel { transition: none; }
}
+1 -1
View File
@@ -20,6 +20,6 @@
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@nodedc/ui-core": "0.7.1"
"@nodedc/ui-core": "0.7.4"
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@nodedc/ui-react",
"version": "0.7.1",
"version": "0.7.10",
"type": "module",
"files": [
"dist"
@@ -21,7 +21,7 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@nodedc/ui-core": "0.7.1",
"@nodedc/ui-core": "0.7.4",
"lucide-react": "^0.468.0"
},
"peerDependencies": {
@@ -7,6 +7,7 @@ export interface ApplicationSidePanelProps extends Omit<HTMLAttributes<HTMLEleme
title: ReactNode;
description?: ReactNode;
closeLabel?: string;
headerActions?: ReactNode;
footer?: ReactNode;
onClose: () => void;
children: ReactNode;
@@ -23,6 +24,7 @@ export function ApplicationSidePanel({
title,
description,
closeLabel = "Закрыть панель",
headerActions,
footer,
onClose,
children,
@@ -42,6 +44,7 @@ export function ApplicationSidePanel({
{description ? <span className="nodedc-application-side-panel__description">{description}</span> : null}
</div>
<div className="nodedc-admin-panel__head-actions">
{headerActions}
<button type="button" className="nodedc-admin-panel__close" aria-label={closeLabel} onClick={onClose}>
<Icon name="close" size={16} strokeWidth={1.6} />
</button>
+5
View File
@@ -65,12 +65,16 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
export interface IconButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
label: string;
shape?: "circle" | "rounded";
/** Glyph-only action; keeps the normal hit target and keyboard focus. */
surface?: "default" | "none";
loading?: boolean;
}
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton({
label,
shape = "circle",
surface = "default",
style,
className,
children,
type = "button",
@@ -84,6 +88,7 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(functio
type={type}
className={cn("nodedc-icon-button", className)}
data-shape={shape === "circle" ? undefined : shape}
style={surface === "none" ? { ...style, background: "transparent", boxShadow: "none", color: "var(--nodedc-text-primary)" } : style}
aria-label={label}
title={label}
{...props}
+17 -9
View File
@@ -16,6 +16,7 @@ import {
arrayMove,
useSortable,
verticalListSortingStrategy,
rectSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { cn } from "./cn.js";
@@ -51,8 +52,9 @@ const copyRect = (rect: DragRect | null | undefined): DragRect | undefined => re
height: rect.height,
}) : undefined;
export function DragHandle({ label = "Перетащить", listeners, attributes, className }: {
export function DragHandle({ label = "Перетащить", listeners, attributes, className, surface="none" }: {
label?: string;
surface?: "none" | "control";
listeners?: ReturnType<typeof useDraggable>["listeners"];
attributes?: ReturnType<typeof useDraggable>["attributes"];
className?: string;
@@ -61,6 +63,7 @@ export function DragHandle({ label = "Перетащить", listeners, attribut
<button
type="button"
className={cn("nodedc-drag-handle", className)}
data-surface={surface}
aria-label={label}
{...attributes}
{...listeners}
@@ -120,31 +123,36 @@ export function DropZone({ id, data, className, children }: { id: string; data?:
return <div ref={setNodeRef} className={cn(className, isOver && "is-drag-over")}>{children}</div>;
}
export function SortableScope({ ids, children }: { ids: string[]; children: ReactNode }) {
return <SortableContext items={ids} strategy={verticalListSortingStrategy}>{children}</SortableContext>;
const SortableLayoutContext=createContext<"list"|"grid">("list");
export function SortableScope({ ids, children, layout="list" }: { ids: string[]; children: ReactNode; layout?:"list"|"grid" }) {
return <SortableLayoutContext.Provider value={layout}><SortableContext items={ids} strategy={layout==="grid"?rectSortingStrategy:verticalListSortingStrategy}>{children}</SortableContext></SortableLayoutContext.Provider>;
}
export function SortableItem({ id, data, className, children }: {
export function SortableItem({ id, data, className, children, handleSurface="none" }: {
id: string;
handleSurface?: "none" | "control";
data?: NodedcDragData;
className?: string;
children: (state: { handle: ReactNode; isDragging: boolean }) => ReactNode;
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, data });
const verticalTransform = transform ? { ...transform, x: 0 } : null;
const layout=useContext(SortableLayoutContext);
const verticalTransform = transform && layout!=="grid" ? { ...transform, x: 0 } : transform;
return (
<div
ref={setNodeRef}
className={cn(className, isDragging && "is-dragging")}
style={{ transform: CSS.Transform.toString(verticalTransform), transition, opacity: isDragging ? 0.65 : undefined }}
>
{children({ handle: <DragHandle listeners={listeners} attributes={attributes} />, isDragging })}
{children({ handle: <DragHandle surface={handleSurface} listeners={listeners} attributes={attributes} />, isDragging })}
</div>
);
}
export function SortableList<T>({ items, getId, className, onReorder, children }: {
export function SortableList<T>({ items, getId, className, onReorder, children, layout="list", handleSurface="none" }: {
items: T[];
handleSurface?: "none" | "control";
layout?: "list" | "grid";
getId: (item: T) => string;
className?: string;
onReorder: (items: T[]) => void;
@@ -158,10 +166,10 @@ export function SortableList<T>({ items, getId, className, onReorder, children }
const to = ids.indexOf(overId);
if (from >= 0 && to >= 0) onReorder(arrayMove(items, from, to));
}}>
<SortableScope ids={ids}>
<SortableScope ids={ids} layout={layout}>
<div className={className}>
{items.map((item) => (
<SortableItem key={getId(item)} id={getId(item)}>
<SortableItem key={getId(item)} id={getId(item)} handleSurface={handleSurface}>
{(state) => children(item, state)}
</SortableItem>
))}
+2 -1
View File
@@ -1,3 +1,4 @@
import {dragHandleFocus} from './dragHandleFocus.js';
import {useEffect,useLayoutEffect,useRef,useState,type KeyboardEvent,type PointerEvent,type ReactNode} from 'react';
import {constrainDockTree,dockIds,dockMinimum,dockRects,dockEditorTool,editorDockTarget,mergeEditorDockRatios,pruneDockTree,resizeDockSplit,type DockMinimum,type DockMove,type DockRect,type DockTree,type EditorDockState} from '@nodedc/ui-core';
import {IconButton} from './Button.js';
@@ -105,7 +106,7 @@ export function EditorDockLayout({value,onChange,primary,primaryId='viewport',pr
return <div key={tool.id} className={cn('nodedc-editor-dock__tool nodedc-glass-material nodedc-ui-root',tool.className)} data-editor-tool={tool.id} data-floating={free||undefined} data-glass-context={free?'scene':undefined} data-dock-corners={free?undefined:editorDockCorners(rect,area)} data-active={order.at(-1)===tool.id||undefined}
role="region" aria-label={tool.label} hidden={!enabled||!tool.open} style={{...rect,zIndex:moving?40:free?10+Math.max(0,order.indexOf(tool.id)):1}}
onPointerDownCapture={()=>activate(tool.id)} onFocusCapture={()=>activate(tool.id)}>
<header className="nodedc-window__head" tabIndex={0} aria-label={`Переместить · ${tool.label}`} aria-roledescription="Перемещаемая панель" onPointerDown={e=>begin(tool.id,e)} onKeyDown={e=>key(tool.id,e)}>
<header {...dragHandleFocus} className="nodedc-window__head" tabIndex={0} aria-label={`Переместить · ${tool.label}`} aria-roledescription="Перемещаемая панель" onPointerDown={e=>begin(tool.id,e)} onKeyDown={e=>key(tool.id,e)}>
<div className="nodedc-window__titles"><h2 className="nodedc-window__title">{tool.title}</h2>{tool.subtitle&&<p className="nodedc-window__subtitle">{tool.subtitle}</p>}</div>
<div className="nodedc-window__actions">{tool.actions}<IconButton label={`Закрыть · ${tool.label}`} onClick={tool.onClose}><Icon name="close"/></IconButton></div>
</header>
+23 -4
View File
@@ -1,4 +1,4 @@
import { useId, type InputHTMLAttributes, type ReactNode, type TextareaHTMLAttributes } from "react";
import { useId, useLayoutEffect, useRef, type InputHTMLAttributes, type ReactNode, type TextareaHTMLAttributes } from "react";
import { cn } from "./cn.js";
export interface FieldFrameProps {
@@ -29,6 +29,8 @@ export interface TextFieldProps extends InputHTMLAttributes<HTMLInputElement> {
hint?: string;
description?: string;
fieldClassName?: string;
/** Plain text appearance for directly editable detail content. Keep an accessible name. */
appearance?: "default" | "plain";
}
export function TextField({
@@ -36,6 +38,7 @@ export function TextField({
hint,
description,
fieldClassName,
appearance = "default",
className,
id,
...props
@@ -43,7 +46,7 @@ export function TextField({
const generatedId = useId();
const controlId = id ?? generatedId;
return (
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={fieldClassName}>
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={cn(fieldClassName, appearance === "plain" && "nodedc-field--plain", !label && "nodedc-field--unlabelled")}>
<input id={controlId} className={cn("nodedc-field__control", className)} {...props} />
</FieldFrame>
);
@@ -54,6 +57,8 @@ export interface TextAreaFieldProps extends TextareaHTMLAttributes<HTMLTextAreaE
hint?: string;
description?: string;
fieldClassName?: string;
/** Plain text appearance for directly editable detail content. Keep an accessible name. */
appearance?: "default" | "plain";
}
export function TextAreaField({
@@ -61,15 +66,29 @@ export function TextAreaField({
hint,
description,
fieldClassName,
appearance = "default",
className,
id,
...props
}: TextAreaFieldProps) {
const generatedId = useId();
const controlId = id ?? generatedId;
const area = useRef<HTMLTextAreaElement>(null);
useLayoutEffect(() => {
const el = area.current;
if (!el || appearance !== "plain") return;
const resize = () => { el.style.height = "auto"; el.style.height = el.scrollHeight + "px"; };
resize();
let width = el.clientWidth;
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
if (el.clientWidth !== width) { width = el.clientWidth; resize(); }
});
observer?.observe(el);
return () => observer?.disconnect();
}, [appearance, props.value]);
return (
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={fieldClassName}>
<textarea id={controlId} className={cn("nodedc-field__control", className)} {...props} />
<FieldFrame label={label} hint={hint} description={description} htmlFor={controlId} className={cn(fieldClassName, appearance === "plain" && "nodedc-field--plain", !label && "nodedc-field--unlabelled")}>
<textarea ref={area} id={controlId} className={cn("nodedc-field__control", className)} {...props} />
</FieldFrame>
);
}
+4
View File
@@ -43,6 +43,7 @@ import {
ListChecks,
LocateFixed,
LockKeyhole,
LockKeyholeOpen,
MailPlus,
Map,
Maximize2,
@@ -63,6 +64,7 @@ import {
ShieldCheck,
SlidersHorizontal,
Square,
Star,
Terminal,
Trash2,
UploadCloud,
@@ -136,6 +138,7 @@ const icons = {
list: ListChecks,
target: LocateFixed,
lock: LockKeyhole,
unlock: LockKeyholeOpen,
mail: MailPlus,
minimize: Minimize2,
network: Network,
@@ -154,6 +157,7 @@ const icons = {
shield: ShieldCheck,
sliders: SlidersHorizontal,
stop: Square,
star: Star,
terminal: Terminal,
trash: Trash2,
upload: UploadCloud,
+23 -2
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, type HTMLAttributes } from "react";
import { createContext, useContext, useEffect, useRef, type HTMLAttributes, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { cn } from "./cn.js";
import { Icon, type IconName } from "./Icon.js";
@@ -13,6 +13,13 @@ export type ToastItem = {
durationMs?: number | null;
};
const ToastObservation = createContext<((items: ToastItem[]) => void) | null>(null);
/** The application owns history/storage; this only reports terminal presentations. */
export function ToastObserver({onPresent, children}: {onPresent: (items: ToastItem[]) => void; children: ReactNode}) {
return <ToastObservation.Provider value={onPresent}>{children}</ToastObservation.Provider>;
}
const toastIcons: Record<ToastTone, IconName> = {
success: "check",
error: "alert",
@@ -69,7 +76,21 @@ function TimedToastCard({ item, onDismiss }: { item: ToastItem; onDismiss: (id:
return <ToastCard item={item} onDismiss={onDismiss} />;
}
export function ToastStack({ items, onDismiss }: { items: ToastItem[]; onDismiss: (id: string) => void }) {
export function ToastStack({ items, onDismiss, observe = true }: { items: ToastItem[]; onDismiss: (id: string) => void; observe?: boolean }) {
const observer = useContext(ToastObservation);
const presented = useRef(new Map<string, string>());
useEffect(() => {
const next = new Map<string, string>();
const fresh: ToastItem[] = [];
for (const item of items) {
if (item.tone === 'loading') continue;
const identity = JSON.stringify([item.tone, item.title, item.description]);
next.set(item.id, identity);
if (presented.current.get(item.id) !== identity) fresh.push(item);
}
presented.current = next;
if (observe && fresh.length) observer?.(fresh);
}, [items, observer, observe]);
if (typeof document === "undefined" || items.length === 0) return null;
return createPortal(
<div className="nodedc-toast-viewport nodedc-ui-root" aria-live="polite" aria-relevant="additions removals">
+12 -5
View File
@@ -24,6 +24,8 @@ export interface UserProfileMenuProps {
triggerLabel?: ReactNode;
/** Optional status glyph between the label and avatar. */
triggerIcon?: IconName;
/** Independent header action; the avatar still opens the profile menu. */
headerAction?: { label: string; pressed?: boolean; controls?: string; onSelect: () => void };
actions: readonly UserProfileMenuAction[];
}
@@ -35,6 +37,7 @@ export function UserProfileMenu({
coverImageUrl,
triggerLabel,
triggerIcon,
headerAction,
actions,
}: UserProfileMenuProps) {
const label = displayName || "NODE.DC";
@@ -51,11 +54,15 @@ export function UserProfileMenu({
</HeaderProfileButton>
<IconButton
ref={setTriggerRef}
label={`Меню пользователя ${label}`}
aria-haspopup="menu"
aria-expanded={open}
aria-controls={surfaceId}
onClick={(event) => { setTriggerRef(event.currentTarget); toggle(); }}
label={headerAction?.label ?? `Меню пользователя ${label}`}
aria-haspopup={headerAction ? undefined : "menu"}
aria-pressed={headerAction?.pressed}
aria-expanded={headerAction ? headerAction.pressed : open}
aria-controls={headerAction ? headerAction.controls : surfaceId}
onClick={(event) => {
if (headerAction) { if (open) toggle(); headerAction.onSelect(); }
else { setTriggerRef(event.currentTarget); toggle(); }
}}
><Icon name={triggerIcon ?? "inbox"} size={20} strokeWidth={1.7} /></IconButton>
<button type="button" className="nodedc-user-profile-menu__trigger" aria-label={`Профиль ${label}`} aria-haspopup="menu" aria-expanded={open} aria-controls={surfaceId}
onClick={(event) => { setTriggerRef(event.currentTarget); toggle(); }}>
+101 -16
View File
@@ -1,3 +1,4 @@
import {dragHandleFocus} from './dragHandleFocus.js';
import {
useCallback,
useEffect,
@@ -39,6 +40,13 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
footer?: ReactNode;
/** Context actions beside close, using canonical IconButton controls. */
headerActions?: ReactNode;
/** Keep actions on one line; place title below them when space is limited. */
headerLayout?: "inline" | "adaptive";
/** Temporarily enlarge within the viewport; restoring retains prior geometry and presentation. */
expanded?: boolean;
/** Separate durable layout for expanded media, committed only after a user gesture. */
expandedRect?: WindowRect;
onExpandedRectCommit?: (rect: WindowRect) => void;
/** Keep contextual actions immediately before close when requested. */
headerActionsPlacement?: "before-move" | "before-close";
size?: WindowSize;
@@ -58,6 +66,9 @@ export interface WindowProps extends Omit<HTMLAttributes<HTMLDivElement>, "title
onRectCommit?: (rect: WindowRect) => void;
/** Centered windows can become modeless without remounting their contents. */
allowFloating?: boolean;
/** App-owned presentation, persisted by window kind alongside rect. */
floating?: boolean;
onFloatingChange?: (floating: boolean) => void;
onClose: () => void;
}
@@ -68,6 +79,10 @@ export function Window({
children,
footer,
headerActions,
headerLayout = "inline",
expanded = false,
expandedRect,
onExpandedRectCommit,
headerActionsPlacement = "before-move",
size = "md",
placement = "center",
@@ -82,6 +97,8 @@ export function Window({
rect,
onRectCommit,
allowFloating = true,
floating: controlledFloating,
onFloatingChange,
onClose,
className,
style,
@@ -93,6 +110,10 @@ export function Window({
const titleId = useId();
const descriptionId = useId();
const dialogRef = useRef<HTMLDivElement>(null);
const minimumRef = useRef({width:320,height:200});
const [headerMinimum,setHeaderMinimum]=useState(320);
const [stackedTitle,setStackedTitle]=useState(false);
const portalHostRef = useRef<Element | null>(null);
const onCloseRef = useRef(onClose);
const dragRef = useRef<{ pointerId: number; offsetX: number; offsetY: number } | null>(null);
const [dragPosition, setDragPosition] = useState<{ left: number; top: number } | null>(null);
@@ -100,13 +121,15 @@ export function Window({
const [floatingRect, setFloatingRect] = useState<WindowRect | null>(null);
const rectRef = useRef<WindowRect | null>(null);
const initialRectRef = useRef<WindowRect | null>(null);
const expansionRestoreRef = useRef<WindowRect | null>(null);
const commitRef = useRef(onRectCommit);
commitRef.current = onRectCommit;
// Temporary media expansion never replaces the application-owned window layout.
commitRef.current = expanded ? onExpandedRectCommit : onRectCommit;
const changeRect = (next: WindowRect | null) => { rectRef.current = next; setFloatingRect(next); };
const gestureChanged = useRef(false);
const resizeRef = useRef<{ pointerId: number; x: number; y: number; rect: WindowRect; edge: ResizeEdge } | null>(null);
const isFloating = floating && allowFloating && placement === "center";
const freeGeometry = isFloating || (resizable && placement === "end");
const isFloating = (controlledFloating ?? floating) && allowFloating && placement === "center";
const freeGeometry = expanded || isFloating || (resizable && placement === "end");
const canDrag = draggable || freeGeometry;
const shouldLockBodyScroll = !suspended && !isFloating && (lockBodyScroll ?? placement === "center");
const shouldTrapFocus = !suspended && !isFloating && (trapFocus ?? placement === "center");
@@ -114,6 +137,31 @@ export function Window({
modeRef.current = { shouldTrapFocus, isFloating, suspended };
onCloseRef.current = onClose;
useLayoutEffect(()=>{
if(!open || headerLayout!=="adaptive")return;
const dialog=dialogRef.current,head=dialog?.querySelector<HTMLElement>(".nodedc-window__head"),actions=head?.querySelector<HTMLElement>(".nodedc-window__actions"),heading=head?.querySelector<HTMLElement>(".nodedc-window__title");
if(!dialog||!head||!actions||!heading)return;
const measure=()=>{
const headStyle=window.getComputedStyle(head),input=heading.querySelector<HTMLInputElement>("input"),copyStyle=window.getComputedStyle(input??heading);
const sample=document.createElement("span");
Object.assign(sample.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"pre",font:copyStyle.font,letterSpacing:copyStyle.letterSpacing});
sample.textContent=input?.value??heading.textContent??"";head.appendChild(sample);
const titleWidth=sample.getBoundingClientRect().width+(parseFloat(copyStyle.paddingLeft)||0)+(parseFloat(copyStyle.paddingRight)||0);sample.remove();
const padding=(parseFloat(headStyle.paddingLeft)||0)+(parseFloat(headStyle.paddingRight)||0),actionWidth=actions.scrollWidth;
const minimum=Math.max(320,Math.ceil(actionWidth+padding+2));
minimumRef.current={width:minimum,height:200};setHeaderMinimum(minimum);
setStackedTitle(head.clientWidth < padding+actionWidth+titleWidth+(parseFloat(headStyle.columnGap)||0)+2);
if(freeGeometry&&rectRef.current){
const fitted=fitWindow(rectRef.current,{width:window.innerWidth,height:window.innerHeight},minimumRef.current);
if(fitted.left!==rectRef.current.left||fitted.top!==rectRef.current.top||fitted.width!==rectRef.current.width||fitted.height!==rectRef.current.height){changeRect(fitted);if(!resizeRef.current&&!dragRef.current)commitRef.current?.(fitted);}
}
};
measure();
const observer=typeof ResizeObserver!=="undefined"?new ResizeObserver(measure):null;
observer?.observe(head);observer?.observe(actions);window.addEventListener("resize",measure);
return()=>{observer?.disconnect();window.removeEventListener("resize",measure);};
},[open,headerLayout,title,headerActions,freeGeometry]);
useEffect(() => {
if (!open || typeof document === "undefined") return;
const previousActiveElement = document.activeElement instanceof HTMLElement ? document.activeElement : null;
@@ -133,13 +181,17 @@ export function Window({
const topModal = Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"][aria-modal="true"]')).filter(dialog => dialog.getClientRects().length > 0).at(-1);
if (topModal && topModal !== dialogRef.current) return;
}
const ownedFullscreen = document.fullscreenElement && dialogRef.current?.contains(document.fullscreenElement);
// Escape restores the embedded viewport, never closes its owning form.
if (event.key === "Escape" && ownedFullscreen) return;
if (event.key === "Escape" && closeOnEscape && (!modeRef.current.isFloating || dialogRef.current?.contains(document.activeElement))) {
event.preventDefault();
onCloseRef.current();
return;
}
if (event.key !== "Tab" || !modeRef.current.shouldTrapFocus || !dialogRef.current) return;
const focusable = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(focusableSelector)).filter(element => element.getClientRects().length > 0);
const focusScope = ownedFullscreen ? document.fullscreenElement! : dialogRef.current;
const focusable = Array.from(focusScope.querySelectorAll<HTMLElement>(focusableSelector)).filter(element => element.getClientRects().length > 0);
if (focusable.length === 0) {
event.preventDefault();
dialogRef.current.focus();
@@ -172,20 +224,39 @@ export function Window({
}, [open, shouldLockBodyScroll]);
useLayoutEffect(() => {
if (open && freeGeometry && !dragRef.current && !resizeRef.current) {
if (!open) return;
const viewport={width:window.innerWidth,height:window.innerHeight};
if(expanded){
if(!expansionRestoreRef.current){
const bounds=dialogRef.current?.getBoundingClientRect();
if(bounds){
expansionRestoreRef.current=rectRef.current??{left:bounds.left,top:bounds.top,width:bounds.width,height:bounds.height};
const width=Math.min(960,viewport.width*0.8),height=Math.min(800,viewport.height*0.82);
const prior=expansionRestoreRef.current;
changeRect(fitWindow(expandedRect??{left:prior.left+(prior.width-width)/2,top:prior.top+(prior.height-height)/2,width,height},viewport,minimumRef.current));
}
}
return;
}
if(expansionRestoreRef.current){
changeRect(fitWindow(expansionRestoreRef.current,viewport,minimumRef.current));
expansionRestoreRef.current=null;
return;
}
if (freeGeometry && !dragRef.current && !resizeRef.current) {
// The modal move toggle already restores its local rectangle. An
// uncontrolled floating window must retain it when toggled twice.
if (placement === "center" && !onRectCommit && !rect && rectRef.current) return;
const bounds=dialogRef.current?.getBoundingClientRect();
if(bounds){
initialRectRef.current ??= initialRect??{left:bounds.left,top:bounds.top,width:bounds.width,height:bounds.height};
changeRect(fitWindow(rect??initialRectRef.current,{width:window.innerWidth,height:window.innerHeight}));
changeRect(fitWindow(rect??initialRectRef.current,{width:window.innerWidth,height:window.innerHeight},minimumRef.current));
}
}
},[open,freeGeometry,rect?.left,rect?.top,rect?.width,rect?.height]);
},[open,expanded,freeGeometry,rect?.left,rect?.top,rect?.width,rect?.height]);
useEffect(() => {
if (!open) { setDragPosition(null); setFloating(false); changeRect(null); initialRectRef.current = null; dragRef.current = null; resizeRef.current = null; }
if (!open) { setDragPosition(null); setFloating(false); changeRect(null); initialRectRef.current = null; expansionRestoreRef.current = null; dragRef.current = null; resizeRef.current = null; }
}, [open]);
useEffect(() => {
@@ -194,7 +265,7 @@ export function Window({
const resizing = resizeRef.current;
if (resizing && event.pointerId === resizing.pointerId) {
gestureChanged.current = true;
changeRect(resizeWindow(resizing.rect, resizing.edge, event.clientX - resizing.x, event.clientY - resizing.y, { width: window.innerWidth, height: window.innerHeight }));
changeRect(resizeWindow(resizing.rect, resizing.edge, event.clientX - resizing.x, event.clientY - resizing.y, { width: window.innerWidth, height: window.innerHeight },minimumRef.current));
return;
}
const drag = dragRef.current;
@@ -203,7 +274,7 @@ export function Window({
const bounds = dialog.getBoundingClientRect();
if (freeGeometry) {
gestureChanged.current = true;
changeRect(fitWindow({ left: event.clientX - drag.offsetX, top: event.clientY - drag.offsetY, width: bounds.width, height: bounds.height }, { width: window.innerWidth, height: window.innerHeight }));
changeRect(fitWindow({ left: event.clientX - drag.offsetX, top: event.clientY - drag.offsetY, width: bounds.width, height: bounds.height }, { width: window.innerWidth, height: window.innerHeight },minimumRef.current));
return;
}
const left = Math.max(8, Math.min(window.innerWidth - bounds.width - 8, event.clientX - drag.offsetX));
@@ -228,10 +299,10 @@ export function Window({
useEffect(() => {
if (!freeGeometry || !open) return;
const fit = () => { if(rectRef.current) changeRect(fitWindow(rect ?? rectRef.current, { width: window.innerWidth, height: window.innerHeight })); };
const fit = () => { if(rectRef.current) changeRect(fitWindow((expanded ? expandedRect : rect) ?? rectRef.current, { width: window.innerWidth, height: window.innerHeight },minimumRef.current)); };
window.addEventListener("resize", fit);
return () => window.removeEventListener("resize", fit);
}, [freeGeometry, open, rect]);
}, [freeGeometry, open, rect, expanded, expandedRect]);
if (!open || typeof document === "undefined") return null;
@@ -241,13 +312,24 @@ export function Window({
if (allowBackdropClose && event.target === event.currentTarget) onClose();
};
// Keep an owning window in its existing portal while its child is fullscreen.
// Reparenting it into that child would form a DOM cycle and remount the renderer.
const fullscreen = document.fullscreenElement;
if (!portalHostRef.current || !fullscreen || !dialogRef.current?.contains(fullscreen)) {
portalHostRef.current = fullscreen ?? document.body;
}
const baseStyle={...style,...(headerLayout==="adaptive"?{minWidth:Math.min(headerMinimum,Math.max(1,window.innerWidth-16))}:{})};
return createPortal(
<LoadingContext.Provider value={null}><InspectorSelectPolicyContext.Provider value={false}>
<WindowSuspensionContext.Provider value={suspend}><div className="nodedc-overlay nodedc-ui-root" style={suspended ? {display:"none"} : undefined} data-placement={placement} data-floating={isFloating || undefined} onPointerDown={handleBackdropPointerDown}>
<div
ref={dialogRef}
className={cn("nodedc-window nodedc-glass-material nodedc-material-rim", className)}
data-expanded={expanded||undefined}
data-header-layout={headerLayout}
data-header-stacked={stackedTitle||undefined}
data-material="glass-v4"
data-glass-context={isFloating ? "scene" : undefined}
data-size={size === "md" ? undefined : size}
data-placement={placement}
data-draggable={canDrag ? "true" : undefined}
@@ -258,10 +340,11 @@ export function Window({
aria-labelledby={titleId}
aria-describedby={subtitle ? descriptionId : undefined}
tabIndex={-1}
style={freeGeometry && floatingRect ? { ...style, position: "fixed", ...floatingRect, right: "auto", bottom: "auto", maxWidth: "none", maxHeight: "none" } : dragPosition ? { ...style, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : style}
style={freeGeometry && floatingRect ? { ...baseStyle, position: "fixed", ...floatingRect, right: "auto", bottom: "auto", maxWidth: "none", maxHeight: "none" } : dragPosition ? { ...baseStyle, position: "fixed", left: dragPosition.left, top: dragPosition.top, right: "auto", bottom: "auto" } : baseStyle}
{...props}
>
<header
{...dragHandleFocus}
className="nodedc-window__head"
tabIndex={freeGeometry ? 0 : undefined}
aria-label={freeGeometry ? "Перемещение окна: стрелки; изменение размера: Shift и стрелки" : undefined}
@@ -271,7 +354,7 @@ export function Window({
const dx = event.key === "ArrowLeft" ? -10 : event.key === "ArrowRight" ? 10 : 0;
const dy = event.key === "ArrowUp" ? -10 : event.key === "ArrowDown" ? 10 : 0;
const bounds = { width: window.innerWidth, height: window.innerHeight };
const next = event.shiftKey ? resizeWindow(floatingRect, "se", dx, dy, bounds) : fitWindow({ ...floatingRect, left: floatingRect.left + dx, top: floatingRect.top + dy }, bounds);
const next = event.shiftKey ? resizeWindow(floatingRect, "se", dx, dy, bounds,minimumRef.current) : fitWindow({ ...floatingRect, left: floatingRect.left + dx, top: floatingRect.top + dy }, bounds,minimumRef.current);
changeRect(next); commitRef.current?.(next);
}}
onPointerDown={(event) => {
@@ -294,9 +377,11 @@ export function Window({
dragRef.current = null; resizeRef.current = null;
if (!isFloating) {
const rect = dialogRef.current?.getBoundingClientRect();
if (rect) changeRect(fitWindow(rectRef.current ?? { left: rect.left, top: rect.top, width: rect.width, height: rect.height }, { width: window.innerWidth, height: window.innerHeight }));
if (rect) changeRect(fitWindow(rectRef.current ?? { left: rect.left, top: rect.top, width: rect.width, height: rect.height }, { width: window.innerWidth, height: window.innerHeight },minimumRef.current));
}
if (rectRef.current) commitRef.current?.({...rectRef.current});
setFloating(!isFloating);
onFloatingChange?.(!isFloating);
}}><Icon name="move" /></IconButton>}
{headerActionsPlacement === "before-close" && headerActions}
<button type="button" className="nodedc-window__close" aria-label={closeLabel} onClick={onClose}>
@@ -316,7 +401,7 @@ export function Window({
</div>
</div>
</WindowSuspensionContext.Provider></InspectorSelectPolicyContext.Provider></LoadingContext.Provider>,
document.fullscreenElement ?? document.body,
portalHostRef.current,
);
}
@@ -1,3 +1,4 @@
import {dragHandleFocus} from './dragHandleFocus.js';
import {
useEffect,
useId,
@@ -397,6 +398,7 @@ export function WorkspaceWindow({
}}
>
<header
{...dragHandleFocus}
ref={headRef}
className="nodedc-workspace-window__head"
tabIndex={maximized ? -1 : 0}
+15
View File
@@ -0,0 +1,15 @@
import type {FocusEvent, KeyboardEvent, PointerEvent} from 'react';
/** A pointer grab must not inherit the previous input's keyboard focus ring. */
export const dragHandleFocus = {
onPointerDownCapture(event: PointerEvent<HTMLElement>) {
if (event.button !== 0 || (event.target as HTMLElement).closest('button,input,select,textarea,a,[role=slider]')) return;
event.currentTarget.dataset.pointerFocus = 'true';
},
onKeyDownCapture(event: KeyboardEvent<HTMLElement>) {
if (event.target === event.currentTarget) delete event.currentTarget.dataset.pointerFocus;
},
onBlur(event: FocusEvent<HTMLElement>) {
if (event.target === event.currentTarget) delete event.currentTarget.dataset.pointerFocus;
},
};
+28 -11
View File
@@ -176,6 +176,7 @@
],
"rules": [
"Icon-only actions are circular by default.",
"IconButton surface=none keeps the normal hit target and focus while removing the disc. Favorite stars use outline/filled glyph states; see docs/FAVORITES.md.",
"Groups over rendered imagery use nodedc-scene-controls: Button, IconButton, Select and SegmentedControl share the opaque field surface and interaction states; all viewport controls use the same 70-percent geometry, and rails must not inherit the translucent header background.",
"Controlled toggle actions expose aria-pressed and use the canonical active surface without changing geometry.",
"Filled accent actions derive foreground contrast from the actual accent.",
@@ -256,7 +257,8 @@
"Labels and validation copy are part of the field contract.",
"Keyboard focus changes the surface and remains visible without a browser-blue outline.",
"Browser autofill retains the canonical field material, text and caret; keyboard focus remains visible.",
"FieldFrame labelPlacement=below is the compact muted caption variant for header selectors; above remains the default."
"FieldFrame labelPlacement=below is the compact muted caption variant for header selectors; above remains the default.",
"appearance=plain renders immediately editable detail copy without a permanent plate; empty labels require aria-label, textarea grows to content, keyboard focus remains visible."
]
},
{
@@ -356,12 +358,14 @@
],
"domContract": [
"nodedc-dropdown-surface",
"nodedc-dropdown-option"
"nodedc-dropdown-option",
"nodedc-viewport-surface"
],
"summary": "Shared portal/fixed floating layer for action and selection menus.",
"behavior": [
"portal to active fullscreen element or document body",
"viewport clamp",
"scene Glass V4 via surfaceClassName nodedc-viewport-surface",
"content resize repositions an open dropdown within viewport bounds",
"vertical flip",
"capture-phase outside pointer close before scene tool interception",
@@ -448,6 +452,7 @@
"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.",
"An embedded fullscreen viewport keeps its owning window mounted at the existing portal host; Escape restores the viewport and Tab stays inside its visible controls.",
"DOM modal resizing shares eight canonical edge handles, centered viewport bounds and keyboard Shift+arrow control; onSizeCommit runs only for completed user changes."
],
"rules": [
@@ -460,12 +465,16 @@
"A draggable inspector moves by its header and remains clamped to the viewport.",
"Closing a modeless inspector is never gated by autosave; preserve the draft, close immediately and report persistence failure through ToastStack.",
"Operational copy inside Window uses component typography tokens; browser-default paragraph or heading sizes are forbidden.",
"Centered windows expose the move toggle by default; allowFloating opts a workflow out. Returning to modal restores canonical centered geometry; closing clears floating geometry.",
"Centered windows expose the move toggle by default; allowFloating opts a workflow out. Returning to modal restores canonical centered geometry; uncontrolled windows clear floating geometry on close.",
"Floating header supports arrow-key movement and Shift+arrow resizing. Bounds stay inside the viewport. Resize affordances have no hover decoration.",
"Inspectors inside a Window use its full available content width.",
"End inspectors opt into resizable with an optional initialRect; existing eight edge geometry and keyboard resize are shared with floating windows.",
"Application-owned rect restores modeless window geometry on reopen and external undo/import. onRectCommit reports one completed drag/resize or keyboard step; viewport fitting never overwrites saved geometry.",
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions."
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions.",
"Drag headers never draw perimeter outlines or inherit keyboard-focus fill on pointer grab. Keyboard focus remains visible through the canonical surface; arrows, Shift+arrows and docking shortcuts remain available.",
"Detached center windows automatically use scene Glass V4; fixed confirmations opt out of detachment with allowFloating=false. Unsaved profile confirmation is owned by the application.",
"floating/onFloatingChange and rect/onRectCommit allow durable application-owned presentation by window kind, independent of the currently displayed entity. Reopening restores mode and fitted geometry. Fixed confirmations do not inherit this state.",
"Adaptive headers keep actions on one row, place the full title below before clipping, and derive the resize minimum from actual actions. Expanded media opens at a moderate size and remains resizable. Separate expandedRect/onExpandedRectCommit preferences restore its user-chosen position and dimensions; returning restores regular geometry."
]
},
{
@@ -504,7 +513,8 @@
"resizeIndicator=false hides only the corner glyph; pointer hit area, cursor and keyboard resizing remain available.",
"Use WorkspaceWindow for auxiliary views inside a stage; modal workflows and viewport inspectors continue to use Window.",
"Dragging and resizing remain clamped when the workspace changes size, including when it becomes smaller than the requested minimum.",
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions."
"Enforced operational typography: independent md/13px base for UI roots and portals; section/value text md, Description/status/error copy sm/12px, only canonical page/window titles use title/18px. Shared build-time typography contract and catalog example prevent browser-default size regressions.",
"Drag headers never draw perimeter outlines or inherit keyboard-focus fill on pointer grab. Keyboard focus remains visible through the canonical surface; arrows, Shift+arrows and docking shortcuts remain available."
]
},
{
@@ -698,6 +708,7 @@
"behavior": [
"portal dropdown",
"profile identity card",
"optional pressed state and controlled region on independent header action; its selected circle and glyph use the active IconButton colors, including on hover",
"theme-independent cover",
"action links and callbacks",
"outside pointer and Escape close",
@@ -707,7 +718,8 @@
"The component owns menu geometry and profile presentation; the application owns settings, profile and logout actions.",
"Use the existing Dropdown engine so the menu is never clipped by the fixed application header.",
"Do not embed product permissions or sharing rules in the visual menu.",
"The default header composes HeaderProfileButton, an independent menu IconButton and HeaderAvatar using the existing header geometry. Application settings belong inside this menu; do not add an adjacent settings button or another HeaderProfile wrapper."
"The default header composes HeaderProfileButton, an independent menu IconButton and HeaderAvatar using the existing header geometry. Application settings belong inside this menu; do not add an adjacent settings button or another HeaderProfile wrapper.",
"Optional headerAction separates the middle icon action from the avatar/profile trigger; without it legacy behavior is preserved."
]
},
{
@@ -898,7 +910,7 @@
"nodedc-application-side-panel",
"nodedc-app-shell__end-panel"
],
"summary": "Theme-aware trailing application panel paired with AdminNavigationPanel and hosted in a separate ApplicationShell end column.",
"summary": "Theme-aware trailing application panel with optional header actions before close, hosted in a separate ApplicationShell end column.",
"anatomy": [
"eyebrow and title",
"optional description",
@@ -1003,7 +1015,8 @@
"ToastCard",
"ToastStack",
"ToastItem",
"ToastTone"
"ToastTone",
"ToastObserver"
],
"domContract": [
"nodedc-toast-viewport",
@@ -1031,7 +1044,8 @@
"Errors and status copy use the compact Toast typography; consumers do not substitute browser-default paragraphs or title-sized text.",
"Adding or updating another notification never restarts the lifetime of an existing item; each item owns its timer by stable id.",
"Loading notifications remain until the operation updates or dismisses them.",
"Status notifications never replace a blocking confirmation modal."
"Status notifications never replace a blocking confirmation modal.",
"ToastObserver reports new or changed terminal presentations to the consumer; storage and history belong to the application. Set observe=false for server-originated items already recorded in history."
]
},
{
@@ -1119,7 +1133,9 @@
"A reordered application page array is the single source of truth for both composition and navigation order.",
"Optional renderOverlay portals the drag preview above scroll clipping without moving source layout; cancellation clears it.",
"Pointer drops report client coordinates for consumer-owned canvas hit testing; dropping on empty space never implies an object target.",
"DraggableItem exposes activator attributes/listeners for whole-tile dragging without a separate handle; the same activation threshold distinguishes clicks from drags."
"DraggableItem exposes activator attributes/listeners for whole-tile dragging without a separate handle; the same activation threshold distinguishes clicks from drags.",
"SortableList/SortableScope layout=grid uses rectangular sorting and two-axis movement with the same handle-only interaction; list remains vertical by default.",
"DragHandle surface=control and SortableList handleSurface=control put the grip in a visible circle; viewport contexts use the shared glass material."
]
},
{
@@ -1422,7 +1438,8 @@
"The fixed editor header is outside docking bounds. Back, edit completion and close return to the original view.",
"When opened inside Window, the editor suspends that overlay, backdrop and focus trap without unmounting; returning restores the same window.",
"EditorWorkspace purpose=view uses the same mounted host, return/fullscreen behavior and optional fixed headerActions; purpose=edit remains the compatible default.",
"Tool minimumSize applies to floating restore, pointer and keyboard resize as well as docked splits; small screens clamp to available space. Footer remains outside the body scroller."
"Tool minimumSize applies to floating restore, pointer and keyboard resize as well as docked splits; small screens clamp to available space. Footer remains outside the body scroller.",
"Drag headers never draw perimeter outlines or inherit keyboard-focus fill on pointer grab. Keyboard focus remains visible through the canonical surface; arrows, Shift+arrows and docking shortcuts remain available."
]
},
{
+3 -1
View File
@@ -102,11 +102,13 @@
"info-plain",
"activity",
"lock",
"unlock",
"key",
"shield",
"circle",
"eye",
"eye-off"
"eye-off",
"star"
]
},
{