-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
443 lines (407 loc) · 13.8 KB
/
content.js
File metadata and controls
443 lines (407 loc) · 13.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
(() => {
const STORAGE_KEY = 'cgpt-sidebar-mode';
const FORMAT_KEY = 'cgpt-sidebar-date-format';
const CACHE_KEY = 'cgpt-date-cache';
const CACHE_VERSION = 2;
const PLACEHOLDER_TEXT = '••••••••';
const BLUR_CLASS = 'cgpt-sidebar-blur';
const ID_RE = /\/c\/([0-9a-fA-F-]+)/;
// Modes: 'fake' | 'date' | 'placeholder' | 'blur' | 'hide' | 'off'
// Formats: 'plain' | 'slash' | 'short' | 'cn' | 'weekday' | 'relative'
// | 'datetime' | 'datetime_short' | 'datetime_cn'
const ALL_FORMATS = [
'plain', 'slash', 'short', 'cn', 'weekday', 'relative',
'datetime', 'datetime_short', 'datetime_cn',
];
const DEFAULT_MODE = 'fake';
const SIDEBAR_SELECTOR = 'a[href^="/c/"]';
let mode = DEFAULT_MODE;
let dateFormat = 'plain';
let accessToken = null;
let fetching = false;
let scanScheduled = false;
const dateMap = new Map();
const titleNodeCache = new WeakMap();
function parseTs(v) {
if (v == null) return null;
if (typeof v === 'number' && isFinite(v)) {
const ms = v < 1e12 ? v * 1000 : v;
const d = new Date(ms);
return isNaN(d.getTime()) ? null : d;
}
if (typeof v === 'string') {
const iso = new Date(v);
if (!isNaN(iso.getTime())) return iso;
const n = Number(v);
if (isFinite(n)) {
const ms = n < 1e12 ? n * 1000 : n;
const d = new Date(ms);
return isNaN(d.getTime()) ? null : d;
}
}
return null;
}
function pad2(n) { return String(n).padStart(2, '0'); }
function formatYMD(d) {
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
}
function extractDateAndTs(item) {
const candidates = [
item.update_time, item.create_time,
item.updated_at, item.created_at,
item.last_active_time,
];
for (const c of candidates) {
const d = parseTs(c);
if (d) return { date: formatYMD(d), ts: d.getTime() };
}
return null;
}
function formatEntry(entry, fmt) {
if (!entry) return '';
const { date, ts } = entry;
const [y, m, d] = date.split('-');
switch (fmt) {
case 'slash': return `${y}/${m}/${d}`;
case 'short': return `${m}-${d}`;
case 'cn': return `${parseInt(m, 10)}月${parseInt(d, 10)}日`;
case 'weekday': {
const wd = window.__veilbar.t('weekday' + new Date(ts).getDay());
return `${wd} ${m}-${d}`;
}
case 'relative': {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const that = new Date(ts);
const thatDay = new Date(that.getFullYear(), that.getMonth(), that.getDate());
const diff = Math.round((today - thatDay) / 86400000);
if (diff <= 0) return window.__veilbar.t('today');
if (diff === 1) return window.__veilbar.t('yesterday');
if (diff < 7) return window.__veilbar.t('daysAgo', String(diff));
if (diff < 30) return window.__veilbar.t('weeksAgo', String(Math.floor(diff / 7)));
return date;
}
case 'datetime': {
const dt = new Date(ts);
return `${date} ${pad2(dt.getHours())}:${pad2(dt.getMinutes())}`;
}
case 'datetime_short': {
const dt = new Date(ts);
return `${m}-${d} ${pad2(dt.getHours())}:${pad2(dt.getMinutes())}`;
}
case 'datetime_cn': {
const dt = new Date(ts);
return `${parseInt(m,10)}月${parseInt(d,10)}日 ${pad2(dt.getHours())}:${pad2(dt.getMinutes())}`;
}
default: return date;
}
}
async function loadCachedMap() {
try {
const r = await chrome.storage.local.get(CACHE_KEY);
const c = r[CACHE_KEY];
if (!c || c.v !== CACHE_VERSION || !Array.isArray(c.entries)) return;
for (const [k, v] of c.entries) {
if (!dateMap.has(k) && v && typeof v === 'object') dateMap.set(k, v);
}
} catch {}
}
async function saveCachedMap() {
try {
const entries = Array.from(dateMap.entries());
await chrome.storage.local.set({
[CACHE_KEY]: { v: CACHE_VERSION, ts: Date.now(), entries },
});
} catch {}
}
async function getAccessToken() {
if (accessToken) return accessToken;
try {
const r = await fetch('/api/auth/session', { credentials: 'include' });
if (!r.ok) return null;
const j = await r.json();
accessToken = j.accessToken || j.access_token || null;
return accessToken;
} catch {
return null;
}
}
async function fetchConversations() {
if (fetching) return;
fetching = true;
try {
const token = await getAccessToken();
if (!token) return;
const limit = 100;
let offset = 0;
const acc = [];
for (let page = 0; page < 10; page++) {
const url = `/backend-api/conversations?offset=${offset}&limit=${limit}&order=updated`;
const r = await fetch(url, {
headers: { Authorization: `Bearer ${token}` },
credentials: 'include',
});
if (!r.ok) break;
const j = await r.json();
const items = j.items || [];
if (items.length === 0) break;
for (const it of items) acc.push(it);
if (items.length < limit) break;
offset += limit;
}
const byDate = new Map();
for (const it of acc) {
const dt = extractDateAndTs(it);
if (!dt || !it.id) continue;
if (!byDate.has(dt.date)) byDate.set(dt.date, []);
byDate.get(dt.date).push({ id: it.id, ts: dt.ts });
}
const newMap = new Map();
for (const [date, list] of byDate) {
list.sort((a, b) => b.ts - a.ts);
list.forEach((e, i) => {
newMap.set(e.id, { date, ts: e.ts, index: i, total: list.length });
});
}
dateMap.clear();
for (const [k, v] of newMap) dateMap.set(k, v);
saveCachedMap();
} catch {} finally {
fetching = false;
}
}
function findTitleNode(linkEl) {
const truncate = linkEl.querySelector(
'div.truncate, span.truncate, [class*="truncate"]'
);
if (truncate) {
const leaf = deepestTextLeaf(truncate);
if (leaf) return leaf;
return truncate;
}
const dirAuto = linkEl.querySelector('[dir="auto"]');
if (dirAuto) {
const leaf = deepestTextLeaf(dirAuto);
if (leaf) return leaf;
return dirAuto;
}
return deepestTextLeaf(linkEl);
}
function deepestTextLeaf(root) {
let best = null;
const all = root.querySelectorAll('*');
const candidates = all.length ? all : [root];
for (const el of candidates) {
if (el.children.length === 0) {
const t = (el.textContent || '').trim();
if (!t) continue;
if (!best || (el.textContent || '').length > (best.textContent || '').length) {
best = el;
}
}
}
return best;
}
// Per-link title leaf cache: skip the descendant walk on every scan, only
// re-find when the cached node has been detached or is no longer a clean
// text-only leaf (React may have wrapped its content in new elements).
function isCleanLeaf(el) {
const first = el.firstChild;
return !first || (first.nodeType === Node.TEXT_NODE && !first.nextSibling);
}
function getTitleNode(linkEl) {
const cached = titleNodeCache.get(linkEl);
if (cached && linkEl.contains(cached) && isCleanLeaf(cached)) return cached;
const found = findTitleNode(linkEl);
if (found) titleNodeCache.set(linkEl, found);
else titleNodeCache.delete(linkEl);
return found;
}
function isOurOutput(text, id) {
if (text === PLACEHOLDER_TEXT) return true;
const entry = dateMap.get(id);
if (entry) {
for (const fmt of ALL_FORMATS) {
if (formatEntry(entry, fmt) === text) return true;
}
}
if (window.__cgptFakeName && window.__cgptFakeName(id) === text) return true;
return false;
}
function toggleClass(el, cls, want) {
const has = el.classList.contains(cls);
if (want && !has) el.classList.add(cls);
else if (!want && has) el.classList.remove(cls);
}
// Only mutate clean text-only leaves. nodeValue keeps React's Fiber
// references intact; textContent would tear them out and crash React on
// its next commit with "removeChild ... not a child of this node". If we
// ever land on a non-leaf, skip silently — a follow-up mutation will
// route us back here once React has settled.
function setLeafText(node, text) {
const first = node.firstChild;
if (!first) {
node.textContent = text;
return;
}
if (first.nodeType === Node.TEXT_NODE && !first.nextSibling) {
if (first.nodeValue !== text) first.nodeValue = text;
}
}
function applyTo(linkEl) {
const href = linkEl.getAttribute('href') || '';
const m = href.match(ID_RE);
if (!m) return;
const id = m[1];
const titleNode = getTitleNode(linkEl);
if (!titleNode) return;
const current = titleNode.textContent || '';
if (!titleNode.dataset.cgptOrig && !isOurOutput(current, id)) {
titleNode.dataset.cgptOrig = current;
}
const orig = titleNode.dataset.cgptOrig || current;
toggleClass(titleNode, BLUR_CLASS, mode === 'blur');
let next;
if (mode === 'off' || mode === 'blur' || mode === 'hide') {
next = orig;
} else if (mode === 'placeholder') {
next = PLACEHOLDER_TEXT;
} else if (mode === 'fake') {
next = window.__cgptFakeName ? window.__cgptFakeName(id) : orig;
} else {
const entry = dateMap.get(id);
next = entry ? formatEntry(entry, dateFormat) : orig;
}
setLeafText(titleNode, next);
if (mode === 'hide') {
if (linkEl.hasAttribute('data-cgpt-applied')) {
linkEl.removeAttribute('data-cgpt-applied');
}
} else {
if (!linkEl.hasAttribute('data-cgpt-applied')) {
linkEl.setAttribute('data-cgpt-applied', '1');
}
}
}
function scan() {
const links = document.querySelectorAll(SIDEBAR_SELECTOR);
let unknownInDate = false;
for (const link of links) {
applyTo(link);
if (mode === 'date' && !unknownInDate) {
const m = (link.getAttribute('href') || '').match(ID_RE);
if (m && !dateMap.has(m[1])) unknownInDate = true;
}
}
if (unknownInDate && !fetching) {
fetchConversations().then(scan);
}
}
function scheduleScan() {
if (scanScheduled) return;
scanScheduled = true;
queueMicrotask(() => {
scanScheduled = false;
scan();
});
}
function restoreStaleProjectMods() {
const projectLinks = document.querySelectorAll('a[href*="/g/g-p-"][href*="/c/"]');
for (const a of projectLinks) {
a.removeAttribute('data-cgpt-applied');
const targets = a.querySelectorAll('[data-cgpt-orig]');
for (const t of targets) {
const orig = t.dataset.cgptOrig;
if (orig) setLeafText(t, orig);
delete t.dataset.cgptOrig;
}
}
}
// Decide whether a DOM mutation could affect sidebar conversation links.
// Skips the overwhelming majority of mutations from chat streaming, hover
// animations, and tooltip toggles, so scan() runs only when there is
// actual work to do.
function isRelevantMutation(m) {
if (m.type !== 'childList') return false;
const target = m.target;
const targetInLink = target && target.closest && target.closest(SIDEBAR_SELECTOR);
for (const node of m.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
if (node.matches && node.matches(SIDEBAR_SELECTOR)) return true;
if (node.querySelector && node.querySelector(SIDEBAR_SELECTOR)) return true;
} else if (node.nodeType === Node.TEXT_NODE && targetInLink) {
return true;
}
}
for (const node of m.removedNodes) {
if (node.nodeType === Node.TEXT_NODE && targetInLink) return true;
}
return false;
}
let observer = null;
function startObserver() {
if (observer) return;
// Observe document.body so we catch sidebar mutations regardless of
// where ChatGPT decides to mount them (lazy-loaded entries appear to
// land outside the obvious <nav> container). The filter does the actual
// narrowing in JS: only mutations that touch a sidebar link element or
// a text node inside one schedule a scan.
observer = new MutationObserver((mutations) => {
for (const m of mutations) {
if (isRelevantMutation(m)) {
scheduleScan();
return;
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
function setHtmlMode(m) {
document.documentElement.dataset.cgptMode = m;
}
async function init() {
try {
if (window.__veilbar) await window.__veilbar.init();
} catch {}
try {
const stored = await chrome.storage.sync.get([STORAGE_KEY, FORMAT_KEY]);
mode = stored[STORAGE_KEY] || DEFAULT_MODE;
dateFormat = stored[FORMAT_KEY] || 'plain';
} catch {
mode = DEFAULT_MODE;
dateFormat = 'plain';
}
setHtmlMode(mode);
restoreStaleProjectMods();
if (mode === 'date') {
await loadCachedMap();
scan();
fetchConversations().then(scan);
} else {
scan();
}
startObserver();
// When the user switches language from the popup, re-scan so the new
// fake names / relative dates take effect without a page reload.
if (window.__veilbar) window.__veilbar.onChange(() => scan());
}
chrome.storage.onChanged.addListener(async (changes, area) => {
if (area !== 'sync') return;
if (changes[STORAGE_KEY]) {
mode = changes[STORAGE_KEY].newValue || DEFAULT_MODE;
setHtmlMode(mode);
if (mode === 'date' && dateMap.size === 0) {
await loadCachedMap();
scan();
fetchConversations().then(scan);
return;
}
scan();
}
if (changes[FORMAT_KEY]) {
dateFormat = changes[FORMAT_KEY].newValue || 'plain';
scan();
}
});
init();
})();