@workday/canvas-kit-react
Version:
The parent module that contains all Workday Canvas Kit React components
46 lines (45 loc) • 2.15 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.focusOnCurrentCursor = void 0;
// retry a function each frame so we don't rely on the timing mechanism of React's render cycle.
const retryEachFrame = (cb, iterations, reject) => {
if (cb() === false && iterations > 1) {
requestAnimationFrame(() => retryEachFrame(cb, iterations - 1));
}
reject === null || reject === void 0 ? void 0 : reject('Retry timeout');
};
const focusOnCurrentCursor = (model, nextId,
/**
* This can be any element in the list. It is used only to get the client-id from the element in
* case it is different than the server ID when DOM is hydrated.
*/
element) => {
return new Promise((resolve, reject) => {
var _a;
// Attempt to extract the ID from the DOM element. This fixes issues where the server and client
// do not agree on a generated ID
const clientId = (((_a = element === null || element === void 0 ? void 0 : element.dataset) === null || _a === void 0 ? void 0 : _a.focusId) || '').split('-')[0] || model.state.id;
const item = model.navigation.getItem(nextId, model);
if (item) {
// If the list is virtualized, we need to manually call out to the virtual list's
// `scrollToIndex`
if (model.state.isVirtualized) {
model.state.UNSTABLE_virtual.scrollToIndex(item.index);
}
const getElement = (id) => {
return document.querySelector(`[data-focus-id="${`${id}-${item.id}`}"]`);
};
// In React concurrent mode, there could be several render attempts before the element we're
// looking for could be available in the DOM
retryEachFrame(() => {
const element = getElement(clientId) || getElement(model.state.id);
if (element) {
element.focus();
resolve(element);
}
return !!element;
}, 5, reject); // 5 should be enough, right?!
}
});
};
exports.focusOnCurrentCursor = focusOnCurrentCursor;
;