-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathx-clean.user.js
More file actions
678 lines (604 loc) · 25 KB
/
Copy pathx-clean.user.js
File metadata and controls
678 lines (604 loc) · 25 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// ==UserScript==
// @name X Cleaner
// @description Hide Annoying left sidebar links and remove right sidebar clutter on X.com. Reorder and clean up the post share menu (copy link first, send via chat second, remove "share via post").
// @namespace https://loongphy.com
// @author Loongphy
// @license PolyForm-Noncommercial-1.0.0; https://polyformproject.org/licenses/noncommercial/1.0.0/
// @icon https://www.google.com/s2/favicons?sz=64&domain=x.com
// @version 1.2.1
// @match https://x.com/*
// @run-at document-start
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// ==/UserScript==
(function () {
"use strict";
if (window.__xCleanerInstalled) return;
window.__xCleanerInstalled = true;
const CONFIG = {
demoMode: false,
demoBlurPx: 12,
};
const DEMO_STYLE_ID = "x-cleaner-demo-style";
const STORE_KEY_DEMO_MODE = "x-cleaner-demo-mode";
function gmGetValue(key, defaultValue) {
try {
if (typeof GM_getValue === "function")
return GM_getValue(key, defaultValue);
} catch (e) {}
try {
if (typeof GM !== "undefined" && typeof GM.getValue === "function")
return GM.getValue(key, defaultValue);
} catch (e) {}
return defaultValue;
}
function gmSetValue(key, value) {
try {
if (typeof GM_setValue === "function")
return GM_setValue(key, value);
} catch (e) {}
try {
if (typeof GM !== "undefined" && typeof GM.setValue === "function")
return GM.setValue(key, value);
} catch (e) {}
}
function gmRegisterMenuCommand(label, handler) {
try {
if (typeof GM_registerMenuCommand === "function")
return GM_registerMenuCommand(label, handler);
} catch (e) {}
try {
if (
typeof GM !== "undefined" &&
typeof GM.registerMenuCommand === "function"
)
return GM.registerMenuCommand(label, handler);
} catch (e) {}
}
function initDemoModeOption() {
const v = gmGetValue(STORE_KEY_DEMO_MODE, CONFIG.demoMode);
if (v && typeof v.then === "function") {
v.then((val) => {
CONFIG.demoMode = !!val;
scheduleCleanup();
});
} else {
CONFIG.demoMode = !!v;
}
gmRegisterMenuCommand("DEMO 模式", () => {
CONFIG.demoMode = !CONFIG.demoMode;
gmSetValue(STORE_KEY_DEMO_MODE, CONFIG.demoMode);
scheduleCleanup();
});
}
function ensureDemoStyle() {
if (document.getElementById(DEMO_STYLE_ID)) return;
const s = document.createElement("style");
s.id = DEMO_STYLE_ID;
s.textContent = `
/* 侧边栏头像模糊 */
header[role="banner"] button[data-testid="SideNav_AccountSwitcher_Button"] [data-testid^="UserAvatar-Container-"] {
filter: blur(var(--x-cleaner-demo-blur, 12px)) !important;
}
/* 侧边栏用户名(显示名)模糊 */
header[role="banner"] button[data-testid="SideNav_AccountSwitcher_Button"] > div:nth-child(2) div[dir="ltr"] > span {
filter: blur(var(--x-cleaner-demo-blur, 12px)) !important;
}
/* 侧边栏 @用户名模糊 */
header[role="banner"] button[data-testid="SideNav_AccountSwitcher_Button"] > div:nth-child(2) div[dir="ltr"] > span[class*="r-poiln3"] {
filter: blur(var(--x-cleaner-demo-blur, 12px)) !important;
}
/* 发推输入框旁的头像模糊 */
div:has([data-testid^="tweetTextarea"]):has([role="progressbar"]):not(:has(article)) [data-testid^="UserAvatar-Container-"] {
filter: blur(var(--x-cleaner-demo-blur, 12px)) !important;
}
`;
(document.head || document.documentElement).appendChild(s);
}
function applyDemoMode() {
ensureDemoStyle();
const root = document.documentElement;
const blurValue = CONFIG.demoMode ? `${CONFIG.demoBlurPx}px` : "0px";
root.style.setProperty("--x-cleaner-demo-blur", blurValue);
}
const rxLists = /^\/[A-Za-z0-9_]{1,20}\/lists\/?$/;
const rxCommunities = /^\/[A-Za-z0-9_]{1,20}\/communities\/?$/;
const RETRIEVAL_MENU_ID = "x-cleaner-retrieval-menu";
function isHandle(s) {
return typeof s === "string" && /^[A-Za-z0-9_]{1,20}$/.test(s);
}
function getMyUsername() {
const btn = document.querySelector(
'header[role="banner"] button[data-testid="SideNav_AccountSwitcher_Button"]',
);
if (btn) {
const spans = btn.querySelectorAll("span");
for (const sp of spans) {
const t = (sp.textContent || "").trim();
if (t && t.startsWith("@")) {
const u = t.slice(1).trim();
if (isHandle(u)) return u;
}
}
}
const banner = document.querySelector('header[role="banner"]');
if (banner) {
const links = banner.querySelectorAll("a[href]");
for (const a of links) {
const href = a.getAttribute("href");
if (!href) continue;
let path = null;
if (href.startsWith("/")) {
path = href;
} else if (
href.startsWith("https://") ||
href.startsWith("http://")
) {
try {
const u = new URL(href);
if (u.origin === location.origin) path = u.pathname;
} catch (e) {}
}
if (!path) continue;
const segs = path.split("/").filter(Boolean);
if (segs.length !== 1) continue;
const u = segs[0];
if (!isHandle(u)) continue;
if (
u === "home" ||
u === "explore" ||
u === "notifications" ||
u === "messages" ||
u === "i" ||
u === "settings"
)
continue;
if (rxLists.test(path) || rxCommunities.test(path)) continue;
return u;
}
}
return null;
}
function getTargetUsernameFromPathname() {
const path = location && location.pathname ? location.pathname : "";
const segs = path.split("/").filter(Boolean);
if (segs.length < 1) return null;
const s = segs[0];
if (!isHandle(s)) return null;
const reserved = new Set([
"home",
"explore",
"notifications",
"messages",
"bookmarks",
"lists",
"communities",
"search",
"compose",
"i",
"settings",
"jobs",
"logout",
"login",
"signup",
]);
if (reserved.has(s)) return null;
if (rxLists.test(path) || rxCommunities.test(path)) return null;
if (segs.length === 1) return s;
if (segs.length >= 2 && segs[1] === "status") return s;
return s;
}
function buildSearchUrl(query, options = {}) {
const { latest = true } = options;
const url = new URL("https://x.com/search");
url.searchParams.set("q", query);
url.searchParams.set("src", "typed_query");
if (latest) url.searchParams.set("f", "live");
return url.toString();
}
function ensureRetrievalMenu(sidebar) {
if (!sidebar) return null;
const baseMenuStyle = [
"margin: 53px 0 12px",
"padding: 12px",
"border: 1px solid rgb(43, 46, 49)",
"border-radius: 16px",
].join(";");
const ensureRetrievalMenuStyle = () => {
const STYLE_ID = "x-cleaner-retrieval-menu-style";
if (document.getElementById(STYLE_ID)) return;
const st = document.createElement("style");
st.id = STYLE_ID;
st.textContent = [
"#x-cleaner-retrieval-menu{border-color:rgb(43, 46, 49) !important;}",
"@media (prefers-color-scheme: light){#x-cleaner-retrieval-menu{border-color:rgb(228, 234, 236) !important;}}",
"@media (prefers-color-scheme: dark){#x-cleaner-retrieval-menu{border-color:rgb(43, 46, 49) !important;}}",
'html[data-theme="light"] #x-cleaner-retrieval-menu{border-color:rgb(228, 234, 236) !important;}',
'html[data-theme="dark"] #x-cleaner-retrieval-menu, html[data-theme="dim"] #x-cleaner-retrieval-menu{border-color:rgb(43, 46, 49) !important;}',
".x-cleaner-retrieval-btn{display:inline-flex;align-items:center;justify-content:center;padding:6px 10px;border-radius:10px;border:1px solid rgb(43, 46, 49);background:transparent;color:inherit;text-decoration:none;cursor:pointer;font:inherit;line-height:1;user-select:none;transition:transform 80ms ease;}",
"@media (prefers-color-scheme: light){.x-cleaner-retrieval-btn{border-color:rgb(228, 234, 236);}}",
"@media (prefers-color-scheme: dark){.x-cleaner-retrieval-btn{border-color:rgb(43, 46, 49);}}",
'html[data-theme="light"] .x-cleaner-retrieval-btn{border-color:rgb(228, 234, 236);}',
'html[data-theme="dark"] .x-cleaner-retrieval-btn, html[data-theme="dim"] .x-cleaner-retrieval-btn{border-color:rgb(43, 46, 49);}',
".x-cleaner-retrieval-btn:active{transform:scale(0.98);}",
".x-cleaner-retrieval-btn:focus-visible{outline:2px solid rgba(29,155,240,0.9);outline-offset:2px;}",
].join("\n");
document.head.appendChild(st);
};
const findSidebarDirectChild = (node) => {
if (!node) return null;
let cur = node;
while (cur && cur.parentElement && cur.parentElement !== sidebar)
cur = cur.parentElement;
return cur && cur.parentElement === sidebar ? cur : null;
};
const findUpsellMount = () => {
const upsell = sidebar.querySelector(
'[data-testid="super-upsell-UpsellCardRenderProperties"]',
);
if (!upsell) return null;
const parent = upsell.parentElement;
const grandparent = parent ? parent.parentElement : null;
const anchor = grandparent ? grandparent.parentElement : null;
if (!anchor) return null;
return { anchor, beforeEl: grandparent };
};
const findFooterMount = () => {
const tosLink = sidebar.querySelector(
'a[href="/tos"], a[href^="https://x.com/tos"], a[href^="http://x.com/tos"]',
);
const footerBlock = findSidebarDirectChild(tosLink);
if (!footerBlock) return null;
return { anchor: sidebar, beforeEl: footerBlock };
};
const findSearchMount = () => {
const form = sidebar.querySelector('form[role="search"]');
if (!form) return null;
let lvl = form;
for (let i = 0; i < 4; i += 1) {
if (!lvl || !lvl.parentElement) return null;
lvl = lvl.parentElement;
}
if (!lvl) return null;
const anchor = lvl.parentElement || sidebar;
return { anchor, afterEl: lvl };
};
const moveToMount = (root) => {
const searchMount = findSearchMount();
if (searchMount && searchMount.anchor) {
const desiredParent = searchMount.anchor;
const afterEl = searchMount.afterEl;
if (root.parentElement !== desiredParent) {
if (afterEl) {
afterEl.insertAdjacentElement("afterend", root);
} else {
desiredParent.prepend(root);
}
return;
}
if (afterEl && root.previousElementSibling !== afterEl) {
afterEl.insertAdjacentElement("afterend", root);
}
return;
}
const upsellMount = findUpsellMount();
if (upsellMount && upsellMount.anchor) {
const desiredParent = upsellMount.anchor;
const beforeEl = upsellMount.beforeEl;
if (root.parentElement !== desiredParent) {
desiredParent.insertBefore(
root,
beforeEl || desiredParent.firstChild,
);
return;
}
if (beforeEl && root.nextElementSibling !== beforeEl) {
desiredParent.insertBefore(root, beforeEl);
} else if (
!beforeEl &&
root !== desiredParent.firstElementChild
) {
desiredParent.insertBefore(root, desiredParent.firstChild);
}
return;
}
const footerMount = findFooterMount();
if (footerMount && footerMount.anchor) {
const desiredParent = footerMount.anchor;
const beforeEl = footerMount.beforeEl;
if (root.parentElement !== desiredParent) {
desiredParent.insertBefore(
root,
beforeEl || desiredParent.firstChild,
);
return;
}
if (beforeEl && root.nextElementSibling !== beforeEl) {
desiredParent.insertBefore(root, beforeEl);
} else if (
!beforeEl &&
root !== desiredParent.firstElementChild
) {
desiredParent.insertBefore(root, desiredParent.firstChild);
}
return;
}
const mount = findSearchMount();
if (!mount || !mount.anchor) return;
const desiredParent = mount.anchor;
const afterEl = mount.afterEl;
// Ensure parent
if (root.parentElement !== desiredParent) {
if (afterEl) {
afterEl.insertAdjacentElement("afterend", root);
} else {
desiredParent.prepend(root);
}
return;
}
// Ensure order (right after afterEl)
if (afterEl && root.previousElementSibling !== afterEl) {
afterEl.insertAdjacentElement("afterend", root);
}
};
let root = document.getElementById(RETRIEVAL_MENU_ID);
if (!root) {
root = document.createElement("div");
root.id = RETRIEVAL_MENU_ID;
root.className = "shortcuts-menu";
root.style.cssText = baseMenuStyle;
const ul = document.createElement("ul");
ul.className = "shortcuts-menu-list";
ul.style.cssText = [
"list-style:none",
"margin:0",
"padding:0",
"display:block",
].join(";");
root.appendChild(ul);
const li = document.createElement("li");
li.className = "shortcuts-menu-row";
ul.appendChild(li);
sidebar.prepend(root);
moveToMount(root);
} else {
// Overwrite any previous inline styles from older versions.
root.style.cssText = baseMenuStyle;
// If the menu exists but is mounted in a wrong place, move it back to the desired position.
moveToMount(root);
}
ensureRetrievalMenuStyle();
const ul = root.querySelector("ul.shortcuts-menu-list");
const li = ul ? ul.querySelector("li.shortcuts-menu-row") : null;
if (!ul || !li) return root;
li.style.cssText = [
"display:flex",
"flex-wrap:wrap",
"gap:8px",
"align-items:center",
].join(";");
const addAction = (label, query, options) => {
const a = document.createElement("a");
a.className = "x-cleaner-retrieval-btn";
a.setAttribute("role", "button");
a.textContent = label;
a.href = buildSearchUrl(query, options);
a.target = "_self";
li.appendChild(a);
};
const my = getMyUsername();
const target = getTargetUsernameFromPathname();
const isHome = location && location.pathname === "/home";
const isMyProfile = !!(my && target && my === target);
const scenario = (() => {
if (my && (isHome || isMyProfile)) return { type: "home", my };
if (target) return { type: "target", my: my || null, target };
return { type: "none", my: my || null, target: target || null };
})();
const renderKey = JSON.stringify(scenario);
const prevKey = root.getAttribute("data-render-key");
if (prevKey === renderKey) return root;
root.setAttribute("data-render-key", renderKey);
li.textContent = "";
const addMyRetrievalAction = () => {
if (scenario.my) {
addAction("我的有回推", `from:${scenario.my} min_replies:1`);
return true;
}
addAction("我的有回推", "min_replies:1");
return false;
};
if (scenario.type === "home") {
addMyRetrievalAction();
} else if (scenario.type === "target") {
addAction(
"TA的推文",
`from:${scenario.target} -filter:replies -filter:retweets`,
);
if (scenario.my) {
addAction(
"我回TA",
`from:${scenario.my} to:${scenario.target} filter:replies`,
);
}
} else {
addMyRetrievalAction();
}
addAction("仅限中文", "lang:zh", { latest: false });
addAction("仅限英文", "lang:en", { latest: false });
return root;
}
function hide(el) {
if (!el || el.nodeType !== 1) return;
if (el.getAttribute("data-x-cleaner-hidden") === "1") return;
el.setAttribute("data-x-cleaner-hidden", "1");
el.style.setProperty("display", "none", "important");
}
function cleanLeftSidebar(banner) {
const links = banner.querySelectorAll("a[href]");
for (const a of links) {
const href = a.getAttribute("href");
if (!href) continue;
if (
href === "/explore" ||
href === "/i/premium_sign_up" ||
href === "/i/jf/creators/studio" ||
rxLists.test(href) ||
rxCommunities.test(href)
) {
hide(a);
}
}
}
function cleanRightSidebar() {
const sidebar = document.querySelector(
'div[data-testid="sidebarColumn"]',
);
if (!sidebar) return;
ensureRetrievalMenu(sidebar);
const hideAncestor = (el, levels = 2) => {
if (!el || levels <= 0) return;
let target = el;
for (let i = 0; i < levels; i += 1) {
if (!target || !target.parentElement) return;
target = target.parentElement;
}
hide(target);
};
for (const h1 of sidebar.querySelectorAll(
'h1[id^="accessible-list-"]',
)) {
if (!/^accessible-list-\d+$/.test(h1.id)) continue;
hideAncestor(h1);
}
hideAncestor(
sidebar.querySelector(
'[data-testid="super-upsell-UpsellCardRenderProperties"]',
),
);
for (const aside of sidebar.querySelectorAll(
'aside[role="complementary"]',
)) {
hideAncestor(aside, 2);
}
hide(sidebar.querySelector('div[data-testid="whoToFollowSspAd"]'));
for (const nav of sidebar.querySelectorAll('nav[role="navigation"]')) {
hide(nav);
}
}
// ---- Share menu optimization ----
// X.com's post share menu is rendered as a [data-testid="Dropdown"] with three menuitems:
// 1. "通过聊天发送" (Send via chat) — chat bubble icon
// 2. "复制链接" (Copy link) — link icon
// 3. "帖子分享途径…" (Share post via…) — share/upload icon
// The menu items have no test IDs and identical styled wrappers, so we identify them
// by visible text. Goal: put "复制链接" first, "通过聊天发送" second, and remove
// the "帖子分享途径…" entry entirely. We also support the English UI variants
// ("Copy link" / "Send via direct message" / "Share post via…").
function processShareMenus() {
const dropdowns = document.querySelectorAll('[data-testid="Dropdown"]');
for (const dropdown of dropdowns) {
if (!dropdown || dropdown.nodeType !== 1) continue;
const items = dropdown.querySelectorAll('[role="menuitem"]');
if (!items || items.length === 0) continue;
// Identify the share menu by the presence of a "copy link" entry.
// Other dropdowns (account menu, tweet actions, etc.) won't have this text.
let copyLinkItem = null;
for (const it of items) {
const t = (it.textContent || "").trim();
if (t === "复制链接" || t === "Copy link") {
copyLinkItem = it;
break;
}
}
if (!copyLinkItem) continue;
// Locate the other two entries we care about.
let sendViaChatItem = null;
let shareViaPostItem = null;
for (const it of items) {
const t = (it.textContent || "").trim();
if (!sendViaChatItem) {
if (t === "通过聊天发送") {
sendViaChatItem = it;
continue;
}
if (/^Send via\b/i.test(t)) {
sendViaChatItem = it;
continue;
}
}
if (!shareViaPostItem) {
if (t === "帖子分享途径…" || t === "帖子分享途径") {
shareViaPostItem = it;
continue;
}
if (/分享途径/.test(t)) {
shareViaPostItem = it;
continue;
}
if (/^Share post via/i.test(t) || /^Share via\b/i.test(t)) {
shareViaPostItem = it;
continue;
}
}
}
// 1) Remove the "帖子分享途径…" entry.
if (shareViaPostItem && shareViaPostItem.parentElement) {
shareViaPostItem.parentElement.removeChild(shareViaPostItem);
}
// 2) Move "复制链接" to the top.
if (copyLinkItem.parentElement) {
const parent = copyLinkItem.parentElement;
if (parent.firstChild !== copyLinkItem) {
parent.insertBefore(copyLinkItem, parent.firstChild);
}
}
// 3) Place "通过聊天发送" right after "复制链接".
if (
sendViaChatItem &&
sendViaChatItem.parentElement &&
copyLinkItem.parentElement === sendViaChatItem.parentElement
) {
const parent = sendViaChatItem.parentElement;
const desiredNext = copyLinkItem.nextSibling;
if (desiredNext !== sendViaChatItem) {
parent.insertBefore(sendViaChatItem, desiredNext);
}
}
}
}
function cleanup() {
applyDemoMode();
const banner = document.querySelector('header[role="banner"]');
if (banner) cleanLeftSidebar(banner);
cleanRightSidebar();
processShareMenus();
}
let scheduled = false;
function scheduleCleanup() {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(() => {
scheduled = false;
cleanup();
});
}
initDemoModeOption();
const mo = new MutationObserver(() => scheduleCleanup());
mo.observe(document.documentElement, { childList: true, subtree: true });
const originalPushState = history.pushState;
history.pushState = function () {
const ret = originalPushState.apply(this, arguments);
scheduleCleanup();
return ret;
};
const originalReplaceState = history.replaceState;
history.replaceState = function () {
const ret = originalReplaceState.apply(this, arguments);
scheduleCleanup();
return ret;
};
window.addEventListener("popstate", () => scheduleCleanup());
scheduleCleanup();
})();