Repository navigation
Expand file tree
/
Copy pathgithub-mark-viewed.user.js
More file actions
343 lines (284 loc) · 11.8 KB
/
Copy pathgithub-mark-viewed.user.js
File metadata and controls
343 lines (284 loc) · 11.8 KB
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
// ==UserScript==
// @name GitHub — mark file as Viewed with "v"
// @namespace https://github.com/solcik/userscripts
// @version 0.6.1
// @description In a GitHub pull request diff view: "v" marks the focused file viewed and moves on, "j"/"k" go to the next/previous file, "u" un-marks the last file "v" marked, and "V" shows or hides viewed files. The first "v" on a pull request only hides viewed files.
// @author David Solc
// @match https://github.com/*/*/pull/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=github.com
// @homepageURL https://github.com/solcik/userscripts
// @supportURL https://github.com/solcik/userscripts/issues
// @updateURL https://raw.githubusercontent.com/solcik/userscripts/main/github-mark-viewed.user.js
// @downloadURL https://raw.githubusercontent.com/solcik/userscripts/main/github-mark-viewed.user.js
// @require https://cdn.jsdelivr.net/npm/mousetrap@1.6.5/mousetrap.min.js
// @grant none
// @license MIT
// ==/UserScript==
(function () {
'use strict';
const VIEWED_BUTTON = 'button[class*="MarkAsViewedButton-module"]';
// Both the React diff view and the older server-rendered one give every file a
// "diff-<sha>" id; the wrapper element around it differs between them. The sha
// hashes the file path, so the id also survives a reload.
const FILE_ID = /^diff-[0-9a-f]{16,}$/;
// GitHub has no "next file" shortcut of its own, so we scroll. The page header
// is sticky and GitHub sets no scroll-padding, so measure whatever is currently
// pinned to the top edge rather than hard-coding its height.
const EDGE = 4;
const SETTLE_MS = 400;
// The file filter is a Primer ActionMenu. Its items render only while it is
// open, and its trigger carries no stable id, so find it by its filter icon.
const FILTER_TRIGGER = 'button[aria-haspopup="true"]:has(svg.octicon-filter)';
const VIEWED_FILTER_LABEL = 'Viewed files';
const WAIT_MS = 1500;
const UNDO_KEY = 'github-mark-viewed:undo:';
const CURSOR_ATTR = 'data-mark-viewed-cursor';
// ---- Page model: files, focus, scrolling -------------------------------
function diffFiles() {
return [...document.querySelectorAll('div[id^="diff-"]')].filter((el) => FILE_ID.test(el.id));
}
function topChrome() {
const padding = parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop);
let bottom = Number.isFinite(padding) ? padding : 0;
for (const el of document.elementsFromPoint(Math.round(window.innerWidth / 2), 1)) {
const position = getComputedStyle(el).position;
if (position === 'fixed' || position === 'sticky') {
bottom = Math.max(bottom, el.getBoundingClientRect().bottom);
}
}
return bottom;
}
// ---- Cursor ---------------------------------------------------------------
// Near the end of the page the browser cannot scroll a file up under the
// header, so the scroll position alone cannot say which file a key moved to.
// The keys therefore keep an explicit cursor and outline that file.
let cursorId = null;
const style = document.createElement('style');
style.textContent = `[${CURSOR_ATTR}] {
outline: 2px solid var(--fgColor-accent, #0969da);
outline-offset: 2px;
border-radius: 6px;
}`;
document.head.append(style);
function setCursor(id) {
for (const el of document.querySelectorAll(`[${CURSOR_ATTR}]`)) {
if (el.id !== id) el.removeAttribute(CURSOR_ATTR);
}
cursorId = id;
const file = id && document.getElementById(id);
if (file && !file.hasAttribute(CURSOR_ATTR)) file.setAttribute(CURSOR_ATTR, '');
}
function onScreen(file) {
const rect = file.getBoundingClientRect();
return rect.bottom > topChrome() && rect.top < window.innerHeight;
}
// The file being read is the cursor file while it is on screen. Otherwise,
// for example after scrolling with the mouse, it is the topmost file still
// visible below the page header.
function focusedIndex(files) {
const cursor = cursorId ? files.findIndex((file) => file.id === cursorId) : -1;
if (cursor >= 0 && onScreen(files[cursor])) return cursor;
if (files.length < 2) return files.length - 1;
const edge = topChrome() + EDGE;
const index = files.findIndex((file) => file.getBoundingClientRect().bottom > edge);
return index === -1 ? files.length - 1 : index;
}
function isViewed(file) {
const button = file.querySelector(VIEWED_BUTTON);
return !!button && button.getAttribute('aria-pressed') === 'true';
}
// Marking a file viewed collapses it — or drops it from the list entirely when
// "Viewed files" is unchecked — so the layout keeps moving for a few frames
// after the click. Re-pin the file to the top until it settles. A newer pin
// cancels an older one, so fast key presses do not fight over the scroll.
let pinToken = 0;
function scrollToFile(id) {
const token = ++pinToken;
const started = performance.now();
(function pin() {
if (token !== pinToken) return;
const file = document.getElementById(id);
if (file) {
// React can re-create the element while the layout settles.
setCursor(id);
const top = window.scrollY + file.getBoundingClientRect().top - topChrome();
if (Math.abs(top - window.scrollY) > 1) window.scrollTo({ top, left: window.scrollX });
}
if (performance.now() - started < SETTLE_MS) requestAnimationFrame(pin);
})();
}
// Poll once per frame until check() returns something truthy, then hand it to
// done(). After WAIT_MS, done() gets null.
function waitFor(check, done) {
const started = performance.now();
(function poll() {
const value = check();
if (value) done(value);
else if (performance.now() - started < WAIT_MS) requestAnimationFrame(poll);
else done(null);
})();
}
// ---- "Viewed files" filter ---------------------------------------------
function viewedFilterItem() {
return [...document.querySelectorAll('[role="menuitemcheckbox"]')].find(
(item) => item.textContent.trim() === VIEWED_FILTER_LABEL,
);
}
function closeMenu() {
if (!viewedFilterItem()) return;
const target = document.activeElement || document.body;
target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
}
// Open the file filter and set "Viewed files" to `show`, or flip it when `show`
// is undefined. Calls done(changed) once the menu is closed again. Returns
// false when this diff view has no such filter.
function setViewedFilter(show, done) {
const trigger = document.querySelector(FILTER_TRIGGER);
if (!trigger) return false;
trigger.click();
waitFor(viewedFilterItem, function (item) {
let changed = false;
if (item) {
const shown = item.getAttribute('aria-checked') === 'true';
const wanted = show === undefined ? !shown : show;
changed = wanted !== shown;
if (changed) item.click();
}
requestAnimationFrame(function () {
closeMenu();
done(changed);
});
});
return true;
}
// ---- Per pull request state --------------------------------------------
// "/files" and "/changes" are the same pull request, so key state by its base.
function pullKey() {
const match = location.pathname.match(/^\/[^/]+\/[^/]+\/pull\/\d+/);
return match ? match[0] : location.pathname;
}
// Undo stack of file ids that "v" marked viewed, kept per pull request in
// sessionStorage so that it survives a reload of the tab.
function loadUndo() {
try {
return JSON.parse(sessionStorage.getItem(UNDO_KEY + pullKey())) || [];
} catch {
return [];
}
}
function saveUndo(ids) {
try {
sessionStorage.setItem(UNDO_KEY + pullKey(), JSON.stringify(ids));
} catch {
// Storage can be blocked; undo then lasts only until the next press.
}
}
// GitHub navigates between pull requests without a page load, so remember
// which one already had its viewed files hidden.
let filteredPull = null;
// ---- Commands ------------------------------------------------------------
function toggleFocusedFile() {
const files = diffFiles();
const index = focusedIndex(files);
if (index < 0) return;
const file = files[index];
const button = file.querySelector(VIEWED_BUTTON);
if (!button) return;
// Un-viewing expands the file again, which is the whole point of pressing
// "v" on an already-viewed file — stay put so it can actually be read.
const marking = !isViewed(file);
button.click();
if (!marking) {
setCursor(file.id);
return;
}
saveUndo([...loadUndo().filter((id) => id !== file.id), file.id]);
const next = files[index + 1];
if (next) scrollToFile(next.id);
}
function markViewed() {
if (filteredPull === pullKey()) {
toggleFocusedFile();
return;
}
// In a long pull request the viewed files above the viewport confuse the
// focus lookup, so the first press only hides them. It toggles nothing,
// because the layout is still moving and the focused file is not known yet.
// If they were hidden already, the press toggles as usual.
const found = setViewedFilter(false, function (changed) {
if (!changed) toggleFocusedFile();
});
if (found) filteredPull = pullKey();
else toggleFocusedFile();
}
function goToNextFile() {
const files = diffFiles();
const next = files[focusedIndex(files) + 1];
if (next) scrollToFile(next.id);
}
// Like "k" in an editor: from the middle of a file, go to its start first.
function goToPreviousFile() {
const files = diffFiles();
const index = focusedIndex(files);
if (index < 0) return;
const scrolledInto = files[index].getBoundingClientRect().top < topChrome() - EDGE;
const target = scrolledInto ? files[index] : files[index - 1];
if (target) scrollToFile(target.id);
}
function unmark(file) {
if (isViewed(file)) file.querySelector(VIEWED_BUTTON).click();
}
// Un-mark the last file "v" marked and jump to it. With viewed files hidden
// that file is not in the page, so show them for a moment, un-mark it, wait
// until GitHub reflects that, and hide them again.
function undoLastMark() {
const ids = loadUndo();
const id = ids.pop();
if (!id) return;
saveUndo(ids);
const present = document.getElementById(id);
if (present) {
unmark(present);
scrollToFile(id);
return;
}
const found = setViewedFilter(true, function (shown) {
waitFor(
() => document.getElementById(id),
function (file) {
if (!file) {
if (shown) setViewedFilter(false, () => {});
return;
}
unmark(file);
waitFor(
() => !isViewed(file),
function () {
if (shown) setViewedFilter(false, () => scrollToFile(id));
else scrollToFile(id);
},
);
},
);
});
if (!found) saveUndo([...ids, id]);
}
// Show or hide viewed files without changing any review state, and keep the
// focused file in place. A viewed file that gets hidden cannot stay in place,
// so then the view lands on the file that follows it.
function togglePeek() {
const files = diffFiles();
const index = focusedIndex(files);
const keep = files.slice(Math.max(index, 0)).map((file) => file.id);
const found = setViewedFilter(undefined, function () {
const id = keep.find((candidate) => document.getElementById(candidate));
if (id) scrollToFile(id);
});
if (found) filteredPull = pullKey();
}
Mousetrap.bind('v', markViewed);
Mousetrap.bind('j', goToNextFile);
Mousetrap.bind('k', goToPreviousFile);
Mousetrap.bind('u', undoLastMark);
Mousetrap.bind('shift+v', togglePeek);
})();