forked from rajun/ar-test
60 lines
2.1 KiB
TypeScript
60 lines
2.1 KiB
TypeScript
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 };
|
|
}
|