arrowtab
Version:
Use arrow keys to "tab" between focusable elements
60 lines • 1.85 kB
JavaScript
const focusHistory = [];
let historyCandidate;
export const setHistoryCandidate = ({ element }) => {
if (!(element instanceof HTMLElement)) {
return;
}
historyCandidate = element;
};
export const pushCandidateIntoHistory = () => {
if (historyCandidate) {
focusHistory.push(historyCandidate);
}
};
export const focusPrevious = () => {
const lastHistoryElement = focusHistory.pop();
if (lastHistoryElement) {
lastHistoryElement.focus();
}
};
export const startAutoDetectHistory = ({ active }) => {
if (!active) {
return {
cleanup: () => { },
};
}
let dialogObserver = null;
// TODO: Support multiple dialogs
let lastDialogElement = null;
dialogObserver = new MutationObserver((mutationList) => {
for (const mutation of mutationList) {
if (mutation.type === 'childList') {
for (const node of mutation.addedNodes) {
if (node.nodeType === 1 &&
node instanceof HTMLElement &&
node.getAttribute('role') === 'dialog') {
lastDialogElement = node;
pushCandidateIntoHistory();
}
}
for (const node of mutation.removedNodes) {
if (node === lastDialogElement || node.contains(lastDialogElement)) {
lastDialogElement = null;
focusPrevious();
return;
}
}
}
}
});
dialogObserver.observe(document.body, {
childList: true,
subtree: true,
});
return {
cleanup: () => {
dialogObserver?.disconnect();
},
};
};
//# sourceMappingURL=focusHistory.js.map