Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions media/main.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
// Webview script moved out of inline <script>. Kept logic changes minimal.

document.body.setAttribute('tabindex', '0');
try { document.body.focus({ preventScroll: true }); } catch { try { document.body.focus(); } catch {} }
// Explorer previews open with preserveFocus, so the Explorer must keep keyboard
// focus (F2, Delete, arrows). Only move focus inside the table once VS Code has
// focused this webview's frame; programmatic focus would otherwise steal it.
const frameHasFocus = () => { try { return document.hasFocus(); } catch { return false; } };
let webviewFocused = frameHasFocus();
window.addEventListener('focus', () => { webviewFocused = true; }, { passive: true });
window.addEventListener('blur', () => { webviewFocused = false; }, { passive: true });
const focusWithinWebview = target => {
if (!target || !(webviewFocused || frameHasFocus())) return;
try { target.focus({ preventScroll: true }); } catch { try { target.focus(); } catch {} }
};
focusWithinWebview(document.body);

const vscode = acquireVsCodeApi();

Expand Down Expand Up @@ -312,7 +323,7 @@ const restoreState = () => {
sel.classList.add('selected');
currentSelection.push(sel);
anchorCell = sel; rangeEndCell = sel;
try { sel.focus({ preventScroll: true }); } catch { try { sel.focus(); } catch {} }
focusWithinWebview(sel);
}
}
// Re-apply scroll after any late chunk loads from selection restoration
Expand Down Expand Up @@ -431,8 +442,14 @@ if (scrollContainer) {

// Persist on blur/visibility change and restore on focus/visibility
const restoreRecreatedView = () => {
if (editingCell) return;
// A live DOM already owns its range and caret; a snapshot only has its anchor.
if (anchorCell?.isConnected || editingCell) return;
if (anchorCell?.isConnected) {
// Focus deferred while the Explorer kept it lands on the selection now.
const active = document.activeElement;
if (!active || active === document.body || active === document.documentElement) { focusWithinWebview(anchorCell); }
return;
}
try { restoreState(); } catch {}
};
window.addEventListener('blur', () => { persistState(); }, { passive: true });
Expand Down Expand Up @@ -2331,11 +2348,9 @@ window.addEventListener('message', event => {
if (message.retry && cell && !editingCell) { editCell(cell, undefined, 'detail'); }
} else if(message.type === 'focus'){
if (document.activeElement?.closest?.('#filterStatus')) return;
if (anchorCell) {
try { anchorCell.focus({ preventScroll: true }); } catch { try { anchorCell.focus(); } catch {} }
} else {
try { document.body.focus({ preventScroll: true }); } catch { try { document.body.focus(); } catch {} }
}
// The panel also becomes active for preserveFocus opens (Explorer preview);
// the window focus listener restores the selection once the frame is focused.
focusWithinWebview(anchorCell || document.body);
} else if (message.type === 'chunkData') {
const requestId = Number(message.requestId);
const start = Number(message.start);
Expand Down
2 changes: 2 additions & 0 deletions src/CsvEditorProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@ class CsvEditorController {
console.warn('CSV: Encoding warning action failed', error);
});

// A hint only: the webview moves focus to its selection solely when VS Code
// has focused its frame, so preserveFocus opens (Explorer preview) keep focus.
webviewPanel.webview.postMessage({ type: 'focus' });
let wasVisible = webviewPanel.visible;
webviewPanel.onDidChangeViewState(e => {
Expand Down
51 changes: 51 additions & 0 deletions src/test/webview-focus-ownership.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import assert from 'assert';
import { describe, it } from 'node:test';
import { createEditorHarness, createWebviewDom } from './edit-integrity-harness';

const settle = (view: ReturnType<typeof createWebviewDom>) =>
new Promise<void>(resolve => view.window.requestAnimationFrame(() => view.window.setTimeout(resolve, 0)));

const deliver = (view: ReturnType<typeof createWebviewDom>, data: unknown) =>
view.window.dispatchEvent(new view.window.MessageEvent('message', { data }));

// Explorer previews (single click) open the table with preserveFocus. Focusing
// inside the webview before VS Code focuses its frame pulls keyboard focus out
// of the Explorer, so F2 rename and other Explorer keys stop working.
describe('Webview focus ownership', () => {
for (const separator of [',', '\t']) {
it(`leaves focus outside until the frame is focused, then restores the selection (${JSON.stringify(separator)})`, async () => {
const host = await createEditorHarness({ rows: [['Name', 'Value'], ['one', '1'], ['two', '2']], separator });
const view = createWebviewDom(host.panel.webview.html, { anchorRow: 2, anchorCol: 1 });
try {
await settle(view);
deliver(view, { type: 'focus' });
await settle(view);
const { document } = view.window;
assert.strictEqual(document.hasFocus(), false, 'loading, restoring state and panel activation must not take focus');
assert.ok(view.cell(2, 1).classList.contains('selected'), 'the restored selection is still shown');

view.window.dispatchEvent(new view.window.Event('focus'));
await settle(view);
assert.strictEqual(document.activeElement, view.cell(2, 1), 'focusing the frame lands on the restored anchor');

view.window.dispatchEvent(new view.window.Event('blur'));
view.cell(2, 1).blur();
deliver(view, { type: 'focus' });
assert.notStrictEqual(document.activeElement, view.cell(2, 1), 'activation after blur does not reclaim focus');
view.window.dispatchEvent(new view.window.Event('focus'));
deliver(view, { type: 'focus' });
assert.strictEqual(document.activeElement, view.cell(2, 1), 'activation while focused moves focus to the anchor');
} finally { view.close(); host.dispose(); }
});
}

it('does not focus the document body of a fresh table without frame focus', async () => {
const host = await createEditorHarness();
const view = createWebviewDom(host.panel.webview.html);
try {
await settle(view);
deliver(view, { type: 'focus' });
assert.strictEqual(view.window.document.hasFocus(), false);
} finally { view.close(); host.dispose(); }
});
});