From cbeeb9939d6025d13a60614ed299c2d4e1c31260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marius=20Lundga=CC=8Ard?= Date: Tue, 12 Sep 2023 13:17:20 +0200 Subject: [PATCH] feat(composer): print message log from iframe --- packages/composer/src/ComposerTool.tsx | 36 +++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/packages/composer/src/ComposerTool.tsx b/packages/composer/src/ComposerTool.tsx index 317ceba1c..2641291ec 100644 --- a/packages/composer/src/ComposerTool.tsx +++ b/packages/composer/src/ComposerTool.tsx @@ -1,5 +1,5 @@ -import { ReactElement } from 'react' -import { Tool } from 'sanity' +import { ReactElement, useEffect, useRef, useState } from 'react' +import { isRecord, Tool } from 'sanity' import { ComposerPluginOptions } from './types' @@ -8,5 +8,35 @@ export default function ComposerTool(props: { }): ReactElement { const { tool } = props - return
ComposerTool: {tool.options?.previewUrl}
+ const iframeRef = useRef(null) + + const [log, setLog] = useState([]) + + useEffect(() => { + const iframe = iframeRef.current + + if (!iframe) return + + function handleMessage(event: MessageEvent) { + if (event.origin !== location.origin) return + + if (isRecord(event.data) && event.data.sanity === true) { + setLog((l) => l.concat(event.data)) + } + } + + window.addEventListener('message', handleMessage) + + return () => { + window.removeEventListener('message', handleMessage) + } + }, []) + + return ( +
+ ComposerTool + +
{JSON.stringify(log, null, 2)}
+
+ ) }