-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathview-source.js
39 lines (33 loc) · 1.08 KB
/
view-source.js
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
const a = document.querySelector('a');
const pre = document.querySelector('pre');
const code = new URL(location.href).searchParams.get('code');
a.href = code;
a.textContent = code;
const SURROUNDING_CHARS = 100000;
const escapeHTML = (str) => {
const div = document.createElement('div');
div.append(document.createTextNode(str));
return div.innerHTML;
};
(async () => {
let text = await fetch(code).then((response) => response.text());
text = escapeHTML(text);
const textStart = document.fragmentDirective.items[0].textStart;
text = text.replaceAll(textStart, `<mark>${textStart}</mark>`);
const index = text.indexOf(`<mark>${textStart}</mark>`);
pre.innerHTML = `${text.substring(
index - SURROUNDING_CHARS > 0 ? index - SURROUNDING_CHARS : 0,
index,
)}${text.substring(
index,
index + SURROUNDING_CHARS > text.length
? text.length
: index + SURROUNDING_CHARS,
)}`;
pre.querySelector('mark').scrollIntoView({
behavior: matchMedia('(prefers-reduced-motion: no-preference').matches
? 'smooth'
: 'auto',
block: 'center',
});
})();