Skip to content

Commit

Permalink
refactor: move preview common logic to @volar/preview
Browse files Browse the repository at this point in the history
close #1115
  • Loading branch information
johnsoncodehk committed Apr 10, 2022
1 parent b6bf667 commit de70d31
Show file tree
Hide file tree
Showing 14 changed files with 318 additions and 127 deletions.
5 changes: 3 additions & 2 deletions extensions/vscode-vue-language-features/package.json
Expand Up @@ -637,16 +637,17 @@
"devDependencies": {
"@types/vscode": "1.63.0",
"@types/ws": "^8.5.3",
"@volar/preview": "0.34.2",
"@volar/shared": "0.34.2",
"@volar/vue-language-server": "0.34.2",
"@vue/compiler-dom": "^3.2.31",
"@vue/compiler-sfc": "^3.2.31",
"@vue/reactivity": "^3.2.31",
"esbuild": "latest",
"esbuild-plugin-copy": "latest",
"path-browserify": "^1.0.1",
"vsce": "latest",
"vscode-languageclient": "^8.0.0-next.14",
"vscode-nls": "5.0.0",
"ws": "^8.5.0"
"vscode-nls": "5.0.0"
}
}
38 changes: 24 additions & 14 deletions extensions/vscode-vue-language-features/scripts/build-node.js
Expand Up @@ -15,19 +15,29 @@ require('esbuild').build({
define: { 'process.env.NODE_ENV': '"production"' },
minify: process.argv.includes('--minify'),
watch: process.argv.includes('--watch'),
plugins: [{
name: 'umd2esm',
setup(build) {
build.onResolve({ filter: /^(vscode-.*|estree-walker|jsonc-parser)/ }, args => {
const pathUmdMay = require.resolve(args.path, { paths: [args.resolveDir] })
const pathEsm = pathUmdMay.replace('/umd/', '/esm/')
return { path: pathEsm }
})
build.onResolve({ filter: /^\@vue\/compiler-sfc$/ }, args => {
const pathUmdMay = require.resolve(args.path, { paths: [args.resolveDir] })
const pathEsm = pathUmdMay.replace('compiler-sfc.cjs.js', 'compiler-sfc.esm-browser.js')
return { path: pathEsm }
})
plugins: [
{
name: 'umd2esm',
setup(build) {
build.onResolve({ filter: /^(vscode-.*|estree-walker|jsonc-parser)/ }, args => {
const pathUmdMay = require.resolve(args.path, { paths: [args.resolveDir] })
const pathEsm = pathUmdMay.replace('/umd/', '/esm/')
return { path: pathEsm }
})
build.onResolve({ filter: /^\@vue\/compiler-sfc$/ }, args => {
const pathUmdMay = require.resolve(args.path, { paths: [args.resolveDir] })
const pathEsm = pathUmdMay.replace('compiler-sfc.cjs.js', 'compiler-sfc.esm-browser.js')
return { path: pathEsm }
})
},
},
}],
require('esbuild-plugin-copy').copy({
resolveFrom: 'cwd',
assets: {
from: ['./node_modules/@volar/preview/bin/**/*'],
to: ['./dist/preview-bin'],
},
keepStructure: true,
}),
],
}).catch(() => process.exit(1))
139 changes: 49 additions & 90 deletions extensions/vscode-vue-language-features/src/features/preview.ts
Expand Up @@ -5,7 +5,7 @@ import * as fs from '../utils/fs';
import * as shared from '@volar/shared';
import { userPick } from './splitEditors';
import { parse, SFCParseResult } from '@vue/compiler-sfc';
import * as WebSocket from 'ws';
import * as preview from '@volar/preview';

interface PreviewState {
mode: 'vite' | 'nuxt',
Expand All @@ -28,40 +28,30 @@ export async function activate(context: vscode.ExtensionContext) {
statusBar.backgroundColor = new vscode.ThemeColor('statusBarItem.warningBackground');
context.subscriptions.push(statusBar);

const wsList: WebSocket.WebSocket[] = [];
let wss: WebSocket.Server | undefined;
let ws: ReturnType<typeof preview.createPreviewWebSocket> | undefined;

function startWsServer() {
wss = new WebSocket.Server({
port: 56789
});

wss.on('connection', ws => {
wsList.push(ws);
ws.on('message', msg => {
webviewEventHandler(JSON.parse(msg.toString()));
});
});
}
if (vscode.window.terminals.some(terminal => terminal.name.startsWith('volar-preview:'))) {
startWsServer();
ws = preview.createPreviewWebSocket({
goToCode: handleGoToCode,
getOpenFileUrl: (fileName, range) => 'vscode://files:/' + fileName,
});
}
vscode.window.onDidOpenTerminal(e => {
if (e.name.startsWith('volar-preview:')) {
startWsServer();
ws = preview.createPreviewWebSocket({
goToCode: handleGoToCode,
getOpenFileUrl: (fileName, range) => 'vscode://files:/' + fileName,
});
}
});
vscode.window.onDidCloseTerminal(e => {
if (e.name.startsWith('volar-preview:')) {
wss?.close();
wsList.length = 0;
ws?.stop();
}
});

const sfcs = new WeakMap<vscode.TextDocument, { version: number, sfc: SFCParseResult }>();

let goToTemplateReq = 0;

class FinderPanelSerializer implements vscode.WebviewPanelSerializer {
async deserializeWebviewPanel(panel: vscode.WebviewPanel, state: PreviewState) {

Expand Down Expand Up @@ -166,31 +156,16 @@ export async function activate(context: vscode.ExtensionContext) {
}
}));
context.subscriptions.push(vscode.window.onDidChangeTextEditorSelection(e => {
for (const panel of panels) {
updateSelectionHighlights(e.textEditor, panel, undefined);
}
for (const ws of wsList) {
updateSelectionHighlights(e.textEditor, undefined, ws);
}
updateSelectionHighlights(e.textEditor);
}));
context.subscriptions.push(vscode.workspace.onDidChangeTextDocument(e => {
if (vscode.window.activeTextEditor) {
for (const panel of panels) {
updateSelectionHighlights(vscode.window.activeTextEditor, panel, undefined);
}
for (const ws of wsList) {
updateSelectionHighlights(vscode.window.activeTextEditor, undefined, ws);
}
updateSelectionHighlights(vscode.window.activeTextEditor);
}
}));
context.subscriptions.push(vscode.workspace.onDidSaveTextDocument(e => {
if (vscode.window.activeTextEditor) {
for (const panel of panels) {
updateSelectionHighlights(vscode.window.activeTextEditor, panel, undefined);
}
for (const ws of wsList) {
updateSelectionHighlights(vscode.window.activeTextEditor, undefined, ws);
}
updateSelectionHighlights(vscode.window.activeTextEditor);
}
}));

Expand Down Expand Up @@ -223,33 +198,21 @@ export async function activate(context: vscode.ExtensionContext) {
}
}

function updateSelectionHighlights(textEditor: vscode.TextEditor, panel: vscode.WebviewPanel | undefined, ws: WebSocket.WebSocket | undefined) {
function updateSelectionHighlights(textEditor: vscode.TextEditor) {
if (textEditor.document.languageId === 'vue') {
const sfc = getSfc(textEditor.document);
const offset = sfc.descriptor.template?.loc.start.offset ?? 0;
const msg = {
sender: 'volar',
command: 'highlightSelections',
data: {
fileName: textEditor.document.fileName,
ranges: textEditor.selections.map(selection => ({
start: textEditor.document.offsetAt(selection.start) - offset,
end: textEditor.document.offsetAt(selection.end) - offset,
})),
isDirty: textEditor.document.isDirty,
},
};
panel?.webview.postMessage(msg);
ws?.send(JSON.stringify(msg));
ws?.highlight(
textEditor.document.fileName,
textEditor.selections.map(selection => ({
start: textEditor.document.offsetAt(selection.start) - offset,
end: textEditor.document.offsetAt(selection.end) - offset,
})),
textEditor.document.isDirty,
);
}
else {
const msg = {
sender: 'volar',
command: 'highlightSelections',
data: undefined,
};
panel?.webview.postMessage(JSON.stringify(msg));
ws?.send(JSON.stringify(msg));
ws?.unhighlight();
}
}

Expand Down Expand Up @@ -394,33 +357,29 @@ export async function activate(context: vscode.ExtensionContext) {
vscode.window.showErrorMessage(text);
break;
}
case 'goToTemplate': {
const req = ++goToTemplateReq;
const data = message.data as {
fileName: string,
range: [number, number],
};
const doc = await vscode.workspace.openTextDocument(data.fileName);

if (req !== goToTemplateReq)
return;

const sfc = getSfc(doc);
const offset = sfc.descriptor.template?.loc.start.offset ?? 0;
const start = doc.positionAt(data.range[0] + offset);
const end = doc.positionAt(data.range[1] + offset);
await vscode.window.showTextDocument(doc, vscode.ViewColumn.One);

if (req !== goToTemplateReq)
return;

const editor = vscode.window.activeTextEditor;
if (editor) {
editor.selection = new vscode.Selection(start, end);
editor.revealRange(new vscode.Range(start, end));
}
break;
}
}
}

