-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
351 lines (309 loc) · 9.98 KB
/
Copy pathcontent.js
File metadata and controls
351 lines (309 loc) · 9.98 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
/**
* ChatGPT Web Accelerator - Content Script
*
* Optimizes page rendering performance in long ChatGPT conversations
* using content-visibility and DOM height-locking techniques.
*/
// Configuration State
let config = {
enabled: true,
mode: 'js', // 'js' | 'css' | 'unload'
buffer: 1.5, // viewports buffer size
gpuAcceleration: true,
debugMode: false,
customSelector: '[data-testid^="conversation-turn-"]'
};
// Internal State
let scrollContainer = null;
let intersectionObserver = null;
let mutationObserver = null;
let observedElements = new Set();
const nodeCountCache = new WeakMap();
// Logger helper
function log(...args) {
console.log('[ChatGPT Accelerator]', ...args);
}
// 1. Initial configuration load
chrome.storage.local.get(Object.keys(config), (items) => {
config = { ...config, ...items };
// Migration: If the user has the old selector stored, auto-migrate to the new, more robust selector
if (config.customSelector === 'article[data-testid^="conversation-turn-"], article') {
config.customSelector = '[data-testid^="conversation-turn-"]';
}
log('Config loaded:', config);
init();
});
// Listen for updates from Popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'GET_STATS') {
sendResponse(getStats());
} else if (request.type === 'UPDATE_CONFIG') {
config = { ...config, ...request.config };
log('Config updated:', config);
applyConfig();
sendResponse({ success: true });
} else if (request.type === 'PING') {
sendResponse({ success: true });
}
return true;
});
// 2. Initialize Virtualization
function init() {
applyConfig();
// Setup MutationObserver to watch for dynamic content loading
if (mutationObserver) mutationObserver.disconnect();
mutationObserver = new MutationObserver(handleMutations);
mutationObserver.observe(document.body, {
childList: true,
subtree: true
});
// Initial scan
scanAndVirtualize();
}
// 3. Apply active configuration settings
function applyConfig() {
// Apply document-level debug class
if (config.enabled && config.debugMode) {
document.documentElement.classList.add('chatgpt-accelerator-debug');
} else {
document.documentElement.classList.remove('chatgpt-accelerator-debug');
}
// Clear existing CSS mode style tags
removeStyleTag('chatgpt-acc-css-style');
removeStyleTag('chatgpt-acc-gpu-style');
// Apply GPU acceleration style if enabled
if (config.enabled && config.gpuAcceleration) {
const style = document.createElement('style');
style.id = 'chatgpt-acc-gpu-style';
style.textContent = `
${config.customSelector} {
will-change: transform, opacity;
}
`;
document.head.appendChild(style);
}
// Clear JS virtualization states if disabled or changing modes
if (!config.enabled || config.mode !== 'js') {
clearJSVirtualization();
}
if (!config.enabled || config.mode !== 'unload') {
clearUnloadVirtualization();
}
if (!config.enabled) {
log('Virtualization disabled.');
return;
}
// Set up selected mode
if (config.mode === 'css') {
applyCssMode();
} else if (config.mode === 'js') {
setupIntersectionObserver();
scanAndVirtualize();
} else if (config.mode === 'unload') {
setupIntersectionObserver();
scanAndVirtualize();
}
}
// Remove style tag helper
function removeStyleTag(id) {
const el = document.getElementById(id);
if (el) el.remove();
}
// 4. CSS Mode implementation (content-visibility: auto)
function applyCssMode() {
log('Applying Pure CSS Mode...');
const style = document.createElement('style');
style.id = 'chatgpt-acc-css-style';
style.textContent = `
${config.customSelector} {
content-visibility: auto !important;
contain-intrinsic-size: auto 150px !important;
}
`;
document.head.appendChild(style);
}
// 5. JS Mode implementation (IntersectionObserver + content-visibility: hidden)
function setupIntersectionObserver() {
if (intersectionObserver) {
intersectionObserver.disconnect();
}
// Find current scroll container (for root margin context)
findScrollContainer();
// Create observer
const rootMarginValue = `${Math.round(config.buffer * 100)}% 0px ${Math.round(config.buffer * 100)}% 0px`;
log(`Setting up IntersectionObserver with rootMargin: ${rootMarginValue}`);
intersectionObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const element = entry.target;
if (entry.isIntersecting) {
// Visible (within buffer)
makeVisible(element);
} else {
// Offscreen (outside buffer)
makeHidden(element);
}
});
}, {
root: scrollContainer,
rootMargin: rootMarginValue
});
// Re-observe all already-scanned elements
observedElements.forEach(el => {
if (document.body.contains(el)) {
intersectionObserver.observe(el);
} else {
observedElements.delete(el);
}
});
}
function makeVisible(element) {
if (config.mode === 'js') {
element.style.removeProperty('contain-intrinsic-size');
element.classList.remove('chatgpt-accelerator-hidden');
} else if (config.mode === 'unload') {
element.classList.remove('chatgpt-accelerator-unloaded');
element.style.removeProperty('height');
element.style.removeProperty('overflow');
// Restore children display styles
Array.from(element.children).forEach(child => {
child.style.removeProperty('display');
});
}
}
function makeHidden(element) {
// Only optimize if we can measure a valid height (don't hide if height is 0)
const rect = element.getBoundingClientRect();
if (rect.height <= 0) return;
if (config.mode === 'js') {
element.style.setProperty('contain-intrinsic-size', `auto ${rect.height}px`);
element.classList.add('chatgpt-accelerator-hidden');
} else if (config.mode === 'unload') {
element.style.setProperty('height', `${rect.height}px`);
element.style.setProperty('overflow', 'hidden');
element.classList.add('chatgpt-accelerator-unloaded');
// Hide children to release browser memory/DOM rendering overhead
Array.from(element.children).forEach(child => {
child.style.setProperty('display', 'none', 'important');
});
}
}
// 6. Cleaners
function clearJSVirtualization() {
observedElements.forEach(el => {
el.style.removeProperty('contain-intrinsic-size');
el.classList.remove('chatgpt-accelerator-hidden');
});
}
function clearUnloadVirtualization() {
observedElements.forEach(el => {
el.classList.remove('chatgpt-accelerator-unloaded');
el.style.removeProperty('height');
el.style.removeProperty('overflow');
Array.from(el.children).forEach(child => {
child.style.removeProperty('display');
});
});
}
// 7. Dynamic Scroll Container and Message detection
function findScrollContainer() {
// Locate a known message row first
const match = document.querySelector(config.customSelector);
if (match) {
let parent = match.parentElement;
while (parent) {
const style = window.getComputedStyle(parent);
if (style.overflowY === 'auto' || style.overflowY === 'scroll') {
scrollContainer = parent;
return;
}
parent = parent.parentElement;
}
}
scrollContainer = null; // fallback to browser viewport
}
function scanAndVirtualize() {
if (!config.enabled || (config.mode !== 'js' && config.mode !== 'unload')) return;
const elements = document.querySelectorAll(config.customSelector);
let newElementsFound = false;
elements.forEach(el => {
if (!observedElements.has(el)) {
observedElements.add(el);
if (intersectionObserver) {
intersectionObserver.observe(el);
newElementsFound = true;
}
}
});
if (newElementsFound && !scrollContainer) {
// Scroll container might be available now
findScrollContainer();
if (scrollContainer && intersectionObserver) {
// Re-setup observer to bind to correct root
setupIntersectionObserver();
}
}
}
// Handle mutations
let mutationDebounceTimeout = null;
function handleMutations(mutations) {
let shouldScan = false;
for (let mutation of mutations) {
if (mutation.addedNodes.length > 0) {
shouldScan = true;
break;
}
// Also invalidate node count cache of mutated text blocks
if (mutation.type === 'characterData' || mutation.type === 'childList') {
let target = mutation.target;
while (target && target !== document.body) {
if (target.matches && target.matches(config.customSelector)) {
nodeCountCache.delete(target);
break;
}
target = target.parentElement;
}
}
}
if (shouldScan) {
// Debounce scan slightly to batch DOM updates
clearTimeout(mutationDebounceTimeout);
mutationDebounceTimeout = setTimeout(() => {
scanAndVirtualize();
}, 100);
}
}
// 8. Statistics Calculation
function getStats() {
const elements = Array.from(document.querySelectorAll(config.customSelector));
const totalMessages = elements.length;
let optimizedMessages = 0;
let totalNodes = 0;
let optimizedNodes = 0;
elements.forEach(el => {
// Count nodes (cached for performance)
let nodeCount = nodeCountCache.get(el);
if (nodeCount === undefined) {
nodeCount = el.querySelectorAll('*').length;
nodeCountCache.set(el, nodeCount);
}
totalNodes += nodeCount;
const isOptimized = el.classList.contains('chatgpt-accelerator-hidden') ||
el.classList.contains('chatgpt-accelerator-unloaded');
if (isOptimized) {
optimizedMessages++;
optimizedNodes += nodeCount;
}
});
// Calculate memory savings: roughly 1.5KB per DOM node (rendering memory structure overhead)
const memorySavedBytes = optimizedNodes * 1500;
return {
enabled: config.enabled,
mode: config.mode,
totalMessages,
optimizedMessages,
totalNodes,
optimizedNodes,
memorySavedMB: (memorySavedBytes / (1024 * 1024)).toFixed(1),
debugMode: config.debugMode
};
}