forked from microsoft/vscode
-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
313 lines (256 loc) · 8.53 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
/*---------------------------------------------------------------------------------------------
* 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';
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();
const state = {
...(typeof originalState === 'object' ? originalState : {}),
...getData<any>('data-state')
};
if (originalState.resource !== state.resource) {
state.scrollProgress = undefined;
}
// 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;
if (typeof scrollProgress === 'number' && !settings.settings.fragment) {
doAfterImagesLoaded(() => {
scrollDisabledCount += 1;
window.scrollTo(0, scrollProgress * document.body.clientHeight);
});
return;
}
if (settings.settings.scrollPreviewWithEditor) {
doAfterImagesLoaded(() => {
// Try to scroll to fragment if available
if (settings.settings.fragment) {
state.fragment = undefined;
vscode.setState(state);
const element = getLineElementForFragment(settings.settings.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);
window.addEventListener('message', async event => {
switch (event.data.type) {
case 'onDidChangeTextEditorSelection':
if (event.data.source === documentResource) {
marker.onDidChangeTextEditorSelection(event.data.line, documentVersion);
}
return;
case 'updateView':
if (event.data.source === documentResource) {
onUpdateView(event.data.line);
}
return;
case 'updateContent': {
const root = document.querySelector('.markdown-body')!;
const parser = new DOMParser();
const newContent = parser.parseFromString(event.data.content, 'text/html');
// Strip out meta http-equiv tags
for (const metaElement of Array.from(newContent.querySelectorAll('meta'))) {
if (metaElement.hasAttribute('http-equiv')) {
metaElement.remove();
}
}
if (event.data.source !== documentResource) {
root.replaceWith(newContent.querySelector('.markdown-body')!);
documentResource = event.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'));
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);
}