async function handleGoToCode(fileName: string, range: [number, number], cancleToken: { readonly isCancelled: boolean }) {

const doc = await vscode.workspace.openTextDocument(fileName);

if (cancleToken.isCancelled)
return;

const sfc = getSfc(doc);
const offset = sfc.descriptor.template?.loc.start.offset ?? 0;
const start = doc.positionAt(range[0] + offset);
const end = doc.positionAt(range[1] + offset);
await vscode.window.showTextDocument(doc, vscode.ViewColumn.One);

if (cancleToken.isCancelled)
return;

const editor = vscode.window.activeTextEditor;
if (editor) {
editor.selection = new vscode.Selection(start, end);
editor.revealRange(new vscode.Range(start, end));
}
}

Expand All @@ -429,8 +388,8 @@ export async function activate(context: vscode.ExtensionContext) {
const port = await shared.getLocalHostAvaliablePort(vscode.workspace.getConfiguration('volar').get('preview.port') ?? 3334);
const terminal = vscode.window.createTerminal('volar-preview:' + port);
const viteProxyPath = type === 'vite'
? require.resolve('./bin/vite', { paths: [context.extensionPath] })
: require.resolve('./bin/nuxi', { paths: [context.extensionPath] });
? require.resolve('./dist/preview-bin/vite', { paths: [context.extensionPath] })
: require.resolve('./dist/preview-bin/nuxi', { paths: [context.extensionPath] });

terminal.sendText(`cd ${viteDir}`);

Expand Down
3 changes: 3 additions & 0 deletions extensions/vscode-vue-language-features/tsconfig.build.json
Expand Up @@ -16,6 +16,9 @@
{
"path": "../../packages/vue-language-server/tsconfig.build.json"
},
{
"path": "../../packages/preview/tsconfig.build.json"
},
{
"path": "../../packages/shared/tsconfig.build.json"
}
Expand Down
21 changes: 21 additions & 0 deletions packages/preview/LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021-present Johnson Chu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
36 changes: 36 additions & 0 deletions packages/preview/README.md
@@ -0,0 +1,36 @@
# vue-tsc

Install: `npm i vue-tsc -D`

Usage: `vue-tsc --noEmit && vite build`

Vue 3 command line Type-Checking tool base on IDE plugin [Volar](https://github.com/johnsoncodehk/volar).

Roadmap:

- [x] Type-Checking with `--noEmit`
- [x] Use released LSP module
- [x] Make `typescript` as peerDependencies
- [x] Cleaner dependencies (remove `prettyhtml`, `prettier` etc.) (with `vscode-vue-languageservice` version >= 0.26.4)
- [x] dts emit support
- [x] Watch mode support

## Using

Type check:

`vue-tsc --noEmit`

Build dts:

`vue-tsc --declaration --emitDeclarationOnly`

Check out https://github.com/johnsoncodehk/volar/discussions/640#discussioncomment-1555479 for example repo.

## Sponsors

<p align="center">
<a href="https://cdn.jsdelivr.net/gh/johnsoncodehk/sponsors/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/johnsoncodehk/sponsors/sponsors.svg'/>
</a>
</p>
File renamed without changes.
Expand Up @@ -43,12 +43,6 @@ export default defineNuxtPlugin(app => {
const cursorInOverlays = new Map<Element, HTMLElement>();
const rangeCoverOverlays = new Map<Element, HTMLElement>();

window.addEventListener('message', event => {
if (event.data?.command === 'highlightSelections') {
selection = event.data.data;
updateHighlights();
}
});
window.addEventListener('scroll', updateHighlights);

ws.addEventListener('message', event => {
Expand Down Expand Up @@ -198,6 +192,13 @@ export default defineNuxtPlugin(app => {
}
});

ws.addEventListener('message', event => {
const data = JSON.parse(event.data);
if (data?.command === 'openFile') {
window.open(data.data);
}
});

const overlay = createOverlay();
const clickMask = createClickMask();

Expand All @@ -216,16 +217,19 @@ export default defineNuxtPlugin(app => {
document.body.appendChild(clickMask);
updateOverlay();
}
function disable(openVscode: boolean) {
function disable(openEditor: boolean) {
if (enabled) {
enabled = false;
clickMask.style.pointerEvents = '';
highlightNodes = [];
updateOverlay();
if (lastCodeLoc) {
ws.send(JSON.stringify(lastCodeLoc));
if (openVscode) {
window.open('vscode://files:/' + lastCodeLoc.fileName);
if (openEditor) {
ws.send(JSON.stringify({
command: 'requestOpenFile',
data: lastCodeLoc.data,
}));
}
lastCodeLoc = undefined;
}
Expand Down

0 comments on commit de70d31

Please sign in to comment.