Files
NODEDC_DESIGN_GUIDELINE/packages/ui-react/src/tooltipTitles.ts
T

21 lines
1.9 KiB
TypeScript

/** 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;}
}
}