-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
311 lines (273 loc) · 10.3 KB
/
Copy pathcontent.js
File metadata and controls
311 lines (273 loc) · 10.3 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
// @ts-check
// GitHub PR Reverse Comments — content script
//
// Reverses chronological lists on GitHub PR pages so the newest entry
// appears first. Currently supports:
//
// /owner/repo/pull/N (Conversation) — reverse .js-timeline-item
// /owner/repo/pull/N/commits (Commits) — reverse .js-commit-group
// AND reverse <li> commits
// within each group
//
// The same toggle preference (newest vs oldest) drives every supported
// page. Non-supported PR sub-tabs (Files Changed, Checks) are ignored.
(() => {
// STORAGE_KEY, ORDER, and normalizeOrder come from constants.js (loaded
// first); applyOrderToTarget from reorder.js; getPageConfig (and every
// GitHub DOM selector) from pages.js; the checks helpers from checks.js.
const RESET_VERSION_KEY = "prrcDefaultResetVersion";
const CURRENT_RESET_VERSION = 1;
const BUTTON_ID = "pr-reverse-comments-toggle";
const CHECKS_STATUS_ID = "pr-reverse-comments-checks-status";
/** @type {PrrcOrder} */
let currentOrder = ORDER.NEWEST;
let isSorting = false;
/** @type {MutationObserver[]} */
let observers = [];
/** @type {PrrcTarget[]} */
let activeTargets = []; // [{ el, item, ... }]
function getCurrentPageConfig() {
return getPageConfig(location.pathname);
}
function onSupportedPage() {
return getCurrentPageConfig() !== null;
}
/** @param {string} order */
function applyOrder(order) {
const cfg = getCurrentPageConfig();
if (!cfg) return;
const targets = cfg.getTargets();
if (!targets.length) return;
activeTargets = targets;
isSorting = true;
try {
for (const t of targets) applyOrderToTarget(t, order);
} finally {
setTimeout(() => {
isSorting = false;
}, 0);
}
}
function disconnectObservers() {
for (const o of observers) o.disconnect();
observers = [];
}
function startObservers() {
disconnectObservers();
if (!activeTargets.length) return;
for (const target of activeTargets) {
const watch = target.descendant
? target.el.querySelector(target.item)?.parentElement || target.el
: target.el;
const obs = new MutationObserver((mutations) => {
if (isSorting) return;
const structural = mutations.some(
(m) => m.type === "childList" && (m.addedNodes.length || m.removedNodes.length),
);
if (!structural) return;
disconnectObservers();
applyOrder(currentOrder);
startObservers();
});
obs.observe(watch, { childList: true });
observers.push(obs);
}
}
function injectToggleButton() {
if (document.getElementById(BUTTON_ID)) return;
const btn = document.createElement("button");
btn.id = BUTTON_ID;
btn.type = "button";
btn.style.cssText = [
"position: fixed",
"bottom: 16px",
"right: 16px",
"z-index: 2147483647",
"padding: 8px 14px",
"background: #1f6feb",
"color: #fff",
"border: 1px solid rgba(255,255,255,0.1)",
"border-radius: 6px",
"font: 12px -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
"cursor: pointer",
"box-shadow: 0 2px 8px rgba(0,0,0,0.3)",
].join(";");
updateButtonLabel(btn);
btn.addEventListener("click", () => {
currentOrder = currentOrder === ORDER.NEWEST ? ORDER.OLDEST : ORDER.NEWEST;
chrome.storage.local.set({ [STORAGE_KEY]: currentOrder });
updateButtonLabel(btn);
applyOrder(currentOrder);
});
document.body.appendChild(btn);
}
// Where to put the checks indicator: at the very top of the conversation
// column, above the PR description. We insert *before* one of these
// anchors within its parent.
function getChecksIndicatorAnchor() {
const candidates = [
'[data-testid="issue-viewer-issue-container"] [data-testid="pr-timeline"]',
".js-discussion",
".pull-discussion-timeline",
];
for (const sel of candidates) {
const el = document.querySelector(sel);
if (el && el.parentElement) return el;
}
return null;
}
function scrollToChecksBox() {
const box = /** @type {HTMLElement | null} */ (findChecksBox());
if (!box) return;
box.scrollIntoView({ behavior: "smooth", block: "center" });
box.style.outline = "2px solid #1f6feb";
box.style.borderRadius = "6px";
setTimeout(() => {
box.style.outline = "";
}, 1500);
}
function injectOrUpdateChecksIndicator() {
const existing = document.getElementById(CHECKS_STATUS_ID);
const cfg = getCurrentPageConfig();
if (!cfg || cfg.name !== "conversation") {
if (existing) existing.remove();
return;
}
const anchor = getChecksIndicatorAnchor();
if (!findChecksBox() || !anchor || !anchor.parentElement) {
if (existing) existing.remove();
return;
}
const state = deriveChecksState(getCheckLabels());
const indicator = /** @type {HTMLButtonElement} */ (
existing || document.createElement("button")
);
if (!existing) {
indicator.id = CHECKS_STATUS_ID;
indicator.type = "button";
indicator.style.cssText = [
"display: inline-block",
"margin: 8px 0 12px 0",
"padding: 6px 10px",
"background: var(--bgColor-muted, #f6f8fa)",
"border-radius: 6px",
"font: 12px -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
"cursor: pointer",
].join(";");
indicator.title = "Click to jump to the PR status checks";
indicator.addEventListener("click", scrollToChecksBox);
}
// Only write to the DOM when the status actually changed; otherwise the
// body MutationObserver that calls us would see our own text/style
// mutations and reschedule forever.
if (indicator.dataset.prrcState !== state.key) {
indicator.dataset.prrcState = state.key;
indicator.textContent = state.label;
indicator.style.border = `1px solid ${state.color}`;
indicator.style.color = state.color;
// The visible label leans on color and a glyph (✓/✗/•); spell the
// status out for assistive tech.
indicator.setAttribute("aria-label", `PR status checks: ${state.key}. Jump to checks`);
}
if (indicator !== anchor.previousElementSibling) {
anchor.parentElement.insertBefore(indicator, anchor);
}
}
/** @param {HTMLElement} btn */
function updateButtonLabel(btn) {
const next = currentOrder === ORDER.NEWEST ? ORDER.OLDEST : ORDER.NEWEST;
btn.textContent = currentOrder === ORDER.NEWEST ? "↓ Newest first" : "↑ Oldest first";
btn.title = `Click to switch to ${next} first`;
// The arrow glyph is decorative; give assistive tech a plain-text label.
btn.setAttribute("aria-label", `Comment order: ${currentOrder} first. Switch to ${next} first`);
}
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== "local" || !changes[STORAGE_KEY]) return;
currentOrder = normalizeOrder(changes[STORAGE_KEY].newValue);
const btn = document.getElementById(BUTTON_ID);
if (btn) updateButtonLabel(btn);
applyOrder(currentOrder);
});
// React to GitHub's soft-navigation by re-applying our work when a
// fresh target container appears (the old element gets detached and
// the new one isn't sorted yet).
let rebindScheduled = false;
function scheduleRebindIfNeeded() {
if (rebindScheduled) return;
rebindScheduled = true;
queueMicrotask(() => {
rebindScheduled = false;
// Off a supported page — tear down everything we put up.
if (!onSupportedPage()) {
const btn = document.getElementById(BUTTON_ID);
if (btn) btn.remove();
const checks = document.getElementById(CHECKS_STATUS_ID);
if (checks) checks.remove();
disconnectObservers();
activeTargets = [];
return;
}
if (!document.getElementById(BUTTON_ID)) {
injectToggleButton();
}
injectOrUpdateChecksIndicator();
const cfg = getCurrentPageConfig();
if (!cfg) return;
const freshTargets = cfg.getTargets();
if (!freshTargets.length) return;
// Compare the new target set to the active one by element identity.
// If every element matches an active target's element, nothing to do.
const activeEls = new Set(activeTargets.map((t) => t.el));
const sameSet =
freshTargets.length === activeTargets.length &&
freshTargets.every((t) => activeEls.has(t.el));
if (sameSet) return;
activeTargets = [];
applyOrder(currentOrder);
startObservers();
});
}
function startBodyWatcher() {
const bodyObs = new MutationObserver(scheduleRebindIfNeeded);
// aria-label is watched because GitHub updates a check row's label in
// place (e.g. "in progress" -> "successful") without any structural
// mutation; without it the checks indicator would go stale until some
// unrelated DOM churn happened to fire the observer.
bodyObs.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["aria-label"],
});
}
async function init() {
const stored = await chrome.storage.local.get([STORAGE_KEY, RESET_VERSION_KEY]);
if (stored[RESET_VERSION_KEY] !== CURRENT_RESET_VERSION) {
await chrome.storage.local.remove(STORAGE_KEY);
await chrome.storage.local.set({ [RESET_VERSION_KEY]: CURRENT_RESET_VERSION });
currentOrder = ORDER.NEWEST;
} else {
currentOrder = normalizeOrder(stored[STORAGE_KEY]);
}
startBodyWatcher();
if (onSupportedPage()) {
injectToggleButton();
injectOrUpdateChecksIndicator();
}
scheduleRebindIfNeeded();
}
init().catch((err) => {
// A storage failure here leaves the extension inert on this page; make
// the cause visible instead of an unhandled rejection.
console.error("[pr-reverse-comments] initialization failed:", err);
});
// Fast paths for the soft-nav events GitHub does fire — avoid waiting
// for the next DOM mutation tick. The body watcher above is the real
// safety net; these just shave latency when the events arrive.
["turbo:render", "turbo:load", "pjax:end", "soft-nav:end"].forEach((evt) => {
document.addEventListener(evt, () => {
activeTargets = [];
scheduleRebindIfNeeded();
});
});
})();