From 20edecf598d0f7196f9182a2f34c2925bc4e6cce Mon Sep 17 00:00:00 2001 From: rajun Date: Tue, 27 Oct 2026 16:28:54 +0530 Subject: [PATCH] feat: add AR launch hook --- app/hooks/ar-viewer/use-ar-launch.ts | 59 ++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 app/hooks/ar-viewer/use-ar-launch.ts diff --git a/app/hooks/ar-viewer/use-ar-launch.ts b/app/hooks/ar-viewer/use-ar-launch.ts new file mode 100644 index 0000000..8fddc95 --- /dev/null +++ b/app/hooks/ar-viewer/use-ar-launch.ts @@ -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 and cycles loading hints until the session starts or fails +export function useArLaunch(viewerRef: RefObject) { + const [launching, setLaunching] = useState(false); + const [hint, setHint] = useState(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 | 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 }; +}