( iframeRef: React.RefObject<HTMLIFrameElement | null>, options?: PickerOptions, )
| 44 | * Communicates with the iframe via postMessage. |
| 45 | */ |
| 46 | export function useElementPicker( |
| 47 | iframeRef: React.RefObject<HTMLIFrameElement | null>, |
| 48 | options?: PickerOptions, |
| 49 | ): UseElementPickerReturn { |
| 50 | const [isPickMode, setIsPickMode] = useState(false); |
| 51 | const [pickedElement, setPickedElement] = useState<PickedElement | null>(null); |
| 52 | |
| 53 | // Secondary/override iframe ref — set when a zoomed frame is active. |
| 54 | // When set, all postMessage sends and DOM reads go to this ref instead. |
| 55 | const activeOverrideRef = useRef<HTMLIFrameElement | null>(null); |
| 56 | |
| 57 | const getActiveIframe = useCallback((): HTMLIFrameElement | null => { |
| 58 | return activeOverrideRef.current ?? iframeRef.current; |
| 59 | }, [iframeRef]); |
| 60 | |
| 61 | // Exposed so the host page can wire the focused view's iframe into the picker |
| 62 | const setActiveIframe = useCallback((el: HTMLIFrameElement | null) => { |
| 63 | activeOverrideRef.current = el; |
| 64 | }, []); |
| 65 | |
| 66 | const enablePick = useCallback(() => { |
| 67 | try { |
| 68 | getActiveIframe()?.contentWindow?.postMessage( |
| 69 | { source: "hf-parent", type: "control", action: "enable-pick-mode" }, |
| 70 | "*", |
| 71 | ); |
| 72 | setIsPickMode(true); |
| 73 | } catch { |
| 74 | /* cross-origin */ |
| 75 | } |
| 76 | }, [getActiveIframe]); |
| 77 | |
| 78 | const disablePick = useCallback(() => { |
| 79 | try { |
| 80 | getActiveIframe()?.contentWindow?.postMessage( |
| 81 | { source: "hf-parent", type: "control", action: "disable-pick-mode" }, |
| 82 | "*", |
| 83 | ); |
| 84 | } catch { |
| 85 | /* cross-origin */ |
| 86 | } |
| 87 | setIsPickMode(false); |
| 88 | }, [getActiveIframe]); |
| 89 | |
| 90 | const clearPick = useCallback(() => { |
| 91 | setPickedElement(null); |
| 92 | }, []); |
| 93 | |
| 94 | // Listen for picker messages from the iframe |
| 95 | useMountEffect(() => { |
| 96 | const handleMessage = (e: MessageEvent) => { |
| 97 | const data = e.data; |
| 98 | if (data?.source !== "hf-preview") return; |
| 99 | // Accept events from either the primary iframe or the active override |
| 100 | const activeIframe = getActiveIframe(); |
| 101 | if (!activeIframe) return; |
| 102 | if (e.source !== activeIframe.contentWindow && e.source !== iframeRef.current?.contentWindow) |
| 103 | return; |
nothing calls this directly
no test coverage detected