diff --git a/src/extension.ts b/src/extension.ts index 24f512f..4e0eb78 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -692,158 +692,23 @@ async function renderDiffPanel( return contentKey; } -async function bindDiffPanel( +/** + * Attaches the shared Webview message handler for diff panels (used by both + * git/file diff panels and the clipboard diff panel). + */ +export function attachDiffWebviewMessageHandler( panel: vscode.WebviewPanel, - context: vscode.ExtensionContext, - resolveState: ResolveDiffPanelState, -) { - attachPanelTracking(panel); - - const diffProvider = new MarkdownDiffProvider(); - const debounceDelay = 300; - let timeout: NodeJS.Timeout | undefined; - let currentState: DiffPanelState | undefined; - let repositorySubscription: vscode.Disposable | undefined; - let currentRepository: GitRepository | undefined; - let isDisposed = false; - let isUpdating = false; - let queuedTrigger: DiffPanelUpdateTrigger | undefined; - let lastContentKey: string | undefined; - - const scheduleUpdate = (trigger: DiffPanelUpdateTrigger) => { - if (timeout) { - clearTimeout(timeout); - } - - timeout = setTimeout( - () => { - timeout = undefined; - void update(trigger); - }, - trigger === "initial" ? 0 : debounceDelay, - ); - }; - - const queueUpdate = (trigger: DiffPanelUpdateTrigger) => { - if (!queuedTrigger) { - queuedTrigger = trigger; - return; - } - - if (trigger === "document" || queuedTrigger === "initial") { - queuedTrigger = trigger; - return; - } - - if (trigger === "repository" && queuedTrigger !== "document") { - queuedTrigger = trigger; - } - }; - - - const update = async (trigger: DiffPanelUpdateTrigger) => { - if (isDisposed) { - return; - } - - if (isUpdating) { - queueUpdate(trigger); - return; - } - - isUpdating = true; - try { - const nextState = await resolveState({ - refreshComparisonStatus: trigger !== "repository", - trigger, - }); - - if (isDisposed) { - return; - } - - currentState = nextState; - - if (currentRepository !== nextState.repository) { - repositorySubscription?.dispose(); - currentRepository = nextState.repository; - repositorySubscription = nextState.repository?.state.onDidChange(() => { - scheduleUpdate("repository"); - }); - } - - lastContentKey = await renderDiffPanel( - panel, - context, - diffProvider, - nextState, - lastContentKey, - ); - - if (isDisposed) { - return; - } - } catch (error) { - if (!isDisposed) { - panel.webview.html = `

${escapeHtml(l10n.t("Error reading file: {0}", String(error)))}

`; - } - } finally { - isUpdating = false; - - if (queuedTrigger) { - const nextTrigger = queuedTrigger; - queuedTrigger = undefined; - scheduleUpdate(nextTrigger); - } - } - }; - - const configSubscription = vscode.workspace.onDidChangeConfiguration((e) => { - if ( - e.affectsConfiguration("rich-markdown-diff.showGutterMarkers") || - e.affectsConfiguration("rich-markdown-diff.showGitBlame") || - e.affectsConfiguration("rich-markdown-diff.lineHoverDelay") || - e.affectsConfiguration("rich-markdown-diff.insertedColor") || - e.affectsConfiguration("rich-markdown-diff.deletedColor") || - e.affectsConfiguration("rich-markdown-diff.defaultViewMode") || - e.affectsConfiguration("rich-markdown-diff.defaultFoldUnchanged") - ) { - lastContentKey = undefined; // Force re-render - scheduleUpdate("document"); - } - }); - - const documentSubscription = vscode.workspace.onDidChangeTextDocument((e) => { - if (!currentState) { - return; - } - - const watchedUris = currentState.watchUris.filter( - (uri) => uri.scheme === "file", - ); - if ( - watchedUris.some((uri) => uri.toString() === e.document.uri.toString()) - ) { - scheduleUpdate("document"); - } - }); - - panel.onDidDispose(() => { - isDisposed = true; - documentSubscription.dispose(); - configSubscription.dispose(); - repositorySubscription?.dispose(); - if (timeout) { - clearTimeout(timeout); - } - }); - - panel.webview.onDidReceiveMessage(async (message) => { + getState: () => DiffPanelState | undefined, + options?: { originalUnavailableMessage?: string }, +): vscode.Disposable { + return panel.webview.onDidReceiveMessage(async (message) => { if (message.command === "ready") { isWebviewReadyForTesting = true; return; } + const currentState = getState(); + if (message.command === "runtimeDiagnostics") { if ( message.payload && @@ -958,7 +823,9 @@ async function bindDiffPanel( if (!uriToOpen) { vscode.window.showInformationMessage( - l10n.t("No source is available for this side of the diff."), + message.side === "original" && options?.originalUnavailableMessage + ? options.originalUnavailableMessage + : l10n.t("No source is available for this side of the diff."), ); return; } @@ -1032,6 +899,159 @@ async function bindDiffPanel( } } }); +} + +async function bindDiffPanel( + panel: vscode.WebviewPanel, + context: vscode.ExtensionContext, + resolveState: ResolveDiffPanelState, +) { + attachPanelTracking(panel); + + const diffProvider = new MarkdownDiffProvider(); + const debounceDelay = 300; + let timeout: NodeJS.Timeout | undefined; + let currentState: DiffPanelState | undefined; + let repositorySubscription: vscode.Disposable | undefined; + let currentRepository: GitRepository | undefined; + let isDisposed = false; + let isUpdating = false; + let queuedTrigger: DiffPanelUpdateTrigger | undefined; + let lastContentKey: string | undefined; + + const scheduleUpdate = (trigger: DiffPanelUpdateTrigger) => { + if (timeout) { + clearTimeout(timeout); + } + + timeout = setTimeout( + () => { + timeout = undefined; + void update(trigger); + }, + trigger === "initial" ? 0 : debounceDelay, + ); + }; + + const queueUpdate = (trigger: DiffPanelUpdateTrigger) => { + if (!queuedTrigger) { + queuedTrigger = trigger; + return; + } + + if (trigger === "document" || queuedTrigger === "initial") { + queuedTrigger = trigger; + return; + } + + if (trigger === "repository" && queuedTrigger !== "document") { + queuedTrigger = trigger; + } + }; + + + const update = async (trigger: DiffPanelUpdateTrigger) => { + if (isDisposed) { + return; + } + + if (isUpdating) { + queueUpdate(trigger); + return; + } + + isUpdating = true; + try { + const nextState = await resolveState({ + refreshComparisonStatus: trigger !== "repository", + trigger, + }); + + if (isDisposed) { + return; + } + + currentState = nextState; + + if (currentRepository !== nextState.repository) { + repositorySubscription?.dispose(); + currentRepository = nextState.repository; + repositorySubscription = nextState.repository?.state.onDidChange(() => { + scheduleUpdate("repository"); + }); + } + + lastContentKey = await renderDiffPanel( + panel, + context, + diffProvider, + nextState, + lastContentKey, + ); + + if (isDisposed) { + return; + } + } catch (error) { + if (!isDisposed) { + panel.webview.html = `

${escapeHtml(l10n.t("Error reading file: {0}", String(error)))}

`; + } + } finally { + isUpdating = false; + + if (queuedTrigger) { + const nextTrigger = queuedTrigger; + queuedTrigger = undefined; + scheduleUpdate(nextTrigger); + } + } + }; + + const configSubscription = vscode.workspace.onDidChangeConfiguration((e) => { + if ( + e.affectsConfiguration("rich-markdown-diff.showGutterMarkers") || + e.affectsConfiguration("rich-markdown-diff.showGitBlame") || + e.affectsConfiguration("rich-markdown-diff.lineHoverDelay") || + e.affectsConfiguration("rich-markdown-diff.insertedColor") || + e.affectsConfiguration("rich-markdown-diff.deletedColor") || + e.affectsConfiguration("rich-markdown-diff.defaultViewMode") || + e.affectsConfiguration("rich-markdown-diff.defaultFoldUnchanged") + ) { + lastContentKey = undefined; // Force re-render + scheduleUpdate("document"); + } + }); + + const documentSubscription = vscode.workspace.onDidChangeTextDocument((e) => { + if (!currentState) { + return; + } + + const watchedUris = currentState.watchUris.filter( + (uri) => uri.scheme === "file", + ); + if ( + watchedUris.some((uri) => uri.toString() === e.document.uri.toString()) + ) { + scheduleUpdate("document"); + } + }); + + const messageDisposable = attachDiffWebviewMessageHandler( + panel, + () => currentState, + ); + + panel.onDidDispose(() => { + isDisposed = true; + messageDisposable.dispose(); + documentSubscription.dispose(); + configSubscription.dispose(); + repositorySubscription?.dispose(); + if (timeout) { + clearTimeout(timeout); + } + }); await update("initial"); } @@ -1365,58 +1385,24 @@ export function activate(context: vscode.ExtensionContext) { panel.webview.html = webviewContent; - // Handle Double Click - const messageDisposable = panel.webview.onDidReceiveMessage((message) => { - if (message.command === "openSource") { - const side = message.side; - const line = message.line; - if (side === "original") { - vscode.window.showInformationMessage( - l10n.t( - "Original source is the clipboard content and cannot be opened as a file.", - ), - ); - return; - } + const clipboardPanelState: DiffPanelState = { + modifiedUri: document.uri, + leftLabel: "Clipboard", + rightLabel: path.basename(document.fileName), + watchUris: [], + modifiedImageBaseUri: document.uri, + fallbackSourceUri: document.uri, + }; - if (editor) { - if (typeof message.page === "string" && message.page.length > 0) { - resolveWikilinkUri(message.page, editor.document.uri).then((resolvedUri) => { - if (resolvedUri) { - vscode.workspace.openTextDocument(resolvedUri).then((doc) => { - vscode.window.showTextDocument(doc, { - viewColumn: vscode.ViewColumn.One, - preserveFocus: false, - }); - }, (err) => { - vscode.window.showErrorMessage( - l10n.t("Could not open file: {0}", String(err)), - ); - }); - } else { - vscode.window.showWarningMessage( - l10n.t("Wikilink target not found: {0}", message.page), - ); - } - }); - return; - } - - vscode.window - .showTextDocument(editor.document, vscode.ViewColumn.One) - .then((e) => { - if ( - typeof line === "number" && - Number.isInteger(line) && - line >= 0 - ) { - const range = new vscode.Range(line, 0, line, 0); - e.revealRange(range, vscode.TextEditorRevealType.InCenter); - } - }); - } - } - }); + const messageDisposable = attachDiffWebviewMessageHandler( + panel, + () => clipboardPanelState, + { + originalUnavailableMessage: l10n.t( + "Original source is the clipboard content and cannot be opened as a file.", + ), + }, + ); panel.onDidDispose(() => { messageDisposable.dispose(); diff --git a/src/test/suite/webviewBridge.test.ts b/src/test/suite/webviewBridge.test.ts index e75dd54..1111c5b 100644 --- a/src/test/suite/webviewBridge.test.ts +++ b/src/test/suite/webviewBridge.test.ts @@ -106,5 +106,63 @@ describe("Webview Bridge Integration Tests", () => { const absoluteResolved = await resolveWikilinkUri("/etc/passwd", tmpFile); assert.strictEqual(absoluteResolved, undefined, "Absolute path wikilink must resolve to undefined"); }); + + it("should handle requestBlockSource and applyEdit via attachDiffWebviewMessageHandler (clipboard diff mode)", async () => { + const { attachDiffWebviewMessageHandler } = require("../../extension"); + + let listener: ((msg: unknown) => Promise) | undefined; + const postedMessages: unknown[] = []; + + const mockPanel = { + webview: { + onDidReceiveMessage: (cb: (msg: unknown) => Promise) => { + listener = cb; + return { dispose: () => {} }; + }, + postMessage: async (msg: unknown) => { + postedMessages.push(msg); + return true; + }, + }, + } as unknown as vscode.WebviewPanel; + + const disposable = attachDiffWebviewMessageHandler( + mockPanel, + () => ({ + modifiedUri: tmpFile, + leftLabel: "Clipboard", + rightLabel: path.basename(tmpFile.fsPath), + watchUris: [], + modifiedImageBaseUri: tmpFile, + fallbackSourceUri: tmpFile, + }), + ); + + assert.ok(listener, "onDidReceiveMessage listener should be registered"); + + await listener!({ command: "requestBlockSource", lineStart: 0, lineEnd: 2 }); + assert.deepStrictEqual(postedMessages, [ + { command: "receiveBlockSource", content: "Line 1\nLine 2" }, + ]); + + await listener!({ + command: "applyEdit", + lineStart: 1, + lineEnd: 2, + newContent: "Edited Line 2", + }); + + const updatedDoc = await vscode.workspace.openTextDocument(tmpFile); + assert.strictEqual(updatedDoc.lineAt(1).text, "Edited Line 2"); + + // Revert changes + await listener!({ + command: "applyEdit", + lineStart: 1, + lineEnd: 2, + newContent: "Line 2", + }); + disposable.dispose(); + }); }); diff --git a/src/test/visual/vrt.test.ts b/src/test/visual/vrt.test.ts index fcb4ee9..f1a30ab 100644 --- a/src/test/visual/vrt.test.ts +++ b/src/test/visual/vrt.test.ts @@ -68,6 +68,35 @@ test.describe("Visual Regression Tests", () => { await page.setContent(html); await page.waitForTimeout(5000); + await page.evaluate(async () => { + if (document.fonts && document.fonts.ready) { + await document.fonts.ready; + } + // Wait for consecutive animation frames with identical layout dimensions + // so fullPage screenshots do not oscillate by 1px during stabilization. + const measure = () => { + const left = document.getElementById("left-pane"); + const right = document.getElementById("right-pane"); + return [ + document.documentElement.scrollHeight, + document.body.scrollHeight, + left ? left.scrollHeight : 0, + right ? right.scrollHeight : 0, + ].join(","); + }; + let last = measure(); + let stableFrames = 0; + for (let i = 0; i < 30 && stableFrames < 5; i++) { + await new Promise((r) => requestAnimationFrame(r)); + const next = measure(); + if (next === last) { + stableFrames++; + } else { + last = next; + stableFrames = 0; + } + } + }); // Systemic check: Save the rendered HTML to a file for objective inspection const htmlDumpPath = path.join(__dirname, `../../../test-results/${c.name}-${c.suffix}.html`);