wayBetter for X
This commit is contained in:
commit
df5dff619e
720 changed files with 147465 additions and 0 deletions
44
apps/desktop/src/inject/accountReport.ts
Normal file
44
apps/desktop/src/inject/accountReport.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// Tells the app which X account is signed in inside this tab's profile, so the account switcher
|
||||
// lists real logins (avatar, name, @handle) instead of hand-named slots. Read from X's own account
|
||||
// button, which X renders anyway; nothing is requested. Only a change is reported (tab_report), and
|
||||
// native code accepts it only from a webview that is on x.com, for that webview's own profile. The
|
||||
// reporting loop is the wayBetter runtime's (accountReport.ts); reading X's account button is here.
|
||||
|
||||
import './xSite.ts';
|
||||
import {
|
||||
installAccountReport as installCore,
|
||||
type Invoke,
|
||||
type SeenAccount,
|
||||
} from '../../../../waybetter/packages/runtime/src/accountReport.ts';
|
||||
|
||||
export type { SeenAccount };
|
||||
|
||||
const SWITCHER = '[data-testid="SideNav_AccountSwitcher_Button"]';
|
||||
const DASH = '[data-testid="DashButton_ProfileIcon_Link"]';
|
||||
const AVATAR = '[data-testid^="UserAvatar-Container-"]';
|
||||
/** X's logged-out page: its own sign-in / sign-up buttons. */
|
||||
const SIGNED_OUT = '[data-testid="loginButton"], [data-testid="signupButton"], [data-testid="google_sign_in_container"]';
|
||||
|
||||
/** Pure over the DOM: the account X's account button shows, or null when there is none. */
|
||||
export function readAccount(root: ParentNode): SeenAccount | null {
|
||||
// Wide layouts: the account button in the left rail. Narrow ones (a small pane, a background tab
|
||||
// the app keeps at 1 px): the avatar button top left that opens X's drawer.
|
||||
const button = root.querySelector(SWITCHER) ?? root.querySelector(DASH);
|
||||
if (!button) return null;
|
||||
const profileLink = root.querySelector('a[data-testid="AppTabBar_Profile_Link"]')?.getAttribute('href')?.slice(1) ?? '';
|
||||
const handle = button.querySelector(AVATAR)?.getAttribute('data-testid')?.slice('UserAvatar-Container-'.length) || profileLink;
|
||||
if (!/^[A-Za-z0-9_]{1,15}$/.test(handle)) return null;
|
||||
// Labelled layout: the display name is the first text that is not the @handle. Icon-only: none.
|
||||
const texts = [...button.querySelectorAll('span')]
|
||||
.filter(span => !span.children.length)
|
||||
.map(span => (span.textContent ?? '').trim())
|
||||
.filter(text => text && !text.startsWith('@'));
|
||||
const src = button.querySelector<HTMLImageElement>('img[src^="https://pbs.twimg.com/profile_images/"]')?.src ?? null;
|
||||
// X's small variant is 48 px; the 96 px one stays sharp at the switcher's sizes.
|
||||
const avatar = src ? src.replace(/_(normal|mini|bigger)(\.\w+)$/, '_x96$2') : null;
|
||||
return { handle, name: texts[0] ?? '', avatar };
|
||||
}
|
||||
|
||||
export function installAccountReport(win: Window, invoke?: Invoke) {
|
||||
return installCore(win, { read: readAccount, signedOut: root => !!root.querySelector(SIGNED_OUT) }, invoke);
|
||||
}
|
||||
162
apps/desktop/src/inject/alerts.ts
Normal file
162
apps/desktop/src/inject/alerts.ts
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
// Keyword alerts: the owner's keywords are matched against tweets in timeline/search/detail
|
||||
// responses X's own UI already fetched (passive, same tap discipline as media/tap.ts). A match is
|
||||
// reported to native code, which checks it again, dedupes, rate limits and shows a local OS
|
||||
// notification. Nothing leaves the machine and no request is ever made by this module.
|
||||
import { isTappedUrl } from './media/parse.ts';
|
||||
import { addTap } from './netHub.ts';
|
||||
|
||||
export type SeenTweet = { tweetId: string; author: string; text: string };
|
||||
export type KeywordHit = SeenTweet & { keyword: string };
|
||||
type Invoke = (command: 'keyword_alert', args: { hit: KeywordHit }) => Promise<unknown>;
|
||||
type TapWindow = { fetch: typeof fetch; XMLHttpRequest?: typeof XMLHttpRequest };
|
||||
|
||||
export const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
||||
export const MAX_REPORT_CHARS = 600;
|
||||
const MAX_SEEN = 4_096;
|
||||
|
||||
const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
function tweetText(tweet: Record<string, any>): string {
|
||||
const note = tweet.note_tweet?.note_tweet_results?.result?.text;
|
||||
if (typeof note === 'string') return note;
|
||||
const full = tweet.legacy?.full_text;
|
||||
return typeof full === 'string' ? full : '';
|
||||
}
|
||||
|
||||
function author(tweet: Record<string, any>): string {
|
||||
const user = tweet.core?.user_results?.result;
|
||||
const name = user?.core?.screen_name ?? user?.legacy?.screen_name;
|
||||
return typeof name === 'string' && /^[A-Za-z0-9_]{1,32}$/.test(name) ? name : '';
|
||||
}
|
||||
|
||||
/** GraphQL tweet objects (`__typename: 'Tweet'` or rest_id + legacy.full_text), deduplicated. */
|
||||
export function extractTweets(root: unknown, maxDepth = 64): SeenTweet[] {
|
||||
const out: SeenTweet[] = [];
|
||||
const seen = new Set<string>();
|
||||
const stack: { node: unknown; depth: number }[] = [{ node: root, depth: 0 }];
|
||||
let budget = 50_000;
|
||||
while (stack.length && budget-- > 0) {
|
||||
const { node, depth } = stack.pop()!;
|
||||
if (!node || typeof node !== 'object' || depth > maxDepth) continue;
|
||||
if (record(node)) {
|
||||
const id = typeof node.rest_id === 'string' ? node.rest_id : undefined;
|
||||
if (id && /^\d{1,25}$/.test(id) && record(node.legacy) && typeof node.legacy.full_text === 'string' && !seen.has(id)) {
|
||||
seen.add(id);
|
||||
out.push({ tweetId: id, author: author(node), text: tweetText(node) });
|
||||
}
|
||||
}
|
||||
for (const key in node as object) {
|
||||
const child = (node as Record<string, unknown>)[key];
|
||||
if (child && typeof child === 'object') stack.push({ node: child, depth: depth + 1 });
|
||||
}
|
||||
}
|
||||
return out.reverse();
|
||||
}
|
||||
|
||||
export function normalizeKeywords(input: unknown): string[] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const out = new Set<string>();
|
||||
for (const value of input.slice(0, 32)) {
|
||||
if (typeof value !== 'string') continue;
|
||||
const keyword = value.trim().replace(/\s+/g, ' ').toLowerCase();
|
||||
if (keyword.length >= 2 && keyword.length <= 64) out.add(keyword);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** First configured keyword contained in the text (case-insensitive, whitespace-collapsed). */
|
||||
export function matchKeyword(text: string, keywords: readonly string[]): string | null {
|
||||
const haystack = text.replace(/\s+/g, ' ').toLowerCase();
|
||||
return keywords.find(keyword => haystack.includes(keyword)) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* At most MAX_REPORT_CHARS code points of the whitespace-collapsed text, windowed so the keyword is
|
||||
* included (native code re-checks that the text contains it; long note tweets would otherwise fail).
|
||||
* Slices by code point so a surrogate pair is never split.
|
||||
*/
|
||||
export function reportSnippet(text: string, keyword: string): string {
|
||||
const chars = Array.from(text.replace(/\s+/g, ' ').trim());
|
||||
if (chars.length <= MAX_REPORT_CHARS) return chars.join('');
|
||||
const lower = chars.map(ch => ch.toLowerCase());
|
||||
const needle = Array.from(keyword);
|
||||
let at = 0;
|
||||
for (let i = 0; i + needle.length <= lower.length; i++) {
|
||||
if (needle.every((ch, j) => lower[i + j] === ch)) { at = i; break; }
|
||||
}
|
||||
const start = Math.max(0, Math.min(at - 100, chars.length - MAX_REPORT_CHARS));
|
||||
return chars.slice(start, start + MAX_REPORT_CHARS).join('');
|
||||
}
|
||||
|
||||
/** Passive JSON tap on the shared request hook: the caller gets X's own promise back; only a clone is read. */
|
||||
function installJsonTap(target: TapWindow, onBody: (body: unknown) => void): () => void {
|
||||
return addTap(target, { match: isTappedUrl, maxBytes: MAX_BODY_BYTES, onJson: onBody });
|
||||
}
|
||||
|
||||
// The owner's keywords as this page has them, for Notifications+
|
||||
// (src/areas/notifications/keywordHighlight.ts): read-only there. They are published whether or not
|
||||
// the alert itself is on (`enable`), so the highlight works without the notifications.
|
||||
type Watched = { keywords: readonly string[]; listeners: Set<() => void> };
|
||||
const watched = new WeakMap<object, Watched>();
|
||||
const watchedOf = (target: object) => watched.get(target) ?? watched.set(target, { keywords: [], listeners: new Set() }).get(target)!;
|
||||
|
||||
/** The owner's alert keywords as this page has them (normalized: lower case, single spaces). */
|
||||
export const alertKeywords = (target: object): readonly string[] => watched.get(target)?.keywords ?? [];
|
||||
|
||||
/** Calls `listener` whenever the keywords change. Returns the disposer. */
|
||||
export function onAlertKeywords(target: object, listener: () => void): () => void {
|
||||
const entry = watchedOf(target);
|
||||
entry.listeners.add(listener);
|
||||
return () => { entry.listeners.delete(listener); };
|
||||
}
|
||||
|
||||
function publishKeywords(target: object, keywords: readonly string[]) {
|
||||
const entry = watchedOf(target);
|
||||
entry.keywords = keywords;
|
||||
for (const listener of [...entry.listeners]) {
|
||||
try { listener(); } catch (error) { console.error('[wayBetter for X] keyword listener failed', error); }
|
||||
}
|
||||
}
|
||||
|
||||
export type AlertsHandle = {
|
||||
set(keywords: unknown): void;
|
||||
/** The alert itself (the `notifications.keywordAlerts` flag): off, nothing is read and nothing reported. */
|
||||
enable(on: boolean): void;
|
||||
ingest(body: unknown): void;
|
||||
dispose(): void;
|
||||
};
|
||||
|
||||
/** The tap exists only while the alert is on and at least one keyword is configured. */
|
||||
export function installKeywordAlerts(target: TapWindow, invoke: Invoke | undefined): AlertsHandle {
|
||||
let keywords: string[] = [];
|
||||
let on = true;
|
||||
let untap: (() => void) | null = null;
|
||||
const reported = new Set<string>();
|
||||
const sync = () => {
|
||||
const wanted = on && keywords.length > 0;
|
||||
if (wanted && !untap) untap = installJsonTap(target, ingest);
|
||||
else if (!wanted && untap) { untap(); untap = null; }
|
||||
};
|
||||
const ingest = (body: unknown) => {
|
||||
if (!on || !keywords.length || !invoke) return;
|
||||
for (const tweet of extractTweets(body)) {
|
||||
if (reported.has(tweet.tweetId)) continue;
|
||||
const keyword = matchKeyword(tweet.text, keywords);
|
||||
if (!keyword) continue;
|
||||
reported.add(tweet.tweetId);
|
||||
if (reported.size > MAX_SEEN) reported.delete(reported.values().next().value!);
|
||||
const hit: KeywordHit = { keyword, tweetId: tweet.tweetId, author: tweet.author, text: reportSnippet(tweet.text, keyword) };
|
||||
invoke('keyword_alert', { hit }).catch(() => {});
|
||||
}
|
||||
};
|
||||
return {
|
||||
set(value) {
|
||||
keywords = normalizeKeywords(value);
|
||||
publishKeywords(target, keywords);
|
||||
sync();
|
||||
},
|
||||
enable(value) { on = value; sync(); },
|
||||
ingest,
|
||||
dispose() { untap?.(); untap = null; keywords = []; publishKeywords(target, keywords); },
|
||||
};
|
||||
}
|
||||
165
apps/desktop/src/inject/column.ts
Normal file
165
apps/desktop/src/inject/column.ts
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
// Power User Mode, X side: how an X tab becomes a narrow deck column. The mechanism (hide chrome,
|
||||
// fill width, density, filters, unread tracking) is the wayBetter runtime's column module; which
|
||||
// parts of x.com are chrome, what a post is and how its id reads are here. Nothing here requests
|
||||
// anything; the only click is selecting X's own For you / Following tab on a home column
|
||||
// (navigation only, like the `followingTimelineDefault` feature).
|
||||
|
||||
import './xSite.ts';
|
||||
import {
|
||||
buildColumnCss as buildCss,
|
||||
installColumnMode,
|
||||
type ColumnConfig,
|
||||
type ColumnDensity,
|
||||
type ColumnHandle,
|
||||
type ColumnSite,
|
||||
type ItemKind,
|
||||
} from '../../../../waybetter/packages/runtime/src/column.ts';
|
||||
|
||||
export type { ColumnHandle };
|
||||
|
||||
const PRIMARY = '[data-testid="primaryColumn"]';
|
||||
const TWEET = 'article[data-testid="tweet"]';
|
||||
const NOTIFICATION = 'article[data-testid="notification"]';
|
||||
const ROOT = 'html[data-wb-column]';
|
||||
|
||||
const STATUS = /\/status\/(\d{1,25})(?:[/?#]|$)/;
|
||||
|
||||
/** A small stable hash for items without a post link (e.g. "liked your post" notifications). */
|
||||
function hash(text: string): string {
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
/** Text X renders for an item, without times and without what plugins add later (their elements'
|
||||
* classes start with `bt-`, or they carry `data-bt-*`), so an item's id does not change under it. */
|
||||
function stableText(item: Element): string {
|
||||
const doc = item.ownerDocument;
|
||||
const walker = doc.createTreeWalker(item, 4 /* NodeFilter.SHOW_TEXT */);
|
||||
const parts: string[] = [];
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
const parent = node.parentElement;
|
||||
if (parent?.closest('time, [class^="bt-"], [class*=" bt-"], [data-bt-exact]')) continue;
|
||||
parts.push(node.nodeValue ?? '');
|
||||
}
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/** Pure over the DOM: a post's id from its timestamp link, else any status link; notifications by text. */
|
||||
export function xItemId(item: Element): string | null {
|
||||
const time = item.querySelector('a[href*="/status/"] time')?.closest('a');
|
||||
const href = time?.getAttribute('href') ?? item.querySelector('a[href*="/status/"]')?.getAttribute('href') ?? '';
|
||||
const id = STATUS.exec(href)?.[1];
|
||||
if (id) return id;
|
||||
if (item.matches(NOTIFICATION)) {
|
||||
// Who (profile links) and what, without numbers: "3h" and plugin timestamps change as time
|
||||
// passes; "liked 3 of your posts" becoming 4 is new activity anyway.
|
||||
const people = [...item.querySelectorAll('a[href^="/"]')].map(a => a.getAttribute('href')).filter(href => href && !href.includes('/status/')).slice(0, 8).join('|');
|
||||
const text = stableText(item).replace(/\d+/g, '#').replace(/\s+/g, ' ').trim().slice(0, 240);
|
||||
return text || people ? `n${hash(`${people}|${text}`)}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Pure over the DOM: reply / repost / media, read from what X renders on the post. */
|
||||
export function xItemKind(item: Element): ItemKind {
|
||||
const context = item.querySelector('[data-testid="socialContext"]')?.textContent ?? '';
|
||||
const repost = /\b(reposted|retweeted)\b/i.test(context);
|
||||
// X prints "Replying to @handle" above the text of a reply shown outside its thread.
|
||||
const reply = [...item.querySelectorAll('div')].some(div => div.children.length <= 2 && /^Replying to\b/.test((div.textContent ?? '').trim()));
|
||||
const media = !!item.querySelector('[data-testid="tweetPhoto"], [data-testid="videoPlayer"], [data-testid="videoComponent"], [data-testid="card.layoutLarge.media"], [data-testid="card.layoutSmall.media"]');
|
||||
return { reply, repost, media };
|
||||
}
|
||||
|
||||
/** The post's text, then its author on the next line: keywords match either, `/^…/` the text. */
|
||||
export function xItemText(item: Element): string {
|
||||
const parts = [item.querySelector('[data-testid="tweetText"]')?.textContent, item.querySelector('[data-testid="User-Name"]')?.textContent];
|
||||
const text = parts.filter(Boolean).join('\n');
|
||||
return text || (item.textContent ?? '');
|
||||
}
|
||||
|
||||
/** X's "Show 12 posts" row at the top of a timeline: posts it has but has not rendered yet. */
|
||||
export function xPendingCount(doc: ParentNode): number {
|
||||
for (const button of doc.querySelectorAll(`${PRIMARY} [data-testid="cellInnerDiv"] button, ${PRIMARY} [data-testid="cellInnerDiv"] [role="button"]`)) {
|
||||
const match = /^Show ([\d.,]+) (?:new )?(?:posts?|Tweets?)$/i.exec((button.textContent ?? '').trim());
|
||||
if (match) return Number(match[1]!.replace(/[.,]/g, '')) || 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Density CSS; every rule is scoped to a column (`html[data-wb-column]`). */
|
||||
export function xColumnCss(density: ColumnDensity): string {
|
||||
const compact = `${ROOT}[data-wb-density="compact"]`;
|
||||
return [
|
||||
// X's own main row keeps a max width and centers; in a column it simply fills.
|
||||
`${ROOT} main[role="main"] { align-items: stretch !important; }`,
|
||||
`${ROOT} main[role="main"] > div, ${ROOT} main[role="main"] > div > div { width: 100% !important; max-width: none !important; }`,
|
||||
`${ROOT} ${PRIMARY} { border-left-width: 0 !important; border-right-width: 0 !important; }`,
|
||||
`${ROOT} body { overflow-x: hidden !important; }`,
|
||||
// Unread posts: a quiet accent bar on the left edge until they are scrolled into view.
|
||||
`${ROOT} [data-wb-unread] { box-shadow: inset 3px 0 0 var(--wb-accent, rgb(29, 155, 240)) !important; }`,
|
||||
`@media (prefers-reduced-motion: no-preference) { ${ROOT} [data-wb-unread] { transition: box-shadow .4s ease; } }`,
|
||||
...(density === 'compact' ? [
|
||||
// Plugin extras that need a wide row (exact timestamps, copy as Markdown) stay out of compact columns.
|
||||
`${compact} .bt-exact-time, ${compact} .bt-copy-md { display: none !important; }`,
|
||||
`${compact} ${TWEET} > div > div > div:last-child, ${compact} ${NOTIFICATION} > div > div > div:last-child { padding-top: 6px !important; padding-bottom: 2px !important; }`,
|
||||
`${compact} ${TWEET} [data-testid="tweetText"] { font-size: 14px !important; line-height: 19px !important; }`,
|
||||
`${compact} ${TWEET} [role="group"] { margin-top: 2px !important; max-width: none !important; }`,
|
||||
`${compact} ${PRIMARY} [role="tablist"] [role="tab"] { min-height: 40px !important; }`,
|
||||
] : []),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export const X_COLUMN: ColumnSite = {
|
||||
prefix: 'wb',
|
||||
keep: PRIMARY,
|
||||
hide: [
|
||||
// X's left rail (with its Post button), right column, narrow-layout bars and floating docks.
|
||||
'header[role="banner"]',
|
||||
'[data-testid="sidebarColumn"]',
|
||||
'[data-testid="BottomBar"]',
|
||||
'[data-testid="TopNavBar"]',
|
||||
'[data-testid="DMDrawer"]',
|
||||
'[data-testid="GrokDrawer"]',
|
||||
'[data-testid="chat-drawer-root"]',
|
||||
// Our own fallback button (the column header opens wayBetter).
|
||||
'#better-twttr-fab',
|
||||
],
|
||||
sourceHide: [
|
||||
// The page title row ("Notifications", "Bookmarks") the column header repeats; its tabs stay.
|
||||
`${PRIMARY} > div > div:first-child > div:first-child > div:first-child:not(:last-child)`,
|
||||
// The inline "What's happening?" composer on Home (with its separator); the deck's compose dock
|
||||
// posts instead.
|
||||
`${PRIMARY} > div > div:has([data-testid="tweetTextarea_0_label"])`,
|
||||
`${PRIMARY} > div > div:has([data-testid="tweetTextarea_0_label"]) + div:empty`,
|
||||
],
|
||||
itemSelector: `${TWEET}, ${NOTIFICATION}`,
|
||||
container: item => item.closest('[data-testid="cellInnerDiv"]') ?? item,
|
||||
itemId: xItemId,
|
||||
itemKind: xItemKind,
|
||||
itemText: xItemText,
|
||||
pendingCount: xPendingCount,
|
||||
css: xColumnCss,
|
||||
prepare(doc, config: ColumnConfig) {
|
||||
if (config.kind !== 'home' && config.kind !== 'following') return true;
|
||||
if (doc.location?.pathname !== '/home') return true;
|
||||
const tabs = doc.querySelectorAll<HTMLElement>(`${PRIMARY} [role="tablist"] [role="tab"]`);
|
||||
const target = tabs[config.kind === 'following' ? 1 : 0];
|
||||
if (!target) return false;
|
||||
if (target.getAttribute('aria-selected') !== 'true') target.click();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
export function buildXColumnCss(density: ColumnDensity): string {
|
||||
return buildCss(X_COLUMN, density);
|
||||
}
|
||||
|
||||
type Invoke = (command: string, args: Record<string, unknown>) => Promise<unknown>;
|
||||
|
||||
/** The column module for this X tab; unread counts go to native code as a number (`tab_report`). */
|
||||
export function installXColumn(win: Window, invoke?: Invoke): ColumnHandle {
|
||||
return installColumnMode(win as Window & typeof globalThis, X_COLUMN, {
|
||||
onUnread: count => { invoke?.('tab_report', { report: { unread: count } }).catch(() => {}); },
|
||||
});
|
||||
}
|
||||
32
apps/desktop/src/inject/domHub.ts
Normal file
32
apps/desktop/src/inject/domHub.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
// X adapter over the wayBetter DOM hub (one MutationObserver and one animation frame per page for
|
||||
// every DOM feature; see waybetter/packages/runtime/src/domHub.ts). Features marked `offOnChat` do
|
||||
// not run on chat/DM pages (XChat is WASM heavy and has no posts, composers or profiles for them).
|
||||
|
||||
import './xSite.ts';
|
||||
import {
|
||||
isHeavyPath,
|
||||
watchDom as watchCore,
|
||||
type DomWatch as CoreDomWatch,
|
||||
type DomWatchHandle,
|
||||
type DomWindow,
|
||||
} from '../../../../waybetter/packages/runtime/src/domHub.ts';
|
||||
|
||||
export type { DomWatchHandle };
|
||||
export type DomWatch = Omit<CoreDomWatch, 'offOnHeavy'> & {
|
||||
/** Skip on /i/chat and /messages. */
|
||||
offOnChat?: boolean;
|
||||
};
|
||||
|
||||
export function isChatPath(pathname: string): boolean {
|
||||
return isHeavyPath(pathname);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `run` in the next animation frame after body mutations of the watched kinds (child list
|
||||
* always), or whenever `schedule()` is called (scroll, popstate, input, ...). Several calls in one
|
||||
* frame run it once.
|
||||
*/
|
||||
export function watchDom(win: DomWindow, run: () => void, opts: DomWatch = {}): DomWatchHandle {
|
||||
const { offOnChat, ...rest } = opts;
|
||||
return watchCore(win, run, offOnChat === undefined ? rest : { ...rest, offOnHeavy: offOnChat });
|
||||
}
|
||||
202
apps/desktop/src/inject/drafts.ts
Normal file
202
apps/desktop/src/inject/drafts.ts
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
// "Drafts" button in X's composer toolbar. Clicking it only asks native code (the narrow
|
||||
// `drafts_picker_open` command) to show the drafts popover right under the button: a local
|
||||
// webview layered over this tab, so X stays visible. The page reports the button's rect in its own
|
||||
// viewport and never reads the vault; the popover lists drafts and native code inserts the chosen
|
||||
// text into the marked composer.
|
||||
//
|
||||
// On a post page, an empty reply composer also asks `drafts_hint` (yes/no, for the webview's own
|
||||
// URL) and shows a "Continue your draft?" chip when a captured draft for this conversation exists.
|
||||
import { t } from './i18n.ts';
|
||||
import { COMPOSER_SELECTOR, identifyComposer, isExcludedComposerPath } from '../observer/composer.ts';
|
||||
import { watchDom } from './domHub.ts';
|
||||
|
||||
export const TOOLBAR_SELECTOR = '[data-testid="toolBar"]';
|
||||
export const BUTTON_ATTR = 'data-bt-drafts-button';
|
||||
export const HINT_ATTR = 'data-bt-drafts-hint';
|
||||
/** Must match `compose::TARGET_ATTRIBUTE` in src-tauri. */
|
||||
export const TARGET_ATTR = 'data-bt-draft-target';
|
||||
const ICON = 'M6 3h9l5 5v12a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zm8 1.5V9h4.5M8 13h8M8 17h5';
|
||||
const FALLBACK_TINT = 'rgb(29, 155, 240)';
|
||||
/** Scrolls this soon after opening are layout settling, not the user moving away. */
|
||||
const SCROLL_GRACE_MS = 250;
|
||||
/** How long a hint answer for a post page is reused before asking again. */
|
||||
const HINT_TTL_MS = 30_000;
|
||||
|
||||
/** `x`/`y`: the anchor's left and bottom edge in the tab's viewport; `width`/`height`: its size. */
|
||||
export type PickerRequest = { kind: 'post' | 'reply' | 'quote' | null; x: number; y: number; width?: number; height?: number };
|
||||
type Invoke = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||
|
||||
/** The single composer editor that shares a composer area with this toolbar, if any. */
|
||||
export function editorForToolbar(toolbar: Element): HTMLElement | null {
|
||||
let area: Element | null = toolbar.parentElement;
|
||||
for (let depth = 0; area && depth < 40; depth++, area = area.parentElement) {
|
||||
const editors = area.querySelectorAll<HTMLElement>(COMPOSER_SELECTOR);
|
||||
if (editors.length === 1) return editors[0];
|
||||
if (editors.length > 1) return null;
|
||||
if (area.matches('main,body,[data-testid="primaryColumn"]')) return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The request for an anchor element's viewport rect (whole CSS px). */
|
||||
export function anchorRequest(rect: { left: number; top: number; width: number; height: number }, kind: PickerRequest['kind']): PickerRequest {
|
||||
return { kind, x: Math.round(rect.left), y: Math.round(rect.top + rect.height), width: Math.round(rect.width), height: Math.round(rect.height) };
|
||||
}
|
||||
|
||||
/** A post page, where an inline reply composer belongs to exactly one conversation. */
|
||||
export function isPostPath(pathname: string): boolean {
|
||||
return /^\/(?!i\/)[^/]+\/status\/\d+(?:\/|$)/.test(pathname);
|
||||
}
|
||||
|
||||
/** `rgb(r, g, b)` / `rgba(r, g, b, a)` with the given alpha; the fallback tint for anything else. */
|
||||
export function withAlpha(color: string, alpha: number): string {
|
||||
const match = /^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/.exec(color);
|
||||
const [r, g, b] = match ? match.slice(1, 4) : ['29', '155', '240'];
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
}
|
||||
|
||||
/** X's own icon color in this toolbar (it follows the user's accent), so the button fits in. */
|
||||
function toolbarTint(win: Window, row: Element): string {
|
||||
const icon = row.querySelector('svg');
|
||||
const color = icon ? win.getComputedStyle(icon).color : '';
|
||||
return /^rgba?\(/.test(color) ? color : FALLBACK_TINT;
|
||||
}
|
||||
|
||||
function makeButton(doc: Document, tint: string, onClick: (anchor: HTMLElement) => void): HTMLElement {
|
||||
const button = doc.createElement('button');
|
||||
button.type = 'button';
|
||||
button.setAttribute(BUTTON_ATTR, '');
|
||||
button.setAttribute('aria-label', t('x.drafts.button'));
|
||||
button.setAttribute('aria-haspopup', 'dialog');
|
||||
button.title = t('x.drafts.title');
|
||||
button.style.cssText = `background:none;border:0;padding:0;margin:0 2px;width:34px;height:34px;min-width:34px;cursor:pointer;color:${tint};display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;transition:background-color .15s ease;outline-offset:1px;`;
|
||||
button.innerHTML = `<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${ICON}"/></svg>`;
|
||||
const hover = withAlpha(tint, 0.1);
|
||||
button.addEventListener('mouseenter', () => { button.style.backgroundColor = hover; });
|
||||
button.addEventListener('mouseleave', () => { button.style.backgroundColor = 'transparent'; });
|
||||
button.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onClick(button);
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
function makeHint(doc: Document, tint: string, onClick: (anchor: HTMLElement) => void): HTMLElement {
|
||||
const chip = doc.createElement('button');
|
||||
chip.type = 'button';
|
||||
chip.setAttribute(HINT_ATTR, '');
|
||||
chip.setAttribute('aria-haspopup', 'dialog');
|
||||
chip.title = t('x.drafts.hintTitle');
|
||||
chip.style.cssText = `display:inline-flex;align-items:center;gap:6px;height:26px;min-width:0;flex:0 1 auto;margin:0 4px;padding:0 10px 0 8px;border-radius:9999px;border:1px solid ${withAlpha(tint, 0.35)};background:${withAlpha(tint, 0.1)};color:${tint};font:600 13px/1 inherit;font-family:inherit;white-space:nowrap;overflow:hidden;cursor:pointer;transition:background-color .15s ease,opacity .2s ease;`;
|
||||
const dot = doc.createElement('span');
|
||||
dot.style.cssText = `width:6px;height:6px;flex:none;border-radius:50%;background:${tint};box-shadow:0 0 0 3px ${withAlpha(tint, 0.2)};`;
|
||||
const label = doc.createElement('span');
|
||||
label.textContent = t('x.drafts.hint');
|
||||
label.style.cssText = 'overflow:hidden;text-overflow:ellipsis;';
|
||||
chip.append(dot, label);
|
||||
chip.addEventListener('mouseenter', () => { chip.style.backgroundColor = withAlpha(tint, 0.18); });
|
||||
chip.addEventListener('mouseleave', () => { chip.style.backgroundColor = withAlpha(tint, 0.1); });
|
||||
chip.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onClick(chip);
|
||||
chip.remove();
|
||||
});
|
||||
return chip;
|
||||
}
|
||||
|
||||
export type DraftsButtonHandle = { rescan(): void; dispose(): void };
|
||||
|
||||
export function installDraftsButton(win: Window, invoke: Invoke | undefined): DraftsButtonHandle {
|
||||
const doc = win.document;
|
||||
let active = true;
|
||||
/** Post path -> hint answer (pending or settled), so X's re-renders do not ask again. */
|
||||
const hints = new Map<string, { at: number; answer: Promise<boolean> }>();
|
||||
let stopWatching: (() => void) | null = null;
|
||||
|
||||
// While the popover is open, scrolling X moves the button away from it: close the popover. The
|
||||
// page gets focus back when the popover closes for any other reason, which ends the watch.
|
||||
const watchWhileOpen = () => {
|
||||
stopWatching?.();
|
||||
const openedAt = win.performance.now();
|
||||
const onScroll = () => {
|
||||
if (win.performance.now() - openedAt < SCROLL_GRACE_MS) return;
|
||||
stop();
|
||||
invoke?.('drafts_popover_dismiss').catch(() => {});
|
||||
};
|
||||
const stop = () => {
|
||||
win.removeEventListener('scroll', onScroll, true);
|
||||
win.removeEventListener('focus', stop);
|
||||
win.clearTimeout(timer);
|
||||
if (stopWatching === stop) stopWatching = null;
|
||||
};
|
||||
const timer = win.setTimeout(stop, 10 * 60_000);
|
||||
win.addEventListener('scroll', onScroll, { capture: true, passive: true });
|
||||
win.addEventListener('focus', stop);
|
||||
stopWatching = stop;
|
||||
};
|
||||
|
||||
const open = (anchor: HTMLElement) => {
|
||||
const toolbar = anchor.closest(TOOLBAR_SELECTOR);
|
||||
const editor = toolbar ? editorForToolbar(toolbar) : null;
|
||||
if (!editor || !invoke) return;
|
||||
for (const marked of doc.querySelectorAll(`[${TARGET_ATTR}]`)) marked.removeAttribute(TARGET_ATTR);
|
||||
editor.setAttribute(TARGET_ATTR, '');
|
||||
const context = identifyComposer(editor, win.location);
|
||||
invoke('drafts_picker_open', { request: anchorRequest(anchor.getBoundingClientRect(), context?.kind ?? null) })
|
||||
.then(watchWhileOpen)
|
||||
.catch(error => console.warn('[wayBetter for X] drafts popover unavailable', error));
|
||||
};
|
||||
|
||||
const offerHint = (row: Element, button: HTMLElement, editor: HTMLElement, tint: string) => {
|
||||
const path = win.location.pathname;
|
||||
if (!invoke || !isPostPath(path) || editor.textContent?.trim() || row.querySelector(`[${HINT_ATTR}]`)) return;
|
||||
const now = win.performance.now();
|
||||
let cached = hints.get(path);
|
||||
if (!cached || now - cached.at > HINT_TTL_MS) {
|
||||
cached = { at: now, answer: invoke('drafts_hint').then(value => value === true, () => false) };
|
||||
hints.set(path, cached);
|
||||
}
|
||||
void cached.answer.then(yes => {
|
||||
// Still the same page, still empty, still on screen, still no chip.
|
||||
if (!yes || !active || win.location.pathname !== path || !button.isConnected || editor.textContent?.trim() || row.querySelector(`[${HINT_ATTR}]`)) return;
|
||||
const chip = makeHint(doc, tint, open);
|
||||
button.after(chip);
|
||||
// Typing means the user is writing something new here: the offer goes away.
|
||||
editor.addEventListener('input', () => chip.remove(), { once: true });
|
||||
});
|
||||
};
|
||||
|
||||
const scan = () => {
|
||||
if (!active || isExcludedComposerPath(win.location.pathname)) return;
|
||||
for (const toolbar of doc.querySelectorAll(TOOLBAR_SELECTOR)) {
|
||||
const editor = editorForToolbar(toolbar);
|
||||
if (!editor) continue;
|
||||
// X's icon row (media, GIF, poll, emoji, ...) is the toolbar's first flex child.
|
||||
const row = toolbar.querySelector('[role="tablist"]') ?? toolbar.firstElementChild ?? toolbar;
|
||||
let button = toolbar.querySelector<HTMLElement>(`[${BUTTON_ATTR}]`);
|
||||
if (!button) {
|
||||
button = makeButton(doc, toolbarTint(win, row), open);
|
||||
row.appendChild(button);
|
||||
}
|
||||
offerHint(row, button, editor, button.style.color || FALLBACK_TINT);
|
||||
}
|
||||
};
|
||||
// Shared body observer + frame (domHub.ts); composers on chat pages are excluded anyway.
|
||||
const watch = watchDom(win as Window & typeof globalThis, scan, { offOnChat: true });
|
||||
const start = () => { if (!active || !doc.body) return; scan(); };
|
||||
if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', start, { once: true });
|
||||
else start();
|
||||
return {
|
||||
rescan: scan,
|
||||
dispose() {
|
||||
active = false;
|
||||
doc.removeEventListener('DOMContentLoaded', start);
|
||||
watch.dispose();
|
||||
stopWatching?.();
|
||||
for (const node of doc.querySelectorAll(`[${BUTTON_ATTR}],[${HINT_ATTR}]`)) node.remove();
|
||||
for (const marked of doc.querySelectorAll(`[${TARGET_ATTR}]`)) marked.removeAttribute(TARGET_ATTR);
|
||||
},
|
||||
};
|
||||
}
|
||||
270
apps/desktop/src/inject/entry.tsx
Normal file
270
apps/desktop/src/inject/entry.tsx
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
// Injected into X tabs at document start. Extends X in place, BetterDiscord-style: a
|
||||
// "wayBetter" item in X's left navigation opens the wayBetter tab in the app shell, Control
|
||||
// Panel-style features restyle X, and `window.wayBetter` (aliases `BetterTwttr`, `XWorkspace`) is the JS plugin runtime.
|
||||
//
|
||||
// What every wayBetter runtime does the same way is the framework's (waybetter/packages/runtime:
|
||||
// siteRuntime.ts composes the runtime object, its window names, the queued native deliveries, the
|
||||
// flag-controlled parts and the palette command report; panelButton.ts keeps the way into the
|
||||
// panel on the page). This file is X's: which parts exist, X's own members (alerts, fixes)
|
||||
// and how the "wayBetter" item joins X's navigation.
|
||||
import { installFeatures, type FeatureConfig } from './features';
|
||||
import { ALL_MODULES } from '../areas/modules';
|
||||
import { surfacesOf } from '../areas/surfaces';
|
||||
import { X_TABLE } from '../areas/table';
|
||||
import { createFeatureRegistry, type FeatureRegistry, type HotfixData } from '../../../../waybetter/packages/runtime/src/featureModules.ts';
|
||||
import { effectiveFlags, tableDefaults, type Flags } from '../../../../waybetter/packages/runtime/src/featureTable.ts';
|
||||
import { installClickGuard, installMutationGate } from '../fixes/mutationGate';
|
||||
import type { LaneStats } from '../fixes/mutationGate/lanes';
|
||||
import type { LiveStats } from '../fixes/mutationGate';
|
||||
import { LOGO_PNG } from '../ui/logo-data';
|
||||
import { installMediaDownload } from './media';
|
||||
import { installDraftsButton } from './drafts';
|
||||
import { installKeywordAlerts } from './alerts';
|
||||
import { installUserInfo } from './userInfo';
|
||||
import { installTheme, type ThemeHandle } from './theme';
|
||||
import { loadBundledFonts, provideFonts } from './fonts';
|
||||
import { installHomeTabMemory, installKeepPosition, installNewPostsPill, installScrollRestore } from '../fixes/timeline';
|
||||
import { installBadgeFix } from '../fixes/badge';
|
||||
import { installChatButtonFix } from '../fixes/chatButton';
|
||||
import { installComposerRestore } from '../fixes/composerRestore';
|
||||
import { installFollowingChronological } from '../fixes/followingOrder';
|
||||
import { installUploadRetry } from '../fixes/uploadRetry';
|
||||
import { X_PERMISSION_GATES, createPluginApi, type PluginApi } from './pluginApi';
|
||||
import { createPluginContext } from '../../../../waybetter/packages/runtime/src/permissions.ts';
|
||||
import { installPanelButton } from '../../../../waybetter/packages/runtime/src/panelButton.ts';
|
||||
import { createFeatureFlags, installSiteRuntime, pageInvoke, type FlagInstaller, type SiteRuntime } from '../../../../waybetter/packages/runtime/src/siteRuntime.ts';
|
||||
import { installPaneNav } from './paneNav';
|
||||
import { X_BOTTOM_BAR_SELECTOR, X_OVERLAY_SELECTOR, isMediaViewer } from './fabPlacement';
|
||||
import { installLinkRouting } from './linkRouting';
|
||||
import { installAccountReport } from './accountReport';
|
||||
import { installXColumn, type ColumnHandle } from './column';
|
||||
import { strings, t } from './i18n';
|
||||
import { X_SITE } from './xSite';
|
||||
import { installPageLangReport } from '../../../../waybetter/packages/runtime/src/pageLang.ts';
|
||||
import { installXStringPacks, type XStringPacks } from './stringPacks';
|
||||
|
||||
/** X's own members of the runtime, next to the framework's (`SiteRuntime`). */
|
||||
type XMembers = {
|
||||
/** Themes X: `{ preset, accent, overrides, themes }` (declarative themes, see src/inject/themeSpec.ts). */
|
||||
theme: ThemeHandle;
|
||||
/** Native code hands over the owner's alert keywords (empty = none). */
|
||||
alerts: { set(keywords: unknown): void };
|
||||
/** Kill switch for the like/follow fix: restores the original fetch and removes the click guard. */
|
||||
fixes: { disable(): void; stats(): (LaneStats & LiveStats) | null };
|
||||
/** String packs (src/inject/stringPacks.ts): the hook's self-check and what each pack did. */
|
||||
stringPacks: XStringPacks;
|
||||
};
|
||||
type Runtime = SiteRuntime<PluginApi> & XMembers;
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
wayBetter?: Runtime;
|
||||
BetterTwttr?: Runtime;
|
||||
XWorkspace?: Runtime;
|
||||
__btFeatures?: Partial<FeatureConfig>;
|
||||
__btAlerts?: unknown;
|
||||
__btTheme?: unknown;
|
||||
__wbFonts?: unknown[];
|
||||
__btPane?: unknown;
|
||||
__btLinks?: unknown;
|
||||
__btColumn?: unknown;
|
||||
__wbI18n?: unknown;
|
||||
/** The signed hotfix data (selector overrides, kill flags): native code sets it, frozen. */
|
||||
__btHotfix?: HotfixData;
|
||||
__TAURI_INTERNALS__?: { invoke(cmd: string, args?: Record<string, unknown>): Promise<unknown> };
|
||||
}
|
||||
}
|
||||
|
||||
const NAV_ID = 'AppTabBar_BetterTwttr';
|
||||
const FAB_ID = 'better-twttr-fab';
|
||||
const LABEL = X_SITE.product;
|
||||
|
||||
function install() {
|
||||
if (window.top !== window || location.origin !== 'https://x.com' || window.BetterTwttr) return;
|
||||
|
||||
// Before X's scripts: a string pack has to be in place when X registers its strings.
|
||||
const stringPacks = installXStringPacks(window);
|
||||
const featureHandle = installFeatures(window);
|
||||
// This runtime only ships inside the app's X tabs; automated test browsers have no bridge, and
|
||||
// the features that need it stay off there.
|
||||
const invoke = pageInvoke(window, LABEL);
|
||||
|
||||
// Flag-controlled fixes and tweaks: installed on enable, disposed on disable. The first ones wrap
|
||||
// fetch like the mutation gate: installed at document start, before X's bundle runs.
|
||||
let laneStats: LaneStats | null = null;
|
||||
let liveStats: LiveStats | null = null;
|
||||
const installers: FlagInstaller<Flags>[] = [
|
||||
['fixLikeFollow', () => {
|
||||
const gate = installMutationGate(window);
|
||||
laneStats = gate.lanes.stats;
|
||||
liveStats = gate.live;
|
||||
const guard = installClickGuard(window);
|
||||
return { dispose() { gate.dispose(); guard.dispose(); laneStats = null; liveStats = null; } };
|
||||
}],
|
||||
['mediaDownload', () => installMediaDownload(window)],
|
||||
['composerDrafts', () => installDraftsButton(window, invoke as Parameters<typeof installDraftsButton>[1])],
|
||||
['followingChronological', () => installFollowingChronological(window)],
|
||||
['fixMediaUpload', () => installUploadRetry(window, message => window.BetterTwttr?.api.toast(message, 9000))],
|
||||
['fixScrollRestore', () => installScrollRestore(window)],
|
||||
['fixTimelineJump', () => installKeepPosition(window)],
|
||||
['fixNewPostsPill', () => installNewPostsPill(window)],
|
||||
['fixHomeTab', () => installHomeTabMemory(window)],
|
||||
['fixNotificationBadge', () => installBadgeFix(window)],
|
||||
['fixChatButton', () => installChatButtonFix(window)],
|
||||
['composerRestorePrompt', () => installComposerRestore(window, invoke as Parameters<typeof installComposerRestore>[1])],
|
||||
];
|
||||
// A deck column may override some flags (allow-listed natively, see src-tauri/src/column.rs): the
|
||||
// page runs with the global flags merged with the column's (the framework's feature flags).
|
||||
// Every flag comes from the one table (src/areas/table.ts): the 46 that were Tweaks, the features
|
||||
// of the area plugins and each area's switch. An area that is off turns off what it owns.
|
||||
const DEFAULTS = tableDefaults(X_TABLE);
|
||||
let registry: FeatureRegistry<PluginApi> | null = null;
|
||||
const flags = createFeatureFlags<Flags>({
|
||||
defaults: DEFAULTS,
|
||||
label: LABEL,
|
||||
installers,
|
||||
document,
|
||||
resolve: all => effectiveFlags(X_TABLE, all),
|
||||
apply(config) {
|
||||
featureHandle.apply(config as Partial<FeatureConfig>);
|
||||
paneNav.setEnabled(config.singleSplitNav!);
|
||||
// The feature modules (src/areas/*): started and stopped by the registry.
|
||||
registry?.setFlags(config);
|
||||
// Notifications+ holds the keyword alerts: off, nothing is read or reported. The page keeps
|
||||
// the owner's keywords either way (its keyword highlight works without the alert).
|
||||
alerts.enable(config['notifications.keywordAlerts']!);
|
||||
},
|
||||
});
|
||||
|
||||
const alerts = installKeywordAlerts(window, invoke as Parameters<typeof installKeywordAlerts>[1]);
|
||||
alerts.enable(flags.current()['notifications.keywordAlerts']!);
|
||||
// Lazy: its response tap installs on the first `api.users.get()`/`onUpdate()` from a plugin.
|
||||
const users = installUserInfo(window);
|
||||
const paneNav = installPaneNav(window);
|
||||
paneNav.setEnabled(flags.current().singleSplitNav!);
|
||||
const linkRouting = installLinkRouting(window);
|
||||
try { installAccountReport(window, invoke); } catch (error) { console.error(`[${LABEL}] account report failed`, error); }
|
||||
// "Follow X" in Settings → Language: X's own <html lang>, reported only when it changes.
|
||||
try { installPageLangReport(window, invoke); } catch (error) { console.error(`[${LABEL}] language report failed`, error); }
|
||||
|
||||
let column: ColumnHandle | null = null;
|
||||
const setColumn = (config: unknown) => {
|
||||
const columnFlags = config && typeof config === 'object' ? (config as { flags?: unknown }).flags : undefined;
|
||||
if (config || column) {
|
||||
column ??= installXColumn(window, invoke);
|
||||
column.set(config);
|
||||
}
|
||||
flags.setColumnFlags(columnFlags);
|
||||
};
|
||||
|
||||
const theme = installTheme(window, { loadFonts: names => loadBundledFonts(document, names) });
|
||||
// Per-plugin API views for declared @permissions (waybetter runtime permissions.ts).
|
||||
// Each plugin's view binds `api.i18n` to its own strings (`plugin.<file name>.*`).
|
||||
const api = createPluginApi(window, users, theme, strings.source);
|
||||
// The area plugins' feature modules run on the full API (they are the app's own code), each only
|
||||
// while its flag is on and the page is on one of its surfaces.
|
||||
registry = createFeatureRegistry<PluginApi>({
|
||||
win: window,
|
||||
table: X_TABLE,
|
||||
api,
|
||||
label: LABEL,
|
||||
surfaces: () => surfacesOf(location.pathname),
|
||||
message: strings.message,
|
||||
locale: strings.locale,
|
||||
hotfix: () => window.__btHotfix,
|
||||
settled: () => !!document.querySelector('[data-testid="primaryColumn"]'),
|
||||
});
|
||||
for (const module of ALL_MODULES) registry.define(module);
|
||||
registry.setFlags(flags.current());
|
||||
const pluginViews = createPluginContext(api, X_PERMISSION_GATES,
|
||||
(full, id) => ({ i18n: full.i18n.namespace(strings.pluginNamespace(id)) }));
|
||||
const guarded = (what: string, fn: (value: unknown) => void) => (value: unknown) => {
|
||||
try { fn(value); } catch (error) { console.error(`[${LABEL}] ${what} failed`, error); }
|
||||
};
|
||||
const extra: XMembers = {
|
||||
theme,
|
||||
alerts: { set: guarded('keyword alerts', keywords => alerts.set(keywords)) },
|
||||
// `stats()`: read-only lane counters (sent/held/shared/paired/synthesized) for live checks.
|
||||
fixes: { disable: () => flags.set('fixLikeFollow', false), stats: () => (flags.installed('fixLikeFollow') && laneStats && liveStats ? { ...laneStats, ...liveStats } : null) },
|
||||
stringPacks,
|
||||
};
|
||||
const runtime: Runtime = installSiteRuntime<PluginApi, XMembers>({
|
||||
win: window,
|
||||
site: X_SITE,
|
||||
version: '0.3.0',
|
||||
// `wayBetter` is the documented name; `BetterTwttr` and `XWorkspace` stay for existing plugins.
|
||||
aliases: ['XWorkspace'],
|
||||
invoke,
|
||||
plugins: pluginViews,
|
||||
strings,
|
||||
pluginFailed: error => t('x.plugin.failed', { error }),
|
||||
features: flags,
|
||||
theme,
|
||||
fonts: list => provideFonts(document, list),
|
||||
pane: paneNav,
|
||||
links: linkRouting,
|
||||
column: { set: setColumn, markRead: () => column?.markRead(), jumpToUnread: () => column?.jumpToUnread(), unread: () => column?.unread() ?? 0 },
|
||||
extra,
|
||||
queues: [['__btAlerts', extra.alerts.set]],
|
||||
});
|
||||
|
||||
/** Clone X's own "More" nav entry so the item inherits X's current look, then retarget it. */
|
||||
const mountNav = (open: () => void): boolean => {
|
||||
const more = document.querySelector<HTMLElement>('[data-testid="AppTabBar_More_Menu"]');
|
||||
const existing = document.querySelector<HTMLElement>(`[data-testid="${NAV_ID}"]`);
|
||||
// X swaps the nav between icon-only and labelled layouts inside the same nodes; a clone taken
|
||||
// in one layout is stale in the other (centered icon, no label), so re-clone when it changes.
|
||||
const layout = more ? `${more.className}|${more.firstElementChild?.className ?? ''}|${more.firstElementChild?.childElementCount ?? 0}` : '';
|
||||
if (existing && (!more || existing.dataset.btLayout === layout)) return true;
|
||||
existing?.remove();
|
||||
if (!more?.parentElement) return false;
|
||||
const item = more.cloneNode(true) as HTMLElement;
|
||||
item.dataset.btLayout = layout;
|
||||
item.setAttribute('data-testid', NAV_ID);
|
||||
item.setAttribute('aria-label', 'wayBetter');
|
||||
item.removeAttribute('aria-expanded');
|
||||
item.removeAttribute('aria-haspopup');
|
||||
const icon = item.querySelector('svg');
|
||||
if (icon) {
|
||||
// Keep X's icon box size so the item lines up with the native entries.
|
||||
const side = Math.round(more.querySelector('svg')?.getBoundingClientRect().width || 26) || 26;
|
||||
const logo = document.createElement('img');
|
||||
logo.src = LOGO_PNG;
|
||||
logo.alt = '';
|
||||
logo.width = side;
|
||||
logo.height = side;
|
||||
Object.assign(logo.style, { width: `${side}px`, height: `${side}px`, borderRadius: '22%', display: 'block' });
|
||||
icon.replaceWith(logo);
|
||||
}
|
||||
const label = [...item.querySelectorAll('span')].reverse().find(span => span.children.length === 0 && span.textContent?.trim());
|
||||
if (label) label.textContent = 'wayBetter';
|
||||
item.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); open(); }, true);
|
||||
// X's hover tint lives in React state the clone does not have: the pill behind icon + label
|
||||
// takes the text color at 10%, like X's own entries.
|
||||
const pill = item.firstElementChild as HTMLElement | null;
|
||||
if (pill) {
|
||||
item.addEventListener('pointerenter', () => {
|
||||
const [r, g, b] = (getComputedStyle(pill).color.match(/\d+/g) ?? ['231', '233', '234']).map(Number);
|
||||
pill.style.backgroundColor = `rgba(${r}, ${g}, ${b}, 0.1)`;
|
||||
});
|
||||
item.addEventListener('pointerleave', () => { pill.style.backgroundColor = ''; });
|
||||
}
|
||||
more.parentElement.insertBefore(item, more);
|
||||
return true;
|
||||
};
|
||||
|
||||
// The "wayBetter" item in X's navigation; where X draws none (photo/video viewer opened by URL,
|
||||
// logged-out pages, X's mobile layout) the framework's floating button stands in: hidden while X
|
||||
// layers anything over the page, above X's bottom bar.
|
||||
installPanelButton(window, {
|
||||
id: FAB_ID,
|
||||
logo: LOGO_PNG,
|
||||
title: () => t('x.fab.title'),
|
||||
mountNav,
|
||||
hiddenOn: isMediaViewer,
|
||||
overlaySelector: X_OVERLAY_SELECTOR,
|
||||
bottomBarSelector: X_BOTTOM_BAR_SELECTOR,
|
||||
}, () => runtime.open());
|
||||
}
|
||||
|
||||
try { install(); } catch (error) { console.error(`[${LABEL}] runtime failed`, error); }
|
||||
30
apps/desktop/src/inject/fabPlacement.ts
Normal file
30
apps/desktop/src/inject/fabPlacement.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
// Where the wayBetter button floats when X draws no left navigation to hold the "wayBetter" item
|
||||
// (X's photo/video viewer opened by URL, logged-out pages, X's mobile layout). It must never cover
|
||||
// X's own UI: it hides while X layers something over the page and sits above X's bottom bar. The
|
||||
// button and its placement are the framework's (waybetter/packages/runtime/src/panelButton.ts);
|
||||
// these are X's pages and selectors.
|
||||
|
||||
import { BUTTON_GAP, buttonBottom } from '../../../../waybetter/packages/runtime/src/panelButton.ts';
|
||||
|
||||
/** X's full-pane photo/video viewer (`/user/status/1/photo/1`, `/video/1`), whose actions sit at the bottom. */
|
||||
export const MEDIA_VIEWER_PATH = /\/status\/\d+\/(?:photo|video)\/\d+\/?$/;
|
||||
|
||||
/** X is showing a modal sheet or a dialog layer (compose, media, menus-as-sheets, sign-in flows). */
|
||||
export const X_OVERLAY_SELECTOR = '[aria-modal="true"], #layers [role="dialog"]';
|
||||
|
||||
/** X's bottom bar (its mobile layout); the button sits above it. */
|
||||
export const X_BOTTOM_BAR_SELECTOR = '[data-testid="BottomBar"]';
|
||||
|
||||
/** Gap between the button and the pane edge or X's bottom bar. */
|
||||
export const FAB_GAP = BUTTON_GAP;
|
||||
|
||||
/** X's photo/video viewer: the button stays hidden there. */
|
||||
export const isMediaViewer = (pathname: string) => MEDIA_VIEWER_PATH.test(pathname);
|
||||
|
||||
/** Pure: whether the button stays hidden on this route / with an X overlay open. */
|
||||
export function fabHidden(pathname: string, overlayOpen: boolean): boolean {
|
||||
return overlayOpen || isMediaViewer(pathname);
|
||||
}
|
||||
|
||||
/** Pure: the button's `bottom` offset (`barTop`: the top edge of X's bottom bar, null when X has none). */
|
||||
export const fabBottom = (barTop: number | null, viewportHeight: number): number => buttonBottom(barTop, viewportHeight);
|
||||
501
apps/desktop/src/inject/features.ts
Normal file
501
apps/desktop/src/inject/features.ts
Normal 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;
|
||||
}
|
||||
19
apps/desktop/src/inject/fonts.ts
Normal file
19
apps/desktop/src/inject/fonts.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// Bundled theme fonts for x.com: Geist and Geist Mono (OFL, via @fontsource-variable) are embedded in
|
||||
// the X runtime and registered from bytes only when a theme uses them; Google Fonts the owner
|
||||
// downloaded arrive as bytes from native code (`BetterTwttr.fonts.provide`). The mechanism is the
|
||||
// wayBetter runtime's (waybetter/packages/runtime/src/fonts.ts). Latin + Latin Extended cover
|
||||
// English, Turkish and most European text; other scripts fall through the theme's stack to system fonts.
|
||||
import geist from '@fontsource-variable/geist/files/geist-latin-wght-normal.woff2';
|
||||
import geistExt from '@fontsource-variable/geist/files/geist-latin-ext-wght-normal.woff2';
|
||||
import geistMono from '@fontsource-variable/geist-mono/files/geist-mono-latin-wght-normal.woff2';
|
||||
import geistMonoExt from '@fontsource-variable/geist-mono/files/geist-mono-latin-ext-wght-normal.woff2';
|
||||
import { LATIN_EXT_RANGE, LATIN_RANGE, loadBundledFonts as load, type BundledFontFiles } from '../../../../waybetter/packages/runtime/src/fonts.ts';
|
||||
|
||||
export { provideFonts, type ProvidedFont } from '../../../../waybetter/packages/runtime/src/fonts.ts';
|
||||
|
||||
const FILES: BundledFontFiles = {
|
||||
'Geist': [[geist, LATIN_RANGE], [geistExt, LATIN_EXT_RANGE]],
|
||||
'Geist Mono': [[geistMono, LATIN_RANGE], [geistMonoExt, LATIN_EXT_RANGE]],
|
||||
};
|
||||
|
||||
export const loadBundledFonts = (doc: Document, names: string[]) => load(doc, names, FILES);
|
||||
40
apps/desktop/src/inject/i18n.ts
Normal file
40
apps/desktop/src/inject/i18n.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// The X runtime's language: the framework's page strings (waybetter/packages/runtime/src/
|
||||
// pageStrings.ts) with X's English. Native code hands X tabs the owner's language and exactly the
|
||||
// strings the page needs (the runtime's own `x.*`, the plugin UI kit's `kit.*` and the bundled
|
||||
// plugins' `plugin.*`, see src-tauri/src/desktop_i18n.rs) as `wayBetter.i18n.set({ locale, dir,
|
||||
// messages })`, queued in `__wbI18n` until this runtime exists. English is built in (the X runtime
|
||||
// build keeps only those prefixes of locales/en.json). A switch applies live: `onChange` listeners
|
||||
// re-render.
|
||||
|
||||
import source from '../../locales/en.json' with { type: 'json' };
|
||||
import { KIT_MESSAGES } from '../../../../waybetter/packages/runtime/src/ui.ts';
|
||||
import { createPageStrings } from '../../../../waybetter/packages/runtime/src/pageStrings.ts';
|
||||
import type { I18nSource } from '../../../../waybetter/packages/runtime/src/pluginI18n.ts';
|
||||
import { AREA_MESSAGES } from '../areas/messages.ts';
|
||||
import { setCoreText } from '../core/text.ts';
|
||||
|
||||
const PREFIXES = ['x.', 'kit.', 'plugin.'];
|
||||
|
||||
// The UI kit's words are its own English (`kit.*`); the rest of the framework catalog is the shell's.
|
||||
const english: Record<string, string> = { ...KIT_MESSAGES };
|
||||
// The areas' new words (src/areas/<area>/messages.en.json) count as English until they are in en.json.
|
||||
for (const [key, value] of Object.entries({ ...AREA_MESSAGES, ...(source.messages as Record<string, string>) })) {
|
||||
if (PREFIXES.some(prefix => key.startsWith(prefix))) english[key] = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bundled plugins are installed as `bt-<name>.plugin.js`, but their strings are keyed by their
|
||||
* source name (`plugin.<name>.*`, src-tauri/bundled-plugins/<name>.plugin.js).
|
||||
*/
|
||||
export const strings = createPageStrings({ english, prefixes: PREFIXES, label: 'wayBetter for X', bundledPrefix: 'bt-' });
|
||||
|
||||
export const { message, t, locale, set: setStrings, onChange } = strings;
|
||||
|
||||
// Shared modules (src/core) speak through this translator in X tabs.
|
||||
setCoreText((key, params) => t(key, params));
|
||||
|
||||
/** The plugin API's view of the language (runtime pluginI18n.ts): `api.i18n` and the UI kit's words. */
|
||||
export const pluginSource: I18nSource = strings.source;
|
||||
|
||||
/** A plugin file's catalog namespace (`plugin.<namespace>.*`). */
|
||||
export const pluginCatalogNamespace = strings.pluginNamespace;
|
||||
74
apps/desktop/src/inject/linkRouting.ts
Normal file
74
apps/desktop/src/inject/linkRouting.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// "Links to X pages" setting: when it is not "same", a plain click on a post, a profile, a hashtag or a
|
||||
// list inside the timeline (or a hover card) opens that page beside the pane, in a new tab or in the
|
||||
// system browser instead of replacing what you are reading. The click becomes an ordinary new-window
|
||||
// request; native code (`new_window_mode`) decides where it opens. Photos and videos keep X's own
|
||||
// in-place viewer; navigation, tabs, menus and every button are never touched. The click router is
|
||||
// the wayBetter runtime's (linkRouting.ts); which X clicks count is decided here (`clickedXUrl`).
|
||||
|
||||
import {
|
||||
installLinkRouting as installCore,
|
||||
type LinkMode,
|
||||
type LinkRoutingHandle,
|
||||
} from '../../../../waybetter/packages/runtime/src/linkRouting.ts';
|
||||
|
||||
export type XLinkMode = LinkMode;
|
||||
export type { LinkRoutingHandle };
|
||||
|
||||
/** Only content: timeline/conversation cells and hover cards. */
|
||||
const SCOPE = '[data-testid="cellInnerDiv"], [data-testid="HoverCard"]';
|
||||
/** A press on one of these is X's (like, reply, menu, media, play…), never a navigation to divert. */
|
||||
const INTERACTIVE = 'button, [role="button"], [role="menuitem"], [role="tab"], input, textarea, select, video, [data-testid="videoPlayer"], [data-testid="tweetPhoto"]';
|
||||
/** First path segments that are X pages, not @handles. */
|
||||
const RESERVED = new Set([
|
||||
'home', 'explore', 'notifications', 'messages', 'i', 'settings', 'search', 'hashtag', 'compose', 'login', 'logout',
|
||||
'signup', 'tos', 'privacy', 'jobs', 'account', 'intent', 'share', 'download', 'about', 'display', 'keyboard_shortcuts',
|
||||
'communities', 'premium', 'jf', 'bookmarks',
|
||||
]);
|
||||
const HANDLE = '[A-Za-z0-9_]{1,15}';
|
||||
const STATUS = new RegExp(`^/${HANDLE}/status/\\d+(?:/(?:quotes|retweets|reposts|likes|history))?$`);
|
||||
const PROFILE = new RegExp(`^/(${HANDLE})(?:/(?:with_replies|media|likes|highlights|articles|followers|following|verified_followers|lists))?$`);
|
||||
|
||||
/** Pure: an X page worth opening elsewhere (post, profile, hashtag, search, list, community). */
|
||||
export function routableXPath(pathname: string, search = ''): boolean {
|
||||
const path = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
|
||||
if (STATUS.test(path) || /^\/hashtag\/[^/]+$/.test(path) || /^\/i\/(?:lists|communities)\/\d+$/.test(path)) return true;
|
||||
if (path === '/search') return /(?:^|[?&])q=./.test(search);
|
||||
const profile = PROFILE.exec(path);
|
||||
return !!profile && !RESERVED.has(profile[1]!.toLowerCase());
|
||||
}
|
||||
|
||||
const sameOriginRoutable = (anchor: HTMLAnchorElement, location: Location): string | null => {
|
||||
// target=_blank links already reach native code as new-window requests (the "other sites" setting).
|
||||
if (anchor.target && anchor.target !== '_self') return null;
|
||||
let url: URL;
|
||||
try { url = new URL(anchor.getAttribute('href') ?? '', location.href); } catch { return null; }
|
||||
return url.origin === location.origin && routableXPath(url.pathname, url.search) ? url.href : null;
|
||||
};
|
||||
|
||||
/** The X page a click on `target` would open in place, when it is one to divert; else null. */
|
||||
export function clickedXUrl(target: Element | null, location: Location): string | null {
|
||||
const scope = target?.closest?.(SCOPE);
|
||||
if (!target || !scope) return null;
|
||||
const anchor = target.closest<HTMLAnchorElement>('a[href]');
|
||||
if (anchor && scope.contains(anchor)) return anchor.closest(INTERACTIVE) ? null : sameOriginRoutable(anchor, location);
|
||||
if (target.closest(INTERACTIVE)) return null;
|
||||
// X opens a post when its body (not a link or button) is clicked: find that post's permalink.
|
||||
const article = target.closest('article[data-testid="tweet"]');
|
||||
if (!article || !scope.contains(article)) return null;
|
||||
const permalink = (root: Element, skipQuotes: boolean) => [...root.querySelectorAll<HTMLAnchorElement>('a[href*="/status/"]')]
|
||||
.find(link => link.querySelector('time') && !(skipQuotes && link.closest('div[role="link"]')));
|
||||
const quote = target.closest('div[role="link"]');
|
||||
if (quote && article.contains(quote)) {
|
||||
const link = permalink(quote, false);
|
||||
return link ? sameOriginRoutable(link, location) : null;
|
||||
}
|
||||
// tabindex=-1 is the post a status page is about: X does nothing on its body.
|
||||
if (article.getAttribute('tabindex') !== '0') return null;
|
||||
const link = permalink(article, true);
|
||||
return link ? sameOriginRoutable(link, location) : null;
|
||||
}
|
||||
|
||||
/** Native code configures it with `{ site: mode }` (waybetter-host `settings::links_script`). */
|
||||
export function installLinkRouting(win: Window): LinkRoutingHandle {
|
||||
return installCore(win, { clickedUrl: clickedXUrl, configKey: 'site' });
|
||||
}
|
||||
19
apps/desktop/src/inject/media/index.ts
Normal file
19
apps/desktop/src/inject/media/index.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// Photo/video/GIF downloader: passive GraphQL tap -> LRU store -> action-bar button.
|
||||
import { mediaStore } from './store.ts';
|
||||
import { installMediaTap } from './tap.ts';
|
||||
import { installMediaButtons } from './ui.ts';
|
||||
|
||||
export type MediaHandle = { dispose(): void };
|
||||
|
||||
export function installMediaDownload(win: Window): MediaHandle {
|
||||
let buttons: ReturnType<typeof installMediaButtons> | null = null;
|
||||
const tap = installMediaTap(win, entry => { mediaStore.set(entry); buttons?.rescan(); });
|
||||
buttons = installMediaButtons(win.document, id => mediaStore.get(id));
|
||||
return {
|
||||
dispose() {
|
||||
tap.dispose();
|
||||
buttons?.dispose();
|
||||
buttons = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
96
apps/desktop/src/inject/media/parse.ts
Normal file
96
apps/desktop/src/inject/media/parse.ts
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
// Pure media helpers for the downloader: GraphQL tweet parsing, original-quality URL selection
|
||||
// and filenames. No DOM access, so everything here runs under node --test.
|
||||
|
||||
export type MediaKind = 'photo' | 'video' | 'animated_gif';
|
||||
export type MediaItem = { kind: MediaKind; url: string };
|
||||
export type TweetMedia = { tweetId: string; username: string; media: MediaItem[] };
|
||||
|
||||
type Variant = { bitrate?: unknown; content_type?: unknown; url?: unknown };
|
||||
|
||||
// UserVideoTimeline: the profile's media tab (seen live 2026-10-01, labelled "Videos"), which X
|
||||
// loads instead of UserMedia; without it no post there got a download button.
|
||||
export const TAPPED_OPERATIONS = /\/i\/api\/graphql\/[^/]+\/(TweetDetail|HomeTimeline|HomeLatestTimeline|UserTweets|UserMedia|UserVideoTimeline|SearchTimeline|TweetResultByRestId|ListLatestTweetsTimeline|Bookmarks|Likes)(?:[?#]|$)/;
|
||||
|
||||
export function isTappedUrl(url: string): boolean {
|
||||
return TAPPED_OPERATIONS.test(url);
|
||||
}
|
||||
|
||||
/** `https://pbs.twimg.com/media/X.png?format=png&name=small` -> `...X?format=png&name=orig`. */
|
||||
export function origPhotoUrl(url: string): string {
|
||||
const [pathPart, query = ''] = url.split('?');
|
||||
const params = new URLSearchParams(query);
|
||||
const extMatch = /\.(jpe?g|png|webp|gif)$/i.exec(pathPart);
|
||||
const base = extMatch ? pathPart.slice(0, -extMatch[0].length) : pathPart.replace(/:[a-z0-9]+$/i, '');
|
||||
let ext = (extMatch?.[1] ?? params.get('format') ?? 'jpg').toLowerCase();
|
||||
if (ext === 'jpeg') ext = 'jpg';
|
||||
return `${base}?format=${ext}&name=orig`;
|
||||
}
|
||||
|
||||
/** Highest-bitrate progressive MP4; HLS playlists are ignored. */
|
||||
export function bestMp4(variants: unknown): string | null {
|
||||
if (!Array.isArray(variants)) return null;
|
||||
let best: { url: string; bitrate: number } | null = null;
|
||||
for (const v of variants as Variant[]) {
|
||||
if (!v || v.content_type !== 'video/mp4' || typeof v.url !== 'string') continue;
|
||||
const bitrate = typeof v.bitrate === 'number' ? v.bitrate : 0;
|
||||
if (!best || bitrate > best.bitrate) best = { url: v.url, bitrate };
|
||||
}
|
||||
return best?.url ?? null;
|
||||
}
|
||||
|
||||
export function mediaExtension(item: MediaItem): string {
|
||||
if (item.kind !== 'photo') return 'mp4';
|
||||
const format = /[?&]format=([a-z0-9]+)/i.exec(item.url)?.[1]?.toLowerCase();
|
||||
return format === 'png' || format === 'webp' ? format : 'jpg';
|
||||
}
|
||||
|
||||
/** `@<username>_<tweetId>_<n>.<ext>`, n 1-based. */
|
||||
export function mediaFilename(username: string, tweetId: string, index: number, item: MediaItem): string {
|
||||
const safeUser = username.replace(/[^A-Za-z0-9_]/g, '') || 'unknown';
|
||||
const safeId = tweetId.replace(/\D/g, '');
|
||||
return `@${safeUser}_${safeId}_${index + 1}.${mediaExtension(item)}`;
|
||||
}
|
||||
|
||||
function toMediaItem(raw: unknown): MediaItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const m = raw as { type?: unknown; media_url_https?: unknown; video_info?: { variants?: unknown } };
|
||||
if (m.type === 'photo' && typeof m.media_url_https === 'string') return { kind: 'photo', url: origPhotoUrl(m.media_url_https) };
|
||||
if (m.type === 'video' || m.type === 'animated_gif') {
|
||||
const url = bestMp4(m.video_info?.variants);
|
||||
return url ? { kind: m.type, url } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function screenName(tweet: Record<string, any>): string {
|
||||
const user = tweet.core?.user_results?.result;
|
||||
const name = user?.core?.screen_name ?? user?.legacy?.screen_name;
|
||||
return typeof name === 'string' ? name : '';
|
||||
}
|
||||
|
||||
/** Recursively finds GraphQL tweet objects (rest_id + legacy.extended_entities.media). */
|
||||
export function extractTweetMedia(root: unknown, maxDepth = 64): TweetMedia[] {
|
||||
const out: TweetMedia[] = [];
|
||||
const seen = new Set<string>();
|
||||
const walk = (node: unknown, depth: number) => {
|
||||
if (!node || typeof node !== 'object' || depth > maxDepth) return;
|
||||
if (Array.isArray(node)) { for (const child of node) walk(child, depth + 1); return; }
|
||||
const obj = node as Record<string, any>;
|
||||
const media = obj.legacy?.extended_entities?.media;
|
||||
const tweetId = typeof obj.rest_id === 'string' ? obj.rest_id : obj.legacy?.id_str;
|
||||
if (Array.isArray(media) && typeof tweetId === 'string' && !seen.has(tweetId)) {
|
||||
const items = media.map(toMediaItem).filter((m): m is MediaItem => m !== null);
|
||||
if (items.length) { seen.add(tweetId); out.push({ tweetId, username: screenName(obj), media: items }); }
|
||||
}
|
||||
for (const key in obj) walk(obj[key], depth + 1);
|
||||
};
|
||||
walk(root, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function isAllowedMediaUrl(url: string): boolean {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
return u.protocol === 'https:' && (u.hostname === 'pbs.twimg.com' || u.hostname === 'video.twimg.com');
|
||||
} catch { return false; }
|
||||
}
|
||||
22
apps/desktop/src/inject/media/store.ts
Normal file
22
apps/desktop/src/inject/media/store.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
// Bounded LRU of tweetId -> media, filled by the response tap and read by the download button.
|
||||
import type { TweetMedia } from './parse.ts';
|
||||
|
||||
export function createMediaStore(limit = 2000) {
|
||||
const map = new Map<string, TweetMedia>();
|
||||
return {
|
||||
set(entry: TweetMedia) {
|
||||
map.delete(entry.tweetId);
|
||||
map.set(entry.tweetId, entry);
|
||||
while (map.size > limit) map.delete(map.keys().next().value as string);
|
||||
},
|
||||
get(tweetId: string): TweetMedia | undefined {
|
||||
const entry = map.get(tweetId);
|
||||
if (entry) { map.delete(tweetId); map.set(tweetId, entry); }
|
||||
return entry;
|
||||
},
|
||||
get size() { return map.size; },
|
||||
clear() { map.clear(); },
|
||||
};
|
||||
}
|
||||
|
||||
export const mediaStore = createMediaStore();
|
||||
24
apps/desktop/src/inject/media/tap.ts
Normal file
24
apps/desktop/src/inject/media/tap.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// Passive tap on X's GraphQL timeline/tweet responses, on the shared request hook (../netHub.ts):
|
||||
// the caller gets the very same promise; only a clone is read (once for all taps), asynchronously.
|
||||
// XHR is observed via a load listener and never altered. Errors are swallowed so the page is never affected.
|
||||
import { addTap } from '../netHub.ts';
|
||||
import { extractTweetMedia, isTappedUrl, type TweetMedia } from './parse.ts';
|
||||
|
||||
export const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
type TapWindow = { fetch: typeof fetch; XMLHttpRequest?: typeof XMLHttpRequest };
|
||||
export type TapHandle = { dispose(): void };
|
||||
|
||||
export function ingestText(text: string, onMedia: (entry: TweetMedia) => void) {
|
||||
if (text.length > MAX_BODY_BYTES) return;
|
||||
try { for (const entry of extractTweetMedia(JSON.parse(text))) onMedia(entry); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
export function installMediaTap(target: TapWindow, onMedia: (entry: TweetMedia) => void): TapHandle {
|
||||
const remove = addTap(target, {
|
||||
match: isTappedUrl,
|
||||
maxBytes: MAX_BODY_BYTES,
|
||||
onJson: body => { for (const entry of extractTweetMedia(body)) onMedia(entry); },
|
||||
});
|
||||
return { dispose: remove };
|
||||
}
|
||||
88
apps/desktop/src/inject/media/ui.ts
Normal file
88
apps/desktop/src/inject/media/ui.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
// Download button in each media tweet's action bar. Only tweets whose media the tap has seen get
|
||||
// a button; clicking fetches the CDN files (pbs/video.twimg.com only) and saves them via <a download>.
|
||||
import { onChange, t } from '../i18n.ts';
|
||||
import { watchDom } from '../domHub.ts';
|
||||
import { isAllowedMediaUrl, mediaFilename, type TweetMedia } from './parse.ts';
|
||||
|
||||
const BUTTON_ATTR = 'data-bt-media-download';
|
||||
const ACTION_BAR = '[data-testid="tweet"] [role="group"]';
|
||||
const ICON = 'M12 3a1 1 0 0 1 1 1v9.59l3.3-3.3a1 1 0 1 1 1.4 1.42l-5 5a1 1 0 0 1-1.4 0l-5-5a1 1 0 1 1 1.4-1.42l3.3 3.3V4a1 1 0 0 1 1-1zM5 19a1 1 0 0 1 1-1h12a1 1 0 1 1 0 2H6a1 1 0 0 1-1-1z';
|
||||
|
||||
export function tweetIdFrom(article: Element): string | null {
|
||||
const link = article.querySelector('a[href*="/status/"] time')?.closest('a');
|
||||
return /\/status\/(\d+)/.exec(link?.getAttribute('href') ?? '')?.[1] ?? null;
|
||||
}
|
||||
|
||||
async function download(entry: TweetMedia) {
|
||||
for (const [index, item] of entry.media.entries()) {
|
||||
if (!isAllowedMediaUrl(item.url)) continue;
|
||||
try {
|
||||
const response = await fetch(item.url, { credentials: 'omit' });
|
||||
if (!response.ok) continue;
|
||||
const objectUrl = URL.createObjectURL(await response.blob());
|
||||
const a = document.createElement('a');
|
||||
a.href = objectUrl;
|
||||
a.download = mediaFilename(entry.username, entry.tweetId, index, item);
|
||||
a.style.display = 'none';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 10_000);
|
||||
} catch (error) {
|
||||
console.warn('[wayBetter for X] media download failed', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makeButton(entry: TweetMedia): HTMLElement {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.setAttribute(BUTTON_ATTR, entry.tweetId);
|
||||
wrap.style.cssText = 'display:flex;align-items:center;';
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.setAttribute('aria-label', t('x.media.download'));
|
||||
button.title = t('x.media.download');
|
||||
button.style.cssText = 'background:none;border:0;padding:6px;cursor:pointer;color:rgb(113,118,123);display:flex;border-radius:9999px;';
|
||||
button.innerHTML = `<svg viewBox="0 0 24 24" width="18.75" height="18.75" fill="currentColor" aria-hidden="true"><path d="${ICON}"/></svg>`;
|
||||
button.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void download(entry);
|
||||
});
|
||||
wrap.appendChild(button);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
export function installMediaButtons(doc: Document, lookup: (tweetId: string) => TweetMedia | undefined) {
|
||||
const scan = () => {
|
||||
for (const bar of doc.querySelectorAll(ACTION_BAR)) {
|
||||
if (bar.querySelector(`[${BUTTON_ATTR}]`)) continue;
|
||||
const article = bar.closest('[data-testid="tweet"]');
|
||||
const tweetId = article ? tweetIdFrom(article) : null;
|
||||
const entry = tweetId ? lookup(tweetId) : undefined;
|
||||
if (entry) bar.appendChild(makeButton(entry));
|
||||
}
|
||||
};
|
||||
// Shared body observer + frame (domHub.ts). No post action bars on chat pages.
|
||||
const watch = watchDom(doc.defaultView as Window & typeof globalThis, scan, { offOnChat: true });
|
||||
const schedule = watch.schedule;
|
||||
const start = () => { schedule(); };
|
||||
if (doc.body) start();
|
||||
else doc.addEventListener('DOMContentLoaded', start, { once: true });
|
||||
// A language switch applies live: buttons already on the page take the new words too.
|
||||
const offLanguage = onChange(() => {
|
||||
for (const button of doc.querySelectorAll<HTMLElement>(`[${BUTTON_ATTR}] button`)) {
|
||||
button.setAttribute('aria-label', t('x.media.download'));
|
||||
button.title = t('x.media.download');
|
||||
}
|
||||
});
|
||||
return {
|
||||
rescan: schedule,
|
||||
dispose() {
|
||||
watch.dispose();
|
||||
offLanguage();
|
||||
doc.removeEventListener('DOMContentLoaded', start);
|
||||
for (const node of doc.querySelectorAll(`[${BUTTON_ATTR}]`)) node.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
8
apps/desktop/src/inject/netHub.ts
Normal file
8
apps/desktop/src/inject/netHub.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
// X adapter over the wayBetter request hub: one shared fetch/XHR hook per window for reply sort,
|
||||
// the mutation gate (like/repost/bookmark/follow lanes), upload retry and the passive JSON taps
|
||||
// (media downloader, keyword alerts, user info). Only `/i/api/` calls (and, for XHR gates,
|
||||
// X's media upload) reach the stages; see waybetter/packages/runtime/src/netHub.ts and xSite.ts.
|
||||
|
||||
import './xSite.ts';
|
||||
|
||||
export * from '../../../../waybetter/packages/runtime/src/netHub.ts';
|
||||
179
apps/desktop/src/inject/packs/index.ts
Normal file
179
apps/desktop/src/inject/packs/index.ts
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
// The built-in icon packs. All four are our own drawings (license "own", GPL-3.0-or-later with the
|
||||
// app): no glyph is traced from X, Twitter, Windows or any icon font.
|
||||
// wb-line thin line icons (stroke width and caps follow the pack's or the theme's style)
|
||||
// wb-classic solid glyphs in the manner of 2012 (a star for like, square-loop arrows for repost)
|
||||
// wb-aero glossy colored glyphs (the classic silhouettes with a vertical sheen)
|
||||
// wb-pixel 16 by 16 pixel art in the manner of a 1998 desktop, drawn on a 24px box
|
||||
// Packs are standalone documents (framework themeIcons.ts); `packDocument(id)` is the JSON a pack
|
||||
// is exported and published as.
|
||||
|
||||
import { sanitizeIconPack, type IconGlyph, type IconName, type IconPack } from '../../../../../waybetter/packages/runtime/src/themeIcons.ts';
|
||||
|
||||
const line = (d: string): IconGlyph => ({ d, stroke: true });
|
||||
const solid = (d: string, evenodd = false): IconGlyph => ({ d, ...(evenodd ? { rule: 'evenodd' as const } : {}) });
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// wb-line
|
||||
|
||||
const LINE: Partial<Record<IconName, IconGlyph>> = {
|
||||
home: line('M4 11l8-7 8 7M6 9.5V20h4.5v-5.5h3V20H18V9.5'),
|
||||
'home.active': solid('M12 3.2l8.6 7.6-1.3 1.5-.3-.3V21h-5.5v-6h-3v6H5v-9L4.7 12.3 3.4 10.8z'),
|
||||
explore: line('M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14zM20 20l-4-4'),
|
||||
notifications: line('M6 16V11a6 6 0 1 1 12 0v5l1.5 2h-15zM10 20.5h4'),
|
||||
'notifications.active': solid('M12 3.5a6.8 6.8 0 0 1 6.8 6.8V15.7l2 2.8H3.2l2-2.8V10.3A6.8 6.8 0 0 1 12 3.5zM9.8 20h4.4a2.2 2.2 0 0 1-4.4 0z'),
|
||||
messages: line('M4 6h16v12H4zM4 7l8 6 8-6'),
|
||||
bookmarks: line('M7 4h10v16l-5-4-5 4z'),
|
||||
lists: line('M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01'),
|
||||
communities: line('M9 11a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7zM3 20a6 6 0 0 1 12 0M16 11a3 3 0 1 0 0-6M17.5 14.3A5 5 0 0 1 21 19.5'),
|
||||
premium: line('M12 3l2.4 1.9 3-.3.7 3 2.6 1.6-1.2 2.8 1.2 2.8-2.6 1.6-.7 3-3-.3L12 21l-2.4-1.9-3 .3-.7-3-2.6-1.6 1.2-2.8-1.2-2.8 2.6-1.6.7-3 3 .3zM8.6 12.2l2.3 2.3 4.5-4.8'),
|
||||
profile: line('M12 12a4 4 0 1 1 0-8 4 4 0 0 1 0 8zM4.5 20a7.5 7.5 0 0 1 15 0'),
|
||||
more: line('M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM8 12h.01M12 12h.01M16 12h.01'),
|
||||
compose: line('M5 20h4L20 9l-4-4L5 16zM14 7l4 4'),
|
||||
grok: line('M5.5 18.5L18.5 5.5M11 5.5h7.5V13'),
|
||||
reply: line('M4 5h16v11h-9.5L6 20v-4H4z'),
|
||||
repost: line('M4 11V8.5A2.5 2.5 0 0 1 6.5 6H18M15 3l3 3-3 3M20 13v2.5a2.5 2.5 0 0 1-2.5 2.5H6M9 21l-3-3 3-3'),
|
||||
'repost.on': line('M4 11V8.5A2.5 2.5 0 0 1 6.5 6H18M15 3l3 3-3 3M20 13v2.5a2.5 2.5 0 0 1-2.5 2.5H6M9 21l-3-3 3-3'),
|
||||
like: line('M12 20l-7.3-7.3a4.5 4.5 0 0 1 7.3-5.2 4.5 4.5 0 0 1 7.3 5.2z'),
|
||||
'like.on': solid('M12 20.8l-7.9-7.9A5.3 5.3 0 0 1 12 6.4a5.3 5.3 0 0 1 7.9 6.5z'),
|
||||
views: line('M5 20v-7M10 20V6M15 20v-9M20 20V4'),
|
||||
bookmark: line('M7 4h10v16l-5-4-5 4z'),
|
||||
'bookmark.on': solid('M6.2 3.2h11.6v17.9L12 16.8l-5.8 4.3z'),
|
||||
share: line('M12 15V4M8 8l4-4 4 4M5 13v6h14v-6'),
|
||||
search: line('M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14zM20 20l-4-4'),
|
||||
back: line('M15 5l-7 7 7 7'),
|
||||
close: line('M7 7l10 10M17 7L7 17'),
|
||||
media: line('M4 5h16v14H4zM4 16l5-5 4 4 2-2 5 5M15 9.5h.01'),
|
||||
gif: line('M3 6h18v12H3zM10.5 10H8.2a1.2 1.2 0 0 0-1.2 1.2v1.6A1.2 1.2 0 0 0 8.2 14h2.3v-2M13.5 10v4M16 14v-4h2.5M16 12h2'),
|
||||
poll: line('M4 6h9M4 12h16M4 18h6'),
|
||||
emoji: line('M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM8.5 14a4 4 0 0 0 7 0M9 9.5h.01M15 9.5h.01'),
|
||||
schedule: line('M4 6h16v14H4zM4 10h16M8 3v4M16 3v4M12 13v3l2 1'),
|
||||
location: line('M12 21s-6-5.5-6-10a6 6 0 1 1 12 0c0 4.5-6 10-6 10zM12 13a2 2 0 1 0 0-4 2 2 0 0 0 0 4z'),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// wb-classic: solid silhouettes
|
||||
|
||||
const SIL = {
|
||||
home: 'M12 3L2 12h3v8.5h5.2v-5.5h3.6v5.5H19V12h3z',
|
||||
explore: 'M9 3h2l-.6 5h4l.6-5h2l-.6 5H20v2h-3.8l-.5 4H19v2h-3.5l-.6 5h-2l.6-5h-4l-.6 5h-2l.6-5H4v-2h3.8l.5-4H5V8h3.5zM10.2 10l-.5 4h4l.5-4z',
|
||||
notifications: 'M12 2.5a9.5 9.5 0 0 0 0 19c1.7 0 3.4-.4 4.8-1.2l-.9-1.7A7.6 7.6 0 1 1 19.6 12v1a1.8 1.8 0 0 1-3.6 0V7.8h-1.9v.8A4.6 4.6 0 1 0 15 15.3a3.7 3.7 0 0 0 6.5-2.3v-1A9.5 9.5 0 0 0 12 2.5zm-.3 7.1a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5z',
|
||||
messages: 'M2.5 5h19v14h-19zM4.5 7.2v.3l7.5 5.6 7.5-5.6v-.3z',
|
||||
profile: 'M12 12a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zm-8.2 9a8.2 8.2 0 0 1 16.4 0z',
|
||||
more: 'M5 10.2a1.8 1.8 0 1 0 0 3.6 1.8 1.8 0 0 0 0-3.6zm7 0a1.8 1.8 0 1 0 0 3.6 1.8 1.8 0 0 0 0-3.6zm7 0a1.8 1.8 0 1 0 0 3.6 1.8 1.8 0 0 0 0-3.6z',
|
||||
compose: 'M20.5 2.5c-6.5 1-10.8 5.3-13 11.8l-2 5.8 1.5.6 1.2-3.2C14.5 16.3 19 11.5 20.5 2.5zM3.5 20.5h17V22h-17z',
|
||||
bookmark: 'M5.8 2.8h12.4v18.8L12 16.9l-6.2 4.7z',
|
||||
lists: 'M3.5 4.5h3.2v3.2H3.5zm5.3 0h11.7v3.2H8.8zM3.5 10.4h3.2v3.2H3.5zm5.3 0h11.7v3.2H8.8zM3.5 16.3h3.2v3.2H3.5zm5.3 0h11.7v3.2H8.8z',
|
||||
reply: 'M10.2 4.8L2.8 11.6l7.4 6.9v-4.2c5.2 0 8.8 1.6 11.2 5.2-.9-5.7-4.2-10.4-11.2-11.3z',
|
||||
repost: 'M6.5 6.5h9.2V3.6l4.3 4.6-4.3 4.6V9.7H8.7v3.4H6.5zm11 11H8.3v2.9L4 15.8l4.3-4.6v3.1h7v-3.4h2.2z',
|
||||
star: 'M12 2.3l2.95 6.1 6.7.95-4.85 4.7 1.15 6.65L12 17.55l-5.95 3.15 1.15-6.65L2.35 9.35l6.7-.95z',
|
||||
heart: 'M12 21.2l-8.4-8.3A5.4 5.4 0 0 1 12 6.1a5.4 5.4 0 0 1 8.4 6.8z',
|
||||
views: 'M3.5 20.5h3.6v-8.4H3.5zm6.7 0h3.6V4.5h-3.6zm6.7 0h3.6V9.3h-3.6z',
|
||||
share: 'M10.9 4.5h2.2v10.2h-2.2zM6.9 8.1L12 3l5.1 5.1-1.5 1.5L12 6 8.4 9.6zM3.8 12.8H6v5.4h12v-5.4h2.2v7.6H3.8z',
|
||||
grok: 'M4.4 18.1L17.7 4.8l1.5 1.5L5.9 19.6zM12 3.8h8.2V12H18V6h-6z',
|
||||
media: 'M2.5 4.5h19v15h-19zM4.7 6.7v9.4l4.8-4.8 4.2 4.2 2.2-2.2 3.4 3.4V6.7zM16 8a1.8 1.8 0 1 0 0 3.6A1.8 1.8 0 0 0 16 8z',
|
||||
search: 'M10.5 3a7.5 7.5 0 1 0 4.55 13.46l4.85 4.85 1.45-1.45-4.85-4.85A7.5 7.5 0 0 0 10.5 3zm0 2.1a5.4 5.4 0 1 1 0 10.8 5.4 5.4 0 0 1 0-10.8z',
|
||||
} as const;
|
||||
|
||||
const CLASSIC: Partial<Record<IconName, IconGlyph>> = {
|
||||
home: solid(SIL.home), explore: solid(SIL.explore, true), notifications: solid(SIL.notifications, true), messages: solid(SIL.messages, true),
|
||||
profile: solid(SIL.profile), more: solid(SIL.more), compose: solid(SIL.compose), bookmarks: solid(SIL.bookmark), lists: solid(SIL.lists),
|
||||
grok: solid(SIL.grok), reply: solid(SIL.reply), repost: solid(SIL.repost), 'repost.on': solid(SIL.repost), like: solid(SIL.star), 'like.on': solid(SIL.star),
|
||||
views: solid(SIL.views), bookmark: solid(SIL.bookmark), 'bookmark.on': solid(SIL.bookmark), share: solid(SIL.share), media: solid(SIL.media, true), search: solid(SIL.search, true),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// wb-aero: the silhouettes in color with a sheen (a vertical gradient, then a white wash over the top)
|
||||
|
||||
const glossy = (d: string, from: string, to: string, evenodd = false): IconGlyph => ({
|
||||
layers: [
|
||||
{ d, fill: { from, to }, ...(evenodd ? { rule: 'evenodd' as const } : {}) },
|
||||
{ d, fill: { from: '#ffffff', to: to }, opacity: 0.32, ...(evenodd ? { rule: 'evenodd' as const } : {}) },
|
||||
],
|
||||
});
|
||||
const SKY: [string, string] = ['#8fe0ff', '#1a73c9'];
|
||||
const AERO: Partial<Record<IconName, IconGlyph>> = {
|
||||
home: glossy(SIL.home, ...SKY), explore: glossy(SIL.search, ...SKY, true), notifications: glossy('M12 3a6.8 6.8 0 0 1 6.8 6.8V15.4l2.2 3.1H3l2.2-3.1V9.8A6.8 6.8 0 0 1 12 3zM9.6 19.8h4.8a2.4 2.4 0 0 1-4.8 0z', '#ffe38a', '#e09a12'),
|
||||
messages: glossy(SIL.messages, '#b9f3ff', '#2d8ed6', true), profile: glossy(SIL.profile, '#a8f0a0', '#2c9a44'), more: glossy(SIL.more, ...SKY),
|
||||
compose: glossy(SIL.compose, '#9fe8ff', '#0e7fcf'), bookmarks: glossy(SIL.bookmark, '#ffc98f', '#d8661a'), lists: glossy(SIL.lists, ...SKY), grok: glossy(SIL.grok, '#d9d9e8', '#5f6479'),
|
||||
reply: glossy(SIL.reply, '#bfe9ff', '#2a86cf'), repost: glossy(SIL.repost, '#d2f7c9', '#6fbf63'), 'repost.on': glossy(SIL.repost, '#9df08e', '#1f9a32'),
|
||||
like: glossy(SIL.heart, '#ffd9ea', '#e79ab9'), 'like.on': glossy(SIL.heart, '#ff9ccb', '#d11f6c'), views: glossy(SIL.views, ...SKY),
|
||||
bookmark: glossy(SIL.bookmark, '#ffe7c9', '#e7a868'), 'bookmark.on': glossy(SIL.bookmark, '#ffc27d', '#d4620e'), share: glossy(SIL.share, ...SKY),
|
||||
media: glossy(SIL.media, '#b2f0c0', '#23945a', true), search: glossy(SIL.search, ...SKY, true),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// wb-pixel: 16 by 16 pixel art; each color becomes one layer of 1.5px squares on the 24px box
|
||||
|
||||
const PALETTE: Record<string, string> = {
|
||||
k: '#000000', w: '#ffffff', s: '#c0c0c0', g: '#808080', n: '#000080', b: '#0000ff', c: '#008080', t: '#00c0c0',
|
||||
y: '#ffff00', d: '#808000', r: '#ff0000', m: '#800000', p: '#ff80c0', e: '#00a000', o: '#ff8000',
|
||||
};
|
||||
/** Rows of 16 characters: `.` is transparent, every other letter a color of PALETTE. */
|
||||
export function pixelGlyph(rows: readonly string[]): IconGlyph {
|
||||
const byColor = new Map<string, string[]>();
|
||||
rows.slice(0, 16).forEach((row, y) => {
|
||||
const cells = row.padEnd(16, '.').slice(0, 16);
|
||||
for (let x = 0; x < 16; x++) {
|
||||
const key = cells[x]!;
|
||||
if (!PALETTE[key]) continue;
|
||||
let run = 1;
|
||||
while (x + run < 16 && cells[x + run] === key) run++;
|
||||
const list = byColor.get(key) ?? [];
|
||||
list.push(`M${+(x * 1.5).toFixed(1)} ${+(y * 1.5).toFixed(1)}h${+(run * 1.5).toFixed(1)}v1.5h-${+(run * 1.5).toFixed(1)}z`);
|
||||
byColor.set(key, list);
|
||||
x += run - 1;
|
||||
}
|
||||
});
|
||||
// Outline last, so it sits on top of the fills.
|
||||
const order = [...byColor.keys()].sort((a, b) => (a === 'k' ? 1 : 0) - (b === 'k' ? 1 : 0));
|
||||
return { layers: order.slice(-6).map(key => ({ d: byColor.get(key)!.join(''), fill: PALETTE[key]! })) };
|
||||
}
|
||||
|
||||
const PX: Record<string, readonly string[]> = {
|
||||
home: ['.......kk.......', '......krrk......', '.....krrrrk.....', '....krrrrrrk....', '...krrrrrrrrk...', '..krrrrrrrrrrk..', '.kkkkkkkkkkkkkk.', '..kwwwwwwwwwwk..', '..kwkkkwwwwwwk..', '..kwkckwwkkkwk..', '..kwkkkwwkckwk..', '..kwwwwwwkkkwk..', '..kwwkkkwwwwwk..', '..kwwkdkwwwwwk..', '..kwwkdkwwwwwk..', '..kkkkkkkkkkkk..'],
|
||||
search: ['....kkkkk.......', '...kwwwwwk......', '..kwtwwwwwk.....', '.kwtwwwwwwwk....', '.kwwwwwwwwwk....', '.kwwwwwwwwwk....', '.kwwwwwwwwwk....', '..kwwwwwwwk.....', '...kwwwwwk......', '....kkkkkgk.....', '.........kgk....', '..........kgk...', '...........kgk..', '............kgk.', '.............kk.', '................'],
|
||||
bell: ['.......kk.......', '......kyyk......', '.....kyyyyk.....', '....kywyyyyk....', '....kywyyyyk....', '....kyyyyyyk....', '....kyyyyyyk....', '...kyyyyyyyyk...', '...kyyyyyyyyk...', '..kyyyyyyyyyyk..', '..kddddddddddk..', '..kkkkkkkkkkkk..', '......kddk......', '.......kk.......', '................', '................'],
|
||||
mail: ['................', '................', '.kkkkkkkkkkkkkk.', '.kswwwwwwwwwwsk.', '.kwswwwwwwwwswk.', '.kwwswwwwwwswwk.', '.kwwwswwwwswwwk.', '.kwwwwskkswwwwk.', '.kwwwskwwksw wk.', '.kwwskwwwwkswwk.', '.kwskwwwwwwkswk.', '.kskwwwwwwwwksk.', '.kkkkkkkkkkkkkk.', '................', '................', '................'],
|
||||
person: ['......kkkk......', '.....kyyyyk.....', '....kyyyyyyk....', '....kykyykyk....', '....kyyyyyyk....', '....kyykkyyk....', '.....kyyyyk.....', '......kkkk......', '....kkcccckk....', '...kcccccccck...', '..kcccccccccck..', '..kccckcckccck..', '..kccckcckccck..', '..kccckcckccck..', '..kkkkkkkkkkkk..', '................'],
|
||||
more: ['................', '................', '................', '................', '................', '................', '..kk....kk....kk', '..kkg...kkg...kk', '...gg....gg....g', '................', '................', '................', '................', '................', '................', '................'],
|
||||
pencil: ['............kk..', '...........kmmk.', '..........kyymk.', '.........kyyyk..', '........kyyyk...', '.......kyyyk....', '......kyyyk.....', '.....kyyyk......', '....kyyyk.......', '...kdyyk........', '...kddk.........', '..kwwk..........', '..kkk...........', '................', '................', '................'],
|
||||
folder: ['................', '................', '..kkkkk.........', '.kyyyyyk........', '.kyyyyyykkkkkkk.', '.kyyyyyyyyyyyyk.', '.kywwwwwwwwwwyk.', '.kywyyyyyyyyyyk.', '.kyyyyyyyyyyyyk.', '.kyyyyyyyyyyyyk.', '.kyyyyyyyyyyyyk.', '.kdddddddddddd k', '.kkkkkkkkkkkkkk.', '................', '................', '................'],
|
||||
balloon: ['................', '..kkkkkkkkkkkk..', '.kwwwwwwwwwwwwk.', '.kwwwwwwwwwwwwk.', '.kwwkkkkkkkkwwk.', '.kwwwwwwwwwwwwk.', '.kwwkkkkkkwwwwk.', '.kwwwwwwwwwwwwk.', '..kkkwwkkkkkkk..', '....kwk.........', '....kk..........', '................', '................', '................', '................', '................'],
|
||||
arrows: ['................', '.....k..........', '....kek.........', '...keeekkkkkk...', '..keeeeeeeeeek..', '...keeekkkkkek..', '....kek.....kek.', '.....k......kek.', '.kek......k.....', '.kek.....kek....', '.kekkkkkkeeek...', '..keeeeeeeeeek..', '...kkkkkkeeek...', '.........kek....', '..........k.....', '................'],
|
||||
heart: ['................', '..kkk.....kkk...', '.kpppk...kpppk..', 'kpwppk kkppppppk', 'kpwpppppppppppk.', 'kppppppppppppppk', 'kppppppppppppppk', '.kppppppppppppk.', '..kppppppppppk..', '...kppppppppk...', '....kppppppk....', '.....kppppk.....', '......kppk......', '.......kk.......', '................', '................'],
|
||||
heartOn: ['................', '..kkk.....kkk...', '.krrrk...krrrk..', 'krwrrrkkkrrrrrk.', 'krwrrrrrrrrrrrk.', 'krrrrrrrrrrrrrrk', 'krrrrrrrrrrrrrrk', '.krrrrrrrrrrrrk.', '..krrrrrrrrrrk..', '...krrrrrrrrk...', '....krrrrrrk....', '.....krrrrk.....', '......krrk......', '.......kk.......', '................', '................'],
|
||||
bars: ['................', '................', '...........kkk..', '...........kbk..', '...........kbk..', '.......kkk.kbk..', '.......kbk.kbk..', '.......kbk.kbk..', '...kkk.kbk.kbk..', '...kbk.kbk.kbk..', '...kbk.kbk.kbk..', '...kbk.kbk.kbk..', '..kkkkkkkkkkkkk.', '................', '................', '................'],
|
||||
up: ['.......kk.......', '......kwwk......', '.....kwwwwk.....', '....kwwwwwwk....', '...kkkwwwwkkk...', '.....kwwwwk.....', '.....kwwwwk.....', '.....kwwwwk.....', '..kk.kkkkkk.kk..', '..kk........kk..', '..kk........kk..', '..kkkkkkkkkkkk..', '................', '................', '................', '................'],
|
||||
picture: ['................', '.kkkkkkkkkkkkkk.', '.ktttttttttyytk.', '.ktttttttttyytk.', '.kttttttttttttk.', '.kttttteettttk..', '.ktttteeeettttk.', '.ktteeeeeeeettk.', '.keeeeeeeeeeeek.', '.keeeddeeeeeeek.', '.kkkkkkkkkkkkkk.', '................', '................', '................', '................', '................'],
|
||||
notepad: ['................', '..kkkkkkkkkkk...', '..kwwwwwwwwwk...', '..kwkkkkkkkwk...', '..kwwwwwwwwwk...', '..kwkkkkkkkwk...', '..kwwwwwwwwwk...', '..kwkkkkkwwwk...', '..kwwwwwwwwwk...', '..kwkkkkkkkwk...', '..kwwwwwwwwwk...', '..kkkkkkkkkkk...', '................', '................', '................', '................'],
|
||||
};
|
||||
const PIXEL: Partial<Record<IconName, IconGlyph>> = {
|
||||
home: pixelGlyph(PX.home!), explore: pixelGlyph(PX.search!), notifications: pixelGlyph(PX.bell!), messages: pixelGlyph(PX.mail!), profile: pixelGlyph(PX.person!),
|
||||
more: pixelGlyph(PX.more!), compose: pixelGlyph(PX.pencil!), bookmarks: pixelGlyph(PX.folder!), lists: pixelGlyph(PX.notepad!),
|
||||
reply: pixelGlyph(PX.balloon!), repost: pixelGlyph(PX.arrows!), 'repost.on': pixelGlyph(PX.arrows!), like: pixelGlyph(PX.heart!), 'like.on': pixelGlyph(PX.heartOn!),
|
||||
views: pixelGlyph(PX.bars!), bookmark: pixelGlyph(PX.folder!), 'bookmark.on': pixelGlyph(PX.folder!), share: pixelGlyph(PX.up!), media: pixelGlyph(PX.picture!), search: pixelGlyph(PX.search!),
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const AUTHOR = 'wayBetter for X';
|
||||
const OWN = { author: AUTHOR, license: 'own', source: 'drawn for wayBetter for X', credits: 'wayBetter for X contributors' };
|
||||
const documents = [
|
||||
{ id: 'wb-line', name: 'Line', description: 'Thin line icons; stroke and caps follow the theme.', ...OWN, style: { stroke: 1.75, cap: 'round', join: 'round', scale: 1 }, glyphs: LINE },
|
||||
{ id: 'wb-classic', name: 'Classic', description: 'Solid glyphs in the manner of 2012: a star to like, square-loop arrows to repost.', ...OWN, style: { stroke: 1.75, cap: 'round', join: 'round', scale: 0.92 }, glyphs: CLASSIC, symbols: { like: 'star' } },
|
||||
{ id: 'wb-aero', name: 'Aero', description: 'Glossy colored glyphs with a sheen.', ...OWN, style: { stroke: 1.75, cap: 'round', join: 'round', scale: 1 }, glyphs: AERO },
|
||||
{ id: 'wb-pixel', name: 'Pixel 98', description: 'Sixteen-pixel icons in the manner of a 1998 desktop. Our own drawings.', ...OWN, style: { stroke: 1.75, cap: 'square', join: 'miter', scale: 1 }, glyphs: PIXEL },
|
||||
];
|
||||
|
||||
/** The built-in packs, validated like any imported pack. */
|
||||
export const BUILTIN_PACKS: IconPack[] = documents.map(doc => {
|
||||
const pack = sanitizeIconPack(doc);
|
||||
if (!pack) throw new Error(`built-in icon pack ${doc.id} is not valid`);
|
||||
return pack;
|
||||
});
|
||||
|
||||
/** A built-in pack as the JSON document it is published as (`<id>.icons.json`). */
|
||||
export const packDocument = (id: string) => {
|
||||
const pack = BUILTIN_PACKS.find(item => item.id === id);
|
||||
return pack ? { $schema: 'https://unpkg.com/waybetter/icons.schema.json', ...pack } : null;
|
||||
};
|
||||
26
apps/desktop/src/inject/paneNav.ts
Normal file
26
apps/desktop/src/inject/paneNav.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Split view: X panes of one account side by side each draw X's whole left navigation. Native code
|
||||
// tells every X pane whether another pane already shows it (`redundantNav`, the leftmost pane of
|
||||
// that account wins). With the `singleSplitNav` feature on, such a pane parks the rail and slides it
|
||||
// back in from the left edge. The mechanism is the wayBetter runtime's (paneNav.ts); X's rail
|
||||
// (`header[role=banner]`, else the column holding the Home link) is `X_SITE.rail`.
|
||||
|
||||
import { X_SITE } from './xSite.ts';
|
||||
import {
|
||||
buildPaneNavCss as buildCss,
|
||||
installPaneNav as install,
|
||||
withAlpha,
|
||||
type PaneNavHandle,
|
||||
type RailPaint,
|
||||
} from '../../../../waybetter/packages/runtime/src/paneNav.ts';
|
||||
|
||||
export { withAlpha };
|
||||
export type { PaneNavHandle, RailPaint };
|
||||
|
||||
/** Pure: the stylesheet for an X pane whose rail is parked. RTL X keeps the rail on the right. */
|
||||
export function buildPaneNavCss(paint: RailPaint = X_SITE.rail.paint): string {
|
||||
return buildCss(X_SITE.rail, paint);
|
||||
}
|
||||
|
||||
export function installPaneNav(win: Window): PaneNavHandle {
|
||||
return install(win, X_SITE.rail);
|
||||
}
|
||||
125
apps/desktop/src/inject/pluginApi.ts
Normal file
125
apps/desktop/src/inject/pluginApi.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
// `window.wayBetter.api` (alias `window.BetterTwttr.api`): small helpers shared by `*.plugin.js` files so each plugin does not
|
||||
// re-implement DOM watching, route tracking, local storage, tweet parsing and cleanup. The core
|
||||
// (CSS, waitFor, storage, routes, observe, keys, copy, toast, scope) is the wayBetter runtime's
|
||||
// (waybetter/packages/runtime/src/pluginApi.ts, configured by `X_SITE.plugins`), and so are `ui`
|
||||
// (dialogs, toasts) and `theme` (the active theme as values), fed by X's theme engine (theme.ts);
|
||||
// reading a rendered tweet is X's and lives here. Everything is local to the page: no network requests, no account
|
||||
// actions.
|
||||
|
||||
import { X_SITE } from './xSite.ts';
|
||||
import {
|
||||
createCorePluginApi,
|
||||
isTypingTarget,
|
||||
type CorePluginApi,
|
||||
type Dispose,
|
||||
type I18nSource,
|
||||
type PluginScope,
|
||||
type PluginStorage,
|
||||
} from '../../../../waybetter/packages/runtime/src/pluginApi.ts';
|
||||
import { CORE_GATES, type PermissionGates } from '../../../../waybetter/packages/runtime/src/permissions.ts';
|
||||
import { readAccount } from './accountReport.ts';
|
||||
import type { SeenAccount } from './accountReport.ts';
|
||||
import type { UsersApi } from './userInfo.ts';
|
||||
import type { ThemeHandle } from './theme.ts';
|
||||
|
||||
export { isTypingTarget };
|
||||
export type { Dispose, PluginScope, PluginStorage };
|
||||
|
||||
export type TweetInfo = {
|
||||
id: string;
|
||||
url: string;
|
||||
handle: string;
|
||||
name: string;
|
||||
/** Tweet text with emoji as their characters and t.co links as the destination X shows. */
|
||||
text: string;
|
||||
/** ISO timestamp from the tweet's `<time datetime>`. */
|
||||
time: string | null;
|
||||
/** Full-size image URLs of the tweet itself (quoted tweets excluded). */
|
||||
media: string[];
|
||||
element: Element;
|
||||
};
|
||||
|
||||
export type PluginApi = CorePluginApi & {
|
||||
/** Reads a rendered tweet (any element inside `article[data-testid="tweet"]`). */
|
||||
tweet(element: Element | null | undefined): TweetInfo | null;
|
||||
/** The signed-in account, read live from X's own account button (DOM-only; no request). */
|
||||
account(): SeenAccount | null;
|
||||
/** Attributes (blue check, org verification, following) observed for a handle in responses
|
||||
* X's own UI already fetched. `get` returns null for a handle never seen this session;
|
||||
* `onUpdate(cb)` calls `cb(handles)` when responses add or update users (returns a dispose). */
|
||||
users: UsersApi;
|
||||
/** True when `target` (e.g. `document.activeElement`) is a text field or contenteditable. */
|
||||
isTypingTarget(target: EventTarget | null): boolean;
|
||||
};
|
||||
|
||||
/** The destination X shows for a t.co link (X renders the expanded URL, partly hidden, as the link text). */
|
||||
export function expandedLinkText(anchor: Element): string {
|
||||
const text = (anchor.textContent ?? '').replace(/…$/, '').trim();
|
||||
const href = anchor.getAttribute('href') ?? '';
|
||||
if (/^https?:\/\/t\.co\//.test(href) && /^https?:\/\/\S+$/.test(text)) return text;
|
||||
return text || href;
|
||||
}
|
||||
|
||||
/** Plain text of a tweet text node tree: emoji images become their alt text, links their destination. */
|
||||
export function nodeText(node: Node): string {
|
||||
if (node.nodeType === 3) return node.nodeValue ?? '';
|
||||
if (node.nodeType !== 1) return '';
|
||||
const element = node as Element;
|
||||
const tag = element.nodeName.toUpperCase();
|
||||
if (tag === 'IMG') return element.getAttribute('alt') ?? '';
|
||||
if (tag === 'BR') return '\n';
|
||||
if (tag === 'A') return expandedLinkText(element);
|
||||
let out = '';
|
||||
for (const child of Array.from(element.childNodes)) out += nodeText(child);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Reads a rendered tweet from X's DOM. */
|
||||
export function readTweet(element: Element | null | undefined): TweetInfo | null {
|
||||
const article = element?.closest?.('article[data-testid="tweet"]');
|
||||
if (!article) return null;
|
||||
// A quoted post is a `[role="link"]` card inside the article; everything else is the post's own.
|
||||
const own = (node: Element) => !node.closest('[role="link"]') || !article.contains(node.closest('[role="link"]'));
|
||||
// The post's own <time> (in a timeline it comes first; on a post page it sits below a quoted post).
|
||||
const times = Array.from(article.querySelectorAll('time'));
|
||||
const time = times.find(own) ?? times[0] ?? null;
|
||||
const link = time?.closest('a[href*="/status/"]');
|
||||
const match = /^\/([^/]+)\/status\/(\d+)/.exec(new URL(link?.getAttribute('href') ?? '/', 'https://x.com').pathname);
|
||||
if (!match) return null;
|
||||
const [, handle, id] = match;
|
||||
const textNode = Array.from(article.querySelectorAll('[data-testid="tweetText"]')).find(own);
|
||||
const nameLink = article.querySelector('[data-testid="User-Name"] a');
|
||||
const media = Array.from(article.querySelectorAll<HTMLImageElement>('img[src*="pbs.twimg.com/media/"]'))
|
||||
.filter(own)
|
||||
.map(img => {
|
||||
const url = new URL(img.getAttribute('src') ?? '', 'https://pbs.twimg.com');
|
||||
url.searchParams.set('name', 'orig');
|
||||
return url.href;
|
||||
});
|
||||
return {
|
||||
id: id!,
|
||||
url: `https://x.com/${handle}/status/${id}`,
|
||||
handle: handle!,
|
||||
name: nameLink ? Array.from(nameLink.childNodes).map(nodeText).join('').trim() || handle! : handle!,
|
||||
text: textNode ? nodeText(textNode).trim() : '',
|
||||
time: time?.getAttribute('datetime') ?? null,
|
||||
media: [...new Set(media)],
|
||||
element: article,
|
||||
};
|
||||
}
|
||||
|
||||
/** X's gated members on top of the core's (storage, ui/toast, copyText): see `@permissions` in docs/PLUGINS.md. */
|
||||
export const X_PERMISSION_GATES: PermissionGates = Object.freeze({ ...CORE_GATES, account: 'account', users: 'users' });
|
||||
|
||||
const NO_USERS: UsersApi = { get: () => null, onUpdate: () => () => {} };
|
||||
|
||||
/** Frozen, like its `users` member: every plugin shares this object and none may patch it. */
|
||||
export function createPluginApi(win: Window & typeof globalThis, users: UsersApi = NO_USERS, theme?: Pick<ThemeHandle, 'resolved' | 'onChange'>, i18n?: I18nSource): PluginApi {
|
||||
const source = theme ? { current: () => theme.resolved(), onChange: (listener: () => void) => theme.onChange(listener) } : undefined;
|
||||
return Object.freeze(Object.assign(createCorePluginApi(win, X_SITE.plugins, { theme: source, i18n }), {
|
||||
tweet: readTweet,
|
||||
account: () => readAccount(win.document),
|
||||
isTypingTarget,
|
||||
users: Object.freeze<UsersApi>({ get: handle => users.get(handle), onUpdate: callback => users.onUpdate(callback) }),
|
||||
}));
|
||||
}
|
||||
187
apps/desktop/src/inject/searchChips.ts
Normal file
187
apps/desktop/src/inject/searchChips.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
// X search operator chips under X's own search box ([data-testid="SearchBox_Search_Input"]).
|
||||
// Clicking a chip only edits the text in X's input (React-controlled: native value setter + input
|
||||
// event); X runs the search itself when the user presses Enter. No requests, no navigation.
|
||||
// Owned by Search+ (the `searchOperators` row of its card); the runtime installs it on that flag.
|
||||
import { t } from './i18n.ts';
|
||||
import { adoptStyles } from '../../../../waybetter/packages/runtime/src/styles.ts';
|
||||
import { applySuggestion, suggest, type Suggestion } from '../core/searchOperators.ts';
|
||||
|
||||
export const SEARCH_INPUT = 'input[data-testid="SearchBox_Search_Input"]';
|
||||
/** The chips' host element: Search+'s own strip (src/areas/search/bar.ts) sits under it. */
|
||||
export const SEARCH_OPS_HOST_ID = 'bt-search-ops';
|
||||
const HOST_ID = SEARCH_OPS_HOST_ID;
|
||||
/** The strip's colors (custom properties set on it by `stripColors`) with X's accent. Shared with Search+'s own strip. */
|
||||
export const STRIP_COLORS_CSS = '--accent:var(--wb-accent,#1d9bf0)';
|
||||
const CSS = `
|
||||
:host{all:initial}
|
||||
.ops{${STRIP_COLORS_CSS};display:flex;flex-wrap:wrap;gap:6px;padding:8px 10px;box-sizing:border-box;background:var(--bg);color:var(--fg);border:1px solid var(--line);border-radius:14px;box-shadow:0 8px 24px rgba(0,0,0,.35);font:500 13px/1 ui-monospace,SFMono-Regular,Consolas,monospace}
|
||||
button{all:unset;cursor:pointer;padding:5px 9px;border-radius:9999px;border:1px solid var(--line);color:var(--muted);white-space:nowrap}
|
||||
button:hover,button:focus-visible,button.first{color:var(--accent);border-color:var(--accent)}
|
||||
`;
|
||||
|
||||
type StyleWin = { getComputedStyle(element: Element): { backgroundColor: string; color: string } };
|
||||
|
||||
/** The alpha of a computed color (`rgb(…)` 1, `rgba(…, a)` a, `transparent` 0). */
|
||||
function alphaOf(color: string): number {
|
||||
const value = color.trim();
|
||||
if (!value || value === 'transparent') return 0;
|
||||
const rgba = /^rgba\((?:[^,]+,){3}\s*([\d.]+)\s*\)$/.exec(value);
|
||||
return rgba ? Number(rgba[1]) : 1;
|
||||
}
|
||||
/** Relative lightness 0..1 of an `rgb(…)` color, null when it cannot be read. */
|
||||
function lightnessOf(color: string): number | null {
|
||||
const rgb = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/.exec(color.trim());
|
||||
return rgb ? (0.2126 * Number(rgb[1]) + 0.7152 * Number(rgb[2]) + 0.0722 * Number(rgb[3])) / 255 : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The colors of a strip under X's search box, read from what the page shows now, so it reads on
|
||||
* X's light, dim and dark and under every theme: the text is X's input text; the background is the
|
||||
* first opaque one behind the input (its ancestors, then the page), else the opposite of the text.
|
||||
* (Only the page body was read before: themes paint elsewhere and leave it transparent, which gave
|
||||
* a black strip on light themes.)
|
||||
*/
|
||||
export function stripColors(win: StyleWin, input: Element): { bg: string; fg: string; muted: string; line: string } {
|
||||
const fg = win.getComputedStyle(input).color || 'rgb(15, 20, 25)';
|
||||
let bg = '';
|
||||
for (let node: Element | null = input.parentElement; node && !bg; node = node.parentElement) {
|
||||
const color = win.getComputedStyle(node).backgroundColor;
|
||||
if (alphaOf(color) >= 0.9) bg = color;
|
||||
}
|
||||
if (!bg) bg = (lightnessOf(fg) ?? 0) > 0.5 ? 'rgb(0, 0, 0)' : 'rgb(255, 255, 255)';
|
||||
return { bg, fg, muted: `color-mix(in srgb, ${fg} 65%, ${bg})`, line: `color-mix(in srgb, ${fg} 28%, ${bg})` };
|
||||
}
|
||||
|
||||
/** Sets the strip's color properties (see `stripColors`). */
|
||||
export function paintStrip(strip: HTMLElement, win: StyleWin, input: Element): void {
|
||||
const colors = stripColors(win, input);
|
||||
for (const [name, value] of Object.entries(colors)) strip.style.setProperty(`--${name}`, value);
|
||||
}
|
||||
|
||||
/** Sets a React-controlled input's value so React's onChange sees it. */
|
||||
export function setReactInputValue(input: HTMLInputElement, value: string) {
|
||||
const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value')?.set
|
||||
?? Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
|
||||
if (setter) setter.call(input, value); else input.value = value;
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
|
||||
/** True for X's search box (no `instanceof`: the page's classes are not the test runner's). */
|
||||
export function isSearchInput(node: unknown, selector = SEARCH_INPUT): node is HTMLInputElement {
|
||||
return !!node && typeof (node as Element).matches === 'function' && (node as Element).matches(selector);
|
||||
}
|
||||
|
||||
export type SearchChipsHandle = { dispose(): void };
|
||||
|
||||
/** `win` and `selector` are given by a feature module (its context's window, its probe); the runtime's installer passes the document only. */
|
||||
export function installSearchChips(doc: Document, win: Window = doc.defaultView ?? window, selector = SEARCH_INPUT): SearchChipsHandle {
|
||||
let host: HTMLElement | null = null;
|
||||
let root: ShadowRoot | null = null;
|
||||
let current: HTMLInputElement | null = null;
|
||||
let chips: Suggestion[] = [];
|
||||
let hideTimer: number | undefined;
|
||||
|
||||
const hide = () => { host?.remove(); host = null; root = null; chips = []; };
|
||||
|
||||
const place = () => {
|
||||
if (!host || !current) return;
|
||||
const rect = current.getBoundingClientRect();
|
||||
// Above the box when there is room, so X's own typeahead list below stays readable.
|
||||
const above = rect.top > 90;
|
||||
Object.assign(host.style, {
|
||||
position: 'fixed', zIndex: '2147483000', left: `${Math.round(rect.left - 12)}px`, width: `${Math.round(Math.max(260, rect.width + 24))}px`,
|
||||
top: above ? '' : `${Math.round(rect.bottom + 10)}px`, bottom: above ? `${Math.round(win.innerHeight - rect.top + 10)}px` : '',
|
||||
});
|
||||
};
|
||||
|
||||
const render = () => {
|
||||
if (!current) return hide();
|
||||
const caret = current.selectionStart ?? current.value.length;
|
||||
chips = suggest(current.value, caret, new Date(), 8);
|
||||
if (!chips.length) return hide();
|
||||
if (!host) {
|
||||
host = doc.createElement('div');
|
||||
host.id = HOST_ID;
|
||||
root = host.attachShadow({ mode: 'closed' });
|
||||
const bar = doc.createElement('div');
|
||||
bar.className = 'ops';
|
||||
bar.setAttribute('role', 'listbox');
|
||||
bar.setAttribute('aria-label', t('x.search.operators'));
|
||||
root.append(bar);
|
||||
// A constructed sheet: X's CSP never governs it (see waybetter runtime styles.ts).
|
||||
adoptStyles(root, CSS);
|
||||
// Keep focus in X's input while clicking chips.
|
||||
host.addEventListener('mousedown', event => event.preventDefault());
|
||||
doc.body.appendChild(host);
|
||||
}
|
||||
const bar = root!.querySelector('.ops')!;
|
||||
paintStrip(bar as HTMLElement, win, current!);
|
||||
bar.replaceChildren(...chips.map((chip, index) => {
|
||||
const button = doc.createElement('button');
|
||||
button.type = 'button';
|
||||
button.setAttribute('role', 'option');
|
||||
if (index === 0 && current!.value) button.className = 'first';
|
||||
button.textContent = chip.label;
|
||||
button.title = chip.hint;
|
||||
button.addEventListener('click', () => accept(chip));
|
||||
return button;
|
||||
}));
|
||||
place();
|
||||
};
|
||||
|
||||
const accept = (chip: Suggestion) => {
|
||||
const input = current;
|
||||
if (!input) return;
|
||||
const next = applySuggestion(input.value, input.selectionStart ?? input.value.length, chip.insert);
|
||||
input.focus();
|
||||
setReactInputValue(input, next.text);
|
||||
try { input.setSelectionRange(next.caret, next.caret); } catch { /* ignore */ }
|
||||
render();
|
||||
};
|
||||
|
||||
const target = (event: Event) => (isSearchInput(event.target, selector) ? event.target : null);
|
||||
const onFocusIn = (event: Event) => {
|
||||
const input = target(event);
|
||||
if (!input) return;
|
||||
win.clearTimeout(hideTimer);
|
||||
current = input;
|
||||
render();
|
||||
};
|
||||
const onFocusOut = (event: Event) => {
|
||||
if (!target(event)) return;
|
||||
hideTimer = win.setTimeout(() => { current = null; hide(); }, 150);
|
||||
};
|
||||
const onInput = (event: Event) => { if (target(event) === current) render(); };
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (target(event) !== current || !current || event.key !== 'Tab' || event.shiftKey || !current.value || !chips[0]) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
accept(chips[0]);
|
||||
};
|
||||
const onScroll = () => place();
|
||||
|
||||
doc.addEventListener('focusin', onFocusIn, true);
|
||||
doc.addEventListener('focusout', onFocusOut, true);
|
||||
doc.addEventListener('input', onInput, true);
|
||||
doc.addEventListener('keyup', onInput, true);
|
||||
doc.addEventListener('keydown', onKeyDown, true);
|
||||
win.addEventListener('resize', onScroll);
|
||||
win.addEventListener('scroll', onScroll, true);
|
||||
const active = doc.activeElement;
|
||||
if (isSearchInput(active, selector)) { current = active; render(); }
|
||||
|
||||
return {
|
||||
dispose() {
|
||||
win.clearTimeout(hideTimer);
|
||||
doc.removeEventListener('focusin', onFocusIn, true);
|
||||
doc.removeEventListener('focusout', onFocusOut, true);
|
||||
doc.removeEventListener('input', onInput, true);
|
||||
doc.removeEventListener('keyup', onInput, true);
|
||||
doc.removeEventListener('keydown', onKeyDown, true);
|
||||
win.removeEventListener('resize', onScroll);
|
||||
win.removeEventListener('scroll', onScroll, true);
|
||||
current = null;
|
||||
hide();
|
||||
},
|
||||
};
|
||||
}
|
||||
129
apps/desktop/src/inject/stringPacks.ts
Normal file
129
apps/desktop/src/inject/stringPacks.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
// String packs on X (waybetter/docs/STRING-PACKS.md): X's catalog hook adapter. A pack replaces
|
||||
// X's own UI strings with data, on top of whatever language the account has set in X; a string no
|
||||
// pack changes stays exactly X's.
|
||||
//
|
||||
// The catalog (`web`): the webpack client X serves to signed-in accounts. One chunk per language
|
||||
// (`…/i18n/<language>.<hash>.js`, later `…/i18n/emoji-<language>.<hash>.js`) whose module does
|
||||
// var set = require(<registry>)._register("<language>", …); set("<id>", <value>), …
|
||||
// The adapter watches the chunk array at document start, touches only a chunk pushed by a
|
||||
// language file, and lets that chunk's module see a shadow of the registry whose `_register`
|
||||
// hands out a setter that asks the engine for each value. X's registry module, its setter and
|
||||
// every other chunk stay as they are. The signed-out client (another build, keys are English
|
||||
// text) is a second catalog for a later adapter.
|
||||
//
|
||||
// What a page gets is a delivery: the packs in application order and the slice of the inventory
|
||||
// their keys need (`sliceInventory`; the inventory itself, strings/x.web.inventory.json, stays
|
||||
// where packs are checked and never ships in this runtime). Phase 1 has no install screen: the
|
||||
// delivery is read from the tab's session storage (`wayBetter.stringPacks`), which is how a
|
||||
// developer tries a pack: it lasts for that tab only and no other tab sees it. It is untrusted
|
||||
// data either way: validated, plain text only. Without a delivery nothing is hooked.
|
||||
import {
|
||||
installStringPacks, mapChunkRequires, watchChunkArray, type CatalogHookAdapter, type CatalogReport, type CatalogSink, type StringPacksHandle,
|
||||
} from '../../../../waybetter/packages/runtime/src/stringPackHook.ts';
|
||||
import { inventoryLookup, isPageInventory, type PageInventory } from '../../../../waybetter/packages/runtime/src/stringPacks.ts';
|
||||
import { createMarker, installTranslateUi, withDraft } from '../../../../waybetter/packages/runtime/src/stringPackTranslate.ts';
|
||||
|
||||
export const X_SITE_ID = 'x';
|
||||
export const X_WEB_CATALOG = 'web';
|
||||
export const X_CHUNK_ARRAY = 'webpackChunk_twitter_responsive_web';
|
||||
export const X_PACKS_KEY = 'wayBetter.stringPacks';
|
||||
|
||||
/**
|
||||
* Packs in application order with the inventory slice for their keys. `translate`: translate mode
|
||||
* (the whole inventory comes along, the strings carry markers and the page gets the editor).
|
||||
*/
|
||||
export type StringPackDelivery = { inventory: PageInventory; packs: unknown[]; translate?: boolean; rev?: number };
|
||||
/** A tab that left translate mode remembers the revision it left (until the next delivery). */
|
||||
export const X_TRANSLATE_OFF_KEY = 'wayBetter.translateOff';
|
||||
|
||||
const LANGUAGE_FILE = /^https:\/\/abs\.twimg\.com\/responsive-web\/[a-z-]+\/i18n\/(emoji-)?[A-Za-z]{2,3}(?:-[A-Za-z]+)*\.[0-9a-f]{8,}\.js$/;
|
||||
|
||||
/** The inventory group a script is a language file of (`main`, `emoji`), or `null`: not ours. */
|
||||
export function languageFile(src: string): 'main' | 'emoji' | null {
|
||||
const match = LANGUAGE_FILE.exec(src);
|
||||
return match ? (match[1] ? 'emoji' : 'main') : null;
|
||||
}
|
||||
|
||||
type Registry = { _register: (this: unknown, language: string, ...rest: unknown[]) => unknown };
|
||||
const isRegistry = (value: unknown): value is Registry => typeof value === 'object' && value !== null && typeof (value as Registry)._register === 'function';
|
||||
|
||||
/** A shadow of X's registry: the same object to read from, with a `_register` that asks `sink`. */
|
||||
function shadowRegistry(registry: Registry, sink: CatalogSink, group: string): unknown {
|
||||
const shadow = Object.create(registry) as Registry;
|
||||
Object.defineProperty(shadow, '_register', {
|
||||
value(this: unknown, ...args: [string, ...unknown[]]) {
|
||||
const set = registry._register.apply(registry, args);
|
||||
if (typeof set !== 'function') return set;
|
||||
sink.matched(String(args[0]), group);
|
||||
return function (this: unknown, id: unknown, value: unknown, ...rest: unknown[]) {
|
||||
return (set as (...a: unknown[]) => unknown).call(this, id, typeof id === 'string' ? sink.resolve(id, value) : value, ...rest);
|
||||
};
|
||||
},
|
||||
});
|
||||
return shadow;
|
||||
}
|
||||
|
||||
export const xWebCatalog: CatalogHookAdapter = {
|
||||
catalog: X_WEB_CATALOG,
|
||||
install(win, sink) {
|
||||
return watchChunkArray(win, X_CHUNK_ARRAY, (chunk, script) => {
|
||||
const group = languageFile(script);
|
||||
if (!group) return;
|
||||
sink.seen(group);
|
||||
mapChunkRequires(chunk, exports => (isRegistry(exports) ? shadowRegistry(exports, sink, group) : undefined));
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/** A delivery as data: for X's `web` catalog, at most 8 packs. Anything else is no delivery. */
|
||||
export function readDelivery(input: unknown): StringPackDelivery | null {
|
||||
if (typeof input !== 'object' || input === null) return null;
|
||||
const { inventory, packs, translate, rev } = input as { inventory?: unknown; packs?: unknown; translate?: unknown; rev?: unknown };
|
||||
if (!isPageInventory(inventory) || inventory.site !== X_SITE_ID || inventory.catalog !== X_WEB_CATALOG) return null;
|
||||
if (!Array.isArray(packs) || (!packs.length && translate !== true)) return null;
|
||||
return { inventory, packs: packs.slice(0, 8), translate: translate === true, rev: typeof rev === 'number' ? rev : 0 };
|
||||
}
|
||||
|
||||
/** The delivery a developer stored for this tab. */
|
||||
export function storedDelivery(win: Window): StringPackDelivery | null {
|
||||
try {
|
||||
const raw = win.sessionStorage.getItem(X_PACKS_KEY);
|
||||
return raw ? readDelivery(JSON.parse(raw)) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type XStringPacks = {
|
||||
/** The self-check and what each pack did (`status`: ok, not-matched, no-catalog, pending). */
|
||||
report(): CatalogReport[];
|
||||
};
|
||||
|
||||
let handle: StringPacksHandle | null = null;
|
||||
|
||||
/** Installs at document start, before X's scripts. Without a delivery it does nothing. */
|
||||
export function installXStringPacks(win: Window, delivery: StringPackDelivery | null = storedDelivery(win)): XStringPacks {
|
||||
let translate = Boolean(delivery?.translate);
|
||||
try { if (translate && win.sessionStorage.getItem(X_TRANSLATE_OFF_KEY) === String(delivery!.rev)) translate = false; } catch { /* no storage */ }
|
||||
const marker = translate ? createMarker() : null;
|
||||
if (delivery && !handle && (delivery.packs.length || translate)) {
|
||||
const lookup = inventoryLookup(delivery.inventory);
|
||||
const packs = translate ? withDraft(delivery.packs, win.sessionStorage, X_SITE_ID, X_WEB_CATALOG, delivery.inventory) : delivery.packs;
|
||||
handle = installStringPacks(win, [{ adapter: xWebCatalog, inventory: delivery.inventory, packs }], {
|
||||
// Translate mode: only strings a pack can replace carry a marker (never formatters or elements).
|
||||
mark: marker ? (id, value) => { const kind = lookup(id)?.kind; return kind === 'text' || kind === 'message' ? marker.mark(id, value) : value; } : undefined,
|
||||
onStatus(report) {
|
||||
if (report.status === 'not-matched') console.warn('[wayBetter] String packs: X\'s language file was seen but the hook did not match it (X changed). X\'s own text is shown.');
|
||||
else if (report.status === 'no-catalog') console.warn('[wayBetter] String packs: no language file of the known X build was seen (signed out, or X serves another build). X\'s own text is shown.');
|
||||
},
|
||||
});
|
||||
}
|
||||
if (marker && delivery) {
|
||||
const rev = String(delivery.rev);
|
||||
installTranslateUi(win, {
|
||||
inventory: delivery.inventory, marker, site: X_SITE_ID, catalog: X_WEB_CATALOG,
|
||||
exit() { try { win.sessionStorage.setItem(X_TRANSLATE_OFF_KEY, rev); } catch { /* no storage */ } win.location.reload(); },
|
||||
});
|
||||
}
|
||||
return { report: () => handle?.report() ?? [] };
|
||||
}
|
||||
542
apps/desktop/src/inject/theme.ts
Normal file
542
apps/desktop/src/inject/theme.ts
Normal file
|
|
@ -0,0 +1,542 @@
|
|||
// Themes recolor x.com itself. X ships its palettes as literal colors in react-native-web's atomic
|
||||
// classes (`.r-kemksi{background-color:rgb(0,0,0)}`), as inline styles on most text and buttons
|
||||
// (`style="color: rgb(231, 233, 234);"`), and as CSS variables for its newer Tailwind surfaces
|
||||
// (`--x-bg-primary`, `--background: 0 0% 0%`). Instead of guessing selectors, the runtime reads X's
|
||||
// own stylesheets, finds every rule that uses a color of X's *current* palette, and re-declares that
|
||||
// rule with the matching role color of our palette (same selector, `!important`); inline colors are
|
||||
// matched with `[style*=...]` attribute selectors, which beat inline declarations with `!important`.
|
||||
// Mapping goes through the color model in themeTokens.ts: every X neutral is placed by its position
|
||||
// on X's own background→text axis (not by raw lightness, so a light theme over Lights out inverts
|
||||
// correctly) and X's blue family follows the theme accent. Alpha variants keep their alpha.
|
||||
// X's chat is a separate app with a token layer of its own: themeChat.ts re-declares those tokens by
|
||||
// role and covers the chat surfaces tokens cannot settle.
|
||||
|
||||
import {
|
||||
BUILTIN_THEMES, buildStructureCss, isNeutral, fontStack,
|
||||
type ButtonRole, type Palette, type Role, type RuleLike, type StructureColors, type ThemeSpec,
|
||||
} from './themeSpec.ts';
|
||||
import { axisPosition, buildColorModel, projectColor, type ColorModel, type Usage } from './themeTokens.ts';
|
||||
import { X_PRIMITIVE_VARS, accentLabel, chatSurfaceCss, fadedAlpha, hexToHslTriple, xTokenOverrides } from './themeChat.ts';
|
||||
import { buildStructureCss as buildThemeStructureCss, installIconGate, normalizeIconChoice, type StructureEnv } from './themeStructure.ts';
|
||||
import type { IconChoice } from '../../../../waybetter/packages/runtime/src/themeIcons.ts';
|
||||
import { contrastRatio, hexToRgb, mix, normalizeResolved, readableOn, relativeLuminance, type ResolvedFonts, type ResolvedTheme } from '../../../../waybetter/packages/runtime/src/themeApi.ts';
|
||||
import { createThemeCatalog, type ThemeChoice } from '../../../../waybetter/packages/runtime/src/themeChoice.ts';
|
||||
import { installThemeRuntime, resolvedFonts, type ThemeHandle as RuntimeHandle, type ThemeRuntimeOptions } from '../../../../waybetter/packages/runtime/src/themeRuntime.ts';
|
||||
|
||||
export type { Palette, Role, ButtonRole, RuleLike } from './themeSpec.ts';
|
||||
export type { ThemeChoice } from '../../../../waybetter/packages/runtime/src/themeChoice.ts';
|
||||
export { hexToHslTriple } from './themeChat.ts';
|
||||
export { MAX_USER_THEMES } from '../../../../waybetter/packages/runtime/src/themeChoice.ts';
|
||||
export { SNAPSHOT_LOCAL_MAX, SNAPSHOT_SESSION_MAX, readSnapshot, writeSnapshot, type ThemeSnapshot } from '../../../../waybetter/packages/runtime/src/themeRuntime.ts';
|
||||
type AnyRole = Role | ButtonRole;
|
||||
|
||||
/** X's built-in themes as a catalog (the first, `x`, is X's own look); what `x-theme.v2.json` holds is a `ThemeChoice`. */
|
||||
export const X_THEMES = createThemeCatalog(BUILTIN_THEMES);
|
||||
export const THEME_DEFAULT: ThemeChoice = X_THEMES.defaultChoice;
|
||||
export const { normalize: normalizeTheme, base: baseTheme, resolve: resolveTheme, palette: paletteFor } = X_THEMES;
|
||||
|
||||
/** Built-in themes with their palettes (null = X's own colors). */
|
||||
export const PRESETS = BUILTIN_THEMES.map(theme => ({ id: theme.id, name: theme.name, description: theme.description, palette: theme.colors as Palette | null }));
|
||||
|
||||
export const ACCENTS = ['#1d9bf0', '#0084b4', '#5b8cff', '#7856ff', '#f91880', '#ff7a00', '#ffd400', '#00ba7c'];
|
||||
|
||||
/**
|
||||
* X's palettes as `r,g,b` keys, checked against X's bundle (`baseColor` / `darkColor` gray scales)
|
||||
* and live computed styles. Current X ships light and dark (Lights out); Dim is kept for clients
|
||||
* that still render it. Per property only the roles that make sense are mapped.
|
||||
*/
|
||||
type Source = { [K in AnyRole]: string[] };
|
||||
export const X_PALETTES: Record<'light' | 'dim' | 'dark', Source> = {
|
||||
light: {
|
||||
bg: ['255,255,255'], surface: ['247,249,249'], elevated: ['239,243,244'],
|
||||
border: ['239,243,244', '207,217,222', '229,234,236'], text: ['15,20,25'], muted: ['83,100,113', '83,100,114'], accent: ['29,155,240', '26,140,216'],
|
||||
inverse: ['15,20,25'], onInverse: ['255,255,255'],
|
||||
},
|
||||
dim: {
|
||||
bg: ['21,32,43'], surface: ['30,39,50', '25,39,52'], elevated: ['39,51,64', '32,44,57'],
|
||||
border: ['56,68,77', '66,83,100'], text: ['247,249,249', '239,243,244'], muted: ['139,152,165'], accent: ['29,155,240', '26,140,216'],
|
||||
inverse: ['239,243,244', '247,249,249'], onInverse: ['15,20,25'],
|
||||
},
|
||||
dark: {
|
||||
// 20,20,20 is the surface of every Lights out layer (More menu, hover cards, modal sheets,
|
||||
// dropdowns); 16,17,20 / 11,11,11 / 27,32,35 are chat surfaces. Read live from X (2026-09-27).
|
||||
bg: ['0,0,0'], surface: ['22,24,28', '24,24,24', '20,20,20', '16,17,20', '11,11,11'], elevated: ['32,35,39', '39,44,48', '27,32,35'],
|
||||
border: ['47,51,54', '51,54,57', '42,45,48', '62,65,68'], text: ['231,233,234', '255,255,255', '239,243,244'], muted: ['113,118,123'], accent: ['29,155,240', '26,140,216'],
|
||||
inverse: ['239,243,244'], onInverse: ['15,20,25'],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Creator Studio (`.jetfuel-style-root`) colors with Tailwind's neutral scale and a variable
|
||||
* alpha (`rgba(0, 0, 0, var(--jbgo))`). Dark values read live from X; light values are Tailwind's
|
||||
* neutral steps mirrored (unverified on x.com Default).
|
||||
*/
|
||||
const JETFUEL: Record<'light' | 'dark', Source> = {
|
||||
light: {
|
||||
bg: ['255,255,255'], surface: ['250,250,250', '245,245,245'], elevated: ['229,229,229'], border: ['229,229,229', '212,212,212'],
|
||||
text: ['0,0,0', '10,10,10', '23,23,23'], muted: ['115,115,115', '82,82,82', '163,163,163'], accent: ['14,165,233', '29,155,240'], inverse: [], onInverse: [],
|
||||
},
|
||||
dark: {
|
||||
bg: ['0,0,0', '10,10,10'], surface: ['23,23,23', '20,20,20'], elevated: ['38,38,38'], border: ['38,38,38', '64,64,64'],
|
||||
text: ['255,255,255', '250,250,250', '229,229,229'], muted: ['115,115,115', '82,82,82', '163,163,163'], accent: ['14,165,233', '29,155,240'], inverse: [], onInverse: [],
|
||||
},
|
||||
};
|
||||
|
||||
const PROPERTY_ROLES: Record<string, AnyRole[]> = {
|
||||
'background-color': ['bg', 'surface', 'elevated', 'accent', 'text'],
|
||||
color: ['text', 'muted', 'accent'],
|
||||
'border-color': ['border', 'accent'],
|
||||
'border-top-color': ['border', 'accent'],
|
||||
'border-right-color': ['border', 'accent'],
|
||||
'border-bottom-color': ['border', 'accent'],
|
||||
'border-left-color': ['border', 'accent'],
|
||||
fill: ['text', 'muted', 'accent'],
|
||||
'outline-color': ['accent'],
|
||||
// Creator Studio (jetfuel) passes its colors through these properties.
|
||||
'--jf-text-color': ['text', 'muted', 'accent'],
|
||||
'--jf-bg-color': ['bg', 'surface', 'elevated'],
|
||||
'--jf-border-color': ['border', 'accent'],
|
||||
};
|
||||
|
||||
/** Roles for X's inline colors. The filled button background is only remapped inline, where its
|
||||
* label is remapped with it (the `onInverse` context rule in `buildInlineCss`). */
|
||||
const INLINE_ROLES: Record<string, AnyRole[]> = {
|
||||
'background-color': ['bg', 'surface', 'elevated', 'inverse', 'accent'],
|
||||
color: ['text', 'muted', 'accent'],
|
||||
'border-color': ['border'],
|
||||
};
|
||||
|
||||
/** Verification badges keep X's exact colors under any palette or accent. */
|
||||
const BADGE = 'svg[data-testid="icon-verified"],svg[aria-label*="Verified"]';
|
||||
/**
|
||||
* A solid fill with one of X's accent variables that `buildThemeCss` re-declares as the theme accent
|
||||
* (see `hsl('accent', …)`). Whole value only: `hsl(var(--color-brand) / 0.1)` is a faint tint, not a fill.
|
||||
*/
|
||||
const ACCENT_VARIABLE = /^(?:hsl\(\s*var\(--(?:chat-accent|color-brand|color-blue-500)\)\s*\)|var\(--x-blue-500\))$/;
|
||||
|
||||
/** A role's color in our palette; button roles default to X's own inversion (text-colored fill). */
|
||||
function target(role: AnyRole, palette: Partial<Palette>): string | undefined {
|
||||
if (role === 'inverse') return palette.inverse ?? (palette.bg ? palette.text : undefined);
|
||||
if (role === 'onInverse') return palette.onInverse ?? (palette.text ? palette.bg : undefined);
|
||||
return palette[role];
|
||||
}
|
||||
|
||||
/** Which X palette a body background (or X's theme-color meta) belongs to. */
|
||||
export function detectXPalette(bodyBackground: string): 'light' | 'dim' | 'dark' {
|
||||
const key = parseColor(bodyBackground)?.key;
|
||||
if (key === '21,32,43') return 'dim';
|
||||
if (key === '0,0,0') return 'dark';
|
||||
return 'light';
|
||||
}
|
||||
|
||||
/** `alpha` is null for opaque colors, a number, or a `var(--x)` reference (Creator Studio's `rgba(0, 0, 0, var(--jbgo))`). */
|
||||
function parseColor(value: string): { key: string; alpha: number | string | null } | null {
|
||||
const hex = /^#([0-9a-f]{6})$/i.exec(value.trim());
|
||||
if (hex) return { key: hexToRgb(`#${hex[1]}`).join(','), alpha: null };
|
||||
const match = /^rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:\s*[,/]\s*([\d.]+%?|var\(--[\w-]+\)))?\s*\)$/.exec(value.trim());
|
||||
if (!match) return null;
|
||||
const raw = match[4];
|
||||
const alpha = raw === undefined ? null : raw.startsWith('var(') ? raw : raw.endsWith('%') ? parseFloat(raw) / 100 : parseFloat(raw);
|
||||
return { key: `${match[1]},${match[2]},${match[3]}`, alpha };
|
||||
}
|
||||
|
||||
/**
|
||||
* A declared color with X's primitives filled in (`vars`: their values with the theme off) and
|
||||
* Tailwind's opacity form reduced to the color it paints: `color-mix(in oklab, var(--x-white) 15%,
|
||||
* transparent)` is white at 15% alpha, so a translucent fill stays translucent. Anything else comes
|
||||
* back as written.
|
||||
*/
|
||||
export function resolveDeclared(value: string, vars: Record<string, string>): string {
|
||||
let out = value.trim();
|
||||
if (out.includes('var(')) out = out.replace(/var\((--[\w-]+)\)/g, (whole, name: string) => vars[name] || whole);
|
||||
const mixed = /^color-mix\(\s*in [\w-]+(?: [\w-]+ hue)?\s*,\s*(.+?)\s+([\d.]+)%\s*,\s*transparent\s*\)$/.exec(out);
|
||||
if (!mixed) return out;
|
||||
const inner = parseColor(mixed[1]!);
|
||||
if (!inner || typeof inner.alpha === 'string') return out;
|
||||
const alpha = +(((inner.alpha ?? 1) * parseFloat(mixed[2]!)) / 100).toFixed(3);
|
||||
return `rgba(${inner.key.split(',').join(', ')}, ${alpha})`;
|
||||
}
|
||||
|
||||
const models = new WeakMap<Source, Map<string, ColorModel | null>>();
|
||||
/** The OKLab axis model for one X palette, one theme palette and one usage (cached). */
|
||||
function modelFor(source: Source, palette: Partial<Palette>, usage: Usage): ColorModel | null {
|
||||
const key = `${usage}|${JSON.stringify(palette)}`;
|
||||
let perSource = models.get(source);
|
||||
if (!perSource) models.set(source, perSource = new Map());
|
||||
if (!perSource.has(key)) perSource.set(key, buildColorModel(source, palette, usage));
|
||||
return perSource.get(key)!;
|
||||
}
|
||||
const usageOf = (property: string): Usage =>
|
||||
/background|--jf-bg/.test(property) ? 'background' : /border|outline/.test(property) ? 'border' : 'text';
|
||||
const format = ([r, g, b]: [number, number, number], alpha: number | string | null) =>
|
||||
alpha === null ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
|
||||
/**
|
||||
* Maps one of X's declared colors to the theme, or null to leave it. With a full theme palette
|
||||
* every neutral and every shade of X's blue is projected through the theme's color model
|
||||
* (themeTokens.ts), so no X gray survives and hover/selected tints keep their relative place. An
|
||||
* explicit `roles` list (and an accent-only palette) matches X's listed role colors instead.
|
||||
*/
|
||||
export function mapColor(property: string, value: string, source: Source, palette: Partial<Palette>, roles?: AnyRole[]): string | null {
|
||||
if (roles) return mapByRoles(property, value, source, palette, roles);
|
||||
if (!PROPERTY_ROLES[property]) return null;
|
||||
const parsed = parseColor(value);
|
||||
if (!parsed || parsed.alpha === 0) return null;
|
||||
// Variable alpha is Creator Studio's jetfuel system, which has its own neutral scale.
|
||||
const axis = typeof parsed.alpha === 'string' ? (source === X_PALETTES.light ? JETFUEL.light : JETFUEL.dark) : source;
|
||||
const model = modelFor(axis, palette, usageOf(property));
|
||||
if (!model) return mapByRoles(property, value, source, palette, PROPERTY_ROLES[property]);
|
||||
const rgb = parsed.key.split(',').map(Number) as [number, number, number];
|
||||
// A solid text-colored background is X's filled button ("Post", "Follow"): the theme's inverse.
|
||||
if (property === 'background-color' && parsed.alpha === null) {
|
||||
const t = axisPosition(model, rgb);
|
||||
if (t !== null && t > 0.85) {
|
||||
const fill = target('inverse', palette);
|
||||
return fill ? format(hexToRgb(fill), null) : null;
|
||||
}
|
||||
}
|
||||
const mapped = projectColor(model, rgb);
|
||||
return mapped ? format(mapped, parsed.alpha) : null;
|
||||
}
|
||||
|
||||
/** X's listed role colors only (badges, button labels, accent-only palettes). */
|
||||
function mapByRoles(property: string, value: string, source: Source, palette: Partial<Palette>, roles: AnyRole[] | undefined): string | null {
|
||||
const parsed = roles && parseColor(value);
|
||||
// Fully transparent is not a palette color. Remapping it would re-declare react-native-web's
|
||||
// base `rgba(0,0,0,0)` with !important over every element, and wipe out any surface we do not
|
||||
// know (that is what made menus, hover cards and modals see-through).
|
||||
if (!parsed || parsed.alpha === 0) return null;
|
||||
// Variable alpha is Creator Studio's jetfuel system, which has its own neutral scale.
|
||||
if (typeof parsed.alpha === 'string') source = source === X_PALETTES.light ? JETFUEL.light : JETFUEL.dark;
|
||||
for (const role of roles) {
|
||||
const color = target(role, palette);
|
||||
if (!color || !source[role].includes(parsed.key)) continue;
|
||||
// A solid text-colored background is X's filled button; only its tints are retinted here.
|
||||
if (property === 'background-color' && role === 'text' && parsed.alpha === null) continue;
|
||||
const [r, g, b] = hexToRgb(color);
|
||||
return parsed.alpha === null ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${parsed.alpha})`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Maps an inline color; `insideInverse` is a label inside X's filled button. */
|
||||
export function mapInlineColor(property: string, value: string, source: Source, palette: Partial<Palette>, insideInverse = false): string | null {
|
||||
if (insideInverse && property === 'color') {
|
||||
const mapped = mapColor(property, value, source, palette, ['onInverse']);
|
||||
if (mapped) return mapped;
|
||||
}
|
||||
return INLINE_ROLES[property] ? mapColor(property, value, source, palette) : null;
|
||||
}
|
||||
|
||||
const spaced = (key: string) => `rgb(${key.split(',').join(', ')})`;
|
||||
/** Matches an inline `property: rgb(key)` declaration (and not a longer property such as background-color). */
|
||||
const inlineSelector = (property: string, key: string) => `[style^="${property}: ${spaced(key)}"],[style*="; ${property}: ${spaced(key)}"]`;
|
||||
|
||||
function buildInlineCss(source: Source, palette: Partial<Palette>): string[] {
|
||||
const out: string[] = [];
|
||||
for (const property of Object.keys(INLINE_ROLES)) {
|
||||
const groups = new Map<string, string[]>();
|
||||
const claimed = new Set<string>();
|
||||
for (const role of INLINE_ROLES[property]!) {
|
||||
for (const key of source[role]) {
|
||||
if (claimed.has(key)) continue;
|
||||
claimed.add(key);
|
||||
const mapped = mapInlineColor(property, spaced(key), source, palette);
|
||||
if (mapped) groups.set(mapped, [...(groups.get(mapped) ?? []), inlineSelector(property, key)]);
|
||||
}
|
||||
}
|
||||
for (const [value, selectors] of groups) out.push(`${selectors.join(',')}{${property}:${value} !important}`);
|
||||
}
|
||||
// Labels inside X's filled button follow the button, not the page text.
|
||||
if (target('inverse', palette)) {
|
||||
const fill = source.inverse.map(key => inlineSelector('background-color', key)).join(',');
|
||||
for (const key of source.onInverse) {
|
||||
const mapped = mapInlineColor('color', spaced(key), source, palette, true);
|
||||
const label = inlineSelector('color', key);
|
||||
if (mapped) out.push(`:is(${fill}) :is(${label}),:is(${fill}):is(${label}){color:${mapped} !important}`);
|
||||
}
|
||||
}
|
||||
// White labels on accent-filled buttons and X's dark media overlays stay white where white is
|
||||
// also X's page text color.
|
||||
if (palette.text && source.text.includes('255,255,255')) {
|
||||
const fill = [...source.accent.map(key => inlineSelector('background-color', key)), '[style*="background-color: rgba(15, 20, 25,"]'].join(',');
|
||||
const white = inlineSelector('color', '255,255,255');
|
||||
out.push(`:is(${fill}) :is(${white}),:is(${fill}):is(${white}){color:rgb(255, 255, 255) !important}`);
|
||||
}
|
||||
if (palette.accent) for (const key of source.accent) out.push(`:is(${BADGE}):is(${inlineSelector('color', key)}){color:${spaced(key)} !important}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* X's floating layers (portaled into `#layers`): the More menu, hover cards, dropdowns and modal
|
||||
* sheets always get an opaque themed surface, a hairline and a shadow, whatever X's own surface
|
||||
* color is and whatever canvas the theme paints. Toasts keep X's inverted look.
|
||||
*/
|
||||
export const LAYER_SURFACES = [
|
||||
'#layers [role="menu"]', '#layers [data-testid="HoverCard"]', '#layers [data-testid="Dropdown"]',
|
||||
// Modal sheets (Edit profile, compose) are not listed: on x.com they share every attribute with
|
||||
// the full-screen photo viewer (`role=dialog aria-modal aria-labelledby=modal-header`), whose
|
||||
// scrim must stay dark. Their surface is X's layer color, which the palette maps to `surface`.
|
||||
'#layers [data-testid="sheetDialog"]',
|
||||
];
|
||||
function layerCss(palette: Partial<Palette>): string {
|
||||
// Lights out paints every layer with one surface color (rgb(20, 20, 20)), mapped to `surface`.
|
||||
const bg = palette.surface ?? palette.bg!;
|
||||
const dark = relativeLuminance(bg) < 0.18;
|
||||
const edge = palette.border ?? mix(bg, dark ? '#ffffff' : '#000000', 0.14);
|
||||
const shadow = dark ? '0 0 0 1px rgba(0, 0, 0, 0.4), 0 10px 32px rgba(0, 0, 0, 0.6)' : '0 1px 3px rgba(0, 0, 0, 0.1), 0 10px 32px rgba(0, 0, 0, 0.16)';
|
||||
const scrim = dark ? 'rgba(0, 0, 0, 0.6)' : `rgba(${hexToRgb(mix(bg, palette.text ?? '#000000', 0.8)).join(', ')}, 0.4)`;
|
||||
return [
|
||||
`:is(${LAYER_SURFACES.join(',')}){background-color:${bg} !important;border:1px solid ${edge} !important;box-shadow:${shadow} !important}`,
|
||||
`#layers [data-testid="mask"]{background-color:${scrim} !important}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* X's signed-out experience — the landing page, the login/signup flow (`/i/flow/*`, the jetfuel
|
||||
* `/i/jf/onboarding/*` onboarding widget) and its "See what's happening" modal — is a different
|
||||
* Tailwind app (`.jetfuel-style-root`, plain `<footer>`, no `[data-testid="primaryColumn"]`) that
|
||||
* paints literal black/white/gray, not X's own palette. Those literals collide with X's real
|
||||
* dark-mode axis (the page canvas is also literal black; its text also includes literal white), so
|
||||
* the generic per-rule remap above reads a signed-out button label or footer link as if it were X's
|
||||
* own canvas or page text and recolors it backwards — a near-black headline on a dialog our own CSS
|
||||
* never touched, or a white ToS link stranded on a dialog we repainted white. Read live on x.com
|
||||
* (2026-09-28, logged out, no sign-in): confirmed on both `/i/jf/onboarding/web?mode=login` and `/`.
|
||||
* Rather than guess which literal means which role in a design system that isn't X's, every
|
||||
* signed-out surface gets one deliberate, always-legible surface + text pair, the way
|
||||
* `LAYER_SURFACES` already does for X's own floating layers. Every logged-in route (home, chat,
|
||||
* articles, settings, creator studio — not every one has a `[data-testid="primaryColumn"]`, e.g.
|
||||
* chat and settings don't) sits inside `<main role="main">`; the signed-out flow has no `<main>` at
|
||||
* all (checked live, 2026-09-28: `document.body.children` on `x.com/` logged out is plain `<div>`s),
|
||||
* so that tag's absence is how a signed-out page is told apart from X's real app shell.
|
||||
*/
|
||||
const SIGNED_OUT_ROOT = 'body:not(:has(main[role="main"]))';
|
||||
function signedOutCss(palette: Partial<Palette> & { page?: string }): string {
|
||||
const bg = palette.bg;
|
||||
const text = palette.text;
|
||||
if (!bg || !text) return '';
|
||||
const surface = palette.surface ?? bg;
|
||||
const accent = palette.accent ?? text;
|
||||
// The signed-out landing has no opaque column: links sit directly on the theme's page canvas.
|
||||
// Some light themes have an accent that reads on white but fades on their tinted page.
|
||||
const link = contrastRatio(accent, bg) >= 4.5 && contrastRatio(accent, palette.page ?? bg) >= 4.5 ? accent : text;
|
||||
const border = palette.border ?? mix(bg, text, 0.14);
|
||||
return [
|
||||
`${SIGNED_OUT_ROOT}{background-color:${bg} !important}`,
|
||||
// A dialog sheet (the login/signup modal) reads as its own surface; everything else sits on `bg`.
|
||||
`${SIGNED_OUT_ROOT} :is([role="dialog"],[aria-modal="true"]){background-color:${surface} !important}`,
|
||||
`${SIGNED_OUT_ROOT} :is(h1,h2,h3,h4,p,span,label,li,div){color:${text} !important}`,
|
||||
`${SIGNED_OUT_ROOT} a{color:${link} !important}`,
|
||||
// Buttons and pills (Google/Apple/phone continue, filled CTAs) get a themed surface and a label
|
||||
// that stays legible on it, instead of X's own literal white-pill/black-text pairing, which our
|
||||
// canvas override otherwise strands (see module comment).
|
||||
`${SIGNED_OUT_ROOT} :is(button,[role="button"]):not(svg):not(:has(> iframe)){background-color:${surface} !important;border-color:${border} !important;color:${text} !important}`,
|
||||
`${SIGNED_OUT_ROOT} :is(button,[role="button"]):not(:has(> iframe)) :is(span,p,div){color:${text} !important}`,
|
||||
// X's Jetfuel sign-in buttons paint their visible pill on a child div (and Google paints
|
||||
// a separate face over an invisible iframe). The generic color remap can give that pill
|
||||
// and its label the same color. Keep these provider controls as a readable light pair.
|
||||
`${SIGNED_OUT_ROOT} button:has(svg):has(.text-text > p.jf-element) > .jf-element.flex,${SIGNED_OUT_ROOT} .jf-gsi-face{background-color:#f8fafc !important}`,
|
||||
`${SIGNED_OUT_ROOT} button:has(svg):has(.text-text > p.jf-element) .text-text > p.jf-element,${SIGNED_OUT_ROOT} .jf-gsi-face > span.jf-element{color:#0f1419 !important;-webkit-text-fill-color:#0f1419 !important}`,
|
||||
`${SIGNED_OUT_ROOT} button:has(svg):has(.text-text > p.jf-element) svg{color:#0f1419 !important;fill:#0f1419 !important}`,
|
||||
`${SIGNED_OUT_ROOT} input,${SIGNED_OUT_ROOT} textarea{background-color:${bg} !important;color:${text} !important;border-color:${border} !important}`,
|
||||
`${SIGNED_OUT_ROOT} hr{border-color:${border} !important}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** Where X declares its variables: `:root`, its `[data-theme]` roots and the theme classes. */
|
||||
// `:host`: X's chat embed declares its tokens on its shadow host (the theme sheet is adopted inside it).
|
||||
const TOKEN_ROOTS = ':root,:host,[data-theme],.dark,.light,.dark-theme,.light-theme';
|
||||
/** The palette when it names every role (a theme's own colors); an accent-only choice keeps X's tokens. */
|
||||
function fullPalette(palette: Partial<Palette>): Palette | null {
|
||||
const { bg, surface, elevated, border, text, muted, accent } = palette;
|
||||
return bg && surface && elevated && border && text && muted && accent ? { ...palette, bg, surface, elevated, border, text, muted, accent } : null;
|
||||
}
|
||||
|
||||
/** Pure: override rules for X's palette-colored rules plus the variable and page-level overrides. */
|
||||
export function buildThemeCss(rules: Iterable<RuleLike>, source: Source, palette: Partial<Palette> & { page?: string }, vars: Record<string, string> = {}): string {
|
||||
// X's newer rules use `var(--x-white)` and Tailwind's `color-mix()` opacity form: read them as the color they paint.
|
||||
const resolve = (value: string) => resolveDeclared(value, vars);
|
||||
const out: string[] = [];
|
||||
// One declaration per variable: a full palette's token table (themeChat.ts) replaces the few below.
|
||||
const tokens = new Map<string, string>();
|
||||
const hex = (role: Role, names: string[]) => { const v = palette[role]; if (v) for (const name of names) tokens.set(name, v); };
|
||||
const hsl = (role: Role, names: string[]) => { const v = palette[role]; if (v) for (const name of names) tokens.set(name, hexToHslTriple(v)); };
|
||||
hex('bg', ['--x-bg-primary']); hex('surface', ['--x-bg-secondary']); hex('elevated', ['--x-bg-tertiary']);
|
||||
hex('text', ['--x-fg-primary']); hex('muted', ['--x-fg-secondary']); hex('accent', ['--x-blue-500']);
|
||||
hsl('bg', ['--background']); hsl('text', ['--foreground', '--color-text', '--primary']);
|
||||
hsl('border', ['--border']);
|
||||
hsl('accent', ['--color-brand', '--color-blue-500', '--chat-accent', '--ring']);
|
||||
hex('muted', ['--x-fg-tertiary']); hex('accent', ['--x-fg-brand']);
|
||||
hsl('bg', ['--color-modal-background']); hsl('border', ['--color-nested-border']);
|
||||
// X's chat / Articles / settings shells color through a token layer (semantic `--x-*` tokens, a
|
||||
// gray ramp, shadcn-style triples) in both modes. With a full palette every token is re-derived by
|
||||
// role, so no step keeps X's light-on-dark (or dark-on-light) value.
|
||||
const full = fullPalette(palette);
|
||||
if (full) for (const [name, value] of xTokenOverrides(full)) tokens.set(name, value);
|
||||
if (tokens.size) {
|
||||
// X re-declares its variables on `[data-theme]` / `.dark` roots (and Creator Studio on
|
||||
// `.jetfuel-style-root`); the override goes wherever X declares them, not just on :root.
|
||||
out.push(`${TOKEN_ROOTS}{${[...tokens].map(([name, value]) => `${name}:${value} !important`).join(';')}}`);
|
||||
if (palette.text) out.push(`.jetfuel-style-root{--color-text:${hexToHslTriple(palette.text)} !important}`);
|
||||
}
|
||||
if (palette.bg) out.push(`html,body{background-color:${palette.bg} !important}`);
|
||||
if (palette.accent) out.push(`::selection{background-color:${palette.accent}55}`);
|
||||
if (palette.bg) out.push(layerCss(palette));
|
||||
const seen = new Set<string>();
|
||||
const badges: string[] = [];
|
||||
// Class-based accent fills (unread badges, "New" pills) and the white labels on them: white is
|
||||
// also Lights out's text color, so without this the label would follow our (dark) text.
|
||||
const accentFills: string[] = [];
|
||||
const whiteLabels: string[] = [];
|
||||
// Translucent white labels (XChat's time stamp inside a sent bubble: `var(--x-white-60)`).
|
||||
const fadedLabels: string[] = [];
|
||||
const opaque = (value: string, keys: string[]) => { const parsed = value ? parseColor(value) : null; return !!parsed && parsed.alpha === null && keys.includes(parsed.key); };
|
||||
const faded = (value: string) => { const parsed = value ? parseColor(value) : null; return !!parsed && parsed.key === '255,255,255' && typeof parsed.alpha === 'number' && parsed.alpha > 0; };
|
||||
for (const rule of rules) {
|
||||
const selector = rule.selectorText;
|
||||
if (!selector || selector.length > 2000) continue;
|
||||
if (/^\.[\w-]+$/.test(selector)) {
|
||||
const background = resolve(rule.style.getPropertyValue('background-color'));
|
||||
// XChat fills its sent bubble with `hsl(var(--chat-accent))`: one of the accent variables we
|
||||
// override, so it is an accent fill even though no color literal is declared.
|
||||
if (opaque(background, source.accent) || ACCENT_VARIABLE.test(background)) accentFills.push(selector);
|
||||
const color = resolve(rule.style.getPropertyValue('color'));
|
||||
if (opaque(color, ['255,255,255'])) whiteLabels.push(selector);
|
||||
else if (faded(color)) fadedLabels.push(selector);
|
||||
}
|
||||
// react-native-web's base classes (`.css-146c3p1{color:rgb(0,0,0)}` on every Text) declare a
|
||||
// framework default, not a palette color. Re-declared with !important it beats every inline
|
||||
// Text color: the liked heart and its count (inline `color: rgb(249, 24, 128)`) turned the page
|
||||
// text color, e.g. white on a light theme over Lights out (invisible, live 2026-09-28).
|
||||
if (/^\.css-[\w-]+$/.test(selector)) continue;
|
||||
const declarations: string[] = [];
|
||||
const keep: string[] = [];
|
||||
for (const property of Object.keys(PROPERTY_ROLES)) {
|
||||
const value = rule.style.getPropertyValue(property);
|
||||
if (!value) continue;
|
||||
const resolved = resolve(value);
|
||||
const mapped = mapColor(property, resolved, source, palette);
|
||||
if (!mapped) continue;
|
||||
declarations.push(`${property}:${mapped} !important`);
|
||||
if ((property === 'color' || property === 'fill') && mapColor(property, resolved, source, palette, ['accent'])) keep.push(`${property}:${resolved} !important`);
|
||||
}
|
||||
if (!declarations.length) continue;
|
||||
const css = `${selector}{${declarations.join(';')}}`;
|
||||
if (seen.has(css)) continue;
|
||||
seen.add(css);
|
||||
out.push(css);
|
||||
// Badges are plain svgs, so rules with pseudo-elements (not allowed inside `:is()`) never hit them.
|
||||
if (keep.length && !selector.includes('::')) badges.push(`:is(${BADGE}):is(${selector}){${keep.join(';')}}`);
|
||||
}
|
||||
out.push(...buildInlineCss(source, palette));
|
||||
// White labels on accent fills follow the accent: white, or the theme's background when the
|
||||
// accent is light (High Contrast yellow, Terminal green). After the inline rules, so it wins.
|
||||
if (palette.accent) {
|
||||
const label = accentLabel(palette.accent, palette.bg);
|
||||
// Class or inline fill, class or inline label (the "See new posts" pill is a class fill with an inline label).
|
||||
const fills = [...accentFills, ...source.accent.map(key => inlineSelector('background-color', key))].join(',');
|
||||
const labels = [...whiteLabels, inlineSelector('color', '255,255,255')].join(',');
|
||||
out.push(`:is(${fills}) :is(${labels}),:is(${fills}):is(${labels}){color:${label} !important}`);
|
||||
// X's on-color label token inside an accent fill (its brand button) follows the fill too.
|
||||
out.push(`:is(${fills}){--x-fg-on-color:${label} !important}`);
|
||||
if (fadedLabels.length) {
|
||||
const [r, g, b] = hexToRgb(label);
|
||||
out.push(`:is(${fills}) :is(${fadedLabels.join(',')}){color:rgba(${r}, ${g}, ${b}, ${fadedAlpha(label, palette.accent, 0.75)}) !important}`);
|
||||
}
|
||||
}
|
||||
if (full) out.push(chatSurfaceCss(full));
|
||||
out.push(...badges);
|
||||
if (palette.bg && palette.text) out.push(signedOutCss(palette));
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
/** X's own interface font (Chirp), used when a theme keeps X's type. */
|
||||
export const X_FONT_STACK = 'TwitterChirp, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
|
||||
export type ThemeHandle = RuntimeHandle<'light' | 'dim' | 'dark'> & {
|
||||
palette(): Partial<Palette> | null;
|
||||
/** The owner's icon choice: 'theme' (follow the theme), 'site' (X's own icons) or a pack id. */
|
||||
setIcons(choice: unknown): void;
|
||||
icons(): IconChoice;
|
||||
};
|
||||
|
||||
/** Role colors for structure CSS: the theme's own, or X's current palette when it keeps X's colors. */
|
||||
export function structureColors(theme: ThemeSpec, mode: 'light' | 'dim' | 'dark'): StructureColors {
|
||||
if (theme.colors) return { ...theme.colors, page: theme.colors.page ?? theme.colors.bg };
|
||||
const hex = (key: string) => `#${key.split(',').map(v => Number(v).toString(16).padStart(2, '0')).join('')}`;
|
||||
const x = X_PALETTES[mode];
|
||||
const pick = (role: Role) => hex(x[role][0]!);
|
||||
return { bg: pick('bg'), surface: pick('surface'), elevated: pick('elevated'), border: pick('border'), text: pick('text'), muted: pick('muted'), accent: pick('accent'), page: pick('bg') };
|
||||
}
|
||||
|
||||
/**
|
||||
* The active theme resolved for plugins and the UI kit: every role color (X's current palette when the
|
||||
* theme keeps X's colors, with the accent override), corner radii, the interface font and light/dark.
|
||||
*/
|
||||
export function resolvedTheme(choice: ThemeChoice, mode: 'light' | 'dim' | 'dark'): ResolvedTheme {
|
||||
const theme = resolveTheme(choice);
|
||||
const colors = structureColors(theme, mode);
|
||||
const x = X_PALETTES[mode];
|
||||
const hex = (key: string) => `#${key.split(',').map(v => Number(v).toString(16).padStart(2, '0')).join('')}`;
|
||||
const accent = theme.colors ? colors.accent : choice.accent ?? colors.accent;
|
||||
const inverse = theme.colors?.inverse ?? hex(x.inverse[0]!);
|
||||
const onInverse = theme.colors?.onInverse ?? hex(x.onInverse[0]!);
|
||||
return normalizeResolved({
|
||||
id: theme.id,
|
||||
name: theme.name,
|
||||
mode: theme.colors ? (relativeLuminance(colors.bg) < relativeLuminance(colors.text) ? 'dark' : 'light') : mode === 'light' ? 'light' : 'dark',
|
||||
siteDefault: !theme.colors,
|
||||
colors: { ...colors, accent, onAccent: readableOn(accent), inverse, onInverse },
|
||||
radius: theme.shape.radius,
|
||||
buttonRadius: theme.shape.button,
|
||||
font: theme.font.family.length ? fontStack(theme.font.family) : X_FONT_STACK,
|
||||
fonts: pageFonts(theme),
|
||||
});
|
||||
}
|
||||
|
||||
/** The theme's font roles as the plugin API reports them in X's page (inheriting interface = Chirp). */
|
||||
export const pageFonts = (theme: ThemeSpec): ResolvedFonts => resolvedFonts(theme.font, X_FONT_STACK);
|
||||
|
||||
/** Everything a theme adds to X: palette remapping first, then type/shape/layout/canvas/motion. */
|
||||
export function buildFullCss(rules: RuleLike[], choice: ThemeChoice, mode: 'light' | 'dim' | 'dark', vars: Record<string, string> = {}): string {
|
||||
const theme = resolveTheme(choice);
|
||||
const palette = paletteFor(choice);
|
||||
const parts: string[] = [];
|
||||
if (palette) parts.push(buildThemeCss(rules, X_PALETTES[mode], { ...palette, page: theme.colors?.page }, vars));
|
||||
if (!isNeutral(theme)) parts.push(buildStructureCss(rules, theme, structureColors(theme, mode)));
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
/** X's display mode as X paints the body: X's inline body style or its theme-color meta before the
|
||||
* computed background (our own override paints the body). */
|
||||
function readXMode(win: Window): 'light' | 'dim' | 'dark' {
|
||||
const doc = win.document;
|
||||
const declared = doc.body.style.backgroundColor || doc.querySelector('meta[name="theme-color"]')?.getAttribute('content') || '';
|
||||
return detectXPalette(declared || win.getComputedStyle(doc.body).backgroundColor);
|
||||
}
|
||||
|
||||
/** Runtime: the wayBetter theme engine (themeRuntime.ts) over X: `<style id="bt-theme">` in sync while X adds rules (react-native-web inserts lazily). */
|
||||
export function installTheme(win: Window, options: ThemeRuntimeOptions = {}): ThemeHandle {
|
||||
const env: StructureEnv = { icons: 'theme' };
|
||||
const handle = installThemeRuntime(win, {
|
||||
catalog: X_THEMES,
|
||||
initialMode: 'light',
|
||||
readMode: readXMode,
|
||||
css: buildFullCss,
|
||||
resolved: resolvedTheme,
|
||||
// X's own values of the variables the palette remaps (read with the theme's sheet disabled).
|
||||
siteVars: [...X_PRIMITIVE_VARS, '--x-blue-500'],
|
||||
styleId: 'bt-theme',
|
||||
name: 'wayBetter for X',
|
||||
// Theme engine v2: components, variants, decoration and icons (themeStructure.ts).
|
||||
// The owner's icon pick travels in the theme choice (persisted natively); `setIcons` only previews one.
|
||||
staticCss: (choice, mode) => buildThemeStructureCss(resolveTheme(choice), resolvedTheme(choice, mode), { ...env, icons: choice.icons ?? env.icons, packs: choice.packs }),
|
||||
}, options);
|
||||
try { installIconGate(win); } catch (error) { console.error('[wayBetter for X] icon gate failed', error); }
|
||||
return {
|
||||
...handle,
|
||||
palette: () => paletteFor(handle.current()),
|
||||
setIcons(choice) { const next = normalizeIconChoice(choice); if (next === env.icons) return; env.icons = next; handle.refresh(); },
|
||||
icons: () => env.icons,
|
||||
};
|
||||
}
|
||||
5
apps/desktop/src/inject/themeArt.ts
Normal file
5
apps/desktop/src/inject/themeArt.ts
Normal file
File diff suppressed because one or more lines are too long
217
apps/desktop/src/inject/themeChat.ts
Normal file
217
apps/desktop/src/inject/themeChat.ts
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
// X's chat (XChat: /i/chat, also reached through /messages) is a separate app inside x.com. It does
|
||||
// not color through react-native-web's atomic classes: it has a token layer of its own (read live,
|
||||
// 2026-09-30):
|
||||
// - primitives on `:root`: `--x-white`, `--x-black`, their alpha steps (`--x-white-15`), `--x-neutral-*`;
|
||||
// - semantic tokens per `[data-theme]`: `--x-bg-*`, `--x-fg-*`, `--x-border-*`, `--x-btn-*`,
|
||||
// `--x-fg-alpha-*` / `--x-bg-alpha-*`, `--x-hover-subtle`, `--x-tooltip-*`;
|
||||
// - shadcn-style HSL triples: `--background`, `--color-text`, `--card`, `--popover`, `--muted`, …,
|
||||
// `--chat-accent`, the `--color-gray-*` ramp and the `--color-blue-*` scale;
|
||||
// and Tailwind utilities over them (`.bg-btn-tertiary{background-color:var(--x-btn-tertiary)}`).
|
||||
// The theme re-declares the semantic tokens by role, so every utility follows without a rule of its
|
||||
// own, and X's local re-assignments (`[--x-btn-tertiary:var(--x-btn-tertiary-opaque)]` on the
|
||||
// floating header and composer) keep working. What tokens cannot promise (the pinned-message pill that
|
||||
// floats over the messages, a link inside a sent bubble, the scrollbar literal) gets a rule by X's
|
||||
// own test ids. Every pair below is checked: text 7:1, secondary text and links 4.5:1, labels 4.5:1.
|
||||
|
||||
import { contrastRatio, hexToRgb, mix, relativeLuminance } from '../../../../waybetter/packages/runtime/src/themeApi.ts';
|
||||
import { reach, rgba, type Palette } from '../../../../waybetter/packages/runtime/src/themeSpec.ts';
|
||||
|
||||
/** X's status colors (its 500 steps); a theme keeps their hue and only fixes their contrast. */
|
||||
const STATUS = { destructive: '#f4212e', success: '#00ba7c', warning: '#ffd400', subscribe: '#c936cc' } as const;
|
||||
/** The alpha steps X declares for `--x-fg-alpha-*` / `--x-bg-alpha-*`. */
|
||||
const ALPHA_STEPS = [0, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 85, 90, 95, 100];
|
||||
/** Steps of X's `--x-blue-*` / `--color-blue-*` scales: 0 sits next to the background, 1100 next to the text. */
|
||||
const BLUE_STEPS = [0, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100];
|
||||
|
||||
/**
|
||||
* X's primitives the palette remap resolves inside a rule (`.text-white{color:var(--x-white)}`,
|
||||
* `color-mix(in oklab, var(--x-white) 15%, transparent)`): read from the page with the theme off.
|
||||
*/
|
||||
export const X_PRIMITIVE_VARS: string[] = [
|
||||
'--x-white', '--x-black',
|
||||
...['00', '02', '04', '08', '10', '15', '20', '30', '40', '50', '60', '70', '80', '85', '90', '95'].flatMap(step => [`--x-white-${step}`, `--x-black-${step}`]),
|
||||
...['000', '050', '100', '200', '300', '400', '500', '600', '700', '800', '900', '1000', '1100'].map(step => `--x-neutral-${step}`),
|
||||
];
|
||||
|
||||
/** `"H S% L%"`, the form X's Tailwind variables use inside `hsl(var(--x))`; one decimal, so a contrast pair survives the round trip. */
|
||||
export function hexToHslTriple(hex: string): string {
|
||||
const [r, g, b] = hexToRgb(hex).map(v => v / 255) as [number, number, number];
|
||||
const max = Math.max(r, g, b), min = Math.min(r, g, b), l = (max + min) / 2;
|
||||
let h = 0, s = 0;
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
|
||||
h *= 60;
|
||||
}
|
||||
const n = (value: number) => +value.toFixed(1);
|
||||
return `${n(h)} ${n(s * 100)}% ${n(l * 100)}%`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The label on an accent fill (a sent bubble, an unread badge, X's brand button): white or the theme's
|
||||
* background as before, whichever reads better; when neither reaches 4.5:1 (a mid-tone accent on a
|
||||
* mid-tone theme) black or white, one of which always does.
|
||||
*/
|
||||
export function accentLabel(accent: string, bg = '#000000'): string {
|
||||
const preferred = contrastRatio(accent, '#ffffff') >= contrastRatio(accent, bg) ? '#ffffff' : bg;
|
||||
if (contrastRatio(accent, preferred) >= 4.5) return preferred;
|
||||
return contrastRatio(accent, '#ffffff') >= contrastRatio(accent, '#000000') ? '#ffffff' : '#000000';
|
||||
}
|
||||
|
||||
/** The lowest alpha from `wanted` up at which `label` over `fill` still reaches `ratio` (X's faded time stamp in a bubble). */
|
||||
export function fadedAlpha(label: string, fill: string, wanted: number, ratio = 4.5): number {
|
||||
for (let alpha = wanted; alpha < 1; alpha += 0.05) {
|
||||
if (contrastRatio(mix(fill, label, alpha), fill) >= ratio) return +alpha.toFixed(2);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
export type ChatColors = {
|
||||
bg: string; surface: string; elevated: string; border: string; text: string; muted: string; accent: string;
|
||||
inverse: string; onInverse: string;
|
||||
/** Label on an accent fill. */
|
||||
onAccent: string;
|
||||
/** Scales X's faint text-colored tints (hover rows, the selected conversation, ghost buttons) so text on them keeps its contrast. */
|
||||
tintScale: number;
|
||||
/** The pinned-message pill and other surfaces that float over the messages: opaque. */
|
||||
floating: string;
|
||||
/** Links and mentions in a received bubble. */
|
||||
link: string;
|
||||
/** A small filled tile inside a bubble (the link card's icon): a step off the raised surface, never the hairline color. */
|
||||
tile: string;
|
||||
};
|
||||
|
||||
/** The chat's colors from a full palette, each pair at its guaranteed contrast. */
|
||||
export function chatColors(palette: Palette): ChatColors {
|
||||
const { bg, surface, elevated, border } = palette;
|
||||
const surfaces = [bg, surface, elevated];
|
||||
const text = reach(palette.text, surfaces, 7);
|
||||
const muted = reach(palette.muted, surfaces, 4.5);
|
||||
const accent = reach(palette.accent, surfaces, 4.5);
|
||||
const inverse = reach(palette.inverse ?? text, [bg], 3);
|
||||
const onInverse = reach(palette.onInverse ?? bg, [inverse], 4.5);
|
||||
// X tints rows and buttons with its text color: 4–10% at rest (the selected conversation, the
|
||||
// composer, ghost buttons), 15% hovered, 20% pressed. A tint moves the surface toward the text, so
|
||||
// text on it loses contrast; the whole range shrinks until text (7:1) and secondary text (4.5:1)
|
||||
// still read on the hovered step over the panel and over a menu. A palette with no room (text
|
||||
// already at its limit on the background) gets no tint at all rather than unreadable rows.
|
||||
let tintScale = 1;
|
||||
const holds = (scale: number) => [bg, surface].every(base => {
|
||||
const tinted = mix(base, text, 0.15 * scale);
|
||||
return contrastRatio(muted, tinted) >= 4.5 && contrastRatio(text, tinted) >= 7;
|
||||
});
|
||||
while (tintScale > 0 && !holds(tintScale)) tintScale = +(tintScale - 0.05).toFixed(2);
|
||||
// X fills small tiles with the ramp steps it also draws dividers with (gray-100/200). A theme whose
|
||||
// hairline is as bright as its text (High Contrast: white lines on black) would paint the tile in
|
||||
// the text color. As a fill it is a step off the raised surface, toward the text where the text
|
||||
// still reads on it and away from it otherwise.
|
||||
const toward = mix(elevated, text, 0.08);
|
||||
const reads = (tile: string) => contrastRatio(text, tile) >= 7 && contrastRatio(muted, tile) >= 4.5;
|
||||
const tile = reads(toward) ? toward : reads(mix(elevated, bg, 0.5)) ? mix(elevated, bg, 0.5) : elevated;
|
||||
return { bg, surface, elevated, border, text, muted, accent, inverse, onInverse, onAccent: accentLabel(accent, bg), tintScale, floating: elevated, link: accent, tile };
|
||||
}
|
||||
|
||||
/** X's text-colored tint at `alpha` (of X's own scale), as the theme allows it. */
|
||||
const tintAlpha = (colors: ChatColors, alpha: number) => (alpha <= 0.2 ? +(alpha * colors.tintScale).toFixed(3) : alpha);
|
||||
|
||||
/**
|
||||
* X's semantic tokens re-declared from the palette: `[name, value]` pairs for `:root` and wherever
|
||||
* X declares them. Hex and `rgba()` for the `--x-*` layer, HSL triples for the shadcn-style layer.
|
||||
*/
|
||||
export function xTokenOverrides(palette: Palette): Array<[string, string]> {
|
||||
const c = chatColors(palette);
|
||||
const { bg, surface, elevated, border, text, muted, accent } = c;
|
||||
const tint = (alpha: number) => rgba(text, tintAlpha(c, alpha));
|
||||
const solid = (alpha: number) => mix(bg, text, tintAlpha(c, alpha));
|
||||
// Hover and pressed steps of a fill move away from its label, so the label never loses contrast.
|
||||
const away = (fill: string, label: string, t: number) => mix(fill, relativeLuminance(label) > relativeLuminance(fill) ? '#000000' : '#ffffff', t);
|
||||
// A hovered surface steps toward the text as X's does, or away from it when that would cost the text its contrast.
|
||||
const raised = (base: string, t: number) => {
|
||||
const toward = mix(base, text, t);
|
||||
return contrastRatio(text, toward) >= 7 && contrastRatio(muted, toward) >= 4.5 ? toward : away(base, text, t);
|
||||
};
|
||||
const status = (color: string) => reach(color, [bg, surface, elevated], 4.5);
|
||||
const out: Array<[string, string]> = [
|
||||
['--x-bg-primary', bg], ['--x-bg-secondary', surface], ['--x-bg-tertiary', elevated], ['--x-bg-quaternary', tint(0.04)],
|
||||
['--x-bg-modal', surface], ['--x-bg-sheets', surface], ['--x-bg-inputs', tint(0.08)],
|
||||
['--x-bg-destructive', mix(bg, STATUS.destructive, 0.14)], ['--x-bg-success', mix(bg, STATUS.success, 0.14)], ['--x-bg-info', mix(bg, accent, 0.14)],
|
||||
['--x-bg-warning', mix(bg, STATUS.warning, 0.14)], ['--x-bg-subscribe', mix(bg, STATUS.subscribe, 0.14)],
|
||||
['--x-fg-primary', text], ['--x-fg-secondary', muted], ['--x-fg-tertiary', muted], ['--x-fg-inverted', c.onInverse], ['--x-fg-brand', accent],
|
||||
['--x-fg-destructive', status(STATUS.destructive)], ['--x-fg-success', status(STATUS.success)], ['--x-fg-warning', status(STATUS.warning)], ['--x-fg-subscribe', status(STATUS.subscribe)],
|
||||
['--x-border-normal', border], ['--x-border-hover', mix(border, text, 0.25)], ['--x-border-active', mix(border, text, 0.5)],
|
||||
['--x-border-media', tint(0.06)], ['--x-border-elevated', mix(border, text, 0.15)],
|
||||
['--x-btn-primary', c.inverse], ['--x-btn-primary-hover', away(c.inverse, c.onInverse, 0.1)], ['--x-btn-primary-pressed', away(c.inverse, c.onInverse, 0.18)],
|
||||
['--x-btn-secondary', elevated], ['--x-btn-secondary-hover', raised(elevated, 0.06)], ['--x-btn-secondary-pressed', raised(elevated, 0.12)],
|
||||
['--x-btn-tertiary', tint(0.1)], ['--x-btn-tertiary-hover', tint(0.15)], ['--x-btn-tertiary-pressed', tint(0.2)],
|
||||
['--x-btn-tertiary-opaque', solid(0.1)], ['--x-btn-tertiary-opaque-hover', solid(0.15)], ['--x-btn-tertiary-opaque-pressed', solid(0.2)],
|
||||
['--x-btn-ghost-hover', tint(0.08)], ['--x-btn-ghost-pressed', tint(0.15)],
|
||||
['--x-btn-inverted', bg], ['--x-btn-inverted-hover', solid(0.08)], ['--x-btn-inverted-pressed', solid(0.15)],
|
||||
['--x-btn-brand', accent], ['--x-btn-brand-hover', away(accent, c.onAccent, 0.1)], ['--x-btn-brand-pressed', away(accent, c.onAccent, 0.18)],
|
||||
['--x-hover-subtle', tint(0.08)], ['--x-tooltip-bg', text], ['--x-tooltip-fg', bg], ['--x-ring', accent],
|
||||
];
|
||||
for (const step of ALPHA_STEPS) {
|
||||
const name = String(step).padStart(2, '0');
|
||||
out.push([`--x-fg-alpha-${name}`, rgba(text, tintAlpha(c, step / 100))], [`--x-bg-alpha-${name}`, rgba(bg, step / 100)]);
|
||||
}
|
||||
// The accent scale keeps its direction: low steps fade into the background, high steps into the text.
|
||||
const blue = (step: number) => step === 500 ? accent : step < 500 ? mix(accent, bg, (500 - step) / 500 * 0.86) : mix(accent, text, (step - 500) / 600 * 0.86);
|
||||
for (const step of BLUE_STEPS) {
|
||||
out.push([`--x-blue-${String(step).padStart(3, '0')}`, blue(step)], [`--color-blue-${step}`, hexToHslTriple(blue(step))]);
|
||||
}
|
||||
const hsl = (names: string[], color: string) => { for (const name of names) out.push([name, hexToHslTriple(color)]); };
|
||||
hsl(['--background', '--color-background'], bg);
|
||||
hsl(['--foreground', '--color-text', '--primary', '--card-foreground', '--popover-foreground', '--secondary-foreground'], text);
|
||||
hsl(['--card', '--popover'], surface);
|
||||
hsl(['--secondary', '--muted'], elevated);
|
||||
hsl(['--muted-foreground'], muted);
|
||||
hsl(['--border', '--input', '--color-nested-border'], border);
|
||||
hsl(['--color-brand', '--chat-accent', '--ring'], accent);
|
||||
hsl(['--color-brand-foreground', '--chat-accent-foreground', '--primary-foreground'], c.onAccent);
|
||||
// shadcn's "accent" is a highlighted row, not the brand color: a wash of the accent with readable text.
|
||||
let strength = 0.2;
|
||||
while (strength > 0 && contrastRatio(text, mix(bg, accent, strength)) < 7) strength = +(strength - 0.02).toFixed(2);
|
||||
hsl(['--accent'], mix(bg, accent, strength));
|
||||
hsl(['--accent-foreground'], text);
|
||||
// X's gray ramp: 0/50 are surfaces, 100/200 dividers, 700 secondary text, 1000/1100 primary text.
|
||||
const ramp: Array<[number, string]> = [
|
||||
[0, surface], [50, elevated], [100, border], [200, mix(border, muted, 0.15)], [300, mix(border, muted, 0.35)],
|
||||
[400, mix(border, muted, 0.55)], [500, mix(border, muted, 0.75)], [600, mix(border, muted, 0.9)], [700, muted],
|
||||
[800, mix(muted, text, 0.35)], [900, mix(muted, text, 0.6)], [1000, mix(muted, text, 0.85)], [1100, text],
|
||||
];
|
||||
for (const [step, color] of ramp) out.push([`--color-gray-${step}`, hexToHslTriple(color)]);
|
||||
return out;
|
||||
}
|
||||
|
||||
const CHAT = '[data-testid="dm-container"]';
|
||||
/** XChat's own menus and popups (Base UI, portaled into `<body>`, not into X's `#layers`). */
|
||||
const MENU = '[data-slot="xds-menu-content"]';
|
||||
|
||||
/**
|
||||
* Rules for the chat surfaces tokens cannot settle, by X's own test ids and token classes. Colors only:
|
||||
* no size, position or display is declared, so X's panel layout (inbox + conversation above 918px of
|
||||
* container width, one panel below) and its floating header and composer stay X's.
|
||||
*/
|
||||
export function chatSurfaceCss(palette: Palette): string {
|
||||
const c = chatColors(palette);
|
||||
const thumb = rgba(c.muted, 0.5);
|
||||
return [
|
||||
// The pinned-message pill floats over the messages (X: 15% white with a blur). Whatever scrolls
|
||||
// under it, its two lines must read: an opaque raised surface with the theme's hairline.
|
||||
`[data-testid="pinned-message-banner"] > div{background-color:${c.floating} !important;border-color:${c.border} !important}`,
|
||||
`[data-testid="pinned-message-banner"] .text-primary{color:${c.text} !important}`,
|
||||
`[data-testid="pinned-message-banner"] .text-secondary{color:${c.muted} !important}`,
|
||||
// A sent bubble is an accent fill: everything in it takes the fill's label color, links included.
|
||||
`${CHAT} .bg-chat-accent{background-color:${c.accent} !important;color:${c.onAccent} !important}`,
|
||||
`${CHAT} .bg-chat-accent :is(a,.text-chat-accent,.text-brand){color:${c.onAccent} !important;text-decoration:underline}`,
|
||||
// Links and mentions in a received bubble, and the quoted original above a sent reply.
|
||||
`${CHAT} .text-chat-accent{color:${c.link} !important}`,
|
||||
// Divider steps of X's gray ramp used as a fill (the link card's icon tile).
|
||||
`${CHAT} :is(.bg-gray-100,.bg-gray-200){background-color:${c.tile} !important}`,
|
||||
// Menus: an opaque themed surface with the theme's hairline (X paints them with its sheet color).
|
||||
`${MENU}{background-color:${c.surface} !important;border-color:${c.border} !important;color:${c.text} !important}`,
|
||||
// X's thin scrollbars carry a literal gray.
|
||||
`${CHAT} .scrollbar-thin-custom{scrollbar-color:${thumb} transparent !important}`,
|
||||
`${CHAT} .scrollbar-thin-custom::-webkit-scrollbar-thumb{background-color:${thumb} !important}`,
|
||||
].join('\n');
|
||||
}
|
||||
42
apps/desktop/src/inject/themeIcons.ts
Normal file
42
apps/desktop/src/inject/themeIcons.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Which of X's `<svg>` boxes is which icon (framework themeIcons.ts draws a pack over them). The
|
||||
// container is the matcher wherever X has a stable hook (test ids, link targets); the set state of
|
||||
// an action comes from its own test id (`like` / `unlike`). Read live on x.com 2026-09-30 (nav,
|
||||
// actions, composer toolbar); `share` and the composer tools are matched by their accessible
|
||||
// container in the English UI only where no test id exists, so they sit in groups of their own.
|
||||
|
||||
import type { IconTable } from '../../../../waybetter/packages/runtime/src/themeIcons.ts';
|
||||
|
||||
const NAV = 'header[role="banner"] nav[role="navigation"]';
|
||||
const ACT = 'article[data-testid="tweet"] [role="group"]';
|
||||
const TOOLS = '[data-testid="toolBar"] nav';
|
||||
|
||||
export const X_ICONS: IconTable = {
|
||||
home: { ctx: `${NAV} [data-testid="AppTabBar_Home_Link"] svg`, group: 'nav', core: true },
|
||||
explore: { ctx: `${NAV} [data-testid="AppTabBar_Explore_Link"] svg`, group: 'nav', core: true },
|
||||
notifications: { ctx: `${NAV} [data-testid="AppTabBar_Notifications_Link"] svg`, group: 'nav', core: true },
|
||||
messages: { ctx: `${NAV} [data-testid="AppTabBar_DirectMessage_Link"] svg`, group: 'nav' },
|
||||
grok: { ctx: `${NAV} a[href="/i/grok"] svg`, group: 'nav' },
|
||||
bookmarks: { ctx: `${NAV} a[href="/i/bookmarks"] svg`, group: 'nav' },
|
||||
lists: { ctx: `${NAV} a[href$="/lists"] svg`, group: 'nav' },
|
||||
communities: { ctx: `${NAV} a[href$="/communities"] svg`, group: 'nav' },
|
||||
premium: { ctx: `${NAV} a[href^="/i/premium"] svg,${NAV} a[href^="/i/verified"] svg`, group: 'nav' },
|
||||
profile: { ctx: `${NAV} [data-testid="AppTabBar_Profile_Link"] svg`, group: 'nav', core: true },
|
||||
more: { ctx: `${NAV} [data-testid="AppTabBar_More_Menu"] svg`, group: 'nav', core: true },
|
||||
compose: { ctx: 'header[role="banner"] [data-testid="SideNav_NewTweet_Button"] svg', group: 'nav' },
|
||||
reply: { ctx: `${ACT} [data-testid="reply"] svg`, group: 'actions', core: true },
|
||||
repost: { ctx: `${ACT} [data-testid="retweet"] svg`, group: 'actions', core: true },
|
||||
'repost.on': { ctx: `${ACT} [data-testid="unretweet"] svg`, group: 'actions' },
|
||||
like: { ctx: `${ACT} [data-testid="like"] svg`, group: 'actions', core: true },
|
||||
'like.on': { ctx: `${ACT} [data-testid="unlike"] svg`, group: 'actions' },
|
||||
views: { ctx: `${ACT} a[href$="/analytics"] svg`, group: 'actions' },
|
||||
bookmark: { ctx: `${ACT} [data-testid="bookmark"] svg`, group: 'actions' },
|
||||
'bookmark.on': { ctx: `${ACT} [data-testid="removeBookmark"] svg`, group: 'actions' },
|
||||
share: { ctx: `${ACT} > div:last-child [role="button"] svg`, group: 'actions' },
|
||||
media: { ctx: `${TOOLS} [role="button"]:has(+ input[data-testid="fileInput"]) svg,${TOOLS} [data-testid="fileInput"] ~ [role="button"] svg`, group: 'composer' },
|
||||
gif: { ctx: `${TOOLS} [data-testid="gifSearchButton"] svg`, group: 'composer' },
|
||||
poll: { ctx: `${TOOLS} [data-testid="createPollButton"] svg`, group: 'composer' },
|
||||
emoji: { ctx: `${TOOLS} [aria-label="Add emoji"] svg`, group: 'composer' },
|
||||
schedule: { ctx: `${TOOLS} [data-testid="scheduleOption"] svg`, group: 'composer' },
|
||||
location: { ctx: `${TOOLS} [data-testid="geoButton"] svg`, group: 'composer' },
|
||||
search: { ctx: 'form[role="search"] [data-testid="SearchBox_Search_Input_label"] svg', group: 'misc' },
|
||||
};
|
||||
149
apps/desktop/src/inject/themeParts.ts
Normal file
149
apps/desktop/src/inject/themeParts.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
// X's parts for theme engine v2: which of X's elements each generic component is (framework
|
||||
// themeComponents.ts), where decoration goes, and how X draws each layout variant. Every selector
|
||||
// is anchored on a test id, a role or an attribute; a generic tag only ends a selector as a text leaf
|
||||
// under such an anchor. `seen` notes the day a selector was read on live x.com (Lights out, the two
|
||||
// test accounts); the fixtures in scripts/theme-matrix carry the same markup.
|
||||
|
||||
import type { PartMap, RoleColors } from '../../../../waybetter/packages/runtime/src/themeComponents.ts';
|
||||
import { cssString, type DecorTargets } from '../../../../waybetter/packages/runtime/src/themeDecor.ts';
|
||||
import type { VariantSkins } from '../../../../waybetter/packages/runtime/src/themeVariants.ts';
|
||||
|
||||
const POST = 'article[data-testid="tweet"]';
|
||||
const COLUMN = '[data-testid="primaryColumn"]';
|
||||
/** The main column on every route but chat (a drawn bar above X's chat app would push its composer out of the window). */
|
||||
/** X's chat app: in the page, or the host of its embed (an open shadow root the page's :has() cannot look into, 2026-10-01). */
|
||||
const CHAT_APP = ':is([data-testid="dm-container"],[data-testid="xchatEmbedRoute"])';
|
||||
const FRAMED = `[data-testid="primaryColumn"]:not(:has(${CHAT_APP}))`;
|
||||
const RAIL = 'header[role="banner"]';
|
||||
const NAV = `${RAIL} nav[role="navigation"]`;
|
||||
const ACTIONS = ['reply', 'retweet', 'unretweet', 'like', 'unlike', 'bookmark', 'removeBookmark'].map(id => `[data-testid="${id}"]`).join(',');
|
||||
const AVATAR = '[data-testid^="UserAvatar-Container-"]';
|
||||
|
||||
/** Read live 2026-09-30 unless marked otherwise. */
|
||||
export const X_PARTS: PartMap = {
|
||||
nav: { sel: NAV },
|
||||
navItem: { sel: `${NAV} > :is(a,button) > div`, text: `${NAV} > :is(a,button) > div :is(span,svg)` },
|
||||
topBar: { sel: `${COLUMN} > div > div:first-child` },
|
||||
tabs: { sel: `${COLUMN} [role="tablist"]` },
|
||||
tab: { sel: `${COLUMN} [role="tablist"] [role="tab"]`, text: `${COLUMN} [role="tablist"] [role="tab"] span` },
|
||||
post: { sel: POST },
|
||||
avatar: { sel: `${POST} ${AVATAR},${POST} ${AVATAR} :is(div,a,img)`, skip: ['size'] },
|
||||
displayName: { sel: `${POST} [data-testid="User-Name"] > div:first-child`, text: `${POST} [data-testid="User-Name"] > div:first-child :is(span,a)` },
|
||||
handle: { sel: `${POST} [data-testid="User-Name"] > div:nth-child(2)`, text: `${POST} [data-testid="User-Name"] > div:nth-child(2) :is(span,a)` },
|
||||
postText: { sel: `${POST} [data-testid="tweetText"]`, text: `${POST} [data-testid="tweetText"],${POST} [data-testid="tweetText"] :is(span,a)` },
|
||||
meta: { sel: `${POST} a[href*="/status/"] > time` },
|
||||
actionBar: { sel: `${POST} [role="group"]` },
|
||||
action: { sel: `${POST} [role="group"] :is(${ACTIONS})` },
|
||||
count: { sel: `${POST} [role="group"] [data-testid="app-text-transition-container"]`, text: `${POST} [role="group"] [data-testid="app-text-transition-container"] span` },
|
||||
buttonPrimary: { sel: '[data-testid="tweetButtonInline"],[data-testid="tweetButton"],[data-testid="SideNav_NewTweet_Button"]', text: ':is([data-testid="tweetButtonInline"],[data-testid="tweetButton"],[data-testid="SideNav_NewTweet_Button"]) :is(span,div[dir])' },
|
||||
buttonSecondary: { sel: '[data-testid$="-follow"],[data-testid$="-unfollow"]', text: ':is([data-testid$="-follow"],[data-testid$="-unfollow"]) span' },
|
||||
// Live 2026-10-01: the painted box is three levels above the input's label (a div, no <label>).
|
||||
search: { sel: 'form[role="search"] div:has(> div > div > [data-testid="SearchBox_Search_Input_label"])', text: 'form[role="search"] input' },
|
||||
composer: { sel: '[data-testid="tweetTextarea_0"]', text: '[data-testid="tweetTextarea_0"] :is(span,div)' },
|
||||
composerTool: { sel: '[data-testid="toolBar"] nav [role="button"]', text: '[data-testid="toolBar"] nav [role="button"] svg' },
|
||||
sidebarCard: { sel: '[data-testid="sidebarColumn"] div:has(> :is(aside[role="complementary"],section[role="region"]))' },
|
||||
menu: { sel: '#layers [role="menu"]' },
|
||||
hoverCard: { sel: '#layers [data-testid="HoverCard"]' },
|
||||
};
|
||||
|
||||
/** Where X's decoration goes. */
|
||||
export function xDecorTargets(): DecorTargets<XSkinContext> {
|
||||
return {
|
||||
divider: `${COLUMN} [data-testid="cellInnerDiv"] > div`,
|
||||
link: `${POST} [data-testid="tweetText"] a`,
|
||||
focusable: 'a,button,[role="button"],[role="tab"],[role="link"],input,textarea,[tabindex="0"]',
|
||||
moving: `${POST},${NAV} > :is(a,button) > div,[role="tab"],[data-testid$="-follow"],[data-testid="tweetButtonInline"]`,
|
||||
pressable: `${NAV} > :is(a,button),[data-testid="tweetButtonInline"],[data-testid="tweetButton"],[data-testid$="-follow"],${POST} [role="group"] [role="button"]`,
|
||||
chrome: {
|
||||
// A window title bar on the main column, and on each sidebar card with X's own label for it.
|
||||
titlebar: (title, { colors }) => [
|
||||
`${FRAMED}::before{content:${cssString(title || 'Home')};display:block;order:-1;box-sizing:border-box;height:24px;padding:4px 8px;font:700 12px/16px "Pixelated MS Sans Serif","MS Sans Serif","Tahoma",sans-serif;letter-spacing:.2px;color:#ffffff;background:linear-gradient(90deg, ${colors.inverse}, ${colors.accent});white-space:nowrap;overflow:hidden}`,
|
||||
`[data-testid="sidebarColumn"] :is(aside[role="complementary"],section[role="region"])[aria-label]::before{content:attr(aria-label);display:block;margin:-12px -16px 10px;padding:3px 8px;font:700 12px/16px "Pixelated MS Sans Serif","MS Sans Serif","Tahoma",sans-serif;color:#ffffff;background:linear-gradient(90deg, ${colors.inverse}, ${colors.accent})}`,
|
||||
].join('\n'),
|
||||
// A newspaper masthead: the theme's title between two rules at the top of the column.
|
||||
masthead: (title, { colors, fonts }) => `${FRAMED}::before{content:${cssString(title || 'The Timeline')};display:block;order:-1;padding:18px 16px 12px;text-align:center;font:700 34px/1.1 ${fonts.heading};letter-spacing:-.01em;color:${colors.text};border-bottom:4px double ${colors.text};margin:0 16px}`,
|
||||
// A terminal prompt line above the column.
|
||||
prompt: (title, { colors, fonts }) => `${FRAMED}::before{content:${cssString(`${title || 'guest@x'}:~$ tail -f timeline`)};display:block;order:-1;padding:10px 16px;font:14px/20px ${fonts.mono};color:${colors.accent};border-bottom:1px dashed ${colors.border}}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type XSkinContext = {
|
||||
colors: RoleColors;
|
||||
fonts: { heading: string; mono: string; post: string; interface: string };
|
||||
/** The words of worded actions (`variants.actions = "labels"`). */
|
||||
labels: { reply: string; repost: string; like: string; views: string; bookmark: string; share: string };
|
||||
/** Brackets around a worded action (Terminal: `[reply 12]`). */
|
||||
brackets: boolean;
|
||||
};
|
||||
|
||||
/** Only above X's narrow breakpoint, never on chat's own row, never while the pane's rail is parked. */
|
||||
const WIDE = '@media (min-width:700px)';
|
||||
const NOT_CHAT = `html:not(:has(${CHAT_APP}))`;
|
||||
|
||||
/** How X looks in each layout variant. */
|
||||
export const X_SKINS: VariantSkins<XSkinContext> = {
|
||||
nav: {
|
||||
// The rail becomes a bar across the top: logo, items and the Post button in a row.
|
||||
top: ({ colors }) => bar('top', colors),
|
||||
bottom: ({ colors }) => bar('bottom', colors),
|
||||
icons: () => `${WIDE}{${NOT_CHAT} ${NAV} > :is(a,button) span{display:none !important}}`,
|
||||
},
|
||||
post: {
|
||||
compact: () => `${POST}{padding-top:6px !important;padding-bottom:6px !important}\n${POST} [data-testid="tweetText"]{margin-top:0 !important}`,
|
||||
cards: ({ colors }) => `${COLUMN} [data-testid="cellInnerDiv"] ${POST}{margin:6px 12px;border:1px solid ${colors.border} !important;border-radius:14px;background-color:${colors.surface} !important}\n${COLUMN} [data-testid="cellInnerDiv"] > div{border-bottom-width:0 !important}`,
|
||||
bubbles: ({ colors }) => `${COLUMN} [data-testid="cellInnerDiv"] ${POST} [data-testid="tweetText"]{background-color:${colors.surface};padding:10px 14px;border-radius:18px;margin-top:4px}\n${COLUMN} [data-testid="cellInnerDiv"] > div{border-bottom-width:0 !important}`,
|
||||
// One column set like a newspaper: small-caps bylines, a serif body, hairlines, and a drop cap on a post's own page.
|
||||
broadsheet: ({ colors, fonts }) => [
|
||||
`${POST} [data-testid="User-Name"] > div:first-child :is(span,a){font-variant-caps:all-small-caps !important;letter-spacing:.06em !important}`,
|
||||
`${POST} [data-testid="tweetText"],${POST} [data-testid="tweetText"] span{font-family:${fonts.post} !important}`,
|
||||
`${COLUMN} [data-testid="cellInnerDiv"] > div{border-bottom:1px solid ${colors.text} !important}`,
|
||||
`html[data-bt-route="status"] ${POST}[tabindex="-1"] [data-testid="tweetText"] > span:first-child::first-letter{float:left;font-size:3.2em;line-height:.9;padding:4px 6px 0 0;font-family:${fonts.post}}`,
|
||||
].join('\n'),
|
||||
},
|
||||
actions: {
|
||||
// Words instead of pictures: the icon box is hidden, the word stands next to X's own count.
|
||||
labels: ({ labels, brackets, colors }) => {
|
||||
const word = (testids: string[], text: string) => {
|
||||
const buttons = testids.map(id => `${POST} [role="group"] [data-testid="${id}"]`).join(',');
|
||||
return [
|
||||
`:is(${buttons}) svg{display:none !important}`,
|
||||
`:is(${buttons}) > div > div:first-child::before{content:${cssString(`${brackets ? '[' : ''}${text}`)};font-size:13px;font-weight:600;white-space:nowrap}`,
|
||||
...(brackets ? [`:is(${buttons}) > div::after{content:"]";font-size:13px;font-weight:600;margin-left:1px}`] : []),
|
||||
].join('\n');
|
||||
};
|
||||
return [
|
||||
word(['reply'], labels.reply), word(['retweet', 'unretweet'], labels.repost), word(['like', 'unlike'], labels.like),
|
||||
word(['bookmark', 'removeBookmark'], labels.bookmark),
|
||||
`${POST} [role="group"] :is([data-testid="unlike"],[data-testid="unretweet"],[data-testid="removeBookmark"]) > div{color:${colors.accent} !important}`,
|
||||
].join('\n');
|
||||
},
|
||||
// Counts show on hover only.
|
||||
quiet: () => `${POST}:not(:hover) [role="group"] [data-testid="app-text-transition-container"]{opacity:0 !important}`,
|
||||
},
|
||||
header: {
|
||||
solid: ({ colors }) => `${COLUMN} > div > div:first-child{background-color:${colors.bg} !important;backdrop-filter:none !important}`,
|
||||
bar: ({ colors }) => `${COLUMN} > div > div:first-child{box-shadow:0 1px 0 ${colors.border},0 2px 8px rgba(0, 0, 0, 0.12) !important}`,
|
||||
},
|
||||
sidebar: {
|
||||
hidden: () => `${WIDE}{${NOT_CHAT} [data-testid="sidebarColumn"]{display:none !important}}`,
|
||||
},
|
||||
};
|
||||
|
||||
/** The rail as a bar across the top or the bottom of the window. */
|
||||
function bar(edge: 'top' | 'bottom', colors: RoleColors): string {
|
||||
const inner = `${RAIL} > div > div`;
|
||||
return `${WIDE}{
|
||||
${NOT_CHAT} ${RAIL}{position:fixed !important;${edge}:0;left:0;right:0;z-index:30;height:56px;width:auto !important;flex-grow:0 !important;align-items:stretch !important;background-color:${colors.surface};border-${edge === 'top' ? 'bottom' : 'top'}:1px solid ${colors.border};box-shadow:0 ${edge === 'top' ? '1px' : '-1px'} 6px rgba(0, 0, 0, 0.12)}
|
||||
${NOT_CHAT} ${RAIL} > div{width:100% !important;height:56px !important}
|
||||
${NOT_CHAT} ${inner}{position:static !important;width:100% !important;height:56px !important;max-width:1280px;margin:0 auto !important}
|
||||
${NOT_CHAT} ${inner} > div{flex-direction:row !important;align-items:center !important;justify-content:space-between !important;height:56px !important;width:100% !important;padding:0 16px !important;overflow:visible !important}
|
||||
${NOT_CHAT} ${inner} > div > div{flex-direction:row !important;align-items:center !important;height:56px !important;gap:4px}
|
||||
${NOT_CHAT} ${NAV}{flex-direction:row !important;align-items:center !important;flex-wrap:nowrap !important;gap:2px}
|
||||
${NOT_CHAT} ${NAV} > :is(a,button) > div{padding:8px 10px !important}
|
||||
${NOT_CHAT} ${RAIL} [data-testid="SideNav_NewTweet_Button"]{margin:0 0 0 8px !important;width:auto !important;min-height:40px !important;padding:0 16px !important}
|
||||
${NOT_CHAT} ${RAIL} [data-testid="SideNav_AccountSwitcher_Button"]{margin:0 !important}
|
||||
${NOT_CHAT} main[role="main"]{padding-${edge}:56px !important;align-items:center !important}
|
||||
${NOT_CHAT} ${COLUMN} > div > div:first-child{${edge === 'top' ? 'top:56px !important' : ''}}
|
||||
}`;
|
||||
}
|
||||
600
apps/desktop/src/inject/themeSpec.ts
Normal file
600
apps/desktop/src/inject/themeSpec.ts
Normal file
|
|
@ -0,0 +1,600 @@
|
|||
// X's theme documents and what a theme does to X's own page structure. The theme document engine
|
||||
// (types, the schema's defaults, sanitizing, import, overrides, legibility, font roles and stacks,
|
||||
// backgrounds) is the wayBetter runtime's (waybetter/packages/runtime/src/themeSpec.ts) and is
|
||||
// re-exported here; this module adds X's built-in themes and the structure CSS (type, shape,
|
||||
// density, layout, canvas and motion) over X's own stylesheet and selectors. Pure, so it runs in
|
||||
// the X runtime, the panel previews and the tests.
|
||||
//
|
||||
// Fonts: X's CSP (`font-src 'self' https://*.twimg.com`) blocks remote and `data:` fonts, so a theme
|
||||
// may name installed system fonts, "Geist" / "Geist Mono", which wayBetter bundles and registers
|
||||
// from bytes (`FontFace(ArrayBuffer)` is not a fetch and is allowed; verified on x.com), and Google
|
||||
// Fonts the owner downloaded (provided as bytes by native code).
|
||||
|
||||
import { ART_AERO, ART_VAPOR } from './themeArt.ts';
|
||||
import {
|
||||
BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, SYSTEM_SANS as SANS, fontStack, pageBackgroundCss, rgba, sanitizeSpec, withRoles,
|
||||
type Density, type FontChoice, type FontRole, type ThemeColors, type ThemeSpec,
|
||||
} from '../../../../waybetter/packages/runtime/src/themeSpec.ts';
|
||||
import type { RuleLike } from '../../../../waybetter/packages/runtime/src/themeRuntime.ts';
|
||||
|
||||
export type { RuleLike } from '../../../../waybetter/packages/runtime/src/themeRuntime.ts';
|
||||
export * from '../../../../waybetter/packages/runtime/src/themeSpec.ts';
|
||||
|
||||
/** X's own type (Chirp): the first font choice in the panel's pickers (an empty stack keeps it). */
|
||||
export const X_FONT_CHOICE: FontChoice = { id: 'chirp', label: "X's Chirp", family: [] };
|
||||
/** Every font choice the panel offers for X. */
|
||||
export const X_FONT_CHOICES: FontChoice[] = [X_FONT_CHOICE, ...FONT_CHOICES];
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Built-in themes
|
||||
|
||||
const V1_THEMES: ThemeSpec[] = [
|
||||
{
|
||||
id: 'x', name: 'X default', description: "X's own look. Follows Default, Dim or Lights out from X's Display settings.",
|
||||
author: 'X', version: 1, mode: 'auto', colors: null,
|
||||
font: BASE_FONT, shape: BASE_SHAPE, layout: BASE_LAYOUT, background: { kind: 'none' }, effects: BASE_EFFECTS, css: '',
|
||||
},
|
||||
{
|
||||
id: 'classic', name: 'Classic Twitter', description: '2012 on a sky-blue canvas: Helvetica, square-ish cards, tight rows and the old link blue.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'light',
|
||||
colors: {
|
||||
page: '#c0deed', bg: '#ffffff', surface: '#f5f8fa', elevated: '#e8f1f7', border: '#e1e8ed',
|
||||
text: '#292f33', muted: '#5b6b78', accent: '#0077b0', inverse: '#0077b0', onInverse: '#ffffff',
|
||||
},
|
||||
font: withRoles({ family: ['Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif'], tweet: [], scale: 0.94, weight: 400, bold: 700, tracking: 0, leading: 0 }),
|
||||
shape: { radius: 5, button: 5, avatar: 'rounded' },
|
||||
layout: { column: 590, sidebar: 320, density: 'compact', cards: false, frame: true },
|
||||
background: { kind: 'pattern', pattern: 'clouds', ink: '#ffffff', opacity: 0.55, size: 220 },
|
||||
effects: { motion: 120, hover: 'tint', shadow: 'soft', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'night-ink', name: 'Night Ink', description: 'Blue-black and Geist. Compact rows, soft corners, a quiet glow behind the timeline.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#05060a', bg: '#07080c', surface: '#0d1017', elevated: '#151924', border: '#1c2130',
|
||||
text: '#eef0f7', muted: '#8e95ab', accent: '#5b8cff', inverse: '#eef0f7', onInverse: '#07080c',
|
||||
},
|
||||
font: withRoles({ family: ['Geist', ...SANS], tweet: [], scale: 0.96, weight: 400, bold: 600, tracking: -0.006, leading: 0 }),
|
||||
shape: { radius: 12, button: 10, avatar: 'rounded' },
|
||||
layout: { column: 640, sidebar: 340, density: 'compact', cards: false, frame: true },
|
||||
background: { kind: 'gradient', from: '#05060a', to: '#05060a', angle: 180, glow: '#233a8f' },
|
||||
effects: { motion: 160, hover: 'tint', shadow: 'deep', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'terminal', name: 'Terminal', description: 'Phosphor green on a CRT. Monospace everything, square corners, scanlines.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#020402', bg: '#040804', surface: '#081008', elevated: '#0d180d', border: '#173117',
|
||||
text: '#b6f7a8', muted: '#6fb363', accent: '#3dff7a', inverse: '#3dff7a', onInverse: '#031003',
|
||||
},
|
||||
font: withRoles({ family: ['Geist Mono', 'Cascadia Mono', 'Consolas', 'Menlo', 'ui-monospace', 'monospace'], tweet: [], scale: 0.92, weight: 400, bold: 700, tracking: 0, leading: 0 }),
|
||||
shape: { radius: 0, button: 0, avatar: 'square' },
|
||||
layout: { column: 620, sidebar: 330, density: 'compact', cards: false, frame: true },
|
||||
background: { kind: 'pattern', pattern: 'scanlines', ink: '#3dff7a', opacity: 0.05, size: 4 },
|
||||
effects: { motion: 0, hover: 'glow', shadow: 'none', crt: true },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'paper', name: 'Paper', description: 'Warm newsprint. Posts as cards set in a serif reading face, with ink-red links.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'light',
|
||||
colors: {
|
||||
page: '#e9e2d3', bg: '#fbf8f1', surface: '#f6f2e8', elevated: '#efe8da', border: '#ddd3c1',
|
||||
text: '#2a241d', muted: '#665b4e', accent: '#a8321f', inverse: '#2a241d', onInverse: '#fbf8f1',
|
||||
},
|
||||
font: withRoles({ family: SANS, tweet: ['Charter', 'Iowan Old Style', 'Georgia', 'Cambria', 'serif'], scale: 1, weight: 400, bold: 650, tracking: 0, leading: 1.5 }),
|
||||
shape: { radius: 12, button: 10, avatar: 'circle' },
|
||||
layout: { column: 620, sidebar: 330, density: 'comfortable', cards: true, frame: false },
|
||||
background: { kind: 'pattern', pattern: 'paper', ink: '#7a6a50', opacity: 0.1, size: 180 },
|
||||
effects: { motion: 180, hover: 'lift', shadow: 'soft', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'dracula', name: 'Dracula', description: 'The editor classic: purple links, pink buttons, Geist on graphite with a faint dot grid.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#1d1e27', bg: '#282a36', surface: '#2d2f3d', elevated: '#353848', border: '#44475a',
|
||||
text: '#f8f8f2', muted: '#a9b1d6', accent: '#bd93f9', inverse: '#ff79c6', onInverse: '#21222c',
|
||||
},
|
||||
font: withRoles({ family: ['Geist', ...SANS], tweet: [], scale: 0.97, weight: 400, bold: 600, tracking: -0.004, leading: 1.45 }),
|
||||
shape: { radius: 8, button: 8, avatar: 'rounded' },
|
||||
layout: { column: 620, sidebar: 340, density: 'default', cards: false, frame: true },
|
||||
background: { kind: 'pattern', pattern: 'dots', ink: '#bd93f9', opacity: 0.16, size: 22 },
|
||||
effects: { motion: 140, hover: 'tint', shadow: 'deep', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'nord', name: 'Nord', description: 'Arctic slate and frost blue. Floating cards, pill buttons, generous rows and an aurora glow.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#232831', bg: '#2e3440', surface: '#333a47', elevated: '#3b4252', border: '#4c566a',
|
||||
text: '#eceff4', muted: '#b4bdcc', accent: '#88c0d0', inverse: '#88c0d0', onInverse: '#242933',
|
||||
},
|
||||
font: withRoles({ family: ['Segoe UI Variable Text', 'Avenir Next', 'Segoe UI', '-apple-system', 'system-ui', 'sans-serif'], tweet: [], scale: 1, weight: 400, bold: 600, tracking: 0.004, leading: 1.5 }),
|
||||
shape: { radius: 14, button: 9999, avatar: 'circle' },
|
||||
layout: { column: 640, sidebar: 340, density: 'comfortable', cards: true, frame: false },
|
||||
background: { kind: 'gradient', from: '#232831', to: '#1b1f27', angle: 165, glow: '#3f6d7c' },
|
||||
effects: { motion: 220, hover: 'lift', shadow: 'soft', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'tokyo-night', name: 'Tokyo Night', description: 'Neon city after rain: indigo and lavender, a wide compact column, tight corners and a street grid.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#13141c', bg: '#1a1b26', surface: '#1f2130', elevated: '#24283b', border: '#2f3549',
|
||||
text: '#c0caf5', muted: '#9099c4', accent: '#7aa2f7', inverse: '#bb9af7', onInverse: '#16161e',
|
||||
},
|
||||
font: withRoles({ family: ['Geist', ...SANS], tweet: [], scale: 0.95, weight: 400, bold: 600, tracking: -0.01, leading: 0 }),
|
||||
shape: { radius: 6, button: 6, avatar: 'rounded' },
|
||||
layout: { column: 680, sidebar: 330, density: 'compact', cards: false, frame: true },
|
||||
background: { kind: 'pattern', pattern: 'grid', ink: '#7aa2f7', opacity: 0.06, size: 36 },
|
||||
effects: { motion: 120, hover: 'glow', shadow: 'deep', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'solarized-light', name: 'Solarized Light', description: 'Ethan Schoonover’s cream and cyan on engineering paper. A wide reading column with square corners.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'light',
|
||||
colors: {
|
||||
page: '#eee8d5', bg: '#fdf6e3', surface: '#fbf3dc', elevated: '#f3ecd6', border: '#e3dbc3',
|
||||
text: '#073642', muted: '#4c6168', accent: '#1d6ea8', inverse: '#1d6ea8', onInverse: '#fdf6e3',
|
||||
},
|
||||
font: withRoles({ family: ['Segoe UI Variable Text', 'Avenir Next', 'Segoe UI', '-apple-system', 'system-ui', 'sans-serif'], tweet: [], scale: 1.02, weight: 400, bold: 650, tracking: 0, leading: 1.5 }),
|
||||
shape: { radius: 3, button: 3, avatar: 'square' },
|
||||
layout: { column: 680, sidebar: 320, density: 'comfortable', cards: false, frame: true },
|
||||
background: { kind: 'pattern', pattern: 'grid', ink: '#93a1a1', opacity: 0.22, size: 24 },
|
||||
effects: { motion: 150, hover: 'tint', shadow: 'soft', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'frutiger-aero', name: 'Frutiger Aero', description: 'A glossy 2008 sky: bubbles over green hills, glass cards, Segoe and shiny pill buttons.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'light',
|
||||
colors: {
|
||||
page: '#d8f0fc', bg: '#f7fcff', surface: '#f2faff', elevated: '#dff1fb', border: '#b4dbf0',
|
||||
text: '#0a2638', muted: '#35586e', accent: '#0667a8', inverse: '#1478c8', onInverse: '#ffffff',
|
||||
},
|
||||
font: withRoles({ family: ['Segoe UI', 'Frutiger', 'Myriad Pro', 'Lucida Grande', 'sans-serif'], tweet: [], scale: 1, weight: 400, bold: 600, tracking: 0.004, leading: 1.45 }),
|
||||
shape: { radius: 18, button: 9999, avatar: 'rounded' },
|
||||
layout: { column: 620, sidebar: 340, density: 'comfortable', cards: true, frame: false },
|
||||
background: { kind: 'image', url: ART_AERO, fit: 'cover', dim: 0.35 },
|
||||
effects: { motion: 240, hover: 'lift', shadow: 'soft', crt: false },
|
||||
css: [
|
||||
// Aqua gloss on the filled buttons: a bright upper half over the button color, a soft drop.
|
||||
'[data-testid="SideNav_NewTweet_Button"],[data-testid="tweetButtonInline"],[data-testid="tweetButton"],[data-testid$="-follow"]{background-image:linear-gradient(180deg,rgba(255,255,255,.5),rgba(255,255,255,.14) 50%,rgba(255,255,255,0) 51%,rgba(255,255,255,.18)) !important;box-shadow:inset 0 1px 0 rgba(255,255,255,.75),0 2px 8px rgba(0,70,140,.3) !important}',
|
||||
// Glass: a white highlight along the top edge of each card.
|
||||
'main[role="main"] [data-testid="cellInnerDiv"] article[data-testid="tweet"]{box-shadow:inset 0 1px 0 rgba(255,255,255,.9),0 4px 18px rgba(0,80,150,.12) !important}',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
id: 'windows-98', name: 'Windows 98', description: 'Teal desktop, silver windows, bevelled buttons, square everything and MS Sans Serif-style type.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'light',
|
||||
colors: {
|
||||
// `page` is the silver of the nav panel; the teal desktop is the background below.
|
||||
page: '#c0c0c0', bg: '#ffffff', surface: '#f4f4f4', elevated: '#dfdfdf', border: '#808080',
|
||||
text: '#000000', muted: '#3c3c3c', accent: '#0000a8', inverse: '#000080', onInverse: '#ffffff',
|
||||
},
|
||||
font: withRoles({ family: ['Microsoft Sans Serif', 'MS Sans Serif', 'Tahoma', 'Geneva', 'Verdana', 'sans-serif'], tweet: [], scale: 0.9, weight: 400, bold: 700, tracking: 0, leading: 0 }),
|
||||
shape: { radius: 0, button: 0, avatar: 'square' },
|
||||
layout: { column: 610, sidebar: 320, density: 'compact', cards: false, frame: true },
|
||||
background: { kind: 'gradient', from: '#008080', to: '#008080', angle: 180 },
|
||||
effects: { motion: 0, hover: 'none', shadow: 'none', crt: false },
|
||||
css: [
|
||||
// Windows: the timeline and the nav are raised silver-framed panels on the teal desktop.
|
||||
'[data-testid="primaryColumn"]{border:0 !important;box-shadow:inset -1px -1px #0a0a0a,inset 1px 1px #dfdfdf,inset -2px -2px #808080,inset 2px 2px #ffffff !important}',
|
||||
'header[role="banner"] > div > div{background:#c0c0c0 !important;box-shadow:inset -1px -1px #0a0a0a,inset 1px 1px #dfdfdf,inset -2px -2px #808080,inset 2px 2px #ffffff}',
|
||||
'[data-testid="sidebarColumn"] div:has(> :is(aside[role="complementary"],section[role="region"],div[aria-label^="Timeline"])){box-shadow:inset -1px -1px #0a0a0a,inset 1px 1px #dfdfdf,inset -2px -2px #808080,inset 2px 2px #ffffff;border:0 !important}',
|
||||
// Bevelled push buttons.
|
||||
'[data-testid="SideNav_NewTweet_Button"],[data-testid="tweetButtonInline"],[data-testid="tweetButton"],[data-testid$="-follow"],[data-testid$="-unfollow"]{box-shadow:inset -1px -1px #0a0a0a,inset 1px 1px #ffffff,inset -2px -2px #404040,inset 2px 2px #dfdfdf !important}',
|
||||
'[data-testid="SideNav_NewTweet_Button"]:active,[data-testid="tweetButtonInline"]:active,[data-testid$="-follow"]:active{box-shadow:inset 1px 1px #0a0a0a,inset -1px -1px #ffffff,inset 2px 2px #404040 !important}',
|
||||
// Sunken search field.
|
||||
'[data-testid="sidebarColumn"] form[role="search"] > div > div{border-radius:0 !important;background:#ffffff !important;box-shadow:inset 1px 1px #808080,inset -1px -1px #ffffff,inset 2px 2px #0a0a0a,inset -2px -2px #dfdfdf}',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
id: 'vaporwave', name: 'Vaporwave', description: 'Sunset over a neon grid. Wide-tracked type with a glow, hot pink links and a cyan button.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#140726', bg: '#1a0b31', surface: '#20103c', elevated: '#2a1650', border: '#4d2a80',
|
||||
text: '#fde9ff', muted: '#cda9ea', accent: '#ff71ce', inverse: '#01cdfe', onInverse: '#140726',
|
||||
},
|
||||
font: withRoles({ family: ['Geist', ...SANS], tweet: [], scale: 1, weight: 400, bold: 700, tracking: 0.03, leading: 1.5 }),
|
||||
shape: { radius: 2, button: 2, avatar: 'rounded' },
|
||||
layout: { column: 640, sidebar: 330, density: 'default', cards: false, frame: true },
|
||||
background: { kind: 'image', url: ART_VAPOR, fit: 'cover', dim: 0.35 },
|
||||
effects: { motion: 260, hover: 'glow', shadow: 'deep', crt: false },
|
||||
css: '',
|
||||
},
|
||||
{
|
||||
id: 'high-contrast', name: 'High Contrast', description: 'For low vision: pure black, white rules, yellow links and buttons, larger Verdana, underlined links, bold focus rings and no motion.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#000000', bg: '#000000', surface: '#0b0b0b', elevated: '#161616', border: '#ffffff',
|
||||
text: '#ffffff', muted: '#e6e6e6', accent: '#ffff00', inverse: '#ffff00', onInverse: '#000000',
|
||||
},
|
||||
font: withRoles({ family: ['Verdana', 'Segoe UI', 'Tahoma', 'system-ui', 'sans-serif'], tweet: [], scale: 1.08, weight: 400, bold: 700, tracking: 0.01, leading: 1.55 }),
|
||||
shape: { radius: 6, button: 6, avatar: 'circle' },
|
||||
layout: { column: 680, sidebar: 350, density: 'comfortable', cards: false, frame: true },
|
||||
background: { kind: 'gradient', from: '#000000', to: '#000000', angle: 180 },
|
||||
effects: { motion: 0, hover: 'tint', shadow: 'none', crt: false },
|
||||
css: [
|
||||
':focus-visible{outline:3px solid #ffff00 !important;outline-offset:2px !important}',
|
||||
'[data-testid="tweetText"] a,[data-testid="UserDescription"] a{text-decoration:underline !important;text-underline-offset:2px}',
|
||||
'[data-testid="primaryColumn"]{border-left-width:2px !important;border-right-width:2px !important}',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
id: 'midnight-oled', name: 'Midnight OLED', description: 'True black for OLED panels: light-weight Geist, soft violet, big round corners and a sparse starfield.',
|
||||
author: 'wayBetter for X', version: 1, mode: 'dark',
|
||||
colors: {
|
||||
page: '#000000', bg: '#000000', surface: '#070708', elevated: '#101013', border: '#1b1b20',
|
||||
text: '#ededf0', muted: '#8d8d99', accent: '#a78bfa', inverse: '#ededf0', onInverse: '#000000',
|
||||
},
|
||||
font: withRoles({ family: ['Geist', ...SANS], tweet: [], scale: 1, weight: 350, bold: 600, tracking: -0.008, leading: 1.5 }),
|
||||
shape: { radius: 22, button: 9999, avatar: 'circle' },
|
||||
layout: { column: 580, sidebar: 320, density: 'comfortable', cards: false, frame: false },
|
||||
background: { kind: 'pattern', pattern: 'dots', ink: '#ffffff', opacity: 0.08, size: 34 },
|
||||
effects: { motion: 260, hover: 'tint', shadow: 'none', crt: false },
|
||||
css: '',
|
||||
},
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Theme engine v2: the structure of each theme (components, variants, decoration, icons). Every theme
|
||||
// keeps its complete v1 part above, so an app that does not know v2 still draws it. Five themes are
|
||||
// structurally different Twitters: Classic (a blue bar across the top, stars, blue tool icons),
|
||||
// Terminal (no pictures, worded actions, a prompt), Windows 98 (a taskbar, bevels, pixel icons, title
|
||||
// bars), Paper (a broadsheet with a masthead) and Frutiger Aero (glass panels, glossy icons).
|
||||
|
||||
const STRUCTURE: Record<string, Partial<ThemeSpec>> = {
|
||||
classic: {
|
||||
colors: {
|
||||
page: '#c0deed', bg: '#ffffff', surface: '#f5f8fa', elevated: '#e8f1f7', border: '#e1e8ed',
|
||||
text: '#292f33', muted: '#5b6b78', accent: '#0077b0', inverse: '#0077b0', onInverse: '#ffffff',
|
||||
actions: { like: '#e8a500', repost: '#19a15f', reply: '#0077b0' },
|
||||
},
|
||||
variants: { nav: 'top' },
|
||||
components: {
|
||||
nav: { fill: { from: 'accent', to: 'inverse', angle: 180 } },
|
||||
navItem: { text: 'onAccent', radius: 4, hover: { fill: 'inverse' } },
|
||||
avatar: { shape: 'square' },
|
||||
displayName: { weight: 700 },
|
||||
handle: { text: 'muted' },
|
||||
buttonPrimary: { radius: 4, borderWidth: 1, borderStyle: 'solid', borderColor: 'inverse', fill: { from: 'accent', to: 'inverse', angle: 180 }, shadow: 'soft' },
|
||||
buttonSecondary: { radius: 4, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface', text: 'text' },
|
||||
search: { radius: 4, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'bg' },
|
||||
composerTool: { text: 'accent' },
|
||||
tab: { weight: 700 },
|
||||
sidebarCard: { radius: 5, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'bg' },
|
||||
},
|
||||
decor: { dividers: { style: 'hairline', color: 'border' }, links: { underline: 'hover' } },
|
||||
icons: { pack: 'wb-classic', symbols: { like: 'star' } },
|
||||
},
|
||||
terminal: {
|
||||
variants: { post: 'compact', actions: 'labels' },
|
||||
components: {
|
||||
avatar: { visible: false },
|
||||
displayName: { text: 'accent', weight: 700 },
|
||||
handle: { text: 'muted' },
|
||||
post: { padX: 14 },
|
||||
buttonPrimary: { preset: 'outline', text: 'accent', borderColor: 'accent', radius: 0, hover: { fill: 'accent', text: 'bg' } },
|
||||
buttonSecondary: { preset: 'outline', text: 'accent', borderColor: 'accent', radius: 0 },
|
||||
search: { radius: 0, borderWidth: 1, borderStyle: 'dashed', borderColor: 'border', fill: 'bg' },
|
||||
tab: { case: 'lower' },
|
||||
navItem: { case: 'lower', radius: 0, hover: { fill: 'elevated' } },
|
||||
sidebarCard: { radius: 0, borderWidth: 1, borderStyle: 'dashed', borderColor: 'border', fill: 'bg' },
|
||||
menu: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'accent', fill: 'bg' },
|
||||
},
|
||||
decor: {
|
||||
dividers: { style: 'dashed', color: 'border', width: 1 }, chrome: { kind: 'prompt', title: 'guest@x' },
|
||||
selection: { fill: 'accent', text: 'bg' }, focusRing: { width: 2, style: 'dashed', color: 'accent', offset: 2 }, motion: { duration: 120, curve: 'steps' },
|
||||
},
|
||||
icons: { pack: 'wb-line', style: { stroke: 1.5, cap: 'square', join: 'miter' }, labels: { reply: 'reply', repost: 'rt', like: 'fav', bookmark: 'save' } },
|
||||
},
|
||||
'windows-98': {
|
||||
// The main column is a raised silver-framed window on the teal desktop (the outset edge of 98.css, MIT).
|
||||
css: '[data-testid="primaryColumn"]{border:0 !important;box-shadow:inset -1px -1px #0a0a0a,inset 1px 1px #dfdfdf,inset -2px -2px #808080,inset 2px 2px #ffffff !important}',
|
||||
variants: { nav: 'bottom' },
|
||||
components: {
|
||||
nav: { fill: 'page', borderStyle: 'bevel-out' },
|
||||
navItem: { radius: 0, text: 'text', hover: { fill: 'elevated' }, active: { shadow: 'inset' } },
|
||||
avatar: { shape: 'square' },
|
||||
buttonPrimary: { preset: 'bevel', fill: 'page', text: 'text', weight: 700 },
|
||||
buttonSecondary: { preset: 'bevel', fill: 'page', text: 'text' },
|
||||
search: { preset: 'sunken', radius: 0 },
|
||||
sidebarCard: { preset: 'window', fill: 'page' },
|
||||
menu: { preset: 'window', fill: 'page' },
|
||||
hoverCard: { preset: 'window', fill: 'page' },
|
||||
tab: { radius: 0 },
|
||||
composerTool: { text: 'text' },
|
||||
},
|
||||
decor: {
|
||||
dividers: { style: 'solid', color: 'border', width: 1 }, chrome: { kind: 'titlebar', title: 'Timeline - wayBetter' },
|
||||
focusRing: { width: 2, style: 'dotted', color: 'text', offset: 1 }, scrollbar: { style: 'classic', track: 'elevated' },
|
||||
},
|
||||
icons: { pack: 'wb-pixel' },
|
||||
},
|
||||
paper: {
|
||||
layout: { column: 640, sidebar: 330, density: 'comfortable', cards: false, frame: false },
|
||||
variants: { post: 'broadsheet', actions: 'quiet' },
|
||||
components: {
|
||||
postText: { fontSize: 17, font: 'post', leading: 1.55 },
|
||||
displayName: { font: 'heading', weight: 700 },
|
||||
meta: { case: 'upper', fontSize: 11, tracking: 0.08 },
|
||||
avatar: { shape: 'square' },
|
||||
buttonPrimary: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'text', fill: 'text', text: 'bg' },
|
||||
buttonSecondary: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'text', fill: 'transparent', text: 'text' },
|
||||
search: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'text', fill: 'bg' },
|
||||
sidebarCard: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'text', fill: 'bg' },
|
||||
tab: { case: 'small-caps', tracking: 0.06 },
|
||||
},
|
||||
decor: { chrome: { kind: 'masthead', title: 'The Daily Timeline' }, links: { underline: 'always' } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 1.25, cap: 'butt', join: 'miter' } },
|
||||
},
|
||||
'frutiger-aero': {
|
||||
css: '',
|
||||
variants: { post: 'cards' },
|
||||
components: {
|
||||
nav: { fill: 'glass' },
|
||||
navItem: { radius: 'pill', hover: { fill: 'elevated', lift: 1 } },
|
||||
topBar: { fill: 'glass' },
|
||||
post: { radius: 18, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface', shadow: 'soft' },
|
||||
avatar: { shape: 'rounded' },
|
||||
buttonPrimary: { preset: 'gloss', fill: { from: 'accent', to: 'inverse', angle: 180 }, borderColor: 'inverse', hover: { lift: 1 } },
|
||||
buttonSecondary: { preset: 'gloss', fill: { from: 'surface', to: 'elevated', angle: 180 }, borderColor: 'border', text: 'accent' },
|
||||
search: { preset: 'pill', fill: 'glass' },
|
||||
sidebarCard: { preset: 'glass' },
|
||||
// Menus and hover cards stay opaque over the timeline (a menu must read whatever is under it); the bars and cards are glass.
|
||||
menu: { preset: 'sheet', radius: 16 },
|
||||
hoverCard: { preset: 'sheet', radius: 16 },
|
||||
},
|
||||
decor: { motion: { duration: 220, curve: 'spring', press: 0.97 } },
|
||||
icons: { pack: 'wb-aero' },
|
||||
},
|
||||
// The other eight: tokens and line icons (stroke, caps and size per theme), no layout variant yet.
|
||||
'night-ink': {
|
||||
components: { navItem: { radius: 10 }, buttonPrimary: { radius: 10 }, post: { hover: { fill: 'surface' } } },
|
||||
decor: { focusRing: { width: 2, color: 'accent', offset: 2 } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 1.5 } },
|
||||
},
|
||||
dracula: {
|
||||
components: { buttonPrimary: { radius: 8, fill: 'inverse' }, tab: { radius: 6 }, count: { font: 'mono' } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 1.75 } },
|
||||
},
|
||||
nord: {
|
||||
variants: { actions: 'quiet' },
|
||||
components: { avatar: { shape: 'squircle' }, buttonPrimary: { radius: 'pill' }, sidebarCard: { radius: 14, borderWidth: 0 } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 2, cap: 'round' } },
|
||||
},
|
||||
'tokyo-night': {
|
||||
variants: { post: 'compact' },
|
||||
components: { count: { font: 'numbers' }, buttonPrimary: { radius: 6 } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 1.5 } },
|
||||
},
|
||||
'solarized-light': {
|
||||
components: { avatar: { shape: 'square' }, meta: { case: 'upper', tracking: 0.06, fontSize: 11 }, buttonPrimary: { preset: 'outline', radius: 3, text: 'accent', borderColor: 'accent' } },
|
||||
decor: { dividers: { style: 'dotted', color: 'border', width: 1 } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 1.75, cap: 'square', join: 'miter' } },
|
||||
},
|
||||
vaporwave: {
|
||||
components: { displayName: { case: 'upper', tracking: 0.08 }, post: { shadow: 'hard' }, avatar: { shape: 'square' } },
|
||||
icons: { pack: 'wb-classic' },
|
||||
},
|
||||
'high-contrast': {
|
||||
components: { buttonPrimary: { borderWidth: 2, borderStyle: 'solid', borderColor: 'accent' }, action: { size: 44 } },
|
||||
decor: { focusRing: { width: 3, color: 'accent', offset: 2 }, links: { underline: 'always' } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 2.25, scale: 1.1 } },
|
||||
},
|
||||
'midnight-oled': {
|
||||
variants: { actions: 'quiet' },
|
||||
components: { buttonPrimary: { radius: 'pill' }, navItem: { radius: 'pill' } },
|
||||
icons: { pack: 'wb-line', style: { stroke: 1.25 } },
|
||||
},
|
||||
};
|
||||
|
||||
/** The built-in themes: the v1 documents with their v2 structure, sanitized like any imported theme. */
|
||||
export const BUILTIN_THEMES: ThemeSpec[] = V1_THEMES.map(theme => {
|
||||
const extra = STRUCTURE[theme.id];
|
||||
return extra ? sanitizeSpec({ ...theme, ...extra, colors: extra.colors ?? theme.colors }) : theme;
|
||||
});
|
||||
|
||||
export const BUILTIN_IDS = BUILTIN_THEMES.map(theme => theme.id);
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Structure CSS: type, shape, density, layout, canvas and motion over X's own stylesheet
|
||||
|
||||
const TWEET = 'article[data-testid="tweet"]';
|
||||
const CELL = '[data-testid="cellInnerDiv"]';
|
||||
/** Layout and canvas modes stay in X's page; `#layers` (menus, hover cards, modals) is outside it. */
|
||||
const MAIN = 'main[role="main"]';
|
||||
const AVATAR = '[data-testid^="UserAvatar-Container"]';
|
||||
const RADII = ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'];
|
||||
const DENSITY: Record<Density, { v: number; h: number; gap: number }> = { compact: { v: 8, h: 14, gap: 8 }, default: { v: 12, h: 16, gap: 12 }, comfortable: { v: 16, h: 20, gap: 14 } };
|
||||
const px = (value: string) => { const m = /^(-?[\d.]+)px$/.exec(value.trim()); return m ? parseFloat(m[1]!) : null; };
|
||||
const round = (value: number) => Math.round(value * 10) / 10;
|
||||
const simple = (selector: string) => /^\.[\w-]+$/.test(selector);
|
||||
|
||||
/**
|
||||
* Where each font role is drawn in X's page. Display names are the first line of `User-Name`
|
||||
* (timeline) and `UserName` (profile header); counts are X's animated count spans and the
|
||||
* following/followers links. `interface` is every Chirp rule; `dialog` reaches the UI kit through
|
||||
* `--wb-font-dialog`; `chrome` is wayBetter's own window.
|
||||
*/
|
||||
export const ROLE_TARGETS = {
|
||||
post: ['[data-testid="tweetText"]'],
|
||||
heading: ['[data-testid="User-Name"] > div:first-child', '[data-testid="UserName"] > div:first-child', 'h1[role="heading"]', 'h2[role="heading"]'],
|
||||
numbers: ['[data-testid="app-text-transition-container"]', 'a:is([href$="/following"],[href$="/followers"],[href$="/verified_followers"]) > span:first-child'],
|
||||
mono: ['code', 'pre', 'kbd', 'samp'],
|
||||
} as const;
|
||||
|
||||
/** One role's rules. Size uses `zoom`, which scales the text and reflows it like a bigger font. */
|
||||
function roleCss(role: keyof typeof ROLE_TARGETS, spec: FontRole): string[] {
|
||||
if (spec === 'inherit') return [];
|
||||
const targets: readonly string[] = ROLE_TARGETS[role];
|
||||
const all = [...targets, ...targets.map(target => `${target} :is(span,a,div,code)`)].join(',');
|
||||
const decl: string[] = [];
|
||||
if (spec.family.length) decl.push(`font-family:${fontStack(spec.family)} !important`);
|
||||
if (spec.weight !== undefined) decl.push(`font-weight:${spec.weight} !important`);
|
||||
if (spec.tracking !== undefined) decl.push(`letter-spacing:${spec.tracking}em !important`);
|
||||
if (spec.tabular) decl.push('font-variant-numeric:tabular-nums !important');
|
||||
const out = decl.length ? [`${all}{${decl.join(';')}}`] : [];
|
||||
if (spec.size !== undefined && spec.size !== 1) out.push(`${targets.join(',')}{zoom:${spec.size}}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The role colors used for structure (cards, frames, scrollbars) when a theme keeps X's colors. */
|
||||
export type StructureColors = Pick<ThemeColors, 'bg' | 'surface' | 'elevated' | 'border' | 'text' | 'muted' | 'accent'> & { page: string };
|
||||
|
||||
export function buildStructureCss(rules: Iterable<RuleLike>, theme: ThemeSpec, colors: StructureColors): string {
|
||||
const out: string[] = [];
|
||||
const { font, shape, layout, effects } = theme;
|
||||
const fontChanged = font.family.length > 0;
|
||||
const scale = font.scale;
|
||||
const radiusChanged = shape.radius !== BASE_SHAPE.radius;
|
||||
const buttonChanged = shape.button !== BASE_SHAPE.button;
|
||||
const density = DENSITY[layout.density];
|
||||
const byProperty = { pt: [] as string[], pb: [] as string[], mt: [] as string[], bb: [] as string[], sideWidth: [] as string[], columnMax: [] as string[] };
|
||||
const rows: Array<[string, number]> = [];
|
||||
const uiStack = fontChanged ? fontStack(font.family) : '';
|
||||
|
||||
for (const rule of rules) {
|
||||
const selector = rule.selectorText;
|
||||
if (!selector || selector.length > 2000) continue;
|
||||
const style = rule.style;
|
||||
const decl: string[] = [];
|
||||
if (fontChanged) {
|
||||
const family = style.getPropertyValue('font-family');
|
||||
if (/TwitterChirp/.test(family)) decl.push(`font-family:${uiStack} !important`);
|
||||
}
|
||||
const weight = style.getPropertyValue('font-weight');
|
||||
if (weight === '700' || weight === 'bold') { if (font.bold !== 700) decl.push(`font-weight:${font.bold} !important`); }
|
||||
else if (weight === '800') { if (font.bold !== 700) decl.push(`font-weight:${Math.min(900, font.bold + 100)} !important`); }
|
||||
else if (weight === '400' || weight === 'normal') { if (font.weight !== 400) decl.push(`font-weight:${font.weight} !important`); }
|
||||
if (scale !== 1) {
|
||||
const size = px(style.getPropertyValue('font-size'));
|
||||
if (size !== null && size >= 9 && size <= 64) decl.push(`font-size:${round(size * scale)}px !important`);
|
||||
const height = px(style.getPropertyValue('line-height'));
|
||||
if (height !== null && height >= 12 && height <= 72) decl.push(`line-height:${round(height * scale)}px !important`);
|
||||
}
|
||||
if (radiusChanged || buttonChanged) {
|
||||
for (const property of RADII) {
|
||||
const value = style.getPropertyValue(property);
|
||||
const size = value ? px(value) : null;
|
||||
if (size === null) continue;
|
||||
if (size >= 100) { if (buttonChanged) decl.push(`${property}:${shape.button}px !important`); }
|
||||
else if (size >= 2 && radiusChanged) decl.push(`${property}:${Math.round(size * shape.radius / 16)}px !important`);
|
||||
}
|
||||
}
|
||||
if (decl.length) out.push(`${selector}{${decl.join(';')}}`);
|
||||
if (simple(selector) && (style.length === undefined || style.length === 1)) {
|
||||
if (style.getPropertyValue('padding-top') === '12px') byProperty.pt.push(selector);
|
||||
if (style.getPropertyValue('padding-bottom') === '12px') byProperty.pb.push(selector);
|
||||
if (style.getPropertyValue('margin-top') === '12px') byProperty.mt.push(selector);
|
||||
if (style.getPropertyValue('border-bottom-width') === '1px') byProperty.bb.push(selector);
|
||||
if (style.getPropertyValue('width') === '350px') byProperty.sideWidth.push(selector);
|
||||
if (style.getPropertyValue('max-width') === '600px') byProperty.columnMax.push(selector);
|
||||
const rowWidth = px(style.getPropertyValue('width'));
|
||||
if (rowWidth !== null && rowWidth >= 600 && rowWidth <= 1400) rows.push([selector, rowWidth]);
|
||||
}
|
||||
}
|
||||
|
||||
// Type: the interface stack everywhere, then each role that says otherwise.
|
||||
if (!font.tweet.length && fontChanged) out.push(`[data-testid="tweetText"],[data-testid="tweetText"] span{font-family:${uiStack} !important}`);
|
||||
if (fontChanged) out.push(`body,input,textarea,button{font-family:${uiStack} !important}`);
|
||||
for (const role of Object.keys(ROLE_TARGETS) as Array<keyof typeof ROLE_TARGETS>) out.push(...roleCss(role, font.roles[role]));
|
||||
if (font.tracking) out.push(`#react-root{letter-spacing:${font.tracking}em}`);
|
||||
if (font.leading) out.push(`[data-testid="tweetText"]{line-height:${font.leading} !important}`);
|
||||
|
||||
// Shape
|
||||
if (radiusChanged) out.push(`:root{--x-radius-m:${+(shape.radius / 16).toFixed(3)} !important}`);
|
||||
if (shape.avatar !== 'circle') {
|
||||
const r = shape.avatar === 'square' ? '2px' : '26%';
|
||||
out.push(`${AVATAR} :is(div,a,img){border-radius:${r} !important}`);
|
||||
}
|
||||
|
||||
// Density
|
||||
if (layout.density !== 'default') {
|
||||
const { v, h, gap } = density;
|
||||
if (byProperty.pt.length) out.push(`${MAIN} ${TWEET} :is(${byProperty.pt.join(',')}){padding-top:${v}px !important}`);
|
||||
if (byProperty.pb.length) out.push(`${MAIN} ${TWEET} :is(${byProperty.pb.join(',')}){padding-bottom:${v}px !important}`);
|
||||
if (byProperty.mt.length) out.push(`${MAIN} ${TWEET} :is(${byProperty.mt.join(',')}){margin-top:${gap}px !important}`);
|
||||
out.push(`${MAIN} ${TWEET}{padding-left:${h}px !important;padding-right:${h}px !important}`);
|
||||
out.push(`${MAIN} [data-testid="UserCell"]{padding:${v}px ${h}px !important}`);
|
||||
}
|
||||
|
||||
// Layout. Widths are rewritten only where X itself declared them (its 600px column cap, its
|
||||
// 350px sidebar, the fixed-width row that holds a primary column), so routes with other shells
|
||||
// (Articles, chat, Creator Studio) and X's own narrow breakpoints keep X's layout. The row is
|
||||
// capped at the pane (`min(..., 100%)`) and the column may shrink, so a theme never forces a
|
||||
// width wider than the window or collapses a column to its content.
|
||||
const columnDelta = layout.column - BASE_LAYOUT.column;
|
||||
const sidebarDelta = layout.sidebar - BASE_LAYOUT.sidebar;
|
||||
if (columnDelta && byProperty.columnMax.length) {
|
||||
out.push(`[data-testid="primaryColumn"]:is(${byProperty.columnMax.join(',')}){max-width:${layout.column}px !important}`);
|
||||
}
|
||||
if (sidebarDelta && byProperty.sideWidth.length) {
|
||||
out.push(`[data-testid="sidebarColumn"]:is(${byProperty.sideWidth.join(',')}),[data-testid="sidebarColumn"] :is(${byProperty.sideWidth.join(',')}){width:${layout.sidebar}px !important}`);
|
||||
}
|
||||
if ((columnDelta || sidebarDelta) && byProperty.columnMax.length) {
|
||||
// The row grows or shrinks by exactly what the theme changed inside it: only rows holding X's
|
||||
// capped 600px column (timelines, profiles, settings; not chat or Articles), plus the sidebar
|
||||
// delta only where a 350px sidebar sits in the row. A wider row applies only when the window
|
||||
// has room for it next to X's nav (X picks its narrow breakpoints for the original widths);
|
||||
// below that X's own row width stands and the column shrinks to fit.
|
||||
const capped = `:has([data-testid="primaryColumn"]:is(${byProperty.columnMax.join(',')}))`;
|
||||
const withSidebar = byProperty.sideWidth.length ? `:has([data-testid="sidebarColumn"]:is(${byProperty.sideWidth.join(',')}))` : '';
|
||||
const byWidth = new Map<number, string[]>();
|
||||
for (const [selector, width] of rows) byWidth.set(width, [...(byWidth.get(width) ?? []), selector]);
|
||||
for (const [width, selectors] of byWidth) {
|
||||
const variants: Array<[string, number]> = withSidebar
|
||||
? [[`${capped}${withSidebar}`, columnDelta + sidebarDelta], [`${capped}:not(${withSidebar})`, columnDelta]]
|
||||
: [[capped, columnDelta]];
|
||||
for (const [condition, delta] of variants) {
|
||||
if (!delta) continue;
|
||||
const next = width + delta;
|
||||
const rule = `main[role="main"] > div:is(${selectors.join(',')})${condition}{width:${next}px !important}`;
|
||||
// X's nav is 275px wide next to its wide rows and 88px next to narrow ones (+ scrollbar).
|
||||
out.push(delta < 0 ? rule : `@media (min-width:${next + (width >= 900 ? 291 : 104)}px){${rule}}`);
|
||||
}
|
||||
}
|
||||
out.push(`main[role="main"] [data-testid="primaryColumn"]{flex-shrink:1 !important;min-width:0 !important}`);
|
||||
}
|
||||
const shadow = effects.shadow === 'soft' ? `0 1px 2px ${rgba('#000000', 0.06)}, 0 8px 28px ${rgba('#000000', 0.08)}` : effects.shadow === 'deep' ? `0 0 0 1px ${rgba(colors.border, 0.6)}, 0 24px 80px ${rgba('#000000', 0.55)}` : '';
|
||||
if (layout.frame) {
|
||||
out.push(`[data-testid="primaryColumn"]{border-left:1px solid ${colors.border} !important;border-right:1px solid ${colors.border} !important;${shadow ? `box-shadow:${shadow};` : ''}}`);
|
||||
}
|
||||
if (layout.cards) {
|
||||
const r = Math.max(0, shape.radius);
|
||||
out.push(`${MAIN} ${CELL} ${TWEET}{margin:${density.gap / 2 + 2}px 12px;border:1px solid ${colors.border} !important;border-radius:${r}px;background-color:${colors.surface} !important;${effects.shadow !== 'none' ? `box-shadow:0 1px 2px ${rgba('#000000', 0.05)};` : ''}}`);
|
||||
if (byProperty.bb.length) out.push(`${MAIN} ${CELL} :is(${byProperty.bb.join(',')}){border-bottom-width:0 !important}`);
|
||||
out.push(`[data-testid="primaryColumn"] section[role="region"] > div{padding-block:6px}`);
|
||||
}
|
||||
|
||||
// Canvas: the page behind the columns; sidebar modules get a solid backing when it is patterned.
|
||||
if (theme.background.kind !== 'none' || colors.page !== colors.bg) {
|
||||
out.push(...pageBackgroundCss(theme.background, colors.page));
|
||||
out.push(`[data-testid="sidebarColumn"] div:has(> :is(aside[role="complementary"],section[role="region"],div[aria-label^="Timeline"])){background-color:${colors.bg} !important}`);
|
||||
out.push(`[data-testid="sidebarColumn"] form[role="search"]{background-color:transparent !important}`);
|
||||
// A photo is not a known color, so text over it (the nav) gets a frosted backing.
|
||||
if (theme.background.kind === 'image') out.push(`header[role="banner"] > div > div{background-color:${rgba(colors.page, 0.78)};backdrop-filter:blur(14px)}`);
|
||||
}
|
||||
out.push(`html,body{scrollbar-color:${colors.border} transparent !important}`);
|
||||
if (theme.mode !== 'auto') out.push(`html{color-scheme:${theme.mode} !important}`);
|
||||
|
||||
// Motion and hover
|
||||
if (effects.motion > 0) {
|
||||
const t = `${effects.motion}ms cubic-bezier(.2,.7,.2,1)`;
|
||||
out.push(`@media (prefers-reduced-motion:no-preference){${TWEET},${CELL},[role="button"],a[role="link"],a[role="tab"],[data-testid="UserCell"]{transition:background-color ${t},box-shadow ${t},transform ${t},border-color ${t},color ${t}}}`);
|
||||
}
|
||||
if (effects.hover === 'lift' && layout.cards) out.push(`@media (prefers-reduced-motion:no-preference){${MAIN} ${CELL} ${TWEET}:hover{transform:translateY(-1px);box-shadow:0 6px 22px ${rgba('#000000', 0.1)}}}`);
|
||||
if (effects.hover === 'tint') out.push(`${TWEET}:hover{background-color:${rgba(colors.accent, 0.035)} !important}`);
|
||||
if (effects.hover === 'glow') {
|
||||
out.push(`[data-testid="tweetText"],[data-testid="User-Name"] span{text-shadow:0 0 6px ${rgba(colors.text, 0.35)}}`);
|
||||
out.push(`${TWEET}:hover{background-color:${rgba(colors.accent, 0.05)} !important;box-shadow:inset 2px 0 0 ${colors.accent}}`);
|
||||
}
|
||||
if (effects.crt) {
|
||||
out.push(`body::after{content:"";position:fixed;inset:0;z-index:2147483000;pointer-events:none;background:repeating-linear-gradient(0deg,${rgba('#000000', 0.14)} 0 1px,transparent 1px 3px),radial-gradient(ellipse at center,transparent 62%,${rgba('#000000', 0.38)})}`);
|
||||
out.push(`::selection{background:${colors.accent};color:${colors.bg}}`);
|
||||
}
|
||||
if (theme.css) out.push(theme.css);
|
||||
return out.join('\n');
|
||||
}
|
||||
93
apps/desktop/src/inject/themeStructure.ts
Normal file
93
apps/desktop/src/inject/themeStructure.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
// Theme engine v2 on X: a theme's components, variants, decoration and icons as X's static sheet
|
||||
// (the framework runtime's `staticCss`). It does not depend on X's stylesheet, only on the theme,
|
||||
// X's mode and the owner's icon choice, so X inserting rules never rebuilds it.
|
||||
|
||||
import { compileComponents, type RoleColors } from '../../../../waybetter/packages/runtime/src/themeComponents.ts';
|
||||
import { compileDecor } from '../../../../waybetter/packages/runtime/src/themeDecor.ts';
|
||||
import { ICON_GROUPS, compileIcons, createIconCatalog, iconGroupsPresent, normalizeIconChoice, type IconChoice, type IconGroup, type IconPack } from '../../../../waybetter/packages/runtime/src/themeIcons.ts';
|
||||
import { compileVariants, resolveVariants } from '../../../../waybetter/packages/runtime/src/themeVariants.ts';
|
||||
import type { ThemeChoice } from '../../../../waybetter/packages/runtime/src/themeChoice.ts';
|
||||
import type { ResolvedTheme } from '../../../../waybetter/packages/runtime/src/themeApi.ts';
|
||||
import type { ThemeSpec } from './themeSpec.ts';
|
||||
import { BUILTIN_PACKS } from './packs/index.ts';
|
||||
import { X_ICONS } from './themeIcons.ts';
|
||||
import { X_PARTS, X_SKINS, xDecorTargets, type XSkinContext } from './themeParts.ts';
|
||||
|
||||
export const X_ICON_PACKS = createIconCatalog(BUILTIN_PACKS);
|
||||
/** Attribute on `<html>` naming the icon groups whose core icons X showed (a rail is never half ours). */
|
||||
export const ICON_GATE = 'data-wb-icons';
|
||||
|
||||
export type StructureEnv = {
|
||||
/** The owner's icon choice: follow the theme, X's own icons, or a pack. */
|
||||
icons: IconChoice;
|
||||
/** Icon packs the owner imported (the theme choice's `packs`). */
|
||||
packs?: readonly IconPack[];
|
||||
/** The owner lets themes change the layout / the icons (Appearance switches; default on). */
|
||||
layout?: boolean;
|
||||
iconsAllowed?: boolean;
|
||||
};
|
||||
|
||||
const DEFAULT_LABELS = { reply: 'reply', repost: 'repost', like: 'like', views: 'views', bookmark: 'save', share: 'share' };
|
||||
|
||||
/** X's static sheet for one theme in one X mode. Empty for a theme without structure groups and no icon pick. */
|
||||
export function buildStructureCss(theme: ThemeSpec, resolved: ResolvedTheme, env: StructureEnv): string {
|
||||
const c = resolved.colors;
|
||||
const colors: RoleColors = {
|
||||
bg: c.bg, surface: c.surface, elevated: c.elevated, page: c.page ?? c.bg, border: c.border, text: c.text, muted: c.muted,
|
||||
accent: c.accent, onAccent: c.onAccent, inverse: c.inverse, onInverse: c.onInverse,
|
||||
};
|
||||
const f = resolved.fonts!;
|
||||
const fonts = { interface: f.interface.stack, post: f.post.stack, heading: f.heading.stack, numbers: f.numbers.stack, mono: f.mono.stack, chrome: f.chrome.stack, dialog: f.dialog.stack };
|
||||
const out: string[] = [];
|
||||
if (theme.components) {
|
||||
const { values, rules } = compileComponents(theme.components, X_PARTS, { colors, fonts });
|
||||
if (values.length) out.push(`:where(:root){${values.join(';')}}`);
|
||||
out.push(...rules);
|
||||
}
|
||||
const catalog = env.packs?.length ? createIconCatalog(BUILTIN_PACKS, env.packs) : X_ICON_PACKS;
|
||||
const labels = { ...DEFAULT_LABELS, ...catalog.resolve(env.icons, theme.icons)?.labels, ...theme.icons?.labels };
|
||||
const skin: XSkinContext = { colors, fonts, labels, brackets: theme.variants?.actions === 'labels' && /\bmono\b|Mono/.test(fonts.interface) };
|
||||
out.push(...compileVariants(resolveVariants(theme.variants, { allowed: env.layout !== false }), X_SKINS, skin));
|
||||
if (theme.decor) out.push(...compileDecor(theme.decor, xDecorTargets(), skin));
|
||||
// Action colors: the set state of like, repost and bookmark, and the reply hover.
|
||||
const actions = theme.colors?.actions;
|
||||
if (actions) {
|
||||
const act = (ids: string, color: string | undefined) => color ? `article[data-testid="tweet"] [role="group"] :is(${ids}) :is(div,span,svg){color:${color} !important}` : '';
|
||||
out.push(act('[data-testid="unlike"]', actions.like), act('[data-testid="unretweet"]', actions.repost), act('[data-testid="removeBookmark"]', actions.bookmark),
|
||||
actions.reply ? `article[data-testid="tweet"] [role="group"] [data-testid="reply"]:hover :is(div,span,svg){color:${actions.reply} !important}` : '');
|
||||
}
|
||||
const pack = catalog.resolve(env.icons, theme.icons);
|
||||
out.push(compileIcons(pack, env.icons === 'site' ? null : theme.icons, X_ICONS, { colors, gate: ICON_GATE, allowed: env.iconsAllowed !== false }));
|
||||
return out.filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
const ICON_KEY = 'wb:icon-groups';
|
||||
/**
|
||||
* Keeps `html[data-wb-icons]` listing the icon groups whose core icons X has shown in this tab. A
|
||||
* group, once seen, stays on for the tab's session (and is remembered for its next document), so
|
||||
* moving to a page without posts never swaps the rail's icons back and forth.
|
||||
*/
|
||||
export function installIconGate(win: Window): () => void {
|
||||
const doc = win.document;
|
||||
let seen = new Set<IconGroup>();
|
||||
try { for (const group of JSON.parse(win.sessionStorage.getItem(ICON_KEY) || '[]') as string[]) if ((ICON_GROUPS as readonly string[]).includes(group)) seen.add(group as IconGroup); } catch { /* No storage: probe from scratch. */ }
|
||||
const write = () => { const value = [...seen].join(' '); if (doc.documentElement.getAttribute(ICON_GATE) !== value) doc.documentElement.setAttribute(ICON_GATE, value); };
|
||||
const probe = () => {
|
||||
if (!doc.querySelector('[data-testid="primaryColumn"]')) return;
|
||||
const before = seen.size;
|
||||
for (const group of iconGroupsPresent(X_ICONS, selector => !!doc.querySelector(selector))) seen.add(group);
|
||||
if (seen.size !== before) { try { win.sessionStorage.setItem(ICON_KEY, JSON.stringify([...seen])); } catch { /* Quota or blocked. */ } }
|
||||
write();
|
||||
};
|
||||
if (doc.documentElement) write();
|
||||
const timer = win.setInterval(() => { try { probe(); } catch { /* Never break the page. */ } }, 1500);
|
||||
return () => { win.clearInterval(timer); seen = new Set(); };
|
||||
}
|
||||
|
||||
export { normalizeIconChoice };
|
||||
/** The choice passed to `buildStructureCss` when nothing was picked. */
|
||||
export const defaultStructureEnv = (): StructureEnv => ({ icons: 'theme' });
|
||||
/** A key that changes when anything the static sheet depends on changes, besides the theme and mode. */
|
||||
export const structureKey = (env: StructureEnv) => `${env.icons}|${env.layout !== false}|${env.iconsAllowed !== false}`;
|
||||
/** Unused choice argument kept out of the sheet: X's static CSS depends on the theme document, not on its id. */
|
||||
export type { ThemeChoice };
|
||||
5
apps/desktop/src/inject/themeTokens.ts
Normal file
5
apps/desktop/src/inject/themeTokens.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// The color foundation every theme is built on comes from the wayBetter runtime
|
||||
// (waybetter/packages/runtime/src/themeTokens.ts). X's own palette (Default, Dim, Lights out;
|
||||
// `X_PALETTES` in theme.ts) is the source axis it maps onto a theme.
|
||||
|
||||
export * from '../../../../waybetter/packages/runtime/src/themeTokens.ts';
|
||||
189
apps/desktop/src/inject/userInfo.ts
Normal file
189
apps/desktop/src/inject/userInfo.ts
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
// Passive per-tab cache of user attributes (X Premium "blue" check, legacy org verification,
|
||||
// following, followed by, the account's creation time) that X's own GraphQL responses already carry — same tap discipline as alerts.ts and
|
||||
// media/tap.ts: one shared JSON tap on responses the page already fetched, no requests of our own.
|
||||
// Exposed to plugins as `api.users.get(handle)` / `api.users.onUpdate(cb)` (see pluginApi.ts) so a
|
||||
// plugin such as Hide Blue Checks can act on data the timeline already loaded instead of guessing
|
||||
// from the DOM. The tap installs on first use only.
|
||||
//
|
||||
// Schema assumptions (is_blue_verified, verified_type, relationship_perspectives/legacy.following
|
||||
// and .followed_by, core/legacy.created_at) are fixture-tested only; live X responses are UNVERIFIED (see observer/relationships.ts).
|
||||
import { addTap } from './netHub.ts';
|
||||
|
||||
const HANDLE = /^[A-Za-z0-9_]{1,15}$/;
|
||||
const X_ID = /^[1-9][0-9]{0,19}$/;
|
||||
/** GraphQL operations whose responses carry user objects (normal browsing only; nothing is replayed). */
|
||||
export const USER_OPERATIONS = /\/i\/api\/graphql\/[^/]+\/(UserByScreenName|UserByRestId|UsersByRestIds|UsersByScreenNames|HomeTimeline|HomeLatestTimeline|UserTweets|UserTweetsAndReplies|UserMedia|UserHighlightsTweets|SearchTimeline|TweetDetail|TweetResultByRestId|Followers|Following|BlueVerifiedFollowers|ListLatestTweetsTimeline|ListMembers|Likes|Bookmarks|ConnectTabTimeline)(?:[?#]|$)/;
|
||||
|
||||
export type VerifiedType = 'None' | 'Business' | 'Government';
|
||||
|
||||
export type UserInfo = {
|
||||
xUserId: string;
|
||||
handle: string;
|
||||
/** X Premium ("blue") checkmark. null = not yet observed for this user. */
|
||||
blue: boolean | null;
|
||||
/** Legacy gold/grey org verification. null = not yet observed. */
|
||||
verifiedType: VerifiedType | null;
|
||||
/** Following, from the viewer's own perspective. null = unknown; never inferred false. */
|
||||
following: boolean | null;
|
||||
/** Whether they follow the viewer. null = unknown (the response had no such field); never inferred false. */
|
||||
followedBy: boolean | null;
|
||||
/** When the account was created, ms since the epoch. null = not yet observed or unreadable; never guessed. */
|
||||
createdAt: number | null;
|
||||
};
|
||||
|
||||
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
/** X's `created_at`: "Mon Jan 01 00:00:00 +0000 2024". */
|
||||
const X_DATE = /^[A-Z][a-z]{2} ([A-Z][a-z]{2}) (\d{2}) (\d{2}):(\d{2}):(\d{2}) ([+-])(\d{2})(\d{2}) (\d{4})$/;
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
||||
/** The day X opened: nothing was created before it. */
|
||||
const FIRST_DAY = Date.UTC(2006, 2, 21);
|
||||
|
||||
/**
|
||||
* A `created_at` value as ms since the epoch, or null when it is not a date in one of the two
|
||||
* shapes X sends (its own format, read by hand because engines disagree on it, or ISO 8601) or lies
|
||||
* outside X's lifetime. Pure.
|
||||
*/
|
||||
export function parseCreatedAt(value: unknown, now = Date.now()): number | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
let ms = NaN;
|
||||
const match = X_DATE.exec(value);
|
||||
if (match) {
|
||||
const month = MONTHS.indexOf(match[1]!);
|
||||
const offset = (match[6] === '-' ? -1 : 1) * (Number(match[7]) * 60 + Number(match[8]));
|
||||
if (month >= 0) ms = Date.UTC(Number(match[9]), month, Number(match[2]), Number(match[3]), Number(match[4]), Number(match[5])) - offset * 60_000;
|
||||
} else if (ISO_DATE.test(value)) {
|
||||
ms = Date.parse(value);
|
||||
}
|
||||
return Number.isFinite(ms) && ms >= FIRST_DAY && ms <= now + 86_400_000 ? ms : null;
|
||||
}
|
||||
|
||||
const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_USERS = 8_192;
|
||||
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
/** GraphQL user objects (rest_id + screen_name + legacy), deduplicated by rest_id. */
|
||||
export function extractUsers(root: unknown, maxDepth = 64): UserInfo[] {
|
||||
const out = new Map<string, UserInfo>();
|
||||
const stack: { node: unknown; depth: number }[] = [{ node: root, depth: 0 }];
|
||||
let budget = 50_000;
|
||||
while (stack.length && budget-- > 0) {
|
||||
const { node, depth } = stack.pop()!;
|
||||
if (!node || typeof node !== 'object' || depth > maxDepth) continue;
|
||||
if (object(node)) {
|
||||
const legacy = object(node.legacy) ? node.legacy : undefined;
|
||||
const restId = node.rest_id;
|
||||
const core = object(node.core) ? node.core : undefined;
|
||||
const handle = typeof core?.screen_name === 'string' ? core.screen_name : legacy?.screen_name;
|
||||
// X's current user objects carry `core`/`relationship_perspectives`/`verification` and no `legacy`.
|
||||
const isUser = !!legacy || !!core || node.__typename === 'User';
|
||||
if (typeof restId === 'string' && X_ID.test(restId) && typeof handle === 'string' && HANDLE.test(handle) && isUser && !out.has(restId)) {
|
||||
const perspective = object(node.relationship_perspectives) ? node.relationship_perspectives : undefined;
|
||||
const following = typeof perspective?.following === 'boolean' ? perspective.following
|
||||
: typeof legacy?.following === 'boolean' ? legacy.following : null;
|
||||
const followedBy = typeof perspective?.followed_by === 'boolean' ? perspective.followed_by
|
||||
: typeof legacy?.followed_by === 'boolean' ? legacy.followed_by : null;
|
||||
const verification = object(node.verification) ? node.verification : undefined;
|
||||
const rawType = typeof node.verified_type === 'string' ? node.verified_type : verification?.verified_type;
|
||||
const verifiedType = rawType === 'Business' || rawType === 'Government' ? rawType
|
||||
: typeof rawType === 'string' || typeof verification?.verified === 'boolean' ? 'None' : null;
|
||||
out.set(restId, {
|
||||
xUserId: restId,
|
||||
handle,
|
||||
blue: typeof node.is_blue_verified === 'boolean' ? node.is_blue_verified : null,
|
||||
verifiedType,
|
||||
following,
|
||||
followedBy,
|
||||
createdAt: parseCreatedAt(core?.created_at ?? legacy?.created_at),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const key in node as object) {
|
||||
const child = (node as Record<string, unknown>)[key];
|
||||
if (child && typeof child === 'object') stack.push({ node: child, depth: depth + 1 });
|
||||
}
|
||||
}
|
||||
return [...out.values()];
|
||||
}
|
||||
|
||||
type TapWindow = { fetch: typeof fetch; XMLHttpRequest?: typeof XMLHttpRequest };
|
||||
/** Called with the lowercase handles a tapped response just added or updated. */
|
||||
export type UsersListener = (handles: string[]) => void;
|
||||
/** What plugins see as `api.users`. */
|
||||
export type UsersApi = {
|
||||
get(handle: string): UserInfo | null;
|
||||
/** Subscribes to newly observed/updated users; returns a dispose function. */
|
||||
onUpdate(callback: UsersListener): () => void;
|
||||
};
|
||||
export type UsersHandle = UsersApi & { dispose(): void };
|
||||
|
||||
/** Merges a newly observed user over anything already known: a response missing a field (e.g. a
|
||||
* timeline entry that omits relationship_perspectives) never erases a value learned earlier. */
|
||||
function merge(prev: UserInfo | undefined, next: UserInfo): UserInfo {
|
||||
return {
|
||||
xUserId: next.xUserId,
|
||||
handle: next.handle,
|
||||
blue: next.blue ?? prev?.blue ?? null,
|
||||
verifiedType: next.verifiedType ?? prev?.verifiedType ?? null,
|
||||
following: next.following ?? prev?.following ?? null,
|
||||
followedBy: next.followedBy ?? prev?.followedBy ?? null,
|
||||
createdAt: next.createdAt ?? prev?.createdAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Least-recently-used cache: reads and writes move an entry to the newest end of the Map, and the
|
||||
* oldest entry (first in iteration order) is evicted past `max`. */
|
||||
export class LruMap<K, V> {
|
||||
readonly map = new Map<K, V>();
|
||||
readonly max: number;
|
||||
constructor(max: number) { this.max = max; }
|
||||
get(key: K): V | undefined {
|
||||
const value = this.map.get(key);
|
||||
if (value !== undefined) { this.map.delete(key); this.map.set(key, value); }
|
||||
return value;
|
||||
}
|
||||
set(key: K, value: V): void {
|
||||
this.map.delete(key);
|
||||
this.map.set(key, value);
|
||||
if (this.map.size > this.max) this.map.delete(this.map.keys().next().value!);
|
||||
}
|
||||
clear(): void { this.map.clear(); }
|
||||
}
|
||||
|
||||
/** The tap is installed with the runtime, at document start: X loads the first timeline before any
|
||||
* plugin could ask, and a later tap would miss it (live-tested: 0 of 14 authors known when lazy). The
|
||||
* walk only runs on user-bearing GraphQL responses and is bounded (MAX_BODY_BYTES, node budget). */
|
||||
export function installUserInfo(target: TapWindow, maxUsers = MAX_USERS): UsersHandle {
|
||||
const byHandle = new LruMap<string, UserInfo>(maxUsers);
|
||||
const listeners = new Set<UsersListener>();
|
||||
const ingest = (body: unknown) => {
|
||||
const changed: string[] = [];
|
||||
for (const user of extractUsers(body)) {
|
||||
const key = user.handle.toLowerCase();
|
||||
byHandle.set(key, merge(byHandle.map.get(key), user));
|
||||
changed.push(key);
|
||||
}
|
||||
if (!changed.length) return;
|
||||
for (const listener of [...listeners]) {
|
||||
try { listener(changed); } catch (error) { console.error('[wayBetter for X] users listener failed', error); }
|
||||
}
|
||||
};
|
||||
let untap: (() => void) | null = null;
|
||||
const ensureTap = () => {
|
||||
if (!untap) untap = addTap(target, { match: url => USER_OPERATIONS.test(url), maxBytes: MAX_BODY_BYTES, onJson: ingest });
|
||||
};
|
||||
ensureTap();
|
||||
return {
|
||||
get(handle) {
|
||||
ensureTap();
|
||||
return byHandle.get(handle.toLowerCase()) ?? null;
|
||||
},
|
||||
onUpdate(callback) {
|
||||
ensureTap();
|
||||
listeners.add(callback);
|
||||
return () => { listeners.delete(callback); };
|
||||
},
|
||||
dispose() { untap?.(); untap = null; listeners.clear(); byHandle.clear(); },
|
||||
};
|
||||
}
|
||||
49
apps/desktop/src/inject/xSite.ts
Normal file
49
apps/desktop/src/inject/xSite.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// The X site adapter for the wayBetter page runtime (waybetter/packages/runtime). Everything the
|
||||
// framework needs to know about x.com that is not a feature: which requests are X's API, which
|
||||
// pages are heavy (XChat), the plugin API names, and X's navigation rail. The account reader and
|
||||
// the link-routing rules live next to their X code (accountReport.ts, linkRouting.ts); X's source
|
||||
// palettes for the theme engine are `X_PALETTES` in theme.ts. The native half is `site.rs`.
|
||||
//
|
||||
// Importing this module applies the adapter (DOM hub + request hub), so every X module that uses a
|
||||
// hub imports it through the local adapters (domHub.ts, netHub.ts).
|
||||
|
||||
import { configureRuntime, type SiteAdapter } from '../../../../waybetter/packages/runtime/src/site.ts';
|
||||
|
||||
export const X_SITE = {
|
||||
product: 'wayBetter for X',
|
||||
hosts: ['x.com'],
|
||||
runtimeGlobal: 'BetterTwttr',
|
||||
// XChat is WASM heavy and has no posts, composers or profiles for the DOM features.
|
||||
heavyPath: /^\/(?:messages|i\/chat)(?:\/|$)/i,
|
||||
// X renders its chat inside the open shadow root of this host (XChatEmbed, seen live 2026-10-01):
|
||||
// the DOM hub observes and searches it like the page (Chat+ finds X's rows there).
|
||||
shadowHosts: ['[data-testid="xchatEmbedRoute"]'],
|
||||
// `/live_pipeline/events`: X's streamed live counts on api.x.com (one request per page session),
|
||||
// filtered by the like/repost/bookmark fix (src/fixes/mutationGate/liveCounts.ts).
|
||||
apiMarks: ['/i/api/', '/live_pipeline/events'],
|
||||
// X's chunked media upload (upload.x.com); only XHR gates see it (see src/fixes/uploadRetry.ts).
|
||||
xhrMarks: ['/i/media/upload.json'],
|
||||
plugins: {
|
||||
name: 'BetterTwttr',
|
||||
product: 'wayBetter for X',
|
||||
storagePrefix: 'bt-plugin:',
|
||||
styleDataKey: 'betterTwttrPlugin',
|
||||
toastId: 'bt-plugin-toast',
|
||||
toastBackground: 'rgb(29, 155, 240)',
|
||||
itemSelector: 'article[data-testid="tweet"]',
|
||||
// X's "g" chords (g h, g n, ...): their second key is never a plugin shortcut.
|
||||
chordKeys: ['g'],
|
||||
},
|
||||
rail: {
|
||||
prefix: 'bt',
|
||||
rail: 'header[role="banner"]',
|
||||
anchor: '[data-testid="AppTabBar_Home_Link"]',
|
||||
main: 'main[role="main"]',
|
||||
accentSource: '[data-testid="SideNav_NewTweet_Button"]',
|
||||
modalOpen: '#layers [aria-modal="true"]',
|
||||
menuOpen: '#layers [role="menu"], #layers [data-testid="Dropdown"]',
|
||||
paint: { width: 88, background: 'rgb(0, 0, 0)', line: 'rgba(231, 233, 234, 0.16)', accent: 'rgb(29, 155, 240)', rtl: false },
|
||||
},
|
||||
} satisfies SiteAdapter;
|
||||
|
||||
configureRuntime(X_SITE);
|
||||
Loading…
Add table
Add a link
Reference in a new issue