-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathDocumentationPreviewEditor.ts
277 lines (258 loc) · 11.2 KB
/
DocumentationPreviewEditor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2024-2025 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import * as vscode from "vscode";
import * as fs from "fs/promises";
import * as path from "path";
import { RenderNode, WebviewContent, WebviewMessage } from "./webview/WebviewMessage";
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",
TITLE = "Preview Swift Documentation",
UNSUPPORTED_EDITOR_ERROR_MESSAGE = "The active text editor does not support Swift Documentation Live Preview",
}
export class DocumentationPreviewEditor implements vscode.Disposable {
static async create(
extension: vscode.ExtensionContext,
context: WorkspaceContext
): Promise<DocumentationPreviewEditor> {
const swiftDoccRenderPath = extension.asAbsolutePath(
path.join("assets", "swift-docc-render")
);
const webviewPanel = vscode.window.createWebviewPanel(
PreviewEditorConstant.VIEW_TYPE,
PreviewEditorConstant.TITLE,
{ viewColumn: vscode.ViewColumn.Beside, preserveFocus: true },
{
enableScripts: true,
localResourceRoots: [
vscode.Uri.file(
extension.asAbsolutePath(
path.join("node_modules", "@vscode/codicons", "dist")
)
),
vscode.Uri.file(
extension.asAbsolutePath(path.join("assets", "documentation-webview"))
),
vscode.Uri.file(swiftDoccRenderPath),
...context.folders.map(f => f.folder),
],
}
);
webviewPanel.iconPath = {
light: vscode.Uri.file(
extension.asAbsolutePath(
path.join("assets", "icons", "light", "swift-documentation.svg")
)
),
dark: vscode.Uri.file(
extension.asAbsolutePath(
path.join("assets", "icons", "dark", "swift-documentation.svg")
)
),
};
const webviewBaseURI = webviewPanel.webview.asWebviewUri(
vscode.Uri.file(swiftDoccRenderPath)
);
const scriptURI = webviewPanel.webview.asWebviewUri(
vscode.Uri.file(
extension.asAbsolutePath(path.join("assets", "documentation-webview", "index.js"))
)
);
let doccRenderHTML = await fs.readFile(
path.join(swiftDoccRenderPath, "index.html"),
"utf-8"
);
const codiconsUri = webviewPanel.webview.asWebviewUri(
vscode.Uri.file(
extension.asAbsolutePath(
path.join("node_modules", "@vscode/codicons", "dist", "codicon.css")
)
)
);
doccRenderHTML = doccRenderHTML
.replaceAll("{{BASE_PATH}}", webviewBaseURI.toString())
.replace("</head>", `<link href="${codiconsUri}" rel="stylesheet" /></head>`)
.replace("</body>", `<script src="${scriptURI.toString()}"></script></body>`);
webviewPanel.webview.html = doccRenderHTML;
return new DocumentationPreviewEditor(context, webviewPanel);
}
private activeTextEditor?: vscode.TextEditor;
private activeTextEditorSelection?: vscode.Selection;
private subscriptions: vscode.Disposable[] = [];
private isDisposed: boolean = false;
private disposeEmitter = new vscode.EventEmitter<void>();
private renderEmitter = new vscode.EventEmitter<void>();
private updateContentEmitter = new vscode.EventEmitter<WebviewContent>();
private constructor(
private readonly context: WorkspaceContext,
private readonly webviewPanel: vscode.WebviewPanel
) {
this.activeTextEditor = vscode.window.activeTextEditor;
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)
);
this.reveal();
}
/** An event that is fired when the Documentation Preview Editor is disposed */
onDidDispose = this.disposeEmitter.event;
/** An event that is fired when the Documentation Preview Editor updates its content */
onDidUpdateContent = this.updateContentEmitter.event;
/** An event that is fired when the Documentation Preview Editor renders its content */
onDidRenderContent = this.renderEmitter.event;
reveal() {
// Reveal the editor, but don't change the focus of the active text editor
this.webviewPanel.reveal(undefined, true);
}
dispose() {
this.isDisposed = true;
this.subscriptions.forEach(subscription => subscription.dispose());
this.subscriptions = [];
this.webviewPanel.dispose();
this.disposeEmitter.fire();
}
private postMessage(message: WebviewMessage) {
if (this.isDisposed) {
return;
}
if (message.type === "update-content") {
this.updateContentEmitter.fire(message.content);
}
this.webviewPanel.webview.postMessage(message);
}
private receiveMessage(message: WebviewMessage) {
switch (message.type) {
case "loaded":
if (!this.activeTextEditor) {
break;
}
this.convertDocumentation(this.activeTextEditor);
break;
case "rendered":
this.renderEmitter.fire();
break;
}
}
private handleActiveTextEditorChange(activeTextEditor: vscode.TextEditor | undefined) {
if (this.activeTextEditor === activeTextEditor || activeTextEditor === undefined) {
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 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,
});
}
);
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,
},
});
}
},
100 /* 10 times per second */,
{ trailing: true }
);
private parseRenderNode(content: string): RenderNode {
const renderNode: RenderNode = JSON.parse(content);
for (const referenceKey of Object.getOwnPropertyNames(renderNode.references)) {
const reference = renderNode.references[referenceKey];
for (const variant of reference.variants ?? []) {
const uri = vscode.Uri.parse(variant.url).with({ scheme: "file" });
variant.url = this.webviewPanel.webview.asWebviewUri(uri).toString();
}
}
return renderNode;
}
}