Compare commits

..
Author SHA1 Message Date
陈大猫 82e64a60d8 docs: note that the plugin system and official plugins are still unstable
Tell users the plugin system and current official plugins are still
in an unstable stage, and that issues are welcome and will be fixed
promptly. Linked from all four README locales to the announcement
in Discussions #4554.
2026-11-29 17:29:51 +08:00
29 changed files with 76 additions and 3162 deletions

No files matched your search

+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -84,6 +86,8 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
<a name="plugin-system"></a>
# 🧩 プラグインシステム — Netcatty を安全に拡張
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
> **SSH 鍵やホストレンダラーを公開することなく機能を追加できます。** Netcatty のセキュリティ優先プラグイン基盤は、通常プラグインをオフラインのサンドボックス内で実行し、**ホストレンダリング UI**(Closed Shadow DOM + ネイティブ Monaco、DataGrid、BI/メトリクスチャート、Vault SSH トンネルプロキシ)のみで画面を描画します。
### ✨ 主な特徴
+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -86,6 +88,8 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
<a name="plugin-system"></a>
# 🧩 Plugin System — Extend Netcatty Safely
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
> **Build and install rich extensions without exposing your SSH keys or host renderer.** Netcatty's security-first plugin platform runs ordinary extensions inside an offline, sandboxed runtime and renders custom views exclusively through **Host-Rendered UI** (closed Shadow DOM + native Monaco, DataGrid, BI/Metric charts, and Vault SSH tunnel brokers).
### ✨ Highlights
+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -84,6 +86,8 @@
<a name="plugin-system"></a>
# 🧩 插件系统 — 安全扩展你的工作台
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 密钥与主进程渲染器的前提下自由扩展 Netcatty。** Netcatty 的安全优先插件平台将普通插件隔离在离线沙箱中运行,并通过**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 编辑器、虚拟化数据网格、实时监控/BI 图表与 Vault SSH 隧道代理)呈现原生手感界面。
### ✨ 核心亮点
+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -84,6 +86,8 @@
<a name="plugin-system"></a>
# 🧩 外掛系統 —— 安全擴充你的工作台
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 金鑰與宿主渲染器的前提下自由擴充 Netcatty。** Netcatty 的安全優先外掛平台將一般外掛隔離於離線沙箱中執行,並透過**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 編輯器、虛擬化資料格、即時監控/BI 圖表與 Vault SSH 通道代理)呈現原生體驗。
### ✨ 核心亮點
-2
View File
@@ -1330,8 +1330,6 @@ Highlight the focused split pane:
"plugins.sidebar.selectTerminal": "Select an open terminal first.",
"plugins.sidebar.loading": "Loading extension page…",
"plugins.vault.loading": "Loading plugin page…",
"plugins.vault.viewError": "The plugin page failed to render.",
"plugins.vault.retry": "Retry",
"plugins.interaction.title": "Plugin request",
"plugins.interaction.openUrlTitle": "Open external link?",
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
-2
View File
@@ -1330,8 +1330,6 @@ Resalta el panel dividido enfocado:
"plugins.sidebar.selectTerminal": "Selecciona primero un terminal abierto.",
"plugins.sidebar.loading": "Cargando página de extensión…",
"plugins.vault.loading": "Cargando página del plugin…",
"plugins.vault.viewError": "No se pudo renderizar la página del plugin.",
"plugins.vault.retry": "Reintentar",
"plugins.interaction.title": "Solicitud de complemento",
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
-2
View File
@@ -1271,8 +1271,6 @@ export const ruCoreMessages: Messages = {
"plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.",
"plugins.sidebar.loading": "Загрузка страницы расширения…",
"plugins.vault.loading": "Загрузка страницы плагина…",
"plugins.vault.viewError": "Не удалось отобразить страницу плагина.",
"plugins.vault.retry": "Повторить",
"plugins.interaction.title": "Запрос плагина",
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
-2
View File
@@ -1247,8 +1247,6 @@ Vaults 标签保持扁平,不使用这块背景。
"plugins.sidebar.selectTerminal": "请先选择已打开的终端。",
"plugins.sidebar.loading": "正在加载扩展页面…",
"plugins.vault.loading": "正在加载插件页面…",
"plugins.vault.viewError": "插件页面渲染失败。",
"plugins.vault.retry": "重试",
"plugins.interaction.title": "插件请求",
"plugins.interaction.openUrlTitle": "打开外部链接?",
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
-2
View File
@@ -1248,8 +1248,6 @@ Vaults 分頁維持扁平,不使用這塊背景。
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
"plugins.vault.loading": "正在載入擴充功能頁面…",
"plugins.vault.viewError": "擴充功能頁面無法顯示。",
"plugins.vault.retry": "重試",
"plugins.interaction.title": "外掛請求",
"plugins.interaction.openUrlTitle": "開啟外部連結?",
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
-406
View File
@@ -65,409 +65,3 @@ test('inserting a child into an existing void element fails the view', async ()
assert.equal(tree.isFailed(), true);
assert.deepEqual(tree.snapshot(), { children: [] });
});
test('duplicate insert of an existing id applies as a move or replace and keeps follow-up updates in sync', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
// Inserting an existing id at a later sibling index replaces the existing node in place.
const replaced = tree.apply([
[3, 'a', 'class', 'stale'],
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }, 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(replaced, {
children: [{ id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }],
});
// Follow-up mutations must apply against the replaced live node (desync gate).
const afterFollowUp = tree.apply([
[3, 'a', 'class', 'after-sort'],
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] }, 1],
]);
assert.deepEqual(afterFollowUp, {
children: [
{ id: 'a', type: 1, element: 'span', attributes: { class: 'after-sort' }, children: [] },
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] },
],
});
// Moving an existing sibling forward adjusts the insert index after detaching the old slot.
const movedForward = tree.apply([
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] }, 2],
]);
assert.deepEqual(movedForward.children.map((node) => node.id), ['b', 'a']);
assert.deepEqual(movedForward.children[1], { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] });
// Moving an existing sibling backward preserves index 0 and keeps subsequent updates working.
const movedBack = tree.apply([
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-start' }, children: [] }, 0],
]);
assert.deepEqual(movedBack.children.map((node) => node.id), ['a', 'b']);
const postMoveAttr = tree.apply([[2, 'b-text', 'updated-second'], [3, 'a', 'class', 'synced']]);
assert.deepEqual(postMoveAttr, {
children: [
{ id: 'a', type: 1, element: 'span', attributes: { class: 'synced' }, children: [] },
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'updated-second' }] },
],
});
});
test('inserting a parent whose subtree re-includes an already-present child detaches the child and preserves later updates', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([
[0, '~', {
id: 'old-parent',
type: 1,
element: 'div',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'unsorted' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
}, 0],
]);
// Parent insertion repeats already-attached descendant IDs without a preceding remove.
const reparented = tree.apply([
[0, '~', {
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-asc' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
}, 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(reparented, {
children: [
{ id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] },
{
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-asc' },
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
}],
},
],
});
// A subsequent sort-like incremental update on the moved child applies cleanly.
const secondSort = tree.apply([
[3, 'cell-1', 'class', 'sorted-desc'],
[2, 'cell-text', 'omega'],
]);
assert.deepEqual(secondSort.children[1], {
id: 'new-parent',
type: 1,
element: 'section',
attributes: {},
children: [{
id: 'cell-1',
type: 1,
element: 'span',
attributes: { class: 'sorted-desc' },
children: [{ id: 'cell-text', type: 3, data: 'omega' }],
}],
});
// Same-batch case: descendant inserted first, then a new parent serializing that descendant.
const sameBatch = tree.apply([
[0, 'old-parent', { id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }, 0],
[0, '~', {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
}, 2],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(sameBatch.children[0], { id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] });
assert.deepEqual(sameBatch.children[2], {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
});
const afterSameBatch = tree.apply([[2, 'child-2-text', 'two']]);
assert.deepEqual(afterSameBatch.children[2], {
id: 'wrapper',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'two' }] }],
});
});
test('unrecoverable self-nesting duplicate throws without failing the tree or corrupting later updates', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
assert.throws(
() => tree.apply([
[3, 'a', 'class', 'rejected'],
[0, 'a', { id: 'a', type: 1, element: 'span', attributes: {}, children: [] }, 0],
]),
/Duplicate view node/,
);
assert.equal(tree.isFailed(), false);
assert.deepEqual(tree.snapshot(), {
children: [{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }],
});
const updated = tree.apply([[0, '~', { id: 'b', type: 3, data: 'second' }, 1]]);
assert.deepEqual(updated, {
children: [
{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] },
{ id: 'b', type: 3, data: 'second' },
],
});
});
test('a duplicate id combined with a forbidden mutation still hard-fails the view', async () => {
const { createPluginRemoteTree, isDuplicatePluginViewNodeError, assertDuplicateOnlyPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
// Mutation order matters for RemoteReceiver: the void-element child is applied first so the
// projected tree actually contains both the policy violation and a later duplicate id.
assert.throws(
() => tree.apply([
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 1],
]),
/Void view elements/,
);
assert.equal(tree.isFailed(), true);
assert.deepEqual(tree.snapshot(), { children: [] });
// Even when the duplicate node appears earlier in root order than the void-element violation,
// unique-id revalidation must still hard-fail instead of rewriting the batch.
const duplicateFirstTree = createPluginRemoteTree();
duplicateFirstTree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
assert.throws(
() => duplicateFirstTree.apply([
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 0],
]),
/Void view elements/,
);
assert.equal(duplicateFirstTree.isFailed(), true);
assert.deepEqual(duplicateFirstTree.snapshot(), { children: [] });
// Defense in depth: if a projected tree already has both issues, unique-id revalidation
// must still surface the void-element violation instead of treating it as recoverable.
const mixed = {
children: [
{ id: 'input', type: 1 as const, element: 'input', attributes: { type: 'text' }, children: [{ id: 'child', type: 3 as const, data: 'invalid' }] },
{ id: 'input', type: 1 as const, element: 'div', attributes: {}, children: [] },
],
};
assert.equal(isDuplicatePluginViewNodeError(new TypeError('Duplicate view node')), true);
assert.throws(() => assertDuplicateOnlyPluginRemoteTree(mixed), /Void view elements/);
});
test('RemoteMutationObserver wrapping a sibling preserves kept siblings and follow-up text updates', async () => {
const dom = new JSDOM('<!doctype html><div id="remote"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
const { RemoteMutationObserver } = await import('@remote-dom/core/elements');
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const staged = createPluginRemoteTree();
const batches: unknown[][][] = [];
const observer = new RemoteMutationObserver({
mutate(records) {
const cloned = JSON.parse(JSON.stringify(records)) as unknown[][];
batches.push(cloned);
staged.apply(cloned);
},
call() { throw new Error('Host method calls are unavailable'); },
});
const container = document.getElementById('remote')!;
observer.observe(container);
const flush = () => new Promise((resolve) => setTimeout(resolve, 10));
try {
const a = document.createElement('div');
a.id = 'a';
const aText = document.createTextNode('Alpha');
a.appendChild(aText);
const b = document.createElement('div');
b.id = 'b';
b.appendChild(document.createTextNode('Beta'));
container.appendChild(a);
container.appendChild(b);
await flush();
assert.equal(staged.isFailed(), false);
assert.equal(staged.snapshot().children.length, 2);
// Same-tick wrap: append wrapper and move b into it.
const wrapper = document.createElement('section');
wrapper.id = 'wrapper';
container.appendChild(wrapper);
wrapper.appendChild(b);
await flush();
assert.equal(staged.isFailed(), false);
const afterWrap = staged.snapshot();
assert.deepEqual(
afterWrap.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a', 'wrapper'],
);
const [aNode, wrapperNode] = afterWrap.children;
assert.ok(aNode && aNode.type === 1, 'Expected sibling a first in host tree');
assert.ok(wrapperNode && wrapperNode.type === 1, 'Expected wrapper second in host tree');
assert.equal(aNode.children[0]?.type === 3 ? aNode.children[0].data : null, 'Alpha');
assert.deepEqual(
wrapperNode.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['b'],
);
const bNode = wrapperNode.children[0];
assert.ok(bNode && bNode.type === 1, 'Expected b inside wrapper');
assert.equal(bNode.children[0]?.type === 3 ? bNode.children[0].data : null, 'Beta');
// Desync gate: a subsequent text update to a must apply cleanly.
aText.data = 'Alpha updated';
await flush();
assert.equal(staged.isFailed(), false);
const afterText = staged.snapshot();
assert.deepEqual(
afterText.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a', 'wrapper'],
);
const updatedANode = afterText.children[0];
assert.ok(updatedANode && updatedANode.type === 1);
assert.equal(updatedANode.children[0]?.type === 3 ? updatedANode.children[0].data : null, 'Alpha updated');
// Later turn: removing wrapper at index 1 must keep a and leave a updatable.
wrapper.remove();
await flush();
assert.equal(staged.isFailed(), false);
const afterRemove = staged.snapshot();
assert.deepEqual(
afterRemove.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
['a'],
);
aText.data = 'Alpha after remove';
await flush();
assert.equal(staged.isFailed(), false);
const afterRemoveText = staged.snapshot();
const survivingANode = afterRemoveText.children[0];
assert.ok(survivingANode && survivingANode.type === 1);
assert.equal(survivingANode.children[0]?.type === 3 ? survivingANode.children[0].data : null, 'Alpha after remove');
assert.ok(batches.length >= 5);
} finally {
observer.disconnect();
for (const [key, value] of saved) {
if (value) Object.defineProperty(globalThis, key, value);
else Reflect.deleteProperty(globalThis, key);
}
dom.window.close();
}
});
test('rewriteDuplicateInsertBatch skips matched detaches and remaps subsequent producer removals', async () => {
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
const tree = createPluginRemoteTree();
tree.apply([
[0, '~', { id: '0', type: 1, element: 'div', attributes: { id: 'a' }, children: [{ id: '1', type: 3, data: 'Alpha' }] }, 0],
[0, '~', { id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }, 1],
]);
// Exact mutation batch from RemoteMutationObserver when appending wrapper and moving b into it.
const wrapped = tree.apply([
[0, '~', {
id: '4',
type: 1,
element: 'section',
attributes: { id: 'wrapper' },
children: [{ id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }],
}, 0],
[1, '~', 1],
]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(wrapped.children.map((node) => node.id), ['0', '4']);
const wrapperNode = wrapped.children[1];
assert.equal(wrapperNode.type, 1);
if (wrapperNode.type === 1) {
assert.deepEqual(wrapperNode.children.map((node) => node.id), ['2']);
}
// Subsequent text update to a must still apply.
const updated = tree.apply([[2, '1', 'Alpha updated']]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(updated.children[0], {
id: '0',
type: 1,
element: 'div',
attributes: { id: 'a' },
children: [{ id: '1', type: 3, data: 'Alpha updated' }],
});
// Later producer remove of wrapper at index 1 must remove wrapper and keep a alive.
const afterRemove = tree.apply([[1, '~', 1]]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(afterRemove.children.map((node) => node.id), ['0']);
const afterRemoveUpdate = tree.apply([[2, '1', 'Alpha after remove']]);
assert.equal(tree.isFailed(), false);
assert.deepEqual(afterRemoveUpdate, {
children: [{
id: '0',
type: 1,
element: 'div',
attributes: { id: 'a' },
children: [{ id: '1', type: 3, data: 'Alpha after remove' }],
}],
});
// Producer remove at a larger index after a rewrite detach at a smaller index remaps to the right sibling.
const remapTree = createPluginRemoteTree();
remapTree.apply([
[0, '~', { id: 'a', type: 1, element: 'div', attributes: {}, children: [] }, 0],
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'keep' }] }, 1],
[0, '~', { id: 'c', type: 1, element: 'div', attributes: {}, children: [] }, 2],
]);
const remapped = remapTree.apply([
[0, '~', { id: 'wrap', type: 1, element: 'section', attributes: {}, children: [{ id: 'a', type: 1, element: 'div', attributes: {}, children: [] }] }, 3],
// Producer removes c (original index 2) while a (index 0) was already detached by the rewrite.
[1, '~', 2],
// Producer then removes a at original index 0 (already detached -> skipped).
[1, '~', 0],
]);
assert.equal(remapTree.isFailed(), false);
assert.deepEqual(remapped.children.map((node) => node.id), ['b', 'wrap']);
const followUp = remapTree.apply([[2, 'b-text', 'still-alive']]);
assert.deepEqual(followUp.children[0], {
id: 'b',
type: 1,
element: 'div',
attributes: {},
children: [{ id: 'b-text', type: 3, data: 'still-alive' }],
});
});
+6 -203
View File
@@ -12,174 +12,6 @@ export function isValidatedPluginRemoteTree(tree: unknown): boolean {
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
}
export function isDuplicatePluginViewNodeError(error: unknown): error is TypeError {
return error instanceof TypeError && error.message === 'Duplicate view node';
}
function withUniqueViewIds(tree: WireTree): WireTree {
let n = 0;
const rewrite = (node: WireNode): WireNode => {
const id = `n${n++}`;
if (node.type === 3 || node.type === 8) return { id, type: node.type, data: node.data };
return { id, type: 1, element: node.element, attributes: node.attributes, children: node.children.map(rewrite) };
};
return { children: tree.children.map(rewrite) };
}
/** If a projected tree has duplicate IDs, still hard-fail when other policy violations exist. */
export function assertDuplicateOnlyPluginRemoteTree(tree: WireTree): void {
validatePluginRemoteTree(withUniqueViewIds(tree));
}
type WorkingNode = {
id: string;
parentId: string | null;
children: WorkingNode[];
};
type RewriteDetach = {
parentId: string;
index: number;
id: string;
};
function collectSubtreeIds(node: WireNode, out: string[] = []): string[] {
out.push(node.id);
if (node.type === 1) {
for (const child of node.children) collectSubtreeIds(child, out);
}
return out;
}
function buildWorkingNode(node: WireNode, parentId: string, nodes: Map<string, WorkingNode>): WorkingNode {
const working: WorkingNode = { id: node.id, parentId, children: [] };
nodes.set(node.id, working);
if (node.type === 1) {
for (const child of node.children) {
working.children.push(buildWorkingNode(child, node.id, nodes));
}
}
return working;
}
function detachWorkingSubtree(node: WorkingNode, nodes: Map<string, WorkingNode>): void {
nodes.delete(node.id);
node.parentId = null;
for (const child of node.children) detachWorkingSubtree(child, nodes);
}
function hasAncestorInSet(startId: string, ids: Set<string>, nodes: Map<string, WorkingNode>): boolean {
let cursor: string | null = startId;
while (cursor !== null) {
if (ids.has(cursor)) return true;
cursor = nodes.get(cursor)?.parentId ?? null;
}
return false;
}
/**
* Normalizes a duplicate-only mutation batch so inserts referencing IDs already
* attached in the tree first emit explicit removals from their previous parents.
* Returns null if an insert would detach its own destination parent (cycle).
*/
function rewriteDuplicateInsertBatch(current: WireTree, batch: unknown[][]): unknown[][] | null {
const root: WorkingNode = { id: '~', parentId: null, children: [] };
const nodes = new Map<string, WorkingNode>([['~', root]]);
for (const child of current.children) {
root.children.push(buildWorkingNode(child, '~', nodes));
}
const rewritten: unknown[][] = [];
const rewriteDetaches: RewriteDetach[] = [];
for (const record of batch) {
const type = record[0];
if (type === 0) {
const parentId = record[1] as string;
const node = record[2] as WireNode;
let insertIndex = record[3] as number;
const parent = nodes.get(parentId);
if (!parent) {
// Detached parent: RemoteReceiver drops this insert as a no-op.
rewritten.push(record);
continue;
}
const subtreeIds = collectSubtreeIds(node);
if (hasAncestorInSet(parentId, new Set(subtreeIds), nodes)) {
return null;
}
for (const existingId of subtreeIds) {
const existing = nodes.get(existingId);
if (!existing || existing.parentId === null) continue;
const oldParent = nodes.get(existing.parentId);
if (!oldParent) continue;
const oldIndex = oldParent.children.indexOf(existing);
if (oldIndex < 0) continue;
rewritten.push([1, oldParent.id, oldIndex]);
rewriteDetaches.push({ parentId: oldParent.id, index: oldIndex, id: existing.id });
oldParent.children.splice(oldIndex, 1);
detachWorkingSubtree(existing, nodes);
if (oldParent.id === parentId) {
if (oldIndex < insertIndex) {
insertIndex -= 1;
} else if (existing.id !== node.id && oldIndex > insertIndex) {
insertIndex = oldIndex;
}
}
}
rewritten.push(insertIndex === record[3] ? record : [0, parentId, node, insertIndex]);
const inserted = buildWorkingNode(node, parentId, nodes);
if (insertIndex >= parent.children.length) {
parent.children.push(inserted);
} else {
parent.children.splice(insertIndex, 0, inserted);
}
} else if (type === 1) {
const parentId = record[1] as string;
const removeIndex = record[2] as number;
const exactMatchIndex = rewriteDetaches.findIndex(
(detach) => detach.parentId === parentId && detach.index === removeIndex,
);
if (exactMatchIndex !== -1) {
rewriteDetaches.splice(exactMatchIndex, 1);
continue;
}
let smallerCount = 0;
for (const detach of rewriteDetaches) {
if (detach.parentId === parentId && detach.index < removeIndex) {
smallerCount += 1;
}
}
const remappedIndex = removeIndex - smallerCount;
const parent = nodes.get(parentId);
if (!parent) {
if (smallerCount === 0) rewritten.push(record);
continue;
}
if (remappedIndex < 0 || remappedIndex >= parent.children.length) {
continue;
}
rewritten.push(remappedIndex === removeIndex ? record : [1, parentId, remappedIndex]);
const [removed] = parent.children.splice(remappedIndex, 1);
if (removed) detachWorkingSubtree(removed, nodes);
for (const detach of rewriteDetaches) {
if (detach.parentId === parentId && detach.index > removeIndex) {
detach.index -= 1;
}
}
} else {
rewritten.push(record);
}
}
return rewritten;
}
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
export function createPluginRemoteTree() {
const receiver = new RemoteReceiver();
@@ -191,16 +23,6 @@ export function createPluginRemoteTree() {
if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' };
return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) };
};
const applyToScratch = (records: unknown[][]): WireTree => {
const scratch = new RemoteReceiver();
if (current.children.length > 0) {
scratch.connection.mutate(
current.children.map((child, index) => [0, '~', child, index]) as unknown as Parameters<typeof scratch.connection.mutate>[0],
);
}
scratch.connection.mutate(records as unknown as Parameters<typeof scratch.connection.mutate>[0]);
return { children: scratch.root.children.map(project) };
};
return {
apply(input: unknown): WireTree {
if (failed) throw new Error('Plugin view has been closed after an invalid update');
@@ -209,35 +31,16 @@ export function createPluginRemoteTree() {
// Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver
// defaults those to properties, so explicitly mark them as attributes.
const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record);
let appliedBatch = batch;
let next = applyToScratch(batch);
try {
validatePluginRemoteTree(next);
} catch (error) {
if (!isDuplicatePluginViewNodeError(error)) throw error;
assertDuplicateOnlyPluginRemoteTree(next);
const rewritten = rewriteDuplicateInsertBatch(current, batch);
if (!rewritten) throw error;
const rewrittenNext = applyToScratch(rewritten);
try {
validatePluginRemoteTree(rewrittenNext);
} catch (rewrittenError) {
if (isDuplicatePluginViewNodeError(rewrittenError)) assertDuplicateOnlyPluginRemoteTree(rewrittenNext);
throw rewrittenError;
}
appliedBatch = rewritten;
next = rewrittenNext;
}
receiver.connection.mutate(appliedBatch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
const next = { children: receiver.root.children.map(project) };
validatePluginRemoteTree(next);
validatedTrees.add(next);
current = next;
return next;
} catch (error) {
if (!isDuplicatePluginViewNodeError(error)) {
failed = true;
current = { children: [] };
validatedTrees.add(current);
}
failed = true;
current = { children: [] };
validatedTrees.add(current);
throw error;
}
},
-277
View File
@@ -60,280 +60,3 @@ test('empty first update holds loading briefly to prevent blank-frame flash then
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
store.dispose();
});
test('update and event failures warn concisely with error message before disposing without logging event payloads', async () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f1 = fixture();
const store = new PluginViewSessions();
const view1 = store.acquire('bad-seq', f1.bridge, request);
f1.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: f1.opened[0].instanceId, sequence: 99, css: '', mutations: [] });
assert.equal(view1.getSnapshot().error, true);
assert.equal(warns.length, 1);
assert.match(String(warns[0][0]), /Invalid plugin update order/);
assert.ok(warns[0][1] instanceof Error);
const f2 = fixture();
f2.bridge.sendHostDrawnPluginViewEvent = async () => { throw new Error('IPC channel closed'); };
const view2 = store.acquire('bad-send', f2.bridge, request);
view2.send({ type: 'input', nodeId: 'field', value: 'secret@example.com' });
await Promise.resolve();
assert.equal(view2.getSnapshot().error, true);
assert.equal(warns.length, 2);
assert.match(String(warns[1][0]), /IPC channel closed/);
assert.doesNotMatch(warns[1].map(String).join(' '), /secret@example\.com/);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('recoverable duplicate node update applies as a move and publishes the new tree without warning', () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('dup-move', f.bridge, request);
const id = f.opened[0].instanceId;
const initialNode = {
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
};
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
assert.equal(view.getSnapshot().loading, false);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
// Re-inserting an existing node (or wrapping it in a new parent without a remove)
// is normalized as a move and published immediately with zero warnings.
const movedNode = {
id: 'group-1',
type: 1 as const,
element: 'section',
attributes: { class: 'sorted' },
children: [{
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
}],
};
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.sorted{color:blue}',
mutations: [[0, '~', movedNode, 1]],
} as Update);
assert.equal(warns.length, 0);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), true);
assert.deepEqual(view.getSnapshot().tree.children, [movedNode]);
assert.equal(f.closes.length, 0);
assert.equal(store.peek('dup-move'), view);
// A subsequent incremental update applies cleanly against the moved nodes.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [
[2, 'cell-1', 'beta'],
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
],
} as Update);
assert.equal(warns.length, 0);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [
{
...movedNode,
children: [{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] }],
},
{ id: 'row-2', type: 3, data: 'second' },
]);
// Forbidden mutations still dispose the session.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'onclick', 'attack()']],
} as Update);
assert.equal(view.getSnapshot().error, true);
assert.deepEqual(view.getSnapshot().tree.children, []);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('unrecoverable duplicate node update warns without failing the session and accepts subsequent valid updates', () => {
const warns: unknown[][] = [];
const originalWarn = console.warn;
console.warn = (...args: unknown[]) => { warns.push(args); };
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('dup-recovery', f.bridge, request);
const id = f.opened[0].instanceId;
const initialNode = {
id: 'row-1',
type: 1 as const,
element: 'div',
attributes: { class: 'row' },
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
};
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
assert.equal(view.getSnapshot().loading, false);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
// Self-nesting cycle cannot be rewritten as a move; last-resort fallback preserves last good tree.
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '',
cssUnchanged: true,
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'div', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(warns.length, 1);
assert.match(String(warns[0][0]), /Duplicate view node/);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
assert.equal(f.closes.length, 0);
assert.equal(store.peek('dup-recovery'), view);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [
[2, 'cell-1', 'beta'],
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.deepEqual(view.getSnapshot().tree.children, [
{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] },
{ id: 'row-2', type: 3, data: 'second' },
]);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'onclick', 'attack()']],
} as Update);
assert.equal(view.getSnapshot().error, true);
assert.deepEqual(view.getSnapshot().tree.children, []);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('pending CSS from a rejected unrecoverable duplicate update is published on the next accepted update', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('css-pending', f.bridge, request);
const id = f.opened[0].instanceId;
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
assert.equal(view.getSnapshot().css.includes('red'), true);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.row{color:blue}',
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('red'), true, 'rejected update does not publish CSS immediately');
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'class', 'ready']],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), true, 'next accepted update publishes the stashed CSS');
store.dispose();
} finally {
console.warn = originalWarn;
}
});
test('explicit CSS matching the last committed value supersedes pending CSS', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const store = new PluginViewSessions();
const view = store.acquire('css-supersede', f.bridge, request);
const id = f.opened[0].instanceId;
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 2,
css: '.row{color:blue}',
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
} as Update);
assert.equal(view.getSnapshot().css.includes('red'), true);
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 3,
css: '.row{color:red}',
mutations: [[3, 'row-1', 'class', 'ready']],
} as Update);
assert.equal(view.getSnapshot().error, false);
assert.equal(view.getSnapshot().css.includes('blue'), false);
assert.equal(view.getSnapshot().css.includes('red'), true, 'explicit red supersedes pending blue');
f.update({
kind: 'host-ui.update',
viewId: request.viewId,
instanceId: id,
sequence: 4,
css: '',
cssUnchanged: true,
mutations: [[3, 'row-1', 'class', 'again']],
} as Update);
assert.equal(view.getSnapshot().css.includes('red'), true);
assert.equal(view.getSnapshot().css.includes('blue'), false);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
+8 -39
View File
@@ -1,4 +1,4 @@
import { createPluginRemoteTree, isDuplicatePluginViewNodeError } from './pluginRemoteTree';
import { createPluginRemoteTree } from './pluginRemoteTree';
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
@@ -27,8 +27,6 @@ export class PluginViewSessions {
const tree = createPluginRemoteTree();
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
let lastRawCss: string | null = null;
let pendingCss: string | null = null;
let pendingRawCss: string | null = null;
let timer: ReturnType<typeof setTimeout> | undefined;
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
const listeners = new Set<() => void>();
@@ -44,26 +42,14 @@ export class PluginViewSessions {
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
let stagedCss: string | null = null;
let stagedRawCss: string | null = null;
try {
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
if (update.cssUnchanged) {
// keep pending CSS, if any, for the nextCss fallback below
} else if (lastRawCss !== null && update.css === lastRawCss) {
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
pendingCss = null;
pendingRawCss = null;
} else {
stagedCss = validatePluginStylesheet(update.css);
stagedRawCss = update.css;
}
const nextCss = stagedCss ?? pendingCss ?? state.css;
const nextCss = update.cssUnchanged
? state.css
: (lastRawCss !== null && update.css === lastRawCss)
? state.css
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
const nextTree = tree.apply(update.mutations);
if (stagedRawCss !== null) lastRawCss = stagedRawCss;
else if (pendingRawCss !== null) lastRawCss = pendingRawCss;
pendingCss = null;
pendingRawCss = null;
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
if (state.loading && !hasRenderableTreeContent(nextTree)) {
// Hold the host loading surface briefly while an older SDK flushes its
@@ -82,20 +68,7 @@ export class PluginViewSessions {
emptyFrameTimer = undefined;
}
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
// Recoverable duplicate-only batches are normalized as moves in
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
if (isDuplicatePluginViewNodeError(error)) {
if (stagedCss !== null && stagedRawCss !== null) {
pendingCss = stagedCss;
pendingRawCss = stagedRawCss;
}
return;
}
dispose(true);
}
} catch { dispose(true); }
}));
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
@@ -127,11 +100,7 @@ export class PluginViewSessions {
send: (event: HostDrawnViewEvent) => {
if (disposed || users === 0) return;
publish({ ...state, settled: false });
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
dispose(true);
});
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
},
dispose,
};
+2 -8
View File
@@ -39,11 +39,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
try {
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
sessionRef.current = { key, send: session.send, image: session.image };
const update = () => {
const snapshot = session.getSnapshot();
if (snapshot.error) sessionRef.current = null;
setState({ key, snapshot, image: session.image });
};
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
const stop = session.subscribe(update); update(); setHidden(false);
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
@@ -53,9 +49,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
const session = sessionRef.current;
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
}, [active, key]);
const hasCurrentState = active
&& state.key === key
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
const resolvedSnapshot = hasCurrentState
? state.snapshot
: cachedSession
-88
View File
@@ -82,91 +82,3 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
test('Failed host-drawn view session stays on the plugin vault page with error and retry instead of falling back to Hosts', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'CustomEvent', 'Event']) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof Window] });
}
for (const [key, value] of Object.entries({ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window), IS_REACT_ACT_ENVIRONMENT: true })) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({ x: 200, y: 100, width: 640, height: 480, top: 100, left: 200, right: 840, bottom: 580, toJSON() {} });
const { act, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { usePluginVaultPages } = await import('../application/state/usePluginVaultPages');
const { PluginVaultNavigation, PluginVaultPage } = await import('./plugins/PluginVaultPages');
const { activeTabStore } = await import('../application/state/activeTabStore');
const { I18nProvider } = await import('../application/i18n/I18nProvider');
const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', visible: true };
let snapshot = { locale: 'en', plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] };
let changed: (() => void) | undefined;
const listeners = new Set<(event: NetcattyPluginViewClosedEvent) => void>();
const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [];
Object.assign(dom.window, { netcatty: {
async getPluginRuntimeStatus() { return { available: true }; },
async getPluginContributions() { return snapshot; },
onPluginContributionsChanged(fn: () => void) { changed = fn; return () => { changed = undefined; }; },
onPluginViewClosed(fn: (event: NetcattyPluginViewClosedEvent) => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
onHostDrawnPluginViewUpdate() { return () => {}; },
async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; },
async closeHostDrawnPluginView(id: string) { closes.push(id); },
} });
function Fixture() {
const [section, select] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
const model = usePluginVaultPages({ locale: 'en', section, select });
return <><aside><button data-plugin-vault-fallback onClick={() => select('hosts')}>Hosts</button><PluginVaultNavigation model={model} collapsed={false} /></aside>
<main data-section="vault-main">{model.selected ? <PluginVaultPage key={model.selected.key} model={model} /> : <p>Built-in hosts</p>}</main></>;
}
const root = createRoot(document.getElementById('root')!);
const settle = () => new Promise((resolve) => setTimeout(resolve, 35));
try {
activeTabStore.setActiveTabId('vault');
await act(async () => { root.render(<I18nProvider locale="en"><Fixture /></I18nProvider>); await settle(); });
await act(async () => {
document.querySelector<HTMLButtonElement>('button[aria-label="Synthetic page — Synthetic plugin"]')!.click();
await import('./plugins/PluginHostDrawnPage');
await settle();
});
assert.equal(opens.length, 1);
assert.ok(document.querySelector('[data-plugin-vault-page]'));
// Session fails while plugin contribution remains active.
await act(async () => {
for (const listener of listeners) {
listener({ instanceId: opens[0].instanceId!, viewId: page.id, pluginId: 'com.example.page', reason: 'view-error' });
}
await settle();
});
assert.ok(document.querySelector('[data-plugin-vault-page]'), 'stays on the plugin vault page');
assert.doesNotMatch(document.querySelector('main')!.textContent!, /Built-in hosts/);
assert.equal(document.querySelector('[data-plugin-remote-surface]'), null, 'does not render an empty remote surface');
const alert = document.querySelector('[data-plugin-vault-page] [role="alert"]');
assert.ok(alert, 'renders in-page error alert');
assert.equal(alert!.textContent, 'The plugin page failed to render.');
const retryButton = [...document.querySelectorAll<HTMLButtonElement>('[data-plugin-vault-page] button')]
.find((btn) => btn.textContent === 'Retry');
assert.ok(retryButton, 'renders Retry control');
await act(async () => {
retryButton!.click();
await settle();
});
assert.equal(opens.length, 2, 'clicking Retry opens a new host-drawn plugin view session');
assert.notEqual(opens[1].instanceId, opens[0].instanceId);
assert.equal(document.querySelector('[data-plugin-vault-page] [role="alert"]'), null);
// Removing the contribution still falls back to Hosts.
await act(async () => { snapshot = { ...snapshot, plugins: [] }; changed?.(); await settle(); });
await act(async () => { await settle(); });
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
} finally {
await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close();
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
}
});
+3 -35
View File
@@ -1,7 +1,4 @@
import { useCallback, useState } from 'react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPluginView';
import { Button } from '../ui/button';
import { PluginViewLoadingSurface } from './LazyPluginHostDrawnPage';
import { PluginSettingsEntry } from './PluginSettingsEntry';
import { PluginRemoteSurface } from './PluginRemoteSurface';
@@ -33,33 +30,12 @@ function hasFullBleedChrome(tree: unknown): boolean {
return check(children, 0);
}
function PluginHostDrawnPageSession({
onRetry,
...props
}: PluginHostDrawnPageProps & { onRetry: () => void }) {
const { t } = useI18n();
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
const view = useHostDrawnPluginView(props);
if (!view.visible) return null;
const slotName = props.slot.split(':')[0];
if (view.loading) return <PluginViewLoadingSurface slot={slotName} loadingLabel={props.loadingLabel} />;
if (view.error) {
return (
<div
className="relative isolate flex h-full min-h-0 w-full flex-1 flex-col items-center justify-center gap-3 bg-background p-6 text-center"
data-plugin-view-slot={slotName}
data-plugin-view-error=""
>
<p role="alert" className="text-sm text-destructive">
{t('plugins.vault.viewError')}
</p>
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
{t('plugins.vault.retry')}
</Button>
</div>
);
}
if (view.loading) return <PluginViewLoadingSurface slot={props.slot.split(':')[0]} loadingLabel={props.loadingLabel} />;
const fullBleed = hasFullBleedChrome(view.tree);
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={slotName} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
{!fullBleed && (
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
@@ -68,11 +44,3 @@ function PluginHostDrawnPageSession({
)}
</div>;
}
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
const [generation, setGeneration] = useState(0);
const handleRetry = useCallback(() => {
setGeneration((n) => n + 1);
}, []);
return <PluginHostDrawnPageSession key={generation} {...props} onRetry={handleRetry} />;
}
@@ -808,793 +808,3 @@ test('PluginDataGrid clears stale editingCell and pending blur timer when insert
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface forwards pointer gestures with capture/coalescing and wheel zoom without breaking scroll or widgets', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
PointerEvent: dom.window.MouseEvent,
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
});
const capturedPointers: Array<{ target: Element; pointerId: number }> = [];
const releasedPointers: Array<{ target: Element; pointerId: number }> = [];
dom.window.HTMLElement.prototype.setPointerCapture = function (pointerId: number) {
capturedPointers.push({ target: this, pointerId });
};
dom.window.HTMLElement.prototype.releasePointerCapture = function (pointerId: number) {
releasedPointers.push({ target: this, pointerId });
};
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const makePointerEvent = (
type: string,
opts: { clientX: number; clientY: number; pointerId?: number; button?: number; buttons?: number; pointerType?: string; shiftKey?: boolean; composed?: boolean },
) => {
const evt = new dom.window.MouseEvent(type, {
bubbles: true,
cancelable: true,
composed: opts.composed ?? true,
clientX: opts.clientX,
clientY: opts.clientY,
button: opts.button ?? 0,
buttons: opts.buttons ?? 0,
shiftKey: opts.shiftKey ?? false,
});
if (opts.pointerId !== undefined) Object.defineProperty(evt, 'pointerId', { value: opts.pointerId });
if (opts.pointerType !== undefined) Object.defineProperty(evt, 'pointerType', { value: opts.pointerType });
return evt;
};
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
const events: Array<Record<string, unknown>> = [];
const gridProps = {
columns: [{ name: 'id', type: 'int4', primaryKey: true }],
rows: [{ id: 1 }],
editable: false,
};
const tree = {
children: [
{
id: 'stage',
type: 1,
element: 'div',
attributes: { class: 'graph-stage', style: 'overflow:hidden;touch-action:none' },
children: [
{
id: 'node-1',
type: 1,
element: 'button',
attributes: { type: 'button', class: 'graph-node', style: 'touch-action:none' },
children: [{ id: 'n1t', type: 3, data: 'Alpha' }],
},
{
id: 'plain-btn',
type: 1,
element: 'button',
attributes: { type: 'button', class: 'plain-btn' },
children: [{ id: 'pbt', type: 3, data: 'Click me' }],
},
],
},
{
id: 'scroll-box',
type: 1,
element: 'div',
attributes: { class: 'scroll-box', style: 'overflow-y:auto;height:120px' },
children: [
{ id: 'scroll-row', type: 1, element: 'div', attributes: { class: 'scroll-row' }, children: [{ id: 'srt', type: 3, data: 'Item' }] },
],
},
{
id: 'fit-box',
type: 1,
element: 'div',
attributes: { class: 'fit-box', style: 'overflow-y:auto;height:120px' },
children: [
{ id: 'fit-row', type: 1, element: 'div', attributes: { class: 'fit-row' }, children: [{ id: 'frt', type: 3, data: 'Short' }] },
],
},
{
id: 'split',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'split-pane',
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 200, minSize: 100, maxSize: 400 }),
},
children: [
{ id: 'pane-node', type: 1, element: 'div', attributes: { class: 'pane-node' }, children: [{ id: 'pn', type: 3, data: 'Pane' }] },
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
],
},
{
id: 'grid',
type: 1,
element: 'div',
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
children: [],
},
],
};
const root = createRoot(document.getElementById('root')!);
const renderSurface = async (settled = true) => {
await act(async () => {
root.render(
<PluginRemoteSurface
tree={tree}
css=""
settled={settled}
onEvent={(e) => {
assert.equal(validateEvent(e), true, `Emitted event must satisfy contract schema: ${JSON.stringify(e)} -> ${JSON.stringify(validateEvent.errors)}`);
events.push(e as unknown as Record<string, unknown>);
}}
/>,
);
});
};
try {
await renderSurface(true);
const mainShadow = shadows[0]!;
const stage = mainShadow.querySelector('.graph-stage') as HTMLElement;
const nodeBtn = mainShadow.querySelector('.graph-node') as HTMLElement;
const plainBtn = mainShadow.querySelector('.plain-btn') as HTMLElement;
const scrollBox = mainShadow.querySelector('.scroll-box') as HTMLElement;
const scrollRow = mainShadow.querySelector('.scroll-row') as HTMLElement;
const fitBox = mainShadow.querySelector('.fit-box') as HTMLElement;
const fitRow = mainShadow.querySelector('.fit-row') as HTMLElement;
const paneNode = mainShadow.querySelector('.pane-node') as HTMLElement;
const splitHandle = mainShadow.querySelector('[data-split-handle]') as HTMLElement;
// 1. Hover pointermove before any pointerdown must NOT forward
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointermove', { clientX: 150, clientY: 90, pointerId: 3, button: -1, buttons: 0 }));
});
assert.equal(events.length, 0, 'idle hover pointermove must not flood plugin IPC');
// 2. pointerdown -> move (including outside node/surface) -> coalesce -> flush before pointerup
const downEvt = makePointerEvent('pointerdown', { clientX: 140, clientY: 90, pointerId: 7, button: 0, buttons: 1, pointerType: 'mouse' });
await act(async () => {
nodeBtn.dispatchEvent(downEvt);
});
assert.equal(downEvt.defaultPrevented, false, 'pointerdown must not preventDefault so focus/click/text-selection remain intact');
assert.deepEqual(capturedPointers, [{ target: nodeBtn, pointerId: 7 }], 'touch-action:none node engages host pointer capture');
assert.deepEqual(events.at(-1), {
nodeId: 'node-1',
type: 'pointerdown',
x: 40,
y: 40,
pointerId: 7,
button: 0,
buttons: 1,
pointerType: 'mouse',
});
// Unchanged coordinate move is skipped; first changed move forwards immediately (leading edge)
// and rapid subsequent moves outside the surface coalesce and flush right before pointerup.
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 140, clientY: 90, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 200, clientY: 130, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 215, clientY: 140, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 80, clientY: 20, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 80, clientY: 20, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' }));
});
assert.deepEqual(releasedPointers, [{ target: nodeBtn, pointerId: 7 }], 'pointer capture released on pointerup');
assert.deepEqual(events.slice(1), [
{ nodeId: 'node-1', type: 'pointermove', x: 100, y: 80, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true },
{ nodeId: 'node-1', type: 'pointermove', x: -20, y: -30, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' },
{ nodeId: 'node-1', type: 'pointerup', x: -20, y: -30, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' },
]);
// Moves after pointerup are ignored
const countAfterUp = events.length;
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 300, clientY: 300, pointerId: 7, button: -1, buttons: 0 }));
});
assert.equal(events.length, countAfterUp);
// 3. Backpressure via settled={false} holds coalesced pointermove until settled flips true
events.length = 0;
await renderSurface(false);
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 150, clientY: 100, pointerId: 9, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 190, clientY: 120, pointerId: 9, button: -1, buttons: 1 }));
});
assert.deepEqual(events.map((e) => e.type), ['pointerdown'], 'unsettled move waits for acknowledgement');
await renderSurface(true);
assert.deepEqual(events.map((e) => ({ type: e.type, x: e.x, y: e.y })), [
{ type: 'pointerdown', x: 50, y: 50 },
{ type: 'pointermove', x: 90, y: 70 },
], 'move flushes immediately once settled becomes true');
await act(async () => {
dom.window.dispatchEvent(makePointerEvent('pointercancel', { clientX: 95, clientY: 75, pointerId: 9, button: -1, buttons: 0 }));
});
assert.equal(events.at(-1)?.type, 'pointercancel');
assert.equal(events.at(-1)?.nodeId, 'node-1');
// 4. Plain button does not engage setPointerCapture and still forwards normal click
events.length = 0;
const captureCountBeforePlain = capturedPointers.length;
await act(async () => {
plainBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 1 }));
plainBtn.dispatchEvent(makePointerEvent('pointerup', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 0 }));
plainBtn.click();
});
assert.equal(capturedPointers.length, captureCountBeforePlain, 'plain button without touch-action:none skips setPointerCapture');
assert.deepEqual(events.map((e) => e.type), ['pointerdown', 'pointerup', 'click']);
// 5. Wheel over non-scrollable remote node prevents default and forwards deltas; rapid ticks coalesce by summing deltas
events.length = 0;
const wheel1 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 260,
clientY: 190,
deltaX: 0,
deltaY: -120,
deltaMode: 0,
ctrlKey: true,
});
const wheel2 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 265,
clientY: 195,
deltaX: 4,
deltaY: -60,
deltaMode: 0,
ctrlKey: true,
});
const wheel3 = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 270,
clientY: 200,
deltaX: 6,
deltaY: -40,
deltaMode: 0,
ctrlKey: true,
});
await act(async () => {
stage.dispatchEvent(wheel1);
stage.dispatchEvent(wheel2);
stage.dispatchEvent(wheel3);
});
assert.equal(wheel1.defaultPrevented, true, 'non-scrollable wheel must preventDefault');
assert.equal(wheel2.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
assert.equal(wheel3.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
assert.deepEqual([...events], [
{ nodeId: 'stage', type: 'wheel', x: 160, y: 140, deltaX: 0, deltaY: -120, deltaMode: 0, ctrlKey: true },
]);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 40));
});
assert.deepEqual(events.at(-1), {
nodeId: 'stage',
type: 'wheel',
x: 170,
y: 150,
deltaX: 10,
deltaY: -100,
deltaMode: 0,
ctrlKey: true,
});
// 6. Wheel over scrollable overflow container allows native scroll (no preventDefault, no wheel event)
events.length = 0;
Object.defineProperty(scrollBox, 'scrollHeight', { value: 600, configurable: true });
Object.defineProperty(scrollBox, 'clientHeight', { value: 120, configurable: true });
const scrollWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: 100,
deltaMode: 0,
});
await act(async () => {
scrollRow.dispatchEvent(scrollWheel);
});
assert.equal(scrollWheel.defaultPrevented, false, 'scrollable overflow ancestor must keep native wheel scrolling');
assert.equal(events.length, 0, 'wheel over scrollable overflow ancestor must not forward wheel');
// Non-overflowing overflow:auto container still forwards wheel
Object.defineProperty(fitBox, 'scrollHeight', { value: 120, configurable: true });
Object.defineProperty(fitBox, 'clientHeight', { value: 120, configurable: true });
const fitWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: -80,
deltaMode: 0,
});
await act(async () => {
fitRow.dispatchEvent(fitWheel);
await new Promise((resolve) => setTimeout(resolve, 35));
});
assert.equal(fitWheel.defaultPrevented, true, 'non-overflowing overflow:auto box forwards wheel');
assert.equal(events.length, 1);
assert.equal(events[0].nodeId, 'fit-row');
assert.equal(events[0].type, 'wheel');
// 7. touch-action:none canvas inside a scrollable surface host still claims wheel zoom
events.length = 0;
const hostDiv = mainShadow.host as HTMLElement;
hostDiv.style.overflowY = 'auto';
Object.defineProperty(hostDiv, 'scrollHeight', { value: 1400, configurable: true });
Object.defineProperty(hostDiv, 'clientHeight', { value: 600, configurable: true });
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 35));
});
const stageWheelInScrollableHost = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
clientX: 220,
clientY: 160,
deltaX: 0,
deltaY: -90,
deltaMode: 0,
});
await act(async () => {
nodeBtn.dispatchEvent(stageWheelInScrollableHost);
});
assert.equal(stageWheelInScrollableHost.defaultPrevented, true, 'touch-action:none graph node claims wheel even when outer host is scrollable');
assert.equal(events.at(-1)?.type, 'wheel');
assert.equal(events.at(-1)?.nodeId, 'node-1');
// 8. Slotted widget pointer & wheel events are never forwarded as generic plugin events
events.length = 0;
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement;
const gridCell = gridHost.querySelector('[role="gridcell"]') as HTMLElement;
const widgetWheel = new dom.window.WheelEvent('wheel', {
bubbles: true,
cancelable: true,
composed: true,
clientX: 200,
clientY: 150,
deltaX: 0,
deltaY: 120,
deltaMode: 0,
});
await act(async () => {
gridCell.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 150, pointerId: 21, button: 0, buttons: 1 }));
gridCell.dispatchEvent(makePointerEvent('pointermove', { clientX: 240, clientY: 170, pointerId: 21, button: -1, buttons: 1 }));
gridCell.dispatchEvent(makePointerEvent('pointerup', { clientX: 240, clientY: 170, pointerId: 21, button: 0, buttons: 0 }));
gridCell.dispatchEvent(widgetWheel);
});
assert.equal(widgetWheel.defaultPrevented, false, 'slotted widget wheel must not be intercepted by surface');
assert.equal(
events.some((e) => ['pointerdown', 'pointermove', 'pointerup', 'wheel'].includes(String(e.type))),
false,
'slotted widget pointer and wheel events must not forward as generic surface events',
);
// 9. SplitPane handle drag does not forward generic pointer events, while remote nodes inside its panes do
events.length = 0;
await act(async () => {
splitHandle.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 100, pointerId: 31, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 250, clientY: 100, pointerId: 31, button: -1, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 250, clientY: 100, pointerId: 31, button: 0, buttons: 0 }));
});
assert.equal(
events.some((e) => ['pointerdown', 'pointermove', 'pointerup'].includes(String(e.type))),
false,
'split-pane handle must not forward generic pointer events',
);
assert.ok(events.some((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'), 'split-pane resize still works');
events.length = 0;
await act(async () => {
paneNode.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 1 }));
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 0 }));
});
assert.deepEqual(events.map((e) => ({ nodeId: e.nodeId, type: e.type, x: e.x, y: e.y })), [
{ nodeId: 'pane-node', type: 'pointerdown', x: 60, y: 60 },
{ nodeId: 'pane-node', type: 'pointerup', x: 60, y: 60 },
]);
// 10. Unmounting the surface mid-drag emits pointercancel so a retained plugin session does not stay in a drag.
events.length = 0;
await act(async () => {
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 41, button: 0, buttons: 1, pointerType: 'mouse' }));
});
assert.equal(events[0]?.type, 'pointerdown');
assert.equal(events[0]?.pointerId, 41);
await act(async () => { root.unmount(); });
assert.deepEqual(events.at(-1), {
nodeId: 'node-1',
type: 'pointercancel',
x: 60,
y: 60,
pointerId: 41,
button: -1,
buttons: 0,
});
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface leaves wheel to a scrollable host-owned popover panel', async () => {
const { JSDOM } = await import('jsdom');
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'WheelEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, {
ResizeObserver: class {
observe() {}
unobserve() {}
disconnect() {}
},
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
});
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const events: Array<Record<string, unknown>> = [];
const root = createRoot(dom.window.document.getElementById('root')!);
try {
await act(async () => {
root.render(
<PluginRemoteSurface
tree={{
children: [
{
id: 'menu',
type: 1,
element: 'div',
attributes: {
'data-plugin-popover': 'true',
'data-plugin-anchor-x': '40',
'data-plugin-anchor-y': '20',
'data-plugin-popover-width': '240',
'data-plugin-popover-max-height': '160',
open: '',
},
children: [
{
id: 'row',
type: 1,
element: 'button',
attributes: { type: 'button' },
children: [{ id: 'row-t', type: 3, data: 'A tall menu item' }],
},
],
},
],
}}
css=""
settled={true}
onEvent={(e) => { events.push(e as unknown as Record<string, unknown>); }}
/>,
);
});
const popover = dom.window.document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
assert.ok(popover, 'host-owned popover panel is present');
popover!.style.overflow = 'auto';
Object.defineProperty(popover!, 'scrollHeight', { configurable: true, value: 400 });
Object.defineProperty(popover!, 'clientHeight', { configurable: true, value: 160 });
const popoverShadow = shadows.find((s) => popover!.contains((s as ShadowRoot).host)) ?? shadows.at(-1);
const row = popoverShadow!.querySelector('button') as HTMLElement;
assert.ok(row, 'popover row is present');
const wheel = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, deltaX: 0, deltaY: 80, deltaMode: 0, clientX: 120, clientY: 80 });
await act(async () => { row.dispatchEvent(wheel); });
assert.equal(wheel.defaultPrevented, false, 'scrollable popover panel must keep native wheel scrolling');
assert.equal(events.some((e) => e.type === 'wheel'), false, 'wheel over a scrollable popover panel must not be forwarded');
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginRemoteSurface + hostDom end-to-end round-trip supports node drag, incident edge tracking, background pan, and wheel zoom', async () => {
const dom = new JSDOM('<!doctype html><div id="host-root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'CustomEvent', 'ShadowRoot']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
Object.assign(dom.window, { PointerEvent: dom.window.MouseEvent });
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 40, y: 20, width: 600, height: 400, top: 20, left: 40, right: 640, bottom: 420, toJSON() {},
});
// In Electron the visible host renderer and hidden plugin runtime run in separate
// BrowserWindows. Guard host window capture listeners while forwarding into hostDom
// so plugin-side synthetic dispatches do not loop back into the host in a shared JSDOM.
let forwardingToPlugin = false;
const origAdd = dom.window.addEventListener.bind(dom.window);
const origRemove = dom.window.removeEventListener.bind(dom.window);
const wrappedListeners = new WeakMap<EventListenerOrEventListenerObject, EventListener>();
dom.window.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
const capture = typeof options === 'boolean' ? options : Boolean(options?.capture);
if (type === 'pointermove' || type === 'pointerup' || type === 'pointercancel') {
const wrapped: EventListener = (evt) => {
if (capture ? forwardingToPlugin : !forwardingToPlugin) return;
if (typeof listener === 'function') listener(evt);
else listener.handleEvent(evt);
};
wrappedListeners.set(listener, wrapped);
return origAdd(type, wrapped, options);
}
return origAdd(type, listener, options);
}) as typeof dom.window.addEventListener;
dom.window.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
return origRemove(type, wrappedListeners.get(listener) ?? listener, options);
}) as typeof dom.window.removeEventListener;
const shadows: ShadowRoot[] = [];
const nativeAttach = dom.window.Element.prototype.attachShadow;
dom.window.Element.prototype.attachShadow = function (options) {
const s = nativeAttach.call(this, options);
shadows.push(s as unknown as ShadowRoot);
return s;
};
const { act, useEffect, useRef, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const { createPluginRemoteTree } = await import('../../application/state/pluginRemoteTree');
const { registerHostReactView } = await import('../../packages/plugin-sdk/src/hostReact');
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
const remoteTree = createPluginRemoteTree();
const hostRoot = createRoot(document.getElementById('host-root')!);
let pluginReceive: (message: unknown) => void = () => {};
let latestEventId = 0;
let latestAck = 0;
const renderHostSurface = () => {
hostRoot.render(
<PluginRemoteSurface
tree={remoteTree.snapshot()}
css=""
settled={latestAck >= latestEventId}
onEvent={(event) => {
const stamped = { ...event, eventId: ++latestEventId };
assert.equal(validateEvent(stamped), true, `Host event failed contract schema: ${JSON.stringify(validateEvent.errors)}`);
forwardingToPlugin = true;
try {
pluginReceive({ kind: 'host-ui.event', instanceId: 'e2e-1', event: stamped });
} finally {
forwardingToPlugin = false;
}
}}
/>,
);
};
const views = {
onDidReceiveMessage(_id: string, listener: (value: unknown) => void) {
pluginReceive = listener;
return { dispose() {} };
},
postMessage(_id: string, value: unknown) {
const msg = value as { kind?: string; mutations?: unknown[]; acknowledgedEvent?: number };
if (msg.kind !== 'host-ui.update') return;
if (Array.isArray(msg.mutations) && msg.mutations.length > 0) {
remoteTree.apply(msg.mutations);
}
if (typeof msg.acknowledgedEvent === 'number') {
latestAck = msg.acknowledgedEvent;
}
renderHostSurface();
},
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
};
function MiniGraphCanvas() {
const stageRef = useRef<HTMLDivElement | null>(null);
const [nodePos, setNodePos] = useState({ x: 80, y: 100 });
const fixedPos = { x: 280, y: 100 };
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [dragging, setDragging] = useState(false);
const dragRef = useRef<{ kind: 'node' | 'pan'; pointerId: number; startX: number; startY: number; originX: number; originY: number } | null>(null);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (event: WheelEvent) => {
event.preventDefault();
setViewport((prev) => ({
...prev,
zoom: Math.round(prev.zoom * (event.deltaY < 0 ? 1.2 : 0.8) * 100) / 100,
}));
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
// Mirror real canvas window-level drag listeners inside the plugin runtime.
useEffect(() => {
if (!dragging) return;
const onMove = (event: PointerEvent) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
if (drag.kind === 'node') {
setNodePos({ x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) });
} else {
setViewport((prev) => ({ ...prev, x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) }));
}
};
const onUp = (event: PointerEvent) => {
if (dragRef.current?.pointerId === event.pointerId) {
dragRef.current = null;
setDragging(false);
}
};
window.addEventListener('pointermove', onMove as unknown as EventListener);
window.addEventListener('pointerup', onUp as unknown as EventListener);
return () => {
window.removeEventListener('pointermove', onMove as unknown as EventListener);
window.removeEventListener('pointerup', onUp as unknown as EventListener);
};
}, [dragging]);
const edgeLen = Math.round(Math.hypot(fixedPos.x - nodePos.x, fixedPos.y - nodePos.y));
return (
<div
className="e2e-stage"
ref={stageRef}
style={{ overflow: 'hidden', touchAction: 'none' }}
onPointerDown={(e) => {
if (e.button !== 0) return;
dragRef.current = { kind: 'pan', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: viewport.x, originY: viewport.y };
setDragging(true);
}}
>
<div className="e2e-world" style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
<div className="e2e-edge" style={{ width: `${edgeLen}px`, transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }} />
<button
type="button"
className="e2e-node"
style={{ touchAction: 'none', transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.stopPropagation();
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodePos.x, originY: nodePos.y };
setDragging(true);
}}
>
N1
</button>
</div>
</div>
);
}
const makePointer = (type: string, clientX: number, clientY: number, pointerId: number, button: number, buttons: number) => {
const evt = new dom.window.MouseEvent(type, { bubbles: true, cancelable: true, composed: true, clientX, clientY, button, buttons });
Object.defineProperty(evt, 'pointerId', { value: pointerId });
return evt;
};
const registration = registerHostReactView(views as never, 'com.example.e2e-graph', () => <MiniGraphCanvas />);
try {
await act(async () => {
pluginReceive({ kind: 'host-ui.open', instanceId: 'e2e-1' });
await new Promise((resolve) => setTimeout(resolve, 20));
});
const shadow = shadows[0]!;
const stageEl = shadow.querySelector('.e2e-stage') as HTMLElement;
const worldEl = shadow.querySelector('.e2e-world') as HTMLElement;
const edgeEl = shadow.querySelector('.e2e-edge') as HTMLElement;
const nodeEl = shadow.querySelector('.e2e-node') as HTMLElement;
assert.equal(nodeEl.style.transform, 'translate(80px, 100px)');
assert.equal(edgeEl.style.width, '200px');
// Drag node across the visible host surface (pointermove/up dispatched on host window outside the node)
await act(async () => {
nodeEl.dispatchEvent(makePointer('pointerdown', 120, 120, 1, 0, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointermove', 170, 160, 1, -1, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointerup', 170, 160, 1, 0, 0));
await new Promise((resolve) => setTimeout(resolve, 25));
});
assert.equal(nodeEl.style.transform, 'translate(130px, 140px)', 'visible host shadow DOM node must move by (+50, +40)');
assert.equal(edgeEl.style.width, `${Math.round(Math.hypot(280 - 130, 100 - 140))}px`, 'visible host incident edge must follow node');
// Pan background stage and wheel-zoom
await act(async () => {
stageEl.dispatchEvent(makePointer('pointerdown', 300, 200, 2, 0, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointermove', 340, 230, 2, -1, 1));
await new Promise((resolve) => setTimeout(resolve, 15));
});
await act(async () => {
dom.window.dispatchEvent(makePointer('pointerup', 340, 230, 2, 0, 0));
await new Promise((resolve) => setTimeout(resolve, 25));
});
const wheelEvt = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 250, clientY: 180, deltaX: 0, deltaY: -120, deltaMode: 0 });
await act(async () => {
stageEl.dispatchEvent(wheelEvt);
await new Promise((resolve) => setTimeout(resolve, 25));
});
assert.equal(wheelEvt.defaultPrevented, true);
assert.equal(worldEl.style.transform, 'translate(40px, 30px) scale(1.2)', 'visible host shadow DOM world must pan and wheel-zoom');
await act(async () => {
pluginReceive({ kind: 'host-ui.close', instanceId: 'e2e-1' });
});
} finally {
await act(async () => {
registration.dispose();
hostRoot.unmount();
});
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
+11 -523
View File
@@ -19,13 +19,8 @@ export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnVi
const MAX_EVENT_VALUE_LENGTH = 131072;
const SCROLL_THROTTLE_MS = 60;
const POINTER_MOVE_THROTTLE_MS = 24;
const POINTER_MOVE_BACKPRESSURE_MAX_MS = 96;
const WHEEL_THROTTLE_MS = 24;
const SURFACE_EVENTS = [
'click', 'dblclick', 'contextmenu',
'pointerdown', 'pointermove', 'pointerup', 'pointercancel',
'wheel',
'input', 'change',
'keydown', 'keyup',
'focusin', 'focusout',
@@ -342,163 +337,6 @@ function readSelectionRange(
return undefined;
}
function readSurfacePoint(
event: MouseEvent,
surfaceEl: HTMLElement | null,
): { x: number; y: number } {
const rect = surfaceEl?.getBoundingClientRect();
const rawX = rect ? event.clientX - rect.left : event.clientX;
const rawY = rect ? event.clientY - rect.top : event.clientY;
return {
x: Number.isFinite(rawX) ? Math.round(rawX) : 0,
y: Number.isFinite(rawY) ? Math.round(rawY) : 0,
};
}
function readModifierKeys(event: MouseEvent | WheelEvent): {
ctrlKey?: true;
metaKey?: true;
altKey?: true;
shiftKey?: true;
} {
return {
...(event.ctrlKey ? { ctrlKey: true as const } : {}),
...(event.metaKey ? { metaKey: true as const } : {}),
...(event.altKey ? { altKey: true as const } : {}),
...(event.shiftKey ? { shiftKey: true as const } : {}),
};
}
function readPointerId(event: Event): number {
const raw = (event as PointerEvent).pointerId;
if (typeof raw === 'number' && Number.isFinite(raw)) {
return Math.max(-2147483648, Math.min(2147483647, Math.trunc(raw)));
}
return 1;
}
function readPointerType(event: Event): 'mouse' | 'pen' | 'touch' | undefined {
const raw = (event as PointerEvent).pointerType;
return raw === 'mouse' || raw === 'pen' || raw === 'touch' ? raw : undefined;
}
function readPointerButton(event: MouseEvent): number {
return typeof event.button === 'number' && Number.isFinite(event.button)
? Math.max(-1, Math.min(32, Math.trunc(event.button)))
: 0;
}
function readPointerButtons(event: MouseEvent): number {
return typeof event.buttons === 'number' && Number.isFinite(event.buttons)
? Math.max(0, Math.min(65535, Math.trunc(event.buttons)))
: 0;
}
function roundWheelDelta(value: number): number {
return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
}
function isScrollableOverflowValue(value: string | undefined): boolean {
return value === 'auto' || value === 'scroll' || value === 'overlay';
}
function readOverflowToken(value: string | undefined, axis: 'x' | 'y'): string | undefined {
if (!value) return undefined;
const parts = value.trim().split(/\s+/);
return axis === 'y' ? (parts[1] ?? parts[0]) : parts[0];
}
function readAxisOverflow(
el: HTMLElement,
style: CSSStyleDeclaration | undefined,
axis: 'x' | 'y',
): string | undefined {
// Prefer a scrollable value from computed or inline styles. Some test DOMs
// report the initial `visible` computed overflow even when the element has
// an inline `overflow: auto` shorthand.
const candidates = [
axis === 'y' ? style?.overflowY : style?.overflowX,
axis === 'y' ? el.style.overflowY : el.style.overflowX,
readOverflowToken(style?.overflow, axis),
readOverflowToken(el.style.overflow, axis),
];
for (const value of candidates) {
if (isScrollableOverflowValue(value)) return value;
}
return candidates.find((value) => value && value !== 'visible') ?? candidates[0];
}
function canElementScrollForWheel(
el: HTMLElement,
view: Window & typeof globalThis,
deltaX: number,
deltaY: number,
): boolean {
const style = view.getComputedStyle?.(el);
const canScrollY = deltaY !== 0
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'y'))
&& el.scrollHeight > el.clientHeight + 1;
const canScrollX = deltaX !== 0
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'x'))
&& el.scrollWidth > el.clientWidth + 1;
return canScrollY || canScrollX;
}
/**
* Wheel vs native scroll rule:
* Walk ancestors inside the shadow root (and then the surface's own scroll host
* unless a non-scrollable element declares `touch-action: none` to claim canvas
* gestures). If an ancestor has `overflow: auto|scroll|overlay` with actual
* overflow along the wheel axis, leave the event to native scrolling (existing
* throttled `scroll` events still forward). Otherwise `preventDefault()` so the
* surrounding workbench does not steal the gesture, and forward coalesced `wheel`.
*/
function hasScrollableAncestorForWheel(
target: HTMLElement,
shadow: ShadowRoot,
host: HTMLElement | null,
view: Window & typeof globalThis,
deltaX: number,
deltaY: number,
): boolean {
let current: HTMLElement | null = target;
let hitGestureBoundary = false;
while (current) {
if (canElementScrollForWheel(current, view, deltaX, deltaY)) return true;
const touchAction = view.getComputedStyle?.(current)?.touchAction || current.style.touchAction;
if (touchAction === 'none') {
hitGestureBoundary = true;
break;
}
const parent = current.parentElement;
if (!parent || parent.getRootNode() !== shadow) break;
current = parent;
}
if (!hitGestureBoundary && host && canElementScrollForWheel(host, view, deltaX, deltaY)) {
return true;
}
// Nested popover surfaces live in a portaled PluginViewPopover panel. That
// panel (not the inner overflow-auto host) is often the only element with a
// bounded max-height, so include it when deciding who owns the wheel.
if (!hitGestureBoundary) {
const popover = (host ?? target).closest?.('[data-plugin-view-popover]') as HTMLElement | null;
if (popover && canElementScrollForWheel(popover, view, deltaX, deltaY)) return true;
}
return false;
}
type ActivePointerGesture = {
nodeId: string;
pointerId: number;
capturedElement: HTMLElement | null;
lastSentX: number;
lastSentY: number;
lastMoveSentAt: number;
pendingMove: PluginSurfaceEvent | null;
pendingMoveSince: number;
moveTimer: ReturnType<typeof setTimeout> | null;
};
/** 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<string>; onEvent(event: PluginSurfaceEvent): void }) {
const checkedTree = useMemo(() => {
@@ -535,8 +373,6 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
const surfaceRef = useRef<HTMLDivElement>(null);
const hostRef = useRef<HTMLDivElement>(null);
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
const settledRef = useRef(settled); settledRef.current = settled;
const flushPendingMovesRef = useRef<(() => void) | null>(null);
const shadowRef = useRef<ShadowRoot | null>(null);
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
@@ -551,10 +387,6 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
setShadowHost(host);
}, []);
useEffect(() => {
if (settled) flushPendingMovesRef.current?.();
}, [settled]);
const surfaceContextValue = useMemo(
() => ({ css, onEvent, depth, shadowHost }),
[css, onEvent, depth, shadowHost],
@@ -562,15 +394,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
useEffect(() => {
if (!shadow) return;
const view = shadow.ownerDocument.defaultView;
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
const pendingScroll = new Map<string, PluginSurfaceEvent>();
const activeGestures = new Map<number, ActivePointerGesture>();
const handledPointerEvents = new WeakSet<Event>();
let windowPointerListenersAttached = false;
let wheelTimer: ReturnType<typeof setTimeout> | null = null;
let pendingWheel: PluginSurfaceEvent | null = null;
let lastWheelSentAt = 0;
const flushScroll = (nodeId: string) => {
scrollTimers.delete(nodeId);
@@ -581,203 +406,10 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
}
};
const flushWheel = () => {
if (wheelTimer !== null) {
clearTimeout(wheelTimer);
wheelTimer = null;
}
const evt = pendingWheel;
pendingWheel = null;
if (!evt || ((evt.deltaX ?? 0) === 0 && (evt.deltaY ?? 0) === 0)) return;
lastWheelSentAt = Date.now();
onEventRef.current(evt);
};
const emitGestureMove = (gesture: ActivePointerGesture, moveEvent: PluginSurfaceEvent, now: number) => {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
gesture.pendingMove = null;
gesture.pendingMoveSince = 0;
if (moveEvent.x === gesture.lastSentX && moveEvent.y === gesture.lastSentY) return;
gesture.lastSentX = moveEvent.x ?? gesture.lastSentX;
gesture.lastSentY = moveEvent.y ?? gesture.lastSentY;
gesture.lastMoveSentAt = now;
onEventRef.current(moveEvent);
};
const scheduleGestureMoveFlush = (gesture: ActivePointerGesture) => {
if (gesture.moveTimer !== null || !gesture.pendingMove) return;
const now = Date.now();
const throttleWait = Math.max(0, POINTER_MOVE_THROTTLE_MS - (now - gesture.lastMoveSentAt));
const backpressureWait = settledRef.current
? 0
: Math.max(0, POINTER_MOVE_BACKPRESSURE_MAX_MS - (now - gesture.pendingMoveSince));
const delay = Math.max(1, throttleWait, backpressureWait);
gesture.moveTimer = setTimeout(() => {
gesture.moveTimer = null;
if (activeGestures.get(gesture.pointerId) !== gesture || !gesture.pendingMove) return;
const tickNow = Date.now();
const elapsed = tickNow - gesture.lastMoveSentAt;
const waitedEnough = settledRef.current || tickNow - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS;
if (elapsed >= POINTER_MOVE_THROTTLE_MS && waitedEnough) {
emitGestureMove(gesture, gesture.pendingMove, tickNow);
} else {
scheduleGestureMoveFlush(gesture);
}
}, delay);
};
const releaseGesture = (gesture: ActivePointerGesture) => {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
gesture.pendingMove = null;
gesture.pendingMoveSince = 0;
if (gesture.capturedElement) {
try {
gesture.capturedElement.releasePointerCapture?.(gesture.pointerId);
} catch {
// Capture may already have been released natively.
}
gesture.capturedElement = null;
}
activeGestures.delete(gesture.pointerId);
if (activeGestures.size === 0) detachWindowPointerListeners();
};
/**
* Active pointer gestures are tracked at the host surface so plugin drags
* continue after leaving the originating node or surface (plugin-side
* setPointerCapture cannot capture the visible host pointer). Moves skip
* unchanged coordinates, coalesce under POINTER_MOVE_THROTTLE_MS, and adapt
* to host-ui acknowledgedEvent backpressure via `settled`.
*/
const onGesturePointerEvent = (event: Event) => {
if (!view || activeGestures.size === 0 || handledPointerEvents.has(event)) return;
const pointerId = readPointerId(event);
const gesture = activeGestures.get(pointerId);
if (!gesture) return;
handledPointerEvents.add(event);
const isMouseLike = event instanceof view.MouseEvent;
const coords = isMouseLike
? readSurfacePoint(event, surfaceRef.current ?? hostRef.current)
: { x: gesture.lastSentX, y: gesture.lastSentY };
const pointerType = readPointerType(event);
const button = isMouseLike ? readPointerButton(event) : -1;
const buttons = isMouseLike ? readPointerButtons(event) : 0;
const modifiers = isMouseLike ? readModifierKeys(event) : {};
if (event.type === 'pointermove') {
const moveEvent: PluginSurfaceEvent = {
nodeId: gesture.nodeId,
type: 'pointermove',
...coords,
pointerId: gesture.pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
};
if (gesture.pendingMove === null && coords.x === gesture.lastSentX && coords.y === gesture.lastSentY) {
return;
}
const now = Date.now();
const elapsed = now - gesture.lastMoveSentAt;
const canSendNow =
elapsed >= POINTER_MOVE_THROTTLE_MS
&& (settledRef.current || (gesture.pendingMoveSince > 0 && now - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS));
if (canSendNow) {
emitGestureMove(gesture, moveEvent, now);
} else {
gesture.pendingMove = moveEvent;
if (gesture.pendingMoveSince === 0) gesture.pendingMoveSince = now;
scheduleGestureMoveFlush(gesture);
}
return;
}
if (event.type === 'pointerup' && gesture.pendingMove) {
emitGestureMove(gesture, gesture.pendingMove, Date.now());
}
releaseGesture(gesture);
onEventRef.current({
nodeId: gesture.nodeId,
type: event.type as 'pointerup' | 'pointercancel',
...coords,
pointerId: gesture.pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
});
};
const onWindowBlur = (event: Event) => {
if (!view || event.target !== view || activeGestures.size === 0) return;
for (const gesture of [...activeGestures.values()]) {
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
releaseGesture(gesture);
onEventRef.current({
nodeId,
type: 'pointercancel',
x: lastSentX,
y: lastSentY,
pointerId,
button: -1,
buttons: 0,
});
}
};
const attachWindowPointerListeners = () => {
if (!view || windowPointerListenersAttached) return;
windowPointerListenersAttached = true;
view.addEventListener('pointermove', onGesturePointerEvent, true);
view.addEventListener('pointerup', onGesturePointerEvent, true);
view.addEventListener('pointercancel', onGesturePointerEvent, true);
view.addEventListener('blur', onWindowBlur, false);
};
const detachWindowPointerListeners = () => {
if (!view || !windowPointerListenersAttached) return;
windowPointerListenersAttached = false;
view.removeEventListener('pointermove', onGesturePointerEvent, true);
view.removeEventListener('pointerup', onGesturePointerEvent, true);
view.removeEventListener('pointercancel', onGesturePointerEvent, true);
view.removeEventListener('blur', onWindowBlur, false);
};
flushPendingMovesRef.current = () => {
const now = Date.now();
for (const gesture of activeGestures.values()) {
if (!gesture.pendingMove) continue;
const elapsed = now - gesture.lastMoveSentAt;
if (elapsed >= POINTER_MOVE_THROTTLE_MS) {
emitGestureMove(gesture, gesture.pendingMove, now);
} else {
if (gesture.moveTimer !== null) {
clearTimeout(gesture.moveTimer);
gesture.moveTimer = null;
}
scheduleGestureMoveFlush(gesture);
}
}
};
const listener = (event: Event) => {
if (!view || !SURFACE_EVENT_SET.has(event.type)) return;
if (event.type === 'pointermove' || event.type === 'pointerup' || event.type === 'pointercancel') {
onGesturePointerEvent(event);
return;
}
const target = event.target;
if (!(target instanceof view.HTMLElement)) return;
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') {
@@ -788,12 +420,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
}
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
// Internal events inside slotted host-rendered widgets or split-pane dividers are handled by the widget itself.
if (
target.closest('[data-plugin-widget-host]')
|| target.closest('[data-split-handle]')
|| SLOTTED_WIDGET_KINDS.has(target.dataset.pluginWidget ?? '')
) return;
// 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();
@@ -808,120 +436,6 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
if (!nodeId) return;
if (event.type === 'pointerdown') {
if (!(event instanceof view.MouseEvent)) return;
const pointerId = readPointerId(event);
const existing = activeGestures.get(pointerId);
if (existing) releaseGesture(existing);
const coords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
const pointerType = readPointerType(event);
const button = readPointerButton(event);
const buttons = readPointerButtons(event);
const modifiers = readModifierKeys(event);
// Engage native pointer capture only on non-control elements that explicitly
// declare `touch-action: none` so text selection, native form controls, and
// normal button click cancellation stay intact. Window capture listeners still
// sustain cross-node/cross-surface drags for every remote node.
let capturedElement: HTMLElement | null = null;
if (!target.matches('input, textarea, select, option')) {
const touchAction = view.getComputedStyle?.(target)?.touchAction || target.style.touchAction;
if (touchAction === 'none') {
try {
target.setPointerCapture?.(pointerId);
capturedElement = target;
} catch {
// Synthetic or unsupported pointer capture environments rely on window listeners.
}
}
}
activeGestures.set(pointerId, {
nodeId,
pointerId,
capturedElement,
lastSentX: coords.x,
lastSentY: coords.y,
lastMoveSentAt: 0,
pendingMove: null,
pendingMoveSince: 0,
moveTimer: null,
});
attachWindowPointerListeners();
onEventRef.current({
nodeId,
type: 'pointerdown',
...coords,
pointerId,
button,
buttons,
...(pointerType ? { pointerType } : {}),
...modifiers,
});
return;
}
if (event.type === 'wheel') {
const wheel = event as WheelEvent;
const deltaX = roundWheelDelta(wheel.deltaX);
const deltaY = roundWheelDelta(wheel.deltaY);
if (deltaX === 0 && deltaY === 0) return;
if (hasScrollableAncestorForWheel(target, shadow, hostRef.current, view, deltaX, deltaY)) {
return;
}
event.preventDefault();
const rawMode = wheel.deltaMode;
const deltaMode = typeof rawMode === 'number' && Number.isFinite(rawMode)
? Math.max(0, Math.min(2, Math.trunc(rawMode)))
: 0;
const coords = readSurfacePoint(wheel, surfaceRef.current ?? hostRef.current);
const modifiers = readModifierKeys(wheel);
const nextWheel: PluginSurfaceEvent = {
nodeId,
type: 'wheel',
...coords,
deltaX,
deltaY,
deltaMode,
...modifiers,
};
const now = Date.now();
if (!pendingWheel && now - lastWheelSentAt >= WHEEL_THROTTLE_MS) {
lastWheelSentAt = now;
onEventRef.current(nextWheel);
return;
}
if (
pendingWheel
&& pendingWheel.nodeId === nodeId
&& pendingWheel.deltaMode === deltaMode
&& Boolean(pendingWheel.ctrlKey) === Boolean(modifiers.ctrlKey)
&& Boolean(pendingWheel.metaKey) === Boolean(modifiers.metaKey)
&& Boolean(pendingWheel.altKey) === Boolean(modifiers.altKey)
&& Boolean(pendingWheel.shiftKey) === Boolean(modifiers.shiftKey)
) {
pendingWheel = {
...pendingWheel,
...coords,
deltaX: roundWheelDelta((pendingWheel.deltaX ?? 0) + deltaX),
deltaY: roundWheelDelta((pendingWheel.deltaY ?? 0) + deltaY),
};
} else {
if (pendingWheel) flushWheel();
pendingWheel = nextWheel;
}
if (wheelTimer === null) {
const delay = Math.max(1, WHEEL_THROTTLE_MS - (Date.now() - lastWheelSentAt));
wheelTimer = setTimeout(flushWheel, delay);
}
return;
}
if (event.type === 'scroll') {
const scrollEvent: PluginSurfaceEvent = {
nodeId,
@@ -949,7 +463,11 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
let pointerCoords: { x: number; y: number } | undefined;
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
pointerCoords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
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 =
@@ -970,21 +488,12 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
});
};
for (const event of SURFACE_EVENTS) {
shadow.addEventListener(event, listener, event === 'wheel' ? { capture: true, passive: false } : true);
}
// Chromium only treats wheel as cancelable when a non-passive listener is
// registered on a real element. A closed ShadowRoot listener alone can see
// `cancelable: false`, so also listen on the shadow host (no-op targeting;
// the shadow capture listener still owns forwarding).
const shadowHostEl = hostRef.current;
const hostWheelOptions: AddEventListenerOptions = { capture: true, passive: false };
const hostWheelListener = (_event: Event) => {};
shadowHostEl?.addEventListener('wheel', hostWheelListener, hostWheelOptions);
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
// When a full-bleed plugin view is visible and focus sits on document.body (e.g.
// right after tab switch or drawer close), forward global Cmd/Ctrl+K / Cmd/Ctrl+S
// into the plugin so its Command Palette and Save shortcuts work reliably.
const view = shadow.ownerDocument.defaultView;
const onWindowKeyDown = (event: KeyboardEvent) => {
if (depth !== 0 || event.defaultPrevented) return;
const surfaceEl = surfaceRef.current;
@@ -1022,28 +531,7 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
view?.addEventListener('keydown', onWindowKeyDown, false);
return () => {
flushPendingMovesRef.current = null;
view?.removeEventListener('keydown', onWindowKeyDown, false);
shadowHostEl?.removeEventListener('wheel', hostWheelListener, hostWheelOptions);
// The retained plugin session keeps its SDK DOM when this surface unmounts
// (tab hide). Send pointercancel so plugin drags do not stay stuck.
for (const gesture of [...activeGestures.values()]) {
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
releaseGesture(gesture);
onEventRef.current({
nodeId,
type: 'pointercancel',
x: lastSentX,
y: lastSentY,
pointerId,
button: -1,
buttons: 0,
});
}
detachWindowPointerListeners();
if (wheelTimer !== null) clearTimeout(wheelTimer);
wheelTimer = null;
pendingWheel = null;
for (const timer of scrollTimers.values()) clearTimeout(timer);
scrollTimers.clear();
pendingScroll.clear();
@@ -1,184 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
function installDom() {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
pretendToBeVisual: true,
url: 'http://localhost',
});
const previous = new Map<string, PropertyDescriptor | undefined>();
const install = (key: string, value: unknown) => {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
for (const key of [
'window',
'document',
'navigator',
'HTMLElement',
'HTMLButtonElement',
'HTMLInputElement',
'Element',
'SVGElement',
'Node',
'NodeFilter',
'MutationObserver',
'CustomEvent',
'Event',
'KeyboardEvent',
'MouseEvent',
]) {
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
}
class MockResizeObserver {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) {
this.cb = cb;
}
observe(target: Element) {
this.cb([
{
target,
borderBoxSize: [{ inlineSize: 960, blockSize: 420 }],
contentRect: { width: 960, height: 420 },
},
]);
}
unobserve() {}
disconnect() {}
}
Object.assign(dom.window, {
PointerEvent: dom.window.MouseEvent,
ResizeObserver: MockResizeObserver,
});
install('PointerEvent', dom.window.MouseEvent);
install('ResizeObserver', MockResizeObserver);
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
install('requestAnimationFrame', dom.window.requestAnimationFrame.bind(dom.window));
install('cancelAnimationFrame', dom.window.cancelAnimationFrame.bind(dom.window));
install('IS_REACT_ACT_ENVIRONMENT', true);
dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(0, 0, 960, 420);
return {
dom,
cleanup() {
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
},
};
}
test('PluginDataGrid header clicks toggle sort on single clicks, ignore double-click second click, and skip non-sortable columns', async () => {
const env = installDom();
const { act, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginDataGrid, SORT_CLICK_DEBOUNCE_MS } = await import('./PluginDataGrid');
type SortState = { column: string; direction: 'asc' | 'desc' } | null;
const events: Array<{ name: string; detail?: Record<string, unknown> }> = [];
let resetSort!: () => void;
function ControlledGrid() {
const [sort, setSort] = useState<SortState>(null);
resetSort = () => setSort(null);
return (
<PluginDataGrid
columns={[
{ name: 'email', type: 'varchar' },
{ name: 'payload', type: 'jsonb', sortable: false },
]}
rows={[
{ email: 'alice@example.com', payload: '{}' },
{ email: 'bob@example.com', payload: '{}' },
]}
sort={sort}
onWidgetEvent={(name, detail) => {
events.push({ name, detail });
if (name === 'sortChange' && detail) {
setSort({
column: String(detail.column),
direction: detail.direction === 'desc' ? 'desc' : 'asc',
});
}
}}
/>
);
}
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<ControlledGrid />);
});
const emailBtn = document.querySelector<HTMLButtonElement>('[role="columnheader"][data-col-name="email"] button');
const payloadBtn = document.querySelector<HTMLButtonElement>('[role="columnheader"][data-col-name="payload"] button');
assert.ok(emailBtn, 'sortable email header button mounted');
assert.ok(payloadBtn, 'non-sortable payload header button mounted');
assert.equal(payloadBtn.disabled, true);
// 1. Single click (detail 1) -> asc; immediate second detail=1 click is debounced
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
]);
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
]);
// 2. Genuine later single click after debounce window (detail 1) -> desc
await new Promise((resolve) => setTimeout(resolve, SORT_CLICK_DEBOUNCE_MS + 30));
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
{ name: 'sortChange', detail: { column: 'email', direction: 'desc' } },
]);
// 3. Double-click sequence: click (detail 1), click (detail 2), dblclick -> only one sortChange total
await new Promise((resolve) => setTimeout(resolve, SORT_CLICK_DEBOUNCE_MS + 30));
events.length = 0;
await act(async () => {
resetSort();
});
let dblClickBubbled = false;
document.body.addEventListener('dblclick', () => {
dblClickBubbled = true;
}, { once: true });
const dblClickEvent = new env.dom.window.MouseEvent('dblclick', { bubbles: true, cancelable: true, detail: 2 });
await act(async () => {
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
emailBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 2 }));
emailBtn.dispatchEvent(dblClickEvent);
});
assert.deepEqual(events, [
{ name: 'sortChange', detail: { column: 'email', direction: 'asc' } },
]);
assert.equal(dblClickEvent.defaultPrevented, true, 'header dblclick should preventDefault');
assert.equal(dblClickBubbled, false, 'header dblclick should not bubble out');
// 4. Non-sortable column emits nothing
events.length = 0;
await act(async () => {
payloadBtn.click();
payloadBtn.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }));
});
assert.deepEqual(events, []);
} finally {
await act(async () => {
root.unmount();
});
env.cleanup();
}
});
@@ -15,7 +15,6 @@ const GUTTER_WIDTH = 64;
const DEFAULT_COL_WIDTH = 156;
const MIN_COL_WIDTH = 68;
const MAX_COL_WIDTH = 640;
export const SORT_CLICK_DEBOUNCE_MS = 500;
export interface PluginDataGridProps extends PluginDataGridWidgetProps {
onWidgetEvent: PluginWidgetEventCallback;
@@ -61,7 +60,6 @@ export function PluginDataGrid({
const scrollRef = useRef<HTMLDivElement>(null);
const editInputRef = useRef<HTMLInputElement>(null);
const blurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastSortClickAtRef = useRef<number | null>(null);
const [colWidths, setColWidths] = useState<Record<string, number>>({});
const [activeCell, setActiveCell] = useState<{ rowIndex: number; colIndex: number } | null>(null);
@@ -225,18 +223,8 @@ export function PluginDataGrid({
onWidgetEvent('rowSelect', { selectedRowIndices: next });
}, [totalRows, selectedSet.size, onWidgetEvent]);
const handleSortClick = useCallback((col: PluginDataGridColumn, event?: React.MouseEvent<HTMLButtonElement>) => {
const handleSortClick = useCallback((col: PluginDataGridColumn) => {
if (col.sortable === false) return;
if (event && event.detail > 1) return;
const now = Date.now();
if (
lastSortClickAtRef.current !== null &&
now >= lastSortClickAtRef.current &&
now - lastSortClickAtRef.current < SORT_CLICK_DEBOUNCE_MS
) {
return;
}
lastSortClickAtRef.current = now;
const nextDirection = sort?.column === col.name && sort.direction === 'asc' ? 'desc' : 'asc';
onWidgetEvent('sortChange', { column: col.name, direction: nextDirection });
}, [sort, onWidgetEvent]);
@@ -464,11 +452,7 @@ export function PluginDataGrid({
<button
type="button"
disabled={!sortable}
onClick={(event) => handleSortClick(col, event)}
onDoubleClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
onClick={() => handleSortClick(col)}
className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`}
title={col.foreignKey
? `${col.name}${col.type ? ` (${col.type})` : ''} -> ${col.foreignKey.schema ? `${col.foreignKey.schema}.` : ''}${col.foreignKey.table}.${col.foreignKey.column}`
@@ -556,9 +556,6 @@ function scheduleTrayPanelIdleDestroy(panelWin) {
&& !trayPanelShowWhenReady
) {
panelWin.destroy();
if (panelWin.isDestroyed() && tray) {
ensureTrayPanelWindow();
}
}
} catch {
// ignore
@@ -1154,9 +1151,6 @@ function createTray() {
});
}
// Load the hidden panel before the first click needs it.
ensureTrayPanelWindow();
console.log("[GlobalShortcut] System tray created");
} catch (err) {
console.error("[GlobalShortcut] Error creating tray:", err);
+24 -102
View File
@@ -83,13 +83,18 @@ function createElectronStub() {
}
}
const electronModule = {
return {
Tray: FakeTray,
Menu: {
buildFromTemplate(template) {
return { template };
},
},
BrowserWindow: {
getAllWindows() {
return [];
},
},
globalShortcut: {
register() {
return true;
@@ -123,8 +128,6 @@ function createElectronStub() {
quit() {},
},
};
installFakeTrayPanelWindow(electronModule);
return electronModule;
}
function createAppLockControllerStub(initialState = { locked: false, reason: null }) {
@@ -792,8 +795,14 @@ test("tray icon event registration is platform-dependent", async () => {
const win = new FakeWindow();
win.minimized = true;
const initializedElectronModule = createElectronStub();
initializedElectronModule.BrowserWindow.getAllWindows = () => [win];
const initializedElectronModule = {
...createElectronStub(),
BrowserWindow: {
getAllWindows() {
return [win];
},
},
};
bridge.init({
electronModule: initializedElectronModule,
getMainWindow: () => win,
@@ -829,8 +838,14 @@ test("tray icon event registration is platform-dependent", async () => {
const appLockController = createAppLockControllerStub();
const win = new FakeWindow();
win.minimized = true;
const initializedElectronModule = createElectronStub();
initializedElectronModule.BrowserWindow.getAllWindows = () => [win];
const initializedElectronModule = {
...createElectronStub(),
BrowserWindow: {
getAllWindows() {
return [win];
},
},
};
bridge.init({
electronModule: initializedElectronModule,
getMainWindow: () => win,
@@ -1348,7 +1363,6 @@ test("tray menu updates refresh an already open tray panel", async () => {
class FakePanelWindow extends FakeWindow {
constructor() {
super();
this.visible = false;
const webContents = new EventEmitter();
webContents.send = (channel, ...args) => {
sentMessages.push([channel, ...args]);
@@ -1523,9 +1537,6 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
height: opts.height,
};
this.setBoundsCalls = [];
this.loadURLCalls = [];
this.showCalls = 0;
this.focusCalls = 0;
this.destroyed = false;
this.visible = false;
const webContents = new EventEmitter();
@@ -1533,9 +1544,7 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
this.webContents = webContents;
}
async loadURL(url) {
this.loadURLCalls.push(url);
}
async loadURL() {}
getBounds() {
if (getBoundsSize) return { ...this.bounds, ...getBoundsSize };
return { ...this.bounds };
@@ -1547,24 +1556,15 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
isDestroyed() {
return this.destroyed;
}
isVisible() {
return this.visible;
}
show() {
this.showCalls += 1;
this.visible = true;
this.emit("show");
}
hide() {
this.visible = false;
this.emit("hide");
}
focus() {
this.focusCalls += 1;
}
focus() {}
destroy() {
this.destroyed = true;
this.emit("closed");
}
}
@@ -1574,84 +1574,6 @@ function installFakeTrayPanelWindow(electronModule, { getBoundsSize } = {}) {
return FakePanelWindow;
}
test("createTray preloads the hidden panel without showing, focusing, or positioning it", async () => {
await withPlatform("win32", async () => {
const bridge = loadBridge();
const electronModule = createElectronStub();
const FakePanelWindow = electronModule.BrowserWindow;
bridge.init({ electronModule, getMainWindow: () => null });
try {
bridge.createTray();
assert.ok(bridge.getTray());
assert.equal(FakePanelWindow.instances.length, 1);
const panelWin = FakePanelWindow.instances[0];
assert.equal(bridge.getTrayPanelWindow(), panelWin);
assert.equal(panelWin.opts.show, false);
assert.equal(panelWin.opts.skipTaskbar, true);
assert.equal(panelWin.loadURLCalls.length, 1);
assert.match(panelWin.loadURLCalls[0], /#\/tray$/);
panelWin.webContents.emit("did-finish-load");
assert.equal(panelWin.isVisible(), false);
assert.equal(panelWin.showCalls, 0);
assert.equal(panelWin.focusCalls, 0);
assert.deepEqual(panelWin.setBoundsCalls, []);
} finally {
bridge.cleanup();
}
});
});
test("idle destroy rewarms the hidden tray panel for the next click", async () => {
await withPatchedTimers(async ({ flushNextTimer, getPendingTimerCount }) => {
await withPlatform("win32", async () => {
const bridge = loadBridge();
const electronModule = createElectronStub();
const FakePanelWindow = electronModule.BrowserWindow;
const eventBounds = { x: 1200, y: 860, width: 24, height: 24 };
electronModule.screen = {
getDisplayNearestPoint: () => ({ workArea: { x: 0, y: 0, width: 1440, height: 860 } }),
};
try {
await enableCloseToTray(bridge, electronModule);
const rightClick = bridge.getTray().handlers.get("right-click");
const firstWin = FakePanelWindow.instances[0];
firstWin.webContents.emit("did-finish-load");
rightClick(null, eventBounds);
assert.equal(firstWin.showCalls, 1);
rightClick(null, eventBounds);
assert.equal(firstWin.isVisible(), false);
assert.equal(getPendingTimerCount(), 1);
assert.equal(flushNextTimer(), true);
assert.equal(firstWin.isDestroyed(), true);
assert.equal(FakePanelWindow.instances.length, 2);
const secondWin = FakePanelWindow.instances[1];
assert.equal(bridge.getTrayPanelWindow(), secondWin);
assert.equal(secondWin.opts.show, false);
assert.equal(secondWin.opts.skipTaskbar, true);
assert.deepEqual(secondWin.loadURLCalls, firstWin.loadURLCalls);
assert.equal(secondWin.showCalls, 0);
assert.equal(secondWin.focusCalls, 0);
assert.deepEqual(secondWin.setBoundsCalls, []);
secondWin.webContents.emit("did-finish-load");
assert.equal(secondWin.isVisible(), false);
assert.equal(secondWin.showCalls, 0);
assert.equal(getPendingTimerCount(), 0);
rightClick(null, eventBounds);
assert.equal(FakePanelWindow.instances.length, 2);
assert.equal(secondWin.showCalls, 1);
assert.equal(secondWin.focusCalls, 1);
} finally {
bridge.cleanup();
}
});
});
});
test("Windows right-click places the designed panel above the taskbar from event bounds", async () => {
await withPlatform("win32", async () => {
const { placeTrayPanel } = require("./trayPanelBounds.cjs");
@@ -4293,11 +4293,6 @@
"reset",
"dblclick",
"contextmenu",
"pointerdown",
"pointermove",
"pointerup",
"pointercancel",
"wheel",
"scroll",
"widget"
]
@@ -4348,39 +4343,6 @@
"y": {
"type": "number"
},
"pointerId": {
"type": "integer",
"minimum": -2147483648,
"maximum": 2147483647
},
"button": {
"type": "integer",
"minimum": -1,
"maximum": 32
},
"buttons": {
"type": "integer",
"minimum": 0,
"maximum": 65535
},
"pointerType": {
"enum": [
"mouse",
"pen",
"touch"
]
},
"deltaX": {
"type": "number"
},
"deltaY": {
"type": "number"
},
"deltaMode": {
"type": "integer",
"minimum": 0,
"maximum": 2
},
"scrollTop": {
"type": "number",
"minimum": 0
@@ -196,26 +196,9 @@ test("extended surface and widget events validate schema and bound detail payloa
const f = fixture(); await open(f);
await f.host.event("instance-1", { nodeId: "1", type: "contextmenu", x: 42, y: 84 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "dblclick", x: 10, y: 20 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointerdown", x: 120, y: 80, pointerId: 1, button: 0, buttons: 1, pointerType: "mouse" }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointermove", x: 165, y: 95, pointerId: 1, button: -1, buttons: 1, pointerType: "mouse", shiftKey: true }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointerup", x: 165, y: 95, pointerId: 1, button: 0, buttons: 0, pointerType: "mouse" }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "pointercancel", x: -10, y: 40, pointerId: 1, button: -1, buttons: 0 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "wheel", x: 200, y: 150, deltaX: 0, deltaY: -120.5, deltaMode: 0, ctrlKey: true }, f.sender);
assert.equal(f.notifications.at(-1)[2].message.event.type, "wheel");
assert.equal(f.notifications.at(-1)[2].message.event.deltaY, -120.5);
await f.host.event("instance-1", { nodeId: "1", type: "scroll", scrollTop: 100, scrollLeft: 0, clientHeight: 400, clientWidth: 600 }, f.sender);
await f.host.event("instance-1", { nodeId: "1", type: "widget", widgetEvent: "execute", detail: { value: "SELECT 1;", currentStatement: "SELECT 1" } }, f.sender);
assert.equal(f.notifications.at(-1)[2].message.event.widgetEvent, "execute");
for (const invalid of [
{ nodeId: "1", type: "pointerdown", pointerId: 1.5 },
{ nodeId: "1", type: "pointerdown", button: -2 },
{ nodeId: "1", type: "pointerdown", buttons: -1 },
{ nodeId: "1", type: "pointerdown", pointerType: "stylus" },
{ nodeId: "1", type: "wheel", deltaMode: 3 },
{ nodeId: "1", type: "wheel", deltaY: -100, unknownField: true },
]) {
await assert.rejects(f.host.event("instance-1", invalid, f.sender), /Invalid plugin view event/);
}
await assert.rejects(
f.host.event("instance-1", { nodeId: "1", type: "widget", widgetEvent: "change", detail: { value: "x".repeat(260 * 1024) } }, f.sender),
/exceeds limits/,
@@ -3690,11 +3690,6 @@
"reset",
"dblclick",
"contextmenu",
"pointerdown",
"pointermove",
"pointerup",
"pointercancel",
"wheel",
"scroll",
"widget"
]
@@ -3745,39 +3740,6 @@
"y": {
"type": "number"
},
"pointerId": {
"type": "integer",
"minimum": -2147483648,
"maximum": 2147483647
},
"button": {
"type": "integer",
"minimum": -1,
"maximum": 32
},
"buttons": {
"type": "integer",
"minimum": 0,
"maximum": 65535
},
"pointerType": {
"enum": [
"mouse",
"pen",
"touch"
]
},
"deltaX": {
"type": "number"
},
"deltaY": {
"type": "number"
},
"deltaMode": {
"type": "integer",
"minimum": 0,
"maximum": 2
},
"scrollTop": {
"type": "number",
"minimum": 0
@@ -1492,26 +1492,3 @@ test("settings accept host-owned groups but reject custom rendering and settings
assert.equal(view({ id: "com.example.contract-test.view", title: "Custom", location }), true, JSON.stringify(view.errors));
}
});
test("HostDrawnViewEvent accepts pointer and wheel fields while rejecting out-of-range or unknown fields", () => {
const validate = validator("HostDrawnViewEvent");
for (const valid of [
{ nodeId: "stage", type: "pointerdown", x: 120, y: 80, pointerId: 1, button: 0, buttons: 1, pointerType: "mouse" },
{ nodeId: "stage", type: "pointermove", x: -12, y: 240, pointerId: 1, button: -1, buttons: 1, shiftKey: true },
{ nodeId: "stage", type: "pointerup", x: 140, y: 90, pointerId: 1, button: 0, buttons: 0, pointerType: "touch" },
{ nodeId: "stage", type: "pointercancel", x: 140, y: 90, pointerId: 2, button: -1, buttons: 0, pointerType: "pen" },
{ nodeId: "stage", type: "wheel", x: 200, y: 150, deltaX: 12.5, deltaY: -120, deltaMode: 0, ctrlKey: true },
]) {
assert.equal(validate(valid), true, JSON.stringify(validate.errors));
}
for (const invalid of [
{ nodeId: "stage", type: "pointerdown", pointerId: 1.5 },
{ nodeId: "stage", type: "pointerdown", button: -2 },
{ nodeId: "stage", type: "pointerdown", buttons: 70000 },
{ nodeId: "stage", type: "pointerdown", pointerType: "unknown" },
{ nodeId: "stage", type: "wheel", deltaMode: 3 },
{ nodeId: "stage", type: "wheel", deltaY: -100, extra: 1 },
]) {
assert.equal(validate(invalid), false, JSON.stringify(invalid));
}
});
@@ -272,7 +272,7 @@ export type HostConfirmRequest = {
export type HostDrawnViewEvent = {
nodeId: string;
type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset" | "dblclick" | "contextmenu" | "pointerdown" | "pointermove" | "pointerup" | "pointercancel" | "wheel" | "scroll" | "widget";
type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset" | "dblclick" | "contextmenu" | "scroll" | "widget";
value?: string;
checked?: boolean;
eventId?: number;
@@ -285,13 +285,6 @@ export type HostDrawnViewEvent = {
values?: Array<string>;
x?: number;
y?: number;
pointerId?: number;
button?: number;
buttons?: number;
pointerType?: "mouse" | "pen" | "touch";
deltaX?: number;
deltaY?: number;
deltaMode?: number;
scrollTop?: number;
scrollLeft?: number;
clientHeight?: number;
+2 -133
View File
@@ -107,91 +107,6 @@ function subscribeControlPropertyMutations(container: HTMLElement, onMutation: (
const MAX_PLUGIN_CSS_LENGTH = 131072;
const MAX_PLUGIN_EVENT_VALUE_LENGTH = 131072;
function createForwardedPointerEvent(
win: (Window & typeof globalThis) | null,
eventType: 'pointerdown' | 'pointermove' | 'pointerup' | 'pointercancel',
event: HostDrawnViewEvent,
pointerId: number,
): Event {
const pointerType = event.pointerType ?? 'mouse';
const button = typeof event.button === 'number' && Number.isFinite(event.button)
? Math.trunc(event.button)
: (eventType === 'pointermove' || eventType === 'pointercancel' ? -1 : 0);
const buttons = typeof event.buttons === 'number' && Number.isFinite(event.buttons)
? Math.trunc(event.buttons)
: 0;
const init: PointerEventInit = {
bubbles: true,
cancelable: eventType !== 'pointercancel',
composed: true,
clientX: event.x ?? 0,
clientY: event.y ?? 0,
button,
buttons,
ctrlKey: Boolean(event.ctrlKey),
metaKey: Boolean(event.metaKey),
altKey: Boolean(event.altKey),
shiftKey: Boolean(event.shiftKey),
pointerId,
pointerType,
isPrimary: true,
};
const PointerCtor = win?.PointerEvent ?? (typeof PointerEvent === 'function' ? PointerEvent : undefined);
const MouseCtor = win?.MouseEvent ?? MouseEvent;
const created = PointerCtor ? new PointerCtor(eventType, init) : new MouseCtor(eventType, init);
// JSDOM either omits PointerEvent or aliases it to MouseEvent, which drops pointer* fields.
if ((created as PointerEvent).pointerId !== pointerId) {
Object.defineProperty(created, 'pointerId', { value: pointerId, configurable: true });
}
if ((created as PointerEvent).pointerType !== pointerType) {
Object.defineProperty(created, 'pointerType', { value: pointerType, configurable: true });
}
if ((created as PointerEvent).isPrimary !== true) {
Object.defineProperty(created, 'isPrimary', { value: true, configurable: true });
}
return created;
}
function createForwardedWheelEvent(
win: (Window & typeof globalThis) | null,
event: HostDrawnViewEvent,
): Event {
const deltaX = typeof event.deltaX === 'number' && Number.isFinite(event.deltaX) ? event.deltaX : 0;
const deltaY = typeof event.deltaY === 'number' && Number.isFinite(event.deltaY) ? event.deltaY : 0;
const deltaMode = typeof event.deltaMode === 'number' && Number.isFinite(event.deltaMode) ? Math.trunc(event.deltaMode) : 0;
const init: WheelEventInit = {
bubbles: true,
cancelable: true,
composed: true,
clientX: event.x ?? 0,
clientY: event.y ?? 0,
deltaX,
deltaY,
deltaZ: 0,
deltaMode,
ctrlKey: Boolean(event.ctrlKey),
metaKey: Boolean(event.metaKey),
altKey: Boolean(event.altKey),
shiftKey: Boolean(event.shiftKey),
};
const WheelCtor = win?.WheelEvent ?? (typeof WheelEvent === 'function' ? WheelEvent : undefined);
const MouseCtor = win?.MouseEvent ?? MouseEvent;
const created = WheelCtor ? new WheelCtor('wheel', init) : new MouseCtor('wheel', init);
if ((created as WheelEvent).deltaX !== deltaX) {
Object.defineProperty(created, 'deltaX', { value: deltaX, configurable: true });
}
if ((created as WheelEvent).deltaY !== deltaY) {
Object.defineProperty(created, 'deltaY', { value: deltaY, configurable: true });
}
if ((created as WheelEvent).deltaZ !== 0) {
Object.defineProperty(created, 'deltaZ', { value: 0, configurable: true });
}
if ((created as WheelEvent).deltaMode !== deltaMode) {
Object.defineProperty(created, 'deltaMode', { value: deltaMode, configurable: true });
}
return created;
}
function matchShortcutFromKeyEvent(event: HostDrawnViewEvent, isTextControl: boolean): string | null {
const key = event.key ?? '';
if (key === 'Escape' && !event.metaKey && !event.ctrlKey && !event.altKey) return 'escape';
@@ -229,7 +144,6 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
acknowledgedEvent: number;
sentAck: number;
controls: Map<string, string>;
pointerAncestors: Map<number, Element[]>;
};
const instances = new Map<string, View>();
const close = (id: string) => {
@@ -242,58 +156,14 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
view.elementsById.clear();
view.controlElements.clear();
view.controls.clear();
view.pointerAncestors.clear();
view.unmount();
view.container.remove();
};
const sendEvent = (view: View, event: HostDrawnViewEvent) => {
view.syncElementIndex();
const eventType = event.type;
const lookedUp = view.elementsById.get(event.nodeId);
if (
eventType === 'pointerdown'
|| eventType === 'pointermove'
|| eventType === 'pointerup'
|| eventType === 'pointercancel'
) {
const pointerId = typeof event.pointerId === 'number' && Number.isFinite(event.pointerId)
? Math.trunc(event.pointerId)
: 1;
let target: HTMLElement | null = lookedUp instanceof HTMLElement && lookedUp.isConnected ? lookedUp : null;
if (eventType === 'pointerdown') {
if (!target) return;
const chain: Element[] = [];
let cur: Element | null = target;
while (cur && view.container.contains(cur)) {
chain.push(cur);
if (cur === view.container) break;
cur = cur.parentElement;
}
view.pointerAncestors.set(pointerId, chain);
} else {
if (!target) {
const chain = view.pointerAncestors.get(pointerId);
if (chain) {
const surviving = chain.find((node): node is HTMLElement => node instanceof HTMLElement && node.isConnected);
target = surviving ?? (view.container.isConnected ? view.container : null);
}
}
if (eventType === 'pointerup' || eventType === 'pointercancel') {
view.pointerAncestors.delete(pointerId);
}
if (!target) return;
}
const win = target.ownerDocument?.defaultView as (Window & typeof globalThis) | null;
target.dispatchEvent(createForwardedPointerEvent(win, eventType, event, pointerId));
return;
}
const element = lookedUp;
const element = view.elementsById.get(event.nodeId);
if (!element || !(element instanceof HTMLElement)) return;
if (eventType === 'wheel') {
const win = element.ownerDocument?.defaultView as (Window & typeof globalThis) | null;
element.dispatchEvent(createForwardedWheelEvent(win, event));
return;
}
const eventType = event.type;
if (eventType === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; }
if (eventType === 'widget') {
const widgetEvent = new CustomEvent('netcatty-widget-event', {
@@ -521,7 +391,6 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
acknowledgedEvent: 0,
sentAck: 0,
controls: new Map(),
pointerAncestors: new Map(),
};
instances.set(id, view);
domObserver.observe(container, { childList: true, subtree: true });
+1 -216
View File
@@ -573,6 +573,7 @@ test('PluginBiChart serializes props and forwards datumClick, exportSvg, exportP
postMessage() {},
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
};
const received: Record<string, unknown> = {};
@@ -649,219 +650,3 @@ test('registerHostReactView still completes initial loading for components that
dom.window.close();
}
});
test('hostDom dispatches pointer drag, pan, cancel, and wheel zoom events into a React graph fixture', async () => {
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent', 'WheelEvent', 'CustomEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
const { act, useEffect, useRef, useState } = await import('react');
const { remoteId } = await import('@remote-dom/core/elements');
const { registerHostReactView } = await import('./hostReact.js');
let receive: (value: JsonValue) => void = () => {};
const messages: Array<Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>> = [];
const views = {
onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) { receive = listener; return { dispose() {} }; },
postMessage(_id: string, value: JsonValue) { messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>); },
getState: async () => undefined,
setState: async () => {},
setBadge: async () => {},
};
const log: Array<Record<string, unknown>> = [];
function GraphFixture() {
const stageRef = useRef<HTMLDivElement | null>(null);
const [nodeA, setNodeA] = useState({ x: 100, y: 100 });
const nodeB = { x: 300, y: 100 };
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
const [showHandle, setShowHandle] = useState(true);
const dragRef = useRef<
| { kind: 'node'; pointerId: number; startX: number; startY: number; originX: number; originY: number }
| { kind: 'pan'; pointerId: number; startX: number; startY: number; originX: number; originY: number }
| null
>(null);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const onWheel = (event: WheelEvent) => {
event.preventDefault();
log.push({
type: 'wheel',
clientX: event.clientX,
clientY: event.clientY,
deltaX: event.deltaX,
deltaY: event.deltaY,
deltaMode: event.deltaMode,
ctrlKey: event.ctrlKey,
});
setViewport((prev) => ({
...prev,
zoom: Math.round(prev.zoom * (event.deltaY < 0 ? 1.25 : 0.8) * 100) / 100,
}));
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
const dx = nodeB.x - nodeA.x;
const dy = nodeB.y - nodeA.y;
const edgeLength = Math.round(Math.hypot(dx, dy));
const edgeAngle = Math.round((Math.atan2(dy, dx) * 180) / Math.PI);
return (
<div
id="graph-stage"
ref={stageRef}
onPointerDown={(e) => {
if (e.button !== 0) return;
log.push({ type: 'stage-down', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, buttons: e.buttons });
dragRef.current = { kind: 'pan', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: viewport.x, originY: viewport.y };
}}
onPointerMove={(e) => {
const drag = dragRef.current;
if (!drag || drag.pointerId !== e.pointerId) return;
log.push({ type: 'move', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, shiftKey: e.shiftKey });
if (drag.kind === 'node') {
setNodeA({ x: drag.originX + (e.clientX - drag.startX), y: drag.originY + (e.clientY - drag.startY) });
} else {
setViewport((prev) => ({ ...prev, x: drag.originX + (e.clientX - drag.startX), y: drag.originY + (e.clientY - drag.startY) }));
}
}}
onPointerUp={(e) => {
if (dragRef.current?.pointerId === e.pointerId) {
log.push({ type: 'up', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY });
dragRef.current = null;
}
}}
onPointerCancel={(e) => {
if (dragRef.current?.pointerId === e.pointerId) {
log.push({ type: 'cancel', pointerId: e.pointerId });
dragRef.current = null;
}
}}
>
<div id="graph-world" style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
<div
id="edge-ab"
style={{ width: `${edgeLength}px`, transform: `translate(${nodeA.x}px, ${nodeA.y}px) rotate(${edgeAngle}deg)` }}
/>
<button
id="node-a"
type="button"
style={{ transform: `translate(${nodeA.x}px, ${nodeA.y}px)` }}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.stopPropagation();
log.push({ type: 'node-down', pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, button: e.button, buttons: e.buttons });
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodeA.x, originY: nodeA.y };
}}
>
Node A
</button>
{showHandle && (
<button
id="ephemeral-handle"
type="button"
onPointerDown={(e) => {
e.stopPropagation();
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodeA.x, originY: nodeA.y };
setShowHandle(false);
}}
>
Handle
</button>
)}
</div>
</div>
);
}
const registration = registerHostReactView(views, 'com.example.graph', () => <GraphFixture />);
try {
await act(async () => {
receive({ kind: 'host-ui.open', instanceId: 'graph-1' });
await new Promise((resolve) => setTimeout(resolve, 20));
});
const stage = document.getElementById('graph-stage')!;
const world = document.getElementById('graph-world')!;
const edge = document.getElementById('edge-ab')!;
const nodeAEl = document.getElementById('node-a')!;
const ephemeralHandle = document.getElementById('ephemeral-handle')!;
assert.equal(nodeAEl.style.transform, 'translate(100px, 100px)');
assert.equal(edge.style.width, '200px');
// 1. Node drag: node moves by (+60, +80) and incident edge recomputes length and start transform
const nodeAId = remoteId(nodeAEl);
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 1, type: 'pointerdown', nodeId: nodeAId, x: 100, y: 100, pointerId: 4, button: 0, buttons: 1, pointerType: 'mouse' } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 2, type: 'pointermove', nodeId: nodeAId, x: 160, y: 180, pointerId: 4, button: -1, buttons: 1, shiftKey: true } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 3, type: 'pointerup', nodeId: nodeAId, x: 160, y: 180, pointerId: 4, button: 0, buttons: 0 } });
// Subsequent move after pointerup must not drag the node further
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 4, type: 'pointermove', nodeId: nodeAId, x: 260, y: 260, pointerId: 4, button: -1, buttons: 0 } });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(nodeAEl.style.transform, 'translate(160px, 180px)', 'node transform must move by pointer delta');
const expectedLen = Math.round(Math.hypot(300 - 160, 100 - 180));
const expectedAngle = Math.round((Math.atan2(100 - 180, 300 - 160) * 180) / Math.PI);
assert.equal(edge.style.width, `${expectedLen}px`, 'incident edge length must follow dragged node');
assert.equal(edge.style.transform, `translate(160px, 180px) rotate(${expectedAngle}deg)`, 'incident edge origin/angle must follow dragged node');
assert.deepEqual(log.slice(0, 3), [
{ type: 'node-down', pointerId: 4, clientX: 100, clientY: 100, button: 0, buttons: 1 },
{ type: 'move', pointerId: 4, clientX: 160, clientY: 180, shiftKey: true },
{ type: 'up', pointerId: 4, clientX: 160, clientY: 180 },
]);
assert.equal(messages.at(-1)?.acknowledgedEvent, 4);
// 2. Stage pan + pointercancel + wheel zoom
const stageId = remoteId(stage);
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 5, type: 'pointerdown', nodeId: stageId, x: 200, y: 200, pointerId: 5, button: 0, buttons: 1 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 6, type: 'pointermove', nodeId: stageId, x: 245, y: 175, pointerId: 5, button: -1, buttons: 1 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 7, type: 'pointercancel', nodeId: stageId, x: 245, y: 175, pointerId: 5, button: -1, buttons: 0 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 8, type: 'wheel', nodeId: stageId, x: 210, y: 140, deltaX: 5, deltaY: -120, deltaMode: 0, ctrlKey: true } });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(world.style.transform, 'translate(45px, -25px) scale(1.25)', 'stage pan and wheel zoom must update viewport transform');
assert.deepEqual(log.at(-1), {
type: 'wheel',
clientX: 210,
clientY: 140,
deltaX: 5,
deltaY: -120,
deltaMode: 0,
ctrlKey: true,
});
assert.equal(log.some((entry) => entry.type === 'cancel' && entry.pointerId === 5), true);
// 3. Unmounting the originating pointerdown node mid-gesture still delivers pointermove/pointerup to surviving ancestors
const handleId = remoteId(ephemeralHandle);
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 9, type: 'pointerdown', nodeId: handleId, x: 10, y: 10, pointerId: 6, button: 0, buttons: 1 } });
});
assert.equal(document.getElementById('ephemeral-handle'), null, 'ephemeral handle unmounted on pointerdown');
await act(async () => {
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 10, type: 'pointermove', nodeId: handleId, x: 35, y: 20, pointerId: 6, button: -1, buttons: 1 } });
receive({ kind: 'host-ui.event', instanceId: 'graph-1', event: { eventId: 11, type: 'pointerup', nodeId: handleId, x: 35, y: 20, pointerId: 6, button: 0, buttons: 0 } });
await new Promise((resolve) => setTimeout(resolve, 20));
});
assert.equal(nodeAEl.style.transform, 'translate(185px, 190px)', 'pointermove after target unmount must still bubble to surviving stage');
assert.equal(log.some((entry) => entry.type === 'up' && entry.pointerId === 6), true, 'pointerup after target unmount must terminate drag cleanly');
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'graph-1' }); });
} finally {
await act(async () => { registration.dispose(); });
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});