-
Notifications
You must be signed in to change notification settings - Fork 0
/
RenderWhitespaceOnGithub.user.js
233 lines (214 loc) · 8.52 KB
/
RenderWhitespaceOnGithub.user.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
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
/**
The MIT License (MIT)
Copyright (c) 2017-2018 Gleb Mazovetskiy
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.
**/
// ==UserScript==
// @id RenderWhitespace
// @name Render Whitespace on GitHub
// @description Renders spaces as · and tabs as → in all the code on GitHub.
// @namespace https://github.com/glebm
// @version 1.3.12
// @author Gleb Mazovetskiy <glex.spb@gmail.com>
// @license MIT
// @domain github.com
// @domain gist.github.com
// @match https://gist.github.com/*
// @match https://github.com/*
// @homepageUrl https://github.com/glebm/render-whitespace-on-github
// @run-at document-end
// @contributionURL https://etherchain.org/account/0x962644db6d8735446c1af84a2c1f16143f780184
// ==/UserScript==
// Settings
let settings;
const DEFAULTS = {
whitespaceOpacity: 0.4,
copyableWhitespace: false,
space: '·',
tab: '→',
};
// Constants
const WS_CLASS = 'glebm-ws';
const ROOT_SELECTOR = 'table[data-tab-size],div[data-tab-size],table.diff-table';
const NODE_FILTER = {
acceptNode(node) {
let parent = node.parentNode;
if (parent.classList.contains(WS_CLASS)) return NodeFilter.FILTER_SKIP;
while (!parent.matches(ROOT_SELECTOR)) {
if ( /* mobile code */
parent.classList.contains('js-file-line') ||
/* desktop code, diff; mobile diff */
parent.classList.contains('blob-code-inner')) {
return !(parent.firstChild === node && node.nodeValue === ' ') ?
NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
}
parent = parent.parentNode;
}
return NodeFilter.FILTER_SKIP;
}
};
function main() {
const styleNode = document.createElement('style');
styleNode.textContent = settings.copyableWhitespaceIndicators ?
`.${WS_CLASS} { opacity: ${settings.whitespaceOpacity}; }` :
`.${WS_CLASS}::before {
opacity: ${settings.whitespaceOpacity};
position: absolute;
text-indent: 0;
}
/* desktop non-diff, mobile diff */
.blob-code .${WS_CLASS}::before {
line-height: 20px;
}
/* horizontal scroll */
.blob-file-content pre,
.diff-view .file .highlight,
.blob-wrapper {
position: relative;
}`;
document.head.appendChild(styleNode);
// github/legacy/pages/diffs/expander
const diffTableObserver = new MutationObserver((records) => {
for (const record of records) {
showWhitespaceIn(record.target.parentElement);
}
});
const initDiffExpanders = () => {
for (const node of document.querySelectorAll('.diff-table > tbody')) {
diffTableObserver.observe(node, { childList: true });
}
};
document.addEventListener('pjax:success', () => {
diffTableObserver.disconnect();
});
// https://github.com/github/include-fragment-element
const registeredFragments = new WeakSet();
const onFragmentLoadEnd = (node) => {
return () => {
setTimeout(() => {
for (const root of node.querySelectorAll(ROOT_SELECTOR)) {
showWhitespaceIn(root);
}
}, 0);
};
}
const initFragments = () => {
for (const node of document.querySelectorAll('include-fragment')) {
if (registeredFragments.has(node)) continue;
registeredFragments.add(node);
node.addEventListener('loadend', onFragmentLoadEnd(node.parentElement));
}
}
const initDOM = () => {
for (const root of document.querySelectorAll(ROOT_SELECTOR)) {
showWhitespaceIn(root);
}
initDiffExpanders();
initFragments();
};
document.addEventListener('pjax:success', initDOM);
initDOM();
}
function showWhitespaceIn(root) {
const rootStyle = window.getComputedStyle(root);
const tab = settings.tab.padEnd(
+(rootStyle['tab-size'] || rootStyle['-moz-tab-size'] || root.dataset.tabSize));
const treeWalker =
document.createTreeWalker(root, NodeFilter.SHOW_TEXT, NODE_FILTER);
const nodes = [];
while (treeWalker.nextNode()) nodes.push(treeWalker.currentNode);
const isDiff = /* desktop */ root.classList.contains('diff-table') ||
/* mobile */ root.classList.contains('file-diff');
for (const node of nodes) replaceWhitespace(node, tab, settings.space, isDiff);
}
function isSpace(char) {
return /* desktop */ char === ' ' ||
/* mobile */ char === '\xa0' /* */;
}
function replaceWhitespace(node, tab, space, isDiff) {
let originalText = node.nodeValue;
const parent = node.parentNode;
const ignoreFirstSpace = isDiff &&
isSpace(originalText.charAt(0)) &&
parent.firstChild === node &&
parent.classList.contains('blob-code-inner') &&
parent.parentNode.classList.contains('blob-expanded') &&
// "Refined Github" extension removes the extra first space:
// https://github.com/sindresorhus/refined-github/blob/34f713a331bf7dbf65c2082d3d2c667e06f22021/src/features/remove-diff-signs.js#L20
!parent.matches('.refined-github-diff-signs *');
if (ignoreFirstSpace) {
if (isSpace(originalText)) return;
originalText = originalText.slice(1);
parent.insertBefore(document.createTextNode(' '), node);
}
const tabParts = originalText.split('\t');
const tabSpaceParts = tabParts.map(s => s.split(/[ \xa0]/));
if (!ignoreFirstSpace && tabSpaceParts.length === 1 &&
tabSpaceParts[0].length === 1) return;
const insert = (newNode) => {
parent.insertBefore(newNode, node);
};
insertParts(tabSpaceParts,
spaceParts => spaceParts.length === 1 && spaceParts[0] === '',
n => insert(createWhitespaceNode('t', '\t', tab, n)),
spaceParts =>
insertParts(spaceParts,
text => text === '',
n => insert(createWhitespaceNode('s', ' ', space, n)),
text => insert(document.createTextNode(text))));
parent.removeChild(node);
}
var WS_ADDED_STYLES = new Set();
function createWhitespaceNode(type, originalText, text, n) {
const node = document.createElement('span');
node.classList.add(WS_CLASS);
if (settings.copyableWhitespace) {
node.textContent = text.repeat(n);
} else {
const className = `${type}-${n}`;
if (!WS_ADDED_STYLES.has(className)) {
const styleNode = document.createElement('style');
styleNode.textContent =
`.${WS_CLASS}-${className}::before { content: '${text.repeat(n)}'; }`;
document.head.appendChild(styleNode);
WS_ADDED_STYLES.add(className);
}
node.classList.add(`${WS_CLASS}-${className}`);
node.textContent = originalText.repeat(n);
}
return node;
}
function insertParts(parts, isConsecutiveFn, addInterFn, addPartFn) {
const n = parts.length;
parts.reduce((consecutive, part, i) => {
const isConsecutive = isConsecutiveFn(part);
if (isConsecutive && i !== n - 1) return consecutive + 1;
if (consecutive > 0) addInterFn(consecutive);
if (!isConsecutive) addPartFn(part);
return 1;
}, 0);
}
function onSettingsLoaded(result) {
settings = result;
main();
}
if (typeof browser !== 'undefined' && typeof browser.storage !== 'undefined') {
browser.storage.sync.get(DEFAULTS).then(onSettingsLoaded);
} else if (typeof chrome !== 'undefined' && typeof chrome.storage !== 'undefined') {
chrome.storage.sync.get(DEFAULTS, onSettingsLoaded);
} else {
onSettingsLoaded(DEFAULTS);
}