App.tsx imported a one-line helper from SchemaForm, which pulled both text domains into the startup bundle. The i18n test now follows the real import graph instead of a hand-kept file list, so it catches this. npm test runs every test file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
333 lines
14 KiB
TypeScript
333 lines
14 KiB
TypeScript
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<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
|
|
/** 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<Props> = ({
|
|
locale, panel, assetToken, appearance, headless, maxHeight = 480, minWidth, refreshSignal = 0,
|
|
viewLocation, vm, onOpenView, onCloseView, onNavigate, onMetadata,
|
|
}) => {
|
|
const iframeRef = useRef<HTMLIFrameElement>(null)
|
|
const wrapperRef = useRef<HTMLDivElement>(null)
|
|
const localeRef = useRef<Locale>(locale)
|
|
localeRef.current = locale
|
|
const [failed, setFailed] = useState(false)
|
|
const [nonce, setNonce] = useState(0)
|
|
const [titleOverride, setTitleOverride] = useState<string | null>(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<PluginConfirmRequest | null>(null)
|
|
const confirmResolverRef = useRef<((confirmed: boolean) => void) | null>(null)
|
|
const [formRequest, setFormRequest] = useState<PluginFormRequest | null>(null)
|
|
const [formError, setFormError] = useState('')
|
|
const formResolverRef = useRef<((result: PluginFormResult) => void) | null>(null)
|
|
const subscriptionsRef = useRef<Set<string>>(new Set())
|
|
const intersectingRef = useRef(true)
|
|
const lastVisibilityRef = useRef<boolean | null>(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<boolean>((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<PluginFormResult>((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<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)
|
|
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<string, unknown> = 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 (
|
|
<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 ref={wrapperRef} className={`plugin-panel-wrap rg-p-plugin-view${headless ? ' is-headless' : ''}`} data-plugin={panel.pluginId} data-view-location={viewLocation} style={minWidth ? { overflowX: 'auto' } : undefined}>
|
|
{!headless && (
|
|
<div className="plugin-panel-head">
|
|
<span>{title}</span>
|
|
{badge && <span className={`badge rg-p-badge badge-${badge.tone === 'ok' ? 'ok' : badge.tone === 'warn' ? 'warn' : badge.tone === 'error' ? 'error' : 'idle'}`}>{badge.text}</span>}
|
|
</div>
|
|
)}
|
|
<iframe
|
|
key={nonce}
|
|
ref={iframeRef}
|
|
className="plugin-panel-frame"
|
|
title={title}
|
|
src={src}
|
|
sandbox="allow-scripts"
|
|
referrerPolicy="no-referrer"
|
|
style={{ height: Math.max(120, Math.min(maxHeight, panel.height || 220)), minWidth }}
|
|
onLoad={syncTheme}
|
|
onError={() => setFailed(true)}
|
|
/>
|
|
{confirmRequest && (
|
|
<ConfirmDialog
|
|
title={confirmRequest.title || title}
|
|
description={confirmRequest.message}
|
|
confirmLabel={confirmRequest.confirmLabel || t(locale, 'confirm')}
|
|
cancelLabel={confirmRequest.cancelLabel || t(locale, 'cancel')}
|
|
tone={confirmRequest.danger ? 'danger' : 'neutral'}
|
|
onCancel={() => finishConfirmation(false)}
|
|
onConfirm={() => finishConfirmation(true)}
|
|
/>
|
|
)}
|
|
{formRequest && (
|
|
<ConfirmDialog
|
|
title={formRequest.title}
|
|
description={formRequest.message || ''}
|
|
confirmLabel={formRequest.confirmLabel || t(locale, 'confirm')}
|
|
cancelLabel={formRequest.cancelLabel || t(locale, 'cancel')}
|
|
tone={formRequest.danger ? 'danger' : 'neutral'}
|
|
onCancel={() => finishForm(false)}
|
|
onConfirm={(e) => submitForm(e, formRequest)}
|
|
>
|
|
<SchemaForm
|
|
locale={locale}
|
|
schema={formRequest.schema}
|
|
values={formRequest.values}
|
|
hideGroupHeader
|
|
onChange={(next) => {
|
|
setFormError('')
|
|
setFormRequest((current) => current ? { ...current, values: next } : current)
|
|
}}
|
|
/>
|
|
{formError && <div className="notice notice-error" role="alert">{formError}</div>}
|
|
</ConfirmDialog>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|