Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add event handler for editor selection in Documentation Live Preview editor #1413

Merged
merged 3 commits into from
Feb 28, 2025
Merged
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
47 changes: 47 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1566,6 +1566,7 @@
"@types/chai-subset": "^1.3.5",
"@types/glob": "^7.1.6",
"@types/lcov-parse": "^1.0.2",
"@types/lodash.throttle": "^4.1.9",
"@types/mocha": "^10.0.10",
"@types/mock-fs": "^4.13.4",
"@types/node": "^18.19.76",
Expand All @@ -1588,6 +1589,7 @@
"esbuild": "^0.25.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^10.0.1",
"lodash.throttle": "^4.1.1",
"mocha": "^10.8.2",
"mock-fs": "^5.5.0",
"node-pty": "^1.0.0",
Expand Down
154 changes: 87 additions & 67 deletions src/documentation/DocumentationPreviewEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import { RenderNode, WebviewContent, WebviewMessage } from "./webview/WebviewMes
import { WorkspaceContext } from "../WorkspaceContext";
import { DocCDocumentationRequest, DocCDocumentationResponse } from "../sourcekit-lsp/extensions";
import { LSPErrorCodes, ResponseError } from "vscode-languageclient";
// eslint-disable-next-line @typescript-eslint/no-require-imports
import throttle = require("lodash.throttle");

export enum PreviewEditorConstant {
VIEW_TYPE = "swift.previewDocumentationEditor",
Expand Down Expand Up @@ -94,6 +96,7 @@ export class DocumentationPreviewEditor implements vscode.Disposable {
}

private activeTextEditor?: vscode.TextEditor;
private activeTextEditorSelection?: vscode.Selection;
private subscriptions: vscode.Disposable[] = [];

private disposeEmitter = new vscode.EventEmitter<void>();
Expand All @@ -108,11 +111,11 @@ export class DocumentationPreviewEditor implements vscode.Disposable {
this.subscriptions.push(
this.webviewPanel.webview.onDidReceiveMessage(this.receiveMessage, this),
vscode.window.onDidChangeActiveTextEditor(this.handleActiveTextEditorChange, this),
vscode.window.onDidChangeTextEditorSelection(this.handleSelectionChange, this),
vscode.workspace.onDidChangeTextDocument(this.handleDocumentChange, this),
this.webviewPanel.onDidDispose(this.dispose, this)
);
// Reveal the editor, but don't change the focus of the active text editor
webviewPanel.reveal(undefined, true);
this.reveal();
}

/** An event that is fired when the Documentation Preview Editor is disposed */
Expand All @@ -125,7 +128,8 @@ export class DocumentationPreviewEditor implements vscode.Disposable {
onDidRenderContent = this.renderEmitter.event;

reveal() {
this.webviewPanel.reveal();
// Reveal the editor, but don't change the focus of the active text editor
this.webviewPanel.reveal(undefined, true);
}

dispose() {
Expand Down Expand Up @@ -161,82 +165,98 @@ export class DocumentationPreviewEditor implements vscode.Disposable {
return;
}
this.activeTextEditor = activeTextEditor;
this.activeTextEditorSelection = activeTextEditor.selection;
this.convertDocumentation(activeTextEditor);
}

private handleSelectionChange(event: vscode.TextEditorSelectionChangeEvent) {
if (
this.activeTextEditor !== event.textEditor ||
this.activeTextEditorSelection === event.textEditor.selection
) {
return;
}
this.activeTextEditorSelection = event.textEditor.selection;
this.convertDocumentation(event.textEditor);
}

private handleDocumentChange(event: vscode.TextDocumentChangeEvent) {
if (this.activeTextEditor?.document === event.document) {
this.convertDocumentation(this.activeTextEditor);
}
}

private async convertDocumentation(textEditor: vscode.TextEditor): Promise<void> {
const document = textEditor.document;
if (
document.uri.scheme !== "file" ||
!["markdown", "tutorial", "swift"].includes(document.languageId)
) {
this.postMessage({
type: "update-content",
content: {
type: "error",
errorMessage: PreviewEditorConstant.UNSUPPORTED_EDITOR_ERROR_MESSAGE,
},
});
return;
}
private convertDocumentation = throttle(
async (textEditor: vscode.TextEditor): Promise<void> => {
const document = textEditor.document;
if (
document.uri.scheme !== "file" ||
!["markdown", "tutorial", "swift"].includes(document.languageId)
) {
this.postMessage({
type: "update-content",
content: {
type: "error",
errorMessage: PreviewEditorConstant.UNSUPPORTED_EDITOR_ERROR_MESSAGE,
},
});
return;
}

try {
const response = await this.context.languageClientManager.useLanguageClient(
async (client): Promise<DocCDocumentationResponse> => {
return await client.sendRequest(DocCDocumentationRequest.type, {
textDocument: {
uri: document.uri.toString(),
},
position: textEditor.selection.start,
});
try {
const response = await this.context.languageClientManager.useLanguageClient(
async (client): Promise<DocCDocumentationResponse> => {
return await client.sendRequest(DocCDocumentationRequest.type, {
textDocument: {
uri: document.uri.toString(),
},
position: textEditor.selection.start,
});
}
);
this.postMessage({
type: "update-content",
content: {
type: "render-node",
renderNode: this.parseRenderNode(response.renderNode),
},
});
} catch (error) {
// Update the preview editor to reflect what error occurred
let livePreviewErrorMessage = "An internal error occurred";
const baseLogErrorMessage = `SourceKit-LSP request "${DocCDocumentationRequest.method}" failed: `;
if (error instanceof ResponseError) {
if (error.code === LSPErrorCodes.RequestCancelled) {
// We can safely ignore cancellations
return undefined;
}
switch (error.code) {
case LSPErrorCodes.RequestFailed:
// RequestFailed response errors can be shown to the user
livePreviewErrorMessage = error.message;
break;
default:
// We should log additional info for other response errors
this.context.outputChannel.log(
baseLogErrorMessage + JSON.stringify(error.toJson(), undefined, 2)
);
break;
}
} else {
this.context.outputChannel.log(baseLogErrorMessage + `${error}`);
}
);
this.postMessage({
type: "update-content",
content: {
type: "render-node",
renderNode: this.parseRenderNode(response.renderNode),
},
});
} catch (error) {
// Update the preview editor to reflect what error occurred
let livePreviewErrorMessage = "An internal error occurred";
const baseLogErrorMessage = `SourceKit-LSP request "${DocCDocumentationRequest.method}" failed: `;
if (error instanceof ResponseError) {
if (error.code === LSPErrorCodes.RequestCancelled) {
// We can safely ignore cancellations
return undefined;
}
switch (error.code) {
case LSPErrorCodes.RequestFailed:
// RequestFailed response errors can be shown to the user
livePreviewErrorMessage = error.message;
break;
default:
// We should log additional info for other response errors
this.context.outputChannel.log(
baseLogErrorMessage + JSON.stringify(error.toJson(), undefined, 2)
);
break;
}
} else {
this.context.outputChannel.log(baseLogErrorMessage + `${error}`);
this.postMessage({
type: "update-content",
content: {
type: "error",
errorMessage: livePreviewErrorMessage,
},
});
}
this.postMessage({
type: "update-content",
content: {
type: "error",
errorMessage: livePreviewErrorMessage,
},
});
}
}
},
100 /* 10 times per second */,
{ trailing: true }
);

private parseRenderNode(content: string): RenderNode {
const renderNode: RenderNode = JSON.parse(content);
Expand Down
Loading