Standardize rounded glass tooltips across application surfaces

This commit is contained in:
Codex
2026-11-16 14:33:59 +03:00
parent ae82c01049
commit f8aa8022f1
18 changed files with 164 additions and 25 deletions
+2 -2
View File
@@ -11,8 +11,8 @@
}, },
"dependencies": { "dependencies": {
"@nodedc/page-patterns": "0.1.0", "@nodedc/page-patterns": "0.1.0",
"@nodedc/ui-core": "0.7.0", "@nodedc/ui-core": "0.7.1",
"@nodedc/ui-react": "0.7.0", "@nodedc/ui-react": "0.7.1",
"cesium": "^1.143.0", "cesium": "^1.143.0",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0" "react-dom": "^19.1.0"
+3 -1
View File
@@ -1480,8 +1480,10 @@ export function CatalogApp() {
<KeyButton label="Клавиша S недоступна" disabled>S</KeyButton> <KeyButton label="Клавиша S недоступна" disabled>S</KeyButton>
</div> </div>
</Preview> </Preview>
<Preview title="Подсказки" note="hover / focus / touch" className="catalog-preview--compact"> <Preview title="Подсказки" note="Скруглённое стекло без обводки · hover / focus / touch" className="catalog-preview--compact">
<div className="catalog-inline catalog-inline--wrap"> <div className="catalog-inline catalog-inline--wrap">
<IconButton label="Инспектор"><Icon name="network" /></IconButton>
<Button title="Общая подсказка для существующего title">Подсказка приложения</Button>
<Tooltip content="Короткое пояснение. Escape закрывает только подсказку."><Button>Подробнее</Button></Tooltip> <Tooltip content="Короткое пояснение. Escape закрывает только подсказку."><Button>Подробнее</Button></Tooltip>
<Tooltip focusable label="Текущий уровень" content="Доступно мышью, клавиатурой и касанием."><StatusBadge tone="neutral">Нормальный уровень</StatusBadge></Tooltip> <Tooltip focusable label="Текущий уровень" content="Доступно мышью, клавиатурой и касанием."><StatusBadge tone="neutral">Нормальный уровень</StatusBadge></Tooltip>
<Tooltip disabled content="Эта подсказка отключена"><Button disabled>Недоступно</Button></Tooltip> <Tooltip disabled content="Эта подсказка отключена"><Button disabled>Недоступно</Button></Tooltip>
+2 -1
View File
@@ -2,11 +2,12 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
import "@nodedc/ui-core/styles.css"; import "@nodedc/ui-core/styles.css";
import "./styles.css"; import "./styles.css";
import { TooltipProvider } from "@nodedc/ui-react";
import { CatalogApp } from "./CatalogApp"; import { CatalogApp } from "./CatalogApp";
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<StrictMode> <StrictMode>
<CatalogApp /> <TooltipProvider><CatalogApp /></TooltipProvider>
</StrictMode>, </StrictMode>,
); );
+4
View File
@@ -160,3 +160,7 @@ immutable archive `nodedc-ui-dom-0.7.0-modal.2.tgz`. Адаптер переда
Сетка файлов, поиск и фильтрация по нескольким типам остаются доменной логикой Сетка файлов, поиск и фильтрация по нескольким типам остаются доменной логикой
CMS; переключатели используют общий IconButton. Проверены выбор глубокого CMS; переключатели используют общий IconButton. Проверены выбор глубокого
пути, переход в каталог, dark/light и узкое окно 390 px. пути, переход в каталог, dark/light и узкое окно 390 px.
## Общие подсказки · 2026-11-16
Mission Core подключает `TooltipProvider` из ui-react 0.7.1 один раз над приложением. BIM Mod 0.2.45 подключает его в переносимом workspace и переиспользует provider хоста. Существующие HTML `title` обрабатываются через общий портал, SVG-подсказки — через `data-nodedc-tooltip` с доступным именем `aria-label`. Богатый контент использует `Tooltip`. Вложенные приложения не создают второй слой подсказок. Общий материал: скруглённое стекло без border, outline и декоративного rim; keyboard focus самих контролов сохраняется.
+2
View File
@@ -568,6 +568,8 @@ Window header actions default to before the move toggle. `headerActionsPlacement
## Tooltip ## Tooltip
Общий стандарт: скруглённое стекло Scene Glass без декоративной рамки, outline и обводки. `TooltipProvider` подключается один раз на корне приложения и заменяет браузерные квадратные подсказки `title`, в том числе в старых экранах. Вложенный переносимый модуль использует уже установленный provider. Rich-content `Tooltip` сохраняет собственный триггер; две подсказки одновременно не появляются. `aria-describedby`, клавиатурный фокус, Escape, fullscreen и положение у границ окна сохраняются.
Нейтральная подсказка с `content`, `children`, необязательными `label`, `focusable`, `disabled` и `placement`. Оборачивает триггер; `focusable` делает читаемую графику доступной клавиатуре, обычная кнопка сохраняет собственный фокус. Hover, focus и touch показывают один общий portal над окном; Escape закрывает подсказку, не родительское окно. Можно перевести курсор в подсказку. Позиция пересчитывается при scroll/resize, с общим clamp/flip. Не содержит действий: для меню используется Dropdown. Нет рамки, акцентных цветов или анимации при reduced motion. Нейтральная подсказка с `content`, `children`, необязательными `label`, `focusable`, `disabled` и `placement`. Оборачивает триггер; `focusable` делает читаемую графику доступной клавиатуре, обычная кнопка сохраняет собственный фокус. Hover, focus и touch показывают один общий portal над окном; Escape закрывает подсказку, не родительское окно. Можно перевести курсор в подсказку. Позиция пересчитывается при scroll/resize, с общим clamp/flip. Не содержит действий: для меню используется Dropdown. Нет рамки, акцентных цветов или анимации при reduced motion.
Принят для запрошенных владельцем пояснений шкал сигнала,10.11.2026; приложение владеет диапазонами и текстом, общий компонент — формой и взаимодействием. Принят для запрошенных владельцем пояснений шкал сигнала,10.11.2026; приложение владеет диапазонами и текстом, общий компонент — формой и взаимодействием.
+8 -8
View File
@@ -1,12 +1,12 @@
{ {
"name": "nodedc-design-guideline", "name": "nodedc-design-guideline",
"version": "0.7.0", "version": "0.7.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "nodedc-design-guideline", "name": "nodedc-design-guideline",
"version": "0.7.0", "version": "0.7.1",
"workspaces": [ "workspaces": [
"packages/*", "packages/*",
"apps/*" "apps/*"
@@ -28,8 +28,8 @@
"version": "0.7.0", "version": "0.7.0",
"dependencies": { "dependencies": {
"@nodedc/page-patterns": "0.1.0", "@nodedc/page-patterns": "0.1.0",
"@nodedc/ui-core": "0.7.0", "@nodedc/ui-core": "0.7.1",
"@nodedc/ui-react": "0.7.0", "@nodedc/ui-react": "0.7.1",
"cesium": "^1.143.0", "cesium": "^1.143.0",
"react": "^19.1.0", "react": "^19.1.0",
"react-dom": "^19.1.0" "react-dom": "^19.1.0"
@@ -2484,7 +2484,7 @@
}, },
"packages/ui-core": { "packages/ui-core": {
"name": "@nodedc/ui-core", "name": "@nodedc/ui-core",
"version": "0.7.0", "version": "0.7.1",
"dependencies": { "dependencies": {
"@nodedc/tokens": "0.6.0" "@nodedc/tokens": "0.6.0"
} }
@@ -2493,17 +2493,17 @@
"name": "@nodedc/ui-dom", "name": "@nodedc/ui-dom",
"version": "0.7.0", "version": "0.7.0",
"dependencies": { "dependencies": {
"@nodedc/ui-core": "0.7.0" "@nodedc/ui-core": "0.7.1"
} }
}, },
"packages/ui-react": { "packages/ui-react": {
"name": "@nodedc/ui-react", "name": "@nodedc/ui-react",
"version": "0.7.0", "version": "0.7.1",
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.3.1", "@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0", "@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
"@nodedc/ui-core": "0.7.0", "@nodedc/ui-core": "0.7.1",
"lucide-react": "^0.468.0" "lucide-react": "^0.468.0"
}, },
"devDependencies": { "devDependencies": {
+4 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "nodedc-design-guideline", "name": "nodedc-design-guideline",
"version": "0.7.0", "version": "0.7.1",
"private": true, "private": true,
"description": "Canonical NODE.DC design system, reusable UI packages and living component catalog.", "description": "Canonical NODE.DC design system, reusable UI packages and living component catalog.",
"type": "module", "type": "module",
@@ -11,7 +11,7 @@
"scripts": { "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": "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", "build:packages": "npm run build --workspace @nodedc/ui-core && npm run build --workspace @nodedc/ui-dom && npm run build --workspace @nodedc/ui-react && npm run build --workspace @nodedc/page-patterns && npm run build --workspace @nodedc/map-cesium-react",
"check": "npm run test:typography && npm run build:packages && npm run typecheck --workspaces --if-present && npm run validate:registry && npm run test:spark-governance && npm run test:analysis-controls && npm run test:activity-indicator && npm run test:control-density && npm run test:icon-contract && npm run test:toast-contract && npm run test:floating-position && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock && npm run test:flat-theme && npm run test:mission-theme && npm run test:modal-size", "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:tooltip && npm run test:inspector-select && npm run test:range-control && npm run test:split-pane && npm run test:dock-layout && npm run test:hgeozone-projection && npm run test:map-grid-lod && npm run test:map-filters && npm run test:map-object-layers && npm run test:map-inspector-overlay-state && npm run test:map-reference-stations && npm run test:map-search && npm run test:map-subject-card && npm run test:map-subject-detail-profile && npm run test:environment-settings && npm run test:settings-surfaces && npm run test:window-geometry && npm run test:editor-dock && npm run test:flat-theme && npm run test:mission-theme && npm run test:modal-size",
"dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog", "dev": "npm run build:packages && npm run dev --workspace @nodedc/ui-catalog",
"serve": "node server/catalog-server.mjs", "serve": "node server/catalog-server.mjs",
"validate:registry": "node scripts/validate-registry.mjs", "validate:registry": "node scripts/validate-registry.mjs",
@@ -50,7 +50,8 @@
"prebuild": "npm run test:typography", "prebuild": "npm run test:typography",
"test:flat-theme": "node --test scripts/flat-theme.test.mjs", "test:flat-theme": "node --test scripts/flat-theme.test.mjs",
"test:mission-theme": "node --test scripts/mission-theme.test.mjs", "test:mission-theme": "node --test scripts/mission-theme.test.mjs",
"test:modal-size": "node --test scripts/modal-size.test.mjs" "test:modal-size": "node --test scripts/modal-size.test.mjs",
"test:tooltip": "node --test scripts/tooltip-titles.test.mjs"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@nodedc/ui-core", "name": "@nodedc/ui-core",
"version": "0.7.0", "version": "0.7.1",
"type": "module", "type": "module",
"files": [ "files": [
"dist", "dist",
+5 -2
View File
@@ -4784,8 +4784,11 @@ textarea.nodedc-field__control {
width: max-content; max-width: min(280px, calc(100vw - 16px)); overflow: auto; width: max-content; max-width: min(280px, calc(100vw - 16px)); overflow: auto;
padding: var(--nodedc-space-3) var(--nodedc-space-4); padding: var(--nodedc-space-3) var(--nodedc-space-4);
border-radius: var(--nodedc-radius-control-compact); border-radius: var(--nodedc-radius-control-compact);
background: var(--nodedc-floating-surface); color: var(--nodedc-text-primary); border: 0; outline: 0;
box-shadow: var(--nodedc-glass-dropdown-shadow); font-family: var(--nodedc-font-family); 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)); color: var(--nodedc-text-primary);
box-shadow: none; font-family: var(--nodedc-font-family);
font-size: var(--nodedc-font-size-sm); font-weight: var(--nodedc-font-weight-regular); line-height: 1.4; 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); animation: nodedc-tooltip-in var(--nodedc-duration-fast) var(--nodedc-ease-standard);
} }
+1 -1
View File
@@ -20,6 +20,6 @@
"typecheck": "tsc -p tsconfig.json --noEmit" "typecheck": "tsc -p tsconfig.json --noEmit"
}, },
"dependencies": { "dependencies": {
"@nodedc/ui-core": "0.7.0" "@nodedc/ui-core": "0.7.1"
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@nodedc/ui-react", "name": "@nodedc/ui-react",
"version": "0.7.0", "version": "0.7.1",
"type": "module", "type": "module",
"files": [ "files": [
"dist" "dist"
@@ -21,7 +21,7 @@
"@dnd-kit/core": "^6.3.1", "@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0", "@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
"@nodedc/ui-core": "0.7.0", "@nodedc/ui-core": "0.7.1",
"lucide-react": "^0.468.0" "lucide-react": "^0.468.0"
}, },
"peerDependencies": { "peerDependencies": {
+1 -1
View File
@@ -62,7 +62,7 @@ export function Tooltip({children,content,label,focusable=false,disabled=false,p
aria-describedby={open?id:undefined} onPointerEnter={e=>{if(e.pointerType!=='touch')show();}} aria-describedby={open?id:undefined} onPointerEnter={e=>{if(e.pointerType!=='touch')show();}}
onPointerLeave={leave} onFocus={show} onBlur={e=>{if(!e.currentTarget.contains(e.relatedTarget)&&!e.currentTarget.matches(':hover'))close();}} 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();}}}> 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})} {focusable||!isValidElement(children)?children:cloneElement(children as ReactElement<{'aria-describedby'?:string;title?:string}>,{title:undefined,'aria-describedby':[children.props && (children.props as {'aria-describedby'?:string})['aria-describedby'],open?id:undefined].filter(Boolean).join(' ')||undefined})}
{open&&typeof document!=='undefined'&&createPortal(<div ref={surface} id={id} role="tooltip" {open&&typeof document!=='undefined'&&createPortal(<div ref={surface} id={id} role="tooltip"
className="nodedc-tooltip" style={style} onPointerEnter={clear} onPointerLeave={leave}>{content}</div>,document.fullscreenElement??document.body)} className="nodedc-tooltip" style={style} onPointerEnter={clear} onPointerLeave={leave}>{content}</div>,document.fullscreenElement??document.body)}
</span>; </span>;
+73
View File
@@ -0,0 +1,73 @@
import {createContext,useContext,useEffect,useId,useLayoutEffect,useRef,useState,type CSSProperties,type ReactNode} from 'react';
import {createPortal} from 'react-dom';
import {computeFloatingPosition} from '@nodedc/ui-core';
import {TooltipTitles} from './tooltipTitles.js';
const Installed=createContext(false);
/** One application-wide bridge for native title hints. Nested modules reuse the host. */
export function TooltipProvider({children}:{children?:ReactNode}){
const installed=useContext(Installed);
return installed?<>{children}</>:<Installed.Provider value={true}><TitleTooltips/>{children}</Installed.Provider>;
}
function TitleTooltips(){
const id=`tooltip-layer-${useId().replaceAll(':','')}`;
const [target,setTarget]=useState<{element:Element;text:string}|null>(null);
const [style,setStyle]=useState<CSSProperties>({visibility:'hidden'});
const surface=useRef<HTMLDivElement>(null),titles=useRef(new TooltipTitles());
const hide=useRef(()=>{});
useEffect(()=>{
let anchor:Element|null=null,timer:ReturnType<typeof setTimeout>|undefined,leaving:ReturnType<typeof setTimeout>|undefined,observer:MutationObserver|null=null;
const clear=()=>{clearTimeout(timer);clearTimeout(leaving);};
const close=()=>{clear();observer?.disconnect();observer=null;anchor=null;titles.current.restore();setTarget(null);};hide.current=close;
const show=(element:Element,text:string)=>{
titles.current.describe(element,id);setTarget({element,text});
window.dispatchEvent(new CustomEvent('nodedc-tooltip-open',{detail:id}));
};
const enter=(node:EventTarget|null,keyboard=false)=>{
if(!(node instanceof Element))return;
if(surface.current?.contains(node)){clear();return;}
if(anchor?.contains(node)){clearTimeout(leaving);if(keyboard){const text=titles.current.text(anchor);if(text)show(anchor,text);}return;}
close();
// Explicit Tooltip already owns rich content and its accessible description.
if(node.closest('.nodedc-tooltip-anchor,[data-nodedc-tooltip="off"]'))return;
const found=titles.current.find(node);if(!found)return;
anchor=found.element;titles.current.suppress(anchor);
observer=new MutationObserver(()=>{
if(!anchor)return;
const updated=anchor.getAttribute('data-nodedc-tooltip')??anchor.getAttribute('title');if(updated===null)return;
titles.current.suppress(anchor);if(updated.trim())show(anchor,updated);else close();
});observer.observe(anchor,{attributes:true,attributeFilter:['title','data-nodedc-tooltip']});
if(keyboard)show(anchor,found.text);else timer=setTimeout(()=>{if(anchor)show(anchor,found.text);},220);
};
const leave=(related:EventTarget|null)=>{
if(related instanceof Node&&(anchor?.contains(related)||surface.current?.contains(related)))return;
if(anchor?.contains(document.activeElement))return;
clearTimeout(leaving);leaving=setTimeout(close,140);
};
const over=(event:PointerEvent)=>{if(event.pointerType!=='touch')enter(event.composedPath()[0]??event.target);};
const out=(event:PointerEvent)=>leave(event.relatedTarget);
const focus=(event:FocusEvent)=>enter(event.composedPath()[0]??event.target,true);
const blur=(event:FocusEvent)=>{if(!(event.relatedTarget instanceof Node)||!anchor?.contains(event.relatedTarget))close();};
const down=()=>{clear();setTarget(null);};
const key=(event:KeyboardEvent)=>{if(event.key==='Escape'&&anchor){close();event.preventDefault();event.stopImmediatePropagation();}};
const other=(event:Event)=>{if((event as CustomEvent<string>).detail!==id)close();};
document.addEventListener('pointerover',over,true);document.addEventListener('pointerout',out,true);
document.addEventListener('focusin',focus,true);document.addEventListener('focusout',blur,true);
document.addEventListener('pointerdown',down,true);document.addEventListener('keydown',key,true);
document.addEventListener('fullscreenchange',close);window.addEventListener('blur',close);window.addEventListener('nodedc-tooltip-open',other);
return()=>{close();document.removeEventListener('pointerover',over,true);document.removeEventListener('pointerout',out,true);document.removeEventListener('focusin',focus,true);document.removeEventListener('focusout',blur,true);document.removeEventListener('pointerdown',down,true);document.removeEventListener('keydown',key,true);document.removeEventListener('fullscreenchange',close);window.removeEventListener('blur',close);window.removeEventListener('nodedc-tooltip-open',other);};
},[id]);
useLayoutEffect(()=>{
if(!target)return;
const position=()=>{
if(!surface.current||!target.element.isConnected){hide.current();return;}
const rect=target.element.getBoundingClientRect();if(rect.bottom<=0||rect.top>=window.innerHeight||rect.right<=0||rect.left>=window.innerWidth){hide.current();return;}
const size=surface.current.getBoundingClientRect(),p=computeFloatingPosition({anchor:rect,surfaceWidth:size.width,surfaceHeight:size.height,placement:'bottom-start',offset:8});
setStyle({left:p.left,top:p.top,maxHeight:p.maxHeight,visibility:'visible'});
};
position();const observer=new ResizeObserver(position);observer.observe(target.element);if(surface.current)observer.observe(surface.current);
window.addEventListener('resize',position);window.addEventListener('scroll',position,true);
return()=>{observer.disconnect();window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true);};
},[target]);
return target&&typeof document!=='undefined'?createPortal(<div ref={surface} id={id} role="tooltip" className="nodedc-tooltip" style={style}>{target.text}</div>,document.fullscreenElement??document.body):null;
}
+2
View File
@@ -58,3 +58,5 @@ export {SceneAnnotation} from "./SceneAnnotation.js";
export {LevelButton,type LevelButtonProps} from "./LevelButton.js"; export {LevelButton,type LevelButtonProps} from "./LevelButton.js";
export {Tooltip,type TooltipProps} from "./Tooltip.js"; export {Tooltip,type TooltipProps} from "./Tooltip.js";
export {TooltipProvider} from "./TooltipProvider.js";
+20
View File
@@ -0,0 +1,20 @@
/** Suppress native tooltips only during interaction; preserve changing titles and ARIA. */
export class TooltipTitles {
private titles=new Map<Element,string>();
private description:{element:Element;id:string;label?:string}|null=null;
text(element:Element){return element.getAttribute('data-nodedc-tooltip')??this.titles.get(element)??element.getAttribute('title');}
find(start:Element){for(let element:Element|null=start;element;element=element.parentElement){const text=element.getAttribute('data-nodedc-tooltip')??element.getAttribute('title');if(text!==null)return text.trim()?{element,text}:null;}return null;}
suppress(start:Element){for(let element:Element|null=start;element;element=element.parentElement){const text=element.getAttribute('title');if(text!==null){this.titles.set(element,text);element.removeAttribute('title');}}}
describe(element:Element,id:string){
const ids=new Set((element.getAttribute('aria-describedby')??'').split(/\s+/).filter(Boolean));ids.add(id);element.setAttribute('aria-describedby',[...ids].join(' '));
let label=this.description?.label;
if(!element.hasAttribute('aria-label')&&!element.hasAttribute('aria-labelledby')&&!element.textContent?.trim()){
label=this.text(element)??undefined;if(label)element.setAttribute('aria-label',label);
}
this.description={element,id,label};
}
restore(){
for(const [element,text] of this.titles)if(!element.hasAttribute('title'))element.setAttribute('title',text);this.titles.clear();
if(this.description){const {element,id,label}=this.description;const ids=(element.getAttribute('aria-describedby')??'').split(/\s+/).filter(value=>value&&value!==id);if(ids.length)element.setAttribute('aria-describedby',ids.join(' '));else element.removeAttribute('aria-describedby');if(label&&element.getAttribute('aria-label')===label)element.removeAttribute('aria-label');this.description=null;}
}
}
+5 -2
View File
@@ -1452,7 +1452,8 @@
"package": "@nodedc/ui-react", "package": "@nodedc/ui-react",
"exports": [ "exports": [
"Tooltip", "Tooltip",
"TooltipProps" "TooltipProps",
"TooltipProvider"
], ],
"domContract": [ "domContract": [
"nodedc-tooltip-anchor", "nodedc-tooltip-anchor",
@@ -1471,7 +1472,9 @@
"rules": [ "rules": [
"Use focusable for read-only graphics; action triggers own their focus.", "Use focusable for read-only graphics; action triggers own their focus.",
"Content is descriptive, never a menu or interactive form.", "Content is descriptive, never a menu or interactive form.",
"No new app-local tooltip geometry or layer management." "No new app-local tooltip geometry or layer management.",
"All tooltip surfaces use rounded scene glass without decorative border, outline or rim.",
"Mount TooltipProvider once at the application root to present legacy native title hints through the same accessible portal. Nested reusable modules reuse the host provider."
] ]
}, },
{ {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"schemaVersion": "1.0.0", "schemaVersion": "1.0.0",
"libraryVersion": "0.7.0", "libraryVersion": "0.7.1",
"name": "NODE.DC Design System", "name": "NODE.DC Design System",
"purpose": "Canonical code-level UI system for current and future NODE.DC applications.", "purpose": "Canonical code-level UI system for current and future NODE.DC applications.",
"packages": [ "packages": [
+28
View File
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {TooltipTitles} from '../packages/ui-react/dist/tooltipTitles.js';
class Node {
constructor(attributes={},parentElement=null){this.attributes=new Map(Object.entries(attributes));this.parentElement=parentElement;this.textContent='';}
getAttribute(name){return this.attributes.get(name)??null;}
hasAttribute(name){return this.attributes.has(name);}
setAttribute(name,value){this.attributes.set(name,value);}
removeAttribute(name){this.attributes.delete(name);}
}
test('native titles are suppressed through ancestor chain and restored without a duplicate bubble',()=>{
const parent=new Node({title:'Parent'}),button=new Node({title:'Inspector','aria-label':'Inspector','aria-describedby':'help'},parent),svg=new Node({},button),titles=new TooltipTitles();
assert.deepEqual(titles.find(svg),{element:button,text:'Inspector'});titles.suppress(button);titles.describe(button,'tip');
assert.equal(button.getAttribute('title'),null);assert.equal(parent.getAttribute('title'),null);assert.equal(button.getAttribute('aria-describedby'),'help tip');
titles.restore();assert.equal(button.getAttribute('title'),'Inspector');assert.equal(parent.getAttribute('title'),'Parent');assert.equal(button.getAttribute('aria-label'),'Inspector');assert.equal(button.getAttribute('aria-describedby'),'help');
});
test('new titles and external ARIA changes survive cleanup; empty title blocks inherited hints',()=>{
const parent=new Node({title:'Parent'}),button=new Node({title:''},parent),titles=new TooltipTitles();assert.equal(titles.find(button),null);
button.setAttribute('title','Before');titles.suppress(button);titles.describe(button,'tip');assert.equal(button.getAttribute('aria-label'),'Before');
button.setAttribute('title','After');titles.suppress(button);button.setAttribute('aria-label','External');button.setAttribute('aria-describedby','tip extra');
titles.restore();assert.equal(button.getAttribute('title'),'After');assert.equal(button.getAttribute('aria-label'),'External');assert.equal(button.getAttribute('aria-describedby'),'extra');
});
test('SVG controls use the same tooltip channel without a native title element',()=>{
const control=new Node({'data-nodedc-tooltip':'Повернуть элемент'}),shape=new Node({},control),titles=new TooltipTitles();
assert.deepEqual(titles.find(shape),{element:control,text:'Повернуть элемент'});
titles.suppress(control);titles.describe(control,'tip');assert.equal(control.getAttribute('aria-label'),'Повернуть элемент');
titles.restore();assert.equal(control.getAttribute('data-nodedc-tooltip'),'Повернуть элемент');assert.equal(control.getAttribute('aria-label'),null);
});