mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-30 06:00:58 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0d542885f | ||
|
|
f3bb457c6c | ||
|
|
cbc07d669f | ||
|
|
d2007f6a8e | ||
|
|
8ba81f14ee | ||
|
|
c950570388 | ||
|
|
2ae02b59da | ||
|
|
438401165c |
No files matched your search
@@ -1330,6 +1330,8 @@ 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:",
|
||||
|
||||
@@ -1330,6 +1330,8 @@ 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:",
|
||||
|
||||
@@ -1271,6 +1271,8 @@ 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-адреса в браузере по умолчанию:",
|
||||
|
||||
@@ -1247,6 +1247,8 @@ 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 链接:",
|
||||
|
||||
@@ -1248,6 +1248,8 @@ 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 連結:",
|
||||
|
||||
@@ -65,3 +65,409 @@ 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' }],
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,174 @@ 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();
|
||||
@@ -23,6 +191,16 @@ 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');
|
||||
@@ -31,16 +209,35 @@ 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);
|
||||
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
const next = { children: receiver.root.children.map(project) };
|
||||
validatePluginRemoteTree(next);
|
||||
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]);
|
||||
validatedTrees.add(next);
|
||||
current = next;
|
||||
return next;
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
if (!isDuplicatePluginViewNodeError(error)) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -60,3 +60,280 @@ 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;
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createPluginRemoteTree } from './pluginRemoteTree';
|
||||
import { createPluginRemoteTree, isDuplicatePluginViewNodeError } from './pluginRemoteTree';
|
||||
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
@@ -27,6 +27,8 @@ 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>();
|
||||
@@ -42,14 +44,26 @@ 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');
|
||||
const nextCss = update.cssUnchanged
|
||||
? state.css
|
||||
: (lastRawCss !== null && update.css === lastRawCss)
|
||||
? state.css
|
||||
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
|
||||
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 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
|
||||
@@ -68,7 +82,20 @@ export class PluginViewSessions {
|
||||
emptyFrameTimer = undefined;
|
||||
}
|
||||
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
|
||||
} catch { dispose(true); }
|
||||
} 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);
|
||||
}
|
||||
}));
|
||||
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
|
||||
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
|
||||
@@ -100,7 +127,11 @@ export class PluginViewSessions {
|
||||
send: (event: HostDrawnViewEvent) => {
|
||||
if (disposed || users === 0) return;
|
||||
publish({ ...state, settled: false });
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
|
||||
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);
|
||||
});
|
||||
},
|
||||
dispose,
|
||||
};
|
||||
|
||||
@@ -39,7 +39,11 @@ 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(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
|
||||
const update = () => {
|
||||
const snapshot = session.getSnapshot();
|
||||
if (snapshot.error) sessionRef.current = null;
|
||||
setState({ key, snapshot, image: session.image });
|
||||
};
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
|
||||
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
|
||||
@@ -49,7 +53,9 @@ 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;
|
||||
const hasCurrentState = active
|
||||
&& state.key === key
|
||||
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
|
||||
const resolvedSnapshot = hasCurrentState
|
||||
? state.snapshot
|
||||
: cachedSession
|
||||
|
||||
@@ -82,3 +82,91 @@ 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); }
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,7 @@
|
||||
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';
|
||||
@@ -30,12 +33,33 @@ function hasFullBleedChrome(tree: unknown): boolean {
|
||||
return check(children, 0);
|
||||
}
|
||||
|
||||
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
function PluginHostDrawnPageSession({
|
||||
onRetry,
|
||||
...props
|
||||
}: PluginHostDrawnPageProps & { onRetry: () => void }) {
|
||||
const { t } = useI18n();
|
||||
const view = useHostDrawnPluginView(props);
|
||||
if (!view.visible) return null;
|
||||
if (view.loading) return <PluginViewLoadingSurface slot={props.slot.split(':')[0]} loadingLabel={props.loadingLabel} />;
|
||||
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>
|
||||
);
|
||||
}
|
||||
const fullBleed = hasFullBleedChrome(view.tree);
|
||||
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}>
|
||||
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}>
|
||||
<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="">
|
||||
@@ -44,3 +68,11 @@ export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
)}
|
||||
</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} />;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
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,6 +15,7 @@ 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;
|
||||
@@ -60,6 +61,7 @@ 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);
|
||||
@@ -223,8 +225,18 @@ export function PluginDataGrid({
|
||||
onWidgetEvent('rowSelect', { selectedRowIndices: next });
|
||||
}, [totalRows, selectedSet.size, onWidgetEvent]);
|
||||
|
||||
const handleSortClick = useCallback((col: PluginDataGridColumn) => {
|
||||
const handleSortClick = useCallback((col: PluginDataGridColumn, event?: React.MouseEvent<HTMLButtonElement>) => {
|
||||
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]);
|
||||
@@ -452,7 +464,11 @@ export function PluginDataGrid({
|
||||
<button
|
||||
type="button"
|
||||
disabled={!sortable}
|
||||
onClick={() => handleSortClick(col)}
|
||||
onClick={(event) => handleSortClick(col, event)}
|
||||
onDoubleClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}}
|
||||
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}`
|
||||
|
||||
Reference in new issue
Block a user