import React, { createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
import { PluginViewPopover } from './PluginViewPopover';
import { PluginSplitPane } from './primitives/PluginSplitPane';
import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } from './primitives/PluginWidgetRenderer';
import type { PluginSplitPaneWidgetProps } from './primitives/types';
import { createPortal } from 'react-dom';
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
type RemoteElementNode = {
id: string; type: 1; element: string; attributes: Record; children: RemoteNode[];
};
type RemoteNode = { id: string; type: 3; data: string } | { id: string; type: 8; data: string } | RemoteElementNode;
export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnViewEvent;
const MAX_EVENT_VALUE_LENGTH = 131072;
const SCROLL_THROTTLE_MS = 60;
const SURFACE_EVENTS = [
'click', 'dblclick', 'contextmenu',
'input', 'change',
'keydown', 'keyup',
'focusin', 'focusout',
'compositionstart', 'compositionupdate', 'compositionend',
'submit', 'reset',
'scroll',
] as const;
const SURFACE_EVENT_SET = new Set(SURFACE_EVENTS);
const SLOTTED_WIDGET_KINDS = new Set(['code-editor', 'data-grid', 'er-canvas']);
const ATTRIBUTE_NAMES: Record = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' };
const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']);
const preventFormSubmit = (event: React.FormEvent) => event.preventDefault();
const SurfaceContext = createContext<{
css: string;
onEvent(event: PluginSurfaceEvent): void;
depth: number;
shadowHost: HTMLDivElement | null;
}>({ css: '', onEvent: () => {}, depth: 0, shadowHost: null });
function remoteText(nodes: RemoteNode[]): string {
return nodes.map((node) => (node.type === 3 ? node.data : node.type === 1 ? remoteText(node.children) : '')).join('');
}
function parseOptionalNumber(raw: string | undefined): number | undefined {
if (raw === undefined || raw === '') return undefined;
const parsed = Number(raw);
return Number.isFinite(parsed) ? parsed : undefined;
}
const ResourceLoader = createContext<((path: string) => Promise) | undefined>(undefined);
function buildRemoteElementProps(node: RemoteElementNode): Record {
const props: Record = { 'data-netcatty-remote-node': node.id };
let inlineStyle: string | undefined;
for (const [name, value] of Object.entries(node.attributes)) {
if (name === 'src' || (node.element === 'option' && name === 'selected')) continue;
if (name === 'style') { inlineStyle = value; continue; }
if (name === 'data-netcatty-remote-node') continue;
props[ATTRIBUTE_NAMES[name] ?? name] = BOOLEAN_ATTRIBUTES.has(name) ? true : value;
}
// The policy validated this declaration list before this component rendered.
props.ref = (el: HTMLElement | null) => { if (el) { if (inlineStyle === undefined) el.removeAttribute('style'); else el.setAttribute('style', inlineStyle); } };
if (node.element === 'form') props.onSubmit = preventFormSubmit;
return props;
}
const RemotePopoverElement = memo(function RemotePopoverElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
const surface = useContext(SurfaceContext);
const loadImage = useContext(ResourceLoader);
if (surface.depth >= 1) return null;
const attrs = node.attributes;
return (
surface.onEvent({ nodeId: node.id, type: 'dismiss' })}
>
);
});
const RemoteSplitPaneElement = memo(function RemoteSplitPaneElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
const surface = useContext(SurfaceContext);
const parsed = useMemo(
() => parseWidgetPropsJson(node.attributes['data-plugin-widget-props']),
[node.attributes['data-plugin-widget-props']],
);
const elementChildren = node.children.filter((child) => child.type === 1 || (child.type === 3 && child.data.length > 0));
const firstChild = elementChildren[0] ? renderRemoteNode(elementChildren[0], settled) : null;
const secondChild = elementChildren[1] ? renderRemoteNode(elementChildren[1], settled) : null;
const emit = useCallback(
(widgetEvent: string, detail?: Record) => {
surface.onEvent({
nodeId: node.id,
type: 'widget',
widgetEvent,
detail: detail as PluginSurfaceEvent['detail'],
});
},
[surface.onEvent, node.id],
);
return (
);
});
const RemoteSlottedWidgetElement = memo(function RemoteSlottedWidgetElement({ node, kind }: { node: RemoteElementNode; kind: SlottedWidgetKind }): React.ReactNode {
const surface = useContext(SurfaceContext);
const slotName = `nc-widget-${node.id}`;
const emit = useCallback(
(widgetEvent: string, detail?: Record) => {
surface.onEvent({
nodeId: node.id,
type: 'widget',
widgetEvent,
detail: detail as PluginSurfaceEvent['detail'],
});
},
[surface.onEvent, node.id],
);
const wrapperProps = buildRemoteElementProps(node);
const origRef = wrapperProps.ref as ((el: HTMLElement | null) => void) | undefined;
const hasExplicitStyle = Object.hasOwn(node.attributes, 'style');
wrapperProps.ref = (el: HTMLElement | null) => {
origRef?.(el);
if (el && !hasExplicitStyle) {
el.setAttribute('style', 'display:flex;flex-direction:column;width:100%;height:100%;min-width:0;min-height:0;overflow:hidden');
}
};
return (
<>
{React.createElement(
'div',
wrapperProps,
React.createElement('slot', { name: slotName, style: { display: 'contents' } }),
)}
{surface.shadowHost && createPortal(
,
surface.shadowHost,
)}
>
);
});
const resolvedImageCache = new WeakMap<(path: string) => Promise, Map>();
const IMAGE_RETRY_DELAYS_MS = [200, 600] as const;
function getCachedImageUrl(loader: ((path: string) => Promise) | undefined, imagePath: string | undefined): string | undefined {
if (!loader || !imagePath) return undefined;
return resolvedImageCache.get(loader)?.get(imagePath);
}
function setCachedImageUrl(loader: (path: string) => Promise, imagePath: string, url: string) {
let map = resolvedImageCache.get(loader);
if (!map) {
map = new Map();
resolvedImageCache.set(loader, map);
}
if (map.size >= 256) {
const oldest = map.keys().next().value;
if (oldest !== undefined) map.delete(oldest);
}
map.set(imagePath, url);
}
const RemoteImageElement = memo(function RemoteImageElement({ node }: { node: RemoteElementNode }): React.ReactNode {
const loadImage = useContext(ResourceLoader);
const imagePath = node.attributes.src?.slice(6);
const [imageUrl, setImageUrl] = useState(() => getCachedImageUrl(loadImage, imagePath));
useEffect(() => {
let cancelled = false;
let retryTimer: ReturnType | undefined;
const cached = getCachedImageUrl(loadImage, imagePath);
if (cached) {
setImageUrl(cached);
return () => { cancelled = true; };
}
setImageUrl(undefined);
if (imagePath && loadImage) {
const attemptLoad = (attempt: number) => {
void loadImage(imagePath).then((url) => {
if (cancelled) return;
setCachedImageUrl(loadImage, imagePath, url);
setImageUrl(url);
}).catch(() => {
if (cancelled) return;
const delay = IMAGE_RETRY_DELAYS_MS[attempt];
if (delay !== undefined) {
retryTimer = setTimeout(() => { if (!cancelled) attemptLoad(attempt + 1); }, delay);
}
});
};
attemptLoad(0);
}
return () => {
cancelled = true;
if (retryTimer !== undefined) clearTimeout(retryTimer);
};
}, [imagePath, loadImage]);
const props = buildRemoteElementProps(node);
props.src = imageUrl;
return React.createElement('img', props);
});
const RemoteSelectElement = memo(function RemoteSelectElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
const attrs = node.attributes;
const isMultiple = Object.hasOwn(attrs, 'multiple');
const remoteSelection = isMultiple
? JSON.stringify(node.children.filter((child) => child.type === 1 && child.element === 'option' && Object.hasOwn(child.attributes, 'selected')).map((child) => child.type === 1 ? child.attributes.value ?? remoteText(child.children).replace(/[\t\n\f\r ]+/g, ' ').trim() : ''))
: '[]';
const [localSelection, setLocalSelection] = useState(() => (isMultiple ? JSON.parse(remoteSelection) : []));
useEffect(() => { if (settled && isMultiple) setLocalSelection(JSON.parse(remoteSelection)); }, [isMultiple, remoteSelection, settled]);
const remoteValue = attrs.value;
const [localValue, setLocalValue] = useState(remoteValue ?? '');
useEffect(() => { if (settled && remoteValue !== undefined) setLocalValue(remoteValue); }, [remoteValue, settled]);
const props = buildRemoteElementProps(node);
if (isMultiple) props.value = localSelection;
else if (remoteValue !== undefined) props.value = localValue;
props.autoComplete = 'off';
props.onChange = (event: React.ChangeEvent) => {
setLocalValue(event.currentTarget.value);
if (event.currentTarget.multiple) setLocalSelection([...event.currentTarget.selectedOptions].map((option) => option.value));
};
return React.createElement('select', props, ...node.children.map((child) => renderRemoteNode(child, settled)));
});
const RemoteInputElement = memo(function RemoteInputElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
const attrs = node.attributes;
const remoteValue = attrs.value ?? (node.element === 'textarea' ? remoteText(node.children) : undefined);
const remoteChecked = Object.hasOwn(attrs, 'checked');
const [localValue, setLocalValue] = useState(remoteValue ?? '');
const [localChecked, setLocalChecked] = useState(remoteChecked);
useEffect(() => { if (settled && remoteValue !== undefined) setLocalValue(remoteValue); }, [remoteValue, settled]);
useEffect(() => { if (settled) setLocalChecked(remoteChecked); }, [remoteChecked, settled]);
const props = buildRemoteElementProps(node);
if (remoteValue !== undefined) props.value = localValue;
props.autoComplete = 'off';
if (node.element === 'input' && ['checkbox', 'radio'].includes(attrs.type ?? '')) props.checked = localChecked;
props.onChange = (event: React.ChangeEvent) => {
setLocalValue(event.currentTarget.value);
if (event.currentTarget instanceof event.currentTarget.ownerDocument.defaultView!.HTMLInputElement) setLocalChecked(event.currentTarget.checked);
};
// React treats textarea text specially; do not wrap it in components.
return React.createElement(node.element, props);
});
const RemotePlainElement = memo(function RemotePlainElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
const props = buildRemoteElementProps(node);
// React treats option text specially; do not wrap it in components.
if (node.element === 'option') return React.createElement(node.element, props, remoteText(node.children));
return React.createElement(node.element, props, ...node.children.map((child) => renderRemoteNode(child, settled)));
});
function renderRemoteNode(node: RemoteNode, settled: boolean): React.ReactNode {
if (node.type === 3) return node.data;
if (node.type === 8) return null;
if (node.attributes['data-plugin-popover'] === 'true') return ;
const widgetKind = node.attributes['data-plugin-widget'];
if (widgetKind === 'split-pane') return ;
if (widgetKind && SLOTTED_WIDGET_KINDS.has(widgetKind)) {
return ;
}
if (node.element === 'img') return ;
if (node.element === 'select') return ;
if (node.element === 'input' || node.element === 'textarea') return ;
return ;
}
function readSelectionRange(
target: HTMLElement,
view: Window & typeof globalThis,
): { selectionStart: number; selectionEnd: number } | undefined {
const isTextInput =
target instanceof view.HTMLTextAreaElement
|| (target instanceof view.HTMLInputElement && ['text', 'search', 'url', 'tel', 'password', ''].includes(target.type));
if (!isTextInput) return undefined;
try {
const start = target.selectionStart;
const end = target.selectionEnd;
if (typeof start === 'number' && typeof end === 'number' && Number.isFinite(start) && Number.isFinite(end)) {
return {
selectionStart: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(start))),
selectionEnd: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(end))),
};
}
} catch {
// Non-selectable input types throw InvalidStateError.
}
return undefined;
}
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise; onEvent(event: PluginSurfaceEvent): void }) {
const checked = useMemo(() => {
try {
validatePluginRemoteTree(tree);
return { tree: tree as { children: RemoteNode[] }, css: validatePluginStylesheet(css) };
} catch { return null; }
}, [tree, css]);
if (!checked) return Unable to display plugin view.
;
return (
Unable to display plugin view.
}>
);
}
const SHADOW_BASE_SCROLLBAR_CSS = [
'*::-webkit-scrollbar{width:6px;height:6px}',
'*::-webkit-scrollbar-track,*::-webkit-scrollbar-corner{background:transparent}',
'*::-webkit-scrollbar-thumb{min-height:28px;border:1px solid transparent;border-radius:999px;background-color:transparent;background-clip:content-box}',
'*:hover::-webkit-scrollbar-thumb{background-color:hsl(var(--muted-foreground) / 0.24)}',
'*::-webkit-scrollbar-thumb:hover{background-color:hsl(var(--muted-foreground) / 0.45)}',
].join('');
function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { settled: boolean; depth: number; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) {
const surfaceRef = useRef(null);
const hostRef = useRef(null);
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
const shadowRef = useRef(null);
const [shadow, setShadow] = useState(null);
const [shadowHost, setShadowHost] = useState(null);
useLayoutEffect(() => {
const host = hostRef.current;
if (!host) return;
// The same DOM node can be mounted twice in React Strict Mode.
const root = shadowRef.current ?? host.attachShadow({ mode: 'closed' });
shadowRef.current = root;
setShadow(root);
setShadowHost(host);
}, []);
const surfaceContextValue = useMemo(
() => ({ css, onEvent, depth, shadowHost }),
[css, onEvent, depth, shadowHost],
);
useEffect(() => {
if (!shadow) return;
const scrollTimers = new Map>();
const pendingScroll = new Map();
const flushScroll = (nodeId: string) => {
scrollTimers.delete(nodeId);
const evt = pendingScroll.get(nodeId);
if (evt) {
pendingScroll.delete(nodeId);
onEventRef.current(evt);
}
};
const listener = (event: Event) => {
const target = event.target;
const view = shadow.ownerDocument.defaultView;
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
// Closed-shadow events hide their editable target from window capture.
if (event.type === 'focusin') {
hostRef.current?.toggleAttribute(
'data-plugin-editing',
target.matches('input, textarea, select, [contenteditable]') || Boolean(target.closest('.monaco-editor')),
);
}
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
if (target.closest('[data-plugin-widget-host]')) return;
if (event.type === 'submit') event.preventDefault();
if (event.type === 'contextmenu') event.preventDefault();
const nodeId = target.dataset.netcattyRemoteNode;
if (!nodeId) return;
if (event.type === 'scroll') {
const scrollEvent: PluginSurfaceEvent = {
nodeId,
type: 'scroll' as PluginSurfaceEvent['type'],
scrollTop: Math.max(0, Math.round(target.scrollTop)),
scrollLeft: Math.max(0, Math.round(target.scrollLeft)),
clientHeight: Math.max(0, Math.round(target.clientHeight)),
clientWidth: Math.max(0, Math.round(target.clientWidth)),
};
pendingScroll.set(nodeId, scrollEvent);
if (!scrollTimers.has(nodeId)) {
scrollTimers.set(nodeId, setTimeout(() => flushScroll(nodeId), SCROLL_THROTTLE_MS));
}
return;
}
const value = target instanceof view.HTMLInputElement || target instanceof view.HTMLTextAreaElement || target instanceof view.HTMLSelectElement ? target.value : undefined;
const values = target instanceof view.HTMLSelectElement && target.multiple ? [...target.selectedOptions].map((option) => option.value) : undefined;
const checkedValue = target instanceof view.HTMLInputElement && ['checkbox', 'radio'].includes(target.type) ? target.checked : undefined;
if (value !== undefined && value.length > MAX_EVENT_VALUE_LENGTH) return;
const keyboard = event instanceof view.KeyboardEvent && event.key.length <= 64
? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey }
: {};
let pointerCoords: { x: number; y: number } | undefined;
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
pointerCoords = {
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
};
}
const selection =
event.type === 'input' || event.type === 'change' || event.type === 'keyup' || event.type === 'keydown'
? readSelectionRange(target, view)
: undefined;
onEventRef.current({
nodeId,
type: event.type as PluginSurfaceEvent['type'],
...(value === undefined ? {} : { value }),
...(checkedValue === undefined ? {} : { checked: checkedValue }),
...keyboard,
...(pointerCoords ?? {}),
...(selection ?? {}),
...(values ? { values } : {}),
...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}),
});
};
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
return () => {
for (const timer of scrollTimers.values()) clearTimeout(timer);
scrollTimers.clear();
pendingScroll.clear();
for (const event of SURFACE_EVENTS) shadow.removeEventListener(event, listener, true);
};
}, [shadow]);
return (
{shadow && createPortal(<>{tree.children.map((node) => renderRemoteNode(node, settled))}>, shadow)}
);
}