44 lines
2.6 KiB
TypeScript
44 lines
2.6 KiB
TypeScript
// 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);
|
|
}
|