All files / views/webviews/hooks use-webview-messaging.ts

0% Statements 0/5
0% Branches 0/8
0% Functions 0/2
0% Lines 0/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44                                                                                       
import { useEffect, useRef } from 'react';
import { WebviewMessaging, WebviewMessage } from '../webview-messaging';
import { WebviewHost } from '../webview-host';
 
/**
 * React hook for webview messaging. Provides the full messaging interface including
 * `postMessage`, `onMessage`, and `executeCommand`.
 *
 * @example
 * ```tsx
 * function MyComponent() {
 *   const messaging = useWebviewMessaging<MyMessages>(message => {
 *     if (message.id === 'DataLoaded') {
 *       setData(message.data);
 *     }
 *   });
 *
 *   const handleClick = () => {
 *     messaging?.postMessage({ id: 'LoadData' });
 *   };
 * }
 * ```
 *
 * @param onMessage Callback invoked when a message is received from the extension host.
 * @param messaging Optional custom messaging instance. If not provided, uses WebviewHost (must be in webview context).
 * @returns The WebviewMessaging interface, or undefined if not in a webview context and no messaging was provided.
 */
export function useWebviewMessaging<M extends WebviewMessage>(
	onMessage?: (message: M) => void,
	messaging?: WebviewMessaging<M>
): WebviewMessaging<M> | undefined {
	const messagingRef = useRef<WebviewMessaging<M> | undefined>(
		messaging ?? (WebviewHost.isAvailable() ? WebviewHost.getMessaging<M>() : undefined)
	);
 
	useEffect(() => {
		if (onMessage && messagingRef.current) {
			return messagingRef.current.onMessage(onMessage);
		}
	}, [onMessage]);
 
	return messagingRef.current;
}