-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.ts
240 lines (226 loc) · 7.15 KB
/
index.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
import type { Client } from "@previewjs/server/client";
import path from "path";
import vscode from "vscode";
import { clientId } from "./client-id";
import { closePreviewPanel, updatePreviewPanel } from "./preview-panel";
import { ensurePreviewServerStarted } from "./preview-server";
import { ensureServerRunning } from "./start-server";
import { openUsageOnFirstTimeStart } from "./welcome";
const codeLensLanguages = [
"javascript",
"javascriptreact",
"jsx",
"svelte",
"typescriptreact",
"vue",
];
const watchedExtensions = new Set([
".js",
".jsx",
".ts",
".tsx",
".vue",
".css",
".sass",
".scss",
".less",
".styl",
".stylus",
".svelte",
".svg",
]);
let dispose = async () => {
// Do nothing.
};
export async function activate(context: vscode.ExtensionContext) {
const outputChannel = vscode.window.createOutputChannel("Preview.js");
const previewjsInitPromise = ensureServerRunning(outputChannel)
.catch((e) => {
outputChannel.appendLine(e.stack);
return null;
})
.then((p) => {
if (!p) {
outputChannel.appendLine("Preview.js server could not be started.");
outputChannel.show();
return null;
}
return p;
});
const config = vscode.workspace.getConfiguration();
let focusedOutputChannelForError = false;
const workspaceIds = new Set<string>();
async function getWorkspaceId(
previewjsClient: Client,
document: vscode.TextDocument
) {
if (!path.isAbsolute(document.fileName)) {
return null;
}
const workspace = await previewjsClient.getWorkspace({
absoluteFilePath: document.fileName,
});
if (!workspace.workspaceId) {
return null;
}
if (!workspaceIds.has(workspace.workspaceId)) {
outputChannel.appendLine(
`✨ Created Preview.js workspace for: ${workspace.rootDirPath}`
);
workspaceIds.add(workspace.workspaceId);
}
return workspace.workspaceId;
}
// Note: ESlint warning isn't relevant because we're correctly inferring arguments types.
// eslint-disable-next-line @typescript-eslint/ban-types
function catchErrors<F extends Function>(f: F) {
return async (...args: F extends (...args: infer A) => any ? A : never) => {
try {
return await f(...args);
} catch (e: unknown) {
if (!focusedOutputChannelForError) {
outputChannel.show();
focusedOutputChannelForError = true;
}
outputChannel.appendLine(
e instanceof Error ? e.stack || e.message : `${e}`
);
throw e;
}
};
}
dispose = async () => {
const previewjsClient = await previewjsInitPromise;
await previewjsClient?.updateClientStatus({
clientId,
alive: false,
});
outputChannel.dispose();
};
await openUsageOnFirstTimeStart(context);
if (config.get("previewjs.codelens", true)) {
vscode.languages.registerCodeLensProvider(codeLensLanguages, {
provideCodeLenses: catchErrors(async (document: vscode.TextDocument) => {
const previewjsClient = await previewjsInitPromise;
if (!previewjsClient) {
return [];
}
const workspaceId = await getWorkspaceId(previewjsClient, document);
if (!workspaceId) {
return [];
}
const { components } = await previewjsClient.analyzeFile({
workspaceId,
absoluteFilePath: document.fileName,
});
return components.map((c) => {
const start = document.positionAt(c.start + 2);
const lens = new vscode.CodeLens(new vscode.Range(start, start));
lens.command = {
command: "previewjs.open",
arguments: [document, c.componentId],
title: `Open ${c.componentName} in Preview.js`,
};
return lens;
});
}),
});
}
if (config.get("previewjs.livePreview", true)) {
vscode.workspace.onDidChangeTextDocument(async (e) => {
await updateDocument(e.document);
});
vscode.workspace.onDidSaveTextDocument(async (e) => {
await updateDocument(e, true);
});
vscode.window.onDidChangeActiveTextEditor(async (e) => {
if (!e) {
// Do nothing.
return;
}
await updateDocument(e.document);
});
async function updateDocument(
document: vscode.TextDocument,
saved = false
) {
const previewjsClient = await previewjsInitPromise;
if (
!previewjsClient ||
!path.isAbsolute(document.fileName) ||
!watchedExtensions.has(path.extname(document.fileName))
) {
return;
}
previewjsClient.updatePendingFile({
absoluteFilePath: document.fileName,
utf8Content: saved ? null : document.getText(),
});
}
}
vscode.commands.registerCommand(
"previewjs.open",
catchErrors(
async (document?: vscode.TextDocument, componentId?: string) => {
const previewjsClient = await previewjsInitPromise;
if (!previewjsClient) {
vscode.window.showErrorMessage(
"Preview.js was unable to start successfully. Please check Preview.js output panel and consider filing a bug at https://github.com/fwouts/previewjs/issues."
);
return;
}
if (typeof componentId !== "string") {
// If invoked from clicking the button, the value may be { groupId: 0 }.
componentId = undefined;
}
const editor = vscode.window.activeTextEditor;
if (!document?.fileName) {
if (editor?.document) {
document = editor.document;
} else {
vscode.window.showErrorMessage("No document selected.");
return;
}
}
const workspaceId = await getWorkspaceId(previewjsClient, document);
if (!workspaceId) {
vscode.window.showErrorMessage(
`No compatible workspace detected from ${document.fileName}`
);
return;
}
if (componentId === undefined) {
const offset = editor?.selection.active
? document.offsetAt(editor.selection.active)
: 0;
const { components } = await previewjsClient.analyzeFile({
workspaceId,
absoluteFilePath: document.fileName,
});
const component =
components.find((c) => offset >= c.start && offset <= c.end) ||
components[0];
if (!component) {
vscode.window.showErrorMessage(
`No component was found at offset ${offset}`
);
return;
}
componentId = component.componentId;
}
const preview = await ensurePreviewServerStarted(
previewjsClient,
workspaceId
);
updatePreviewPanel(previewjsClient, preview.url, componentId);
}
)
);
}
export async function deactivate() {
await dispose();
await closePreviewPanel();
dispose = async () => {
// Do nothing.
};
}