wayBetter for X

This commit is contained in:
CRTkafa 2026-10-01 06:01:13 +07:00
commit df5dff619e
720 changed files with 147465 additions and 0 deletions

View file

@ -0,0 +1,501 @@
// Ports a subset of "Control Panel for Twitter" (CPFT, MIT, (c) 2019 Jonny Buchanan,
// https://github.com/insin/control-panel-for-twitter) into wayBetter's own injection
// contract. Selectors and SVG paths are re-derived from CPFT's script.js/options.js and
// re-verified against the live x.com DOM rather than copied as a script include.
// See THIRD_PARTY_NOTICES.md for the CPFT license text.
import { LOGO_PNG } from '../ui/logo-data.ts';
import { routeKind } from '../fixes/route.ts';
import { watchDom } from './domHub.ts';
/**
* The flags that were the Tweaks section, by name. They are rows of the feature table now
* (src/areas/table.ts, which also owns their defaults: tests/areas.test.ts keeps the two in step);
* newer flags (`<area>.<feature>`, `area.<id>`) only exist there.
*/
export type FeatureConfig = {
/** wayBetter's brush-wing bird in X's header and favicon (wins over `replaceLogo`). */
logoBrush: boolean;
/** Classic Twitter bird (used when `logoBrush` is off). Both off: X's own logo. */
replaceLogo: boolean;
twitterWording: boolean;
hidePromotedPosts: boolean;
hidePremiumUpsells: boolean;
hideGrok: boolean;
hideSidebarTrends: boolean;
hideWhoToFollow: boolean;
hideLiveOnX: boolean;
hideTodaysNews: boolean;
hideViewCounts: boolean;
hideEngagementCounts: boolean;
hideBookmarkButton: boolean;
hideExploreContent: boolean;
followingTimelineDefault: boolean;
hideForYouTab: boolean;
hidePremiumNav: boolean;
hideChatNav: boolean;
hideCommunitiesNav: boolean;
hideGrokNav: boolean;
/** Split view: X panes of the same account right of (or below) another hide X's left navigation. */
singleSplitNav: boolean;
disableTweetTextFormatting: boolean;
/** Download button for original-quality photos, videos and GIFs on posts. */
mediaDownload: boolean;
/** "Drafts" button in X's composer toolbar that opens the wayBetter drafts picker. */
composerDrafts: boolean;
/** Operator chips (from:, since:, filter:media…) under X's search box. */
searchOperators: boolean;
/** Serializes like/repost/bookmark/follow requests per target so rapid clicks cannot desync X's state. */
fixLikeFollow: boolean;
/** Returns to the post you were reading after Back or a timeline tab switch. */
fixScrollRestore: boolean;
/** Keeps the post you are reading still when X inserts posts or content above it. */
fixTimelineJump: boolean;
/** Switches back to the Home tab you last picked when X re-selects "For you". */
fixHomeTab: boolean;
/** Hides a notification count you have already seen on the Notifications page. */
fixNotificationBadge: boolean;
/** "See new posts" keeps the post you were reading in place instead of jumping to the top. */
fixNewPostsPill: boolean;
/** Retries a media upload chunk/status request X gives up on (network error, 503, timeout); toast if it still fails. */
fixMediaUpload: boolean;
/** Following tab asks X for newest-first order even when its sort is set to "Popular". */
followingChronological: boolean;
/** "Restore unsent text" button on a composer whose earlier text was lost. */
composerRestorePrompt: boolean;
/** X's floating Chat button fades out while it would cover an inline reply/post box. */
fixChatButton: boolean;
rememberVideoVolume: boolean;
disableVideoAutoplay: boolean;
stopVideoLoop: boolean;
sortRepliesRecent: boolean;
fullNumbers: boolean;
hideVerifiedBadges: boolean;
hideSubscribeButtons: boolean;
fullWidthTimeline: boolean;
hideSidebar: boolean;
hideRelevantPeople: boolean;
hideProfileWhoToFollow: boolean;
};
export const FEATURE_DEFAULTS: FeatureConfig = {
logoBrush: true,
replaceLogo: false,
twitterWording: true,
hidePromotedPosts: true,
hidePremiumUpsells: false,
hideGrok: false,
hideSidebarTrends: false,
hideWhoToFollow: false,
hideLiveOnX: false,
hideTodaysNews: false,
hideViewCounts: false,
hideEngagementCounts: false,
hideBookmarkButton: false,
hideExploreContent: false,
followingTimelineDefault: false,
hideForYouTab: false,
hidePremiumNav: false,
hideChatNav: false,
hideCommunitiesNav: false,
hideGrokNav: false,
singleSplitNav: true,
disableTweetTextFormatting: false,
mediaDownload: true,
composerDrafts: true,
searchOperators: true,
fixLikeFollow: true,
fixScrollRestore: true,
fixTimelineJump: true,
fixHomeTab: true,
fixNotificationBadge: true,
fixNewPostsPill: true,
fixMediaUpload: true,
followingChronological: true,
composerRestorePrompt: true,
fixChatButton: true,
rememberVideoVolume: true,
disableVideoAutoplay: false,
stopVideoLoop: false,
sortRepliesRecent: false,
fullNumbers: false,
hideVerifiedBadges: false,
hideSubscribeButtons: false,
fullWidthTimeline: false,
hideSidebar: false,
hideRelevantPeople: false,
hideProfileWhoToFollow: false,
};
const FEATURE_KEYS = Object.keys(FEATURE_DEFAULTS) as (keyof FeatureConfig)[];
/** Unknown keys are dropped; non-boolean values fall back to the default for that key. */
export function normalizeFeatures(input: unknown): FeatureConfig {
const source = input && typeof input === 'object' ? (input as Record<string, unknown>) : {};
const result = {} as FeatureConfig;
for (const key of FEATURE_KEYS) {
const value = source[key];
result[key] = typeof value === 'boolean' ? value : FEATURE_DEFAULTS[key];
}
return result;
}
// -- CPFT-derived constants (script.js `Svgs` / `Selectors`), re-verified live on x.com --
const THEME_BLUE = 'rgb(29,155,240)';
// Svgs.TWITTER_LOGO_PATH
const TWITTER_LOGO_PATH = 'M23.643 4.937c-.835.37-1.732.62-2.675.733.962-.576 1.7-1.49 2.048-2.578-.9.534-1.897.922-2.958 1.13-.85-.904-2.06-1.47-3.4-1.47-2.572 0-4.658 2.086-4.658 4.66 0 .364.042.718.12 1.06-3.873-.195-7.304-2.05-9.602-4.868-.4.69-.63 1.49-.63 2.342 0 1.616.823 3.043 2.072 3.878-.764-.025-1.482-.234-2.11-.583v.06c0 2.257 1.605 4.14 3.737 4.568-.392.106-.803.162-1.227.162-.3 0-.593-.028-.877-.082.593 1.85 2.313 3.198 4.352 3.234-1.595 1.25-3.604 1.995-5.786 1.995-.376 0-.747-.022-1.112-.065 2.062 1.323 4.51 2.093 7.14 2.093 8.57 0 13.255-7.098 13.255-13.254 0-.2-.005-.402-.014-.602.91-.658 1.7-1.477 2.323-2.41z';
// Selectors.X_LOGO_PATH / X_DARUMA_LOGO_PATH (attribute value only, without the `svg path[d=...]` wrapper)
const X_LOGO_PATH_D = 'M21.742 21.75l-7.563-11.179 7.056-8.321h-2.456l-5.691 6.714-4.54-6.714H2.359l7.29 10.776L2.25 21.75h2.456l6.035-7.118 4.818 7.118h6.191-.008zM7.739 3.818L18.81 20.182h-2.447L5.29 3.818h2.447z';
const X_DARUMA_LOGO_PATH_D = 'M18.436 1.92h3.403l-7.433 8.495 8.745 11.563h-6.849l-5.363-7.012-6.136 7.012H1.4l7.951-9.088L.96 1.92h7.02l4.848 6.41 5.608-6.41zm-1.194 18.021h1.886L6.958 3.851H4.933l12.308 16.09z';
// Svgs.X_HOME_ACTIVE_PATH / X_HOME_INACTIVE_PATH / TWITTER_HOME_ACTIVE_PATH / TWITTER_HOME_INACTIVE_PATH
const X_HOME_ACTIVE_PATH = 'M10.059 2.593c1.175-.784 2.707-.784 3.882 0l6.5 4.333C21.415 7.575 22 8.668 22 9.838V18.5c0 1.933-1.567 3.5-3.5 3.5h-4.25v-5.25c0-1.243-1.007-2.25-2.25-2.25s-2.25 1.007-2.25 2.25V22H5.5C3.567 22 2 20.433 2 18.5V9.838c0-1.17.585-2.263 1.559-2.912l6.5-4.333z';
const X_HOME_INACTIVE_PATH = 'M20 9.838c0-.502-.25-.97-.668-1.248l-6.5-4.333c-.504-.336-1.16-.336-1.664 0l-6.5 4.333C4.251 8.868 4 9.336 4 9.838V18.5c0 .828.672 1.5 1.5 1.5h3v-3.5c0-1.933 1.567-3.5 3.5-3.5s3.5 1.567 3.5 3.5V20h3c.828 0 1.5-.672 1.5-1.5V9.838zm2 8.662c0 1.933-1.567 3.5-3.5 3.5h-5v-5.5c0-.829-.672-1.5-1.5-1.5s-1.5.671-1.5 1.5V22h-5C3.567 22 2 20.433 2 18.5V9.838c0-1.17.585-2.263 1.559-2.912l6.5-4.333c1.175-.784 2.707-.784 3.882 0l6.5 4.333C21.415 7.575 22 8.668 22 9.838V18.5z';
const TWITTER_HOME_ACTIVE_PATH = 'M12 1.696L.622 8.807l1.06 1.696L3 9.679V19.5C3 20.881 4.119 22 5.5 22h13c1.381 0 2.5-1.119 2.5-2.5V9.679l1.318.824 1.06-1.696L12 1.696zM12 16.5c-1.933 0-3.5-1.567-3.5-3.5s1.567-3.5 3.5-3.5 3.5 1.567 3.5 3.5-1.567 3.5-3.5 3.5z';
const TWITTER_HOME_INACTIVE_PATH = 'M12 9c-2.209 0-4 1.791-4 4s1.791 4 4 4 4-1.791 4-4-1.791-4-4-4zm0 6c-1.105 0-2-.895-2-2s.895-2 2-2 2 .895 2 2-.895 2-2 2zm0-13.304L.622 8.807l1.06 1.696L3 9.679V19.5C3 20.881 4.119 22 5.5 22h13c1.381 0 2.5-1.119 2.5-2.5V9.679l1.318.824 1.06-1.696L12 1.696zM19 19.5c0 .276-.224.5-.5.5h-13c-.276 0-.5-.224-.5-.5V8.429l7-4.375 7 4.375V19.5z';
// Selectors.NAV_HOME_LINK
const NAV_HOME_LINK = 'a[data-testid="AppTabBar_Home_Link"]';
const STYLE_ID = 'bt-features';
const ORIGINAL_D_ATTR = 'data-bt-x-d';
const ORIGINAL_HREF_ATTR = 'data-bt-x-href';
const HOME_ROUTE_ATTR = 'data-bt-home';
const ROUTE_ATTR = 'data-bt-route';
function pushIf(rules: string[], condition: boolean, css: string) {
if (condition) rules.push(css);
}
const SIDEBAR = '[data-testid="sidebarColumn"]';
/**
* Pure: selectors for a right-column module and the bordered card X draws around it (1px border,
* 16px corners, 16px gap below). Hiding only the module left the card behind as an empty box, so
* the card (its wrapper one or two levels up) goes too, but only when the module is all it holds:
* a wrapper with anything else in it (search, other modules, the footer) never matches.
* `base` is the module's landmark, `inside` what identifies it (optional).
*/
export function sidebarModuleSelectors(base: string, inside = '', scope = SIDEBAR): string[] {
const target = inside ? `${base} ${inside}` : base;
return [
`${scope} ${inside ? `${base}:has(${inside})` : base}`,
`${scope} div:has(> ${target}):not(:has(> :not(${base})))`,
`${scope} div:has(> div > ${target}):not(:has(> :not(div))):not(:has(> div > :not(${base})))`,
];
}
/** Attributes on an opened post's "· 1,234 Views" unit and the "·" before it (see focalViewsParts). */
export const VIEWS_ATTR = 'data-bt-views';
export const VIEWS_SEP_ATTR = 'data-bt-views-sep';
/** The DOM surface focalViewsParts reads (tests feed plain objects). */
export type ShapeNode = {
tagName: string;
parentElement: ShapeNode | null;
nextElementSibling: ShapeNode | null;
children: ArrayLike<ShapeNode>;
textContent: string | null;
getAttribute(name: string): string | null;
};
/**
* Pure (DOM shape only): the views unit on an opened post's date line ("10:06 PM · Sep 28, 2026 ·
* 1,234 Views"). Walks up from the date link and returns the sibling holding the count (plus X's
* " " and "Views" when they are its siblings) and the "·" separator before it, or null. Hiding just
* the number left "· Views" behind.
*/
export function focalViewsParts(time: ShapeNode): { unit: ShapeNode[]; separators: ShapeNode[] } | null {
const isCount = (el: ShapeNode) => el.getAttribute('data-testid') === 'app-text-transition-container'
|| (el.tagName === 'A' && /\/analytics\/?$/.test(el.getAttribute('href') ?? ''));
const has = (el: ShapeNode, test: (el: ShapeNode) => boolean): boolean => test(el) || Array.from(el.children).some(child => has(child, test));
const isTime = (el: ShapeNode) => el.tagName === 'TIME';
const isSeparator = (el: ShapeNode) => /^[·•]$/.test((el.textContent ?? '').trim());
let node: ShapeNode | null = time;
while (node.parentElement && node.tagName !== 'A') node = node.parentElement;
if (node.tagName !== 'A') node = time;
for (let depth = 0; depth < 4 && node?.parentElement && node.parentElement.tagName !== 'ARTICLE'; depth += 1, node = node.parentElement) {
const separators: ShapeNode[] = [];
for (let sib = node.nextElementSibling; sib; sib = sib.nextElementSibling) {
if (has(sib, isTime)) break;
if (isSeparator(sib)) { separators.push(sib); continue; }
if (!has(sib, isCount)) break;
const unit = [sib];
for (let rest = sib.nextElementSibling; rest && !isSeparator(rest) && !has(rest, isTime); rest = rest.nextElementSibling) unit.push(rest);
return { unit, separators: separators.slice(-1) };
}
}
return null;
}
/**
* Pure: builds the full `<style id="bt-features">` contents for a given config. The rail, right
* column and layout rules are Navigation+'s feature modules now (src/areas/navigation/css.ts), the
* timeline and post rules Reader+'s (src/areas/reader/css.ts), the profile rules Profile+'s
* (src/areas/profile/css.ts) and the Explore rule Search+'s. What is left here is the branding.
*/
export function buildFeatureCss(config: FeatureConfig): string {
const rules: string[] = [];
// Brush logo: CSS-only, so it survives X re-rendering its header. The X glyph stays in the
// DOM (invisible) and the svg box paints our logo instead.
pushIf(rules, config.logoBrush, `
svg:has(> g > path[d="${X_LOGO_PATH_D}"]), svg:has(> path[d="${X_LOGO_PATH_D}"]),
svg:has(> g > path[d="${X_DARUMA_LOGO_PATH_D}"]), svg:has(> path[d="${X_DARUMA_LOGO_PATH_D}"]) {
background: url("${LOGO_PNG}") center / contain no-repeat;
border-radius: 22%;
}
svg path[d="${X_LOGO_PATH_D}"], svg path[d="${X_DARUMA_LOGO_PATH_D}"] {
opacity: 0;
}
.bt-brand-logo { opacity: 0; }`);
pushIf(rules, !config.logoBrush && config.replaceLogo, `
svg path[d="${X_LOGO_PATH_D}"],
svg path[d="${X_DARUMA_LOGO_PATH_D}"] {
fill: ${THEME_BLUE};
d: path("${TWITTER_LOGO_PATH}");
}
.bt-logo-patched {
fill: ${THEME_BLUE};
}
${NAV_HOME_LINK} svg path[d="${X_HOME_ACTIVE_PATH}"] {
d: path("${TWITTER_HOME_ACTIVE_PATH}");
}
${NAV_HOME_LINK} svg path[d="${X_HOME_INACTIVE_PATH}"] {
d: path("${TWITTER_HOME_INACTIVE_PATH}");
}`.trim());
return rules.join('\n\n');
}
// -- Full numbers: X keeps the exact count in each action's aria-label ("1234 Likes. Like").
// The feature is Reader+'s module (src/areas/reader/fullNumbers.ts); these are its pure parts. --
/** The exact count at the start of an action label, in any locale's digit grouping, or null. */
export function fullCountFromLabel(label: string | null | undefined): number | null {
const match = /^\s*(\d{1,3}(?:[.,\s\u00a0\u202f]\d{3})+|\d+)(?=\s|$)/.exec(label ?? '');
if (!match) return null;
const value = Number(match[1]!.replace(/\D/g, ''));
return Number.isSafeInteger(value) ? value : null;
}
/** X's abbreviated count text ("1.2K", "3,4 Mio.", "12M"), as opposed to an exact one. */
export function isCompactCount(text: string): boolean {
return /^\d+(?:[.,]\d+)?\s?[^\d\s.,]{1,4}\.?$/u.test(text.trim());
}
export function formatFullCount(value: number, locale?: string): string {
try { return new Intl.NumberFormat(locale).format(value); } catch { return String(value); }
}
// -- Runtime: DOM patching + observers (installFeatures) --
const WORDING_MAP: Record<string, string> = { Post: 'Tweet', Posts: 'Tweets', Repost: 'Retweet', Reposts: 'Retweets' };
const WORDING_REVERSE: Record<string, string> = Object.fromEntries(Object.entries(WORDING_MAP).map(([x, twitter]) => [twitter, x]));
const RETEXT_ATTR = 'data-bt-retext';
const TEXT_NODE = 3;
/** Retexts X's own label text nodes in place. Editing the node (not `span.textContent`, which
* swaps in a new node) keeps React owning it, so X's later updates (e.g. the label emptied when the
* nav collapses to icon-only) still land instead of leaving a stale "Tweet" behind. */
function retextExact(el: Element | null | undefined) {
if (!el) return;
for (const span of el.querySelectorAll('span')) {
for (const node of Array.from(span.childNodes)) {
const text = node.nodeType === TEXT_NODE ? node.nodeValue : null;
if (text == null || !Object.hasOwn(WORDING_MAP, text)) continue;
node.nodeValue = WORDING_MAP[text]!;
span.setAttribute(RETEXT_ATTR, '');
}
}
}
/** Puts X's own wording back on labels `retextExact` changed. */
function restoreText(root: ParentNode | null | undefined) {
if (!root) return;
for (const span of root.querySelectorAll(`[${RETEXT_ATTR}]`)) {
for (const node of Array.from(span.childNodes)) {
const text = node.nodeType === TEXT_NODE ? node.nodeValue : null;
if (text != null && Object.hasOwn(WORDING_REVERSE, text)) node.nodeValue = WORDING_REVERSE[text]!;
}
span.removeAttribute(RETEXT_ATTR);
}
}
function buildFaviconDataUrl(brush: boolean): string {
if (brush) return LOGO_PNG;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="${THEME_BLUE}" d="${TWITTER_LOGO_PATH}"/></svg>`;
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}
type FeatureHandle = { apply(config: Partial<FeatureConfig>): void; dispose(): void };
// `MutationObserver` is a DOM global, not a member of TS's `Window` interface; declare it
// explicitly here so callers can inject a fake constructor (as tests do) without needing jsdom.
type FeatureWindow = Window & { MutationObserver: typeof MutationObserver };
declare global {
interface Window { __betterTwttrFeatures?: FeatureHandle }
}
export function installFeatures(target: Window = window): FeatureHandle {
let win: FeatureWindow;
try {
win = target as FeatureWindow;
if (win.top !== win || win.location.origin !== 'https://x.com') return { apply() {}, dispose() {} };
} catch {
return { apply() {}, dispose() {} };
}
if (win.__betterTwttrFeatures) return win.__betterTwttrFeatures;
const doc = win.document;
let config: FeatureConfig = { ...FEATURE_DEFAULTS };
let disposed = false;
const ensureStyle = (): HTMLStyleElement => {
let el = doc.getElementById(STYLE_ID) as HTMLStyleElement | null;
if (!el) {
el = doc.createElement('style');
el.id = STYLE_ID;
(doc.head || doc.documentElement).appendChild(el);
}
return el;
};
// The bird is also written into the path (engines without CSS `d:` support); it remembers X's
// glyph so switching to the brush logo (which matches X's glyph) or back to X reverts it.
const patchLogo = () => {
try {
if (!config.logoBrush && config.replaceLogo) {
for (const path of doc.querySelectorAll('h1 svg path')) {
const d = path.getAttribute('d');
if (d === X_LOGO_PATH_D || d === X_DARUMA_LOGO_PATH_D) {
path.setAttribute(ORIGINAL_D_ATTR, d);
path.setAttribute('d', TWITTER_LOGO_PATH);
path.classList.add('bt-logo-patched');
}
}
return;
}
for (const path of doc.querySelectorAll(`path[${ORIGINAL_D_ATTR}]`)) {
path.setAttribute('d', path.getAttribute(ORIGINAL_D_ATTR)!);
path.removeAttribute(ORIGINAL_D_ATTR);
path.classList.remove('bt-logo-patched');
}
} catch { /* degrade silently */ }
};
// Keeps X's own favicon href (it swaps in a badge variant for notifications) to restore it.
const patchFavicon = () => {
try {
const href = config.logoBrush || config.replaceLogo ? buildFaviconDataUrl(config.logoBrush) : null;
for (const link of doc.querySelectorAll<HTMLLinkElement>('link[rel~="icon"]')) {
const current = link.getAttribute('href') ?? '';
if (href) {
if (current === href) continue;
// Ours are data: URLs; anything else is X's (possibly a new badge variant).
if (!current.startsWith('data:')) link.setAttribute(ORIGINAL_HREF_ATTR, current);
link.setAttribute('href', href);
} else if (link.hasAttribute(ORIGINAL_HREF_ATTR)) {
link.setAttribute('href', link.getAttribute(ORIGINAL_HREF_ATTR)!);
link.removeAttribute(ORIGINAL_HREF_ATTR);
}
}
} catch { /* degrade silently */ }
};
const patchWording = () => {
try {
retextExact(doc.querySelector('button[data-testid^="tweetButton"]'));
// Compact nav: X renders an icon-only round button (svg + empty label). Leave it as X drew it.
const sideNav = doc.querySelector('[data-testid="SideNav_NewTweet_Button"]');
if (sideNav?.querySelector('svg')) restoreText(sideNav);
else retextExact(sideNav);
for (const item of doc.querySelectorAll('[data-testid="retweetConfirm"], [data-testid="repostConfirm"], [data-testid="unretweetConfirm"], [data-testid="unrepostConfirm"]')) {
retextExact(item);
}
} catch { /* degrade silently */ }
};
const patchTitle = () => {
if (!config.twitterWording) return;
try {
const title = doc.title;
if (/ \/ X$/.test(title)) doc.title = title.replace(/ \/ X$/, ' / Twitter');
} catch { /* degrade silently */ }
};
const syncRoute = () => {
try {
if (win.location.pathname === '/home') doc.documentElement.setAttribute(HOME_ROUTE_ATTR, '');
else doc.documentElement.removeAttribute(HOME_ROUTE_ATTR);
const kind = routeKind(win.location.pathname);
if (doc.documentElement.getAttribute(ROUTE_ATTR) !== kind) doc.documentElement.setAttribute(ROUTE_ATTR, kind);
} catch { /* degrade silently */ }
};
// The icon links live in <head>: re-checked when <head> changes or the config does, not on every
// body mutation (reading a data: href copies ~20 KB each time).
let faviconDirty = true;
const runPatches = () => {
if (disposed) return;
syncRoute();
patchLogo();
if (faviconDirty) { faviconDirty = false; patchFavicon(); }
if (config.twitterWording) patchWording();
else restoreText(doc);
};
// Shared body observer + frame (domHub.ts). Route, logo and wording also apply on chat pages.
const watch = watchDom(win, runPatches);
const schedule = watch.schedule;
// Runs at document start, before <title> exists, and X replaces the title node on navigation:
// watch the whole <head> once it exists. patchTitle is idempotent, so its own write settles.
let titleObserver: MutationObserver | null = null;
const onHead = (records?: MutationRecord[]) => {
patchTitle();
if (!records?.length || records.some(record => record.type !== 'characterData')) { faviconDirty = true; schedule(); }
};
const watchTitle = () => {
if (titleObserver || !doc.head) return;
titleObserver = new win.MutationObserver(onHead);
titleObserver.observe(doc.head, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['href'] });
patchTitle();
};
if (doc.head) watchTitle();
else doc.addEventListener('DOMContentLoaded', watchTitle, { once: true });
const onPopState = () => schedule();
win.addEventListener('popstate', onPopState);
schedule();
patchTitle();
const handle: FeatureHandle = {
apply(partial) {
const next = normalizeFeatures({ ...config, ...partial });
config = next;
ensureStyle().textContent = buildFeatureCss(config);
faviconDirty = true;
schedule();
patchTitle();
},
dispose() {
disposed = true;
watch.dispose();
titleObserver?.disconnect();
win.removeEventListener('popstate', onPopState);
doc.getElementById(STYLE_ID)?.remove();
delete win.__betterTwttrFeatures;
},
};
win.__betterTwttrFeatures = handle;
return handle;
}