-
-
Save renoirb/c14050700e634099646823abead68c8f to your computer and use it in GitHub Desktop.
aria utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Creates a menu button that opens a menu of links | |
// | |
// TODO continue refactoring WAI's example for reusability | |
// | |
// Source: https://www.w3.org/TR/wai-aria-practices/examples/menu-button/menu-button-links.html | |
// | |
export interface IFocusBy<T> { | |
readonly firstChars: ReadonlySet<string> | |
setFocus(by: T) | |
} | |
export const isPrintableCharacter = (str: string): boolean => { | |
const isTextualString = str.match(/\S/) !== null | |
return str.length === 1 && isTextualString; | |
} | |
export class FocusByKey implements IFocusBy<string> { | |
private _host: HTMLElement | |
get firstChars(): ReadonlySet<string> { | |
const data: ReadonlySet<string> = new Set([...this._firstChars.keys()]) | |
return data | |
} | |
private _firstChars = new Set<string>() | |
constructor(domNode: HTMLElement) { | |
this._host = domNode | |
var nodes: NodeListOf<HTMLElement> = domNode.querySelectorAll('[role="menuitem"]'); | |
for (var i = 0; i < nodes.length; i++) { | |
var menuitem = nodes[i]; | |
const fc = menuitem.textContent.trim()[0].toLowerCase() | |
this._firstChars.add(fc); | |
menuitem.dataset.focusKey = fc | |
} | |
} | |
setFocus(by: string) { | |
if (this.firstChars.has(by)) { | |
const detail = { | |
eventName: 'key', | |
data: by, | |
} | |
const event = new CustomEvent('focus-by', { bubbles: true, composed: true, cancelable: true, detail }) | |
this._host.dispatchEvent(event) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Screen Reader Only