Skip to content

Commit

Permalink
feat(composer): print message log from iframe
Browse files Browse the repository at this point in the history
  • Loading branch information
mariuslundgard committed Sep 12, 2023
1 parent e00e9ea commit cbeeb99
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions packages/composer/src/ComposerTool.tsx
Original file line number Diff line number Diff line change
@@ -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'

Expand All @@ -8,5 +8,35 @@ export default function ComposerTool(props: {
}): ReactElement {
const { tool } = props

return <div>ComposerTool: {tool.options?.previewUrl}</div>
const iframeRef = useRef<HTMLIFrameElement>(null)

const [log, setLog] = useState<string[]>([])

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 (
<div>
ComposerTool
<iframe ref={iframeRef} src={tool.options?.previewUrl || '/'}></iframe>
<pre>{JSON.stringify(log, null, 2)}</pre>
</div>
)
}

0 comments on commit cbeeb99

Please sign in to comment.