Refactor command center and focus handling
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
let focusRestoreElement: HTMLElement | null = null;
|
||||
|
||||
export function setCommandCenterFocusRestoreElement(el: HTMLElement | null): void {
|
||||
focusRestoreElement = el;
|
||||
}
|
||||
|
||||
export function takeCommandCenterFocusRestoreElement(): HTMLElement | null {
|
||||
const el = focusRestoreElement;
|
||||
focusRestoreElement = null;
|
||||
return el;
|
||||
}
|
||||
|
||||
export function clearCommandCenterFocusRestoreElement(): void {
|
||||
focusRestoreElement = null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
type FocusWithRetriesOptions = {
|
||||
focus: () => void;
|
||||
isFocused: () => boolean;
|
||||
timeoutMs?: number;
|
||||
onSuccess?: () => void;
|
||||
onTimeout?: () => void;
|
||||
};
|
||||
|
||||
export function focusWithRetries({
|
||||
focus,
|
||||
isFocused,
|
||||
timeoutMs = 1500,
|
||||
onSuccess,
|
||||
onTimeout,
|
||||
}: FocusWithRetriesOptions): () => void {
|
||||
let cancelled = false;
|
||||
const deadlineMs = Date.now() + timeoutMs;
|
||||
|
||||
const tick = () => {
|
||||
if (cancelled) return;
|
||||
|
||||
try {
|
||||
focus();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
if (isFocused()) {
|
||||
onSuccess?.();
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() >= deadlineMs) {
|
||||
onTimeout?.();
|
||||
return;
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(tick);
|
||||
});
|
||||
};
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(tick);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user