From 59411f4937326a2394825c61d98e4c55dcea35af Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 11 Nov 2026 23:53:26 +0300 Subject: [PATCH] feat(ui): add accessible tooltips and enforce compact operational typography --- AGENTS.md | 5 + apps/catalog/package.json | 3 +- apps/catalog/src/CatalogApp.tsx | 10 ++ .../catalog/src/OperationalTypographyDemo.tsx | 20 +++ docs/COMPONENTS.md | 10 ++ docs/GOVERNANCE.md | 3 + docs/OPERATIONAL_TYPOGRAPHY.md | 35 ++++ docs/WINDOWS_AND_LAYERS.md | 3 + package.json | 6 +- packages/ui-core/package.json | 9 +- packages/ui-core/styles.css | 55 +++++-- packages/ui-core/typography.mjs | 46 ++++++ packages/ui-react/src/Tooltip.tsx | 69 ++++++++ packages/ui-react/src/index.ts | 2 + registry/candidates.json | 155 ++++++++++++++---- registry/components.json | 40 ++++- scripts/operational-typography.test.mjs | 41 +++++ scripts/typography-policy.json | 59 +++++++ 18 files changed, 514 insertions(+), 57 deletions(-) create mode 100644 apps/catalog/src/OperationalTypographyDemo.tsx create mode 100644 packages/ui-core/typography.mjs create mode 100644 packages/ui-react/src/Tooltip.tsx create mode 100644 scripts/operational-typography.test.mjs create mode 100644 scripts/typography-policy.json diff --git a/AGENTS.md b/AGENTS.md index bf3fa69..37c6199 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,3 +37,8 @@ All subagent work in this repository follows deploy, install dependencies or expand their own scope. - Do not invent per-agent token measurements. Report measured usage only when the product exposes it; otherwise report model, task, state, turns and outcome. + + +## Enforced compact typography + +Operational values/section headings use md (13 px), explanatory/status/error copy uses Description/sm (12 px). Only canonical window/page title roles use title (18 px). Do not add browser-default paragraphs, local larger sizes, font shorthand or inline fontSize. Typography checks are mandatory build gates; never extend the frozen compact legacy baseline or generalize scene/display exceptions to satisfy a feature. Run the typography contract tests and verify computed sizes in centered/floating and narrow windows. See Design Guideline docs/OPERATIONAL_TYPOGRAPHY.md. diff --git a/apps/catalog/package.json b/apps/catalog/package.json index 0eb2686..f9fa417 100644 --- a/apps/catalog/package.json +++ b/apps/catalog/package.json @@ -6,7 +6,8 @@ "scripts": { "dev": "vite --host 127.0.0.1", "build": "tsc -b && vite build", - "typecheck": "tsc -b --pretty false" + "typecheck": "tsc -b --pretty false", + "prebuild": "node --test ../../scripts/operational-typography.test.mjs" }, "dependencies": { "@nodedc/page-patterns": "0.1.0", diff --git a/apps/catalog/src/CatalogApp.tsx b/apps/catalog/src/CatalogApp.tsx index 77117d3..4016abe 100644 --- a/apps/catalog/src/CatalogApp.tsx +++ b/apps/catalog/src/CatalogApp.tsx @@ -1,9 +1,11 @@ +import { OperationalTypographyDemo } from "./OperationalTypographyDemo"; 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"; import {EditorDockExample} from './EditorDockExample'; import { ActivityIndicator, + Tooltip, LoadingRegion, Description, ComparisonTable, @@ -1467,6 +1469,13 @@ export function CatalogApp() { S + +
+ + Нормальный уровень + +
+
@@ -1528,6 +1537,7 @@ export function CatalogApp() { + diff --git a/apps/catalog/src/OperationalTypographyDemo.tsx b/apps/catalog/src/OperationalTypographyDemo.tsx new file mode 100644 index 0000000..f918c9f --- /dev/null +++ b/apps/catalog/src/OperationalTypographyDemo.tsx @@ -0,0 +1,20 @@ +import { useState } from "react"; +import { Button, Description, SettingsCard, Window, WindowFooterActions } from "@nodedc/ui-react"; + +/** Catalog-only sample: verify host-size independence and centered/floating status copy. */ +export function OperationalTypographyDemo() { + const [open, setOpen] = useState(false); + return <> + +

Подключение

+
192.168.1.1
+ Нет сведений о подключении. + Не удалось получить ответ устройства. + +
+ setOpen(false)} + footer={}> + Связь прервалась после приёма команды. Проверьте, выключился ли борт. + + ; +} diff --git a/docs/COMPONENTS.md b/docs/COMPONENTS.md index 35f763c..b5984d9 100644 --- a/docs/COMPONENTS.md +++ b/docs/COMPONENTS.md @@ -529,3 +529,13 @@ Window: `rect` / `onRectCommit` — восстановление и фиксац `--nodedc-description-font-size`; по умолчанию используется `--nodedc-font-size-sm`. Window header actions default to before the move toggle. `headerActionsPlacement="before-close"` places supplied canonical IconButtons between move and close, preserving DOM/Tab order. Deletion confirmation remains application-owned content in the same mounted Window. + + +## Tooltip + +Нейтральная подсказка с `content`, `children`, необязательными `label`, `focusable`, `disabled` и `placement`. Оборачивает триггер; `focusable` делает читаемую графику доступной клавиатуре, обычная кнопка сохраняет собственный фокус. Hover, focus и touch показывают один общий portal над окном; Escape закрывает подсказку, не родительское окно. Можно перевести курсор в подсказку. Позиция пересчитывается при scroll/resize, с общим clamp/flip. Не содержит действий: для меню используется Dropdown. Нет рамки, акцентных цветов или анимации при reduced motion. + +Принят для запрошенных владельцем пояснений шкал сигнала,10.11.2026; приложение владеет диапазонами и текстом, общий компонент — формой и взаимодействием. + + +Window, WorkspaceWindow, ApplicationPanel and AdminPanel establish an independent compact md text base, including portals. Native semantic headings inside operational surfaces use md unless an explicit canonical title rule applies. Use Description for result/error/pending paragraphs. The living catalog includes a typography example with values, nested headings and a status dialog. See OPERATIONAL_TYPOGRAPHY.md and the exported build-time `@nodedc/ui-core/typography` contract. diff --git a/docs/GOVERNANCE.md b/docs/GOVERNANCE.md index 018f723..13757c0 100644 --- a/docs/GOVERNANCE.md +++ b/docs/GOVERNANCE.md @@ -59,3 +59,6 @@ ## Владение У дизайн-системы должен быть явный code owner. Product team может предлагать компоненты, но общий API и theme contract проходят отдельное review, потому что изменение распространяется на все будущие приложения. + + +Typography is a build gate, not a recommendation. See `OPERATIONAL_TYPOGRAPHY.md`: operational values/sections 13 px, descriptions/status/error copy 12 px, canonical window/page titles 18 px. Browser defaults, new local sizes and inline font overrides fail validation. The frozen compact legacy list cannot be expanded for new UI; exceptions require an explicit owner decision. diff --git a/docs/OPERATIONAL_TYPOGRAPHY.md b/docs/OPERATIONAL_TYPOGRAPHY.md index 5c0c9fc..809f2d3 100644 --- a/docs/OPERATIONAL_TYPOGRAPHY.md +++ b/docs/OPERATIONAL_TYPOGRAPHY.md @@ -29,3 +29,38 @@ Explanatory paragraphs use `Description`, the same contract as `SettingsCard.des пояснения вне карточки также используют `Description` с `role="status"`, если нужно объявление для скринридера. Заголовки, значения полей и кнопки сохраняют собственную типографику; глобальный стиль для всех `p` страницы не вводится. + + +## Обязательная проверка сборки — 10.11.2026 + +Операционный UI имеет собственный базовый `md` (13 px), в том числе портальные +`Window`, `WorkspaceWindow`, `ApplicationPanel` и `AdminPanel`. Размер body +внешнего приложения не является контрактом. Корневой размер `html` не меняется: +rem и пользовательское масштабирование остаются доступными. Семантические +h1–h6 внутри этих поверхностей по умолчанию используют md, а явные канонические +заголовки страницы/окна — title (18 px). Значения и заголовки секций — md; +пояснения, ошибки, ожидание и результат команды — `Description` / sm (12 px). + +Правило исполняется модулем `@nodedc/ui-core/typography` и обязательным +`npm run test:typography` Design Guideline. Mission Core запускает +`check:typography` перед сборкой Control Station и Node UI, а также в полном +наборе unit-тестов. Проверяется исходный код всех экранов, общих пакетов и +frontend-плагинов, а не только последний изменённый компонент. + +Проверка запрещает новые локальные размеры вместо токенов, lg/title для данных, +увеличивающие calc/clamp/em, font shorthand, inline fontSize и обычные p без +явного класса. Сохранившиеся компактные значения старого UI (не более 13 px) +зафиксированы по файлу, селектору и значению в `typography-policy.json`; +добавлять туда новый UI запрещено. При изменении такого правила его переводят +на токен, запись удаляют. Список не допускает крупных значений даже при ошибочном +добавлении. Исключения перечислены отдельно с причиной и точным выражением: +существующая обложка LandingStage, подписи в координатах SVG и управляемый +пользователем масштаб сцены. Они не разрешают увеличивать текст рабочих панелей. +Начальный размер значений батареи — 13 px; сохранённый пользователем масштаб +3D-сцены не перезаписывается. + +Изменение шкалы токенов, списка ролей или исключений требует явного решения +владельца продукта и обновления живого каталога. Нельзя ослаблять проверку ради +одного экрана, закрывать проблему локальным font-size или менять масштаб html. +При приёмке проверяют computed font-size в обычном и плавающем окне, на узкой +ширине, а также ожидание, ошибку, пустое состояние и результат команды. diff --git a/docs/WINDOWS_AND_LAYERS.md b/docs/WINDOWS_AND_LAYERS.md index 8d713cd..5ad991c 100644 --- a/docs/WINDOWS_AND_LAYERS.md +++ b/docs/WINDOWS_AND_LAYERS.md @@ -156,3 +156,6 @@ When an EditorWorkspace detaches from a Window, the owning overlay is suspended without unmounting its children. Its backdrop and focus trap are inactive until the editor returns. Escape/Tab belong to the focused dialog, so nested settings close without also closing the battery/detail window. + + +Portal typography is self-contained: Window text base is md/13 px, its title is title/18 px, and explanatory/status paragraphs use Description/sm/12 px. This stays identical in centered and floating modes and is independent of the host body size. diff --git a/package.json b/package.json index 4cf2517..420fcc1 100644 --- a/package.json +++ b/package.json @@ -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 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", + "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", "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", @@ -45,7 +45,9 @@ "test:analysis-controls": "node --test scripts/analysis-controls.test.mjs", "test:settings-surfaces": "node --test scripts/settings-surfaces.test.mjs", "test:window-geometry": "node --test scripts/window-geometry.test.mjs", - "test:editor-dock": "node --test scripts/editor-dock.test.mjs" + "test:editor-dock": "node --test scripts/editor-dock.test.mjs", + "test:typography": "node --test scripts/operational-typography.test.mjs", + "prebuild": "npm run test:typography" }, "engines": { "node": ">=20" diff --git a/packages/ui-core/package.json b/packages/ui-core/package.json index 8dc4307..461c4a6 100644 --- a/packages/ui-core/package.json +++ b/packages/ui-core/package.json @@ -4,7 +4,8 @@ "type": "module", "files": [ "dist", - "styles.css" + "styles.css", + "typography.mjs" ], "main": "./dist/index.js", "types": "./dist/index.d.ts", @@ -13,11 +14,13 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, - "./styles.css": "./styles.css" + "./styles.css": "./styles.css", + "./typography": "./typography.mjs" }, "scripts": { "build": "tsc -p tsconfig.json", - "typecheck": "tsc -p tsconfig.json --noEmit" + "typecheck": "tsc -p tsconfig.json --noEmit", + "prebuild": "node --test ../../scripts/operational-typography.test.mjs" }, "dependencies": { "@nodedc/tokens": "0.6.0" diff --git a/packages/ui-core/styles.css b/packages/ui-core/styles.css index 0476e1c..c1801f9 100644 --- a/packages/ui-core/styles.css +++ b/packages/ui-core/styles.css @@ -1,7 +1,7 @@ @import "@nodedc/tokens/tokens.css"; @import "@nodedc/tokens/themes.css"; -:where([data-nodedc-ui], .nodedc-ui-root) { +:where([data-nodedc-ui], .nodedc-ui-root, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) { color: var(--nodedc-text-primary); font-family: var(--nodedc-font-family); font-synthesis: none; @@ -9,6 +9,18 @@ -webkit-font-smoothing: antialiased; } +/* Theme attributes may live on html. Set the text base on body instead, so + rem tokens and user zoom never get multiplied by the operational base. */ +:where([data-nodedc-ui]:not(html), .nodedc-ui-root:not(html), html[data-nodedc-ui] > body, html.nodedc-ui-root > body, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) { + font-size: var(--nodedc-font-size-md); +} + +/* Semantic headings inside operational surfaces do not inherit browser h1–h6 scaling. + Explicit canonical window/page titles retain their title token. */ +:where([data-nodedc-ui], .nodedc-ui-root, .nodedc-window, .nodedc-workspace-window, .nodedc-application-panel, .nodedc-admin-panel) :where(h1, h2, h3, h4, h5, h6) { + font-size: var(--nodedc-font-size-md); +} + :where([data-nodedc-ui], .nodedc-ui-root) *, :where([data-nodedc-ui], .nodedc-ui-root) *::before, :where([data-nodedc-ui], .nodedc-ui-root) *::after { @@ -1431,7 +1443,7 @@ textarea.nodedc-field__control { .nodedc-user-profile-card__cover strong { margin-top: 0.25rem; - font-size: 0.92rem; + font-size: var(--nodedc-font-size-md); } .nodedc-user-profile-card__cover > span:not(.nodedc-header__avatar) { @@ -1458,7 +1470,7 @@ textarea.nodedc-field__control { text-align: left; text-decoration: none; font: inherit; - font-size: 0.82rem; + font-size: var(--nodedc-font-size-md); font-weight: 700; cursor: pointer; } @@ -1703,7 +1715,7 @@ textarea.nodedc-field__control { } .nodedc-application-panel__titles h1 { - font-size: 1.15rem; + font-size: var(--nodedc-font-size-title); font-weight: 780; line-height: 1.15; } @@ -1711,7 +1723,7 @@ textarea.nodedc-field__control { .nodedc-application-panel__titles p { max-width: 42rem; color: var(--nodedc-text-muted); - font-size: 0.75rem; + font-size: var(--nodedc-font-size-sm); line-height: 1.35; } @@ -1847,7 +1859,7 @@ textarea.nodedc-field__control { .nodedc-admin-panel__head p { color: var(--nodedc-text-muted); - font-size: 0.68rem; + font-size: var(--nodedc-font-size-sm); font-weight: 850; letter-spacing: 0.04em; text-transform: uppercase; @@ -1855,7 +1867,7 @@ textarea.nodedc-field__control { .nodedc-admin-panel__head h2 { margin-top: 0.55rem; - font-size: 1.15rem; + font-size: var(--nodedc-font-size-title); font-weight: 780; line-height: 1.1; } @@ -2008,7 +2020,7 @@ textarea.nodedc-field__control { } .nodedc-admin-context__body strong { - font-size: 0.92rem; + font-size: var(--nodedc-font-size-md); font-weight: 800; } @@ -2047,7 +2059,7 @@ textarea.nodedc-field__control { color: var(--nodedc-text-secondary); padding: 5px 0.9rem 5px calc(5px + 2.92rem + 0.86rem); font: inherit; - font-size: 0.91rem; + font-size: var(--nodedc-font-size-md); font-weight: 570; text-align: left; opacity: 0.66; @@ -4099,7 +4111,7 @@ textarea.nodedc-field__control { max-width: 34rem; margin: 0; color: var(--nodedc-text-secondary); - font-size: clamp(0.8rem, 1vw, 1rem); + font-size: var(--nodedc-font-size-sm); line-height: 1.6; } @@ -4134,7 +4146,7 @@ textarea.nodedc-field__control { .nodedc-landing-stage__status p { margin: 0.15rem 0 0; color: var(--nodedc-text-muted); - font-size: 0.66rem; + font-size: var(--nodedc-font-size-sm); line-height: 1.45; } @@ -4241,7 +4253,7 @@ textarea.nodedc-field__control { .nodedc-environment-media-playlist__error { margin: 0; color: var(--nodedc-text-muted); - font-size: var(--nodedc-font-size-xs); + font-size: var(--nodedc-font-size-sm); line-height: 1.4; } @@ -4353,7 +4365,7 @@ textarea.nodedc-field__control { } @media (max-height: 720px) and (min-width: 761px) { .nodedc-landing-stage__copy p { - font-size: 0.76rem; + font-size: var(--nodedc-font-size-sm); } } @media (max-height: 720px) and (min-width: 761px) { @@ -4676,3 +4688,20 @@ textarea.nodedc-field__control { .nodedc-level-button[data-custom-fill].nodedc-button{position:relative;overflow:hidden;background-image:none} .nodedc-level-button__fill{position:absolute;inset:0;display:grid;place-items:center;pointer-events:none;background:var(--nodedc-level-custom);color:var(--nodedc-level-ink);clip-path:inset(0 calc(100% - var(--nodedc-level-percent)) 0 0)} + + +.nodedc-tooltip-anchor { display: inline-flex; min-width: 0; } +.nodedc-tooltip-anchor[tabindex] { border-radius: var(--nodedc-radius-control-compact); } +.nodedc-tooltip-anchor[tabindex]:focus-visible { outline: 2px solid var(--nodedc-text-primary); outline-offset: 3px; } +.nodedc-tooltip { + position: fixed; z-index: var(--nodedc-layer-popover); box-sizing: border-box; + width: max-content; max-width: min(280px, calc(100vw - 16px)); overflow: auto; + padding: var(--nodedc-space-3) var(--nodedc-space-4); + border-radius: var(--nodedc-radius-control-compact); + background: var(--nodedc-floating-surface); color: var(--nodedc-text-primary); + box-shadow: var(--nodedc-glass-dropdown-shadow); font-family: var(--nodedc-font-family); + font-size: var(--nodedc-font-size-sm); font-weight: var(--nodedc-font-weight-regular); line-height: 1.4; + animation: nodedc-tooltip-in var(--nodedc-duration-fast) var(--nodedc-ease-standard); +} +@keyframes nodedc-tooltip-in { from { opacity: 0; } to { opacity: 1; } } +@media (prefers-reduced-motion: reduce) { .nodedc-tooltip { animation: none; } } diff --git a/packages/ui-core/typography.mjs b/packages/ui-core/typography.mjs new file mode 100644 index 0000000..a77552e --- /dev/null +++ b/packages/ui-core/typography.mjs @@ -0,0 +1,46 @@ +/** Build-time typography contract. CSS parsers/TypeScript are supplied by the consumer. */ +export const operationalFontSizes = Object.freeze({xs: 11, sm: 12, md: 13, dense: 7.2}); +export const titleFontSize = 18; +export function declarationKey({file, selector, property, value}) { + return [file, selector.replace(/\s+/g,' ').trim(), property, value].join(' | '); +} +export function typographyViolation(declaration, policy={}) { + const {property,value}=declaration,key=declarationKey(declaration); + if(property.startsWith('--nodedc-font-size-'))return 'Do not redefine canonical size tokens in a consumer'; + if(property!=='font-size'&&property!=='font'&&!/font-size$/.test(property))return null; + if(property==='font-size'&&/(^|[,\s])(?:html|:root)(?=$|[,\s])/.test(declaration.selector))return 'Do not resize html/rem to make operational UI smaller'; + if(policy.exceptions?.some(e=>e.key===key&&e.reason))return null; + if(property==='font-size'&&declaration.selector.split(',').some(s=>/(?:^|[\s>+~])p$|\.nodedc-description$/.test(s.trim()))&&value!=='var(--nodedc-font-size-sm)')return 'Explanatory paragraphs use sm/12px; do not restyle Description per feature'; + if(property==='font')return value==='inherit'?null:'Use inherited typography; font shorthand can reintroduce browser/large sizes'; + if(/^var\(--nodedc-font-size-(xs|sm|md|dense)\)$/.test(value))return null; + if(value==='var(--nodedc-font-size-title)'&&policy.titles?.includes(declaration.selector))return null; + // Existing compact custom geometry is frozen by exact declaration, never an open size allowance. + if(policy.compactLegacy?.includes(key)){ + const literal=/^([\d.]+)(px|rem)$/.exec(value); + if(literal&&Number(literal[1])*(literal[2]==='rem'?16:1)<=13)return null; + } + return 'Use xs/sm/md tokens (11/12/13 px); title is reserved for canonical page/window titles'; +} +export function auditStyles(postcss, text, file, policy) { + const violations=[]; + postcss.parse(text,{from:file}).walkDecls(d=>{ + const declaration={file,selector:d.parent.selector||d.parent.name||'',property:d.prop,value:d.value}; + const reason=typographyViolation(declaration,policy); + if(reason)violations.push(`${file}:${d.source.start.line}: ${d.parent.selector}: ${d.prop}: ${d.value}: ${reason}`); + }); + return violations; +} +export function auditMarkup(ts,text,file,{allowBareParagraphs=false,inlineExceptions=[]}={}) { + const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true,file.endsWith('tsx')?ts.ScriptKind.TSX:ts.ScriptKind.TS),violations=[]; + function report(n,reason){const fragment=n.getText(source);if(!inlineExceptions.some(e=>e.file===file&&e.fragment===fragment&&e.reason))violations.push(`${file}:${source.getLineAndCharacterOfPosition(n.getStart(source)).line+1}: ${reason}`);} + function visit(n){ + if(ts.isJsxOpeningElement(n)||ts.isJsxSelfClosingElement(n)){ + if(!allowBareParagraphs&&n.tagName.getText(source)==='p'&&!n.attributes.properties.some(p=>ts.isJsxAttribute(p)&&p.name.text==='className'))report(n,'Use Description for explanatory/status copy, or an explicitly styled data paragraph'); + for(const a of n.attributes.properties)if(ts.isJsxAttribute(a)&&/^(fontSize|style)$/.test(a.name.text)&&a.initializer){ + if(a.name.text==='fontSize'||(ts.isStringLiteral(a.initializer)&&/font(?:-size)?\s*:/.test(a.initializer.text)))report(a,'Inline typography bypasses the shared contract'); + } + } + if(ts.isPropertyAssignment(n)&&(/^(fontSize|font|--nodedc-font-size-.+)$/.test(n.name.getText(source).replace(/['"]/g,''))))report(n,'Inline typography bypasses the shared contract'); + ts.forEachChild(n,visit); + }visit(source);return violations; +} diff --git a/packages/ui-react/src/Tooltip.tsx b/packages/ui-react/src/Tooltip.tsx new file mode 100644 index 0000000..dfeba97 --- /dev/null +++ b/packages/ui-react/src/Tooltip.tsx @@ -0,0 +1,69 @@ +import {cloneElement,isValidElement,useCallback,useEffect,useId,useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode,type ReactElement} from 'react'; +import {createPortal} from 'react-dom'; +import {computeFloatingPosition,type FloatingPlacement} from '@nodedc/ui-core'; +import {cn} from './cn.js'; + +export interface TooltipProps { + children:ReactNode; + content:ReactNode; + label?:string; + /** Use for a read-only graphic; buttons already supply their own focus target. */ + focusable?:boolean; + disabled?:boolean; + placement?:FloatingPlacement; + className?:string; +} + +/** Non-interactive explanation; selection/actions belong to Dropdown. */ +export function Tooltip({children,content,label,focusable=false,disabled=false,placement='top-start',className}:TooltipProps){ + const id=`tooltip-${useId().replaceAll(':','')}`; + const anchor=useRef(null),surface=useRef(null); + const timer=useRef|undefined>(undefined); + const [open,setOpen]=useState(false),[style,setStyle]=useState({visibility:'hidden'}); + const clear=useCallback(()=>{clearTimeout(timer.current);},[]); + const close=useCallback(()=>{clear();setOpen(false);},[clear]); + const show=useCallback(()=>{clear();if(!disabled)setOpen(true);},[clear,disabled]); + const leave=()=>{ + clear(); + if(anchor.current?.contains(document.activeElement))return; + timer.current=setTimeout(close,140); + }; + useEffect(()=>()=>clear(),[clear]); + useEffect(()=>{if(disabled)close();},[disabled,close]); + useLayoutEffect(()=>{ + if(!open)return; + const position=()=>{ + if(!anchor.current||!surface.current)return; + const rect=anchor.current.getBoundingClientRect(),size=surface.current.getBoundingClientRect(); + if(rect.bottom<=0||rect.top>=window.innerHeight||rect.right<=0||rect.left>=window.innerWidth){close();return;} + const p=computeFloatingPosition({anchor:rect,surfaceWidth:size.width,surfaceHeight:size.height,placement,offset:8}); + setStyle({left:p.left,top:p.top,maxHeight:p.maxHeight,visibility:'visible'}); + }; + position(); + const observer=new ResizeObserver(position); + if(anchor.current)observer.observe(anchor.current); + if(surface.current)observer.observe(surface.current); + window.addEventListener('resize',position);window.addEventListener('scroll',position,true); + document.addEventListener('fullscreenchange',close); + return()=>{observer.disconnect();window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true);document.removeEventListener('fullscreenchange',close);}; + },[open,placement,close]); + useEffect(()=>{ + if(!open)return; + const key=(e:KeyboardEvent)=>{if(e.key==='Escape'){close();e.preventDefault();e.stopImmediatePropagation();}}; + const outside=(e:PointerEvent)=>{if(e.target instanceof Node&&!anchor.current?.contains(e.target)&&!surface.current?.contains(e.target))close();}; + const other=(e:Event)=>{if((e as CustomEvent).detail!==id)close();}; + document.addEventListener('keydown',key,true);document.addEventListener('pointerdown',outside,true); + window.addEventListener('nodedc-tooltip-open',other); + window.dispatchEvent(new CustomEvent('nodedc-tooltip-open',{detail:id})); + return()=>{document.removeEventListener('keydown',key,true);document.removeEventListener('pointerdown',outside,true);window.removeEventListener('nodedc-tooltip-open',other);}; + },[open,id,close]); + return {if(e.pointerType!=='touch')show();}} + onPointerLeave={leave} onFocus={show} onBlur={e=>{if(!e.currentTarget.contains(e.relatedTarget)&&!e.currentTarget.matches(':hover'))close();}} + onPointerDown={e=>{if(e.pointerType==='touch'){if(open)close();else show();}}}> + {focusable||!isValidElement(children)?children:cloneElement(children as ReactElement<{'aria-describedby'?:string}>,{'aria-describedby':[children.props && (children.props as {'aria-describedby'?:string})['aria-describedby'],open?id:undefined].filter(Boolean).join(' ')||undefined})} + {open&&typeof document!=='undefined'&&createPortal(,document.fullscreenElement??document.body)} + ; +} diff --git a/packages/ui-react/src/index.ts b/packages/ui-react/src/index.ts index 41da1c1..621c2c9 100644 --- a/packages/ui-react/src/index.ts +++ b/packages/ui-react/src/index.ts @@ -56,3 +56,5 @@ export {useApplicationPanelFullscreen} from "./ApplicationPanelFullscreen.js"; export {SceneAnnotation} from "./SceneAnnotation.js"; export {LevelButton,type LevelButtonProps} from "./LevelButton.js"; + +export {Tooltip,type TooltipProps} from "./Tooltip.js"; diff --git a/registry/candidates.json b/registry/candidates.json index b372963..0e169e4 100644 --- a/registry/candidates.json +++ b/registry/candidates.json @@ -6,90 +6,177 @@ "id": "calendar-popover", "classification": "planned-primitive", "priority": "P1", - "referenceSources": ["launcher", "task-manager"], + "referenceSources": [ + "launcher", + "task-manager" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["dropdown", "button", "field"], - "requiredBehavior": ["portal", "locale-aware labels", "single date", "date range", "keyboard navigation"], + "dependsOn": [ + "dropdown", + "button", + "field" + ], + "requiredBehavior": [ + "portal", + "locale-aware labels", + "single date", + "date range", + "keyboard navigation" + ], "reasonNotBaseline": "Current Launcher and Task Manager implementations must be reconciled before one API is declared canonical." }, { "id": "profile-menu", "classification": "planned-pattern", "priority": "P1", - "referenceSources": ["launcher", "task-manager"], + "referenceSources": [ + "launcher", + "task-manager" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["dropdown", "button", "status-badge"], - "requiredBehavior": ["avatar trigger", "identity summary", "role/workspace switch", "logout action"], + "dependsOn": [ + "dropdown", + "button", + "status-badge" + ], + "requiredBehavior": [ + "avatar trigger", + "identity summary", + "role/workspace switch", + "logout action" + ], "reasonNotBaseline": "Identity and role data contracts differ between Hub and Ops and must remain application-owned." }, { "id": "action-dropdown", "classification": "planned-pattern", "priority": "P1", - "referenceSources": ["task-manager", "launcher"], + "referenceSources": [ + "task-manager", + "launcher" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["dropdown"], - "requiredBehavior": ["commands", "disabled rows", "danger row", "optional groups", "keyboard navigation"], + "dependsOn": [ + "dropdown" + ], + "requiredBehavior": [ + "commands", + "disabled rows", + "danger row", + "optional groups", + "keyboard navigation" + ], "reasonNotBaseline": "Floating behavior is stable; command-row API still needs validation against Ops consumers." }, { "id": "data-table", "classification": "planned-pattern", "priority": "P1", - "referenceSources": ["launcher", "task-manager"], + "referenceSources": [ + "launcher", + "task-manager" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["button", "select", "status-badge", "field"], - "requiredBehavior": ["toolbar", "responsive overflow", "row actions", "editable cells", "loading", "empty state"], + "dependsOn": [ + "button", + "select", + "status-badge", + "field" + ], + "requiredBehavior": [ + "toolbar", + "responsive overflow", + "row actions", + "editable cells", + "loading", + "empty state" + ], "reasonNotBaseline": "The library should own presentation and interaction slots, not adopt Launcher entity schemas or Plane table models." }, { "id": "avatar-stack", "classification": "planned-primitive", "priority": "P1", - "referenceSources": ["engine", "task-manager"], + "referenceSources": [ + "engine", + "task-manager" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["dropdown"], - "requiredBehavior": ["overflow count", "presence", "picker mode", "fallback initials"], + "dependsOn": [ + "dropdown" + ], + "requiredBehavior": [ + "overflow count", + "presence", + "picker mode", + "fallback initials" + ], "reasonNotBaseline": "Engine picker behavior and Task Manager presence semantics must not be coupled accidentally." }, { "id": "service-rail-card", "classification": "product-pattern", "priority": "P2", - "referenceSources": ["launcher"], + "referenceSources": [ + "launcher" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["glass-surface", "status-badge", "button"], - "requiredBehavior": ["ambient media", "access status", "selected state", "open/request action"], + "dependsOn": [ + "glass-surface", + "status-badge", + "button" + ], + "requiredBehavior": [ + "ambient media", + "access status", + "selected state", + "open/request action" + ], "reasonNotBaseline": "Likely reusable for product catalogs, but current contract is tightly connected to Launcher service data." }, { "id": "work-item-card", "classification": "product-pattern", "priority": "P2", - "referenceSources": ["task-manager"], + "referenceSources": [ + "task-manager" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["glass-surface", "avatar-stack", "status-badge", "action-dropdown"], - "requiredBehavior": ["selected state", "drag state", "assignees", "dates", "quick actions"], + "dependsOn": [ + "glass-surface", + "avatar-stack", + "status-badge", + "action-dropdown" + ], + "requiredBehavior": [ + "selected state", + "drag state", + "assignees", + "dates", + "quick actions" + ], "reasonNotBaseline": "The visual pattern is mature, but task-domain fields must be separated from the reusable card shell." }, - { - "id": "tooltip", - "classification": "missing-primitive", - "priority": "P2", - "referenceSources": ["launcher", "task-manager", "engine"], - "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["dropdown"], - "requiredBehavior": ["hover", "focus", "delay", "viewport placement"], - "reasonNotBaseline": "Needs a small dedicated accessibility contract rather than reuse of an application tooltip." - }, { "id": "empty-loading-error", "classification": "planned-pattern", "priority": "P2", - "referenceSources": ["launcher", "seo", "task-manager"], + "referenceSources": [ + "launcher", + "seo", + "task-manager" + ], "expectedPackage": "@nodedc/ui-react", - "dependsOn": ["button", "status-badge"], - "requiredBehavior": ["empty message", "retry", "loading progress", "fatal error"], + "dependsOn": [ + "button", + "status-badge" + ], + "requiredBehavior": [ + "empty message", + "retry", + "loading progress", + "fatal error" + ], "reasonNotBaseline": "Copy and domain actions vary; the layout contract still needs examples from all product families." } ] diff --git a/registry/components.json b/registry/components.json index 8dcb36f..44559e9 100644 --- a/registry/components.json +++ b/registry/components.json @@ -429,7 +429,8 @@ "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." + "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." ] }, { @@ -467,7 +468,8 @@ "Rectangle, maximized state, visibility, activation and z-order are controlled by the application.", "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." + "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." ] }, { @@ -743,7 +745,8 @@ "Applications supply routes, profile data, stage media and panel content without changing shell geometry.", "Light panels use the SEO white surface and shadow tokens rather than a dark shell with inverted text.", "A layout-level save action belongs to ApplicationPanel.utilityActions and is never duplicated inside individual content cards.", - "ApplicationPanel allowFullscreen exposes an owned full-window context; the whole panel and its header move atomically, preserving the renderer and body-portaled inspectors." + "ApplicationPanel allowFullscreen exposes an owned full-window context; the whole panel and its header move atomically, preserving the renderer and body-portaled inspectors.", + "ApplicationPanel establishes md/13px operational typography independent of the host; its page title alone uses title/18px. Semantic section headings remain md; explanatory copy uses Description/sm." ] }, { @@ -1192,7 +1195,8 @@ "summary": "Secondary explanatory copy matching SettingsCard descriptions.", "rules": [ "Use the same inherited family, regular 400 weight, small font token, muted text token and 1.4 line height for explanatory paragraphs. Do not restyle per feature.", - "Use role=status for explanatory pending/result copy. SettingsCard applies the same contract to unclassed body paragraphs as a fallback, without changing headings or controls." + "Use role=status for explanatory pending/result copy. SettingsCard applies the same contract to unclassed body paragraphs as a fallback, without changing headings or controls.", + "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." ] }, { @@ -1385,6 +1389,34 @@ "Optional geometry sets width, height and radius with a 32 × 12 px minimum. At small dimensions the text and padding shrink proportionally; both contrast layers share the same type geometry. Consumer owns header-group offset." ], "documentation": "../docs/LEVEL_BUTTON.md" + }, + { + "id": "tooltip", + "status": "baseline", + "package": "@nodedc/ui-react", + "exports": [ + "Tooltip", + "TooltipProps" + ], + "domContract": [ + "nodedc-tooltip-anchor", + "nodedc-tooltip" + ], + "summary": "Neutral non-interactive explanation on hover, focus or touch.", + "behavior": [ + "portal to active fullscreen element or body", + "shared viewport clamp and flip", + "hoverable content and focus persistence", + "Escape dismisses tooltip without closing its parent", + "one tooltip at a time", + "scroll/resize reposition", + "reduced-motion fade disabled" + ], + "rules": [ + "Use focusable for read-only graphics; action triggers own their focus.", + "Content is descriptive, never a menu or interactive form.", + "No new app-local tooltip geometry or layer management." + ] } ] } diff --git a/scripts/operational-typography.test.mjs b/scripts/operational-typography.test.mjs new file mode 100644 index 0000000..cf41053 --- /dev/null +++ b/scripts/operational-typography.test.mjs @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import postcss from 'postcss'; +import {readFileSync,readdirSync} from 'node:fs'; +import {fileURLToPath} from 'node:url'; +import path from 'node:path'; +import {auditStyles,typographyViolation,operationalFontSizes,titleFontSize} from '../packages/ui-core/typography.mjs'; +const root=fileURLToPath(new URL('../',import.meta.url)); +const policy=JSON.parse(readFileSync(new URL('./typography-policy.json',import.meta.url),'utf8')); +function walk(dir){return readdirSync(dir,{withFileTypes:true}).flatMap(e=>['dist','node_modules','tokens'].includes(e.name)?[]:e.isDirectory()?walk(path.join(dir,e.name)):[path.join(dir,e.name)]);} +test('all shared CSS uses compact operational roles and canonical title exceptions',()=>{ + const violations=[];for(const file of walk(path.join(root,'packages')).filter(f=>f.endsWith('.css')))violations.push(...auditStyles(postcss,readFileSync(file,'utf8'),path.relative(root,file),policy));assert.deepEqual(violations,[]); +}); +test('UI roots and portaled windows establish their own 13px typography, independent of host body',()=>{ + const css=postcss.parse(readFileSync(path.join(root,'packages/ui-core/styles.css'),'utf8')); + for(const scope of ['.nodedc-ui-root','.nodedc-window','.nodedc-workspace-window','.nodedc-application-panel','.nodedc-admin-panel']){ + let base=false,headings=false;css.walkRules(rule=>{if(rule.selector.includes(scope)){if(!rule.selector.includes(' :where(')&&rule.nodes.some(d=>d.prop==='font-size'&&d.value==='var(--nodedc-font-size-md)'))base=true;if(rule.selector.includes(':where(h1, h2, h3, h4, h5, h6)')&&rule.nodes.some(d=>d.prop==='font-size'&&d.value==='var(--nodedc-font-size-md)'))headings=true;}});assert.ok(base,scope+' independent base');assert.ok(headings,scope+' semantic heading reset'); + } +}); +test('token values cannot silently make all operational consumers larger',()=>{ + const css=postcss.parse(readFileSync(path.join(root,'packages/tokens/tokens.css'),'utf8')); + for(const [role,px] of Object.entries({...operationalFontSizes,title:titleFontSize})){ + const values=[];css.walkDecls('--nodedc-font-size-'+role,d=>values.push(d.value));assert.ok(values.length,role);for(const value of values)assert.equal(parseFloat(value)*16,px,role); + } +}); +test('title role never grants large typography to a data field or nested card',()=>{ + assert.equal(typographyViolation({file:'example.css',selector:'.nodedc-window__title',property:'font-size',value:'var(--nodedc-font-size-title)'},policy),null); + for(const selector of ['.value','.settings-card h2','.nodedc-window__body'])assert.ok(typographyViolation({file:'example.css',selector,property:'font-size',value:'var(--nodedc-font-size-title)'},policy)); + assert.ok(typographyViolation({file:'example.css',selector:'.value',property:'font-size',value:'16px'},{compactLegacy:['example.css | .value | font-size | 16px']})); +}); + +test('theme attributes on html cannot shrink the rem coordinate system',()=>{ + const css=postcss.parse(readFileSync(path.join(root,'packages/ui-core/styles.css'),'utf8')); + css.walkRules(rule=>{ + if(rule.nodes.some(d=>d.prop==='font-size')&&rule.selector.startsWith(':where([data-nodedc-ui]')&&!rule.selector.includes(' :where(')){ + assert.ok(rule.selector.includes('[data-nodedc-ui]:not(html)')); + assert.ok(rule.selector.includes('.nodedc-ui-root:not(html)')); + assert.ok(rule.selector.includes('html[data-nodedc-ui] > body')); + } + }); +}); diff --git a/scripts/typography-policy.json b/scripts/typography-policy.json new file mode 100644 index 0000000..1476fe4 --- /dev/null +++ b/scripts/typography-policy.json @@ -0,0 +1,59 @@ +{ + "compactLegacy": [ + "packages/ui-core/styles.css | .nodedc-admin-context__body small | font-size | 0.72rem", + "packages/ui-core/styles.css | .nodedc-admin-panel__group-label | font-size | 0.68rem", + "packages/ui-core/styles.css | .nodedc-application-panel__titles span | font-size | 0.68rem", + "packages/ui-core/styles.css | .nodedc-application-side-panel__description | font-size | 0.72rem", + "packages/ui-core/styles.css | .nodedc-environment-settings__quick-actions span | font-size | 0.68rem", + "packages/ui-core/styles.css | .nodedc-environment-settings__surface > span | font-size | 0.74rem", + "packages/ui-core/styles.css | .nodedc-feature-settings__group | font-size | 0.66rem", + "packages/ui-core/styles.css | .nodedc-header__avatar | font-size | 0.72rem", + "packages/ui-core/styles.css | .nodedc-landing-stage__footer | font-size | 0.57rem", + "packages/ui-core/styles.css | .nodedc-media-field__kind | font-size | 0.62rem", + "packages/ui-core/styles.css | .nodedc-media-file__button | font-size | 0.78rem", + "packages/ui-core/styles.css | .nodedc-media-file__name | font-size | 0.78rem", + "packages/ui-core/styles.css | .nodedc-media-source-button | font-size | 0.68rem", + "packages/ui-core/styles.css | .nodedc-media-url | font-size | 0.78rem", + "packages/ui-core/styles.css | .nodedc-settings-card__titles > span | font-size | 0.66rem", + "packages/ui-core/styles.css | .nodedc-share-access__avatar | font-size | 0.68rem", + "packages/ui-core/styles.css | .nodedc-share-access__summary-avatar | font-size | 0.62rem", + "packages/ui-core/styles.css | .nodedc-share-access__summary-count | font-size | 0.68rem", + "packages/ui-core/styles.css | .nodedc-user-profile-card__cover > span:not(.nodedc-header__avatar) | font-size | 0.78rem" + ], + "titles": [ + ".nodedc-application-panel__titles h1", + ".nodedc-admin-panel__head h2", + ".nodedc-window__title" + ], + "exceptions": [ + { + "key": "packages/ui-core/styles.css | .nodedc-description, .nodedc-settings-card__titles p, .nodedc-settings-card__body :where(p:not([class])) | font-size | var(--nodedc-description-font-size, var(--nodedc-font-size-sm))", + "reason": "Canonical Description fallback, compact sm token." + }, + { + "key": "packages/ui-core/styles.css | .nodedc-range-scale__limit | font-size | calc(var(--nodedc-font-size-xs) * 0.9)", + "reason": "Existing compact viewport label multiplier below sm/xs." + }, + { + "key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(3rem, 7vw, 7.6rem)", + "reason": "Cover display heading only; never an operational value or message." + }, + { + "key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(2.7rem, 7vw, 5.6rem)", + "reason": "Cover display heading only; never an operational value or message." + }, + { + "key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(2.8rem, 14vw, 5rem)", + "reason": "Cover display heading only; never an operational value or message." + }, + { + "key": "packages/ui-core/styles.css | .nodedc-landing-stage__copy h1 | font-size | clamp(2.7rem, 6vw, 5rem)", + "reason": "Cover display heading only; never an operational value or message." + }, + { + "key": "packages/ui-core/styles.css | .nodedc-navigation-cube text | font | 600 9px var(--nodedc-font-family)", + "reason": "SVG viewBox coordinate text, not a CSS-screen text size." + } + ], + "inlineExceptions": [] +}