feat: add AR launch hook

This commit is contained in:
rajun 2026-10-27 16:28:54 +05:30
parent 99a1ae969b
commit 20edecf598

View File

@ -0,0 +1,59 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';
import { AR_HINTS } from '~/data/ar-viewer/constants';
const HINT_DELAY_MS = 1500;
const HINT_INTERVAL_MS = 2000;
const FALLBACK_RESET_MS = 15000;
const SESSION_END_STATUSES = new Set(['session-started', 'object-placed', 'failed', 'not-presenting']);
interface ModelViewerElement extends HTMLElement {
activateAR?: () => void;
}
// Starts AR on a <model-viewer> and cycles loading hints until the session starts or fails
export function useArLaunch(viewerRef: RefObject<ModelViewerElement | null>) {
const [launching, setLaunching] = useState(false);
const [hint, setHint] = useState<string | null>(null);
const cleanupRef = useRef<(() => void) | null>(null);
useEffect(() => () => cleanupRef.current?.(), []);
const launch = useCallback(() => {
const viewer = viewerRef.current;
if (!viewer?.activateAR || cleanupRef.current) return;
setLaunching(true);
viewer.activateAR();
let hintIndex = 0;
let hintInterval: ReturnType<typeof setInterval> | undefined;
const hintDelay = setTimeout(() => {
setHint(AR_HINTS[0]);
hintInterval = setInterval(() => {
hintIndex = (hintIndex + 1) % AR_HINTS.length;
setHint(AR_HINTS[hintIndex] ?? null);
}, HINT_INTERVAL_MS);
}, HINT_DELAY_MS);
const onStatus = (event: Event) => {
const status = (event as CustomEvent<{ status?: string }>).detail?.status;
if (status && SESSION_END_STATUSES.has(status)) cleanup();
};
const fallback = setTimeout(() => cleanup(), FALLBACK_RESET_MS);
const cleanup = () => {
clearTimeout(hintDelay);
clearTimeout(fallback);
clearInterval(hintInterval);
viewer.removeEventListener('ar-status', onStatus);
cleanupRef.current = null;
setLaunching(false);
setHint(null);
};
viewer.addEventListener('ar-status', onStatus);
cleanupRef.current = cleanup;
}, [viewerRef]);
return { launch, launching, hint };
}