-
Notifications
You must be signed in to change notification settings - Fork 29.3k
/
index.ts
373 lines (314 loc) · 10.7 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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ActiveLineMarker } from './activeLineMarker';
import { onceDocumentLoaded } from './events';
import { createPosterForVsCode } from './messaging';
import { getEditorLineNumberForPageOffset, scrollToRevealSourceLine, getLineElementForFragment } from './scroll-sync';
import { SettingsManager, getData } from './settings';
import throttle = require('lodash.throttle');
import morphdom from 'morphdom';
import type { ToWebviewMessage } from '../types/previewMessaging';
let scrollDisabledCount = 0;
const marker = new ActiveLineMarker();
const settings = new SettingsManager();
let documentVersion = 0;
let documentResource = settings.settings.source;
const vscode = acquireVsCodeApi();
const originalState = vscode.getState() ?? {} as any;
const state = {
...originalState,
...getData<any>('data-state')
};
if (typeof originalState.scrollProgress !== 'undefined' && originalState?.resource !== state.resource) {
state.scrollProgress = 0;
}
// Make sure to sync VS Code state here
vscode.setState(state);
const messaging = createPosterForVsCode(vscode, settings);
window.cspAlerter.setPoster(messaging);
window.styleLoadingMonitor.setPoster(messaging);
function doAfterImagesLoaded(cb: () => void) {
const imgElements = document.getElementsByTagName('img');
if (imgElements.length > 0) {
const ps = Array.from(imgElements, e => {
if (e.complete) {
return Promise.resolve();
} else {
return new Promise<void>((resolve) => {
e.addEventListener('load', () => resolve());
e.addEventListener('error', () => resolve());
});
}
});
Promise.all(ps).then(() => setTimeout(cb, 0));
} else {
setTimeout(cb, 0);
}
}
onceDocumentLoaded(() => {
const scrollProgress = state.scrollProgress;
addImageContexts();
if (typeof scrollProgress === 'number' && !settings.settings.fragment) {
doAfterImagesLoaded(() => {
scrollDisabledCount += 1;
// Always set scroll of at least 1 to prevent VS Code's webview code from auto scrolling us
const scrollToY = Math.max(1, scrollProgress * document.body.clientHeight);
window.scrollTo(0, scrollToY);
});
return;
}
if (settings.settings.scrollPreviewWithEditor) {
doAfterImagesLoaded(() => {
// Try to scroll to fragment if available
if (settings.settings.fragment) {
let fragment: string;
try {
fragment = encodeURIComponent(settings.settings.fragment);
} catch {
fragment = settings.settings.fragment;
}
state.fragment = undefined;
vscode.setState(state);
const element = getLineElementForFragment(fragment, documentVersion);
if (element) {
scrollDisabledCount += 1;
scrollToRevealSourceLine(element.line, documentVersion, settings);
}
} else {
if (!isNaN(settings.settings.line!)) {
scrollDisabledCount += 1;
scrollToRevealSourceLine(settings.settings.line!, documentVersion, settings);
}
}
});
}
if (typeof settings.settings.selectedLine === 'number') {
marker.onDidChangeTextEditorSelection(settings.settings.selectedLine, documentVersion);
}
});
const onUpdateView = (() => {
const doScroll = throttle((line: number) => {
scrollDisabledCount += 1;
doAfterImagesLoaded(() => scrollToRevealSourceLine(line, documentVersion, settings));
}, 50);
return (line: number) => {
if (!isNaN(line)) {
state.line = line;
doScroll(line);
}
};
})();
window.addEventListener('resize', () => {
scrollDisabledCount += 1;
updateScrollProgress();
}, true);
function addImageContexts() {
const images = document.getElementsByTagName('img');
let idNumber = 0;
for (const img of images) {
img.id = 'image-' + idNumber;
idNumber += 1;
img.setAttribute('data-vscode-context', JSON.stringify({ webviewSection: 'image', id: img.id, 'preventDefaultContextMenuItems': true, resource: documentResource }));
}
}
async function copyImage(image: HTMLImageElement, retries = 5) {
if (!document.hasFocus() && retries > 0) {
// copyImage is called at the same time as webview.reveal, which means this function is running whilst the webview is gaining focus.
// Since navigator.clipboard.write requires the document to be focused, we need to wait for focus.
// We cannot use a listener, as there is a high chance the focus is gained during the setup of the listener resulting in us missing it.
setTimeout(() => { copyImage(image, retries - 1); }, 20);
return;
}
try {
await navigator.clipboard.write([new ClipboardItem({
'image/png': new Promise((resolve) => {
const canvas = document.createElement('canvas');
if (canvas !== null) {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext('2d');
context?.drawImage(image, 0, 0);
}
canvas.toBlob((blob) => {
if (blob) {
resolve(blob);
}
canvas.remove();
}, 'image/png');
})
})]);
} catch (e) {
console.error(e);
}
}
window.addEventListener('message', async event => {
const data = event.data as ToWebviewMessage.Type;
switch (data.type) {
case 'copyImage': {
const img = document.getElementById(data.id);
if (img instanceof HTMLImageElement) {
copyImage(img);
}
return;
}
case 'onDidChangeTextEditorSelection':
if (data.source === documentResource) {
marker.onDidChangeTextEditorSelection(data.line, documentVersion);
}
return;
case 'updateView':
if (data.source === documentResource) {
onUpdateView(data.line);
}
return;
case 'updateContent': {
const root = document.querySelector('.markdown-body')!;
const parser = new DOMParser();
const newContent = parser.parseFromString(data.content, 'text/html'); // CodeQL [SM03712] This renderers content from the workspace into the Markdown preview. Webviews (and the markdown preview) have many other security measures in place to make this safe
// Strip out meta http-equiv tags
for (const metaElement of Array.from(newContent.querySelectorAll('meta'))) {
if (metaElement.hasAttribute('http-equiv')) {
metaElement.remove();
}
}
if (data.source !== documentResource) {
root.replaceWith(newContent.querySelector('.markdown-body')!);
documentResource = data.source;
} else {
const skippedAttrs = [
'open', // for details
];
// Compare two elements but some elements
const areEqual = (a: Element, b: Element): boolean => {
if (a.isEqualNode(b)) {
return true;
}
if (a.tagName !== b.tagName || a.textContent !== b.textContent) {
return false;
}
const aAttrs = [...a.attributes].filter(attr => !skippedAttrs.includes(attr.name));
const bAttrs = [...b.attributes].filter(attr => !skippedAttrs.includes(attr.name));
if (aAttrs.length !== bAttrs.length) {
return false;
}
for (let i = 0; i < aAttrs.length; ++i) {
const aAttr = aAttrs[i];
const bAttr = bAttrs[i];
if (aAttr.name !== bAttr.name) {
return false;
}
if (aAttr.value !== bAttr.value && aAttr.name !== 'data-line') {
return false;
}
}
const aChildren = Array.from(a.children);
const bChildren = Array.from(b.children);
return aChildren.length === bChildren.length && aChildren.every((x, i) => areEqual(x, bChildren[i]));
};
const newRoot = newContent.querySelector('.markdown-body')!;
// Move styles to head
// This prevents an ugly flash of unstyled content
const styles = newRoot.querySelectorAll('link');
for (const style of styles) {
style.remove();
}
newRoot.prepend(...styles);
morphdom(root, newRoot, {
childrenOnly: true,
onBeforeElUpdated: (fromEl, toEl) => {
if (areEqual(fromEl, toEl)) {
// areEqual doesn't look at `data-line` so copy those over manually
const fromLines = fromEl.querySelectorAll('[data-line]');
const toLines = toEl.querySelectorAll('[data-line]');
if (fromLines.length !== toLines.length) {
console.log('unexpected line number change');
}
for (let i = 0; i < fromLines.length; ++i) {
const fromChild = fromLines[i];
const toChild = toLines[i];
if (toChild) {
fromChild.setAttribute('data-line', toChild.getAttribute('data-line')!);
}
}
return false;
}
if (fromEl.tagName === 'DETAILS' && toEl.tagName === 'DETAILS') {
if (fromEl.hasAttribute('open')) {
toEl.setAttribute('open', '');
}
}
return true;
}
});
}
++documentVersion;
window.dispatchEvent(new CustomEvent('vscode.markdown.updateContent'));
addImageContexts();
break;
}
}
}, false);
document.addEventListener('dblclick', event => {
if (!settings.settings.doubleClickToSwitchToEditor) {
return;
}
// Ignore clicks on links
for (let node = event.target as HTMLElement; node; node = node.parentNode as HTMLElement) {
if (node.tagName === 'A') {
return;
}
}
const offset = event.pageY;
const line = getEditorLineNumberForPageOffset(offset, documentVersion);
if (typeof line === 'number' && !isNaN(line)) {
messaging.postMessage('didClick', { line: Math.floor(line) });
}
});
const passThroughLinkSchemes = ['http:', 'https:', 'mailto:', 'vscode:', 'vscode-insiders:'];
document.addEventListener('click', event => {
if (!event) {
return;
}
let node: any = event.target;
while (node) {
if (node.tagName && node.tagName === 'A' && node.href) {
if (node.getAttribute('href').startsWith('#')) {
return;
}
let hrefText = node.getAttribute('data-href');
if (!hrefText) {
// Pass through known schemes
if (passThroughLinkSchemes.some(scheme => node.href.startsWith(scheme))) {
return;
}
hrefText = node.getAttribute('href');
}
// If original link doesn't look like a url, delegate back to VS Code to resolve
if (!/^[a-z\-]+:/i.test(hrefText)) {
messaging.postMessage('openLink', { href: hrefText });
event.preventDefault();
event.stopPropagation();
return;
}
return;
}
node = node.parentNode;
}
}, true);
window.addEventListener('scroll', throttle(() => {
updateScrollProgress();
if (scrollDisabledCount > 0) {
scrollDisabledCount -= 1;
} else {
const line = getEditorLineNumberForPageOffset(window.scrollY, documentVersion);
if (typeof line === 'number' && !isNaN(line)) {
messaging.postMessage('revealLine', { line });
}
}
}, 50));
function updateScrollProgress() {
state.scrollProgress = window.scrollY / document.body.clientHeight;
vscode.setState(state);
}