import { AlertTriangle } from 'lucide-react' import React, { useEffect, useRef, useState } from 'react' import { getPluginMessageBundle, localeDir, locText, parseAppError, t } from '../i18n' import { Locale, PanelContribution, ViewContribution } from '../types' import { Button } from '../ui/controls' import { ConfirmDialog } from '../ui/dialog' import { api } from '../wails' import { ClipboardSetText } from '../../wailsjs/runtime/runtime' import { createPluginTaskScope, initialFormValues, invokePluginViewAction, missingFormFields, PluginConfirmRequest, PluginFormRequest, PluginFormResult, } from '../lib/pluginViewActions' import { buildSafePluginAssetURL } from '../lib/pluginAssets' import { subscribePluginHostEvents } from '../lib/pluginViewEvents' import { SchemaForm } from './SchemaForm' interface Props { locale: Locale panel: Omit assetToken: string appearance: 'light' | 'dark' /** Omit the panel title bar (e.g. when hosted inside a tab/segmented view). */ headless?: boolean /** Upper bound for the iframe height in px (defaults to 480 for inline panels). */ maxHeight?: number /** Narrower containers scroll horizontally instead of shrinking the page below this width. */ minWidth?: number /** Incrementing this reloads the iframe cleanly. */ refreshSignal?: number viewLocation?: ViewContribution['location'] vm?: string onOpenView?: (view: ViewContribution, vm?: string) => void onCloseView?: () => { closed: boolean } onNavigate?: (target: { page?: string; vm?: string }) => void onMetadata?: (metadata: { title?: string; badge?: { text: string; tone: string } }) => void } /** Sandboxed plugin frame with identity-checked host RPC and local UI effects. */ export const PluginPanelFrame: React.FC = ({ locale, panel, assetToken, appearance, headless, maxHeight = 480, minWidth, refreshSignal = 0, viewLocation, vm, onOpenView, onCloseView, onNavigate, onMetadata, }) => { const iframeRef = useRef(null) const wrapperRef = useRef(null) const localeRef = useRef(locale) localeRef.current = locale const [failed, setFailed] = useState(false) const [nonce, setNonce] = useState(0) const [titleOverride, setTitleOverride] = useState(null) const [badge, setBadge] = useState<{ text: string; tone: string } | null>(null) const metadataRef = useRef<{ title?: string; badge?: { text: string; tone: string } }>({}) const actionContextRef = useRef({ vm, onOpenView, onCloseView, onNavigate, onMetadata }) actionContextRef.current = { vm, onOpenView, onCloseView, onNavigate, onMetadata } const [confirmRequest, setConfirmRequest] = useState(null) const confirmResolverRef = useRef<((confirmed: boolean) => void) | null>(null) const [formRequest, setFormRequest] = useState(null) const [formError, setFormError] = useState('') const formResolverRef = useRef<((result: PluginFormResult) => void) | null>(null) const subscriptionsRef = useRef>(new Set()) const intersectingRef = useRef(true) const lastVisibilityRef = useRef(null) const src = buildSafePluginAssetURL(assetToken, panel.pluginId, panel.entry) const title = titleOverride || locText(panel.title, locale, panel.id) const updateMetadata = (patch: { title?: string; badge?: { text: string; tone: string } }) => { metadataRef.current = { ...metadataRef.current, ...patch } if (patch.title !== undefined) setTitleOverride(patch.title) if ('badge' in patch) setBadge(patch.badge ?? null) actionContextRef.current.onMetadata?.(metadataRef.current) } const finishConfirmation = (confirmed: boolean) => { const resolve = confirmResolverRef.current confirmResolverRef.current = null setConfirmRequest(null) resolve?.(confirmed) } const requestConfirmation = (request: PluginConfirmRequest) => new Promise((resolve, reject) => { if (confirmResolverRef.current || formResolverRef.current) { reject(new Error('A plugin dialog is already pending')) return } confirmResolverRef.current = resolve setConfirmRequest(request) }) const finishForm = (confirmed: boolean) => { const resolve = formResolverRef.current formResolverRef.current = null const values = formRequest?.values setFormRequest(null) resolve?.(confirmed ? { confirmed: true, values } : { confirmed: false }) } const requestForm = (request: PluginFormRequest) => new Promise((resolve, reject) => { if (confirmResolverRef.current || formResolverRef.current) { reject(new Error('A plugin dialog is already pending')) return } formResolverRef.current = resolve setFormError('') setFormRequest({ ...request, values: initialFormValues(request.schema, request.values) }) }) const submitForm = (e: React.MouseEvent, request: PluginFormRequest) => { const missing = missingFormFields(request.schema, request.values) if (missing.length === 0) { finishForm(true) return } e.preventDefault() const fields = missing.map((key) => locText(request.schema.properties?.[key]?.title, locale, key)).join(', ') setFormError(t(locale, 'formRequiredFields', { fields })) } const emitVisibility = (reason: string, force = false) => { const visible = !document.hidden && intersectingRef.current if (!force && lastVisibilityRef.current === visible) return lastVisibilityRef.current = visible if (!subscriptionsRef.current.has('view.visibilityChanged')) return iframeRef.current?.contentWindow?.postMessage({ type: 'reims:event', event: 'view.visibilityChanged', data: { visible, reason }, }, '*') } const subscribe = (events: string[]) => { for (const event of events) subscriptionsRef.current.add(event) if (events.includes('view.visibilityChanged')) emitVisibility('subscribe', true) } const unsubscribe = (events: string[]) => { if (events.length === 0) subscriptionsRef.current.clear() else for (const event of events) subscriptionsRef.current.delete(event) } useEffect(() => { setConfirmRequest(null) setFormRequest(null) subscriptionsRef.current.clear() lastVisibilityRef.current = null return () => { confirmResolverRef.current?.(false) confirmResolverRef.current = null formResolverRef.current?.({ confirmed: false }) formResolverRef.current = null } }, [src, nonce]) useEffect(() => { if (refreshSignal > 0) { setFailed(false) setNonce((n) => n + 1) } }, [refreshSignal]) useEffect(() => { const onVisibility = () => emitVisibility('document') document.addEventListener('visibilitychange', onVisibility) const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver((entries) => { intersectingRef.current = entries[0]?.isIntersecting ?? true emitVisibility('viewport') }) if (wrapperRef.current) observer?.observe(wrapperRef.current) emitVisibility('mount', true) return () => { document.removeEventListener('visibilitychange', onVisibility) observer?.disconnect() subscriptionsRef.current.clear() } }, [src, nonce]) useEffect(() => subscribePluginHostEvents((event, data) => { if (!subscriptionsRef.current.has(event)) return if (event === 'task.updated') { const task = data as { kind?: string } if (task.kind !== `plugin:${panel.pluginId}`) return } iframeRef.current?.contentWindow?.postMessage({ type: 'reims:event', event, data }, '*') }), [panel.pluginId, nonce, src]) const syncTheme = () => { const win = iframeRef.current?.contentWindow if (!win) return const cs = getComputedStyle(document.documentElement) const tokens: Record = {} for (const k of ['--surface-0', '--surface-1', '--text', '--text-2', '--border', '--accent', '--font-sans']) { tokens[k] = cs.getPropertyValue(k).trim() } const dir = localeDir(locale) const messages = getPluginMessageBundle(panel.pluginId ?? '', locale) win.postMessage({ type: 'reims:event', event: 'theme.changed', data: { appearance, tokens } }, '*') win.postMessage({ type: 'reims:event', event: 'locale.changed', data: { locale, dir, messages } }, '*') win.postMessage({ type: 'reims:theme', appearance, locale, dir, tokens, messages }, '*') win.postMessage({ type: 'reims:i18n', locale, dir, messages }, '*') } useEffect(() => { syncTheme() // eslint-disable-next-line react-hooks/exhaustive-deps }, [appearance, locale]) useEffect(() => { if (!src) return let cancelled = false const taskScope = createPluginTaskScope((method, input) => api.PanelBridgeCall(panel.pluginId ?? '', method, input)) const onMessage = async (e: MessageEvent) => { const win = iframeRef.current?.contentWindow if (!win || e.source !== win || e.origin !== 'null') return const msg = e.data if (!msg || typeof msg !== 'object' || msg.type !== 'reims:rpc' || typeof msg.id !== 'string' || typeof msg.method !== 'string') return const rawParams = msg.params const params: Record = rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams) ? rawParams : {} try { if (msg.method === 'i18n.getBundle') { const curLocale = localeRef.current const bundle = { locale: curLocale, dir: localeDir(curLocale), messages: getPluginMessageBundle(panel.pluginId ?? '', curLocale) } win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result: bundle }, '*') return } const result = await invokePluginViewAction(msg.method, params, { invoke: taskScope.invoke, confirm: requestConfirmation, showForm: requestForm, copy: async (text) => { if (!await ClipboardSetText(text)) throw new Error('The clipboard is unavailable') }, setTitle: (nextTitle) => updateMetadata({ title: nextTitle }), setBadge: (text, tone) => updateMetadata({ badge: text ? { text, tone } : undefined }), openView: (view, targetVM) => { const context = actionContextRef.current if (!context.onOpenView) throw new Error('not_supported') context.onOpenView(view, targetVM ?? context.vm) }, close: async () => { const context = actionContextRef.current if (!context.onCloseView) throw new Error('not_supported') return context.onCloseView() }, navigate: (target) => { const context = actionContextRef.current if (!context.onNavigate) throw new Error('not_supported') context.onNavigate(target) }, subscribe, unsubscribe, }) if (cancelled || iframeRef.current?.contentWindow !== win) return win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: true, result }, '*') } catch (err) { if (cancelled || iframeRef.current?.contentWindow !== win) return win.postMessage({ type: 'reims:rpc-result', id: msg.id, ok: false, error: parseAppError(err).summary || 'RPC failed' }, '*') } } window.addEventListener('message', onMessage) return () => { cancelled = true taskScope.close() window.removeEventListener('message', onMessage) } }, [panel.pluginId, nonce, src]) if (failed || !src) { return (
{src && }
) } return (
{!headless && (
{title} {badge && {badge.text}}
)}