/
index.ts
87 lines (71 loc) · 1.73 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
import * as WebSocket from 'ws';
export function createPreviewConnection(options: {
onGotoCode: (fileName: string, range: [number, number], cancelToken: { readonly isCancelled: boolean; }) => void,
getFileHref: (fileName: string, range: [number, number]) => string,
}) {
const wsList: WebSocket.WebSocket[] = [];
let wss: WebSocket.Server | undefined;
let goToTemplateReq = 0;
wss = new WebSocket.Server({ port: 56789 });
wss.on('connection', ws => {
wsList.push(ws);
ws.on('message', msg => {
const message = JSON.parse(msg.toString());
if (message.command === 'goToTemplate') {
const req = ++goToTemplateReq;
const data = message.data as {
fileName: string,
range: [number, number],
};
const token = {
get isCancelled() {
return req !== goToTemplateReq;
}
};
options.onGotoCode(data.fileName, data.range, token);
}
if (message.command === 'requestOpenFile') {
const data = message.data as {
fileName: string,
range: [number, number],
};
const url = options.getFileHref(data.fileName, data.range);
ws.send(JSON.stringify({
command: 'openFile',
data: url,
}));
}
});
});
return {
stop,
highlight,
unhighlight,
};
function stop() {
wss?.close();
wsList.length = 0;
}
function highlight(fileName: string, ranges: { start: number, end: number; }[], isDirty: boolean) {
const msg = {
command: 'highlightSelections',
data: {
fileName,
ranges,
isDirty,
},
};
for (const ws of wsList) {
ws.send(JSON.stringify(msg));
}
}
function unhighlight() {
const msg = {
command: 'highlightSelections',
data: undefined,
};
for (const ws of wsList) {
ws.send(JSON.stringify(msg));
}
}
}