-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
503 lines (439 loc) · 25.2 KB
/
Copy pathcontent.js
File metadata and controls
503 lines (439 loc) · 25.2 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/* global chrome */
(() => {
const ext = typeof browser !== 'undefined' ? browser : chrome;
const BUTTON_TEXT = 'Dunk';
const LOG_PREFIX = '[Twitter Dunkr]';
let lastRetweetButton = null;
let lastTweetForMenu = null;
let isCapturing = false;
let featureEnabled = true;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function storageGet(defaults) {
if (!ext.storage || !ext.storage.local) return Promise.resolve(defaults);
if (typeof browser !== 'undefined') return ext.storage.local.get(defaults);
return new Promise((resolve) => {
ext.storage.local.get(defaults, (result) => resolve(result || defaults));
});
}
function removeCaptureMenuItems() {
document.querySelectorAll('[data-x-capture-quote="true"]').forEach((item) => item.remove());
}
async function loadFeatureEnabled() {
const result = await storageGet({ captureEnabled: true });
featureEnabled = result.captureEnabled !== false;
if (!featureEnabled) removeCaptureMenuItems();
}
function watchFeatureToggle() {
if (!ext.storage || !ext.storage.onChanged) return;
ext.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== 'local' || !changes.captureEnabled) return;
featureEnabled = changes.captureEnabled.newValue !== false;
if (!featureEnabled) removeCaptureMenuItems();
else {
const menu = findOpenMenu();
if (menu) addCaptureMenuItem(menu);
}
});
}
function sendMessage(message) {
if (typeof browser !== 'undefined') return ext.runtime.sendMessage(message);
return new Promise((resolve, reject) => {
ext.runtime.sendMessage(message, (response) => {
const err = chrome.runtime.lastError;
if (err) reject(new Error(err.message));
else resolve(response);
});
});
}
function notify(message, isError = false) {
let el = document.getElementById('x-capture-quote-toast');
if (!el) {
el = document.createElement('div');
el.id = 'x-capture-quote-toast';
Object.assign(el.style, {
position: 'fixed',
zIndex: '2147483647',
right: '18px',
bottom: '18px',
maxWidth: '340px',
padding: '12px 14px',
borderRadius: '12px',
color: 'white',
background: 'rgba(15, 20, 25, 0.94)',
boxShadow: '0 8px 28px rgba(0,0,0,.25)',
font: '14px/1.35 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
whiteSpace: 'pre-wrap'
});
document.documentElement.appendChild(el);
}
el.textContent = message;
el.style.background = isError ? 'rgba(180, 30, 45, .96)' : 'rgba(15, 20, 25, .94)';
window.setTimeout(() => el.remove(), 4500);
}
function cleanText(text) {
return (text || '').replace(/\s+/g, ' ').trim();
}
function closestTweetFromElement(el) {
return el && el.closest && el.closest('article[data-testid="tweet"]');
}
function findOpenMenu() {
return document.querySelector('[role="menu"]');
}
function findTweetForCurrentMenu() {
const active = document.activeElement;
return lastTweetForMenu || closestTweetFromElement(active) || closestTweetFromElement(lastRetweetButton);
}
function isRetweetButton(el) {
return !!(el && el.closest && el.closest('[data-testid="retweet"]'));
}
function iconSvg() {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', '5.0 13.06 240.0 223.88');
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('width', '20');
svg.setAttribute('height', '20');
svg.setAttribute('fill', 'currentColor');
svg.setAttribute('stroke', 'currentColor');
// svg.setAttribute('stroke-width', '1.8');
// svg.setAttribute('stroke-linecap', 'round');
// svg.setAttribute('stroke-linejoin', 'round');
svg.innerHTML = [
'<g/>',
'<path d="M135.377,28.32c-0.092-0.488-0.155-0.993-0.189-1.504c-0.493-7.083,4.839-13.225,11.922-13.724 c7.089-0.494,13.23,4.845,13.724,11.928c0.494,7.083-4.839,13.225-11.921,13.724c-0.448,0.034-0.891,0.04-1.326,0.023 c-0.287,0.074-0.459,0.109-0.706,0.327c-0.729,1.136,1.854,0.924,0.098,5.889c0,0-0.012,0.545-0.207,1.09 c-0.138,1.906-0.872,7.554-0.976,10.562c0.373,0.436,0.477,0.648,0.437,1.705c-0.167,1.429-0.494,4.931-1.022,7.175 c-0.447,1.923-1.233,2.29-1.865,2.761c-0.89,3.984-1.125,7.284-3.409,12.123c-0.207,3.668-0.465,4.667-1.234,6.458 c-0.086,5.401,0.287,6.205-3.357,14.757c-0.941,4-0.046,6.767,0.947,10.923c1.016,4.271,3.834,6.056,4.253,10.43 c0.987,10.3,0.74,17.314-1.47,25.39l1.929,4.569c2.394,1.097,8.334,4.099,5.04,8.851c4.638,2.439,11.646,5.028,17.426,9.971 c2.325,1.935,4.781,4.047,6.985,6.526c4.196,0.654,3.748,0.987,6.859,2.898c9.144,5.607,23.809,16.731,32.31,24.606 c1.464,0.855,2.061,1.47,3.243,2.09c0.184,0.355,0.235,0.436,0.195,0.533c-0.407,1.028-0.391,1.057-0.758,1.877 c0.459,0.506,1.314,0.981,1.825,1.424c0.477,0.149,0.477-0.08,1.298-0.281c1.067,0.999,2.388,1.803,2.863,1.757 c1.447-0.368,1.2-0.069,2.423-1.436c0.441-0.453,1.177,0.006,1.177,0.006c0.459-0.539,1.446-1.613,2.761-2.388 c1.05-0.62,3.054-0.688,3.054-0.688c0.671,0.006,0.545,0.694,0.487,0.918c-0.757,0.391-2.364,0.821-3.266,1.486 c-1.963,2.032-3.501,4.771-3.501,4.771c3.954-0.54,6.383,0.441,9.677,0.063c1.797-0.103,3.123,0.012,5.011-1.354 c0,0,1.814-1.291,3.438-1.975c1.579-0.688,3.077-0.321,4.466,0.689c0.981,1.107,1.572,1.113,0.08,2.675 c-0.539,0.608-1.32,1.285-2.313,2.267c-1.745,1.723-4.093,4.023-6.526,5.924c-2.463,1.923-5.258,3.65-7.003,4.442 c-4.402,3.163-3.363,2.336-6.824,5.471c-0.437,0.39-1.596,1.09-2.158,1.463c-1.366,0.896-1.791,0.149-2.681-1.492 c0,0-0.408-0.614-1.079-1.923c-0.735-1.429-1.286-3.064-1.063-3.036c-0.82-0.104-4.512-4.432-4.522-5.361 c-0.781-0.178-4.11-3.403-4.23-4.018l-2.95-2.365c-3.375,0.7-4.15-1.395-13.064-7.72c-1.016-0.018-2.588-0.568-4.839-2.238 c-4.023-3.221-13.672-10.51-15.308-11.343c-1.757-0.895-3.857-1.738-5.144-2.801c-1.928-0.355-2.984-0.557-3.948-0.826 c-0.987-0.27-1.883-0.62-4.38-0.953c-4.063-0.505-8.277-2.187-12.289-4.195c-1.899-0.901-3.553-1.36-5.188-2.062 c-3.668-1.549-6.813-2.944-9.25-3.507c-0.93-0.092-5.35-1.418-7.668-2.772c-0.804-0.413-1.269-0.809-1.797-0.93 c-1.217-0.281-1.998,0.201-2.548,0.385c-2.973,1.55-5.757,2.887-8.329,4.271c-2.394,1.28-4.598,2.611-6.934,3.955 c-2.107,1.217-4.541,2.364-7.043,3.559c0,0-7.135,3.576-11.032,4.965c-3.381,2.761-10.292,7.536-14.51,9.901 c-2.089,0.993-6.147,3.564-8.019,4.139c-1.068,0.86-4.873,3.575-7.852,5.814c-2.302,1.722-4.041,3.174-4.041,3.174 c-1.337,1.199-1.246,1.768-3.788,0.688c-0.706,0.58-1.251,0.941-1.705,1.274c-1.836,1.332-1.992,1.011-2.663,0.976 c-1.28,1.108-1.441,0.534-2.56,1.809c-0.735,1.137,0.017,0.866-1.533,1.418c-0.327,0.126-0.482,0.521-0.734,0.74 c-1.246,1.027-1.251,3.926-4.236,4.133c-1.728,1.233-1.286,2.721-2.606,2.657c0.081,1.28-2.336,3.146-2.772,3.14 c-3.806,1.314-4.07-1.486-8.639,0.603c-0.591,0.27-1.458,1.017-2.6,1.234c-2.009,0.379-4.437-0.018-5.918-1.165 c-2.331-1.797-4.477-5.264-4.477-5.264c-0.741-1.751-0.31-2.858,2.003-4.512c0.964-0.614,1.142-1.073,2.761-1.183 c0.804-0.304,0.585,0.161,2.021-0.355c0.832-0.299,0.832-0.086,2.508-0.229c0.384-0.259,0.924-0.351,1.647-0.586 c1.326-0.436,2.618-0.924,2.618-0.924s0.338-0.339,1.613-0.218c1.079-0.442,2.187-1.097,2.755-1.298 c-0.144-1.71,0.04-1.63,0.832-2.318c0.987-0.85,1.165-0.712,1.9-0.184c0.31-0.179,0.459-0.241,0.425-0.5 c-0.121-0.89-0.884-1.309-0.654-3.271c-0.339-0.786-0.838-1.756-0.729-2.342c0.161-0.632,0.316-0.936,0.7-1.137 c0.408-0.218,0.54,0.075,0.758,0.321c0.39,0.454,0.706,1.797,0.706,1.797c0.138,1.516,0.608,3.479,2.106,2.371 c0.884-0.896,1.056-3.283,2.858-2.772l1.286,1.119c1.091-1.027,1.143-1.027,1.797-1.44c0,0-1.022-1.033-0.126-1.837 c0.614-0.546,1.354-0.936,2.669-2.394c3.61-3.989,5.464-5.752,9.368-8.966c7.789-6.406,16.651-10.9,22.282-13.133 c1.836-2.331,3.622-3.88,7.697-4.271c4.844-8.18,14.12-15.486,16.25-16.651c1.733-3.14,2.485-2.807,4.752-3.438 c1.796-1.44,2.204-1.44,3.008-2.944c0.781-3.105-1.802-11.399,4.792-11.818c1.401-1.98,1.051-1.504,2.612-3.375 c-1.056-2.606-1.492-4.787-1.779-6.664c-0.052-0.218-2.617-2.026-1.889-4.386c-1.09-1.297-3.128-4.324-3.765-5.742 c-0.292,0.006-0.534-0.104-0.855-0.149c-0.333-0.052-0.747-0.034-1.211-0.074c-1.027,2.651-2.146,2.847-3.972,3.432 c-3.26,6.948-4.408,9.888-13.632,15.633c-3.662,4.099-4.833,8.667-4.816,8.599c-0.631,1.354-0.408,3.249-0.075,4.265 c-0.482,1.504-0.356,1.653-0.356,1.653c0.201,0.568,0.724,1.32,1.366,1.48c1.108,0.293,2.216,0.247,2.152,1.481 c-0.149,1.544-2.175,1.291-3.134,1.119c-3.691-0.586-2.525-2.991-4.885-2.188c-1.808,1.183-2.485,4.673-5.436,4.219 c-0.39-0.258-0.27-1.021-0.006-1.572c0.414-0.861,1.148-1.573,0.712-1.895c-1.917,0.603-5.763,1.877-5.763,1.877 c-1.808,0.494-3.789-0.407-2.009-1.596c0.827-0.321,2.009-0.723,3.467-1.658c0,0,0.751-1.022-0.689-0.511 c-1.573,0.563-3.892,0.912-5.556,0.729c0,0-3.45-0.453-3.892-0.724c-0.448-0.27-0.855-1.337,0.224-1.331 c1.366,0.012,4.787-0.391,7.439-1.097c1.28-0.499,3.714-1.939,5.08-2.617c0,0,1.481-2.158,2.296-2.583 c1.36-1.567,2.508-2.491,3.713-4.093c1.177-2.428,2.394-6.273,6.291-12.226c1.802-2.744,4.041-5.94,6.859-8.797 c0,0,0.729-4.574,4.397-7.829c0.81-1.906,2.038-4.15,3.249-6.228c0.471-0.798,0.918-1.492,1.366-2.25 c1.137-1.785,2.331-5.108,6.762-5.631c0,0,1.894-1.4,2.623-2.394c1.137-0.97,0.878-2.479,1.802-3.542 c-1.412-1.377-5.022-3.966-5.373-7.565c-0.373-3.817,0.987-6.957,3.295-9.281c2.56-2.56,5.258-3.84,8.535-3.645 c4.092,0.608,4.867,1.963,6.17,3.306c1.251,1.274,1.716,0.454,2.244,1.946c3.433,0.913,3.243,0.511,3.214,3.037 c0.528,0.711,1.412,1.372,1.4,2.847c1.154-2.394,1.383-2.835,4.466-5.47c0.729-2.141,1.223-4.247,1.865-6.388 c0.6-1.98,1.347-4.018,1.926-5.551c-0.614-4.328,0.648-5.045,2.33-8.839c-0.298-0.522-0.234-0.671-0.108-1.527 c0.654-2.508,1.676-5.826,2.284-7.99c0,0,0.201-0.861,1.091-0.924c0.769-2.738,1.923-7.835,2.118-8.874 c0.792-2.864,0.281-3.783-0.327-5.396c-0.195-0.528-0.104-1.28-0.442-1.866c-0.958-1.67-1.991-3.84-2.691-5.39 c-0.454-0.987-1.172-4.707-1.172-4.707C134.843,26.42,135.377,28.32,135.377,28.32"/>',
].join('');
return svg;
}
function replaceMenuLabelText(label, text) {
// Keep X's cloned typography/classes intact. Replacing the wrong parent node
// strips the nested span structure and makes the text look unlike Repost/Quote.
const walker = document.createTreeWalker(label, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
if (cleanText(node.nodeValue).toLowerCase() === 'quote') {
node.nodeValue = text;
return;
}
}
label.textContent = text;
}
function addCaptureMenuItem(menu) {
if (!featureEnabled) { removeCaptureMenuItems(); return; }
if (!menu || menu.querySelector('[data-x-capture-quote="true"]')) return;
const quoteItem = Array.from(menu.querySelectorAll('[role="menuitem"]')).find((item) => /quote/i.test(item.textContent || ''));
if (!quoteItem) return;
const item = quoteItem.cloneNode(true);
item.setAttribute('data-x-capture-quote', 'true');
item.setAttribute('tabindex', '0');
item.querySelectorAll('svg').forEach((svg) => {
const replacement = iconSvg();
// Do not preserve X's icon classes here; some menu icon classes carry
// accent colors. Let the Dunk icon inherit the menu text color instead.
replacement.style.setProperty('color', 'inherit', 'important');
replacement.style.setProperty('fill', 'currentcolor', 'important');
replacement.style.setProperty('stroke', 'currentColor', 'important');
replacement.querySelectorAll('path, ellipse').forEach((shape) => {
shape.style.setProperty('fill', 'currentcolor', 'important');
shape.style.setProperty('stroke', 'currentColor', 'important');
});
svg.replaceWith(replacement);
});
const label = Array.from(item.querySelectorAll('span')).find((node) => cleanText(node.textContent).toLowerCase() === 'quote')
|| Array.from(item.querySelectorAll('div')).find((node) => cleanText(node.textContent).toLowerCase() === 'quote')
|| item;
replaceMenuLabelText(label, BUTTON_TEXT);
const menuColor = getComputedStyle(label).color || getComputedStyle(item).color || 'inherit';
item.style.setProperty('color', menuColor, 'important');
item.querySelectorAll('svg, svg *, div, span').forEach((node) => {
if (node.tagName && node.tagName.toLowerCase() === 'svg') {
node.style.setProperty('color', menuColor, 'important');
node.style.setProperty('fill', 'currentcolor', 'important');
node.style.setProperty('stroke', 'currentColor', 'important');
}
if (node.closest && node.closest('svg')) {
node.style.setProperty('fill', 'currentcolor', 'important');
node.style.setProperty('stroke', 'currentColor', 'important');
}
});
item.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
captureFromMenu().catch((error) => {
console.error(LOG_PREFIX, error);
notify(error.message || 'Dunk failed.', true);
});
}, true);
quoteItem.insertAdjacentElement('afterend', item);
}
function watchMenus() {
document.addEventListener('pointerdown', (event) => {
const target = event.target;
if (isRetweetButton(target)) {
lastRetweetButton = target.closest('[data-testid="retweet"]');
lastTweetForMenu = closestTweetFromElement(target);
}
}, true);
document.addEventListener('click', (event) => {
const target = event.target;
if (isRetweetButton(target)) {
lastRetweetButton = target.closest('[data-testid="retweet"]');
lastTweetForMenu = closestTweetFromElement(target);
}
}, true);
const observer = new MutationObserver(() => {
const menu = findOpenMenu();
if (menu) addCaptureMenuItem(menu);
});
observer.observe(document.documentElement, { childList: true, subtree: true });
}
async function closeOrHideOpenMenus() {
// X renders menus in a portal, so a menu opened above a tweet can overlap the
// tweet in the visible-tab screenshot. Hide immediately, then also send Escape
// so X cleans up its own menu state.
const menus = Array.from(document.querySelectorAll('[role="menu"]'));
menus.forEach((menu) => {
menu.setAttribute('data-x-capture-hidden-menu', 'true');
menu.style.setProperty('visibility', 'hidden', 'important');
menu.style.setProperty('pointer-events', 'none', 'important');
});
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
await sleep(250);
}
async function captureFromMenu() {
if (isCapturing) return;
isCapturing = true;
try {
const tweet = findTweetForCurrentMenu();
if (!tweet) throw new Error('Could not find the tweet connected to this repost menu.');
await closeOrHideOpenMenus();
const screenshotDataUrl = await captureTweetImage(tweet);
await openComposerAndAttach(screenshotDataUrl);
notify('Captured tweet screenshot and opened a new post.');
} finally {
isCapturing = false;
}
}
async function captureTweetImage(tweet) {
await scrollTweetIntoCapturePosition(tweet);
await sleep(350);
const rect = tweet.getBoundingClientRect();
const crop = getTweetCropRect(tweet, rect);
const response = await sendMessage({ type: 'X_CAPTURE_VISIBLE_TAB' });
if (!response || !response.ok) throw new Error(response && response.error ? response.error : 'Browser screenshot failed.');
return cropDataUrl(response.dataUrl, crop);
}
async function scrollTweetIntoCapturePosition(tweet) {
const rect = tweet.getBoundingClientRect();
const maxHeight = Math.min(rect.height, rect.width * 2);
// Leave room for X's sticky top banners/nav so the top of the tweet is not
// covered in the visible-tab screenshot.
const topOffset = 75;
const targetY = window.scrollY + rect.top - topOffset;
if (rect.top < topOffset - 8 || rect.top > topOffset + 20 || maxHeight > window.innerHeight - topOffset - 16) {
window.scrollTo({ top: Math.max(0, targetY), behavior: 'instant' });
await sleep(120);
}
}
function getTweetCropRect(tweet, rect) {
const dpr = window.devicePixelRatio || 1;
const top = Math.max(0, rect.top);
const viewportCssHeight = Math.max(1, window.innerHeight - top - 4);
const twoWidthCap = rect.width * 2;
const uncroppedCssHeight = Math.max(1, Math.min(rect.height, viewportCssHeight));
const hitTwoWidthCap = uncroppedCssHeight > twoWidthCap;
let cssHeight;
if (hitTwoWidthCap) {
// For very tall tweets, the 2x-width cap already cuts off the below-tweet
// chrome. Do not crop the action area again or long tweets lose content.
cssHeight = twoWidthCap;
} else {
const contentBottom = findTweetContentBottom(tweet, rect);
cssHeight = Math.max(1, contentBottom - top);
}
const maxCssHeight = Math.min(cssHeight, twoWidthCap, viewportCssHeight);
return {
x: Math.max(0, Math.floor(rect.left * dpr)),
y: Math.max(0, Math.floor(top * dpr)),
width: Math.max(1, Math.floor(rect.width * dpr)),
height: Math.max(1, Math.floor(maxCssHeight * dpr))
};
}
function findTweetContentBottom(tweet, rect) {
// On tweet detail pages, X can place reply sorting / quote-tweet links below
// the visible interaction bar inside or adjacent to the same article area.
// Crop at the action bar instead of using the full article height.
const actionButtons = Array.from(tweet.querySelectorAll([
'[data-testid="reply"]',
'[data-testid="retweet"]',
'[data-testid="like"]',
'[data-testid="unlike"]',
'[data-testid="bookmark"]',
'[data-testid="removeBookmark"]'
].join(',')));
const rowRects = actionButtons
.map((button) => findActionRow(button, tweet))
.filter(Boolean)
.map((row) => row.getBoundingClientRect())
.filter((r) => r.width > rect.width * 0.35 && r.height > 8);
if (rowRects.length) {
const bottom = Math.max(...rowRects.map((r) => r.bottom));
if (bottom > rect.top && bottom < rect.bottom + 1) {
const firstCropBottom = Math.min(bottom + 8, rect.bottom);
const firstCropAmount = Math.max(0, rect.bottom - firstCropBottom);
const extraCrop = Math.min(firstCropAmount, 96);
return Math.max(rect.top + 1, firstCropBottom - extraCrop);
}
}
return rect.bottom;
}
function findActionRow(button, tweet) {
let node = button;
while (node && node !== tweet) {
const role = node.getAttribute && node.getAttribute('role');
if (role === 'group') return node;
const rect = node.getBoundingClientRect && node.getBoundingClientRect();
if (rect && rect.width > 250 && rect.height < 90) return node;
node = node.parentElement;
}
return button.parentElement;
}
function cropDataUrl(dataUrl, crop) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = Math.min(crop.width, img.naturalWidth - crop.x);
canvas.height = Math.min(crop.height, img.naturalHeight - crop.y);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, crop.x, crop.y, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
resolve(canvas.toDataURL('image/png'));
};
img.onerror = () => reject(new Error('Could not decode captured screenshot.'));
img.src = dataUrl;
});
}
async function openComposerAndAttach(dataUrl) {
const blob = dataUrlToBlob(dataUrl);
const file = new File([blob], 'x-captured-post.png', { type: 'image/png' });
const editor = await openComposer();
let uploaded = await attachFileToComposer(file, editor);
if (!uploaded) uploaded = await pasteFileIntoComposer(blob, editor);
if (!uploaded) {
await writeImageToClipboard(blob).catch(() => false);
notify('Screenshot copied to clipboard. X did not expose a usable media input, so paste it into the composer manually.', true);
}
}
async function openComposer() {
// Prefer the modal/overlay composer. Returning an existing feed composer causes
// feed captures to attach to the input at the top of the timeline.
const existingDialogEditor = findComposerEditor({ preferDialog: true, dialogOnly: true });
if (existingDialogEditor) return existingDialogEditor;
const composeButton = findComposeButton();
if (composeButton) {
composeButton.click();
} else {
history.pushState(null, '', '/compose/post');
window.dispatchEvent(new PopStateEvent('popstate'));
}
return waitFor(() => findComposerEditor({ preferDialog: true, dialogOnly: true }), 7000);
}
function findComposeButton() {
return document.querySelector('[data-testid="SideNav_NewTweet_Button"], [aria-label="Post"], [aria-label="Tweet"]');
}
function findComposerEditor(options = {}) {
const selector = '[data-testid="tweetTextarea_0"][contenteditable="true"], div[contenteditable="true"][role="textbox"]';
if (options.preferDialog || options.dialogOnly) {
const dialog = document.querySelector('[role="dialog"]');
const dialogEditor = dialog && dialog.querySelector(selector);
if (dialogEditor || options.dialogOnly) return dialogEditor;
}
return document.querySelector(selector);
}
async function attachFileToComposer(file, editorHint = null) {
await revealMediaInput(editorHint);
const input = await waitFor(() => findMediaInput(editorHint), 7000).catch(() => null);
if (!input) return false;
const dt = new DataTransfer();
dt.items.add(file);
input.files = dt.files;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
// X often clears the underlying input as soon as it starts processing the
// file, so checking input.files can incorrectly report failure and cause the
// paste fallback to upload a duplicate. If we found a real media input and
// dispatched the file, treat this path as handled.
await sleep(1200);
return true;
}
async function revealMediaInput(editorHint = null) {
if (findMediaInput(editorHint)) return;
const editor = editorHint || findComposerEditor({ preferDialog: true, dialogOnly: true });
const composerRoot = editor ? (editor.closest('[role="dialog"]') || editor.closest('form') || document) : document;
const mediaButton = composerRoot.querySelector('[data-testid="fileInput"]')
|| composerRoot.querySelector('[aria-label*="Add photos"], [aria-label*="Add photo"], [aria-label*="Media"]');
if (mediaButton && mediaButton.click) {
mediaButton.click();
await sleep(250);
}
}
function findMediaInput(editorHint = null) {
const editor = editorHint || findComposerEditor({ preferDialog: true, dialogOnly: true });
const roots = [];
if (editor) {
const dialog = editor.closest('[role="dialog"]');
if (dialog) roots.push(dialog);
const form = editor.closest('form');
if (form) roots.push(form);
}
if (!roots.length) roots.push(document);
for (const root of roots) {
const inputs = Array.from(root.querySelectorAll('input[type="file"]'));
const match = inputs.find((input) => {
const accept = (input.getAttribute('accept') || '').toLowerCase();
return accept.includes('image') || accept.includes('png') || accept.includes('jpeg') || !accept;
});
if (match) return match;
}
return null;
}
async function pasteFileIntoComposer(blob, editorHint = null) {
const editor = editorHint || await waitFor(() => findComposerEditor({ preferDialog: true, dialogOnly: true }), 5000).catch(() => null);
if (!editor || !window.ClipboardEvent || !window.DataTransfer) return false;
const file = new File([blob], 'x-captured-post.png', { type: 'image/png' });
const dt = new DataTransfer();
dt.items.add(file);
editor.focus();
const event = new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: dt });
editor.dispatchEvent(event);
await sleep(800);
return event.defaultPrevented;
}
async function writeImageToClipboard(blob) {
if (!navigator.clipboard || !window.ClipboardItem) return false;
await navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })]);
return true;
}
function dataUrlToBlob(dataUrl) {
const [header, base64] = dataUrl.split(',');
const mime = /data:([^;]+)/.exec(header)?.[1] || 'image/png';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
return new Blob([bytes], { type: mime });
}
function waitFor(fn, timeout = 4000, interval = 80) {
const started = Date.now();
return new Promise((resolve, reject) => {
const tick = () => {
const value = fn();
if (value) return resolve(value);
if (Date.now() - started > timeout) return reject(new Error('Timed out waiting for X composer UI.'));
window.setTimeout(tick, interval);
};
tick();
});
}
loadFeatureEnabled().catch(() => { featureEnabled = true; });
watchFeatureToggle();
watchMenus();
})();