Files
Reims-Go/frontend/src/components/PluginPanelFrame.tsx
T

161 lines
6.4 KiB
TypeScript

import { AlertTriangle } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
import { Locale, PanelContribution } from '../types'
import { Button } from '../ui/controls'
import { api } from '../wails'
import { locText } from './SchemaForm'
interface Props {
locale: Locale
panel: Omit<PanelContribution, 'convertValues'>
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
/** Incrementing this reloads the iframe cleanly. */
refreshSignal?: number
}
/**
* Sandboxed L4 iframe panel verifying window identity (`event.source === iframe.contentWindow`
* and opaque `null` origin) and routing Host API calls through `PanelBridgeCall`.
*/
const RE_SAFE_TOKEN = /^[a-f0-9]+$/
const RE_SAFE_PLUGIN_ID = /^[a-z0-9][a-z0-9._-]*$/
const RE_SAFE_ENTRY_SEG = /^[a-zA-Z0-9._@ -]+$/
function buildSafePanelSrc(assetToken: string, pluginId: string | undefined, entry: string | undefined): string | null {
if (!assetToken || !RE_SAFE_TOKEN.test(assetToken)) return null
if (!pluginId || !RE_SAFE_PLUGIN_ID.test(pluginId) || pluginId.includes('..')) return null
const raw = (entry || 'index.html').trim().replace(/^\/+/, '')
if (!raw || raw.includes('\\') || raw.includes('?') || raw.includes('#') || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(raw)) {
return null
}
const segs = raw.split('/')
for (const seg of segs) {
if (!seg || seg === '.' || seg === '..' || !RE_SAFE_ENTRY_SEG.test(seg)) return null
}
return `/plugin-assets/${encodeURIComponent(assetToken)}/${encodeURIComponent(pluginId)}/${segs.map(encodeURIComponent).join('/')}`
}
export const PluginPanelFrame: React.FC<Props> = ({
locale, panel, assetToken, appearance, headless, maxHeight = 480, refreshSignal = 0,
}) => {
const iframeRef = useRef<HTMLIFrameElement>(null)
const localeRef = useRef<Locale>(locale)
localeRef.current = locale
const [failed, setFailed] = useState(false)
const [nonce, setNonce] = useState(0)
useEffect(() => {
if (refreshSignal > 0) {
setFailed(false)
setNonce((n) => n + 1)
}
}, [refreshSignal])
const src = buildSafePanelSrc(assetToken, panel.pluginId, panel.entry)
const syncTheme = () => {
const win = iframeRef.current?.contentWindow
if (!win) return
const cs = getComputedStyle(document.documentElement)
const tokens: Record<string, string> = {}
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)
// bridgeApi 1.0 events (bridgeContract.ts).
win.postMessage({ type: 'reims:event', event: 'theme.changed', data: { appearance, tokens } }, '*')
win.postMessage({ type: 'reims:event', event: 'locale.changed', data: { locale, dir, messages } }, '*')
// Pre-1.0 message types, kept for panels written before the bridge contract.
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 onMessage = async (e: MessageEvent) => {
const win = iframeRef.current?.contentWindow
// Require opaque origin and exact contentWindow identity for sandbox="allow-scripts".
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<string, unknown> =
rawParams && typeof rawParams === 'object' && !Array.isArray(rawParams)
? (rawParams as Record<string, unknown>)
: {}
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 api.PanelBridgeCall(panel.pluginId ?? '', msg.method, params)
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
window.removeEventListener('message', onMessage)
}
}, [panel.pluginId, nonce, src])
if (failed || !src) {
return (
<div className="notice notice-error" role="alert">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{t(locale, 'panelLoadFailed')}</span>
</span>
{src && (
<Button onClick={() => { setFailed(false); setNonce((n) => n + 1) }}>
{t(locale, 'installersRetry')}
</Button>
)}
</div>
)
}
return (
<div className={`plugin-panel-wrap rg-p-plugin-view${headless ? ' is-headless' : ''}`} data-plugin={panel.pluginId}>
{!headless && <div className="plugin-panel-head">{locText(panel.title, locale, panel.id)}</div>}
<iframe
key={nonce}
ref={iframeRef}
className="plugin-panel-frame"
title={locText(panel.title, locale, panel.id)}
src={src}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
style={{ height: Math.max(120, Math.min(maxHeight, panel.height || 220)) }}
onLoad={syncTheme}
onError={() => setFailed(true)}
/>
</div>
)
}