wayBetter for X

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

View file

@ -0,0 +1,354 @@
// Chat+ · Starred messages. A star button on every message; a starred message is kept in this
// tab's page storage, in full, because its owner asked for exactly that one: conversation, message
// id, sequence number, sender, text, time, media references and what it replied to. Nothing is read
// or kept for a message nobody starred, nothing leaves the machine, and it is never part of sync.
//
// The list ("Starred messages": the palette, or the star in X's chat header) opens any of them at
// the message with X's own mechanisms (./x.ts), also months back, and can open X's own Reply for it.
// The reply itself is X's: this feature stops with the text box focused.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi, PluginStorage } from '../../inject/pluginApi.ts';
import { ICONS, SHARED_CSS, clearAttribute, flash, headerButton, icon, removeHeaderButtons, timers } from './ui.ts';
import {
CONVERSATION_PROBES, chatRoot, chatSelectors, conversationKey, conversationOf, conversationTitle, isChatPath, jumpToMessage, openConversation, openReply, readRow, renderedRows,
type ChatSelectors, type MediaRef, type MessageInfo, type Pace, type ReplyRef,
} from './x.ts';
export type Starred = {
uuid: string;
conversation: string;
/** The conversation's name when the message was starred. */
title: string;
seq: string | null;
sender: { id: string | null; name: string; handle: string | null };
text: string;
/** Epoch ms, from the sequence number. */
time: number | null;
/** The clock X showed on the row. */
timeLabel: string;
media: MediaRef[];
reply: ReplyRef | null;
starredAt: number;
};
export const STARRED_NAMESPACE = 'chat-plus.bookmarks';
export const STARRED_KEY = 'items';
export const MAX_STARRED = 2000;
const MAX_TEXT = 10000;
const str = (value: unknown, max: number) => (typeof value === 'string' ? value.slice(0, max) : '');
const strOrNull = (value: unknown, max: number) => (typeof value === 'string' && value ? value.slice(0, max) : null);
const seqOrNull = (value: unknown) => (typeof value === 'string' && /^\d{10,20}$/.test(value) ? value : null);
function normalizeOne(raw: unknown): Starred | null {
if (!raw || typeof raw !== 'object') return null;
const from = raw as Record<string, unknown>;
const uuid = str(from.uuid, 64);
const conversation = conversationKey(str(from.conversation, 64));
if (!uuid || !conversation) return null;
const sender = (from.sender && typeof from.sender === 'object' ? from.sender : {}) as Record<string, unknown>;
const reply = from.reply && typeof from.reply === 'object' ? from.reply as Record<string, unknown> : null;
return {
uuid, conversation, title: str(from.title, 200), seq: seqOrNull(from.seq),
sender: { id: strOrNull(sender.id, 32), name: str(sender.name, 200), handle: strOrNull(sender.handle, 32) },
text: str(from.text, MAX_TEXT),
time: typeof from.time === 'number' && Number.isFinite(from.time) ? from.time : null,
timeLabel: str(from.timeLabel, 40),
media: (Array.isArray(from.media) ? from.media : []).flatMap((item: unknown): MediaRef[] => {
const media = item && typeof item === 'object' ? item as Record<string, unknown> : null;
return media && (media.type === 'image' || media.type === 'video') ? [{ type: media.type, url: strOrNull(media.url, 2000) }] : [];
}).slice(0, 8),
reply: reply ? { uuid: strOrNull(reply.uuid, 64), seq: seqOrNull(reply.seq), senderId: strOrNull(reply.senderId, 32), senderName: strOrNull(reply.senderName, 200), text: str(reply.text, 2000) } : null,
starredAt: typeof from.starredAt === 'number' && Number.isFinite(from.starredAt) ? from.starredAt : 0,
};
}
/** The starred messages from whatever was stored: valid ones only, each message once, newest star first. */
export function normalizeStarred(raw: unknown): Starred[] {
const seen = new Set<string>();
const out: Starred[] = [];
for (const item of Array.isArray(raw) ? raw : []) {
const one = normalizeOne(item);
if (!one || seen.has(one.uuid)) continue;
seen.add(one.uuid);
out.push(one);
}
return out.sort((a, b) => b.starredAt - a.starredAt).slice(0, MAX_STARRED);
}
/** The starred messages in a tab's storage (Person filter reads the senders it knows from here). */
export const readStarred = (storage: Pick<PluginStorage, 'get'>): Starred[] => normalizeStarred(storage.get<unknown>(STARRED_KEY, []));
/** The record of a message the user stars now. */
export function starOf(info: MessageInfo, conversation: string, title: string, now: number): Starred {
return normalizeOne({
uuid: info.uuid, conversation, title, seq: info.seq,
sender: { id: info.senderId, name: info.senderName, handle: info.senderHandle },
text: info.text, time: info.time, timeLabel: info.timeLabel, media: info.media, reply: info.reply, starredAt: now,
})!;
}
export const isStarred = (list: readonly Starred[], uuid: string) => list.some(item => item.uuid === uuid);
export const withStar = (list: readonly Starred[], item: Starred): Starred[] => normalizeStarred([item, ...list.filter(other => other.uuid !== item.uuid)]);
export const withoutStar = (list: readonly Starred[], uuid: string): Starred[] => list.filter(item => item.uuid !== uuid);
const EXPORT_KIND = 'chat-plus.starred';
/** The starred messages as a text the owner can keep (they are in no backup): JSON, to paste back into Import. */
export const exportStarred = (list: readonly Starred[]): string => JSON.stringify({ kind: EXPORT_KIND, version: 1, items: list }, null, 2);
/** The starred messages in a pasted export (or a bare list of them), validated; null when the text is not one. */
export function importStarred(text: string): Starred[] | null {
let parsed: unknown;
try { parsed = JSON.parse(text); } catch { return null; }
const from = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
const items = Array.isArray(parsed) ? parsed : from && from.kind === EXPORT_KIND && Array.isArray(from.items) ? from.items : null;
return items ? normalizeStarred(items) : null;
}
/** The list with imported stars added: a message that is starred already stays as it is. */
export const mergeStarred = (list: readonly Starred[], more: readonly Starred[]): Starred[] => normalizeStarred([...list, ...more]);
/** The conversations that have starred messages, with the newest name each was starred under. */
export function starredConversations(list: readonly Starred[]): { id: string; title: string }[] {
const out = new Map<string, string>();
for (const item of list) if (!out.get(item.conversation)) out.set(item.conversation, item.title);
return [...out].map(([id, title]) => ({ id, title: title || id }));
}
/** The list as the dialog shows it: one conversation or all, and every word of the query in the text, sender or conversation. */
export function filterStarred(list: readonly Starred[], query: string, conversation: string): Starred[] {
const words = query.toLocaleLowerCase().split(/\s+/).filter(Boolean);
return list.filter(item => {
if (conversation && item.conversation !== conversation) return false;
const hay = [item.text, item.sender.name, item.sender.handle ?? '', item.title, item.reply?.text ?? ''].join('\n').toLocaleLowerCase();
return words.every(word => hay.includes(word));
});
}
/** A starred message as text to paste: who, when, then the message as a quote. */
export function quoteOf(item: Starred, when: string): string {
const who = [item.sender.name || item.sender.handle || '', item.sender.handle && item.sender.name ? `(@${item.sender.handle})` : ''].filter(Boolean).join(' ');
const head = [who, when].filter(Boolean).join(', ');
const body = (item.text || item.media.map(media => `[${media.type}]`).join(' ')).split('\n').map(line => `> ${line}`).join('\n');
return head ? `${head}:\n${body}` : body;
}
export type OpenResult = 'opened' | 'replied' | 'no-position' | 'gone' | 'reply-failed';
/**
* "Open at message": goes to a starred message with X's own mechanisms (`landed` is called once its
* row is there). With `reply`, X's own Reply is then opened for it and the text box focused; what
* is written and whether it is sent stays with the user. When a step fails the user is left where
* the earlier steps brought them, and the result says which.
*/
export async function openStarred(win: Window & typeof globalThis, sel: ChatSelectors, item: Pick<Starred, 'conversation' | 'uuid' | 'seq'>, reply: boolean, pace: Pace, landed: () => void = () => {}): Promise<OpenResult> {
if (!item.seq) {
// Starred while X's record of the row could not be read: the conversation is all there is to open.
if (conversationOf(win.location.pathname) !== item.conversation) openConversation(win, item.conversation);
return 'no-position';
}
if (!await jumpToMessage(win, sel, { conversation: item.conversation, uuid: item.uuid, seq: item.seq }, pace)) return 'gone';
landed();
if (!reply) return 'opened';
return await openReply(win, sel, item.uuid, pace) === 'ok' ? 'replied' : 'reply-failed';
}
const starCss = (row: string) => `
.bt-chat-star { position: absolute; z-index: 1; top: 50%; inset-inline-end: 6px; transform: translateY(-50%); display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 999px; background: transparent; color: inherit; cursor: pointer; opacity: 0; transition: opacity .12s; }
.bt-chat-star[data-bt-chat-side="start"] { inset-inline: 6px auto; }
.bt-chat-star[data-bt-chat-side="inline"] { position: static; flex: none; align-self: center; margin: 0 2px; transform: none; }
${row}:hover .bt-chat-star, ${row}:focus-within .bt-chat-star, .bt-chat-star:focus-visible, .bt-chat-star[aria-pressed="true"] { opacity: .75; }
.bt-chat-star:hover { opacity: 1; background: rgba(127, 127, 127, .18); }
.bt-chat-star:focus-visible { opacity: 1; outline: 2px solid var(--wb-accent, rgb(29, 155, 240)); outline-offset: 1px; }
.bt-chat-star[aria-pressed="true"] { color: #f5b301; }
.bt-chat-star[aria-pressed="true"] svg, .bt-chat-hbtn[data-bt-chat-button="bookmarks"][aria-pressed="true"] svg { fill: currentColor; }
`;
const LIST_CSS = `
.bt-starred-tools { display: flex; gap: 8px; margin-bottom: 12px; }
.bt-starred-tools input { flex: 2; min-width: 0; }
.bt-starred-tools select { flex: 1; min-width: 0; }
.bt-starred-list { display: flex; flex-direction: column; gap: 10px; max-height: min(60vh, 560px); overflow: auto; padding-inline-end: 4px; }
.bt-starred-item { display: flex; flex-direction: column; gap: 6px; padding: 12px; border: 1px solid var(--wb-border); border-radius: 12px; }
.bt-starred-head { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; font-size: 13px; color: var(--wb-muted); }
.bt-starred-head b { color: var(--wb-text); font-size: 14px; }
.bt-starred-reply { padding-inline-start: 8px; border-inline-start: 2px solid var(--wb-border-strong); font-size: 13px; color: var(--wb-muted); white-space: pre-wrap; overflow-wrap: anywhere; }
.bt-starred-text { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 9em; overflow: auto; user-select: text; }
.bt-starred-acts { display: flex; flex-wrap: wrap; gap: 6px; }
.bt-starred-acts .wb-btn { min-height: 32px; padding: 0 12px; font-size: 13px; }
`;
type Ctx = FeatureContext<PluginApi>;
export const bookmarks: FeatureModule<PluginApi> = {
id: 'chat.bookmarks',
probes: CONVERSATION_PROBES,
start(ctx: Ctx) {
const { win } = ctx;
const doc = win.document;
const chatScope = () => chatRoot(doc);
const sel = chatSelectors(ctx, CONVERSATION_PROBES);
const clock = timers(win);
let alive = true;
let busy = false;
// The list is read once and again after another tab changed it.
let cache: Starred[] | null = null;
const list = () => cache ??= readStarred(ctx.storage);
const save = (next: Starred[]) => {
if (!ctx.storage.set(STARRED_KEY, next)) { ctx.api.toast(ctx.text('full')); return false; }
cache = next;
watch.schedule();
return true;
};
const when = (item: Starred) => (item.time ? ctx.api.i18n.date(item.time, { dateStyle: 'medium', timeStyle: 'short' }) : item.timeLabel);
const toggle = (row: Element) => {
const info = readRow(row, sel);
const conversation = conversationOf(win.location.pathname);
if (!info || !conversation) { ctx.api.toast(ctx.text('cannot')); return; }
if (isStarred(list(), info.uuid)) { if (save(withoutStar(list(), info.uuid))) ctx.api.toast(ctx.text('removed')); return; }
if (list().length >= MAX_STARRED) { ctx.api.toast(ctx.text('limit', { count: MAX_STARRED })); return; }
if (save(withStar(list(), starOf(info, conversation, conversationTitle(chatScope(), sel), Date.now())))) ctx.api.toast(ctx.text('added'));
};
const starButton = () => {
const button = doc.createElement('button');
button.type = 'button';
button.className = 'bt-chat-star';
button.append(icon(doc, ICONS.star));
// The button sits inside X's row: its clicks and presses are not X's to handle.
for (const type of ['pointerdown', 'mousedown', 'dblclick']) button.addEventListener(type, event => event.stopPropagation());
button.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
const row = button.closest(sel.row);
if (row) toggle(row);
});
return button;
};
const scan = () => {
if (!isChatPath(win.location.pathname)) return;
const starred = new Set(list().map(item => item.uuid));
for (const row of renderedRows(chatScope(), sel)) {
const on = starred.has(row.getAttribute('data-dm-message-row') ?? '');
let button = row.querySelector('.bt-chat-star') as HTMLElement | null;
// Beside X's own React and More buttons while X shows them (in their row, never over them). Else
// on the free side of the row, out of the layout: X puts your own messages at the end.
const home = row.querySelector('[data-testid^="message-overflow-button-"]')?.parentElement ?? row;
const side = home !== row ? 'inline' : /(?:^|\s)justify-end(?:\s|$)/.test(row.getAttribute('class') ?? '') ? 'start' : 'end';
if (!button) button = starButton();
if (button.parentElement !== home) home.append(button);
if (button.getAttribute('data-bt-chat-side') !== side) button.setAttribute('data-bt-chat-side', side);
if (button.getAttribute('aria-pressed') !== String(on)) {
button.setAttribute('aria-pressed', String(on));
const label = on ? ctx.text('unstar') : ctx.text('star');
button.setAttribute('aria-label', label);
button.title = label;
}
if (row.hasAttribute('data-bt-chat-starred') !== on) { if (on) row.setAttribute('data-bt-chat-starred', ''); else row.removeAttribute('data-bt-chat-starred'); }
}
const button = { name: 'bookmarks', title: ctx.text('title'), icon: ICONS.star, pressed: starred.size > 0, onClick: openList };
headerButton(doc, chatScope().querySelector(sel.header), 'bookmarks', button);
headerButton(doc, chatScope().querySelector(sel.inboxHeader), 'bookmarks', button);
};
/** What the list's "Open at message" and "Reply" do, said in a toast when a step failed. */
const openAt = async (item: Starred, reply: boolean) => {
if (busy) return;
busy = true;
try {
const result = await openStarred(win, sel, item, reply, { sleep: clock.sleep }, () => flash(chatScope(), sel, item.uuid, item.seq, clock));
if (!alive) return;
if (result === 'no-position') ctx.api.toast(ctx.text('noPosition'), 5000);
else if (result === 'gone') ctx.api.toast(ctx.text('gone'), 5000);
else if (result === 'reply-failed') ctx.api.toast(ctx.text('replyFailed'), 5000);
} catch (error) {
console.error('[wayBetter for X] chat.bookmarks: opening a starred message failed', error);
if (alive) ctx.api.toast(ctx.text('gone'), 5000);
} finally { busy = false; }
};
function openList() {
const h = ctx.ui.h;
let query = '';
let conversation = '';
const items = h('div', { class: 'bt-starred-list' });
const render = () => {
const shown = filterStarred(list(), query, conversation);
items.replaceChildren(...(shown.length ? shown.map(row) : [h('p', { class: 'wb-hint' }, list().length ? ctx.text('noMatch') : ctx.text('empty'))]));
};
const act = (label: string, run: () => void, tone = 'wb-secondary') => h('button', { type: 'button', class: `wb-btn ${tone}`, onclick: run }, label);
const row = (item: Starred) => h('div', { class: 'bt-starred-item' },
h('div', { class: 'bt-starred-head' },
h('b', null, item.sender.name || ctx.text('unknownSender')),
item.sender.handle ? h('span', null, `@${item.sender.handle}`) : null,
h('span', null, item.title || item.conversation),
h('span', null, when(item))),
item.reply ? h('div', { class: 'bt-starred-reply' }, item.reply.text ? ctx.text('replyTo', { name: item.reply.senderName ?? '', text: item.reply.text }) : ctx.text('isReply')) : null,
item.text ? h('div', { class: 'bt-starred-text' }, item.text) : null,
item.media.length ? h('div', { class: 'wb-hint' }, item.media.map(media => (media.type === 'video' ? ctx.text('video') : ctx.text('image'))).join(' · ')) : null,
h('div', { class: 'bt-starred-acts' },
act(ctx.text('open'), () => { dialog.close(); void openAt(item, false); }, 'wb-primary'),
act(ctx.text('reply'), () => { dialog.close(); void openAt(item, true); }),
act(ctx.text('copy'), () => { void ctx.api.copyText(quoteOf(item, when(item))).then(ok => ctx.api.toast(ok ? ctx.text('copied') : ctx.text('copyFailed'))); }),
act(ctx.text('remove'), () => { if (save(withoutStar(list(), item.uuid))) render(); }, 'wb-plain')));
const dialog = ctx.ui.dialog({
title: ctx.text('title'),
width: 'lg',
css: LIST_CSS,
content: body => {
const chats = starredConversations(list());
body.append(
h('div', { class: 'bt-starred-tools' },
h('input', { type: 'search', class: 'wb-input', placeholder: ctx.text('search'), 'aria-label': ctx.text('search'), oninput: (event: Event) => { query = (event.target as HTMLInputElement).value; render(); } }),
h('select', { class: 'wb-input', 'aria-label': ctx.text('chat'), onchange: (event: Event) => { conversation = (event.target as HTMLSelectElement).value; render(); } },
h('option', { value: '' }, ctx.text('allChats')), chats.map(chat => h('option', { value: chat.id }, chat.title)))),
items,
h('p', { class: 'wb-hint' }, ctx.text('local')));
render();
},
actions: [
// Starred messages are in no backup: a copy as JSON, and the way back in.
{ label: ctx.text('export'), tone: 'plain', onClick: () => { void ctx.api.copyText(exportStarred(list())).then(ok => ctx.api.toast(ok ? ctx.text('exported', { count: list().length }) : ctx.text('copyFailed'))); return false; } },
{ label: ctx.text('import'), tone: 'plain', onClick: () => { void importFrom(render); return false; } },
{ label: ctx.text('close'), tone: 'secondary' },
],
});
}
/** Import: a pasted export, validated like everything read from storage, added to the list. */
async function importFrom(done: () => void) {
const pasted = await ctx.ui.prompt({
title: ctx.text('import'), message: ctx.text('importHint'), multiline: true, confirmLabel: ctx.text('import'),
validate: value => (importStarred(value) ? null : ctx.text('importBad')),
});
const more = pasted === null ? null : importStarred(pasted);
if (!alive || !more) return;
const before = list().length;
const next = mergeStarred(list(), more);
if (!save(next)) return;
ctx.api.toast(ctx.text('imported', { count: next.length - before }));
done();
}
ctx.css(SHARED_CSS + starCss(sel.row));
const watch = ctx.watch(scan);
ctx.on(win, 'storage', () => { cache = null; watch.schedule(); });
ctx.onRouteChange(() => watch.schedule());
ctx.command({ id: 'bookmarks.open', title: ctx.text('title'), keywords: 'starred messages bookmarks saved chat dm reply jump', run: openList });
ctx.defer(() => {
alive = false;
clock.clear();
for (const place of new Set<ParentNode>([doc, chatScope()])) {
for (const node of Array.from(place.querySelectorAll('.bt-chat-star'))) node.remove();
removeHeaderButtons(place, 'bookmarks');
clearAttribute(place, 'data-bt-chat-starred');
clearAttribute(place, 'data-bt-chat-flash');
}
});
watch.schedule();
},
};

View file

@ -0,0 +1,29 @@
// Chat+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
//
// X's chat is a heavy page: every row says `heavy`, so it runs there (nothing else of the app does).
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { modules } from '../rows.ts';
const CHAT = ['chat'];
/** The words of a feature's row on the card (./messages.en.json). */
const words = (name: string) => ({ label: `plugin.chat-plus.feature.${name}.label`, description: `plugin.chat-plus.feature.${name}.description` });
export const FEATURES: readonly FeatureSpec[] = [
...modules('chat', '', [
// No surfaces: the list of starred messages opens from any page of X (its star buttons only exist in chats).
{ id: 'chat.bookmarks', heavy: true, ...words('bookmarks'), keywords: 'star starred messages bookmarks saved dm reply jump', permissions: ['storage', 'ui', 'clipboard', 'commands'] },
{ id: 'chat.searchLoaded', surfaces: CHAT, heavy: true, ...words('searchLoaded'), keywords: 'find search in conversation ctrl shift f messages', permissions: ['ui', 'commands'] },
{ id: 'chat.pins', surfaces: CHAT, heavy: true, ...words('pins'), keywords: 'pin pinned label color chats conversations strip', permissions: ['storage', 'ui', 'commands'] },
{ id: 'chat.personFilter', surfaces: CHAT, heavy: true, ...words('personFilter'), keywords: 'group chat person participant filter only from', permissions: ['storage', 'ui', 'commands'] },
{ id: 'chat.keywords', surfaces: CHAT, heavy: true, settings: true, ...words('keywords'), keywords: 'highlight mute words keywords hide messages', permissions: ['storage', 'ui'] },
]),
];
/**
* Flags Power User turns on besides the defaults (this area's advanced features). None of them does
* anything by itself: a star, a pin, a picked person or a word list of the owner's comes first.
*/
export const POWER: readonly string[] = ['chat.bookmarks', 'chat.searchLoaded', 'chat.pins', 'chat.personFilter', 'chat.keywords'];

View file

@ -0,0 +1,24 @@
// Chat+: its feature modules (docs/AREA-PLUGINS.md; Navigation+ in ../navigation is the reference).
// One module per `backing: 'module'` row of ./features.ts; the registry starts each only while its
// flag is on, the area is on and the page is on one of its surfaces.
//
// X's chat is the one place the rest of the app stays out of (a heavy page). These modules run
// there on purpose and keep it cheap: one shared watch each (child list only, one frame), looking
// only at X's message list or its conversation list. ./x.ts is what they know about X's chat.
// None of them makes a request, writes or sends a message, reacts, deletes or marks anything read.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { bookmarks } from './bookmarks.ts';
import { keywords } from './keywords.ts';
import { personFilter } from './personFilter.ts';
import { pins } from './pins.ts';
import { searchLoaded } from './searchLoaded.ts';
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [
bookmarks,
searchLoaded,
pins,
personFilter,
keywords,
];

View file

@ -0,0 +1,103 @@
// Chat+ · Keywords in chats. Two word lists in the settings: a message with a highlight word gets
// an accent, a message with a mute word folds into a thin "hidden by Chat+" line that opens on a
// click. Both are attributes on X's message row: the message text itself is never edited, and
// nothing but the two word lists is stored. A message whose text cannot be read stays as it is.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { clearAttribute } from './ui.ts';
import { CONVERSATION_PROBES, CHAT_PAGE_PROBE, chatRoot, chatSelectors, conversationOf, renderedRows, rowText } from './x.ts';
export const KEYWORDS_SCHEMA: SettingsSchema = [
{ key: 'highlight', type: 'list', default: [], label: 'highlight', hint: 'highlightHint', maxItems: 100, maxLength: 80 },
{ key: 'mute', type: 'list', default: [], label: 'mute', hint: 'muteHint', maxItems: 100, maxLength: 80 },
];
export type Matcher = (text: string) => boolean;
/**
* A test for "one of these words is in the text": whole words or phrases, any letter case, in any
* script. An empty list matches nothing.
*/
export function wordMatcher(words: readonly string[]): Matcher {
const parts = [...new Set(words.map(word => word.trim()).filter(Boolean))].map(word => word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+'));
if (!parts.length) return () => false;
const pattern = new RegExp(`(?<![\\p{L}\\p{N}_])(?:${parts.join('|')})(?![\\p{L}\\p{N}_])`, 'iu');
return text => pattern.test(text);
}
export type Verdict = 'muted' | 'hit' | null;
/** What a message's text asks for: muted wins over highlighted; no text, no verdict. */
export const verdictOf = (text: string, highlight: Matcher, mute: Matcher): Verdict => (!text ? null : mute(text) ? 'muted' : highlight(text) ? 'hit' : null);
const MARK = 'data-bt-chat-kw';
const LABEL = 'data-bt-chat-kw-label';
const ACCENT = 'var(--wb-accent, rgb(29, 155, 240))';
const css = (row: string) => `
${row}[${MARK}="hit"] { box-shadow: inset 3px 0 0 ${ACCENT}; background: color-mix(in srgb, ${ACCENT} 12%, transparent); border-radius: 6px; }
${row}[${MARK}="muted"] { display: block; cursor: pointer; }
${row}[${MARK}="muted"] > * { display: none !important; }
${row}[${MARK}="muted"]::before { content: attr(${LABEL}); display: block; padding: 2px 12px; text-align: center; font: 500 12px/1.5 var(--wb-font, system-ui, sans-serif); color: var(--wb-muted, inherit); opacity: .7; }
${row}[${MARK}="muted"]:hover::before { opacity: 1; text-decoration: underline; }
`;
type Ctx = FeatureContext<PluginApi>;
export const keywords: FeatureModule<PluginApi> = {
id: 'chat.keywords',
probes: { ...CONVERSATION_PROBES, ...CHAT_PAGE_PROBE },
settings: KEYWORDS_SCHEMA,
start(ctx: Ctx) {
const { win } = ctx;
const doc = win.document;
const chatScope = () => chatRoot(doc);
const sel = chatSelectors(ctx, CONVERSATION_PROBES);
let highlight: Matcher = () => false;
let mute: Matcher = () => false;
let conversation: string | null = null;
/** Muted messages the user opened (by message id), until the conversation changes. */
const opened = new Set<string>();
const compile = () => {
const values = ctx.settings.get();
highlight = wordMatcher(values.highlight as string[]);
mute = wordMatcher(values.mute as string[]);
};
const scan = () => {
const open = conversationOf(win.location.pathname);
if (open !== conversation) { conversation = open; opened.clear(); }
for (const row of renderedRows(chatScope(), sel)) {
let verdict = verdictOf(rowText(row, sel), highlight, mute);
if (verdict === 'muted' && opened.has(row.getAttribute('data-dm-message-row') ?? '')) verdict = null;
if ((row.getAttribute(MARK) ?? null) === verdict) continue;
if (verdict) row.setAttribute(MARK, verdict); else row.removeAttribute(MARK);
if (verdict === 'muted') row.setAttribute(LABEL, ctx.text('hidden')); else row.removeAttribute(LABEL);
}
};
compile();
ctx.css(css(sel.row));
const watch = ctx.watch(scan);
ctx.settings.onChange(() => { compile(); watch.schedule(); });
ctx.onRouteChange(() => watch.schedule());
// A click on a folded message opens it (and is not a click on the message).
ctx.on(doc, 'click', event => {
const row = ((event.composedPath?.()[0] ?? event.target) as Element | null)?.closest?.(`${sel.row}[${MARK}="muted"]`);
if (!row) return;
event.preventDefault();
event.stopPropagation();
opened.add(row.getAttribute('data-dm-message-row') ?? '');
watch.schedule();
}, true);
ctx.defer(() => {
for (const place of new Set<ParentNode>([doc, chatScope()])) {
clearAttribute(place, MARK);
clearAttribute(place, LABEL);
}
});
watch.schedule();
},
};

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,137 @@
// Chat+ · Person filter. In a group chat: pick one participant from a small list under the button
// in X's chat header and everyone else's messages fade, so that person's messages can be followed
// through the conversation. One click on the chip that replaces the button (or Esc) clears it. The
// participants offered are the senders of the messages X has loaded plus the senders of messages
// starred in this chat. A message whose sender cannot be read stays as it is. Nothing is stored:
// the choice ends with the conversation.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { STARRED_NAMESPACE, readStarred, type Starred } from './bookmarks.ts';
import { ICONS, SHARED_CSS, clearAttribute, headerButton, paint, removeHeaderButtons } from './ui.ts';
import { CONVERSATION_PROBES, CHAT_PAGE_PROBE, chatRoot, chatSelectors, conversationOf, isGroup, loadedMessages, messageItemOf, renderedRows, senderOf, type LoadedMessage } from './x.ts';
export type Person = { id: string; name: string };
/**
* The participants to offer: every sender of a loaded message and of a message starred in this
* conversation whose name is known, each once, by name. `names` are the ones seen on rows earlier.
*/
export function participants(loaded: readonly LoadedMessage[], starred: readonly Starred[], conversation: string, names: ReadonlyMap<string, string> = new Map()): Person[] {
const out = new Map<string, string>(names);
for (const message of loaded) if (message.senderId && message.senderName && !out.has(message.senderId)) out.set(message.senderId, message.senderName);
for (const item of starred) if (item.conversation === conversation && item.sender.id && item.sender.name && !out.has(item.sender.id)) out.set(item.sender.id, item.sender.name);
return [...out].map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name));
}
/** Whether a row fades: only when its sender is known and is somebody else. */
export const dims = (senderId: string | null | undefined, selected: string | null) => !!selected && !!senderId && senderId !== selected;
const DIM = 'data-bt-chat-dim';
const css = (row: string) => `
${row}[${DIM}] { opacity: .16; transition: opacity .15s; }
${row}[${DIM}]:hover, ${row}[${DIM}]:focus-within { opacity: .6; }
.bt-chat-people { position: fixed; z-index: 2147483000; top: 64px; right: 24px; box-sizing: border-box; display: flex; flex-direction: column; gap: 2px; width: min(280px, calc(100vw - 32px)); max-height: min(60vh, 420px); overflow: auto; padding: 6px; border: 1px solid var(--bt-chat-border, rgba(127, 127, 127, .4)); border-radius: 14px; background: var(--bt-chat-bg, #16181c); color: var(--bt-chat-text, #e7e9ea); box-shadow: 0 12px 32px -8px rgba(0, 0, 0, .45); font: 400 14px/1.4 var(--wb-font, system-ui, sans-serif); }
.bt-chat-people button { flex: none; min-height: 36px; padding: 0 12px; border: 0; border-radius: 9px; background: transparent; color: inherit; font: 600 14px/1.2 inherit; text-align: start; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }
.bt-chat-people button:hover { background: rgba(127, 127, 127, .2); }
.bt-chat-people button:focus-visible { outline: 2px solid var(--bt-chat-accent, rgb(29, 155, 240)); outline-offset: -2px; }
.bt-chat-people p { margin: 0; padding: 6px 12px; font-size: 12px; color: var(--bt-chat-muted, inherit); }
`;
type Ctx = FeatureContext<PluginApi>;
export const personFilter: FeatureModule<PluginApi> = {
id: 'chat.personFilter',
probes: { ...CONVERSATION_PROBES, ...CHAT_PAGE_PROBE },
start(ctx: Ctx) {
const { win } = ctx;
const doc = win.document;
const chatScope = () => chatRoot(doc);
const sel = chatSelectors(ctx, CONVERSATION_PROBES);
/** The conversation the state below belongs to: it starts over when another one opens. */
let conversation: string | null = null;
let selected: Person | null = null;
let list: HTMLElement | null = null;
/** Names X showed on rows of this conversation (a sender's id is in X's record of a row, the name on the row). */
const names = new Map<string, string>();
const group = () => { const open = conversationOf(win.location.pathname); return open && isGroup(open) ? open : null; };
const closeList = () => { list?.remove(); list = null; };
const clear = () => { selected = null; watch.schedule(); };
const scan = () => {
const open = group();
if (open !== conversation) { conversation = open; selected = null; names.clear(); closeList(); }
if (!open) {
removeHeaderButtons(chatScope(), 'personFilter');
clearAttribute(chatScope(), DIM);
return;
}
for (const row of renderedRows(chatScope(), sel)) {
const item = messageItemOf(row);
const sender = item ? senderOf(item) : null;
const name = (row.querySelector('[id$="-sender"]')?.textContent ?? '').trim() || sender?.name;
if (sender && name && !names.has(sender.id)) names.set(sender.id, name);
const dim = dims(sender?.id, selected?.id ?? null);
if (row.hasAttribute(DIM) !== dim) { if (dim) row.setAttribute(DIM, ''); else row.removeAttribute(DIM); }
}
headerButton(doc, chatScope().querySelector(sel.header), 'personFilter', selected
? { name: 'personFilter', title: ctx.text('clear'), icon: ICONS.close, pressed: true, label: selected.name, onClick: clear }
: { name: 'personFilter', title: ctx.text('title'), icon: ICONS.person, pressed: false, onClick: pick });
};
/** The small list of participants, under the header button; a second call closes it. */
function pick() {
if (list) { closeList(); return; }
const open = group();
if (!open) { ctx.api.toast(ctx.text('groupOnly')); return; }
scan();
const people = participants(loadedMessages(chatScope(), sel).messages, readStarred(ctx.api.storage(STARRED_NAMESPACE)), open, names);
const root = doc.createElement('div');
root.className = 'bt-chat-people';
root.setAttribute('role', 'dialog');
root.setAttribute('aria-label', ctx.text('title'));
paint(ctx.api, root);
const anchor = (chatScope().querySelector('[data-bt-chat-button="personFilter"]') ?? chatScope().querySelector(sel.header))?.getBoundingClientRect?.();
if (anchor && anchor.width > 0) {
root.style.top = `${Math.round(anchor.bottom + 6)}px`;
root.style.right = `${Math.max(12, Math.round(win.innerWidth - anchor.right))}px`;
}
for (const person of people) {
const button = doc.createElement('button');
button.type = 'button';
button.textContent = person.name;
button.addEventListener('click', () => { selected = person; closeList(); watch.schedule(); });
root.append(button);
}
const hint = doc.createElement('p');
hint.textContent = people.length ? ctx.text('hint') : ctx.text('nobody');
root.append(hint);
doc.body.append(root);
list = root;
(root.querySelector('button') as HTMLElement | null)?.focus();
}
ctx.css(SHARED_CSS + css(sel.row));
const watch = ctx.watch(scan);
ctx.onRouteChange(() => watch.schedule());
// Esc closes the list when it is open, else clears the filter; a click anywhere else closes the list.
ctx.on(doc, 'keydown', event => {
if ((event as KeyboardEvent).key !== 'Escape') return;
if (list) closeList(); else if (selected) clear();
});
ctx.on(doc, 'click', event => {
const target = (event.composedPath?.()[0] ?? event.target) as Element | null;
if (list && !list.contains(target) && !target?.closest?.('[data-bt-chat-button="personFilter"]')) closeList();
}, true);
ctx.command({ id: 'personFilter.pick', title: ctx.text('command'), keywords: 'group chat person participant only show messages from filter', run: pick });
ctx.defer(() => {
closeList();
for (const place of new Set<ParentNode>([doc, chatScope()])) {
removeHeaderButtons(place, 'personFilter');
clearAttribute(place, DIM);
}
});
watch.schedule();
},
};

View file

@ -0,0 +1,237 @@
// Chat+ · Pinned chats. A strip above X's conversation list with the chats you pinned, each with
// an optional label and color of your own. X's list is virtualized and stays exactly as X orders
// it: the strip is a separate row of links. A chip opens its conversation through X's own link when
// that row is in the list, else through X's router. Pin, rename, label or unpin from the small
// button on a conversation row, from a chip's edit button or from the palette. Only conversation
// ids and the names and labels you typed are stored, in this tab's page storage.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { ICONS, icon } from './ui.ts';
import { INBOX_PROBES, CHAT_PAGE_PROBE, chatRoot, chatSelectors, conversationKey, conversationOf, conversationTitle, inboxRowConversation, openConversation, type ChatSelectors } from './x.ts';
export const COLORS = ['', 'blue', 'green', 'yellow', 'orange', 'red', 'purple'] as const;
export type PinColor = typeof COLORS[number];
/** The word of each color (./messages.en.json). */
const COLOR_WORDS: Record<PinColor, string> = { '': 'colorNone', blue: 'colorBlue', green: 'colorGreen', yellow: 'colorYellow', orange: 'colorOrange', red: 'colorRed', purple: 'colorPurple' };
const COLOR_VALUES: Record<PinColor, string> = { '': 'rgba(127, 127, 127, .7)', blue: '#1d9bf0', green: '#00ba7c', yellow: '#f5b301', orange: '#ff7a00', red: '#f4212e', purple: '#7856ff' };
export type Pin = { id: string; title: string; label: string; color: PinColor; at: number };
export const PINS_KEY = 'pins';
export const MAX_PINS = 30;
const TITLE_MAX = 60;
const LABEL_MAX = 24;
const clean = (value: unknown, max: number) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '');
/** The pins from whatever was stored: valid conversations only, each once, oldest pin first. */
export function normalizePins(raw: unknown): Pin[] {
const out: Pin[] = [];
for (const item of Array.isArray(raw) ? raw : []) {
const from = item && typeof item === 'object' ? item as Record<string, unknown> : null;
const id = from ? conversationKey(typeof from.id === 'string' ? from.id : '') : null;
if (!from || !id || out.some(pin => pin.id === id)) continue;
out.push({
id, title: clean(from.title, TITLE_MAX) || id, label: clean(from.label, LABEL_MAX),
color: (COLORS as readonly string[]).includes(from.color as string) ? from.color as PinColor : '',
at: typeof from.at === 'number' && Number.isFinite(from.at) ? from.at : 0,
});
}
return out.sort((a, b) => a.at - b.at).slice(0, MAX_PINS);
}
/** The pins with `pin` added, or changed in place when its conversation is pinned already. */
export function withPin(pins: readonly Pin[], pin: Pin): Pin[] {
const known = pins.find(other => other.id === pin.id);
return normalizePins(known ? pins.map(other => (other === known ? { ...pin, at: known.at } : other)) : [...pins, pin]);
}
export const withoutPin = (pins: readonly Pin[], id: string): Pin[] => pins.filter(pin => pin.id !== id);
/** The name X shows on an inbox row (its first line of text). */
export function inboxRowTitle(row: Element): string {
return clean(row.querySelector('[dir="auto"]')?.textContent ?? '', TITLE_MAX);
}
const css = (row: string) => `
.bt-chat-pins { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--wb-border, rgba(127, 127, 127, .25)); font: 500 13px/1.2 var(--wb-font, system-ui, sans-serif); color: var(--wb-text, inherit); }
.bt-chat-pin-chip { display: inline-flex; align-items: center; max-width: 100%; border: 1px solid var(--wb-border, rgba(127, 127, 127, .35)); border-radius: 999px; overflow: hidden; }
.bt-chat-pin-chip[data-bt-chat-current] { border-color: var(--bt-chat-color); box-shadow: inset 0 0 0 1px var(--bt-chat-color); }
.bt-chat-pin-chip button { display: inline-flex; align-items: center; gap: 6px; min-width: 0; height: 28px; padding: 0 10px; border: 0; background: transparent; color: inherit; font: inherit; cursor: pointer; }
.bt-chat-pin-chip button:hover { background: rgba(127, 127, 127, .18); }
.bt-chat-pin-chip button:focus-visible, .bt-chat-pin:focus-visible { outline: 2px solid var(--wb-accent, rgb(29, 155, 240)); outline-offset: -2px; }
.bt-chat-pin-chip .bt-chat-pin-edit { padding: 0 8px 0 4px; opacity: .55; }
.bt-chat-pin-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--bt-chat-color); }
.bt-chat-pin-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 160px; }
.bt-chat-pin-label { flex: none; padding: 1px 6px; border-radius: 999px; background: color-mix(in srgb, var(--bt-chat-color) 22%, transparent); font-size: 11px; font-weight: 700; }
.bt-chat-pin { position: absolute; z-index: 1; inset-inline-start: 2px; top: 2px; display: inline-flex; align-items: center; justify-content: center; width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%; background: var(--wb-bg, rgba(0, 0, 0, .6)); color: var(--wb-text, #fff); cursor: pointer; opacity: 0; transition: opacity .12s; }
.bt-chat-pin svg { width: 12px; height: 12px; }
li:hover > .bt-chat-pin, ${row}:hover .bt-chat-pin, .bt-chat-pin:focus-visible { opacity: .85; }
.bt-chat-pin[aria-pressed="true"] { opacity: 1; background: var(--bt-chat-color); color: #fff; }
.bt-chat-pin-colors { display: flex; gap: 8px; margin: 4px 0 8px; }
.bt-chat-pin-colors button { width: 26px; height: 26px; padding: 0; border: 2px solid transparent; border-radius: 50%; background: var(--bt-chat-color); cursor: pointer; }
.bt-chat-pin-colors button[aria-pressed="true"] { border-color: var(--wb-text); box-shadow: 0 0 0 2px var(--wb-bg) inset; }
`;
type Ctx = FeatureContext<PluginApi>;
/** Opens a conversation: a click on X's own link for it when that row is in the list, else X's router. */
export function openPinned(win: Window & typeof globalThis, sel: ChatSelectors, id: string): void {
const links = Array.from(chatRoot(win.document).querySelectorAll(`${sel.inboxScroller} a[href^="/i/chat/"]`));
const link = links.find(node => conversationKey((node.getAttribute('href') ?? '').slice('/i/chat/'.length)) === id) as HTMLElement | undefined;
if (link) link.click(); else openConversation(win, id);
}
export const pins: FeatureModule<PluginApi> = {
id: 'chat.pins',
probes: { ...INBOX_PROBES, ...CHAT_PAGE_PROBE },
start(ctx: Ctx) {
const { win } = ctx;
const doc = win.document;
const chatScope = () => chatRoot(doc);
const sel = chatSelectors(ctx, INBOX_PROBES);
let cache: Pin[] | null = null;
const list = () => cache ??= normalizePins(ctx.storage.get<unknown>(PINS_KEY, []));
const save = (next: Pin[]) => {
if (!ctx.storage.set(PINS_KEY, next)) { ctx.api.toast(ctx.text('failed')); return false; }
cache = next;
watch.schedule();
return true;
};
const colorOf = (pin: Pin | undefined) => COLOR_VALUES[pin?.color ?? ''];
const chip = (pin: Pin, current: boolean) => {
const wrap = doc.createElement('span');
wrap.className = 'bt-chat-pin-chip';
wrap.style.setProperty('--bt-chat-color', colorOf(pin));
if (current) wrap.setAttribute('data-bt-chat-current', '');
const open = doc.createElement('button');
open.type = 'button';
open.title = pin.title;
const dot = doc.createElement('span');
dot.className = 'bt-chat-pin-dot';
const name = doc.createElement('span');
name.className = 'bt-chat-pin-name';
name.textContent = pin.title;
open.append(dot, name);
if (pin.label) { const label = doc.createElement('span'); label.className = 'bt-chat-pin-label'; label.textContent = pin.label; open.append(label); }
open.addEventListener('click', () => openPinned(win, sel, pin.id));
const edit = doc.createElement('button');
edit.type = 'button';
edit.className = 'bt-chat-pin-edit';
edit.title = ctx.text('edit');
edit.setAttribute('aria-label', `${ctx.text('edit')}: ${pin.title}`);
edit.append(icon(doc, ICONS.edit));
edit.addEventListener('click', () => editPin(pin.id, pin.title));
wrap.append(open, edit);
return wrap;
};
const scan = () => {
const scroller = chatScope().querySelector(sel.inboxScroller);
const all = list();
const current = conversationOf(win.location.pathname);
// The strip: one element just above X's list, rebuilt only when what it shows changed.
let strip = chatScope().querySelector('.bt-chat-pins') as HTMLElement | null;
if (!scroller?.parentElement || !all.length) { strip?.remove(); strip = null; }
else {
const key = JSON.stringify([all, current]);
if (strip && (strip.nextElementSibling !== scroller || strip.getAttribute('data-bt-chat-key') !== key)) { strip.remove(); strip = null; }
if (!strip) {
strip = doc.createElement('div');
strip.className = 'bt-chat-pins';
strip.setAttribute('role', 'navigation');
strip.setAttribute('aria-label', ctx.text('strip'));
strip.setAttribute('data-bt-chat-key', key);
strip.append(...all.map(pin => chip(pin, pin.id === current)));
scroller.parentElement.insertBefore(strip, scroller);
}
}
// The pin button of each conversation row X has rendered.
for (const row of scroller ? Array.from(scroller.querySelectorAll(sel.inboxRow)) : []) {
const id = inboxRowConversation(row);
const host = row.closest('li') ?? row;
let button = Array.from(host.children).find(node => node.classList?.contains('bt-chat-pin')) as HTMLElement | undefined;
if (!id) { button?.remove(); continue; }
if (!button) {
button = doc.createElement('button');
button.setAttribute('type', 'button');
button.className = 'bt-chat-pin';
button.append(icon(doc, ICONS.pin));
for (const type of ['pointerdown', 'mousedown']) button.addEventListener(type, event => event.stopPropagation());
button.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
const at = (event.currentTarget as Element).getAttribute('data-bt-chat-pin') ?? '';
const source = Array.from(chatScope().querySelectorAll(sel.inboxRow)).find(node => inboxRowConversation(node) === at);
editPin(at, source ? inboxRowTitle(source) : '');
});
host.append(button);
}
const pin = all.find(other => other.id === id);
const key = `${id}|${pin ? pin.color : '-'}`;
if (button.getAttribute('data-bt-chat-key') === key) continue;
button.setAttribute('data-bt-chat-key', key);
button.setAttribute('data-bt-chat-pin', id);
button.setAttribute('aria-pressed', String(!!pin));
const label = pin ? ctx.text('edit') : ctx.text('pin');
button.setAttribute('aria-label', label);
button.title = label;
button.style.setProperty('--bt-chat-color', colorOf(pin));
}
};
/** The pin dialog of a conversation: its name in the strip, a label, a color; unpin when it is pinned. */
function editPin(id: string, seenTitle: string) {
if (!conversationKey(id)) return;
const known = list().find(pin => pin.id === id);
if (!known && list().length >= MAX_PINS) { ctx.api.toast(ctx.text('limit', { count: MAX_PINS })); return; }
const h = ctx.ui.h;
let color: PinColor = known?.color ?? '';
const name = h('input', { type: 'text', class: 'wb-input', maxLength: TITLE_MAX, value: known?.title ?? seenTitle }) as HTMLInputElement;
const label = h('input', { type: 'text', class: 'wb-input', maxLength: LABEL_MAX, value: known?.label ?? '', placeholder: ctx.text('labelHint') }) as HTMLInputElement;
const swatches = COLORS.map(value => {
const swatch = h('button', { type: 'button', 'aria-label': ctx.text(COLOR_WORDS[value]), title: ctx.text(COLOR_WORDS[value]), 'aria-pressed': String(value === color), onclick: () => { color = value; for (const other of swatches) other.setAttribute('aria-pressed', String(other === swatch)); } });
swatch.style.setProperty('--bt-chat-color', COLOR_VALUES[value]);
return swatch;
});
ctx.ui.dialog({
title: known ? ctx.text('edit') : ctx.text('pin'),
width: 'sm',
css: css(sel.inboxRow),
content: body => {
body.append(
h('label', { class: 'wb-field' }, h('span', { class: 'wb-label' }, ctx.text('name')), name),
h('label', { class: 'wb-field' }, h('span', { class: 'wb-label' }, ctx.text('label')), label),
h('span', { class: 'wb-label' }, ctx.text('colors')),
h('div', { class: 'bt-chat-pin-colors' }, swatches));
},
actions: [
...(known ? [{ label: ctx.text('unpin'), tone: 'danger' as const, onClick: () => { save(withoutPin(list(), id)); } }] : []),
{ label: ctx.text('cancel'), tone: 'secondary' as const },
{ label: known ? ctx.text('save') : ctx.text('pin'), tone: 'primary' as const, default: true, onClick: () => { save(withPin(list(), { id, title: name.value || seenTitle || id, label: label.value, color, at: Date.now() })); } },
],
});
}
ctx.css(css(sel.inboxRow));
const watch = ctx.watch(scan);
ctx.on(win, 'storage', () => { cache = null; watch.schedule(); });
ctx.onRouteChange(() => watch.schedule());
ctx.command({
id: 'pins.edit',
title: ctx.text('command'),
keywords: 'pin unpin label color chat conversation strip favorite',
run: () => {
const open = conversationOf(win.location.pathname);
if (!open) { ctx.api.toast(ctx.text('openFirst')); return; }
const row = Array.from(chatScope().querySelectorAll(sel.inboxRow)).find(node => inboxRowConversation(node) === open);
editPin(open, (row ? inboxRowTitle(row) : '') || conversationTitle(chatScope(), sel));
},
});
ctx.defer(() => {
for (const place of new Set<ParentNode>([doc, chatScope()])) for (const node of Array.from(place.querySelectorAll('.bt-chat-pins, .bt-chat-pin'))) node.remove();
});
watch.schedule();
},
};

View file

@ -0,0 +1,240 @@
// Chat+ · Find in conversation. Ctrl+Shift+F in an open chat (or the palette) opens a small find bar over
// the conversation: it searches the messages X has loaded for this chat so far, says so, and steps
// through the matches with X's own jump (./x.ts), so a match far outside the rows on screen is
// reached too: Enter goes to the newest match and then to older ones, Shift+Enter to newer ones. "Load older" scrolls X's list up the way a wheel does while the bar is open, so X
// loads more history by itself; it stops on a click, on Esc, or when X has no more to give.
//
// The index exists only while the bar is open and only in memory: X's own list of loaded messages
// when its page exposes it, otherwise the rows that were on screen while the bar was open.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { ICONS, SHARED_CSS, clearAttribute, flash, headerButton, icon, paint, removeHeaderButtons, timers } from './ui.ts';
import { CONVERSATION_PROBES, CHAT_PAGE_PROBE, chatRoot, chatSelectors, conversationOf, jumpToMessage, loadedMessages, scrollOlder, sequenceTime, type LoadedMessage } from './x.ts';
/** The messages that have every word of the query in their text or their sender's name, oldest first. */
export function searchMessages(messages: readonly LoadedMessage[], query: string): LoadedMessage[] {
const words = query.toLocaleLowerCase().split(/\s+/).filter(Boolean);
if (!words.length) return [];
return messages.filter(message => {
const hay = `${message.text}\n${message.senderName ?? ''}`.toLocaleLowerCase();
return words.every(word => hay.includes(word));
});
}
/** The match to show after stepping by `delta` from `at` among `count` matches (wraps around); -1 when there is none. */
export const stepMatch = (at: number, delta: number, count: number) => (count ? ((at + delta) % count + count) % count : -1);
const BAR_CSS = `
.bt-chat-find { position: fixed; z-index: 2147483000; top: 64px; right: 24px; box-sizing: border-box; width: min(420px, calc(100vw - 32px)); padding: 10px 12px; border: 1px solid var(--bt-chat-border, rgba(127, 127, 127, .4)); border-radius: 14px; background: var(--bt-chat-bg, #16181c); color: var(--bt-chat-text, #e7e9ea); box-shadow: 0 12px 32px -8px rgba(0, 0, 0, .45); font: 400 14px/1.4 var(--wb-font, system-ui, sans-serif); }
.bt-chat-find-row { display: flex; align-items: center; gap: 4px; }
.bt-chat-find input { flex: 1; min-width: 0; height: 34px; padding: 0 10px; border: 1px solid var(--bt-chat-border, rgba(127, 127, 127, .4)); border-radius: 8px; background: transparent; color: inherit; font: inherit; outline: none; }
.bt-chat-find input:focus { border-color: var(--bt-chat-accent, rgb(29, 155, 240)); }
.bt-chat-find-count { flex: none; min-width: 56px; padding: 0 4px; text-align: center; font-size: 12px; font-variant-numeric: tabular-nums; color: var(--bt-chat-muted, inherit); }
.bt-chat-find button { flex: none; display: inline-flex; align-items: center; justify-content: center; height: 30px; min-width: 30px; padding: 0 6px; border: 0; border-radius: 8px; background: transparent; color: inherit; font: inherit; cursor: pointer; }
.bt-chat-find button:hover { background: rgba(127, 127, 127, .2); }
.bt-chat-find button:focus-visible { outline: 2px solid var(--bt-chat-accent, rgb(29, 155, 240)); outline-offset: -1px; }
.bt-chat-find button:disabled { opacity: .4; cursor: default; }
.bt-chat-find-note { display: flex; align-items: flex-start; gap: 8px; margin-top: 8px; font-size: 12px; color: var(--bt-chat-muted, inherit); }
.bt-chat-find-note span { flex: 1; min-width: 0; }
.bt-chat-find-note button { height: 26px; padding: 0 10px; border: 1px solid var(--bt-chat-border, rgba(127, 127, 127, .4)); font-size: 12px; font-weight: 600; color: var(--bt-chat-text, inherit); }
`;
type Ctx = FeatureContext<PluginApi>;
type Bar = { root: HTMLElement; input: HTMLInputElement; count: HTMLElement; note: HTMLElement; older: HTMLButtonElement; previous: HTMLButtonElement; next: HTMLButtonElement };
export const searchLoaded: FeatureModule<PluginApi> = {
id: 'chat.searchLoaded',
probes: { ...CONVERSATION_PROBES, ...CHAT_PAGE_PROBE },
start(ctx: Ctx) {
const { win } = ctx;
const doc = win.document;
const chatScope = () => chatRoot(doc);
const sel = chatSelectors(ctx, CONVERSATION_PROBES);
const clock = timers(win);
let bar: Bar | null = null;
let conversation: string | null = null;
/** What is searched: X's loaded list, or (when its page does not expose it) the rows seen while the bar is open. */
let index: LoadedMessage[] = [];
const seen = new Map<string, LoadedMessage>();
let matches: LoadedMessage[] = [];
let at = -1;
let loading = false;
let ended = false;
let jumps = 0;
/** The match the conversation was last moved to (its sequence number). */
let shown: string | null = null;
// Writes only what changed: a scan that always wrote would be its own next mutation.
const setText = (node: HTMLElement, value: string) => { if (node.textContent !== value) node.textContent = value; };
const button = (title: string, path: string | null, label: string | null, run: () => void) => {
const node = doc.createElement('button');
node.type = 'button';
node.title = title;
node.setAttribute('aria-label', title);
if (path) node.append(icon(doc, path));
if (label) node.append(label);
node.addEventListener('click', run);
return node;
};
const show = () => {
if (!bar) return;
setText(bar.count, bar.input.value.trim() ? (matches.length ? ctx.text('count', { at: at + 1, total: matches.length }) : ctx.text('none')) : '');
bar.previous.disabled = bar.next.disabled = matches.length === 0;
const oldest = index.length ? sequenceTime(index[0]!.seq) : null;
const scope = index.length
? ctx.text('scope', { count: index.length, date: oldest ? ctx.api.i18n.date(oldest, { dateStyle: 'medium', timeStyle: 'short' }) : '' })
: ctx.text('nothingLoaded');
setText(bar.note, ended ? `${scope} ${ctx.text('noMore')}` : scope);
setText(bar.older, loading ? ctx.text('stop') : ctx.text('older'));
};
/** Reads what X has loaded now and searches it again; the match being shown stays the shown one. */
const refresh = () => {
if (!bar) return;
const loaded = loadedMessages(chatScope(), sel);
if (loaded.complete) { seen.clear(); index = loaded.messages; }
else {
for (const message of loaded.messages) seen.set(message.seq, message);
index = [...seen.values()].sort((a, b) => (BigInt(a.seq) < BigInt(b.seq) ? -1 : 1));
}
const current = matches[at]?.seq;
matches = searchMessages(index, bar.input.value);
const kept = current ? matches.findIndex(message => message.seq === current) : -1;
// A new search starts at the newest match.
at = kept >= 0 ? kept : matches.length - 1;
show();
};
const go = async (delta: number) => {
if (!bar || !conversation || !matches.length) return;
at = stepMatch(at, delta, matches.length);
show();
const target = matches[at]!;
shown = target.seq;
const mine = ++jumps;
const found = await jumpToMessage(win, sel, { conversation, uuid: target.uuid, seq: target.seq }, { sleep: clock.sleep, timeout: 6000, settle: 400 });
if (mine !== jumps || !bar) return;
if (found) flash(chatScope(), sel, target.uuid, target.seq, clock);
else ctx.api.toast(ctx.text('lost'));
};
const loadOlder = async () => {
if (loading) { loading = false; show(); return; }
loading = true;
ended = false;
show();
let height = 0;
let size = index.length;
let idle = 0;
for (let step = 1; loading && bar; step += 1) {
// X loads nothing in a tab that is not shown.
if (doc.visibilityState === 'hidden') break;
const now = scrollOlder(win, sel);
if (now === null) break;
if (step % 4 === 0) refresh();
if (now > height || index.length > size) { height = Math.max(height, now); size = index.length; idle = 0; }
else if ((idle += 1) > 25) { ended = true; break; }
await clock.sleep(320);
}
loading = false;
refresh();
};
const close = () => {
loading = false;
jumps += 1;
bar?.root.remove();
bar = null;
index = [];
matches = [];
seen.clear();
at = -1;
shown = null;
ended = false;
watch.schedule();
};
const open = () => {
const now = conversationOf(win.location.pathname);
if (!now || !chatScope().querySelector(sel.scroller)) { ctx.api.toast(ctx.text('openFirst')); return; }
if (bar && conversation === now) { bar.input.focus(); bar.input.select?.(); return; }
close();
conversation = now;
const root = doc.createElement('div');
root.className = 'bt-chat-find';
root.setAttribute('role', 'search');
root.setAttribute('aria-label', ctx.text('title'));
paint(ctx.api, root);
// Over the conversation, under X's header.
const header = chatScope().querySelector(sel.header)?.getBoundingClientRect?.();
if (header && header.width > 0) {
root.style.top = `${Math.round(header.bottom + 8)}px`;
root.style.right = `${Math.max(12, Math.round(win.innerWidth - header.right + 12))}px`;
}
const input = doc.createElement('input');
input.type = 'search';
input.placeholder = ctx.text('placeholder');
input.setAttribute('aria-label', ctx.text('placeholder'));
input.spellcheck = false;
const count = doc.createElement('span');
count.className = 'bt-chat-find-count';
count.setAttribute('aria-live', 'polite');
const previous = button(ctx.text('previous'), ICONS.up, null, () => { void go(-1); });
const next = button(ctx.text('next'), ICONS.down, null, () => { void go(1); });
const row = doc.createElement('div');
row.className = 'bt-chat-find-row';
row.append(input, count, previous, next, button(ctx.text('close'), ICONS.close, null, close));
const note = doc.createElement('span');
const older = button(ctx.text('olderHint'), null, ctx.text('older'), () => { void loadOlder(); });
const foot = doc.createElement('div');
foot.className = 'bt-chat-find-note';
foot.append(note, older);
root.append(row, foot);
input.addEventListener('input', () => { matches = []; at = -1; shown = null; refresh(); });
root.addEventListener('keydown', event => {
// The bar's keys are its own: X's chat shortcuts do not see them.
event.stopPropagation();
if (event.key === 'Escape') { event.preventDefault(); close(); }
else if (event.key === 'Enter' && event.target === input) { event.preventDefault(); void go(event.shiftKey ? 1 : matches[at] && matches[at]!.seq !== shown ? 0 : -1); }
});
doc.body.append(root);
bar = { root, input, count, note, older, previous, next };
refresh();
input.focus();
};
const scan = () => {
const now = conversationOf(win.location.pathname);
if (bar && now !== conversation) close();
// While the bar is open and X's list is not exposed, the rows that come on screen join the index.
else if (bar && seen.size) refresh();
headerButton(doc, chatScope().querySelector(sel.header), 'searchLoaded', now ? { name: 'searchLoaded', title: ctx.text('title'), icon: ICONS.search, onClick: open } : null);
};
ctx.css(SHARED_CSS + BAR_CSS);
const watch = ctx.watch(scan);
ctx.onRouteChange(() => watch.schedule());
ctx.command({ id: 'searchLoaded.open', title: ctx.text('title'), keywords: 'find search in conversation chat messages ctrl shift f', shortcut: 'Ctrl+Shift+F', run: open });
// The palette's shortcut rests while you type; in X's own message box Ctrl+Shift+F opens the bar too.
// (Plain Ctrl+F is the app's own find bar: the tab never sees that key.)
ctx.on(doc, 'keydown', event => {
const key = event as KeyboardEvent;
if (key.defaultPrevented || key.repeat || !(key.ctrlKey || key.metaKey) || key.altKey || !key.shiftKey || (key.code !== 'KeyF' && key.key?.toLowerCase() !== 'f')) return;
if (!conversationOf(win.location.pathname) || !(key.target as Element | null)?.closest?.(sel.composer)) return;
key.preventDefault();
key.stopPropagation();
open();
}, true);
ctx.defer(() => {
close();
clock.clear();
for (const place of new Set<ParentNode>([doc, chatScope()])) {
removeHeaderButtons(place, 'searchLoaded');
clearAttribute(place, 'data-bt-chat-flash');
}
});
watch.schedule();
},
};

View file

@ -0,0 +1,121 @@
// Chat+ · the small pieces its features share: the buttons they add to X's chat headers, the flash
// that shows where a jump landed, icons, and the timers of a feature (cleared when it stops).
//
// What a feature adds to X's own elements is an attribute (`data-bt-chat-…`) or a node of its own
// (`.bt-chat-…`), never a change to X's classes or text: X re-renders its rows freely.
import type { ChatSelectors } from './x.ts';
import { findRow } from './x.ts';
export const ICONS = {
star: 'M8 1.8l1.9 3.9 4.3.6-3.1 3 .7 4.3L8 11.5l-3.8 2.1.7-4.3-3.1-3 4.3-.6z',
person: 'M8 7.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5zM3 13.5a5 5 0 0 1 10 0',
search: 'M7 11.5a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.5 10.5l3 3',
pin: 'M6 2.5h4l-.5 4 2 2.5h-7l2-2.5zM8 9v4.5',
edit: 'M3 13l.6-2.6L10.5 3.5l2 2-6.9 6.9zM9 5l2 2',
up: 'M4 10l4-4 4 4',
down: 'M4 6l4 4 4-4',
close: 'M4 4l8 8M12 4l-8 8',
} as const;
const SVG = 'http://www.w3.org/2000/svg';
/** A 16x16 stroke icon (`currentColor`). */
export function icon(doc: Document, path: string): Element {
const svg = doc.createElementNS(SVG, 'svg');
for (const [name, value] of Object.entries({ viewBox: '0 0 16 16', width: '16', height: '16', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.5', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(name, value);
const shape = doc.createElementNS(SVG, 'path');
shape.setAttribute('d', path);
svg.append(shape);
return svg;
}
const ACCENT = 'var(--wb-accent, rgb(29, 155, 240))';
/** The buttons in X's chat headers and the flash: every feature that uses them adds this sheet under its own id. */
export const SHARED_CSS = `
.bt-chat-hbtn { flex: none; display: inline-flex; align-items: center; justify-content: center; gap: 6px; box-sizing: border-box; min-width: 34px; height: 34px; margin-inline-start: 4px; padding: 0 9px; border: 0; border-radius: 999px; background: transparent; color: inherit; font: 600 13px/1 var(--wb-font, system-ui, sans-serif); cursor: pointer; }
.bt-chat-hbtn:hover { background: rgba(127, 127, 127, .18); }
.bt-chat-hbtn:focus-visible { outline: 2px solid ${ACCENT}; outline-offset: 1px; }
.bt-chat-hbtn[aria-pressed="true"] { background: color-mix(in srgb, ${ACCENT} 18%, transparent); color: ${ACCENT}; }
.bt-chat-hbtn span { max-width: 160px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
[data-bt-chat-flash] { animation: bt-chat-flash 2.2s ease-out 1; border-radius: 12px; }
@keyframes bt-chat-flash { 0%, 35% { background: color-mix(in srgb, ${ACCENT} 30%, transparent); box-shadow: 0 0 0 2px ${ACCENT}; } 100% { background: transparent; box-shadow: 0 0 0 2px transparent; } }
@media (prefers-reduced-motion: reduce) { [data-bt-chat-flash] { animation: none; box-shadow: 0 0 0 2px ${ACCENT}; } }
`;
export type HeaderButton = { name: string; title: string; icon: string; pressed?: boolean; label?: string; onClick(): void };
/**
* Keeps one button of a feature at the end of an X chat header (`host`), in step with `wanted`
* (null: no button). Called on every scan: X re-renders its header, so the button is put back when
* it is gone. Returns the button.
*/
export function headerButton(doc: Document, host: Element | null, name: string, wanted: HeaderButton | null): HTMLElement | null {
const existing = host ? Array.from(host.children).find(node => node.getAttribute('data-bt-chat-button') === name) as HTMLElement | undefined : undefined;
if (!host || !wanted) { existing?.remove(); return null; }
const key = JSON.stringify([wanted.title, wanted.icon, !!wanted.pressed, wanted.label ?? '']);
if (existing?.getAttribute('data-bt-chat-key') === key) return existing;
existing?.remove();
const button = doc.createElement('button');
button.type = 'button';
button.className = 'bt-chat-hbtn';
button.setAttribute('data-bt-chat-button', name);
button.setAttribute('data-bt-chat-key', key);
button.setAttribute('aria-label', wanted.title);
button.title = wanted.title;
if (wanted.pressed !== undefined) button.setAttribute('aria-pressed', String(wanted.pressed));
button.append(icon(doc, wanted.icon));
if (wanted.label) { const label = doc.createElement('span'); label.textContent = wanted.label; button.append(label); }
button.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); wanted.onClick(); });
host.append(button);
return button;
}
/** Takes every header button named `name` out of the page. */
export function removeHeaderButtons(doc: ParentNode, name: string): void {
for (const node of Array.from(doc.querySelectorAll(`[data-bt-chat-button="${name}"]`))) node.remove();
}
/** Takes attribute `name` off every element that carries it. */
export function clearAttribute(doc: ParentNode, name: string): void {
for (const node of Array.from(doc.querySelectorAll(`[${name}]`))) node.removeAttribute(name);
}
export type Timers = {
sleep(ms: number): Promise<void>;
after(ms: number, fn: () => void): void;
/** Cancels what is pending (a pending `sleep` never resolves: whatever waited on it ends there). */
clear(): void;
};
export function timers(win: Window): Timers {
const pending = new Set<number>();
const after = (ms: number, fn: () => void) => {
const id = win.setTimeout(() => { pending.delete(id); fn(); }, ms);
pending.add(id);
};
return {
after,
sleep: ms => new Promise(resolve => after(ms, resolve)),
clear() { for (const id of pending) win.clearTimeout(id); pending.clear(); },
};
}
/** Shows where a jump landed: the row of `uuid` lights up once (the sheet is `SHARED_CSS`). */
export function flash(doc: ParentNode, sel: ChatSelectors, uuid: string | null, seq: string | null, clock: Timers): void {
clearAttribute(doc, 'data-bt-chat-flash');
findRow(doc, sel, { uuid, seq })?.setAttribute('data-bt-chat-flash', '');
clock.after(2300, () => clearAttribute(doc, 'data-bt-chat-flash'));
}
/**
* Gives a floating node of a feature (a bar, a small list) the active theme's colors as
* `--bt-chat-bg/text/muted/border/accent`; its sheet carries fallbacks for a page without them.
*/
export function paint(api: { theme: { current(): { colors: { surface: string; text: string; muted: string; border: string; accent: string } } } }, node: HTMLElement): void {
try {
const colors = api.theme.current().colors;
for (const [name, value] of Object.entries({ bg: colors.surface, text: colors.text, muted: colors.muted, border: colors.border, accent: colors.accent })) node.style.setProperty(`--bt-chat-${name}`, value);
} catch { /* the sheet's own colors */ }
}

View file

@ -0,0 +1,550 @@
// Chat+ · X's chat as the features see it: its markup, what X's own page keeps about a rendered
// message, and X's own ways to move to a message and to start a reply.
//
// X's chat (/i/chat, also reached from /messages) has stable test ids but a virtualized list: only
// the rows near the viewport are in the DOM, and they come and go while you scroll. So nothing here
// keeps an element: a message is found again by its id every time. What the DOM does not show (the
// sender's id, the sequence number X positions by) is read from the props X's own page gave the row.
// The names of those props change between X builds, so they are found by shape: the sequence is the
// value with a bigint `num`, the sender the value with a `userId`.
//
// Since 2026-10-01 X may render the whole chat inside the open shadow root of its chat embed
// (`[data-testid="xchatEmbedRoute"]`, X's XChatEmbed); accounts without it keep the chat in the page.
// `chatRoot` is where to look: that shadow root when there is one, else the document. The DOM hub
// observes that root too (the X site adapter names the host), so the features' scans run on its
// changes and their sheets reach it.
//
// Nothing here makes a request, writes a message or presses Send. The only clicks are navigation
// (X's router, X's own conversation link) and opening X's own Reply for one message.
export const CHAT = {
embed: '[data-testid="xchatEmbedRoute"]',
container: '[data-testid="dm-container"]',
inbox: '[data-testid="dm-inbox-panel"]',
inboxHeader: '[data-testid="dm-inbox-header"]',
inboxScroller: '[data-testid="dm-conversation-scroller"]',
inboxRow: '[data-testid^="dm-conversation-item-"]',
header: '[data-testid="dm-conversation-header"]',
title: '[data-testid="dm-conversation-username"]',
scroller: '[data-testid="dm-message-scroller"]',
row: '[data-dm-message-row]',
text: '[data-testid^="message-text-"]',
composer: '[data-testid="dm-composer-container"]',
textarea: '[data-testid="dm-composer-textarea"]',
} as const;
export type ChatSelectors = { readonly [K in keyof typeof CHAT]: string };
/** Probes of a feature that works in an open conversation (judged only while X's composer is there). */
export const CONVERSATION_PROBES = {
scroller: { selector: CHAT.scroller, when: CHAT.textarea },
header: { selector: CHAT.header, when: CHAT.textarea },
row: { selector: CHAT.row, when: CHAT.text },
} as const;
/**
* The chat itself, in either shape (in the page or in the embed's shadow root; probes look into both),
* judged on every visit of a feature that runs only on chat pages: when X serves neither shape, those
* features pause themselves with the registry's note instead of silently finding nothing.
*/
export const CHAT_PAGE_PROBE = {
container: { selector: CHAT.container },
} as const;
/** Probes of a feature that works in the inbox. */
export const INBOX_PROBES = {
inboxScroller: { selector: CHAT.inboxScroller, when: CHAT.inbox },
inboxRow: { selector: CHAT.inboxRow, when: `${CHAT.inboxScroller} a[href^="/i/chat/"]` },
} as const;
/** X's selectors, with the ones a feature names as probes read through `ctx.selector` (a hotfix may replace them). */
export function chatSelectors(ctx: { selector(name: string): string }, probes: Readonly<Record<string, unknown>>): ChatSelectors {
const out: Record<string, string> = { ...CHAT };
for (const name of Object.keys(probes)) if (name in out) out[name] = ctx.selector(name);
return out as ChatSelectors;
}
// ---- Conversations -------------------------------------------------------------------------------
const CONVERSATION = /^(?:g\d{5,25}|\d{1,25}-\d{1,25})$/;
/** A conversation id as X's address has it (`<id>-<id>`, or `g<digits>` for a group); null for anything else. */
export function conversationKey(id: string | null | undefined): string | null {
const key = (id ?? '').replace(':', '-');
return CONVERSATION.test(key) ? key : null;
}
export const isChatPath = (pathname: string) => /^\/(?:i\/chat|messages)(?:\/|$)/i.test(pathname);
export const isGroup = (conversation: string) => conversation.startsWith('g');
/** Where X's chat is rendered: the open shadow root of its embed, else the page itself. */
export type ChatRoot = Document | ShadowRoot;
export function chatRoot(doc: Document): ChatRoot {
const host = doc.querySelector(CHAT.embed) as (Element & { shadowRoot?: ShadowRoot | null }) | null;
return host?.shadowRoot ?? doc;
}
/** The conversation a chat address shows; null on the inbox and on X's other chat pages. */
export function conversationOf(pathname: string): string | null {
const match = /^\/(?:i\/chat|messages)\/([^/]+)\/?$/i.exec(pathname);
if (!match) return null;
try { return conversationKey(decodeURIComponent(match[1]!)); } catch { return null; }
}
/** The open conversation's name as X's header shows it. */
export function conversationTitle(doc: ParentNode, sel: ChatSelectors): string {
return (doc.querySelector(`${sel.header} ${sel.title}`)?.textContent ?? doc.querySelector(sel.title)?.textContent ?? '').trim();
}
/** The conversation an inbox row stands for. */
export function inboxRowConversation(row: Element): string | null {
return conversationKey((row.getAttribute('data-testid') ?? '').replace(/^dm-conversation-item-/, ''));
}
// ---- What X's page keeps about a message ---------------------------------------------------------
type Bag = Record<string, unknown>;
type Fiber = { return?: Fiber | null; memoizedProps?: Bag | null };
const bag = (value: unknown): Bag | null => (value !== null && typeof value === 'object' ? value as Bag : null);
const read = (from: Bag, key: string): unknown => { try { return from[key]; } catch { return undefined; } };
const entries = (from: Bag): [string, unknown][] => { try { return Object.entries(from); } catch { return []; } };
const text = (value: unknown): string | null => (typeof value === 'string' && value.trim() ? value.trim() : null);
const idText = (value: unknown): string | null =>
(typeof value === 'string' && value ? value : typeof value === 'number' || typeof value === 'bigint' ? String(value) : null);
function fiberOf(element: Element): Fiber | null {
for (const key of Object.keys(element)) if (key.startsWith('__reactFiber$')) return bag((element as unknown as Bag)[key]) as Fiber | null;
return null;
}
/** Whether `value` is reachable from `root` within `depth` steps: the path of keys, or null. */
function pathTo(root: unknown, depth: number, test: (value: unknown) => boolean): string[] | null {
const from = bag(root);
if (!from || Array.isArray(from)) return null;
for (const [key, value] of entries(from)) if (test(value)) return [key];
if (depth <= 1) return null;
for (const [key, value] of entries(from)) {
const rest = pathTo(value, depth - 1, test);
if (rest) return [key, ...rest];
}
return null;
}
const follow = (root: unknown, path: readonly string[]): unknown => path.reduce<unknown>((at, key) => { const from = bag(at); return from ? read(from, key) : undefined; }, root);
/** X's record of the message a rendered row shows (the `messageItem` its page gave the row). */
export function messageItemOf(row: Element): Bag | null {
const uuid = row.getAttribute('data-dm-message-row') ?? '';
let first: Bag | null = null;
let fiber = fiberOf(row);
for (let depth = 0; fiber && depth < 24; depth += 1, fiber = fiber.return ?? null) {
const item = bag(fiber.memoizedProps ? read(fiber.memoizedProps, 'messageItem') : null);
if (!item) continue;
// The record that names this row's message wins; a build that keeps the id as its own type has none.
if (uuid && pathTo(item, 2, value => value === uuid)) return item;
first ??= item;
}
return first;
}
export type Sequence = { /** X's own sequence object. */ object: unknown; /** Its number, as text. */ text: string };
function asSequence(value: unknown): Sequence | null {
const from = bag(value);
if (!from) return null;
const num = read(from, 'num');
return typeof num === 'bigint' && num > 0n ? { object: value, text: num.toString() } : null;
}
/** A message's sequence number: the one value of its record that carries a bigint `num`. */
export function sequenceOf(item: Bag): Sequence | null {
for (const [, value] of entries(item)) {
const sequence = asSequence(value);
if (sequence) return sequence;
}
return null;
}
/** X's sequence object for `seq`, made by the class of one X already made (`fromString`). */
export function sequenceObject(sample: unknown, seq: string): unknown {
const made = bag(sample)?.constructor as unknown as Bag | undefined;
for (const holder of [made, bag(made ? read(made, 'Companion') : null)]) {
const fromString = holder ? read(holder, 'fromString') : null;
if (typeof fromString !== 'function') continue;
try {
const object = (fromString as (value: string) => unknown).call(holder, seq);
if (object != null) return object;
} catch { /* not this one */ }
}
return null;
}
const SNOWFLAKE_EPOCH = 1288834974657n;
/** When a message was sent, from its sequence number (epoch ms); null when it is not one. */
export function sequenceTime(seq: string | null | undefined): number | null {
if (!seq || !/^\d{10,20}$/.test(seq)) return null;
const ms = Number((BigInt(seq) >> 22n) + SNOWFLAKE_EPOCH);
return Number.isSafeInteger(ms) ? ms : null;
}
const NAME_KEYS = ['displayName', 'name', 'fullName'];
const HANDLE_KEYS = ['screenName', 'screen_name', 'handle', 'username', 'userName'];
const firstText = (from: Bag | null, keys: readonly string[]) => { for (const key of keys) { const found = from ? text(read(from, key)) : null; if (found) return found; } return null; };
export type Sender = { id: string; name: string | null; handle: string | null };
/** Who sent a message: the value of its record that carries a `userId`. */
export function senderOf(item: Bag): Sender | null {
for (const [, value] of entries(item)) {
const from = bag(value);
const id = from && !Array.isArray(from) ? idText(read(from, 'userId')) : null;
if (!from || !id) continue;
const user = bag(read(from, 'user'));
return { id, name: firstText(user, NAME_KEYS), handle: firstText(user, HANDLE_KEYS)?.replace(/^@/, '') ?? null };
}
return null;
}
export type ReplyRef = { uuid: string | null; seq: string | null; senderId: string | null; senderName: string | null; text: string };
/** The message a reply answers (X's reply preview: the value with a `previewText`), when it is one. */
export function replyOf(item: Bag): ReplyRef | null {
const path = pathTo(item, 3, value => { const from = bag(value); return !!from && typeof read(from, 'previewText') === 'string'; });
const from = path ? bag(follow(item, path)) : null;
if (!from) return null;
const sequence = read(from, 'sequenceNumber');
return {
uuid: text(read(from, 'id')),
seq: asSequence(sequence)?.text ?? (typeof sequence === 'string' && /^\d{10,20}$/.test(sequence) ? sequence : null),
senderId: idText(read(from, 'senderId')),
senderName: text(read(from, 'senderDisplayName')),
text: String(read(from, 'previewText')),
};
}
// ---- A rendered row ------------------------------------------------------------------------------
export type MediaRef = { type: 'image' | 'video'; url: string | null };
export type MessageInfo = {
uuid: string;
/** The sequence number X positions by; null when X's record of the row could not be read. */
seq: string | null;
senderId: string | null;
/** The name X shows for the sender (its own word for "You" on your messages). */
senderName: string;
senderHandle: string | null;
text: string;
/** Epoch ms from the sequence number. */
time: number | null;
/** The clock X shows on the row. */
timeLabel: string;
media: MediaRef[];
reply: ReplyRef | null;
};
/** The text of a rendered message, as X shows it. */
export function rowText(row: Element, sel: ChatSelectors): string {
const block = row.querySelector(sel.text);
// The text span comes first; X's clock and send status follow it in the same block.
return (block?.querySelector('[dir="auto"]')?.textContent ?? '').trim();
}
const httpsUrl = (value: string | null) => (value && /^https:\/\//i.test(value) ? value : null);
function mediaOf(row: Element, sel: ChatSelectors): MediaRef[] {
const out: MediaRef[] = [];
for (const node of Array.from(row.querySelectorAll('video, img'))) {
const video = node.nodeName.toUpperCase() === 'VIDEO';
// Not the sender's picture (X's `aria-hidden` block) and not an emoji inside the text.
if (!video && (node.closest('[aria-hidden]') || node.closest(sel.text))) continue;
const url = httpsUrl(video ? node.getAttribute('poster') ?? node.getAttribute('src') : node.getAttribute('src'));
if (!out.some(item => item.type === (video ? 'video' : 'image') && item.url === url)) out.push({ type: video ? 'video' : 'image', url });
if (out.length >= 8) break;
}
return out;
}
/** Everything a rendered row says about its message: what the DOM shows plus X's own record of it. */
export function readRow(row: Element, sel: ChatSelectors): MessageInfo | null {
const uuid = row.getAttribute('data-dm-message-row');
if (!uuid) return null;
const item = messageItemOf(row);
const sender = item ? senderOf(item) : null;
const seq = item ? sequenceOf(item)?.text ?? null : null;
const reply = item ? replyOf(item) : null;
return {
uuid,
seq,
senderId: sender?.id ?? null,
senderName: (row.querySelector('[id$="-sender"]')?.textContent ?? '').trim() || sender?.name || '',
senderHandle: sender?.handle ?? null,
text: rowText(row, sel),
time: sequenceTime(seq),
timeLabel: (row.querySelector('[id$="-time"]')?.textContent ?? '').trim(),
media: mediaOf(row, sel),
// A reply X's record did not describe is still marked as one (X's quote block carries this icon).
reply: reply ?? (row.querySelector('svg[data-icon="icon-reply-alt"]') ? { uuid: null, seq: null, senderId: null, senderName: null, text: '' } : null),
};
}
/** The message rows in the DOM right now (the ones near the viewport). */
export const renderedRows = (doc: ParentNode, sel: ChatSelectors): Element[] => Array.from(doc.querySelectorAll(`${sel.scroller} ${sel.row}`));
export type RowTarget = { uuid: string | null; seq: string | null };
/** The rendered row of a message, by its id (or by its sequence number when the id is not known). */
export function findRow(doc: ParentNode, sel: ChatSelectors, target: RowTarget): Element | null {
for (const row of renderedRows(doc, sel)) {
if (target.uuid) { if (row.getAttribute('data-dm-message-row') === target.uuid) return row; continue; }
const item = messageItemOf(row);
if (target.seq && item && sequenceOf(item)?.text === target.seq) return row;
}
return null;
}
// ---- The loaded history --------------------------------------------------------------------------
export type LoadedMessage = { uuid: string | null; seq: string; senderId: string | null; senderName: string | null; text: string };
const itemIn = (element: unknown): Bag | null => {
const from = bag(element);
if (!from || Array.isArray(from)) return null;
if (sequenceOf(from)) return from;
for (const [, value] of entries(from)) { const inner = bag(value); if (inner && !Array.isArray(inner) && sequenceOf(inner)) return inner; }
return null;
};
/** The list X's page holds for the open conversation: the array (in some prop above a row) that contains that row's record. */
function loadedItems(row: Element, item: Bag): Bag[] | null {
let fiber = fiberOf(row);
for (let depth = 0; fiber && depth < 60; depth += 1, fiber = fiber.return ?? null) {
for (const [, value] of entries(fiber.memoizedProps ?? {})) {
if (!Array.isArray(value) || value.length < 1 || value.length > 200000) continue;
if (!value.some(element => element === item || itemIn(element) === item)) continue;
return value.map(itemIn).filter((found): found is Bag => !!found);
}
}
return null;
}
/**
* The messages of the open conversation that X has loaded: the whole loaded list when X's page
* exposes it (`complete`), otherwise only the rows in the DOM. Read on request, kept by nobody.
*/
export function loadedMessages(doc: ParentNode, sel: ChatSelectors): { messages: LoadedMessage[]; complete: boolean } {
const rows = renderedRows(doc, sel).map(row => ({ row, info: readRow(row, sel), item: messageItemOf(row) }));
const rendered = rows.flatMap(({ info }) => (info?.seq ? [{ uuid: info.uuid, seq: info.seq, senderId: info.senderId, senderName: info.senderName || null, text: info.text }] : []));
const known = rows.find(entry => entry.item);
const items = known ? loadedItems(known.row, known.item!) : null;
// Where a record keeps its text and its id is learned from rows whose text and id the DOM shows.
let textPath: string[] | null = null;
let uuidPath: string[] | null = null;
for (const { info, item } of rows) {
if (!item || !info) continue;
textPath ??= info.text ? pathTo(item, 3, value => typeof value === 'string' && value.trim() === info.text) : null;
uuidPath ??= pathTo(item, 2, value => value === info.uuid);
}
if (!items || items.length < rendered.length || !textPath) return { messages: bySequence(rendered), complete: false };
const names = new Map(rendered.filter(message => message.senderId && message.senderName).map(message => [message.senderId!, message.senderName!]));
const messages: LoadedMessage[] = [];
for (const item of items) {
const seq = sequenceOf(item)?.text;
if (!seq) continue;
const sender = senderOf(item);
const body = follow(item, textPath);
const uuid = uuidPath ? follow(item, uuidPath) : null;
messages.push({
uuid: typeof uuid === 'string' ? uuid : null, seq, senderId: sender?.id ?? null,
senderName: (sender && names.get(sender.id)) ?? sender?.name ?? null, text: typeof body === 'string' ? body.trim() : '',
});
}
return { messages: bySequence(messages), complete: true };
}
const bySequence = (messages: LoadedMessage[]) => {
const seen = new Set<string>();
return messages
.filter(message => (seen.has(message.seq) ? false : (seen.add(message.seq), true)))
.sort((a, b) => (BigInt(a.seq) < BigInt(b.seq) ? -1 : BigInt(a.seq) > BigInt(b.seq) ? 1 : 0));
};
// ---- Moving to a message (X's own mechanisms) ----------------------------------------------------
type Win = Window & typeof globalThis;
/**
* Opens a conversation through X's router, positioned on `seq` when given: the state X's own
* "open conversation at message" sets. A navigation, nothing else.
*/
export function openConversation(win: Win, conversation: string, seq?: string | null): void {
const state = { key: Math.random().toString(36).slice(2, 8), state: seq ? { scrollToMessage: seq } : undefined };
win.history.pushState(state, '', `/i/chat/${conversation}`);
win.dispatchEvent(new win.PopStateEvent('popstate', { state }));
}
/**
* Asks the open conversation to scroll to `seq`: the event X's own message search fires. False when
* no row is rendered yet to take X's sequence class from. A sequence X does not know does nothing.
*/
export function fireScrollToMessage(win: Win, sel: ChatSelectors, seq: string): boolean {
for (const row of renderedRows(chatRoot(win.document), sel)) {
const item = messageItemOf(row);
const sample = item ? sequenceOf(item) : null;
const sequenceNumber = sample ? sequenceObject(sample.object, seq) : null;
if (sequenceNumber == null) continue;
win.dispatchEvent(new win.CustomEvent('scrollToMessage', { detail: { timestamp: Date.now(), sequenceNumber, source: 'Inbox' } }));
return true;
}
return false;
}
export type JumpTarget = { conversation: string; uuid: string | null; seq: string };
export type Pace = {
/** Resolves after `ms` (the feature's own timer, cleared when it stops). */
sleep(ms: number): Promise<void>;
/** How long to look for the row (default 10 s), how often (250 ms), and how long X's list needs to settle after landing (1.2 s). */
timeout?: number;
step?: number;
settle?: number;
};
/**
* Goes to a message with X's own mechanisms: the router state when its conversation is not the
* open one, the scroll event when it is (and as the second try when the router did not position).
* Then waits for the row. False when it did not appear: deleted, or never loaded by X.
*/
export async function jumpToMessage(win: Win, sel: ChatSelectors, target: JumpTarget, pace: Pace): Promise<boolean> {
const root = () => chatRoot(win.document);
const step = pace.step ?? 250;
const inTarget = () => conversationOf(win.location.pathname) === target.conversation;
const here = inTarget() && !!root().querySelector(sel.scroller);
if (!here) openConversation(win, target.conversation, target.seq);
let fireAt = here ? 0 : 3000;
let fires = 0;
const fire = (waited: number) => {
if (waited < fireAt || fires >= 3 || !fireScrollToMessage(win, sel, target.seq)) return;
fires += 1;
fireAt = waited + 3500;
};
let found = false;
for (let waited = 0; waited <= (pace.timeout ?? 10000) && !found; waited += step) {
// The user went somewhere else meanwhile: leave them there.
if (!inTarget()) return false;
fire(waited);
const row = findRow(root(), sel, target);
if (row) {
// In the DOM but X could not be asked to position it (its record of the rows is unreadable).
if (here && !fires) row.scrollIntoView?.({ block: 'center' });
found = true;
} else await pace.sleep(step);
}
if (!found) return false;
// X's list moves for a moment after landing; the row is looked up again afterwards, never kept.
await pace.sleep(pace.settle ?? 1200);
if (findRow(root(), sel, target)) return true;
fireScrollToMessage(win, sel, target.seq);
for (let waited = 0; waited <= 2500; waited += step) {
if (findRow(root(), sel, target)) return true;
await pace.sleep(step);
}
return false;
}
// ---- X's own Reply -------------------------------------------------------------------------------
export type ReplyResult = 'ok' | 'no-row' | 'no-button' | 'no-menu' | 'no-item' | 'unconfirmed';
const mouse = (win: Win, target: Element, types: readonly string[]) => {
const rect = target.getBoundingClientRect?.();
const at = { clientX: rect ? rect.left + rect.width / 2 : 0, clientY: rect ? rect.top + rect.height / 2 : 0 };
for (const type of types) {
const Make = type.startsWith('pointer') && win.PointerEvent ? win.PointerEvent : win.MouseEvent;
target.dispatchEvent(new Make(type, { bubbles: !type.endsWith('enter'), cancelable: true, view: win, button: 0, ...at }));
}
};
async function waitFor<T>(pace: Pace, ms: number, look: () => T | null | undefined | false): Promise<T | null> {
const step = Math.min(pace.step ?? 250, 150);
for (let waited = 0; waited <= ms; waited += step) {
const found = look();
if (found) return found;
await pace.sleep(step);
}
return null;
}
/** X's open message menu: the newest `role=menu` that has items (in the chat's root or in the page). */
function openMenu(roots: ParentNode[]): Element | null {
const menus = roots.flatMap(root => Array.from(root.querySelectorAll('[role="menu"]'))).filter(menu => menu.querySelector('[role="menuitem"]'));
return menus[menus.length - 1] ?? null;
}
/**
* The Reply item of X's message menu, without reading its label: the item with X's reply icon;
* else the first item (Reply leads both menus seen), but only in a menu of at least three items.
*/
export function replyItem(menu: Element): Element | null {
const items = Array.from(menu.querySelectorAll('[role="menuitem"]'));
return items.find(item => item.querySelector('svg[data-icon*="reply"]')) ?? (items.length >= 3 ? items[0]! : null);
}
// X's reply preview adds a "cancel" button without a test id above the text box.
const composerButtons = (doc: ParentNode, sel: ChatSelectors) => doc.querySelectorAll(`${sel.composer} button:not([data-testid])`).length;
/**
* Opens X's own Reply for a rendered message: the row's "More" button, then the menu's Reply item.
* X's composer then shows its reply preview and the text box gets the focus. Nothing is typed and
* nothing is sent: what is written and whether it is sent stays with the user.
*/
export async function openReply(win: Win, sel: ChatSelectors, uuid: string, pace: Pace): Promise<ReplyResult> {
const doc = () => chatRoot(win.document);
const menuRoots = () => [...new Set<ParentNode>([doc(), win.document])];
const row = () => findRow(doc(), sel, { uuid, seq: null });
const more = () => doc().querySelector(`[data-testid="message-overflow-button-${uuid}"]`);
const first = row();
if (!first) return 'no-row';
// X shows a row's buttons while the pointer is over it, or while it has the focus.
if (!more()) mouse(win, first.querySelector('[role="article"]') ?? first, ['pointerover', 'pointerenter', 'mouseover', 'mouseenter', 'pointermove', 'mousemove']);
let button = await waitFor(pace, 900, more);
if (!button) {
(row()?.querySelector('[data-dm-message-focus-target]') as HTMLElement | null)?.focus?.();
button = await waitFor(pace, 900, more);
}
if (!button) return 'no-button';
const before = composerButtons(doc(), sel);
const known = openMenu(menuRoots());
const fresh = () => { const menu = openMenu(menuRoots()); return menu && menu !== known ? menu : null; };
(button as HTMLElement).click();
let menu = await waitFor(pace, 900, fresh);
if (!menu && (button = more())) {
// A trigger that opens on press rather than on click.
mouse(win, button, ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']);
menu = await waitFor(pace, 900, fresh);
}
if (!menu) return 'no-menu';
const item = replyItem(menu);
if (!item) {
menu.dispatchEvent(new win.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));
return 'no-item';
}
(item as HTMLElement).click();
const shown = await waitFor(pace, 1500, () => composerButtons(doc(), sel) > before);
(doc().querySelector(sel.textarea) as HTMLElement | null)?.focus?.();
return shown ? 'ok' : 'unconfirmed';
}
// ---- Older history -------------------------------------------------------------------------------
/**
* One step of scrolling X's message list up, the way a wheel does, so X loads older history by
* itself. Returns the list's height (it grows when X added messages); null when there is no list.
*/
export function scrollOlder(win: Win, sel: ChatSelectors): number | null {
const scroller = chatRoot(win.document).querySelector(sel.scroller) as HTMLElement | null;
if (!scroller) return null;
const by = Math.max(600, (scroller.clientHeight || 0) * 3);
scroller.dispatchEvent(new win.WheelEvent('wheel', { deltaY: -by, bubbles: true, cancelable: true, view: win }));
if (typeof scroller.scrollBy === 'function') scroller.scrollBy({ top: -by, behavior: 'auto' });
else scroller.scrollTop = Math.max(0, scroller.scrollTop - by);
return scroller.scrollHeight || 0;
}

View file

@ -0,0 +1,65 @@
// Compose+ · Alt-text Reminder (was the Alt-text Reminder plugin, 1.2.0). A notice while images in
// the composer have no description (alt text), and one more toast when Post is pressed. It only
// reads the composer: the click on Post goes on to X untouched, nothing is blocked or delayed.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
/** X gives attached images a generic alt until a description is added (best-effort, may need updates when X changes). */
export const GENERIC_ALT = /^(|image|media|photo|picture|bild|imagen|immagine|imagem|görsel|resim|画像|이미지|图片|圖片)$/i;
const ATTACHED = '[data-testid="attachments"] img';
const POST_BUTTON = '[data-testid="tweetButton"], [data-testid="tweetButtonInline"]';
const NOTE = 'bt-compose-alt-note';
/** How many attached images under `root` still have X's generic alt. Pure over the DOM. */
export function missingAlt(root: ParentNode): number {
let count = 0;
for (const img of root.querySelectorAll(ATTACHED)) {
if (GENERIC_ALT.test((img.getAttribute('alt') || '').trim())) count += 1;
}
return count;
}
export const altTextReminder: FeatureModule<PluginApi> = {
id: 'compose.altTextReminder',
// The plugin's words, kept: nothing is retranslated.
words: 'alt-text-reminder',
start(ctx) {
const doc = ctx.win.document;
ctx.css(`
.${NOTE} { position: fixed; left: 50%; top: 16px; transform: translateX(-50%); z-index: 2147483645; pointer-events: none;
width: max-content; max-width: calc(100vw - 32px); box-sizing: border-box; text-align: center;
padding: 8px 14px; border-radius: 999px; background: rgb(255, 212, 0); color: #0f1419; font: 600 13px/1.3 system-ui, sans-serif;
box-shadow: 0 4px 16px rgba(0,0,0,.25); }
`);
let note: HTMLElement | null = null;
const update = () => {
const missing = missingAlt(doc);
if (!missing) {
note?.remove();
return;
}
if (!note) {
note = doc.createElement('div');
note.className = NOTE;
note.setAttribute('role', 'status');
}
const text = ctx.text('missing', { count: missing });
// Only write on change: this node lives inside the observed tree.
if (note.textContent !== text) note.textContent = text;
if (!note.isConnected) doc.body.appendChild(note);
};
ctx.watch(update, { attributes: ['alt'] });
ctx.defer(() => { note?.remove(); note = null; });
// Capture phase, passive: only reads the composer and shows a toast; the click continues to X untouched.
ctx.on(doc, 'click', event => {
const target = event.target as Element | null;
const button = target?.closest?.(POST_BUTTON);
if (!button) return;
const missing = missingAlt(button.closest('[role="dialog"]') ?? doc);
if (missing) ctx.api.toast(ctx.text('headsUp', { count: missing }), 3500);
}, { capture: true, passive: true });
update();
},
};

View file

@ -0,0 +1,135 @@
// Compose+ · what its composer features share: finding X's composers, the one line above the
// toolbar they put their notes in, reading the text, and inserting text at the caret.
//
// Insertion is the app's one path (focus + `execCommand('insertText')`, as the Emoji Picker and
// the drafts popover do): X's editor takes it as typed text. Nothing here presses Post or changes
// what X sends on its own.
import { TOOLBAR_SELECTOR, editorForToolbar } from '../../inject/drafts.ts';
import { COMPOSER_SELECTOR } from '../../observer/composer.ts';
export { COMPOSER_SELECTOR, TOOLBAR_SELECTOR };
/** The line above a composer's toolbar ("Posting as", the length meter). */
export const BAR_ATTR = 'data-bt-compose-bar';
const BAR_STYLE = 'display:flex;flex-direction:row;flex-wrap:wrap;align-items:center;gap:4px 10px;min-height:22px;padding:2px 0 6px;font:13px/1.3 system-ui,sans-serif;';
export type Composer = { toolbar: Element; editor: HTMLElement };
/** Every composer on the page that has X's toolbar, with its editor. */
export function composers(doc: Document): Composer[] {
const out: Composer[] = [];
for (const toolbar of doc.querySelectorAll(TOOLBAR_SELECTOR)) {
const editor = editorForToolbar(toolbar);
if (editor) out.push({ toolbar, editor });
}
return out;
}
/** The line above `toolbar`, when a feature has made it. */
export function barOf(toolbar: Element): HTMLElement | null {
const before = toolbar.previousElementSibling;
return before?.hasAttribute(BAR_ATTR) ? before as HTMLElement : null;
}
/** The part `attr` of the line above `toolbar` (a feature's own node), when it is there. */
export const barPart = (toolbar: Element, attr: string): HTMLElement | null => barOf(toolbar)?.querySelector<HTMLElement>(`[${attr}]`) ?? null;
/** The line above `toolbar`, made when it is not there. Only call it with something to put in. */
export function ensureBar(doc: Document, toolbar: Element): HTMLElement {
const existing = barOf(toolbar);
if (existing) return existing;
const bar = doc.createElement('div');
bar.setAttribute(BAR_ATTR, '');
bar.style.cssText = BAR_STYLE;
toolbar.before(bar);
return bar;
}
/** Removes the lines that are empty or whose toolbar X took away. */
export function sweepBars(doc: Document): void {
for (const bar of doc.querySelectorAll(`[${BAR_ATTR}]`)) {
if (!bar.firstElementChild || !bar.nextElementSibling?.matches(TOOLBAR_SELECTOR)) bar.remove();
}
}
/** Removes every node a feature marked with `attr`, and the lines that became empty. */
export function clearParts(doc: Document, attr: string): void {
for (const node of doc.querySelectorAll(`[${attr}]`)) node.remove();
sweepBars(doc);
}
/** The text of a composer as X will count it: one line per block of X's editor. */
export function composerText(editor: HTMLElement): string {
if (!editor.textContent) return '';
const blocks = editor.querySelectorAll('[data-block="true"]');
if (blocks.length) return Array.from(blocks, block => block.textContent ?? '').join('\n');
return typeof editor.innerText === 'string' ? editor.innerText.replace(/\n$/, '') : editor.textContent;
}
export type Target = { editor: HTMLElement; range: Range | null };
/**
* The composer an insert goes to: the one the selection is in (with that selection), else the
* focused one, else the only one on the page. Null when that is not one composer.
*/
export function targetComposer(win: Window): Target | null {
const doc = win.document;
const selection = win.getSelection?.() ?? null;
const anchor = selection && selection.rangeCount ? selection.anchorNode : null;
const holder = anchor ? (anchor.nodeType === 1 ? anchor as Element : anchor.parentElement) : null;
const selected = holder?.closest<HTMLElement>(COMPOSER_SELECTOR);
if (selected) return { editor: selected, range: selection!.getRangeAt(0).cloneRange() };
const focused = doc.activeElement?.closest?.<HTMLElement>(COMPOSER_SELECTOR);
if (focused) return { editor: focused, range: null };
const all = doc.querySelectorAll<HTMLElement>(COMPOSER_SELECTOR);
return all.length === 1 ? { editor: all[0]!, range: null } : null;
}
/**
* Puts `text` into the composer at `range` (or at the end of its text) as typed text. False when
* the composer is gone.
*/
export function insertText(win: Window & typeof globalThis, target: Target, text: string): boolean {
const doc = win.document;
const { editor } = target;
const selection = win.getSelection?.();
if (!editor.isConnected || !selection) return false;
editor.focus();
let range = target.range;
if (!range || !editor.contains(range.commonAncestorContainer)) {
range = doc.createRange();
range.selectNodeContents(editor);
range.collapse(false);
}
selection.removeAllRanges();
selection.addRange(range);
if (!doc.execCommand('insertText', false, text)) {
const data = new win.DataTransfer();
data.setData('text/plain', text);
editor.dispatchEvent(new win.ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
}
return true;
}
export type CaretText = { editor: HTMLElement; node: Text; offset: number; before: string };
/** What was typed before the caret in the text node it is in; null unless the caret is a plain caret in a composer. */
export function caretText(win: Window): CaretText | null {
const selection = win.getSelection?.();
if (!selection || !selection.rangeCount || !selection.isCollapsed) return null;
const node = selection.anchorNode;
if (!node || node.nodeType !== 3) return null;
const editor = node.parentElement?.closest<HTMLElement>(COMPOSER_SELECTOR);
if (!editor) return null;
return { editor, node: node as Text, offset: selection.anchorOffset, before: (node.nodeValue ?? '').slice(0, selection.anchorOffset) };
}
/** Replaces the `back` characters before the caret with `text`, as typed text. */
export function replaceBack(win: Window & typeof globalThis, caret: CaretText, back: number, text: string): boolean {
if (!caret.node.isConnected || back > caret.offset) return false;
const range = win.document.createRange();
range.setStart(caret.node, caret.offset - back);
range.setEnd(caret.node, caret.offset);
return insertText(win, { editor: caret.editor, range }, text);
}

View file

@ -0,0 +1,29 @@
// Compose+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { app, modules, plugin, ported } from '../rows.ts';
/** Every page a composer can be on: the inline ones of timelines and post pages, and X's composer page. */
const COMPOSER_PAGES = ['timeline', 'composer'] as const;
/** The row words of a feature that is new with Compose+ (./messages.en.json). */
const words = (name: string) => ({ label: `plugin.compose-plus.feature.${name}.label`, description: `plugin.compose-plus.feature.${name}.description` });
export const FEATURES: readonly FeatureSpec[] = [
// Asks native code for the drafts popover (`drafts_picker_open`): a part of the X runtime.
...app('compose', '', [{ id: 'composerDrafts', default: true }]),
// Ported last (it is being redesigned): until then it runs from its plugin file.
plugin('compose', '', 'compose.emojiPicker', 'emoji-picker', ['storage', 'ui']),
...modules('compose', '', [
ported('compose.altTextReminder', 'alt-text-reminder', { surfaces: COMPOSER_PAGES, keywords: 'Alt-text Reminder image description accessibility', permissions: ['ui'] }),
ported('compose.replyGuard', 'reply-guard', { settings: true, keywords: 'Reply Guard old post stranger', permissions: ['storage', 'ui', 'account', 'users', 'commands'] }),
// New with Compose+. Off until turned on (or Power User): each adds something to X's composer.
{ id: 'compose.postingAs', surfaces: COMPOSER_PAGES, ...words('postingAs'), keywords: 'account handle multi-account wrong account', permissions: ['account'] },
{ id: 'compose.lengthMeter', surfaces: COMPOSER_PAGES, settings: true, ...words('lengthMeter'), keywords: 'character count limit 280 thread', permissions: ['storage'] },
{ id: 'compose.snippets', surfaces: COMPOSER_PAGES, settings: true, ...words('snippets'), keywords: 'saved text template signature shortcut', permissions: ['storage', 'ui', 'commands'] },
]),
];
/** Flags Power User turns on besides the defaults (this area's advanced features). Reply Guard holds a click back: never by a preset. */
export const POWER: readonly string[] = ['compose.altTextReminder', 'compose.postingAs', 'compose.lengthMeter', 'compose.snippets'];

View file

@ -0,0 +1,23 @@
// Compose+: its feature modules (docs/AREA-PLUGINS.md; Navigation+ in ../navigation is the reference).
// One module per `backing: 'module'` row of ./features.ts; the registry starts each only while its
// flag is on, the area is on and the page is on one of its surfaces.
//
// Not modules: the Drafts button (`composerDrafts`) asks native code for the drafts popover, so it
// stays a part of the X runtime (src/inject/drafts.ts, `app`-backed); the Emoji Picker still runs
// from its plugin file until it is ported (last: it is being redesigned).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { altTextReminder } from './altTextReminder.ts';
import { lengthMeter } from './lengthMeter.ts';
import { postingAs } from './postingAs.ts';
import { replyGuard } from './replyGuard.ts';
import { snippets } from './snippets.ts';
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [
altTextReminder,
replyGuard,
postingAs,
lengthMeter,
snippets,
];

View file

@ -0,0 +1,105 @@
// Compose+ · Length meter. Shows the length of what is in the composer the way X counts it (a link
// is 23, an emoji 2, CJK 2), against the limit, and how many posts a longer text would need. It
// only reads the composer's text; X's own counter and its Post button are untouched.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { barPart, clearParts, composerText, composers, ensureBar, sweepBars } from './composer.ts';
export const METER_ATTR = 'data-bt-compose-meter';
/** What X counts for any link, whatever its length (t.co). */
export const LINK_LENGTH = 23;
/** Within this many characters of the limit the meter turns to its warning colour. */
export const NEAR = 20;
export const LENGTH_SCHEMA: SettingsSchema = [
{ key: 'limit', type: 'number', default: 280, min: 1, max: 25000, step: 1, label: 'limit', hint: 'limitHint' },
];
// X's counting (twitter-text, configuration v3): code points in these ranges weigh 1, everything
// else 2; an emoji is 2 however many code points it is made of; the text is counted in NFC.
const LIGHT: ReadonlyArray<readonly [number, number]> = [[0, 4351], [8192, 8205], [8208, 8223], [8242, 8247]];
const EMOJI = /\p{Emoji_Presentation}|\p{Extended_Pictographic}️|[#*0-9]️?⃣/u;
const TLDS = 'com|org|net|edu|gov|io|co|dev|app|ai|me|tv|gg|fm|ly|to|be|fyi|xyz|info|blog|news|shop|site|online|tech|uk|de|fr|es|it|nl|se|no|fi|pl|ru|jp|kr|cn|in|br|ca|au|tr|us|eu|ch|at';
// A link with its scheme, or a bare domain that does not continue a word, an address or a path
// (group 2 is what stands before it; no lookbehind: older WebKit does not have it).
const LINK = new RegExp(`(https?:\\/\\/[^\\s<>"']+)|(^|[^\\w@.\\-\\/])((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:${TLDS})(?![\\w-])(?:\\/[^\\s<>"']*)?)`, 'gi');
const TRAILING = /[.,;:!?)\]}'"»]+$/;
const plain = (text: string): number => {
let count = 0;
for (const { segment } of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text)) {
if (EMOJI.test(segment)) { count += 2; continue; }
for (const char of segment) {
const point = char.codePointAt(0)!;
count += LIGHT.some(([from, to]) => point >= from && point <= to) ? 1 : 2;
}
}
return count;
};
/** The length of `text` as X counts it. Pure. (Links are found by shape: a rare domain ending may be missed.) */
export function weightedLength(text: string): number {
const source = text.normalize('NFC');
let count = 0;
let last = 0;
for (const match of source.matchAll(LINK)) {
// Punctuation after a link is not part of it.
const link = (match[1] ?? match[3]!).replace(TRAILING, '');
const start = match.index + (match[2]?.length ?? 0);
count += plain(source.slice(last, start)) + LINK_LENGTH;
last = start + link.length;
}
return count + plain(source.slice(last));
}
export type Measure = { count: number; limit: number; state: 'ok' | 'near' | 'over'; posts: number };
/** Where `text` stands against `limit`; `posts` is how many posts of that limit it needs at least. Pure. */
export function measure(text: string, limit: number): Measure {
const count = weightedLength(text);
return { count, limit, state: count > limit ? 'over' : count >= limit - NEAR ? 'near' : 'ok', posts: Math.max(1, Math.ceil(count / limit)) };
}
const CSS = `
[${METER_ATTR}] { margin-left: auto; white-space: nowrap; font-variant-numeric: tabular-nums; color: rgb(113, 118, 123); }
[${METER_ATTR}="near"] { color: rgb(255, 173, 31); }
[${METER_ATTR}="over"] { color: rgb(244, 33, 46); font-weight: 600; }
`;
export const lengthMeter: FeatureModule<PluginApi> = {
id: 'compose.lengthMeter',
settings: LENGTH_SCHEMA,
start(ctx) {
const doc = ctx.win.document;
ctx.css(CSS);
// Read once and on a save: the scan runs with every change of the page.
let limit = 280;
const read = () => { limit = Math.round(ctx.settings.get().limit as number); };
read();
const scan = () => {
for (const { toolbar, editor } of composers(doc)) {
const result = measure(composerText(editor), limit);
let meter = barPart(toolbar, METER_ATTR);
// An empty composer has nothing to measure.
if (!result.count) { meter?.remove(); continue; }
const text = ctx.text(result.state === 'over' ? 'over' : 'count', { count: result.count, limit, posts: result.posts });
if (!meter) {
meter = doc.createElement('span');
meter.setAttribute('role', 'status');
ensureBar(doc, toolbar).append(meter);
}
// Only written on change: these nodes live inside the observed tree.
if (meter.getAttribute(METER_ATTR) !== result.state) meter.setAttribute(METER_ATTR, result.state);
if (meter.textContent !== text) meter.textContent = text;
}
sweepBars(doc);
};
const watch = ctx.watch(scan, { characterData: true });
ctx.on(doc, 'input', () => watch.schedule(), { capture: true, passive: true });
ctx.settings.onChange(() => { read(); scan(); });
ctx.defer(() => clearParts(doc, METER_ATTR));
scan();
},
};

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,61 @@
// Compose+ · "Posting as @handle". A chip above the composer's toolbar that names the account this
// tab is signed in to, in that account's own colour, so a post written in the wrong account is seen
// before it is sent. The account is the one X's own account button shows (`api.account()`): no
// request. When it cannot be read there is no chip.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { barPart, clearParts, composers, ensureBar, sweepBars } from './composer.ts';
export const CHIP_ATTR = 'data-bt-compose-chip';
/** The hue (0-359) an account keeps: the same handle always gets the same colour, whatever its case. */
export function accountHue(handle: string): number {
let hash = 0x811c9dc5;
for (const char of handle.toLowerCase()) hash = Math.imul(hash ^ char.codePointAt(0)!, 0x01000193) >>> 0;
return hash % 360;
}
const CSS = `
[${CHIP_ATTR}] { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; min-width: 0; box-sizing: border-box;
padding: 2px 9px 2px 7px; border-radius: 9999px; white-space: nowrap; color: rgb(113, 118, 123);
border: 1px solid hsl(var(--bt-compose-hue) 70% 50% / .4); background: hsl(var(--bt-compose-hue) 70% 50% / .1); }
[${CHIP_ATTR}] > i { flex: none; width: 7px; height: 7px; border-radius: 50%; background: hsl(var(--bt-compose-hue) 70% 50%); }
[${CHIP_ATTR}] > span { overflow: hidden; text-overflow: ellipsis; }
[${CHIP_ATTR}] b { font-weight: 700; color: hsl(var(--bt-compose-hue) 70% 50%); }
`;
export const postingAs: FeatureModule<PluginApi> = {
id: 'compose.postingAs',
start(ctx) {
const doc = ctx.win.document;
ctx.css(CSS);
const scan = () => {
const handle = ctx.api.account()?.handle ?? '';
for (const { toolbar } of composers(doc)) {
let chip = barPart(toolbar, CHIP_ATTR);
if (!handle) { chip?.remove(); continue; }
// Only written on change: these nodes live inside the observed tree.
if (chip?.getAttribute(CHIP_ATTR) === handle) continue;
if (!chip) {
chip = doc.createElement('span');
ensureBar(doc, toolbar).prepend(chip);
}
chip.setAttribute(CHIP_ATTR, handle);
chip.title = ctx.text('title', { handle: `@${handle}` });
chip.style.setProperty('--bt-compose-hue', String(accountHue(handle)));
// "Posting as {handle}": the words around the handle stay in the catalog's order.
const [before = '', after = ''] = ctx.text('label', { handle: '\u0000' }).split('\u0000');
const name = doc.createElement('b');
name.textContent = `@${handle}`;
const label = doc.createElement('span');
label.append(before, name, after);
chip.replaceChildren(doc.createElement('i'), label);
}
sweepBars(doc);
};
ctx.watch(scan);
ctx.defer(() => clearParts(doc, CHIP_ATTR));
scan();
},
};

View file

@ -0,0 +1,113 @@
// Compose+ · Reply Guard (was the Reply Guard plugin, 1.1.0). Asks before a reply to an old post
// and, when turned on, to someone you do not follow. "Reply anyway" clicks X's own reply button,
// which only opens X's reply box: nothing is ever sent. It uses the post's date and what X's own
// responses said about who you follow; what is unknown never asks.
//
// Its settings stay where the plugin kept them (page storage `reply-guard` / `settings`), and
// Alt+Shift+R still opens them.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export type ReplyGuardSettings = { oldDays: number; strangers: boolean };
export type ReplyContext = { time: string | null; now: number; handle: string; following: boolean | null; own: boolean };
type Text = (key: string, params?: Record<string, string | number>) => string;
export const REPLY_GUARD_SCHEMA: SettingsSchema = [
{ key: 'oldDays', type: 'number', default: 30, min: 0, max: 3650, step: 1, label: 'days', hint: 'daysHint' },
{ key: 'strangers', type: 'toggle', default: false, label: 'strangers', hint: 'strangersHint' },
];
const DAY = 24 * 60 * 60 * 1000;
const REPLY_BUTTON = 'article[data-testid="tweet"] [data-testid="reply"]';
/** "3 years", "5 months", "45 days" for an age in days. */
export function formatAge(days: number, text: Text): string {
if (days >= 365) return text('year', { count: Math.floor(days / 365) });
if (days >= 60) return text('month', { count: Math.floor(days / 30) });
return text('day', { count: Math.max(1, Math.floor(days)) });
}
/**
* Pure decision: why a reply to this post deserves a question, or null. `following` is true,
* false or null (not known); `own`: the post is yours. Unknown values never ask.
*/
export function replyReason(settings: ReplyGuardSettings, context: ReplyContext, text: Text): string | null {
if (context.own) return null;
const reasons: string[] = [];
const posted = context.time ? Date.parse(context.time) : NaN;
if (settings.oldDays > 0 && Number.isFinite(posted)) {
const days = (context.now - posted) / DAY;
if (days >= settings.oldDays) reasons.push(text('old', { age: formatAge(days, text) }));
}
if (settings.strangers && context.following === false) reasons.push(text('stranger', { handle: `@${context.handle}` }));
return reasons.length ? reasons.join(' ') : null;
}
export const replyGuard: FeatureModule<PluginApi> = {
id: 'compose.replyGuard',
// The plugin's words and storage, kept: nothing is retranslated and no setting is lost.
words: 'reply-guard',
storage: 'reply-guard',
settings: REPLY_GUARD_SCHEMA,
// A post with its action bar always has X's reply button: without it there is nothing to ask about.
probes: { reply: { selector: REPLY_BUTTON, when: 'article[data-testid="tweet"] [role="group"]' } },
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
const current = (): ReplyGuardSettings => {
const values = ctx.settings.get();
return { oldDays: Math.round(values.oldDays as number), strangers: values.strangers === true };
};
let allowed: Element | null = null;
let asking = false;
ctx.defer(() => { allowed = null; });
const intercept = (event: Event, button: HTMLElement) => {
if (allowed === button) { allowed = null; return; }
const tweet = api.tweet(button.closest('article[data-testid="tweet"]'));
if (!tweet) return;
const settings = current();
const viewer = api.account()?.handle;
const why = replyReason(settings, {
time: tweet.time,
now: Date.now(),
handle: tweet.handle,
following: settings.strangers ? api.users.get(tweet.handle)?.following ?? null : null,
own: !!viewer && viewer.toLowerCase() === tweet.handle.toLowerCase(),
}, ctx.text);
if (!why) return;
const hold = () => { event.preventDefault(); event.stopImmediatePropagation(); };
if (asking) { hold(); return; }
let answer: Promise<boolean>;
// A page where the question cannot be drawn: X's own click goes on, as without Reply Guard.
try { answer = ctx.ui.confirm({ title: ctx.text('confirmTitle'), message: why, confirmLabel: ctx.text('replyAnyway'), cancelLabel: ctx.text('cancel') }); } catch { return; }
hold();
asking = true;
void answer.then(ok => {
asking = false;
if (!ok || !button.isConnected) return;
// click() dispatches synchronously: the capture listener sees `allowed` and lets this one
// through. X's reply button only opens X's reply box.
allowed = button;
try { button.click(); } finally { allowed = null; }
}, () => { asking = false; });
};
// Capture on window runs before X's own handlers: the click (or X's "r" shortcut) is held until
// the question is answered.
ctx.on(win, 'click', event => {
const button = (event.target as Element | null)?.closest?.<HTMLElement>(ctx.selector('reply'));
if (button) intercept(event, button);
}, true);
ctx.on(win, 'keydown', raw => {
const event = raw as KeyboardEvent;
if (event.key !== 'r' || event.ctrlKey || event.metaKey || event.altKey || event.repeat) return;
if (api.isTypingTarget(event.target) || api.isTypingTarget(doc.activeElement)) return;
const button = doc.activeElement?.closest?.('article[data-testid="tweet"]')?.querySelector<HTMLElement>('[data-testid="reply"]');
if (button) intercept(event, button);
}, true);
ctx.command({ id: 'replyGuard.settings', title: ctx.text('title'), keywords: 'reply guard old post stranger ask settings alt shift r', shortcut: 'Alt+Shift+R', run: () => ctx.settings.open() });
},
};

View file

@ -0,0 +1,112 @@
// Compose+ · Snippets. Text you write often (a signature, a link, a standard reply), kept in this
// tab's local storage and put into the composer when you ask: pick one from "Insert a snippet"
// (the palette), or type its shortcut, `;name` and a space, while writing. It is inserted as typed
// text at the caret, the way the Emoji Picker inserts; it never posts and makes no request.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { caretText, insertText, replaceBack, targetComposer } from './composer.ts';
export type Snippet = { name: string; text: string };
export const SNIPPET_LIMITS = Object.freeze({ items: 100, line: 500, name: 24 });
export const SNIPPETS_SCHEMA: SettingsSchema = [
{ key: 'items', type: 'list', default: [], maxItems: SNIPPET_LIMITS.items, maxLength: SNIPPET_LIMITS.line, label: 'items', hint: 'itemsHint' },
{ key: 'expand', type: 'toggle', default: true, label: 'expand', hint: 'expandHint' },
];
const LINE = /^\s*([A-Za-z0-9_-]{1,24})\s*=\s?(.*)$/;
const TYPED = /(?:^|\s);([A-Za-z0-9_-]{1,24})[  ]$/;
/**
* The snippets of the stored lines. A line is `name = text` (`\n` in the text is a line break); a
* line without a name is a snippet that can only be picked from the list. Empty ones are dropped. Pure.
*/
export function parseSnippets(lines: readonly string[]): Snippet[] {
const out: Snippet[] = [];
for (const line of lines) {
const match = LINE.exec(line);
const text = (match ? match[2]! : line).replace(/\\n/g, '\n').trim();
if (text) out.push({ name: match ? match[1]! : '', text });
}
return out;
}
/** The snippet whose shortcut was just typed before the caret (`;name` and a space), and how many characters to replace. Pure. */
export function expansionAt(before: string, snippets: readonly Snippet[]): { back: number; text: string } | null {
const match = TYPED.exec(before);
if (!match) return null;
const name = match[1]!.toLowerCase();
const snippet = snippets.find(item => item.name.toLowerCase() === name);
// The space that was typed stays after the text.
return snippet ? { back: name.length + 2, text: `${snippet.text} ` } : null;
}
/** One line for the list: the shortcut and the start of the text. */
export function snippetLabel(snippet: Snippet, max = 72): string {
const text = snippet.text.replace(/\s+/g, ' ');
const short = text.length > max ? `${text.slice(0, max - 1)}…` : text;
return snippet.name ? `;${snippet.name} ${short}` : short;
}
export const snippets: FeatureModule<PluginApi> = {
id: 'compose.snippets',
settings: SNIPPETS_SCHEMA,
start(ctx) {
const { win } = ctx;
const doc = win.document;
// Read once and on a save: the shortcut check runs with every key typed.
let items: Snippet[] = [];
let expand = true;
const read = () => {
const values = ctx.settings.get();
items = parseSnippets(values.items as string[]);
expand = values.expand === true;
};
read();
ctx.settings.onChange(read);
let active = true;
ctx.defer(() => { active = false; });
// `;name` and a space: replaced once X's editor has taken the space (the next frame).
ctx.on(doc, 'input', () => {
if (!expand || !items.length) return;
const typed = caretText(win);
if (!typed || !expansionAt(typed.before, items)) return;
win.requestAnimationFrame(() => {
if (!active) return;
const caret = caretText(win);
const found = caret && expansionAt(caret.before, items);
if (caret && found) replaceBack(win, caret, found.back, found.text);
});
}, { capture: true, passive: true });
const pick = () => {
if (!items.length) {
ctx.ui.toast(ctx.text('none'), { action: { label: ctx.text('edit'), onClick: () => ctx.settings.open() } });
return;
}
// Remembered now: the dialog takes the focus and the selection with it.
const target = targetComposer(win);
if (!target) { ctx.ui.toast(ctx.text('noComposer')); return; }
const h = ctx.ui.h;
const dialog = ctx.ui.dialog({
title: ctx.text('pick'),
width: 'sm',
content: body => body.append(h('div', { class: 'wb-stack' }, items.map(item => h('button', {
type: 'button', class: 'wb-btn wb-plain', title: item.text,
onclick: () => dialog.close(item),
}, snippetLabel(item))))),
actions: [{ label: ctx.text('edit'), onClick: () => { ctx.settings.open(); } }],
});
void dialog.closed.then(result => {
const chosen = result as Snippet | undefined;
if (!active || !chosen || typeof chosen.text !== 'string') return;
if (!insertText(win, target, chosen.text)) ctx.ui.toast(ctx.text('noComposer'));
});
};
ctx.command({ id: 'snippets.insert', title: ctx.text('pick'), keywords: 'snippet snippets saved text insert template signature', run: pick });
},
};

View file

@ -0,0 +1,16 @@
// The core flags: owned by no area plugin, so no plugin switch turns them off. Branding (the logo,
// the wording) has its controls in Appearance, "one navigation in split view" in Settings; the rest
// is the Fixes list under the area cards.
import type { FeatureSpec } from '../../../../waybetter/packages/runtime/src/featureTable.ts';
import { core } from './rows.ts';
export const CORE_FEATURES: readonly FeatureSpec[] = [
...core('branding', ['logoBrush', { id: 'replaceLogo', default: false }, 'twitterWording']),
...core('layout', ['singleSplitNav']),
...core('fixes', ['fixLikeFollow', 'fixScrollRestore', 'fixTimelineJump', 'fixHomeTab', 'fixNotificationBadge', 'fixNewPostsPill', 'fixMediaUpload',
'followingChronological', 'fixChatButton', 'composerRestorePrompt']),
];
/** Core flags with a control of their own (Appearance, Settings): not repeated under Fixes. */
export const X_ELSEWHERE: readonly string[] = ['logoBrush', 'replaceLogo', 'twitterWording', 'singleSplitNav'];

View file

@ -0,0 +1,146 @@
// Media+ · Alt text viewer. Under a post's photos, an "ALT" button per photo that has a
// description: a click shows the description as text you can select and copy. Optionally a mark on
// photos nobody described. It only reads the `alt` X already rendered on its own `<img>`.
//
// X gives an undescribed photo a generic label in the page's language ("Image" in English). Only
// the English one is known here: on a page in another language that word is shown as if it were a
// description, and only a photo with no text at all is marked (nothing is called undescribed on a guess).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export const ALT_SCHEMA: SettingsSchema = [
{ key: 'open', type: 'toggle', default: false, label: 'open' },
{ key: 'missing', type: 'toggle', default: false, label: 'missing', hint: 'missingHint' },
];
type AltSettings = { open: boolean; missing: boolean };
/** X's label for a photo without a description, on an English page. */
const GENERIC_EN = 'Image';
/**
* What X's `alt` says about a photo: its description; `null` when it certainly has none (no text,
* or X's generic English label on an English page). Pure.
*/
export function readAlt(raw: string | null | undefined, english: boolean): string | null {
const text = (raw ?? '').trim();
if (!text || (english && text === GENERIC_EN)) return null;
return text;
}
export type AltItem = { index: number; text: string | null };
/** The rows to show for a post's photos (`alts` in page order): every description, and when asked the ones that certainly have none. Pure. */
export function altItems(alts: ReadonlyArray<string | null | undefined>, english: boolean, missing: boolean): AltItem[] {
return alts
.map((raw, index) => ({ index: index + 1, text: readAlt(raw, english) }))
.filter(item => item.text !== null || missing);
}
const POST = 'article[data-testid="tweet"]';
const PANEL_CLASS = 'bt-media-alt';
const CSS = `
.${PANEL_CLASS} { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 6px; margin-top: 10px; color: var(--wb-text, inherit); font: 400 14px/1.4 var(--wb-font, system-ui, sans-serif); cursor: default; }
.${PANEL_CLASS}-item { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 6px; max-width: 100%; }
.${PANEL_CLASS}-item[data-open] { flex-basis: 100%; }
.${PANEL_CLASS}-chip, .${PANEL_CLASS}-copy, .${PANEL_CLASS}-none { flex: none; box-sizing: border-box; height: 22px; padding: 0 8px; border-radius: 4px; font: 700 12px/20px var(--wb-font, system-ui, sans-serif); }
.${PANEL_CLASS}-chip, .${PANEL_CLASS}-copy { border: 1px solid var(--wb-border, rgba(127, 127, 127, .5)); background: transparent; color: inherit; cursor: pointer; }
.${PANEL_CLASS}-chip:hover, .${PANEL_CLASS}-copy:hover, .${PANEL_CLASS}-chip[aria-expanded="true"] { background: rgba(127, 127, 127, .2); }
.${PANEL_CLASS}-chip:focus-visible, .${PANEL_CLASS}-copy:focus-visible { outline: 2px solid var(--wb-accent, rgb(29, 155, 240)); outline-offset: 1px; }
.${PANEL_CLASS}-none { border: 1px dashed var(--wb-border, rgba(127, 127, 127, .5)); color: var(--wb-muted, inherit); font-weight: 500; }
.${PANEL_CLASS}-body { display: flex; flex: 1 1 200px; align-items: flex-start; gap: 6px; min-width: 0; }
.${PANEL_CLASS}-body[hidden] { display: none; }
.${PANEL_CLASS}-text { flex: 1; min-width: 0; white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; cursor: text; }
`;
export const altText: FeatureModule<PluginApi> = {
id: 'media.altText',
// If posts show photos and none is inside X's photo element, X renamed it: there is no alt to read.
probes: { photo: { selector: '[data-testid="tweetPhoto"]', when: `${POST} img[src*="pbs.twimg.com/media/"]` } },
settings: ALT_SCHEMA,
start(ctx) {
const doc = ctx.win.document;
const photo = ctx.selector('photo');
const settings = () => ctx.settings.get() as AltSettings;
const english = () => /^en\b/i.test(doc.documentElement?.getAttribute('lang') ?? '');
/** Per post: its panel and what it was built from (so a re-render of the same photos keeps what you opened). */
const panels = new Map<Element, { panel: HTMLElement; key: string }>();
const element = (tag: string, part: string, text = '') => {
const node = doc.createElement(tag);
node.className = `${PANEL_CLASS}-${part}`;
if (text) node.textContent = text;
return node;
};
const button = (part: string, text: string) => {
const node = element('button', part, text) as HTMLButtonElement;
node.type = 'button';
return node;
};
const build = (items: AltItem[], many: boolean, open: boolean) => {
const panel = doc.createElement('div');
panel.className = PANEL_CLASS;
// The panel sits inside the post: a click or Enter in it must not open the post.
for (const type of ['click', 'dblclick']) panel.addEventListener(type, event => event.stopPropagation());
panel.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') event.stopPropagation(); });
for (const item of items) {
const row = element('div', 'item');
if (item.text === null) {
row.append(element('span', 'none', many ? ctx.text('noneN', { n: item.index }) : ctx.text('none')));
panel.append(row);
continue;
}
const text = item.text;
const chip = button('chip', many ? ctx.text('chipN', { n: item.index }) : ctx.text('chip'));
chip.title = ctx.text('show');
const body = element('div', 'body');
const copy = button('copy', ctx.text('copy'));
copy.addEventListener('click', () => {
void ctx.api.copyText(text).then(ok => ctx.api.toast(ok ? ctx.text('copied') : ctx.text('copyFailed'), 1800));
});
body.append(element('div', 'text', text), copy);
const show = (on: boolean) => {
body.hidden = !on;
chip.setAttribute('aria-expanded', String(on));
row.toggleAttribute('data-open', on);
};
chip.addEventListener('click', () => show(!!body.hidden));
show(open);
row.append(chip, body);
panel.append(row);
}
return panel;
};
const render = (post: Element) => {
const alts = Array.from(post.querySelectorAll('img')).filter(img => img.closest(photo)).map(img => img.getAttribute('alt'));
const { open, missing } = settings();
const items = altItems(alts, english(), missing);
const key = JSON.stringify([items, open]);
const known = panels.get(post);
if (known?.panel.isConnected && known.key === key) return;
known?.panel.remove();
panels.delete(post);
// Above the post's action bar. A post without one (not seen so far) gets no panel.
const bar = post.querySelector('[role="group"]');
if (!items.length || !bar?.parentElement) return;
const panel = build(items, alts.length > 1, open);
bar.parentElement.insertBefore(panel, bar);
panels.set(post, { panel, key });
};
const renderAll = () => {
for (const [post, known] of panels) if (!known.panel.isConnected) panels.delete(post);
for (const post of Array.from(doc.querySelectorAll(POST))) render(post);
};
ctx.css(CSS);
ctx.observe(`${POST} ${photo} img`, img => { const post = img.closest(POST); if (post) render(post); });
ctx.settings.onChange(renderAll);
ctx.defer(() => {
for (const known of panels.values()) known.panel.remove();
panels.clear();
});
},
};

View file

@ -0,0 +1,89 @@
// Media+ · Blur media until hover ("work mode"). Photos, videos and link-card pictures in posts
// are blurred until the pointer is on them. Local CSS only; X loads and plays what it would anyway.
//
// "Only accounts I don't follow" needs to know whether you follow a post's author. That comes from
// the responses X already fetched (api.users); when X has not said, it is unknown, and unknown is
// never blurred. Your own posts are never blurred in that mode.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export type BlurScope = 'all' | 'notFollowed';
export type BlurSettings = { enabled: boolean; scope: BlurScope; strength: number };
export const BLUR_SCHEMA: SettingsSchema = [
{ key: 'enabled', type: 'toggle', default: true, label: 'enabled' },
{ type: 'divider' },
{ key: 'scope', type: 'select', default: 'all', label: 'scope', hint: 'scopeHint', options: [{ value: 'all', label: 'scopeAll' }, { value: 'notFollowed', label: 'scopeNotFollowed' }] },
{ key: 'strength', type: 'number', default: 24, min: 4, max: 60, step: 2, label: 'strength' },
];
const MARK = 'data-bt-media-blur';
const POST = 'article[data-testid="tweet"]';
/** What counts as media inside a post. */
const IN_POST = ['[data-testid="tweetPhoto"]', '[data-testid="videoPlayer"]', '[data-testid="card.layoutLarge.media"]', '[data-testid="card.layoutSmall.media"]'];
/** The cells of a profile's Media tab (no post around them). */
const GRID = ['[data-testid="primaryColumn"] section li a[href*="/photo/"]', '[data-testid="primaryColumn"] section li a[href*="/video/"]'];
/** The CSS for `settings` (empty while blurring is off). Pure. */
export function blurCss(settings: BlurSettings): string {
if (!settings.enabled) return '';
const post = settings.scope === 'notFollowed' ? `${POST}[${MARK}]` : POST;
// The Media tab has no author per cell to ask about: it is only blurred when everything is.
const targets = [...IN_POST.map(media => `${post} ${media}`), ...(settings.scope === 'all' ? GRID : [])];
const each = (suffix: string) => targets.map(target => `${target}${suffix}`).join(',\n');
return [
`${each('')} { filter: blur(${settings.strength}px) !important; transition: filter .15s; }`,
`${each(':hover')},\n${each(':focus-within')} { filter: none !important; }`,
`@media (prefers-reduced-motion: reduce) { ${each('')} { transition: none; } }`,
].join('\n');
}
/**
* Whether a post's media is blurred in "only accounts I don't follow": only when X said you do
* not follow its author. `null`/`undefined` (X has not said) is unknown: not blurred. Pure.
*/
export function blursAuthor(following: boolean | null | undefined, isOwn: boolean): boolean {
return following === false && !isOwn;
}
export const blurMedia: FeatureModule<PluginApi> = {
id: 'media.blurMedia',
settings: BLUR_SCHEMA,
start(ctx) {
const doc = ctx.win.document;
const current = () => ctx.settings.get() as BlurSettings;
const mark = (post: Element) => {
const settings = current();
let on = false;
if (settings.enabled && settings.scope === 'notFollowed') {
const handle = ctx.api.tweet(post)?.handle;
const own = ctx.api.account()?.handle;
if (handle) on = blursAuthor(ctx.api.users.get(handle)?.following, !!own && own.toLowerCase() === handle.toLowerCase());
}
if (on !== post.hasAttribute(MARK)) post.toggleAttribute(MARK, on);
};
const markAll = () => { for (const post of Array.from(doc.querySelectorAll(POST))) mark(post); };
const apply = () => {
ctx.css(blurCss(current()));
markAll();
};
apply();
ctx.settings.onChange(apply);
ctx.observe(POST, mark);
// X said more about some accounts (a response arrived): posts that were unknown may be known now.
ctx.defer(ctx.api.users.onUpdate(() => { if (current().scope === 'notFollowed') markAll(); }));
ctx.defer(() => { for (const post of Array.from(doc.querySelectorAll(`[${MARK}]`))) post.removeAttribute(MARK); });
ctx.command({
id: 'blurMedia.toggle', title: ctx.text('toggle'), keywords: 'blur media photos videos work mode hide alt shift b', shortcut: 'Alt+Shift+B',
run: () => {
ctx.settings.set({ enabled: !current().enabled });
ctx.api.toast(current().enabled ? ctx.text('on') : ctx.text('off'), 1800);
},
});
},
};

View file

@ -0,0 +1,30 @@
// Media+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { app, modules, ported } from '../rows.ts';
/** The pages that show posts (and so photos and videos): timelines, Explore, notifications. Not chats. */
const POSTS = ['timeline', 'explore', 'notifications'];
/** The words of a new feature's row on the card (./messages.en.json). */
const words = (name: string) => ({ label: `plugin.media-plus.feature.${name}.label`, description: `plugin.media-plus.feature.${name}.description` });
export const FEATURES: readonly FeatureSpec[] = [
// The download reads X's own responses and fetches from X's CDN: it stays in the app runtime.
...app('media', '', [{ id: 'mediaDownload', default: true }]),
...modules('media', 'video', [
// The three video rules (./videoRules.ts): on chat pages too, as before.
{ id: 'rememberVideoVolume', default: true, heavy: true }, { id: 'disableVideoAutoplay', heavy: true }, { id: 'stopVideoLoop', heavy: true },
{ id: 'media.videoSpeed', surfaces: POSTS, settings: true, ...words('videoSpeed'), keywords: 'playback rate faster slower 2x', permissions: ['storage', 'ui', 'commands'] },
{ id: 'media.pictureInPicture', surfaces: POSTS, ...words('pictureInPicture'), keywords: 'pip pop out floating window', permissions: ['storage', 'ui'] },
]),
...modules('media', '', [
ported('media.gridFocus', 'media-grid-focus', { surfaces: ['profile'], keywords: 'Media Grid Focus gallery photos', permissions: [] }),
{ id: 'media.altText', surfaces: POSTS, settings: true, ...words('altText'), keywords: 'alt image description accessibility', permissions: ['storage', 'ui', 'clipboard'] },
{ id: 'media.blurMedia', surfaces: POSTS, settings: true, ...words('blurMedia'), keywords: 'work mode hide photos videos sensitive nsfw', permissions: ['storage', 'ui', 'commands', 'account', 'users'] },
]),
];
/** Flags Power User turns on besides the defaults (this area's advanced features). Blurring hides things: never. */
export const POWER: readonly string[] = ['media.videoSpeed', 'media.pictureInPicture', 'media.altText'];

View file

@ -0,0 +1,37 @@
// Media+ · Media Grid Focus (was the Media Grid Focus plugin, 1.1.1). On a profile's Media tab it
// hides the right column, widens the page and tightens the gaps so the photo and video grid fills
// the window. Other pages are unchanged.
//
// The plugin scoped its rules with an attribute on <html> that it kept in step with the route; the
// module's stylesheet is simply only there while the page is a Media tab. The rules are the same.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
/** `/<handle>/media`: a profile's Media tab. Pure. */
export const isMediaTab = (pathname: string): boolean => /^\/[A-Za-z0-9_]{1,15}\/media\/?$/.test(pathname);
export const GRID_FOCUS_CSS = `
[data-testid="sidebarColumn"] { display: none !important; }
/* The main area takes the free width next to X's nav (whatever the nav's width: 275px, 88px or
none), and the page fills it up to 1400px. A fixed "100vw - 88px" was wider than the pane
next to X's 275px nav and scrolled the page sideways. */
main[role="main"] { flex-grow: 1000 !important; min-width: 0 !important; }
main[role="main"] > div { width: min(1400px, 100%) !important; max-width: none !important; }
main[role="main"] > div > div,
[data-testid="primaryColumn"] { max-width: none !important; width: 100% !important; flex-grow: 1 !important; }
[data-testid="primaryColumn"] section li,
[data-testid="primaryColumn"] section [data-testid="cellInnerDiv"] a[href*="/photo/"],
[data-testid="primaryColumn"] section [data-testid="cellInnerDiv"] a[href*="/video/"] { padding: 1px !important; margin: 0 !important; }
`;
export const gridFocus: FeatureModule<PluginApi> = {
id: 'media.gridFocus',
// The plugin's words, kept: nothing is retranslated. It stored nothing.
words: 'media-grid-focus',
start(ctx) {
const sync = () => ctx.css(isMediaTab(ctx.win.location.pathname) ? GRID_FOCUS_CSS : '');
sync();
ctx.onRouteChange(sync);
},
};

View file

@ -0,0 +1,25 @@
// Media+: photos, video and downloads (docs/AREA-PLUGINS.md; Navigation+ in ../navigation is the
// reference). One module per `backing: 'module'` row of ./features.ts; the registry starts each only
// while its flag is on, the area is on and the page is on one of its surfaces. The download button
// stays in the app runtime (src/inject/media: it reads X's responses and fetches from X's CDN); the
// card only owns its flag.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { altText } from './altText.ts';
import { blurMedia } from './blurMedia.ts';
import { gridFocus } from './gridFocus.ts';
import { pictureInPicture } from './pictureInPicture.ts';
import { disableVideoAutoplay, rememberVideoVolume, stopVideoLoop } from './videoRules.ts';
import { videoSpeed } from './videoSpeed.ts';
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [
rememberVideoVolume,
disableVideoAutoplay,
stopVideoLoop,
gridFocus,
videoSpeed,
pictureInPicture,
altText,
blurMedia,
];

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,79 @@
// Media+ · Picture-in-picture. A button on X's own player that pops the video out into the
// system's floating window (the standard `requestPictureInPicture` on X's `<video>`, on your click)
// and brings it back. Nothing is loaded or sent; the video keeps playing from X's player.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { PLAYER, controlBar, controlButton, controlsCss, removeControl } from './playerControls.ts';
const PIP_ATTR = 'data-bt-media-pip';
// The icon is drawn by the button itself: a frame with a small filled window in its corner.
const CSS = `
[${PIP_ATTR}] { position: relative; order: 2; width: 32px; padding: 0; }
[${PIP_ATTR}]::before { content: ""; position: absolute; left: 8px; top: 6px; width: 14px; height: 10px; border: 1.5px solid currentColor; border-radius: 2px; }
[${PIP_ATTR}]::after { content: ""; position: absolute; left: 16px; top: 12px; width: 7px; height: 5px; background: currentColor; border-radius: 1px; }
[${PIP_ATTR}][aria-pressed="true"] { background: #fff; color: #000; }
`;
type PipDocument = Document & { pictureInPictureEnabled?: boolean; pictureInPictureElement?: Element | null; exitPictureInPicture?(): Promise<void> };
type PipVideo = HTMLVideoElement & { disablePictureInPicture?: boolean; requestPictureInPicture?(): Promise<unknown> };
/** Pops `video` out, or brings it back when it is the one floating. Resolves to false when the webview refused. */
export async function togglePictureInPicture(doc: PipDocument, video: PipVideo): Promise<boolean> {
try {
if (doc.pictureInPictureElement === video) { await doc.exitPictureInPicture?.(); return true; }
if (typeof video.requestPictureInPicture !== 'function') return false;
// X may mark its videos as not poppable; the click is the user asking for exactly that.
if (video.disablePictureInPicture) video.disablePictureInPicture = false;
await video.requestPictureInPicture();
return true;
} catch {
return false;
}
}
export const pictureInPicture: FeatureModule<PluginApi> = {
id: 'media.pictureInPicture',
// If a page shows videos and none is inside X's player element, X renamed it: there is nothing to put the button on.
probes: { player: { selector: PLAYER, when: '[data-testid="primaryColumn"] video' } },
start(ctx) {
const doc = ctx.win.document as PipDocument;
// A webview without picture-in-picture: no button that could only fail. Said once, not on every page.
if (!doc.pictureInPictureEnabled) {
if (!ctx.storage.get('unsupportedSaid', false)) { ctx.storage.set('unsupportedSaid', true); ctx.api.toast(ctx.text('unsupported'), 6000); }
return;
}
const selector = ctx.selector('player');
const buttons = new Map<Element, HTMLElement>();
const mount = (player: Element) => {
if (buttons.get(player)?.isConnected) return;
for (const [known, button] of buttons) if (!button.isConnected) buttons.delete(known);
const button = controlButton(doc, ctx.text('title'));
button.setAttribute(PIP_ATTR, '');
button.setAttribute('aria-pressed', 'false');
button.addEventListener('click', () => {
const video = player.querySelector('video') as PipVideo | null;
if (!video) return;
void togglePictureInPicture(doc, video).then(ok => { if (!ok) ctx.api.toast(ctx.text('failed'), 4000); });
});
buttons.set(player, button);
controlBar(player).append(button);
};
ctx.css(controlsCss(selector) + CSS);
ctx.observe(selector, mount);
ctx.defer(() => {
for (const button of buttons.values()) removeControl(button);
buttons.clear();
});
// Which button is "on": the player whose video is the floating one.
const mark = (event: Event) => {
const player = (event.target as Element | null)?.closest?.(selector);
const button = player && buttons.get(player);
if (button) button.setAttribute('aria-pressed', String(event.type === 'enterpictureinpicture'));
};
ctx.on(doc, 'enterpictureinpicture', mark, true);
ctx.on(doc, 'leavepictureinpicture', mark, true);
},
};

View file

@ -0,0 +1,58 @@
// Media+: the small bar the area's video features put on X's own player (speed, picture-in-picture).
// Each feature adds its own control and takes it away again; the bar exists while it holds one.
//
// X's player keeps working as it does: the bar is never focused (its buttons are outside the tab
// order and a press does not move focus, so X's keys keep going where they went), and a press on
// it does not reach the player (no play/pause, no opening of the viewer). Nothing else of X's
// events is touched.
export const PLAYER = '[data-testid="videoPlayer"]';
export const BAR_CLASS = 'bt-media-controls';
export const CONTROL_CLASS = 'bt-media-control';
/** On the bar while one of its menus is open (it stays visible without the pointer on the player). */
export const OPEN_ATTR = 'data-bt-media-open';
/** The bar and its buttons, for the player `player` matches. Every feature that uses the bar adds these rules to its own sheet. */
export const controlsCss = (player: string = PLAYER): string => `
.${BAR_CLASS} { position: absolute; top: 8px; left: 8px; z-index: 2; display: flex; align-items: flex-start; gap: 6px; opacity: 0; pointer-events: none; transition: opacity .15s; }
${player}:hover > .${BAR_CLASS}, .${BAR_CLASS}[${OPEN_ATTR}] { opacity: 1; pointer-events: auto; }
/* X's GIFs are looping clips without controls: nothing to add. */
${player}:has(video[src*="/tweet_video/"]) > .${BAR_CLASS} { display: none; }
.${CONTROL_CLASS} { box-sizing: border-box; min-width: 28px; height: 24px; padding: 0 8px; border: 0; border-radius: 4px; background: rgba(0, 0, 0, .77); color: #fff; font: 700 13px/24px system-ui, sans-serif; cursor: pointer; }
.${CONTROL_CLASS}:hover { background: rgba(0, 0, 0, .92); }
@media (prefers-reduced-motion: reduce) { .${BAR_CLASS} { transition: none; } }
`;
/** Presses that must not reach X's player. */
const SHIELDED = ['click', 'dblclick', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'touchstart', 'touchend'];
/** The bar of `player`, created when it has none yet. */
export function controlBar(player: Element): HTMLElement {
const existing = Array.from(player.children).find(child => child.className === BAR_CLASS);
if (existing) return existing as HTMLElement;
const bar = player.ownerDocument.createElement('div');
bar.className = BAR_CLASS;
for (const type of SHIELDED) bar.addEventListener(type, event => event.stopPropagation());
// A press on a control must not take the focus away from where X has it.
bar.addEventListener('mousedown', event => event.preventDefault());
player.append(bar);
return bar;
}
/** A button for the bar: outside the tab order, named by `title`. */
export function controlButton(doc: Document, title: string): HTMLButtonElement {
const button = doc.createElement('button');
button.type = 'button';
button.tabIndex = -1;
button.className = CONTROL_CLASS;
button.title = title;
button.setAttribute('aria-label', title);
return button;
}
/** Takes a feature's control out of its bar, and the bar with it when that was its last one. */
export function removeControl(control: Element): void {
const bar = control.parentElement;
control.remove();
if (bar && bar.className === BAR_CLASS && !bar.firstElementChild) bar.remove();
}

View file

@ -0,0 +1,19 @@
// Media+ · the three video rules (src/fixes/video.ts): remember the volume, no autoplay, no loop.
// Listeners on X's own video elements, started and stopped by the registry with the flags they
// always had. `heavy` in the table: a video in a chat follows the same rules, as before.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import { installVideoAutoplayBlock, installVideoLoopStop, installVideoVolumeMemory } from '../../fixes/video.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
const rule = (id: string, install: (win: Window) => { dispose(): void }): FeatureModule<PluginApi> => ({
id,
start(ctx) {
const handle = install(ctx.win);
ctx.defer(() => handle.dispose());
},
});
export const rememberVideoVolume = rule('rememberVideoVolume', installVideoVolumeMemory);
export const disableVideoAutoplay = rule('disableVideoAutoplay', installVideoAutoplayBlock);
export const stopVideoLoop = rule('stopVideoLoop', installVideoLoopStop);

View file

@ -0,0 +1,175 @@
// Media+ · Video speed. A small speed button on X's own player with a menu of speeds, and two keys
// (Alt+Shift+Up / Alt+Shift+Down) for the video that is playing. The speed you chose is given to
// the next video too. It only sets `playbackRate` on the `<video>` X already has in the page.
//
// GIFs are left alone. A speed picked in X's own player menu is shown on the button, not remembered
// (X sets rates itself when it loads a video; those must not become "your" speed).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import { isGifSource } from '../../fixes/video.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { BAR_CLASS, OPEN_ATTR, PLAYER, controlBar, controlButton, controlsCss, removeControl } from './playerControls.ts';
export const SPEEDS: readonly number[] = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 3];
export const SPEED_SCHEMA: SettingsSchema = [
{ key: 'remember', type: 'toggle', default: true, label: 'remember', hint: 'rememberHint' },
{ key: 'button', type: 'toggle', default: true, label: 'button' },
];
type SpeedSettings = { remember: boolean; button: boolean };
/** A stored speed, or null for anything that is not one. */
export function parseSpeed(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) && value >= SPEEDS[0]! && value <= SPEEDS[SPEEDS.length - 1]! ? value : null;
}
/** The next speed of the list above (`1`) or below (`-1`) `current`; the ends stay where they are. */
export function stepSpeed(current: number, direction: 1 | -1): number {
if (direction > 0) return SPEEDS.find(speed => speed > current + 0.001) ?? SPEEDS[SPEEDS.length - 1]!;
return [...SPEEDS].reverse().find(speed => speed < current - 0.001) ?? SPEEDS[0]!;
}
/** `1.5` -> `1.5×`. */
export const formatSpeed = (rate: number): string => `${Math.round(rate * 100) / 100}×`;
type VideoLike = { paused: boolean; ended: boolean; isConnected: boolean; src: string; currentSrc: string };
/** The video the keys act on: the one playing (the last one started first), else the last one started. GIFs never. */
export function pickVideo<T extends VideoLike>(videos: readonly T[], last: T | null): T | null {
const usable = videos.filter(video => video.isConnected && !isGifSource(video.currentSrc || video.src));
const playing = usable.filter(video => !video.paused && !video.ended);
if (last && playing.includes(last)) return last;
return playing[0] ?? (last && usable.includes(last) ? last : null);
}
const SPEED_ATTR = 'data-bt-media-speed';
const CSS = `${controlsCss()}
.bt-media-speed { position: relative; order: 1; }
/* A speed other than normal stays visible: you see why a video is fast. */
.${BAR_CLASS}:has([${SPEED_ATTR}]:not([${SPEED_ATTR}="1"])) { opacity: 1; pointer-events: auto; }
.bt-media-speed-menu { position: absolute; top: 28px; left: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 2px; padding: 4px; border-radius: 6px; background: rgba(0, 0, 0, .85); }
.bt-media-speed-menu[hidden] { display: none; }
.bt-media-speed-menu button { min-width: 52px; height: 26px; padding: 0 8px; border: 0; border-radius: 4px; background: transparent; color: #fff; font: 500 13px/26px system-ui, sans-serif; cursor: pointer; }
.bt-media-speed-menu button:hover { background: rgba(255, 255, 255, .16); }
.bt-media-speed-menu button[aria-checked="true"] { background: rgba(255, 255, 255, .28); font-weight: 700; }
`;
export const videoSpeed: FeatureModule<PluginApi> = {
id: 'media.videoSpeed',
settings: SPEED_SCHEMA,
start(ctx) {
const doc = ctx.win.document;
const settings = () => ctx.settings.get() as SpeedSettings;
/** The speed new videos get while "remember" is on: the one chosen last. */
let speed = parseSpeed(ctx.storage.get<unknown>('speed', null)) ?? 1;
let last: HTMLVideoElement | null = null;
/** Per video, the source it got the speed for: once per source, so X's own speed menu is not fought. */
const applied = new WeakMap<HTMLVideoElement, string>();
type Control = { root: HTMLElement; pill: HTMLElement; menu: HTMLElement; items: HTMLElement[] };
const controls = new Map<Element, Control>();
const videoOf = (player: Element) => player.querySelector('video') as HTMLVideoElement | null;
const asVideo = (target: EventTarget | null) => ((target as Element | null)?.nodeName === 'VIDEO' ? target as HTMLVideoElement : null);
const usable = (video: HTMLVideoElement) => !isGifSource(video.currentSrc || video.src);
const show = (control: Control, rate: number) => {
control.pill.textContent = formatSpeed(rate);
control.pill.setAttribute(SPEED_ATTR, String(rate));
for (const item of control.items) item.setAttribute('aria-checked', String(Number(item.getAttribute('data-rate')) === rate));
};
const refresh = (video: HTMLVideoElement) => {
const player = video.closest(PLAYER);
const control = player && controls.get(player);
if (control) show(control, video.playbackRate);
};
const close = (control: Control) => {
control.menu.hidden = true;
control.root.parentElement?.removeAttribute(OPEN_ATTR);
};
const setSpeed = (video: HTMLVideoElement, rate: number) => {
applied.set(video, video.currentSrc || video.src);
video.playbackRate = rate;
if (settings().remember) { speed = rate; ctx.storage.set('speed', rate); }
refresh(video);
};
const mount = (player: Element) => {
if (!settings().button || controls.get(player)?.root.isConnected) return;
for (const [known, control] of controls) if (!control.root.isConnected) controls.delete(known);
const root = doc.createElement('div');
root.className = 'bt-media-speed';
const pill = controlButton(doc, ctx.text('title'));
pill.setAttribute('aria-haspopup', 'true');
const menu = doc.createElement('div');
menu.className = 'bt-media-speed-menu';
menu.setAttribute('role', 'menu');
menu.hidden = true;
const control: Control = { root, pill, menu, items: [] };
for (const rate of SPEEDS) {
const item = doc.createElement('button');
item.type = 'button';
item.tabIndex = -1;
item.textContent = formatSpeed(rate);
item.setAttribute('role', 'menuitemradio');
item.setAttribute('data-rate', String(rate));
item.addEventListener('click', () => {
const video = videoOf(player);
if (video) setSpeed(video, rate);
close(control);
});
control.items.push(item);
menu.append(item);
}
pill.addEventListener('click', () => {
if (!menu.hidden) { close(control); return; }
menu.hidden = false;
root.parentElement?.setAttribute(OPEN_ATTR, '');
});
root.append(pill, menu);
show(control, videoOf(player)?.playbackRate ?? 1);
controls.set(player, control);
controlBar(player).append(root);
};
const unmountAll = () => {
for (const control of controls.values()) { close(control); removeControl(control.root); }
controls.clear();
};
ctx.css(CSS);
ctx.observe(PLAYER, mount);
ctx.defer(unmountAll);
ctx.settings.onChange(next => {
if (!(next as SpeedSettings).button) unmountAll();
else for (const player of Array.from(doc.querySelectorAll(PLAYER))) mount(player);
});
// A press anywhere else closes an open menu.
ctx.on(doc, 'pointerdown', event => {
for (const control of controls.values()) if (!control.menu.hidden && !control.root.contains(event.target as Node | null)) close(control);
}, true);
// Media events do not bubble: capturing listeners on the document, as the other video rules use.
const onStart = (event: Event) => {
const video = asVideo(event.target);
if (!video || !usable(video)) return;
if (event.type === 'play') last = video;
const source = video.currentSrc || video.src;
if (applied.get(video) === source) return;
applied.set(video, source);
if (settings().remember && speed !== 1 && Math.abs(video.playbackRate - speed) > 0.001) video.playbackRate = speed;
};
ctx.on(doc, 'play', onStart, true);
ctx.on(doc, 'loadedmetadata', onStart, true);
ctx.on(doc, 'ratechange', event => { const video = asVideo(event.target); if (video) refresh(video); }, true);
const step = (direction: 1 | -1) => {
const video = pickVideo(Array.from(doc.querySelectorAll('video')), last);
if (!video) { ctx.api.toast(ctx.text('noVideo'), 1800); return; }
const rate = stepSpeed(video.playbackRate, direction);
setSpeed(video, rate);
ctx.api.toast(ctx.text('now', { speed: formatSpeed(rate) }), 1200);
};
ctx.command({ id: 'videoSpeed.faster', title: ctx.text('faster'), keywords: 'video speed faster playback rate alt shift up', shortcut: 'Alt+Shift+ArrowUp', run: () => step(1) });
ctx.command({ id: 'videoSpeed.slower', title: ctx.text('slower'), keywords: 'video speed slower playback rate alt shift down', shortcut: 'Alt+Shift+ArrowDown', run: () => step(-1) });
},
};

View file

@ -0,0 +1,24 @@
// English words the areas added and that are not in locales/en.json yet. Each area writes its new
// words into src/areas/<area>/messages.en.json with their full catalog keys
// (`plugin.<area>-plus.<feature>.<key>`, `plugin.<area>-plus.feature.<name>.label`, ...), so
// no two areas edit the same catalog. They count as English everywhere (the X runtime, the panel,
// the tests) until the words step moves them into locales/en.json and translates them.
import compose from './compose/messages.en.json' with { type: 'json' };
import reader from './reader/messages.en.json' with { type: 'json' };
import profile from './profile/messages.en.json' with { type: 'json' };
import chat from './chat/messages.en.json' with { type: 'json' };
import media from './media/messages.en.json' with { type: 'json' };
import search from './search/messages.en.json' with { type: 'json' };
import notifications from './notifications/messages.en.json' with { type: 'json' };
import navigation from './navigation/messages.en.json' with { type: 'json' };
export const AREA_MESSAGES: Record<string, string> = {
...compose,
...reader,
...profile,
...chat,
...media,
...search,
...notifications,
...navigation,
};

View file

@ -0,0 +1,17 @@
// Every area's feature modules, for the X runtime (src/inject/entry.tsx defines them in the
// registry). Each area exports `MODULES` from src/areas/<area>/index.ts.
import type { FeatureModule } from '../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../inject/pluginApi.ts';
import { MODULES as COMPOSE } from './compose/index.ts';
import { MODULES as READER } from './reader/index.ts';
import { MODULES as PROFILE } from './profile/index.ts';
import { MODULES as CHAT } from './chat/index.ts';
import { MODULES as MEDIA } from './media/index.ts';
import { MODULES as SEARCH } from './search/index.ts';
import { MODULES as NOTIFICATIONS } from './notifications/index.ts';
import { MODULES as NAVIGATION } from './navigation/index.ts';
export const ALL_MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [
...COMPOSE, ...READER, ...PROFILE, ...CHAT, ...MEDIA, ...SEARCH, ...NOTIFICATIONS, ...NAVIGATION,
];

View file

@ -0,0 +1,94 @@
// Navigation+: the rules of its hide and layout features, one builder per flag. Pure (a string
// out), so the tests read them without a DOM. Selectors come from Control Panel for Twitter (MIT,
// see THIRD_PARTY_NOTICES.md) and live checks on x.com; they moved here from
// src/inject/features.ts (`buildFeatureCss`) unchanged.
import { sidebarModuleSelectors } from '../../inject/features.ts';
const hide = (selectors: string[]) => `${selectors.join(',\n')} {\n display: none !important;\n}`;
const SIDEBAR = '[data-testid="sidebarColumn"]';
/** An id no element has: it only lifts the full-width rules above a theme's layout rules (see fullWidthTimeline). */
export const FULL_WIDTH_ID = 'bt-navigation-full-width';
export const NAVIGATION_CSS = {
// Rail: Premium link (CPFT Selectors.PRIMARY_NAV_DESKTOP / PRIMARY_NAV_MOBILE)
hidePremiumNav: () => hide([
'header nav a:is([href^="/i/premium"], [href^="/i/verified"])',
'#layers nav a[href^="/i/premium"]',
'div[aria-labelledby="modal-header"] a[href^="/i/premium"]',
]),
// Rail: Chat/Messages link
hideChatNav: () => hide([
'header nav a[href$="/i/chat"]',
'#layers nav a[href="/i/chat"]',
]),
// Rail: Communities link
hideCommunitiesNav: () => hide([
'header nav a[href$="/communities"]',
'#layers nav a[href$="/communities"]',
'div[aria-labelledby="modal-header"] a[href$="/communities"]',
]),
// Rail: Grok link only (Grok inside posts is Reader+'s hideGrok)
hideGrokNav: () => hide([
'header nav a[href="/i/grok"]',
'#layers nav a[href="/i/grok"]',
'div[aria-labelledby="modal-header"] a[href$="/i/grok"]',
]),
// Right-column modules go with X's bordered card around them (sidebarModuleSelectors), so no empty
// box or double gap is left between the search field and the footer.
// Trends module (the `trend` testid inside its ARIA region landmark). Only in the right column:
// Explore's own trends are Search+'s hideExploreContent.
hideSidebarTrends: () => hide(sidebarModuleSelectors('section[role="region"]', '[data-testid="trend"]')),
// Who to follow module (the `UserCell` testid inside its complementary landmark)
hideWhoToFollow: () => hide([
'aside[role="complementary"]:has([data-testid="UserCell"])',
...sidebarModuleSelectors('aside[role="complementary"]', '[data-testid="UserCell"]'),
]),
// Live on X module (best-effort; English UI, module not always rendered)
hideLiveOnX: () => hide(sidebarModuleSelectors('aside[role="complementary"][aria-label="Live on X"]')),
// Today's News module (CPFT hideTodaysNews). Live 2026-10-01 the `news_sidebar` testid is only an
// empty impression tracker; the heading and the stories are its sibling inside the same card, so the
// card that holds it as a direct child goes (only that card: the NFL and other cards beside it stay).
hideTodaysNews: () => hide(['[data-testid="news_sidebar"]', ...sidebarModuleSelectors('[data-testid="news_sidebar"]'), `${SIDEBAR} div:has(> [data-testid="news_sidebar"])`]),
// Premium upsell card + hover-card upsell link (CPFT hideTwitterBlueUpsells)
hidePremiumUpsells: () => hide([
'aside[role="complementary"]:has(a[href^="/i/premium_sign_up"])',
...sidebarModuleSelectors('aside[role="complementary"]', 'a[href^="/i/premium_sign_up"]'),
'[data-testid="HoverCard"] a[href^="/i/premium"]',
]),
// "Relevant people" on post pages (route-scoped so hideWhoToFollow stays independent)
hideRelevantPeople: () => hide([
...sidebarModuleSelectors('aside', '[data-testid="UserCell"]', `html[data-bt-route="status"] ${SIDEBAR}`),
'aside[aria-label="Relevant people"]',
...sidebarModuleSelectors('aside[aria-label="Relevant people"]'),
]),
// The whole right column
hideSidebar: () => hide([SIDEBAR]),
// The main column takes the free width (X fixes it at 600px inside a 990px row). X's chat lays
// out its own row (inbox + conversation, by container query): widening it there squeezes the
// chat into half the pane and drops the inbox, so the chat row is left alone.
// A theme with a layout of its own (Classic Twitter: `[data-testid="primaryColumn"]:is(.r-…)
// { max-width: 590px !important }` and fixed row widths, seen live) is as !important and more
// specific, so these rules carry an id in `:is()` (FULL_WIDTH_ID, on no element): whoever turns
// this on gets the full width under every theme.
fullWidthTimeline: () => `
:is(main[role="main"], #${FULL_WIDTH_ID}) > div:not(:has(:is([data-testid="dm-container"], [data-testid="xchatEmbedRoute"]))), :is(main[role="main"], #${FULL_WIDTH_ID}) > div:not(:has(:is([data-testid="dm-container"], [data-testid="xchatEmbedRoute"]))) > div {
width: 100% !important;
max-width: none !important;
}
:is([data-testid="primaryColumn"], #${FULL_WIDTH_ID}) {
max-width: none !important;
flex-grow: 1 !important;
}`.trim(),
} as const satisfies Record<string, () => string>;
export type NavigationCssFlag = keyof typeof NAVIGATION_CSS;
/** The rules of every Navigation+ hide/layout flag that is on in `flags` (tests, the perf probe). */
export function navigationCss(flags: Readonly<Record<string, boolean | undefined>>): string {
return (Object.keys(NAVIGATION_CSS) as NavigationCssFlag[]).filter(flag => flags[flag]).map(flag => NAVIGATION_CSS[flag]()).join('\n\n');
}

View file

@ -0,0 +1,23 @@
// Navigation+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { modules, ported } from '../rows.ts';
export const FEATURES: readonly FeatureSpec[] = [
...modules('navigation', 'navigation', ['hidePremiumNav', 'hideChatNav', 'hideCommunitiesNav', 'hideGrokNav']),
...modules('navigation', 'sidebar', [
'hideSidebarTrends', 'hideWhoToFollow', 'hideLiveOnX', 'hideTodaysNews', 'hidePremiumUpsells',
{ id: 'hideRelevantPeople', surfaces: ['status'] },
'hideSidebar',
]),
...modules('navigation', 'layout', ['fullWidthTimeline']),
...modules('navigation', 'tools', [
ported('navigation.focusMode', 'focus-mode', { settings: true, keywords: 'Focus Mode distraction zen', permissions: ['storage', 'ui', 'commands'] }),
ported('navigation.keyboardPlus', 'keyboard-plus', { keywords: 'Keyboard Plus shortcuts keys', permissions: ['ui', 'clipboard'] }),
]),
];
/** Flags Power User turns on besides the defaults (this area's advanced features). */
export const POWER: readonly string[] = ['navigation.keyboardPlus'];

View file

@ -0,0 +1,117 @@
// Navigation+ · Focus Mode (was the Focus Mode plugin, 1.2.0). Hides what pulls you away from
// reading: like/repost/reply/view counts, trends, "Who to follow", follower counts or the whole
// right column. Alt+Shift+F turns it on and off. It only hides what X already shows, locally.
//
// Its settings stay where the plugin kept them (page storage `focus-mode` / `settings`), so an
// upgrade changes nothing for someone who used the plugin.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import { focalViewsParts, sidebarModuleSelectors, type ShapeNode } from '../../inject/features.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export type FocusSettings = { enabled: boolean; metrics: boolean; trends: boolean; whoToFollow: boolean; followCounts: boolean; sidebar: boolean };
export const FOCUS_SCHEMA: SettingsSchema = [
{ key: 'enabled', type: 'toggle', default: true, label: 'enabled' },
{ type: 'divider' },
{ key: 'metrics', type: 'toggle', default: true, label: 'metrics', hint: 'metricsHint' },
{ key: 'trends', type: 'toggle', default: true, label: 'trends' },
{ key: 'whoToFollow', type: 'toggle', default: true, label: 'whoToFollow' },
{ key: 'followCounts', type: 'toggle', default: false, label: 'followCounts' },
{ key: 'sidebar', type: 'toggle', default: false, label: 'sidebar', hint: 'sidebarHint' },
];
const VIEWS = 'data-bt-fm-views';
const VIEWS_SEP = 'data-bt-fm-views-sep';
const SIDE = '[data-testid="sidebarColumn"]';
const hide = (selectors: string[]) => `${selectors.join(',\n')} { display: none !important; }`;
/** The CSS for `settings` (empty when Focus Mode is off or hides nothing). Pure. */
export function focusCss(settings: FocusSettings): string {
if (!settings.enabled) return '';
const rules: string[] = [];
if (settings.metrics) {
// The numbers in each post's action bar (replies, reposts, likes, bookmarks, views); the buttons
// keep their place, so the bar does not jump.
rules.push('article[data-testid="tweet"] [role="group"] [data-testid="app-text-transition-container"] { visibility: hidden !important; }');
// The "· 1,234 Views" unit under an opened post, number, word and separator together (marked
// below; a views link outside the action bar is hidden even before it is marked).
rules.push(hide([
`article[data-testid="tweet"] [${VIEWS}]`,
`article[data-testid="tweet"] [${VIEWS_SEP}]`,
'article[data-testid="tweet"] a[href$="/analytics"]:not([role="group"] a)',
]));
// Quote / repost / like counts under an opened post: the number goes without leaving a gap; the
// word stays as the link to who quoted, reposted or liked.
rules.push(hide(['quotes', 'retweets', 'likes'].map(kind => `article[data-testid="tweet"] a[href$="/${kind}"] [data-testid="app-text-transition-container"]`)));
}
if (settings.sidebar) {
rules.push(`${SIDE} { visibility: hidden !important; }`);
} else {
if (settings.trends) {
rules.push(hide([
...sidebarModuleSelectors('section[role="region"]', '[data-testid="trend"]'),
...sidebarModuleSelectors('div[aria-label^="Timeline: Trending"]'),
`${SIDE} div:has(> [data-testid="trend"])`,
]));
}
if (settings.whoToFollow) rules.push(hide(sidebarModuleSelectors('aside[role="complementary"]', '[data-testid="UserCell"]')));
}
if (settings.followCounts) {
// Follower / following numbers on profiles and hover cards, without a gap; the words stay as
// the links to the lists. (`/<handle>/followers` links only: an @mention links to `/<handle>`,
// profile tabs are role="tab".)
const link = (kind: string) => `a[href$="/${kind}"]:not([href="/${kind}"]):not([role="tab"])`;
const kinds = ['followers', 'verified_followers', 'following'];
rules.push(hide(kinds.map(kind => `${link(kind)} > span:first-child`)));
// X's text keeps white space (pre-wrap): the " " before "Followers" would stay as a gap.
rules.push(`${kinds.map(link).join(', ')} { white-space: nowrap !important; }`);
}
return rules.join('\n');
}
export const focusMode: FeatureModule<PluginApi> = {
id: 'navigation.focusMode',
// The plugin's words and storage, kept: nothing is retranslated and no setting is lost.
words: 'focus-mode',
storage: 'focus-mode',
settings: FOCUS_SCHEMA,
start(ctx) {
const doc = ctx.win.document;
const current = () => ctx.settings.get() as FocusSettings;
const apply = () => ctx.css(focusCss(current()));
apply();
ctx.settings.onChange(apply);
// The views unit of an opened post (focal posts print "time · date" in one link). Re-marked when
// X re-renders the count (a new node) as well as when the date appears.
const markViews = (time: Element) => {
if (!(time.textContent ?? '').includes('·')) return;
const parts = focalViewsParts(time as unknown as ShapeNode);
if (!parts) return;
for (const el of parts.unit) (el as unknown as Element).setAttribute(VIEWS, '');
for (const el of parts.separators) (el as unknown as Element).setAttribute(VIEWS_SEP, '');
};
ctx.observe('article[data-testid="tweet"] a time, article[data-testid="tweet"] [data-testid="app-text-transition-container"]', node => {
const article = node.closest('article');
if (!article) return;
for (const time of article.querySelectorAll('a time')) markViews(time);
});
ctx.defer(() => {
for (const el of doc.querySelectorAll(`[${VIEWS}], [${VIEWS_SEP}]`)) {
el.removeAttribute(VIEWS);
el.removeAttribute(VIEWS_SEP);
}
});
// One toast for the latest state, not a stack of on/off/on.
let notice: { close(): void } | null = null;
const toggle = () => {
ctx.settings.set({ enabled: !current().enabled });
notice?.close();
notice = ctx.ui.toast(current().enabled ? ctx.text('on') : ctx.text('off'), { action: { label: ctx.text('settings'), onClick: () => ctx.settings.open() } });
};
ctx.command({ id: 'focusMode.toggle', title: ctx.text('toggle'), keywords: 'focus distraction hide counts trends sidebar alt shift f', shortcut: 'Alt+Shift+F', run: toggle });
},
};

View file

@ -0,0 +1,19 @@
// Navigation+: the rail, the right column, the layout, Focus Mode and the extra keys. The
// reference area (docs/AREA-PLUGINS.md): one module per feature of its rows (./features.ts),
// each started by the registry only while its flag is on, the area is on and the page is on one of
// its surfaces, and leaving nothing behind when it stops.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { NAVIGATION_CSS, type NavigationCssFlag } from './css.ts';
import { focusMode } from './focusMode.ts';
import { keyboardPlus } from './keyboardPlus.ts';
/** A hide or layout feature: one stylesheet while it is on. */
const cssFeature = (id: NavigationCssFlag): FeatureModule<PluginApi> => ({ id, start(ctx) { ctx.css(NAVIGATION_CSS[id]()); } });
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [
...(Object.keys(NAVIGATION_CSS) as NavigationCssFlag[]).map(cssFeature),
focusMode,
keyboardPlus,
];

View file

@ -0,0 +1,62 @@
// Navigation+ · Keyboard Plus (was the Keyboard Plus plugin, 1.1.0). Extra keys on the post
// focused with X's j/k: c copies its link, Shift+C its text, v opens its first photo or video,
// a opens the author's profile and q the quoted post. Only navigates or copies; never likes,
// reposts or posts.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
type Action = (article: Element) => void | Promise<void>;
/** The keys and what each does on a post. */
export function keyboardActions(ctx: Pick<FeatureContext<PluginApi>, 'api' | 'text' | 'win'>): Record<string, Action> {
const { api, text, win } = ctx;
const click = (element: Element | null | undefined) => {
if (!element) return false;
(element as HTMLElement).click();
return true;
};
return {
async c(article) {
const tweet = api.tweet(article);
if (tweet) api.toast(await api.copyText(tweet.url) ? text('linkCopied') : text('copyFailed'));
},
async C(article) {
const tweet = api.tweet(article);
if (tweet) api.toast(await api.copyText(tweet.text) ? text('textCopied') : text('copyFailed'));
},
v(article) {
// A quoted post is a `[role="link"]` card inside the article; its media is not this post's.
const own = (el: Element) => !el.closest('[role="link"]') || !article.contains(el.closest('[role="link"]'));
const photo = [...article.querySelectorAll('a[href*="/photo/"], a[href*="/video/"]')].find(own);
if (click(photo)) return;
const video = [...article.querySelectorAll('[data-testid="videoPlayer"], [data-testid="videoComponent"]')].find(own);
if (!click(video)) api.toast(text('noMedia'));
},
a(article) {
const tweet = api.tweet(article);
const link = article.querySelector('[data-testid="User-Name"] a[href^="/"]');
if (!click(link) && tweet) win.location.assign(`https://x.com/${tweet.handle}`);
},
q(article) {
if (!click(article.querySelector('[role="link"][tabindex]'))) api.toast(text('noQuote'));
},
};
}
export const keyboardPlus: FeatureModule<PluginApi> = {
id: 'navigation.keyboardPlus',
words: 'keyboard-plus',
// If timelines render cells but none is a post, X renamed the post: the keys have nothing to act on.
probes: { post: { selector: 'article[data-testid="tweet"]', when: '[data-testid="primaryColumn"] [data-testid="cellInnerDiv"] article' } },
start(ctx) {
const actions = keyboardActions(ctx);
ctx.onKey((event, article) => {
const action = Object.hasOwn(actions, event.key) ? actions[event.key] : undefined;
if (!action || !article) return;
event.preventDefault();
event.stopPropagation();
void action(article);
});
},
};

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,28 @@
// Notifications+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { app, modules, type Row } from '../rows.ts';
/** A new feature of this area: its words are `plugin.notifications-plus.feature.<name>.*` (./messages.en.json). */
const added = (name: string, extra: Omit<Exclude<Row, string>, 'id'> = {}): Row => ({
id: `notifications.${name}`, label: `plugin.notifications-plus.feature.${name}.label`, description: `plugin.notifications-plus.feature.${name}.description`,
// Everything here works on the Notifications timeline only.
surfaces: ['notifications'], ...extra,
});
export const FEATURES: readonly FeatureSpec[] = [
// The alerts themselves (keywords, on/off) stay in Settings; this flag is the plugin's hold on
// them: off (or the plugin off), no keyword is watched. Matching and the OS notification are the
// app's (src/inject/alerts.ts, this area's file, and native alerts.rs).
...app('notifications', '', [{ id: 'notifications.keywordAlerts', default: true }]),
...modules('notifications', '', [
added('kindFilters', { settings: true, keywords: 'filter hide likes reposts follows mentions replies', permissions: ['storage', 'ui', 'account'] }),
added('keywordHighlight', { keywords: 'highlight keyword alerts glow' }),
added('openMentions', { keywords: 'mentions tab default' }),
]),
];
/** Flags Power User turns on besides the defaults (this area's advanced features). */
export const POWER: readonly string[] = ['notifications.keywordHighlight'];

View file

@ -0,0 +1,11 @@
// Notifications+: its feature modules (docs/AREA-PLUGINS.md; Navigation+ in ../navigation is the reference).
// One module per `backing: 'module'` row of ./features.ts; the registry starts each only while its
// flag is on, the area is on and the page is on one of its surfaces.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { keywordHighlight } from './keywordHighlight.ts';
import { kindFilters } from './kindFilters.ts';
import { openMentions } from './openMentions.ts';
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [kindFilters, keywordHighlight, openMentions];

View file

@ -0,0 +1,82 @@
// Notifications+ · Keyword highlight. Marks the notifications that contain one of your alert
// keywords (the list of Settings, Keyword alerts): the row gets a coloured edge and the word itself
// is tinted. Read-only: it uses the keywords the app handed this page (src/inject/alerts.ts; they are
// there whether or not the alert itself is on), reads what X drew, stores nothing and tells nobody.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import { alertKeywords, matchKeyword, onAlertKeywords } from '../../inject/alerts.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { NOTIFICATION_ROWS } from './kindFilters.ts';
export const KEYWORD_ATTR = 'data-bt-notifications-keyword';
/** The name of the CSS highlight that tints the words (`::highlight(...)`): no node of X is changed. */
export const HIGHLIGHT = 'bt-notifications-keyword';
const CSS = `
article[${KEYWORD_ATTR}] { box-shadow: inset 3px 0 0 rgb(255, 212, 0), inset 0 0 28px rgba(255, 212, 0, .12) !important; }
::highlight(${HIGHLIGHT}) { background-color: rgba(255, 212, 0, .4); color: inherit; }
`;
/** The text a keyword is looked for in: a post row's own text, the whole row of a grouped notification. */
export function rowText(row: Element): string {
const scope = row.getAttribute('data-testid') === 'tweet' ? row.querySelector('[data-testid="tweetText"]') : row;
return scope?.textContent ?? '';
}
/** Where `keywords` occur in one piece of text: [start, end) pairs, in order, not overlapping. */
export function keywordSpans(text: string, keywords: readonly string[]): Array<[number, number]> {
const lower = text.toLowerCase();
// Lower-casing may change the length of some letters: then the offsets would not be the text's.
if (lower.length !== text.length) return [];
const spans: Array<[number, number]> = [];
for (const keyword of keywords) {
if (!keyword) continue;
for (let at = lower.indexOf(keyword); at >= 0; at = lower.indexOf(keyword, at + keyword.length)) spans.push([at, at + keyword.length]);
}
spans.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
let end = 0;
return spans.filter(span => { if (span[0] < end) return false; end = span[1]; return true; });
}
type HighlightWindow = { Highlight?: new (...ranges: Range[]) => unknown; CSS?: { highlights?: { set(name: string, value: unknown): void; delete(name: string): void } } };
export const keywordHighlight: FeatureModule<PluginApi> = {
id: 'notifications.keywordHighlight',
start(ctx) {
const { win } = ctx;
const doc = win.document;
const paint = win as unknown as HighlightWindow;
const registry = typeof paint.Highlight === 'function' ? paint.CSS?.highlights : undefined;
ctx.css(CSS);
const pass = () => {
const keywords = alertKeywords(win);
const ranges: Range[] = [];
for (const row of doc.querySelectorAll(NOTIFICATION_ROWS)) {
const hit = keywords.length ? matchKeyword(rowText(row), keywords) : null;
if (!hit) { if (row.hasAttribute(KEYWORD_ATTR)) row.removeAttribute(KEYWORD_ATTR); continue; }
if (row.getAttribute(KEYWORD_ATTR) !== hit) row.setAttribute(KEYWORD_ATTR, hit);
if (!registry) continue;
const scope = row.getAttribute('data-testid') === 'tweet' ? row.querySelector('[data-testid="tweetText"]') : row;
const walker = scope ? doc.createTreeWalker(scope, 4 /* NodeFilter.SHOW_TEXT */) : null;
for (let node = walker?.nextNode(); node; node = walker!.nextNode()) {
for (const [start, end] of keywordSpans(node.nodeValue ?? '', keywords)) {
const range = doc.createRange();
range.setStart(node, start);
range.setEnd(node, end);
ranges.push(range);
}
}
}
if (!registry) return;
if (ranges.length) registry.set(HIGHLIGHT, new paint.Highlight!(...ranges)); else registry.delete(HIGHLIGHT);
};
const watch = ctx.watch(pass, { characterData: true });
ctx.defer(onAlertKeywords(win, () => watch.schedule()));
pass();
ctx.defer(() => {
for (const row of doc.querySelectorAll(`[${KEYWORD_ATTR}]`)) row.removeAttribute(KEYWORD_ATTR);
registry?.delete(HIGHLIGHT);
});
},
};

View file

@ -0,0 +1,106 @@
// Notifications+ · Filters by kind. Hides the kinds of notifications you pick (likes, reposts, new
// followers, mentions, replies) in the Notifications timeline. Local and reversible: the rows are
// only hidden in this window; X still has them, and the Mentions tab is never filtered.
//
// The kind is read from the row's structure, never from its words, so it works in any language:
// - X's grouped rows (`article[data-testid="notification"]`) by their icon (the first drawing of
// the row: a heart, the repost arrows, a person);
// - post rows (`article[data-testid="tweet"]`): a reply carries X's "replying to @…" line (an
// @-link outside the author, the text and a quoted post); a mention links your handle in its text.
// A row that fits none of these is unknown, and unknown never hides.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema, SettingValues } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export const KINDS = ['like', 'repost', 'follow', 'mention', 'reply'] as const;
export type Kind = typeof KINDS[number];
/** Which kinds are hidden. Likes by default: the feature does something the moment it is turned on. */
export const KIND_SCHEMA: SettingsSchema = [
{ key: 'like', type: 'toggle', default: true, label: 'like' },
{ key: 'repost', type: 'toggle', default: false, label: 'repost' },
{ key: 'follow', type: 'toggle', default: false, label: 'follow' },
{ key: 'mention', type: 'toggle', default: false, label: 'mention' },
{ key: 'reply', type: 'toggle', default: false, label: 'reply' },
];
export const NOTIFICATION_ROWS = 'article[data-testid="notification"], article[data-testid="tweet"]';
export const KIND_ATTR = 'data-bt-notifications-kind';
/** How the icon of each kind of grouped row starts (the `d` of its first path, X's own icon set). */
export const KIND_ICONS: Readonly<Record<'like' | 'repost' | 'follow', readonly string[]>> = {
like: ['M20.884 13.19c-1.351 2.48'],
repost: ['M4.75 3.79l4.603 4.3'],
follow: ['M17.863 13.44c1.477 1.58'],
};
/** The kind an icon path stands for, or null. */
export function iconKind(d: string | null | undefined): Kind | null {
const path = (d ?? '').trim();
if (!path) return null;
for (const kind of ['like', 'repost', 'follow'] as const) if (KIND_ICONS[kind].some(prefix => path.startsWith(prefix))) return kind;
return null;
}
// Where an @-link of a post row is not a "replying to" line.
const NOT_REPLY_LINE = '[data-testid="User-Name"], [data-testid="tweetText"], [data-testid="socialContext"], [role="link"][tabindex]';
/**
* The kind of a notification row, or null when it cannot be told. `me` is the signed-in handle
* (null while X has not drawn the account button: then a mention is unknown).
*/
export function notificationKind(row: Element, me: string | null): Kind | null {
if (row.getAttribute('data-testid') === 'notification') return iconKind(row.querySelector('svg path')?.getAttribute('d'));
if (row.getAttribute('data-testid') !== 'tweet') return null;
const replying = [...row.querySelectorAll('a[href^="/"]')].some(link =>
(link.textContent ?? '').trim().startsWith('@') && !link.closest(NOT_REPLY_LINE));
if (replying) return 'reply';
if (!me) return null;
const mine = `/${me.toLowerCase()}`;
const mentioned = [...row.querySelectorAll('[data-testid="tweetText"] a[href^="/"]')].some(link =>
(link.getAttribute('href') ?? '').toLowerCase() === mine && !link.closest('[role="link"][tabindex]'));
return mentioned ? 'mention' : null;
}
/** The Mentions tab shows mentions and replies only: filtering it would empty it. */
export const filtersApply = (pathname: string) => !/^\/notifications\/mentions\/?$/.test(pathname);
/** The rule that hides the marked rows of the hidden kinds (empty when none is hidden). Pure. */
export function kindCss(settings: SettingValues, pathname: string): string {
if (!filtersApply(pathname)) return '';
const hidden = KINDS.filter(kind => settings[kind] === true);
// The row and the timeline cell around it (X measures the cell, so no gap is left).
const rows = hidden.flatMap(kind => [`[data-testid="cellInnerDiv"]:has(article[${KIND_ATTR}="${kind}"])`, `article[${KIND_ATTR}="${kind}"]`]);
return rows.length ? `${rows.join(',\n')} { display: none !important; }` : '';
}
export const kindFilters: FeatureModule<PluginApi> = {
id: 'notifications.kindFilters',
settings: KIND_SCHEMA,
start(ctx) {
const { win } = ctx;
const doc = win.document;
const apply = () => ctx.css(kindCss(ctx.settings.get(), win.location.pathname ?? ''));
apply();
ctx.settings.onChange(apply);
ctx.onRouteChange(apply);
// Each row is judged until its kind is known or known to be unknown, and carries the mark itself
// (a row X draws anew is a new element: a mark can never outlive what it described).
const judged = new WeakSet<Element>();
const pass = () => {
const me = ctx.api.account()?.handle ?? null;
for (const row of doc.querySelectorAll(NOTIFICATION_ROWS)) {
if (judged.has(row)) continue;
const kind = notificationKind(row, me);
if (kind) row.setAttribute(KIND_ATTR, kind);
// A post row stays open to a second look while the account is not known yet.
if (kind || me || row.getAttribute('data-testid') === 'notification') judged.add(row);
}
};
ctx.watch(pass);
pass();
ctx.defer(() => { for (const element of doc.querySelectorAll(`[${KIND_ATTR}]`)) element.removeAttribute(KIND_ATTR); });
},
};

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,29 @@
// Notifications+ · Open on Mentions. When you open Notifications, X's own Mentions tab is selected
// once (a navigation click, nothing else). Going back to "All" by hand stays on All: the feature
// only acts at the moment Notifications opens (the registry starts it when the page enters the
// notifications surface, and stops it when the page leaves).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
/** X's Mentions tab: the tab link to its own page. No words are read. */
export const MENTIONS_TAB = '[role="tablist"] a[role="tab"][href="/notifications/mentions"]';
/** Notifications' first tab ("All"): the only page the feature moves away from. */
export const isAllTab = (pathname: string) => /^\/notifications\/?$/.test(pathname);
export const openMentions: FeatureModule<PluginApi> = {
id: 'notifications.openMentions',
start(ctx) {
const { win } = ctx;
if (!isAllTab(win.location.pathname ?? '')) return;
let done = false;
// The user chose a tab (or left) before X drew the tabs: their choice stands.
ctx.onRouteChange(() => { done = true; });
ctx.observe(MENTIONS_TAB, tab => {
if (done) return;
done = true;
if (isAllTab(win.location.pathname ?? '')) (tab as HTMLElement).click();
});
},
};

View file

@ -0,0 +1,63 @@
// Profile+ · Account age. "9 y 2 mo" next to a profile's "Joined …" line. The creation time comes
// from the user object X already fetched for that profile (the runtime's passive cache,
// `api.users`): no request of its own, and X's rendered month is never parsed. When X has not sent
// it, nothing is shown: an age is never guessed.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import type { UsersApi } from '../../inject/userInfo.ts';
import { handleSpanOf } from './notes.ts';
export type Age = { years: number; months: number; days: number };
/** Whole calendar years and months (UTC) and whole days from `created` to `now`; null when `created` is ahead of `now`. */
export function ageOf(created: number, now: number): Age | null {
if (!Number.isFinite(created) || !Number.isFinite(now) || created > now) return null;
const from = new Date(created);
const to = new Date(now);
let months = (to.getUTCFullYear() - from.getUTCFullYear()) * 12 + to.getUTCMonth() - from.getUTCMonth();
if (to.getUTCDate() < from.getUTCDate()) months -= 1;
months = Math.max(0, months);
return { years: Math.floor(months / 12), months: months % 12, days: Math.floor((now - created) / 86_400_000) };
}
/** "9 y 2 mo", "9 y", "2 mo", "12 d", "today": the two largest units that are not zero. `text` reads this feature's words. */
export function ageText(age: Age, text: (key: string, params?: Record<string, number>) => string): string {
if (age.years > 0) return age.months > 0 ? text('yearsMonths', { years: age.years, months: age.months }) : text('years', { years: age.years });
if (age.months > 0) return text('months', { months: age.months });
return age.days > 0 ? text('days', { days: age.days }) : text('today');
}
const ATTR = 'data-bt-profile-age';
const JOINED = '[data-testid="primaryColumn"] [data-testid="UserJoinDate"]';
/**
* Writes the age onto every "Joined" line under `root` (an attribute the stylesheet prints after
* X's own text; X's nodes are not changed), and takes it off where the account's creation time is
* not known. The account is the one the same column's header names.
*/
export function applyAge(root: ParentNode, users: Pick<UsersApi, 'get'>, text: Parameters<typeof ageText>[1], now: number): void {
for (const joined of root.querySelectorAll(JOINED)) {
const handle = handleSpanOf(joined.closest('[data-testid="primaryColumn"]')?.querySelector('[data-testid="UserName"]'))?.handle;
const created = handle ? users.get(handle)?.createdAt ?? null : null;
const age = created === null ? null : ageOf(created, now);
const value = age ? ageText(age, text) : null;
if (value === null) joined.removeAttribute(ATTR);
else if (joined.getAttribute(ATTR) !== value) joined.setAttribute(ATTR, value);
}
}
export const accountAge: FeatureModule<PluginApi> = {
id: 'profile.accountAge',
start(ctx) {
const doc = ctx.win.document;
ctx.css(`[${ATTR}]::after { content: " · " attr(${ATTR}); white-space: pre; }`);
// X keeps the header mounted from profile to profile and fills it as responses arrive, so the
// line is re-read after every change of the page and whenever the cache learns something.
const watch = ctx.watch(() => applyAge(doc, ctx.api.users, ctx.text, Date.now()));
watch.schedule();
ctx.defer(ctx.api.users.onUpdate(() => watch.schedule()));
ctx.defer(ctx.api.i18n.onChange(() => watch.schedule()));
ctx.defer(() => { for (const joined of doc.querySelectorAll(`[${ATTR}]`)) joined.removeAttribute(ATTR); });
},
};

View file

@ -0,0 +1,32 @@
// Profile+: the rules of its two hide features, one builder per flag. Pure (a string out), so the
// tests read them without a DOM. They moved here unchanged from src/inject/features.ts
// (`buildFeatureCss`); selectors from Control Panel for Twitter (MIT, see THIRD_PARTY_NOTICES.md).
import { sidebarModuleSelectors } from '../../inject/features.ts';
const hide = (selectors: string[]) => `${selectors.join(',\n')} {\n display: none !important;\n}`;
const PROFILE = 'html[data-bt-route="profile"]';
export const PROFILE_CSS = {
// Profiles: follow suggestions in the sidebar and the ones X inserts into the profile timeline
// (`html[data-bt-route]` is set by the runtime).
hideProfileWhoToFollow: () => hide([
...sidebarModuleSelectors('aside', '[data-testid="UserCell"]', `${PROFILE} [data-testid="sidebarColumn"]`),
`${PROFILE} [data-testid="primaryColumn"] aside:has([data-testid="UserCell"])`,
`${PROFILE} [data-testid="primaryColumn"] [data-testid="cellInnerDiv"]:has([data-testid="UserCell"])`,
`${PROFILE} [data-testid="primaryColumn"] [data-testid="cellInnerDiv"]:has(a[href^="/i/connect_people"])`,
]),
// Posts/profiles: creator subscription buttons and prompts
hideSubscribeButtons: () => hide([
'a[href*="/creator-subscriptions/subscribe"]',
'button[data-testid$="-subscribe"]',
'a[data-testid$="-subscribe"]',
]),
} as const;
export type ProfileCssFlag = keyof typeof PROFILE_CSS;
/** The rules of the Profile+ hide flags that are on in `flags`, in table order (tests; the modules inject one sheet each). */
export function profileCss(flags: Readonly<Record<string, boolean | undefined>>): string {
return (Object.keys(PROFILE_CSS) as ProfileCssFlag[]).filter(flag => flags[flag] === true).map(flag => PROFILE_CSS[flag]()).join('\n\n');
}

View file

@ -0,0 +1,26 @@
// Profile+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { modules, ported } from '../rows.ts';
/** Where a name, a hover card or a profile's ··· menu can show: every page but X's chat and settings. */
const NAMES = ['profile', 'timeline', 'notifications', 'explore', 'composer', 'other'];
/** A new feature's row words: `plugin.profile-plus.feature.<name>.label` / `.description` (./messages.en.json). */
const words = (name: string) => ({ label: `plugin.profile-plus.feature.${name}.label`, description: `plugin.profile-plus.feature.${name}.description` });
export const FEATURES: readonly FeatureSpec[] = [
...modules('profile', '', [
// The two flags that were Tweaks: one rule each (./css.ts).
{ id: 'hideProfileWhoToFollow', surfaces: ['profile'] }, 'hideSubscribeButtons',
ported('profile.userNotes', 'user-notes', { surfaces: NAMES, keywords: 'User Notes private note', permissions: ['storage', 'ui'] }),
{ id: 'profile.privateLabels', ...words('privateLabels'), surfaces: NAMES, settings: true, keywords: 'label tag private', permissions: ['storage', 'ui', 'commands'] },
{ id: 'profile.accountAge', ...words('accountAge'), surfaces: ['profile'], keywords: 'joined age old', permissions: ['users'] },
{ id: 'profile.hoverPeek', ...words('hoverPeek'), surfaces: NAMES, settings: true, keywords: 'hover card peek follows you age note label', permissions: ['storage', 'account', 'users'] },
]),
];
/** Flags Power User turns on besides the defaults (this area's advanced features): they only add what is already known. */
export const POWER: readonly string[] = ['profile.privateLabels', 'profile.accountAge', 'profile.hoverPeek'];

View file

@ -0,0 +1,116 @@
// Profile+ · Hover card peek. A few more facts on X's own hover card, all from what is already in
// memory: the account's age and whether it follows you (the runtime's passive cache of the user
// objects X fetched, `api.users`), and your private label and note about it (User Notes' page
// storage). No request of its own. A fact that is not known is left out: a relationship X did not
// send is unknown, not "does not follow you".
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import type { UserInfo } from '../../inject/userInfo.ts';
import { ageOf, ageText, type Age } from './accountAge.ts';
import { LABEL_ATTR } from './privateLabels.ts';
import { NOTES_NAMESPACE, handleSpanOf, labelChipCss, readLabel, readNote, type Label } from './notes.ts';
export const PEEK_SCHEMA: SettingsSchema = [
{ key: 'age', type: 'toggle', default: true, label: 'showAge' },
{ key: 'relationship', type: 'toggle', default: true, label: 'showRelationship', hint: 'relationshipHint' },
{ key: 'note', type: 'toggle', default: true, label: 'showNote' },
];
export type PeekSettings = { age: boolean; relationship: boolean; note: boolean };
export type Relation = 'mutual' | 'followsYou' | 'notFollowingYou';
export type PeekFacts = { age: Age | null; relation: Relation | null; label: Label | null; note: string };
/** What the card may add about an account, from what is known. Pure. */
export function peekFacts(input: { user: Pick<UserInfo, 'createdAt' | 'following' | 'followedBy'> | null; self: boolean; label: Label | null; note: string; settings: PeekSettings; now: number }): PeekFacts {
const { user, settings } = input;
const followedBy = settings.relationship && !input.self ? user?.followedBy ?? null : null;
return {
age: settings.age && user && user.createdAt !== null ? ageOf(user.createdAt, input.now) : null,
relation: followedBy === null ? null : !followedBy ? 'notFollowingYou' : user?.following === true ? 'mutual' : 'followsYou',
label: settings.note ? input.label : null,
note: settings.note ? input.note : '',
};
}
const HOVER_CARD = '[data-testid="HoverCard"]';
const HOVER_PARTS = `${HOVER_CARD} [data-testid="UserDescription"], ${HOVER_CARD} [data-testid^="UserAvatar-Container-"]`;
const COLOR_ATTR = 'data-bt-profile-peek-color';
// Colors come from the active theme (`--wb-*`) with neutral fallbacks. What User Notes or Private
// labels already show on the same card is not shown twice.
export const PEEK_CSS = [
'.bt-profile-peek { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin-top: 8px;',
' font: 400 13px/1.4 var(--wb-font, system-ui, sans-serif); color: var(--wb-muted, inherit); }',
labelChipCss('.bt-profile-peek-label', '.bt-profile-peek-label', COLOR_ATTR),
'.bt-profile-peek-note { flex-basis: 100%; padding: 6px 8px; border-radius: 8px; background: rgba(255, 212, 0, .12);',
' color: var(--wb-text, inherit); white-space: pre-wrap; overflow-wrap: anywhere; }',
'.bt-profile-peek-note::before { content: attr(data-prefix); font-weight: 700; }',
`${HOVER_CARD}:has(.bt-note-hover) .bt-profile-peek-note, ${HOVER_CARD}:has([${LABEL_ATTR}]) .bt-profile-peek-label { display: none; }`,
].join('\n');
export const hoverPeek: FeatureModule<PluginApi> = {
id: 'profile.hoverPeek',
settings: PEEK_SCHEMA,
start(ctx) {
const doc = ctx.win.document;
const store = ctx.api.storage(NOTES_NAMESPACE);
const word = ctx.text;
// The age is worded by Account age's words: one set for both features.
const ageWords = ctx.api.i18n.namespace(ctx.area.namespace);
const element = (className: string, text: string) => {
const node = doc.createElement('span');
node.className = className;
node.textContent = text;
return node;
};
/** The card's block, rebuilt from what is known now; gone when nothing is. */
const render = (card: Element) => {
const old = card.querySelector('.bt-profile-peek');
const handle = handleSpanOf(card)?.handle ?? null;
const facts = handle ? peekFacts({
user: ctx.api.users.get(handle),
self: ctx.api.account()?.handle.toLowerCase() === handle,
label: readLabel(store, handle),
note: readNote(store, handle),
settings: ctx.settings.get() as PeekSettings,
now: Date.now(),
}) : null;
const parts: HTMLElement[] = [];
if (facts?.age) parts.push(element('bt-profile-peek-age', word('age', { age: ageText(facts.age, (key, params) => ageWords.t(`accountAge.${key}`, params)) })));
if (facts?.relation) parts.push(element('bt-profile-peek-relation', word(facts.relation)));
if (facts?.label) {
const chip = element('bt-profile-peek-label', facts.label.text);
chip.setAttribute(COLOR_ATTR, facts.label.color);
parts.push(chip);
}
if (facts?.note) {
const note = element('bt-profile-peek-note', facts.note);
note.dataset.prefix = word('notePrefix');
parts.push(note);
}
if (!handle || !parts.length) { old?.remove(); return; }
const block = (old as HTMLElement | null) ?? doc.createElement('div');
block.className = 'bt-profile-peek';
block.dataset.handle = handle;
block.textContent = '';
block.append(...parts);
if (old) return;
const anchor = card.querySelector('[data-testid="UserDescription"]') ?? card.querySelector('[data-testid^="UserAvatar-Container-"]');
if (anchor) anchor.after(block);
else card.append(block);
};
const renderAll = () => { for (const card of doc.querySelectorAll(HOVER_CARD)) render(card); };
ctx.css(PEEK_CSS);
// The card is there before its content: wait for a part that comes with the account.
ctx.observe(HOVER_PARTS, part => { const card = part.closest(HOVER_CARD); if (card) render(card); });
// X often fetches the account while the card is open: what it sends is added then.
ctx.defer(ctx.api.users.onUpdate(renderAll));
ctx.settings.onChange(renderAll);
ctx.defer(ctx.api.i18n.onChange(renderAll));
ctx.defer(() => { for (const block of doc.querySelectorAll('.bt-profile-peek')) block.remove(); });
},
};

View file

@ -0,0 +1,16 @@
// Profile+: its feature modules (docs/AREA-PLUGINS.md; Navigation+ in ../navigation is the reference).
// One module per `backing: 'module'` row of ./features.ts; the registry starts each only while its
// flag is on, the area is on and the page is on one of its surfaces.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { accountAge } from './accountAge.ts';
import { PROFILE_CSS, type ProfileCssFlag } from './css.ts';
import { hoverPeek } from './hoverPeek.ts';
import { privateLabels } from './privateLabels.ts';
import { userNotes } from './userNotes.ts';
/** A hide feature that is only its rule: one stylesheet while it is on. */
const cssFeature = (id: ProfileCssFlag): FeatureModule<PluginApi> => ({ id, start(ctx) { ctx.css(PROFILE_CSS[id]()); } });
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [cssFeature('hideProfileWhoToFollow'), cssFeature('hideSubscribeButtons'), userNotes, privateLabels, accountAge, hoverPeek];

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,118 @@
// Profile+ · what User Notes, Private labels and the hover card peek share: whose name a piece of
// X's page shows, and the owner's private words about that account. Notes and labels live in the
// page storage User Notes always used (`user-notes`): a note under the handle, as the plugin wrote
// it, and a label under `label:<handle>` beside it, so a note can carry a label and neither changes
// the other's shape. Local only: nothing here is sent anywhere or put into sync. Pure.
import type { PluginStorage } from '../../../../../waybetter/packages/runtime/src/pluginApi.ts';
/** The storage namespace of the User Notes plugin, kept. */
export const NOTES_NAMESPACE = 'user-notes';
const HANDLE = /^@([A-Za-z0-9_]{1,15})$/;
/** What these helpers read of an element (an `Element` has all of it; tests pass plain objects). */
export type NameNode = {
textContent: string | null;
parentElement: NameNode | null;
previousElementSibling: NameNode | null;
querySelectorAll(selector: string): Iterable<NameNode>;
closest(selector: string): NameNode | null;
getAttribute(name: string): string | null;
};
/**
* The handle a block of X's page names (lowercase): a span whose whole text is "@handle". A display
* name may itself be "@someone", so a span inside a link only counts when the link goes to that
* handle, a link that does is preferred, a bio (and what the hover card peek added) is never read,
* and without any link the last candidate wins (the handle follows the name).
* Returns the span too: a label goes beside the name above it.
*/
export function handleSpanOf(root: NameNode | null | undefined): { handle: string; span: NameNode } | null {
let last: { handle: string; span: NameNode } | null = null;
for (const span of root?.querySelectorAll('span') ?? []) {
const match = HANDLE.exec((span.textContent ?? '').trim());
if (!match || span.closest('[data-testid="UserDescription"], .bt-profile-peek')) continue;
const handle = match[1]!.toLowerCase();
const link = span.closest('a[href]');
if (link) {
const href = (link.getAttribute('href') ?? '').replace(/^https:\/\/(?:x|twitter)\.com/i, '').toLowerCase();
if (href === `/${handle}`) return { handle, span };
continue;
}
last = { handle, span };
}
return last;
}
/**
* The row that holds the display name: X puts the name and the "@handle" in two sibling rows, so it
* is the element just before the handle's row. `root` itself when the block is not shaped that way.
*/
export function nameRowOf(root: NameNode, span: NameNode): NameNode {
for (let node: NameNode | null = span; node && node !== root; node = node.parentElement) {
if (node.previousElementSibling) return node.previousElementSibling;
}
return root;
}
// ---- Notes and labels ----------------------------------------------------------------------------
export const LABEL_COLORS = ['gray', 'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink'] as const;
export type LabelColor = typeof LABEL_COLORS[number];
export type Label = { text: string; color: LabelColor };
/** A label is a tag, not a note: this many characters at most. */
export const LABEL_MAX = 24;
type Store = Pick<PluginStorage, 'get' | 'set' | 'remove'>;
/** The note about `handle` ('' when there is none). */
export function readNote(store: Store, handle: string): string {
const saved = store.get<unknown>(handle.toLowerCase(), '');
return typeof saved === 'string' ? saved : '';
}
/** One line of plain text: no control or direction-override characters, single spaces, at most `LABEL_MAX` characters. */
export function labelText(value: unknown): string {
if (typeof value !== 'string') return '';
const plain = value.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim();
return Array.from(plain).slice(0, LABEL_MAX).join('').trim();
}
/** A stored label, or null when what is stored is not one. */
export function normalizeLabel(raw: unknown): Label | null {
if (!raw || typeof raw !== 'object') return null;
const { text, color } = raw as Record<string, unknown>;
const clean = labelText(text);
if (!clean) return null;
return { text: clean, color: (LABEL_COLORS as readonly unknown[]).includes(color) ? color as LabelColor : 'gray' };
}
/** A handle can never contain ":", so a label's key never meets a note's. */
export const labelKey = (handle: string) => `label:${handle.toLowerCase()}`;
export const readLabel = (store: Store, handle: string): Label | null => normalizeLabel(store.get<unknown>(labelKey(handle), null));
/** Saves the label (an empty text removes it). False when storage refused it. */
export function writeLabel(store: Store, handle: string, label: { text: string; color: string } | null): boolean {
const next = normalizeLabel(label);
if (next) return store.set(labelKey(handle), next);
store.remove(labelKey(handle));
return true;
}
/** Each color as "r, g, b": readable as text and as a tint on a light and on a dark theme. */
const LABEL_RGB: Record<LabelColor, string> = {
gray: '128, 134, 140', red: '244, 33, 46', orange: '255, 122, 0', yellow: '214, 160, 0',
green: '0, 186, 124', blue: '29, 155, 240', purple: '120, 86, 255', pink: '249, 24, 128',
};
/** A label chip's look for `selector`, colored by the value of `attribute` on `host` (the chip itself or what carries it). */
export function labelChipCss(selector: string, host: string, attribute: string): string {
return [
`${selector} { display: inline-block; flex: 0 0 auto; padding: 0 6px; border-radius: 999px; white-space: nowrap;`,
' font: 700 11px/16px var(--wb-font, system-ui, sans-serif); color: rgb(var(--bt-profile-label, 128, 134, 140));',
' background: rgba(var(--bt-profile-label, 128, 134, 140), .14); border: 1px solid rgba(var(--bt-profile-label, 128, 134, 140), .45); }',
...LABEL_COLORS.map(color => `${host}[${attribute}="${color}"] { --bt-profile-label: ${LABEL_RGB[color]}; }`),
].join('\n');
}

View file

@ -0,0 +1,151 @@
// Profile+ · Private labels. A short tag of your own ("friend", "client", "press") beside an
// account's name: on its profile, on its posts and in its hover card. Set from the profile's ···
// menu or the palette. A label lives beside the account's note in User Notes' page storage
// (`user-notes`, key `label:<handle>`), on this device only: never sent, never in sync.
//
// The chip is drawn by the stylesheet from an attribute on X's own name row, so nothing is
// inserted into X's markup and stopping the feature only takes the attributes off.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginStorage } from '../../../../../waybetter/packages/runtime/src/pluginApi.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { ModalHandle } from '../../../../../waybetter/packages/runtime/src/ui.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { LABEL_COLORS, LABEL_MAX, NOTES_NAMESPACE, handleSpanOf, labelChipCss, nameRowOf, readLabel, writeLabel } from './notes.ts';
import { profileMenuItem } from './profileMenu.ts';
export const LABELS_SCHEMA: SettingsSchema = [
{ key: 'posts', type: 'toggle', default: true, label: 'posts', hint: 'postsHint' },
];
export const LABEL_ATTR = 'data-bt-profile-label';
const COLOR_ATTR = 'data-bt-profile-label-color';
const PROFILE_NAME = '[data-testid="primaryColumn"] [data-testid="UserName"]';
const POST_NAME = '[data-testid="User-Name"]';
const HOVER_CARD = '[data-testid="HoverCard"]';
const HOVER_PARTS = `${HOVER_CARD} [data-testid="UserDescription"], ${HOVER_CARD} [data-testid^="UserAvatar-Container-"]`;
const TAG = 'M3 3h8.59l9.7 9.7a1 1 0 0 1 0 1.42l-7.17 7.17a1 1 0 0 1-1.42 0L3 11.59V3zm2 2v5.76l8.41 8.41 5.76-5.76L10.76 5H5zm3 1.5a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3z';
// The auto margins keep the chip at its own size beside the name whether X lays the row out as a
// row (posts) or as a column (a hover card).
export const LABELS_CSS = [
labelChipCss(`[${LABEL_ATTR}]::after`, '', COLOR_ATTR),
`[${LABEL_ATTR}]::after { content: attr(${LABEL_ATTR}); margin: auto auto auto 6px; }`,
].join('\n');
/**
* Puts the label of the account `root` names onto its name row, and takes any label off that no
* longer belongs there (the account has none, or X reused the block for another account).
*/
export function markLabel(root: Element, store: Pick<PluginStorage, 'get' | 'set' | 'remove'>): void {
const found = handleSpanOf(root);
const label = found ? readLabel(store, found.handle) : null;
const row = found && label ? nameRowOf(root, found.span) as Element : null;
for (const old of [root, ...root.querySelectorAll(`[${LABEL_ATTR}]`)]) {
if (old === row || !old.hasAttribute(LABEL_ATTR)) continue;
old.removeAttribute(LABEL_ATTR);
old.removeAttribute(COLOR_ATTR);
}
if (!row || !label) return;
if (row.getAttribute(LABEL_ATTR) !== label.text) row.setAttribute(LABEL_ATTR, label.text);
if (row.getAttribute(COLOR_ATTR) !== label.color) row.setAttribute(COLOR_ATTR, label.color);
}
export const privateLabels: FeatureModule<PluginApi> = {
id: 'profile.privateLabels',
settings: LABELS_SCHEMA,
start(ctx) {
const doc = ctx.win.document;
const store = ctx.api.storage(NOTES_NAMESPACE);
const word = ctx.text;
let onPosts = ctx.settings.get().posts === true;
let editor: ModalHandle | null = null;
ctx.css(LABELS_CSS);
const mark = (root: Element) => markLabel(root, store);
const refresh = () => {
for (const name of doc.querySelectorAll(PROFILE_NAME)) mark(name);
for (const card of doc.querySelectorAll(HOVER_CARD)) mark(card);
if (onPosts) for (const name of doc.querySelectorAll(POST_NAME)) mark(name);
};
const clear = () => {
for (const row of doc.querySelectorAll(`[${LABEL_ATTR}]`)) {
row.removeAttribute(LABEL_ATTR);
row.removeAttribute(COLOR_ATTR);
}
};
ctx.observe(PROFILE_NAME, mark);
ctx.observe(POST_NAME, name => { if (onPosts) mark(name); });
// The card is there before its content: wait for a part that comes with the account.
ctx.observe(HOVER_PARTS, part => { const card = part.closest(HOVER_CARD); if (card) mark(card); });
ctx.settings.onChange(values => {
onPosts = values.posts === true;
clear();
refresh();
});
/** The label editor: a themed dialog from the UI kit (closed when the feature stops). */
const edit = (handle: string) => {
if (editor?.open) return;
const ui = ctx.ui;
const saved = readLabel(store, handle);
const input = ui.h('input', { type: 'text', maxLength: LABEL_MAX, placeholder: word('placeholder'), value: saved?.text ?? '' }) as HTMLInputElement;
const select = ui.h('select', null, LABEL_COLORS.map(color => ui.h('option', { value: color, selected: color === (saved?.color ?? 'gray') }, word(`color.${color}`)))) as HTMLSelectElement;
const save = (label: { text: string; color: string } | null) => {
const ok = writeLabel(store, handle, label);
if (ok) refresh();
return ok;
};
editor = ui.dialog({
title: word('title', { handle: `@${handle}` }),
message: word('message'),
width: 'sm',
initialFocus: input,
content: body => {
body.append(
ui.h('label', { class: 'wb-field' }, ui.h('span', { class: 'wb-label' }, word('text')), input),
ui.h('label', { class: 'wb-field' }, ui.h('span', { class: 'wb-label' }, word('color')), select),
);
},
actions: [
...(saved ? [{ label: word('remove'), tone: 'plain' as const, onClick: () => { save(null); ui.toast(word('removed')); } }] : []),
{ label: word('cancel') },
{
label: word('save'), tone: 'primary' as const, default: true,
onClick: (dialog: ModalHandle) => {
if (!save({ text: input.value, color: select.value })) { dialog.setError(word('saveFailed')); return false; }
return undefined;
},
},
],
});
};
const profileHandle = (name: Element | null) => handleSpanOf(name)?.handle ?? null;
profileMenuItem(ctx, {
kind: 'label', className: 'bt-profile-label-item', icon: TAG,
handle: profileHandle,
label: handle => (readLabel(store, handle) ? word('edit') : word('add')),
choose: edit,
});
ctx.command({
id: 'privateLabels.edit', title: word('command'), keywords: 'label tag private account profile',
run: () => {
const handle = profileHandle(doc.querySelector(PROFILE_NAME));
if (handle) edit(handle);
else ctx.api.toast(word('noProfile'));
},
});
// X keeps the profile header mounted across profile-to-profile navigation.
let timer = 0;
ctx.onRouteChange(() => {
refresh();
ctx.win.clearTimeout(timer);
timer = ctx.win.setTimeout(refresh, 800);
});
ctx.defer(() => ctx.win.clearTimeout(timer));
ctx.defer(clear);
},
};

View file

@ -0,0 +1,67 @@
// Profile+ · an item of our own in the ··· menu of the profile being visited (User Notes: "Add
// private note"; Private labels: "Add private label"). The way the User Notes plugin did it: a
// press on the profile's ··· button says whose menu X opens next in #layers, and the item is a
// copy of X's own first item (X's look, none of X's handlers). Choosing it closes X's menu the way
// a click outside it would; it never chooses one of X's items.
import type { FeatureContext } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
const PROFILE_NAME = '[data-testid="primaryColumn"] [data-testid="UserName"]';
/** Marks our items, so one feature's item is never the template (or the "already there") of another's. */
const ITEM = 'data-bt-profile-item';
export type ProfileMenuItem = {
/** Which feature's item (`note`, `label`): one per menu. */
kind: string;
/** Its class besides the ones X's item has. */
className: string;
/** The handle the profile header names. */
handle(name: Element | null): string | null;
label(handle: string): string;
/** The path of its icon (X's 24 px view box). */
icon: string;
choose(handle: string): void;
};
export function profileMenuItem(ctx: Pick<FeatureContext<PluginApi>, 'win' | 'on' | 'observe' | 'defer'>, item: ProfileMenuItem): void {
const doc = ctx.win.document;
let menuFor: string | null = null;
ctx.on(doc, 'pointerdown', event => {
const button = (event.target as Element | null)?.closest?.('[data-testid="primaryColumn"] [data-testid="userActions"]');
menuFor = button ? item.handle(doc.querySelector(PROFILE_NAME)) : null;
}, true);
ctx.observe('#layers [role="menu"]', menu => {
const handle = menuFor;
menuFor = null;
if (!handle || menu.querySelector(`[${ITEM}="${item.kind}"]`)) return;
const template = menu.querySelector(`[role="menuitem"]:not([${ITEM}])`);
if (!template) return;
const node = template.cloneNode(true) as HTMLElement;
node.classList.add(item.className);
node.setAttribute(ITEM, item.kind);
node.removeAttribute('data-testid');
node.removeAttribute('href');
node.setAttribute('role', 'menuitem');
node.setAttribute('tabindex', '0');
const label = [...node.querySelectorAll('span')].reverse().find(span => !span.children.length && (span.textContent ?? '').trim());
if (label) label.textContent = item.label(handle);
const path = node.querySelector('svg path');
if (path) {
for (const extra of [...node.querySelectorAll('svg path')].slice(1)) extra.remove();
path.setAttribute('d', item.icon);
}
const choose = (event: Event) => {
event.preventDefault();
event.stopPropagation();
const mask = doc.querySelector<HTMLElement>('#layers [data-testid="mask"]');
if (mask) mask.click();
else doc.dispatchEvent(new ctx.win.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
item.choose(handle);
};
node.addEventListener('click', choose, true);
node.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') choose(event); });
template.before(node);
});
ctx.defer(() => { for (const node of doc.querySelectorAll(`[${ITEM}="${item.kind}"]`)) node.remove(); });
}

View file

@ -0,0 +1,161 @@
// Profile+ · User Notes (was the User Notes plugin, 1.3.1). Private notes on accounts: "Add private
// note" in a profile's ··· menu opens a note editor; the note shows under the bio (click it to edit)
// and in hover cards. Notes stay in this app's local storage and are never sent anywhere.
//
// The notes stay where the plugin kept them (page storage `user-notes`, one key per handle), and
// the words are the plugin's own, so an upgrade changes nothing for someone who used it.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { ModalHandle } from '../../../../../waybetter/packages/runtime/src/ui.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { NOTES_NAMESPACE, handleSpanOf, readNote } from './notes.ts';
import { profileMenuItem } from './profileMenu.ts';
const PROFILE_NAME = '[data-testid="primaryColumn"] [data-testid="UserName"]';
const PENCIL = 'M14.23 2.854c.98-.977 2.56-.977 3.54 0l3.38 3.378c.97.977.97 2.559 0 3.536L9.91 20.999H3v-6.91L14.23 2.854zm2.12 1.414c-.19-.195-.51-.195-.7 0L5 14.917V19h4.08L19.73 8.354c.2-.196.2-.512 0-.708l-3.38-3.378zM14.75 19h6.25v2h-6.25v-2z';
// Colors come from the active theme (`--wb-*`, set by wayBetter on :root) with neutral fallbacks.
export const USER_NOTES_CSS = `
.bt-note { margin: 12px 0 4px; padding: 8px 12px; border-radius: 10px; cursor: pointer; white-space: pre-wrap; overflow-wrap: anywhere;
border: 1px dashed var(--wb-border, rgba(127,127,127,.5)); background: rgba(255, 212, 0, .08); color: var(--wb-text, inherit);
font: 400 14px/1.4 var(--wb-font, system-ui, sans-serif); }
.bt-note:hover { background: rgba(255, 212, 0, .14); }
.bt-note:focus-visible { outline: 2px solid var(--wb-accent, rgb(29,155,240)); outline-offset: 2px; }
.bt-note-label { display: block; margin-bottom: 2px; font-size: 12px; font-weight: 700; color: var(--wb-muted, inherit); }
.bt-note-hover { margin-top: 8px; padding: 6px 8px; border-radius: 8px; background: rgba(255, 212, 0, .12); white-space: pre-wrap;
font: 400 13px/1.4 var(--wb-font, system-ui, sans-serif); }
.bt-note-hover::before { content: attr(data-prefix); font-weight: 700; }
`;
export const userNotes: FeatureModule<PluginApi> = {
id: 'profile.userNotes',
// The plugin's words and storage, kept: nothing is retranslated and no note is lost.
words: 'user-notes',
storage: NOTES_NAMESPACE,
start(ctx) {
const doc = ctx.win.document;
const store = ctx.storage;
const word = ctx.text;
let editor: ModalHandle | null = null;
// Whose block it is, as the newer Profile+ features read it: a display name that looks like a
// handle, or an "@someone" in a bio, never borrows another account's note.
const handleOf = (root: Element | null) => handleSpanOf(root)?.handle ?? null;
ctx.css(USER_NOTES_CSS);
ctx.defer(ctx.api.i18n.onChange(() => {
for (const label of doc.querySelectorAll('.bt-note-label')) label.textContent = word('label');
for (const block of doc.querySelectorAll<HTMLElement>('.bt-note-hover')) block.dataset.prefix = word('hoverPrefix');
}));
// Profile header: a written note shows under the bio (or the name when there is no bio). Notes
// are written in a dialog opened from the profile's ··· menu or by clicking the note.
const mountProfile = (name: Element): Element | null => {
const handle = handleOf(name);
if (!handle) return null;
const anchor = name.parentElement?.querySelector('[data-testid="UserDescription"]') || name;
const column: ParentNode = name.closest('[data-testid="primaryColumn"]') || doc;
const saved = readNote(store, handle);
let current: Element | null = null;
for (const old of column.querySelectorAll<HTMLElement>('.bt-note')) {
if (!current && saved && old.dataset.handle === handle && old.previousElementSibling === anchor
&& old.querySelector('.bt-note-text')?.textContent === saved) current = old;
else old.remove();
}
if (current || !saved) return current;
const box = doc.createElement('div');
box.className = 'bt-note';
box.dataset.handle = handle;
box.tabIndex = 0;
box.setAttribute('role', 'button');
box.setAttribute('aria-label', word('boxLabel', { handle: `@${handle}` }));
const label = doc.createElement('span');
label.className = 'bt-note-label';
label.textContent = word('label');
const text = doc.createElement('span');
text.className = 'bt-note-text';
text.textContent = saved;
box.append(label, text);
box.addEventListener('click', event => { event.stopPropagation(); edit(handle); });
box.addEventListener('keydown', event => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
event.stopPropagation();
edit(handle);
});
anchor.after(box);
return box;
};
const refreshProfiles = () => { for (const name of doc.querySelectorAll(PROFILE_NAME)) mountProfile(name); };
/** The note editor: a themed dialog from the UI kit (closed when the feature stops). */
const edit = (handle: string) => {
if (editor?.open) return;
const ui = ctx.ui;
const saved = readNote(store, handle);
const area = ui.h('textarea', { rows: 5, maxLength: 4000, placeholder: word('placeholder'), 'aria-label': word('areaLabel', { handle: `@${handle}` }) }) as HTMLTextAreaElement;
area.value = saved;
const save = (text: string) => {
const ok = text.trim() ? store.set(handle, text) : (store.remove(handle), true);
if (ok) refreshProfiles();
return ok;
};
editor = ui.dialog({
title: word('title', { handle: `@${handle}` }),
message: word('message'),
content: area,
actions: [
...(saved ? [{
label: word('delete'), tone: 'plain' as const,
onClick: async () => {
const sure = await ui.confirm({ title: word('deleteTitle'), message: word('deleteMessage', { handle: `@${handle}` }), confirmLabel: word('delete'), danger: true });
if (!sure) return false;
save('');
ui.toast(word('deleted'));
return undefined;
},
}] : []),
{ label: word('cancel') },
{
label: word('save'), tone: 'primary' as const, default: true,
onClick: (dialog: ModalHandle) => {
if (!save(area.value)) { dialog.setError(word('saveFailed')); return false; }
return undefined;
},
},
],
});
};
const mountHover = (node: Element) => {
const card = node.closest('[data-testid="HoverCard"]');
if (!card || card.querySelector('.bt-note-hover')) return;
const handle = handleOf(card);
const note = handle && readNote(store, handle);
if (!note) return;
const block = doc.createElement('div');
block.className = 'bt-note-hover';
block.dataset.prefix = word('hoverPrefix');
block.textContent = note;
(card.querySelector('[data-testid="UserDescription"]') || node).after(block);
};
ctx.observe(PROFILE_NAME, name => { mountProfile(name); });
profileMenuItem(ctx, {
kind: 'note', className: 'bt-note-item', icon: PENCIL,
handle: handleOf,
label: handle => (readNote(store, handle) ? word('edit') : word('add')),
choose: edit,
});
ctx.observe('[data-testid="HoverCard"] [data-testid="UserDescription"], [data-testid="HoverCard"] [data-testid^="UserAvatar-Container-"]', mountHover);
// X keeps the profile header mounted across profile-to-profile navigation.
let timer = 0;
ctx.onRouteChange(() => {
refreshProfiles();
ctx.win.clearTimeout(timer);
timer = ctx.win.setTimeout(refreshProfiles, 800);
});
ctx.defer(() => ctx.win.clearTimeout(timer));
ctx.defer(() => { for (const node of doc.querySelectorAll('.bt-note, .bt-note-hover')) node.remove(); });
},
};

View file

@ -0,0 +1,51 @@
// Reader+ · Clean Links (was the Clean Links plugin, 1.0.1). Points t.co links in posts and
// profiles straight at the destination X already shows in the link text, strips common tracking
// parameters (utm_*, fbclid, gclid, ...) and shows the full URL on hover. No extra requests.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
const TRACKING = /^(utm_[a-z_]+|fbclid|gclid|dclid|gbraid|wbraid|msclkid|mc_cid|mc_eid|igshid|yclid|_hsenc|_hsmi|mkt_tok|ref_src|ref_url)$/i;
const SHORT = 'data-bt-tco';
const TITLED = 'data-bt-title';
/** The destination of a link whose text is the expanded URL (partly hidden, "…" when shortened), without tracking parameters; null when the text is not a URL. */
export function cleanDestination(linkText: string | null | undefined): string | null {
const text = (linkText || '').replace(/…$/, '').trim();
if (!/^https?:\/\/\S+$/.test(text)) return null;
try {
const url = new URL(text);
for (const key of [...url.searchParams.keys()]) if (TRACKING.test(key)) url.searchParams.delete(key);
return url.href;
} catch {
return null;
}
}
export const cleanLinks: FeatureModule<PluginApi> = {
id: 'reader.cleanLinks',
words: 'clean-links',
start(ctx) {
const doc = ctx.win.document;
ctx.observe('[data-testid="tweetText"] a[href^="https://t.co/"], [data-testid="UserUrl"] a[href^="https://t.co/"], [data-testid="UserDescription"] a[href^="https://t.co/"]', link => {
const target = cleanDestination(link.textContent);
if (!target) return;
link.setAttribute(SHORT, link.getAttribute('href')!);
link.setAttribute('href', target);
if (!link.hasAttribute('title')) {
link.setAttribute('title', target);
link.setAttribute(TITLED, '');
}
});
ctx.defer(() => {
for (const link of doc.querySelectorAll(`a[${SHORT}]`)) {
link.setAttribute('href', link.getAttribute(SHORT)!);
link.removeAttribute(SHORT);
if (link.hasAttribute(TITLED)) {
link.removeAttribute('title');
link.removeAttribute(TITLED);
}
}
});
},
};

View file

@ -0,0 +1,232 @@
// Reader+ · Collapse posts from verified accounts (was the Hide Blue Checks plugin, 1.2.1).
// Collapses posts from X Premium ("blue check") accounts into a one-line stub you can click to
// show, locally (nothing is muted on X itself). Optionally also Business- and Government-verified
// accounts. Never you, accounts you follow (default on; a post whose follow status is not known
// yet stays visible) or handles on your allowlist, and nothing until your own account is known.
// Posts are checked again when X's responses bring the missing details. Alt+Shift+H opens its
// settings.
//
// Owner decision (docs/AREA-PLUGINS.md, section 9), new with the port: a post by the owner of the
// profile page being visited (any of its tabs) is never collapsed, their quotes included, nor the
// post an opened post page is about. A post they reposted from someone else follows the normal
// rule. Leaving the page judges the posts on screen again.
//
// Its settings stay where the plugin kept them (page storage `hide-blue-checks` / `settings`).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import type { UserInfo } from '../../inject/userInfo.ts';
import { focalPost, visitedProfile } from './pages.ts';
export type CollapseSettings = { hideBlue: boolean; hideBusiness: boolean; hideGovernment: boolean; keepFollowed: boolean; hideQuotes: boolean; allowlist: string[] };
export const COLLAPSE_SCHEMA: SettingsSchema = [
{ key: 'hideBlue', type: 'toggle', default: true, label: 'hideBlue' },
{ key: 'hideBusiness', type: 'toggle', default: false, label: 'hideBusiness', hint: 'hideBusinessHint' },
{ key: 'hideGovernment', type: 'toggle', default: false, label: 'hideGovernment', hint: 'hideGovernmentHint' },
{ key: 'keepFollowed', type: 'toggle', default: true, label: 'keepFollowed', hint: 'keepFollowedHint' },
{ key: 'hideQuotes', type: 'toggle', default: false, label: 'hideQuotes' },
{ type: 'divider' },
{ key: 'allowlist', type: 'list', default: [], label: 'allowlist', maxLength: 16 },
];
export type CollapseContext = {
handle: string | null | undefined;
/** `null`: not observed this session. Unknown never hides: X's responses report absence, not a guaranteed "no". */
blue: boolean | null;
verifiedType: string | null;
following: boolean | null;
/** The signed-in handle; while it is unknown nothing is hidden, since the post could be yours. */
viewer: string | null | undefined;
/** The handle of the profile page being visited, if the page is one. */
profile?: string | null;
/** This post is the one the opened post page is about. */
focal?: boolean;
};
/** Pure decision, no DOM: whether a post by `ctx` should be collapsed under `settings`. */
export function shouldCollapse(settings: CollapseSettings, ctx: CollapseContext): boolean {
if (!ctx.viewer) return false;
const handle = String(ctx.handle || '').toLowerCase();
if (String(ctx.viewer).toLowerCase() === handle) return false;
// You came to read this post, or this account: it stays.
if (ctx.focal || (!!ctx.profile && ctx.profile.toLowerCase() === handle)) return false;
if ((settings.allowlist || []).some(h => String(h).toLowerCase() === handle)) return false;
// With "never hide accounts you follow" on, only a known "not following" can hide.
if (settings.keepFollowed && ctx.following !== false) return false;
const isBlue = ctx.blue === true;
const isBusiness = ctx.verifiedType === 'Business';
const isGovernment = ctx.verifiedType === 'Government';
return !!((settings.hideBlue && isBlue) || (settings.hideBusiness && isBusiness) || (settings.hideGovernment && isGovernment));
}
/** Whether a later response could change the decision for `user` (null = never seen). */
export function isUnknown(settings: Pick<CollapseSettings, 'keepFollowed'>, user: Pick<UserInfo, 'blue' | 'verifiedType' | 'following'> | null | undefined): boolean {
if (!user) return true;
return user.blue === null || user.verifiedType === null || (!!settings.keepFollowed && user.following === null);
}
/** Parses the allowlist (one @handle per line) into lowercase handles. */
export function parseAllowlist(source: unknown): string[] {
return [...new Set(String(source || '').split('\n')
.map(line => line.trim().replace(/^@/, '').toLowerCase())
.filter(line => /^[a-z0-9_]{1,15}$/.test(line)))];
}
const CSS = `
article[data-bt-hidden-check] { display: none !important; }
.bt-hbc-stub { padding: 10px 16px; font: 400 13px/1.3 var(--wb-font, system-ui, sans-serif); color: var(--wb-muted, inherit); opacity: .75; cursor: pointer;
border-bottom: 1px solid var(--wb-border, rgba(127,127,127,.2)); }
.bt-hbc-stub:hover { opacity: 1; }
`;
export const collapseVerified: FeatureModule<PluginApi> = {
id: 'reader.collapseVerified',
words: 'hide-blue-checks',
storage: 'hide-blue-checks',
settings: COLLAPSE_SCHEMA,
// If timelines render cells but none is a post, X renamed the post: there is nothing to judge.
probes: { post: { selector: 'article[data-testid="tweet"]', when: '[data-testid="primaryColumn"] [data-testid="cellInnerDiv"] article' } },
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
let settings: CollapseSettings;
const load = () => {
const saved = ctx.settings.get() as CollapseSettings;
settings = { ...saved, allowlist: parseAllowlist(saved.allowlist.join('\n')) };
};
// Posts decided while their author (or the viewer) was unknown, re-checked when X's responses
// bring that user: article -> lowercase handles it depends on ([] = any update).
const pending = new Map<Element, string[]>();
let dirty = new Set<string>();
let recheckFrame = 0;
// Stub id -> { article, stub }; stubs carry `data-bt-stub-for`, their post `data-bt-hbc-id`.
const stubs = new Map<string, { article: Element; stub: Element }>();
let stubSeq = 0;
/** The handle whose quote card is embedded in this post, or null when there is none. */
const quotedHandle = (article: Element) => {
const link = article.querySelector('div[role="link"] a[href^="/"][href*="/status/"]');
const match = /^\/([A-Za-z0-9_]{1,15})\/status\//.exec(link?.getAttribute('href') || '');
return match ? match[1]! : null;
};
/** `{ hit, unknown }` for a post by `handle`; `unknown`: a later response may change the answer. */
const decide = (handle: string | null, viewer: string | null, page: { profile: string | null; focal: boolean }) => {
if (!handle) return { hit: false, unknown: false };
const user = api.users.get(handle);
const hit = shouldCollapse(settings, {
handle,
blue: user?.blue ?? null,
verifiedType: user?.verifiedType ?? null,
following: user?.following ?? null,
viewer,
...page,
});
return { hit, unknown: !hit && (!viewer || isUnknown(settings, user)) };
};
/** Removes stubs whose post is no longer on the page (X recycles timeline cells). */
const sweepStubs = () => {
for (const [id, entry] of stubs) {
if (entry.article.isConnected && entry.stub.isConnected) continue;
entry.stub.remove();
stubs.delete(id);
}
};
const check = (article: Element) => {
sweepStubs();
if (article.hasAttribute('data-bt-hidden-check-shown')) return;
const id = article.getAttribute('data-bt-hbc-id');
if (id && stubs.has(id) && article.hasAttribute('data-bt-hidden-check')) return;
const tweet = api.tweet(article);
if (!tweet || !article.parentNode) return;
const viewer = api.account()?.handle ?? null;
const profile = visitedProfile(win.location.pathname);
const page = { profile, focal: focalPost(win.location.pathname) === tweet.id };
// The page's own subject stays whatever it quotes: the quoted author is not asked about.
const kept = page.focal || profile === tweet.handle.toLowerCase();
const quoted = settings.hideQuotes && !kept ? quotedHandle(article) : null;
const own = decide(tweet.handle, viewer, page);
const quote = quoted ? decide(quoted, viewer, { profile, focal: false }) : { hit: false, unknown: false };
if (!own.hit && !quote.hit) {
article.removeAttribute('data-bt-hidden-check');
if (!kept && (own.unknown || quote.unknown)) {
pending.set(article, viewer ? [tweet.handle, quoted].filter((h): h is string => !!h).map(h => h.toLowerCase()) : []);
}
return;
}
pending.delete(article);
article.setAttribute('data-bt-hidden-check', '');
const stubId = id || String(++stubSeq);
article.setAttribute('data-bt-hbc-id', stubId);
const stub = doc.createElement('div');
stub.className = 'bt-hbc-stub';
stub.setAttribute('data-bt-stub-for', stubId);
stub.textContent = ctx.text('stub');
stub.addEventListener('click', event => {
event.stopPropagation();
article.removeAttribute('data-bt-hidden-check');
article.setAttribute('data-bt-hidden-check-shown', '');
stub.remove();
stubs.delete(stubId);
});
article.before(stub);
stubs.set(stubId, { article, stub });
};
/** Every collapsed post comes back; `shown` too forgets which ones the reader opened by hand. */
const unhideAll = (shown: boolean) => {
for (const stub of doc.querySelectorAll('.bt-hbc-stub')) stub.remove();
stubs.clear();
pending.clear();
for (const article of doc.querySelectorAll('article[data-bt-hidden-check]')) article.removeAttribute('data-bt-hidden-check');
if (shown) for (const article of doc.querySelectorAll('article[data-bt-hidden-check-shown]')) article.removeAttribute('data-bt-hidden-check-shown');
};
const checkAll = () => { for (const article of doc.querySelectorAll(ctx.selector('post'))) check(article); };
const recheck = () => {
recheckFrame = 0;
const changed = dirty;
dirty = new Set();
for (const [article, handles] of [...pending]) {
if (!article.isConnected) { pending.delete(article); continue; }
if (handles.length && !handles.some(handle => changed.has(handle))) continue;
pending.delete(article);
check(article);
}
};
load();
ctx.css(CSS);
ctx.observe(ctx.selector('post'), check);
ctx.defer(api.users.onUpdate(handles => {
if (!pending.size) return;
for (const handle of handles) dirty.add(handle);
// Coalesced: one re-check per animation frame, however many responses arrive.
if (!recheckFrame) recheckFrame = win.requestAnimationFrame(recheck);
}));
ctx.defer(() => {
if (recheckFrame) win.cancelAnimationFrame(recheckFrame);
recheckFrame = 0;
});
// Another page: whose profile it is, or which post it is about, changed. X keeps some posts
// across a navigation, and those were judged for the page before.
ctx.onRouteChange(() => { unhideAll(false); checkAll(); });
ctx.settings.onChange(() => {
load();
unhideAll(true);
checkAll();
ctx.ui.toast(ctx.text('saved'), { tone: 'success' });
});
ctx.defer(api.i18n.onChange(() => { for (const stub of doc.querySelectorAll('.bt-hbc-stub')) stub.textContent = ctx.text('stub'); }));
ctx.defer(() => unhideAll(true));
// The plugin's own key, kept. (Its palette entry is the area's "Reader+ settings" now.)
ctx.on(doc, 'keydown', event => {
const key = event as KeyboardEvent;
if (key.altKey && key.shiftKey && !key.ctrlKey && !key.metaKey && key.code === 'KeyH') {
if (api.isTypingTarget(doc.activeElement)) return;
key.preventDefault();
key.stopPropagation();
ctx.settings.open();
}
}, true);
},
};

View file

@ -0,0 +1,82 @@
// Reader+ · Copy as Markdown (was the Copy as Markdown plugin, 1.2.1). A copy button on every
// post: click copies it as a Markdown quote (text, images, author, date and link), Shift+click
// copies plain text. With a post focused (j/k): m / Shift+M.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi, TweetInfo } from '../../inject/pluginApi.ts';
type Quoted = Pick<TweetInfo, 'text' | 'name' | 'handle' | 'url' | 'media'>;
/** A post as plain text: its text, then author, date and link. */
export function postPlainText(tweet: Quoted, date: string): string {
return `${tweet.text}\n\n— ${tweet.name} (@${tweet.handle}) ${date}\n${tweet.url}`.trim();
}
/** A post as a Markdown quote; `linkWord` stands in for a missing date. */
export function postMarkdown(tweet: Quoted, date: string, linkWord: string): string {
const body = tweet.text ? tweet.text.split('\n').map(line => `> ${line}`.trimEnd()) : [];
for (const src of tweet.media) body.push('>', `> ![](${src})`);
body.push('>', `> — ${tweet.name} ([@${tweet.handle}](https://x.com/${tweet.handle})) [${date || linkWord}](${tweet.url})`);
return body.join('\n');
}
const CSS = `
.bt-copy-md { display: inline-flex; flex: none; align-self: center; align-items: center; justify-content: center; min-width: 28px; height: 20px; padding: 0 5px; margin-right: 4px; box-sizing: border-box;
border: 0; border-radius: 999px; background: transparent; color: inherit; opacity: .55; cursor: pointer; font: 700 11px/1 system-ui, sans-serif; }
.bt-copy-md:hover { opacity: 1; background: rgba(29,155,240,.12); color: rgb(29,155,240); }
/* A phone-narrow pane or deck column has no room for a third header button: the post's time
would slide under it. m / Shift+M on a focused post still copy. */
@media (max-width: 420px) { .bt-copy-md { display: none; } }
`;
export const copyAsMarkdown: FeatureModule<PluginApi> = {
id: 'reader.copyAsMarkdown',
words: 'copy-as-markdown',
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
const date = (tweet: TweetInfo) => (tweet.time
? new Intl.DateTimeFormat(api.i18n.locale.split('-x-')[0], { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(tweet.time))
: '');
const copy = async (article: Element, plain: boolean) => {
const tweet = api.tweet(article);
if (!tweet) return;
const text = plain ? postPlainText(tweet, date(tweet)) : postMarkdown(tweet, date(tweet), ctx.text('link'));
api.toast(await api.copyText(text) ? (plain ? ctx.text('copiedText') : ctx.text('copiedMarkdown')) : ctx.text('copyFailed'));
};
ctx.css(CSS);
ctx.observe('article[data-testid="tweet"] [data-testid="caret"]', caret => {
const article = caret.closest('article[data-testid="tweet"]');
if (!article || !caret.parentElement) return;
// The button sits in the row with X's Grok and ··· buttons. Where ··· has a wrapper of its own
// that stacks its children (a column), it goes before that wrapper instead of on top of ···.
const wrapper = caret.parentElement;
const anchor = wrapper.parentElement && wrapper.childElementCount === 1 && win.getComputedStyle(wrapper).display.includes('flex')
&& win.getComputedStyle(wrapper).flexDirection.startsWith('column') ? wrapper : caret;
if (anchor.previousElementSibling?.classList.contains('bt-copy-md')) return;
const button = doc.createElement('button');
button.type = 'button';
button.className = 'bt-copy-md';
button.textContent = 'MD';
button.title = ctx.text('button');
button.setAttribute('aria-label', button.title);
button.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
void copy(article, event.shiftKey);
});
anchor.parentElement!.insertBefore(button, anchor);
});
ctx.onKey((event, article) => {
if (event.key.toLowerCase() !== 'm' || !article) return;
event.preventDefault();
void copy(article, event.shiftKey);
});
// The buttons' tooltips follow the app's language.
ctx.defer(api.i18n.onChange(() => {
for (const button of doc.querySelectorAll<HTMLElement>('.bt-copy-md')) { button.title = ctx.text('button'); button.setAttribute('aria-label', button.title); }
}));
ctx.defer(() => { for (const button of doc.querySelectorAll('.bt-copy-md')) button.remove(); });
},
};

View file

@ -0,0 +1,83 @@
// Reader+: the rules of its hide features, one builder per flag. Pure (a string out), so the tests
// read them without a DOM. Selectors come from Control Panel for Twitter (MIT, see
// THIRD_PARTY_NOTICES.md) and live checks on x.com; they moved here from src/inject/features.ts
// (`buildFeatureCss`). Three of them changed on the way (docs/AREA-PLUGINS.md, section 9):
// hideGrok also matches by the brand name and the Grok glyph, in any X language;
// hideBookmarkButton no longer depends on a body class nobody sets (./hideBookmarkButton.ts
// leaves the Bookmarks page alone);
// hideVerifiedBadges keeps the badge in the header of the profile being visited.
import { VIEWS_ATTR, VIEWS_SEP_ATTR } from '../../inject/features.ts';
const hide = (selectors: string[]) => `${selectors.join(',\n')} {\n display: none !important;\n}`;
/** How X's Grok glyph starts (`svg path[d]`): the same in every language. */
export const GROK_GLYPH = 'M2.205 7.423L11.745 21';
const GROK_BUTTON = `button:has(svg path[d^="${GROK_GLYPH}"])`;
export const READER_CSS = {
// Timeline: promoted posts (CPFT Selectors.PROMOTED_TWEET_CONTAINER). Only a placementTracking
// wrapper around a whole post is an ad: X also wraps ordinary video players in one (live,
// 2026-09-27), and hiding those left every such video an empty box.
hidePromotedPosts: () => hide([
'[data-testid="cellInnerDiv"]:has([data-testid="placementTracking"] article)',
'[data-testid="placementTracking"]:has(article)',
]),
// Timeline: "For you" tab, only on the home route (`html[data-bt-home]`, set by the runtime)
hideForYouTab: () => hide([
'html[data-bt-home] div[data-testid="primaryColumn"] div[role="tablist"] > div:first-child',
]),
// Posts: Grok actions/prompts/summaries attached to posts (CPFT hideGrokNav content selectors).
// The two labelled buttons are also found without their English label: "Grok" is a brand name X
// keeps in every language, and the glyph is the same everywhere.
hideGrok: () => hide([
'button[data-testid="grokImgGen"]',
'[data-testid="tweet"] [data-testid^="followups_"]',
'[data-testid="tweet"] [data-testid^="followups_"] + nav',
'[data-testid="tweet"] a[href="/i/grok"]',
'div[data-testid="GrokDrawer"]',
'button[aria-label="Grok Actions"]',
'button[aria-label="Profile Summary"]',
'[data-testid="tweet"] button[aria-label*="Grok" i]',
`[data-testid="tweet"] ${GROK_BUTTON}`,
`html[data-bt-route="profile"] [data-testid="primaryColumn"] ${GROK_BUTTON}`,
]),
// Posts: view counts (CPFT Selectors-derived analytics link under posts) and, on an opened post,
// the whole "· 1,234 Views" unit of its date line (marked by ./hideViewCounts.ts; a views link
// outside the action bar is hidden even before it is marked).
hideViewCounts: () => hide([
'[data-testid="tweet"][tabindex="0"] [role="group"] > div:has(> a[href$="/analytics"])',
'[aria-modal="true"] [role="group"] > div:has(> a[href$="/analytics"])',
`[data-testid="tweet"] [${VIEWS_ATTR}]`,
`[data-testid="tweet"] [${VIEWS_SEP_ATTR}]`,
'[data-testid="tweet"] a[href$="/analytics"]:not([role="group"] a)',
]),
// Posts: reply/repost/like counts (CPFT configureHideMetricsCss)
hideEngagementCounts: () => `
[role="group"] button:is([data-testid="reply"], [data-testid$="retweet"], [data-testid$="like"]) span {
visibility: hidden !important;
}`.trim(),
// Posts: bookmark button (CPFT hideBookmarkButton), in timelines and on an opened post
hideBookmarkButton: () => hide([
'[data-testid="tweet"][tabindex="0"] [role="group"] > div:has(> button[data-testid$="ookmark"])',
'[data-testid="tweet"][tabindex="-1"] [role="group"] > div:has(> button[data-testid$="ookmark"])',
]),
// Names: verified check marks (X's own `icon-verified` testid on the badge svg), except in the
// header of the profile being visited (its name block and the page's title bar).
hideVerifiedBadges: () => hide([
'svg[data-testid="icon-verified"]:not([data-testid="UserName"] svg):not(html[data-bt-route="profile"] [data-testid="primaryColumn"] h2 svg)',
]),
// Posts: disable bold/italic text formatting (CPFT disableTweetTextFormatting)
disableTweetTextFormatting: () => `
[data-testid="tweetText"] span {
font-style: normal;
font-weight: normal;
}`.trim(),
} as const;
export type ReaderCssFlag = keyof typeof READER_CSS;
/** The rules of the Reader+ hide flags that are on in `flags`, in table order (tests; the modules inject one sheet each). */
export function readerCss(flags: Readonly<Record<string, boolean | undefined>>): string {
return (Object.keys(READER_CSS) as ReaderCssFlag[]).filter(flag => flags[flag] === true).map(flag => READER_CSS[flag]()).join('\n\n');
}

View file

@ -0,0 +1,99 @@
// Reader+ · Exact Timestamps (was the Exact Timestamps plugin, 1.2.0). The full local date and
// time next to relative post times ("5h" becomes "5h · Sep 27, 2026, 14:03") and on hover. When the
// header is short on room the date gives way first (it shortens, then hides) and never covers X's
// buttons.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
// The date is its own flex item in X's header row (name · @handle · 2h | Grok ··· ). It shrinks
// a thousand times faster than X's name block, so a narrow header cuts the date (with an
// ellipsis, the full date stays in the tooltip) before it truncates the name, and X's buttons
// on the right never move or get covered.
const CSS = `
.bt-exact-time { flex: 0 1000 auto; min-width: 0; margin: 0 auto 0 4px; align-self: flex-start;
overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
font: 400 15px/20px var(--wb-font, inherit); color: var(--wb-muted, inherit); opacity: .85; }
.bt-exact-time.bt-exact-inline { margin-right: 0; }
`;
/**
* Where the date goes: right after the name block in the post's header row (the row that also
* holds X's Grok / ··· buttons), or, where a header has no buttons (quoted posts), right after the
* time's own box. Returns the node to insert after and whether it is the header row. ("Grok" is a
* brand name: the label holds it in every X language.)
*/
export function timePlacement(time: Element, style: (element: Element) => { flexDirection: string }): { after: Element; header: boolean } {
const article = time.closest('article');
const link = time.closest('a') || time;
const name = link.closest('[data-testid="User-Name"]');
// A quoted post (a role=link card inside the post) has no buttons of its own.
const quoted = link.closest('div[role="link"]');
if (name && article && !(quoted && article.contains(quoted))) {
// Nearest ancestor of the name block whose parent is a row that also holds X's header buttons.
let node: Element = name;
for (let depth = 0; depth < 6 && node.parentElement && node.parentElement !== article; depth += 1, node = node.parentElement) {
const row = node.parentElement;
if (!row.querySelector('[data-testid="caret"], button[aria-label*="Grok" i]')) continue;
if (node.querySelector('[data-testid="caret"]') || !style(row).flexDirection.startsWith('row')) break;
return { after: node, header: true };
}
}
// X keeps the time in a box that never shrinks; the date goes after that box (the outermost
// wrapper holding only the time), where it can shrink, not inside it.
let box: Element = link;
while (name && box.parentElement && box.parentElement !== name && box.parentElement.childElementCount === 1 && name.contains(box.parentElement)) box = box.parentElement;
return { after: box, header: false };
}
export const exactTimestamps: FeatureModule<PluginApi> = {
id: 'reader.exactTimestamps',
words: 'exact-timestamps',
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
// Dates in the app's language; a language switch redraws every date.
const formatter = () => new Intl.DateTimeFormat(api.i18n.locale.split('-x-')[0], { dateStyle: 'medium', timeStyle: 'short' });
let format = formatter();
const decorate = (time: Element) => {
const date = new Date(time.getAttribute('datetime')!);
if (Number.isNaN(date.getTime())) return;
const full = format.format(date);
// X renders post times without a title; stopping removes the one set here.
time.setAttribute('data-bt-exact', '');
time.setAttribute('title', full);
// The focused post on a post page already prints the full date ("2:03 PM · Sep 27, 2026").
if ((time.textContent || '').includes('·')) return;
const { after, header } = timePlacement(time, element => win.getComputedStyle(element));
if (!after.parentNode) return;
const text = `· ${full}`;
const next = after.nextElementSibling;
if (next?.classList.contains('bt-exact-time')) {
if (next.textContent !== text) next.textContent = text;
return;
}
// A header row keeps at most one date (X may re-render the name block next to an old one).
if (header) for (const old of after.parentNode.querySelectorAll(':scope > .bt-exact-time')) old.remove();
const span = doc.createElement('span');
span.className = header ? 'bt-exact-time' : 'bt-exact-time bt-exact-inline';
span.title = full;
span.textContent = text;
after.after(span);
};
ctx.css(CSS);
ctx.observe('article time[datetime]', decorate);
ctx.defer(api.i18n.onChange(() => {
format = formatter();
for (const time of doc.querySelectorAll('article time[data-bt-exact]')) decorate(time);
}));
// Per-element changes are marked in the DOM (no per-element closures that keep old nodes alive).
ctx.defer(() => {
for (const span of doc.querySelectorAll('.bt-exact-time')) span.remove();
for (const time of doc.querySelectorAll('time[data-bt-exact]')) {
time.removeAttribute('title');
time.removeAttribute('data-bt-exact');
}
});
},
};

View file

@ -0,0 +1,44 @@
// Reader+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { modules, ported } from '../rows.ts';
/** A feature that is new with Reader+: its row's words are the area's (`plugin.reader-plus.feature.<name>.*`). */
const added = (name: string, extra: { surfaces?: readonly string[]; settings?: boolean; keywords?: string; permissions?: readonly string[] } = {}) => ({
id: `reader.${name}`, label: `plugin.reader-plus.feature.${name}.label`, description: `plugin.reader-plus.feature.${name}.description`, ...extra,
});
export const FEATURES: readonly FeatureSpec[] = [
...modules('reader', 'timeline', [
{ id: 'hidePromotedPosts', default: true },
// Not bound to the home surface: its "once per page load" has to outlive a visit elsewhere.
'followingTimelineDefault',
{ id: 'hideForYouTab', surfaces: ['home'] },
added('readMarker', { surfaces: ['home'], settings: true, keywords: 'read marker left off position unread line', permissions: ['storage', 'ui', 'commands'] }),
added('languageFilter', { settings: true, keywords: 'language filter foreign translate collapse', permissions: ['storage', 'ui', 'account'] }),
]),
// Grok and the check marks also show outside posts (a drawer, names in chat): CSS only, so they stay on X's heavy pages.
...modules('reader', 'posts', [{ id: 'hideGrok', heavy: true }, 'hideViewCounts', 'hideEngagementCounts', 'hideBookmarkButton', 'disableTweetTextFormatting']),
...modules('reader', 'posts', [
// X's own request is rewritten (src/fixes/replySort.ts): the stage stays in place on every page.
{ id: 'sortRepliesRecent', heavy: true },
'fullNumbers',
{ id: 'hideVerifiedBadges', heavy: true },
ported('reader.cleanLinks', 'clean-links', { keywords: 'Clean Links t.co tracking utm' }),
ported('reader.copyAsMarkdown', 'copy-as-markdown', { keywords: 'Copy as Markdown quote', permissions: ['ui', 'clipboard'] }),
ported('reader.exactTimestamps', 'exact-timestamps', { keywords: 'Exact Timestamps date time' }),
{
...ported('reader.collapseVerified', 'hide-blue-checks', { settings: true, keywords: 'Hide Blue Checks verified premium collapse', permissions: ['storage', 'ui', 'account', 'users'] }),
label: 'plugin.reader-plus.feature.collapseVerified.label', description: 'plugin.reader-plus.feature.collapseVerified.description',
},
ported('reader.mutedRegex', 'muted-regex', { keywords: 'Muted Regex mute words patterns', permissions: ['storage', 'ui', 'commands'] }),
added('quickMute', { keywords: 'quick mute selection word pattern', permissions: ['storage', 'ui', 'commands'] }),
ported('reader.readingTime', 'reading-time', { keywords: 'Reading Time minutes long posts articles' }),
ported('reader.threadReader', 'thread-reader', { surfaces: ['status'], keywords: 'Thread Reader unroll', permissions: ['ui', 'clipboard', 'commands'] }),
]),
];
/** Flags Power User turns on besides the defaults (this area's advanced features): reading tools only, nothing that hides or collapses. */
export const POWER: readonly string[] = ['reader.readMarker', 'reader.cleanLinks', 'reader.copyAsMarkdown', 'reader.exactTimestamps', 'reader.readingTime', 'reader.threadReader'];

View file

@ -0,0 +1,26 @@
// Reader+ · Default to Following timeline. Once per page load, when Home opens on "For you", it
// selects X's own "Following" tab: one navigation click, by the tabs' position (the second tab), so
// it works in any X language. Not bound to the home surface: the "once" has to survive a visit to
// another page.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export const followingTimelineDefault: FeatureModule<PluginApi> = {
id: 'followingTimelineDefault',
start(ctx) {
const { win } = ctx;
let done = false;
const watch = ctx.watch(() => {
if (done || win.location.pathname !== '/home') return;
const tabs = win.document.querySelectorAll('div[data-testid="primaryColumn"] div[role="tablist"] [role="tab"]');
const forYou = tabs[0];
const following = tabs[1];
if (!forYou || !following) return;
done = true;
watch.dispose();
if (forYou.getAttribute('aria-selected') === 'true') (following as HTMLElement).click();
});
watch.schedule();
},
};

View file

@ -0,0 +1,55 @@
// Reader+ · Show full numbers. X abbreviates counts ("1.2K") but keeps the exact one in each
// action's aria-label ("1234 Likes. Like"); the abbreviated text node is rewritten in place (React
// keeps owning it) and X's text is remembered, so turning the feature off puts it back.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import { formatFullCount, fullCountFromLabel, isCompactCount } from '../../inject/features.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
const COUNT_ATTR = 'data-bt-count';
const TEXT_NODE = 3;
/**
* The exact count an action's label carries, in any X language: the number the label starts with
* (English and most languages), else the only number in it (languages that put the word first).
* A label with no number, or with several away from its start, gives null: the count stays as X wrote it.
*/
export function countFromLabel(label: string | null | undefined): number | null {
const leading = fullCountFromLabel(label);
if (leading != null) return leading;
const groups = (label ?? '').match(/\d{1,3}(?:[.,\s  ]\d{3})+|\d+/g) ?? [];
if (groups.length !== 1) return null;
const value = Number(groups[0]!.replace(/\D/g, ''));
return Number.isSafeInteger(value) ? value : null;
}
export const fullNumbers: FeatureModule<PluginApi> = {
id: 'fullNumbers',
start(ctx) {
const doc = ctx.win.document;
const patch = () => {
const locale = doc.documentElement.getAttribute('lang') || undefined;
const owners = doc.querySelectorAll('[role="group"] button[data-testid][aria-label], [role="group"] a[href$="/analytics"][aria-label]');
for (const owner of owners) {
const value = countFromLabel(owner.getAttribute('aria-label'));
if (value == null) continue;
for (const span of owner.querySelectorAll('span')) {
for (const node of Array.from(span.childNodes)) {
const text = node.nodeType === TEXT_NODE ? node.nodeValue : null;
if (text == null || !isCompactCount(text)) continue;
span.setAttribute(COUNT_ATTR, text);
node.nodeValue = formatFullCount(value, locale);
}
}
}
};
ctx.watch(patch).schedule();
ctx.defer(() => {
for (const span of doc.querySelectorAll(`[${COUNT_ATTR}]`)) {
const original = span.getAttribute(COUNT_ATTR)!;
for (const node of Array.from(span.childNodes)) if (node.nodeType === TEXT_NODE) node.nodeValue = original;
span.removeAttribute(COUNT_ATTR);
}
});
},
};

View file

@ -0,0 +1,16 @@
// Reader+ · Hide bookmark button. The bookmark action under posts goes, except on the Bookmarks
// page: there it is the only way to take a post off the list. (The old rule asked for a body class
// the app never sets, so it hid the button there too.)
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { READER_CSS } from './css.ts';
export const hideBookmarkButton: FeatureModule<PluginApi> = {
id: 'hideBookmarkButton',
start(ctx) {
const apply = () => ctx.css(ctx.surfaces().includes('bookmarks') ? '' : READER_CSS.hideBookmarkButton());
apply();
ctx.onRouteChange(apply);
},
};

View file

@ -0,0 +1,36 @@
// Reader+ · Hide view counts. The views in each post's action bar, and on an opened post the whole
// "· 1,234 Views" unit of its date line: that unit has no selector of its own, so it is marked here
// (`focalViewsParts`) and hidden by the rule in ./css.ts. Hiding just the number left "· Views".
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import { VIEWS_ATTR, VIEWS_SEP_ATTR, focalViewsParts, type ShapeNode } from '../../inject/features.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { READER_CSS } from './css.ts';
export const hideViewCounts: FeatureModule<PluginApi> = {
id: 'hideViewCounts',
start(ctx) {
const doc = ctx.win.document;
ctx.css(READER_CSS.hideViewCounts());
// Opened posts print "time · date" in one link; their date line may carry the views unit.
// Re-marked when X re-renders the count (a new node) as well as when the date appears.
const mark = (time: Element) => {
if (!(time.textContent ?? '').includes('·')) return;
const parts = focalViewsParts(time as unknown as ShapeNode);
if (!parts) return;
for (const el of parts.unit) if (el.getAttribute(VIEWS_ATTR) === null) (el as unknown as Element).setAttribute(VIEWS_ATTR, '');
for (const el of parts.separators) if (el.getAttribute(VIEWS_SEP_ATTR) === null) (el as unknown as Element).setAttribute(VIEWS_SEP_ATTR, '');
};
ctx.observe('article[data-testid="tweet"] a time, article[data-testid="tweet"] [data-testid="app-text-transition-container"]', node => {
const article = node.closest('article');
if (!article) return;
for (const time of article.querySelectorAll('a time')) mark(time);
});
ctx.defer(() => {
for (const el of doc.querySelectorAll(`[${VIEWS_ATTR}], [${VIEWS_SEP_ATTR}]`)) {
el.removeAttribute(VIEWS_ATTR);
el.removeAttribute(VIEWS_SEP_ATTR);
}
});
},
};

View file

@ -0,0 +1,45 @@
// Reader+: timelines, posts and threads. One module per `backing: 'module'` row of ./features.ts
// (docs/AREA-PLUGINS.md; Navigation+ in ../navigation is the reference); the registry starts each
// only while its flag is on, the area is on and the page is on one of its surfaces, and each leaves
// nothing behind when it stops.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { cleanLinks } from './cleanLinks.ts';
import { collapseVerified } from './collapseVerified.ts';
import { copyAsMarkdown } from './copyAsMarkdown.ts';
import { READER_CSS, type ReaderCssFlag } from './css.ts';
import { exactTimestamps } from './exactTimestamps.ts';
import { followingTimelineDefault } from './followingTimelineDefault.ts';
import { fullNumbers } from './fullNumbers.ts';
import { hideBookmarkButton } from './hideBookmarkButton.ts';
import { hideViewCounts } from './hideViewCounts.ts';
import { languageFilter } from './languageFilter.ts';
import { mutedRegex } from './mutedRegex.ts';
import { quickMute } from './quickMute.ts';
import { readMarker } from './readMarker.ts';
import { readingTime } from './readingTime.ts';
import { sortRepliesRecent } from './sortRepliesRecent.ts';
import { threadReader } from './threadReader.ts';
/** A hide feature that is only its rule: one stylesheet while it is on. */
const cssFeature = (id: ReaderCssFlag): FeatureModule<PluginApi> => ({ id, start(ctx) { ctx.css(READER_CSS[id]()); } });
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [
...(['hidePromotedPosts', 'hideForYouTab', 'hideGrok', 'hideEngagementCounts', 'hideVerifiedBadges', 'disableTweetTextFormatting'] as const).map(cssFeature),
hideViewCounts,
hideBookmarkButton,
followingTimelineDefault,
sortRepliesRecent,
fullNumbers,
cleanLinks,
copyAsMarkdown,
exactTimestamps,
collapseVerified,
mutedRegex,
quickMute,
readingTime,
threadReader,
readMarker,
languageFilter,
];

View file

@ -0,0 +1,125 @@
// Reader+ · Language filter. Collapses posts written in a language you did not list into a one-line
// stub you can click to show; with no language listed it collapses nothing. It reads the language X itself put on the post's text (`lang`), so
// nothing is detected or requested here. Unknown never hides: a post without text, a text too short
// to judge, or one X could not name a language for ("und", media-only, ...) stays. So do your own
// posts, the post an opened post page is about and the posts of the profile you are visiting.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { focalPost, visitedProfile } from './pages.ts';
export const LANGUAGE_SCHEMA: SettingsSchema = [
{ key: 'languages', type: 'list', default: [], label: 'languages', hint: 'languagesHint', maxItems: 40, maxLength: 12 },
];
/** Tags X uses when it has no language for a text (undetermined, no text, only media, mentions, tags or links). */
const NO_LANGUAGE = new Set(['', 'und', 'zxx', 'mul', 'mis', 'art', 'qme', 'qam', 'qct', 'qht', 'qst']);
/** Old and alternative codes for the same language, as X and readers write them. */
const SAME: Record<string, string> = { in: 'id', iw: 'he', ji: 'yi', nb: 'no', nn: 'no', fil: 'tl' };
/** Shorter texts are not judged: X's guess for a few words is often wrong. */
export const MIN_TEXT = 12;
/** The language of a tag ("pt-BR" -> "pt"), or '' when the tag names none. */
export function languageOf(tag: string | null | undefined): string {
const primary = String(tag ?? '').trim().toLowerCase().split(/[-_]/)[0]!;
if (NO_LANGUAGE.has(primary) || !/^[a-z]{2,3}$/.test(primary)) return '';
return SAME[primary] ?? primary;
}
/**
* The languages the reader listed, and only those. An empty list hides nothing: no language is
* guessed for the reader (the webview's `navigator.languages` is the engine's accept-language,
* en-US on a Turkish Windows as seen live, and folded the owner's own Turkish posts).
*/
export function readLanguages(list: ReadonlyArray<string>): Set<string> {
return new Set(list.map(languageOf).filter(Boolean));
}
/** Pure decision: collapse a post whose text is `text` in X's language tag `lang`? */
export function shouldCollapseLanguage(lang: string | null | undefined, text: string, read: ReadonlySet<string>): boolean {
const language = languageOf(lang);
if (!language || !read.size) return false;
if (text.trim().length < MIN_TEXT) return false;
return !read.has(language);
}
const HIDDEN = 'data-bt-reader-lang';
const SHOWN = 'data-bt-reader-lang-shown';
const CSS = `
article[${HIDDEN}] { display: none !important; }
.bt-reader-lang-stub { padding: 10px 16px; font: 400 13px/1.3 var(--wb-font, system-ui, sans-serif); color: var(--wb-muted, inherit); opacity: .75; cursor: pointer;
border-bottom: 1px solid var(--wb-border, rgba(127,127,127,.2)); }
.bt-reader-lang-stub:hover { opacity: 1; }
`.trim();
export const languageFilter: FeatureModule<PluginApi> = {
id: 'reader.languageFilter',
settings: LANGUAGE_SCHEMA,
// If timelines render cells but none is a post, X renamed the post: there is nothing to judge.
probes: { post: { selector: 'article[data-testid="tweet"]', when: '[data-testid="primaryColumn"] [data-testid="cellInnerDiv"] article' } },
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
const texts = `${ctx.selector('post')} [data-testid="tweetText"]`;
const read = () => readLanguages(ctx.settings.get().languages as string[]);
let languages = read();
// Stub -> its post, to drop the stubs of posts X took off the page (it recycles timeline cells).
const stubs = new Map<Element, Element>();
const nameOf = (language: string) => {
try { return new Intl.DisplayNames([api.i18n.locale.split('-x-')[0]!], { type: 'language' }).of(language) ?? language; } catch { return language; }
};
const sweep = () => {
for (const [stub, article] of stubs) {
if (article.isConnected && stub.isConnected) continue;
stub.remove();
stubs.delete(stub);
}
};
const check = (text: Element) => {
sweep();
const article = text.closest(ctx.selector('post'));
if (!article?.parentNode || article.hasAttribute(HIDDEN) || article.hasAttribute(SHOWN)) return;
// A quoted post's text (a role=link card inside the post) is not this post's.
const card = text.closest('[role="link"]');
if (card && article.contains(card)) return;
if (!shouldCollapseLanguage(text.getAttribute('lang'), text.textContent ?? '', languages)) return;
const tweet = api.tweet(article);
if (!tweet) return;
// While the signed-in account is unknown nothing is collapsed: the post could be yours.
const viewer = api.account()?.handle.toLowerCase();
const author = tweet.handle.toLowerCase();
const path = win.location.pathname;
if (!viewer || author === viewer || author === visitedProfile(path) || tweet.id === focalPost(path)) return;
article.setAttribute(HIDDEN, '');
const stub = doc.createElement('div');
stub.className = 'bt-reader-lang-stub';
stub.textContent = ctx.text('stub', { language: nameOf(languageOf(text.getAttribute('lang'))) });
stub.addEventListener('click', event => {
event.stopPropagation();
article.removeAttribute(HIDDEN);
article.setAttribute(SHOWN, '');
stub.remove();
stubs.delete(stub);
});
article.before(stub);
stubs.set(stub, article);
};
/** Every collapsed post comes back; `shown` too forgets which ones the reader opened by hand. */
const unhideAll = (shown: boolean) => {
for (const stub of doc.querySelectorAll('.bt-reader-lang-stub')) stub.remove();
stubs.clear();
for (const article of doc.querySelectorAll(`article[${HIDDEN}]`)) article.removeAttribute(HIDDEN);
if (shown) for (const article of doc.querySelectorAll(`article[${SHOWN}]`)) article.removeAttribute(SHOWN);
};
const checkAll = () => { for (const text of doc.querySelectorAll(texts)) check(text); };
ctx.css(CSS);
ctx.observe(texts, check);
// Another page: whose profile it is, or which post it is about, changed.
ctx.onRouteChange(() => { unhideAll(false); checkAll(); });
ctx.settings.onChange(() => { languages = read(); unhideAll(true); checkAll(); });
ctx.defer(() => unhideAll(true));
},
};

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,147 @@
// Reader+ · Muted Regex (was the Muted Regex plugin, 1.2.0). Collapses posts whose text, author
// name or @handle matches your regular expressions, locally (X's own mute list is untouched).
// Alt+Shift+M edits the list: one pattern per line, "/pattern/flags" or plain (case-insensitive),
// "#" for comments. A collapsed post leaves a one-line stub you can click to show.
//
// The list stays where the plugin kept it (page storage `muted-regex` / `patterns`, the editor's
// text as one string), so it has its own editor instead of a generated settings form. Quick mute
// (./quickMute.ts) adds lines to the same list and says so with `MUTED_CHANGED`.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export const MUTED_STORE = 'muted-regex';
export const MUTED_KEY = 'patterns';
/** Dispatched on the document after the stored list changed; a running Muted Regex sets `detail.handled`. */
export const MUTED_CHANGED = 'bt-reader-muted-changed';
export type MutedPattern = { source: string; pattern: RegExp };
/** Parses the editor text into RegExps; invalid lines are returned separately instead of throwing. */
export function parsePatterns(source: unknown): { patterns: MutedPattern[]; invalid: string[] } {
const patterns: MutedPattern[] = [];
const invalid: string[] = [];
for (const raw of String(source || '').split('\n')) {
const line = raw.trim();
if (!line || line.startsWith('#')) continue;
const literal = /^\/(.+)\/([a-z]*)$/.exec(line);
try {
// "g"/"y" make .test() stateful; they are dropped.
const pattern = literal ? new RegExp(literal[1]!, literal[2]!.replace(/[gy]/g, '')) : new RegExp(line, 'i');
patterns.push({ source: line, pattern });
} catch {
invalid.push(line);
}
}
return { patterns, invalid };
}
/** What the patterns are matched against: the @handle, the name, the text and any quoted text. */
export const mutedHaystack = (tweet: { handle: string; name: string; text: string }, quoted: string) => `@${tweet.handle}\n${tweet.name}\n${tweet.text}\n${quoted}`;
const CSS = `
article[data-bt-muted] { display: none !important; }
.bt-muted-stub { padding: 10px 16px; font: 400 13px/1.3 var(--wb-font, system-ui, sans-serif); color: var(--wb-muted, inherit); opacity: .75; cursor: pointer;
border-bottom: 1px solid var(--wb-border, rgba(127,127,127,.2)); }
.bt-muted-stub:hover { opacity: 1; }
`;
export const mutedRegex: FeatureModule<PluginApi> = {
id: 'reader.mutedRegex',
words: 'muted-regex',
storage: MUTED_STORE,
// If timelines render cells but none is a post, X renamed the post: there is nothing to match.
probes: { post: { selector: 'article[data-testid="tweet"]', when: '[data-testid="primaryColumn"] [data-testid="cellInnerDiv"] article' } },
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
let source = '';
let patterns: MutedPattern[] = [];
const load = () => {
source = ctx.storage.get(MUTED_KEY, '');
patterns = parsePatterns(source).patterns;
};
const unhideAll = () => {
for (const stub of doc.querySelectorAll('.bt-muted-stub')) stub.remove();
for (const article of doc.querySelectorAll('article[data-bt-muted], article[data-bt-muted-shown]')) {
article.removeAttribute('data-bt-muted');
article.removeAttribute('data-bt-muted-shown');
}
};
const match = (article: Element) => {
const tweet = api.tweet(article);
if (!tweet) return null;
const quoted = Array.from(article.querySelectorAll('[data-testid="tweetText"]'), node => node.textContent || '').join('\n');
const haystack = mutedHaystack(tweet, quoted);
return patterns.find(({ pattern }) => pattern.test(haystack)) || null;
};
const check = (article: Element) => {
if (!patterns.length || article.hasAttribute('data-bt-muted-shown')) return;
const hit = match(article);
if (!hit || !article.parentNode) return;
article.setAttribute('data-bt-muted', '');
const stub = doc.createElement('div');
stub.className = 'bt-muted-stub';
stub.textContent = ctx.text('stub', { pattern: hit.source });
stub.addEventListener('click', event => {
event.stopPropagation();
article.removeAttribute('data-bt-muted');
article.setAttribute('data-bt-muted-shown', '');
stub.remove();
});
article.before(stub);
};
/** The list changed: every post on screen is judged again. */
const reload = () => {
load();
unhideAll();
for (const article of doc.querySelectorAll(ctx.selector('post'))) check(article);
};
/** The pattern editor, a themed dialog from the UI kit (closed when the feature stops). */
let editor: ReturnType<typeof ctx.ui.dialog> | null = null;
const openEditor = () => {
if (editor?.open) return;
const ui = ctx.ui;
const area = ui.h('textarea', { class: 'wb-mono', rows: 10, spellcheck: false, 'aria-label': ctx.text('patternsLabel'), placeholder: 'crypto giveaway\n/^@spam_bot$/m' }) as HTMLTextAreaElement;
area.value = source;
const dialog = ui.dialog({
title: ctx.text('title'),
message: ctx.text('message'),
width: 560,
content: area,
actions: [
{ label: ctx.text('cancel') },
{
label: ctx.text('save'), tone: 'primary',
onClick: handle => {
if (!ctx.storage.set(MUTED_KEY, area.value)) { handle.setError(ctx.text('saveFailed')); return false; }
reload();
api.toast(ctx.text('active', { count: patterns.length }));
return undefined;
},
},
],
});
editor = dialog;
area.addEventListener('input', () => {
const { invalid } = parsePatterns(area.value);
dialog.setError(invalid.length ? ctx.text('invalid', { patterns: invalid.join(', ') }) : null);
});
};
load();
ctx.css(CSS);
ctx.observe(ctx.selector('post'), check);
ctx.on(doc, MUTED_CHANGED, event => {
const detail = (event as CustomEvent<{ handled?: boolean } | null>).detail;
if (detail) detail.handled = true;
reload();
});
ctx.defer(unhideAll);
// The plugin listened for Alt+Shift+M itself; as a command the palette lists it too. Its title
// is a new word, so it is the area's (`plugin.reader-plus.mutedRegex.edit`), not the plugin's.
const words = api.i18n.namespace(ctx.area.namespace);
ctx.command({ id: 'mutedRegex.edit', title: words.t(`${ctx.name}.edit`), keywords: 'muted regex mute patterns words filter alt shift m', shortcut: 'Alt+Shift+M', run: openEditor });
},
};

View file

@ -0,0 +1,16 @@
// Reader+: which page a path is, for the features that treat the page's own subject differently
// (the visited profile's owner, the post an opened post page is about). Pure.
import { routeKind } from '../../fixes/route.ts';
/** The handle (lowercase) of the profile a path shows, on any of its tabs, or null. */
export function visitedProfile(pathname: string): string | null {
if (routeKind(pathname) !== 'profile') return null;
return /^\/([A-Za-z0-9_]{1,15})/.exec(pathname)![1]!.toLowerCase();
}
/** The id of the post an opened post page is about (its photo or video viewer included), or null. */
export function focalPost(pathname: string): string | null {
const match = /^\/[A-Za-z0-9_]{1,15}\/status\/(\d+)(?:\/|$)/.exec(pathname);
return match ? match[1]! : null;
}

View file

@ -0,0 +1,69 @@
// Reader+ · Quick mute. Select a word or a phrase on the page and press Alt+Shift+U (or run the
// command): the selection is added, as literal text, to Muted Regex's local list (page storage
// `muted-regex` / `patterns`), with an Undo. Nothing is muted on X itself. Posts are collapsed by
// Muted Regex (./mutedRegex.ts): when that feature is off the toast says so.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { MUTED_CHANGED, MUTED_KEY, MUTED_STORE } from './mutedRegex.ts';
export const QUICK_MUTE_LIMITS = Object.freeze({ min: 2, max: 120 });
/**
* The list line for a selection: one line, white space collapsed, every character literal (the
* list's lines are regular expressions; a leading "#" would be a comment). Null when the selection
* is too short, too long or empty.
*/
export function quickMuteLine(selection: string | null | undefined): string | null {
const text = String(selection ?? '').replace(/\s+/g, ' ').trim();
if (text.length < QUICK_MUTE_LIMITS.min || text.length > QUICK_MUTE_LIMITS.max) return null;
return text.replace(/[\\^$.*+?()[\]{}|/#]/g, '\\$&').replace(/ /g, '\\s+');
}
/** The list with `line` added at its end, or null when it already has that line. */
export function appendPattern(source: string, line: string): string | null {
const lines = source.split('\n').map(item => item.trim());
if (lines.includes(line)) return null;
return source && !source.endsWith('\n') ? `${source}\n${line}\n` : `${source}${line}\n`;
}
export const quickMute: FeatureModule<PluginApi> = {
id: 'reader.quickMute',
// Muted Regex's list, not a store of its own.
storage: MUTED_STORE,
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
/** Tells a running Muted Regex that the list changed; true when there is one. */
const announce = () => {
const detail = { handled: false };
try { doc.dispatchEvent(new win.CustomEvent(MUTED_CHANGED, { detail })); } catch { /* no events here: the list is saved all the same */ }
return detail.handled;
};
const write = (source: string) => ctx.storage.set(MUTED_KEY, source);
let notice: { close(): void } | null = null;
const add = () => {
notice?.close();
const shown = String(win.getSelection?.()?.toString() ?? '').replace(/\s+/g, ' ').trim();
if (!shown) { api.toast(ctx.text('none')); return; }
const line = quickMuteLine(shown);
if (!line) { api.toast(ctx.text('length', QUICK_MUTE_LIMITS)); return; }
const before = ctx.storage.get(MUTED_KEY, '');
const after = appendPattern(before, line);
if (after === null) { api.toast(ctx.text('exists', { text: shown })); return; }
if (!write(after)) { api.toast(ctx.text('failed')); return; }
const active = announce();
notice = ctx.ui.toast(ctx.text(active ? 'added' : 'addedOff', { text: shown }), {
action: {
label: ctx.text('undo'),
onClick: () => {
// Only this line goes: the list may have been edited since.
const now = ctx.storage.get(MUTED_KEY, '');
if (write(now.split('\n').filter(item => item.trim() !== line).join('\n'))) announce();
},
},
});
};
ctx.command({ id: 'quickMute.add', title: ctx.text('add'), keywords: 'quick mute selection selected text word phrase pattern alt shift u', shortcut: 'Alt+Shift+U', run: add });
},
};

View file

@ -0,0 +1,144 @@
// Reader+ · Read marker. Remembers the post you were at on Home when you stopped reading, per Home
// tab (For you, Following, a pinned list: by the tab's position, so in any X language). The next
// time that post is on the page it carries a line ("You left off here"), and a toast offers to
// jump to it. Local only: a post id and a time in page storage; nothing is requested, and a post X
// has not loaded is not fetched (scrolling down brings it, and the line with it).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export type Marker = { id: string; time: number };
export type Markers = Record<string, Marker>;
export const READ_MARKER_SCHEMA: SettingsSchema = [
{ key: 'toast', type: 'toggle', default: true, label: 'toast', hint: 'toastHint' },
];
const MARK = 'data-bt-reader-marker';
const TABS = '[data-testid="primaryColumn"] [role="tablist"] [role="tab"]';
/** X's sticky header covers about this much of the top of the window. */
const HEADER = 56;
/** Above this scroll position the reader is at the top of Home, not somewhere in it. */
const TOP = 200;
const SAVE_MS = 1000;
/** The stored markers, whatever was stored: only `{ id: digits, time: number }` entries survive. */
export function readMarkers(stored: unknown): Markers {
const out: Markers = {};
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return out;
for (const [key, value] of Object.entries(stored as Record<string, unknown>)) {
const marker = value as Partial<Marker> | null;
if (/^tab\d{1,2}$/.test(key) && marker && typeof marker.id === 'string' && /^\d{1,25}$/.test(marker.id) && typeof marker.time === 'number' && Number.isFinite(marker.time)) {
out[key] = { id: marker.id, time: marker.time };
}
}
return out;
}
/** The storage key of the selected Home tab (`tab0`, `tab1`, ...), or null while X has not drawn the tabs. */
export function tabKey(selected: ReadonlyArray<boolean>): string | null {
const index = selected.indexOf(true);
return index < 0 ? null : `tab${index}`;
}
/** The post being read: the first one that reaches below X's header. `posts` in page order. */
export function readingPost(posts: ReadonlyArray<{ id: string; bottom: number }>, header = HEADER): string | null {
return posts.find(post => post.bottom > header)?.id ?? null;
}
/**
* Whether a scroll position may replace the marker. At the top of Home the marker you came back
* for is kept until you have reached it: opening Home and leaving again does not lose your place.
*/
export function maySave(scrollY: number, previous: Marker | null, reached: boolean): boolean {
return scrollY >= TOP || !previous || reached;
}
const CSS = `
article[${MARK}] { position: relative; box-shadow: inset 0 2px 0 var(--wb-accent, rgb(29,155,240)); }
article[${MARK}]::before { content: attr(${MARK}); position: absolute; top: 2px; right: 16px; z-index: 1; padding: 1px 8px; border-radius: 0 0 8px 8px;
font: 700 11px/1.5 var(--wb-font, system-ui, sans-serif); color: var(--wb-on-accent, #fff); background: var(--wb-accent, rgb(29,155,240)); pointer-events: none; }
`.trim();
export const readMarker: FeatureModule<PluginApi> = {
id: 'reader.readMarker',
settings: READ_MARKER_SCHEMA,
// If Home renders cells but none is a post, X renamed the post: there is nothing to mark.
probes: { post: { selector: 'article[data-testid="tweet"]', when: '[data-testid="primaryColumn"] [data-testid="cellInnerDiv"] article' } },
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
const posts = `[data-testid="primaryColumn"] ${ctx.selector('post')}`;
const currentTab = () => tabKey(Array.from(doc.querySelectorAll(TABS), tab => tab.getAttribute('aria-selected') === 'true'));
const stored = () => readMarkers(ctx.storage.get<unknown>('markers', null));
// The marker this visit came back to (per tab): it keeps its line while newer positions are saved.
let tab: string | null = null;
let previous: Marker | null = null;
let marked: Element | null = null;
let reached = false;
let announced = false;
let notice: { close(): void } | null = null;
const unmark = () => { for (const article of doc.querySelectorAll(`article[${MARK}]`)) article.removeAttribute(MARK); };
/** X drew the Home tabs, or another tab was picked: the marker of that tab is the one to show. */
const syncTab = () => {
const now = currentTab();
if (now === tab) return;
tab = now;
previous = now ? stored()[now] ?? null : null;
marked = null;
reached = false;
announced = false;
unmark();
};
const onScreen = (element: Element) => {
const box = element.getBoundingClientRect();
return box.bottom > HEADER && box.top < win.innerHeight;
};
const jump = () => {
notice?.close();
if (!previous) { api.toast(ctx.text('none')); return; }
if (!marked?.isConnected) { api.toast(ctx.text('notLoaded')); return; }
marked.scrollIntoView({ block: 'center' });
};
const found = (article: Element) => {
marked = article;
article.setAttribute(MARK, ctx.text('line'));
if (onScreen(article)) { reached = true; return; }
if (announced || ctx.settings.get().toast !== true) return;
announced = true;
notice = ctx.ui.toast(ctx.text('found'), { action: { label: ctx.text('jump'), onClick: jump } });
};
ctx.css(CSS);
ctx.observe(posts, article => {
syncTab();
if (previous && api.tweet(article)?.id === previous.id) found(article);
});
// Where you are now, saved a moment after the page stops scrolling.
let timer = 0;
const save = () => {
timer = 0;
syncTab();
if (!tab) return;
if (marked?.isConnected && onScreen(marked)) reached = true;
if (!maySave(win.scrollY, previous, reached)) return;
const visible: { id: string; bottom: number }[] = [];
for (const article of doc.querySelectorAll(posts)) {
// An ad is not a place in the timeline: it may never be shown again.
if (article.closest('[data-testid="placementTracking"]')) continue;
const id = api.tweet(article)?.id;
if (id) visible.push({ id, bottom: article.getBoundingClientRect().bottom });
}
const id = readingPost(visible);
if (id) ctx.storage.set('markers', { ...stored(), [tab]: { id, time: Date.now() } });
};
ctx.on(win, 'scroll', () => { if (!timer) timer = win.setTimeout(save, SAVE_MS); }, { passive: true });
ctx.defer(() => { if (timer) win.clearTimeout(timer); });
ctx.defer(unmark);
ctx.command({ id: 'readMarker.jump', title: ctx.text('jump'), keywords: 'read marker left off jump back position home timeline', run: jump });
},
};

View file

@ -0,0 +1,55 @@
// Reader+ · Reading Time (was the Reading Time plugin, 1.2.0). An estimated reading time
// ("3 min read") on long posts and X Articles, counted from the text on screen at 230 words per
// minute.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
const WORDS_PER_MINUTE = 230;
const MIN_WORDS = 120;
const CJK = /[぀-ヿ㐀-鿿가-힯]/g;
/** Minutes to read `text`, or 0 when it is too short to be worth a label. CJK characters count as words. */
export function readingMinutes(text: string | null | undefined): number {
const value = String(text || '');
const cjk = (value.match(CJK) || []).length;
const words = (value.replace(CJK, ' ').match(/\S+/g) || []).length + cjk;
return words < MIN_WORDS ? 0 : Math.max(1, Math.round(words / WORDS_PER_MINUTE));
}
const CSS = `
/* X lays posts out in flex columns that stretch their children: the pill keeps its own width. */
.bt-reading-time { display: inline-block; align-self: flex-start; width: max-content; max-width: 100%; box-sizing: border-box; margin: 0 0 6px; padding: 2px 8px; border-radius: 999px;
font: 600 12px/1.5 system-ui, sans-serif; background: rgba(29,155,240,.12); color: rgb(29,155,240); }
`;
export const readingTime: FeatureModule<PluginApi> = {
id: 'reader.readingTime',
words: 'reading-time',
start(ctx) {
const doc = ctx.win.document;
const label = (target: Element) => {
const minutes = readingMinutes(target.textContent);
const previous = target.previousElementSibling?.classList.contains('bt-reading-time') ? target.previousElementSibling : null;
if (!minutes) { previous?.remove(); return; }
const text = ctx.text('label', { minutes });
if (previous) { if (previous.textContent !== text) previous.textContent = text; return; }
if (!target.parentNode) return;
const badge = doc.createElement('div');
badge.className = 'bt-reading-time';
badge.textContent = text;
target.before(badge);
};
ctx.css(CSS);
// Long posts. Timelines show a truncated preview; the post page has the full text.
ctx.observe('article [data-testid="tweetText"]', label);
// X Articles (long-form): label the article body once.
ctx.observe('[data-testid="twitterArticleRichTextView"], [data-testid="longformRichTextComponent"]', label);
// A language switch relabels the badges already on screen.
ctx.defer(ctx.api.i18n.onChange(() => {
for (const badge of doc.querySelectorAll('.bt-reading-time')) if (badge.nextElementSibling) label(badge.nextElementSibling);
}));
ctx.defer(() => { for (const node of doc.querySelectorAll('.bt-reading-time')) node.remove(); });
},
};

View file

@ -0,0 +1,16 @@
// Reader+ · Sort replies by Recent. A rewrite stage of the shared request hook
// (src/fixes/replySort.ts): X's own post-page request asks for "Recency" instead of "Relevance".
// No request is added. `heavy` in the table, so the stage stays in place on every page, as it did
// when the runtime installed it.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import { installReplySort } from '../../fixes/replySort.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export const sortRepliesRecent: FeatureModule<PluginApi> = {
id: 'sortRepliesRecent',
start(ctx) {
const sort = installReplySort(ctx.win);
ctx.defer(() => sort.dispose());
},
};

View file

@ -0,0 +1,212 @@
// Reader+ · Thread Reader (was the Thread Reader plugin, 1.2.0). A "Read thread" button in the
// header of post pages that unrolls the author's thread into a clean reading view, with copy as
// Markdown. Reads only what X already shows; "Load more" scrolls the page behind the reader.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi, TweetInfo } from '../../inject/pluginApi.ts';
type ThreadPost = Pick<TweetInfo, 'id' | 'url' | 'name' | 'handle' | 'text' | 'time' | 'media'> & { shown: string[] };
/** The post id of a plain post page (`/user/status/id`), not its photo/video viewer or lists. */
export function focalIdOf(pathname: string | null | undefined): string | null {
const match = /^\/[^/]+\/status\/(\d+)\/?$/.exec(String(pathname || ''));
return match ? match[1]! : null;
}
/** Posts in thread order (post ids grow with time). */
export const threadOrder = <T extends { id: string }>(posts: Iterable<T>): T[] => [...posts].sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1));
/** A thread as Markdown: a heading, the source link, then each post's text and images. */
export function threadMarkdown(posts: ReadonlyArray<Pick<ThreadPost, 'name' | 'handle' | 'url' | 'text' | 'media'>>): string {
if (!posts.length) return '';
const first = posts[0]!;
const lines = [`# Thread by ${first.name} (@${first.handle})`, '', `Source: ${first.url}`, ''];
for (const post of posts) {
lines.push(post.text, '');
for (const src of post.media) lines.push(`![](${src})`, '');
}
return lines.join('\n').trim() + '\n';
}
const CSS = `
.bt-tr-open { position: fixed; right: 24px; bottom: 88px; z-index: 2147483000; border: 0; border-radius: var(--wb-button-radius, 999px);
padding: 10px 16px; font: 700 14px/1 var(--wb-font, system-ui, sans-serif); color: var(--wb-on-inverse, #fff); background: var(--wb-inverse, rgb(29,155,240));
box-shadow: 0 6px 20px rgba(0,0,0,.3); cursor: pointer; }
.bt-tr-open:hover { filter: brightness(1.08); }
.bt-tr-open:focus-visible { outline: 2px solid var(--wb-accent, rgb(29,155,240)); outline-offset: 2px; }
.bt-tr-open.bt-tr-bar { position: static; flex: none; align-self: center; margin: 0 12px 0 8px; padding: 8px 14px;
font-size: 13px; white-space: nowrap; box-shadow: none; }
`;
const READER_CSS = `
.bt-tr-post { margin: 0 0 1.1em; font: 400 18px/1.65 Georgia, 'Iowan Old Style', serif; white-space: pre-wrap; overflow-wrap: anywhere; }
.bt-tr-post img { display: block; max-width: 100%; border-radius: min(var(--wb-radius), 12px); margin: .6em 0; }
.bt-tr-num { font: 600 12px/1 var(--wb-font); color: var(--wb-muted) !important; margin-right: 6px; text-decoration: none; }
`;
const POSTS = '[data-testid="primaryColumn"] article[data-testid="tweet"]';
export const threadReader: FeatureModule<PluginApi> = {
id: 'reader.threadReader',
words: 'thread-reader',
start(ctx) {
const { api, win } = ctx;
const doc = win.document;
let collected = new Map<string, ThreadPost>();
let author: string | null = null;
let button: HTMLElement | null = null;
let reader: ReturnType<typeof ctx.ui.dialog> | null = null;
let stopWatching: (() => void) | null = null;
const focalId = () => focalIdOf(win.location.pathname);
const tweetsOnPage = () => Array.from(doc.querySelectorAll(POSTS), article => api.tweet(article)).filter((tweet): tweet is TweetInfo => !!tweet);
/** True when the focal post's author has at least one more post rendered here (a thread). */
const hasThread = (id: string) => {
const tweets = tweetsOnPage();
const focal = tweets.find(tweet => tweet.id === id);
if (!focal) return false;
const by = focal.handle.toLowerCase();
return tweets.some(tweet => tweet.id !== id && tweet.handle.toLowerCase() === by);
};
/**
* The row of X's own page header (back arrow, "Post"). The button sits at its end, so it never
* floats over posts, the reply box or X's bottom bars, in a narrow split pane too.
*/
const headerBar = () => {
const back = doc.querySelector('[data-testid="primaryColumn"] [data-testid="app-bar-back"]');
const row = back?.parentElement?.parentElement;
return row && row.querySelector('h2') && win.getComputedStyle(row).flexDirection === 'row' ? row : null;
};
const close = () => {
stopWatching?.();
stopWatching = null;
const open = reader;
reader = null;
if (open?.open) open.close();
};
/** Tweets by the focal post's author that X currently renders on this page. */
const collect = () => {
const id = focalId();
if (!id) return;
const tweets = tweetsOnPage();
const focal = tweets.find(tweet => tweet.id === id);
const by = (focal?.handle ?? author ?? '').toLowerCase();
if (!by) return;
author = by;
for (const tweet of tweets) {
if (tweet.handle.toLowerCase() === by && !collected.has(tweet.id)) {
// The images exactly as X rendered them (no new, larger downloads); quoted posts' images excluded.
const shown = Array.from(tweet.element.querySelectorAll('img[src*="pbs.twimg.com/media/"]'))
.filter(img => { const card = img.closest('[role="link"]'); return !card || !tweet.element.contains(card); })
.map(img => img.getAttribute('src')!);
collected.set(tweet.id, { id: tweet.id, url: tweet.url, name: tweet.name, handle: tweet.handle, text: tweet.text, time: tweet.time, media: tweet.media, shown: [...new Set(shown)] });
}
}
};
/** Text as text nodes; http(s) URLs become links. No HTML parsing. */
const appendLinkified = (parent: Element, text: string) => {
for (const part of text.split(/(https?:\/\/\S+)/g)) {
if (/^https?:\/\/\S+$/.test(part)) {
const link = doc.createElement('a');
link.href = part;
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.textContent = part;
parent.appendChild(link);
} else if (part) {
parent.appendChild(doc.createTextNode(part));
}
}
};
/** A post number: close the reader and let X's own link to that post navigate in the app. */
const goTo = (event: Event, post: ThreadPost) => {
const own = doc.querySelector<HTMLElement>(`[data-testid="primaryColumn"] a[href="/${post.handle}/status/${post.id}"]`);
if (!own) return;
event.preventDefault();
close();
own.click();
};
const render = () => {
if (!reader?.open) return;
const posts = threadOrder(collected.values());
const title = reader.element.querySelector('.wb-title');
if (title) title.textContent = ctx.text('heading', { name: posts[0]!.name, handle: `@${posts[0]!.handle}`, count: posts.length });
const h = ctx.ui.h;
reader.body.replaceChildren(
...posts.map((post, index) => {
const block = h('div', { class: 'bt-tr-post' }, h('a', { class: 'bt-tr-num', href: post.url, onClick: (event: Event) => goTo(event, post) }, `${index + 1}/`));
appendLinkified(block, post.text);
for (const src of post.shown) block.appendChild(h('img', { src, alt: '', loading: 'lazy' }));
return block;
}),
h('p', { class: 'wb-hint' }, ctx.text('hint')),
);
};
/** The reader: a wide dialog from the UI kit, in the theme's colors with a serif reading face. */
const open = () => {
if (reader?.open) return;
collected = new Map();
author = null;
collect();
if (!collected.size) { api.toast(ctx.text('nothing')); return; }
const ui = ctx.ui;
reader = ui.dialog({
title: ctx.text('title'),
width: 680,
closeOnBackdrop: true,
css: READER_CSS,
actions: [
{ label: ctx.text('loadMore'), tone: 'plain', onClick: () => { win.scrollBy({ top: win.innerHeight * 1.5 }); return false; } },
{
label: ctx.text('copyMarkdown'),
onClick: async () => {
const ok = await api.copyText(threadMarkdown(threadOrder(collected.values())));
ui.toast(ok ? ctx.text('copied') : ctx.text('copyFailed'), { tone: ok ? 'success' : 'danger' });
return false;
},
},
{ label: ctx.text('close'), tone: 'primary', default: true },
],
onClose: () => close(),
});
// Keep adding the author's posts as X renders more of the conversation.
stopWatching = api.observe(POSTS, () => {
const before = collected.size;
collect();
if (collected.size !== before) render();
});
render();
};
const sync = () => {
const id = focalId();
if (!id || !hasThread(id)) {
button?.remove();
button = null;
close();
return;
}
const bar = headerBar();
if (button?.isConnected && (bar ? button.parentElement === bar : true)) return;
button?.remove();
const created = doc.createElement('button');
created.type = 'button';
created.className = bar ? 'bt-tr-open bt-tr-bar' : 'bt-tr-open';
created.textContent = ctx.text('button');
created.addEventListener('click', () => open());
button = ctx.add(created);
// Without X's header (a layout X may change), fall back to the floating pill.
(bar ?? doc.body).appendChild(created);
};
ctx.css(CSS);
ctx.onRouteChange(() => sync());
// The button shows only once the author's own replies (a thread) are on the page.
ctx.observe(POSTS, () => sync());
ctx.defer(() => close());
ctx.defer(api.i18n.onChange(() => { if (button) button.textContent = ctx.text('button'); }));
sync();
// Ctrl+K: read the thread of the post on screen (runs here, in this tab).
ctx.command({
id: 'threadReader.open', title: ctx.text('command'), keywords: 'thread reader unroll read markdown',
run: () => (focalId() ? open() : api.toast(ctx.text('openFirst'))),
});
},
};

View file

@ -0,0 +1,44 @@
// Row builders for the feature table (src/areas/table.ts): each area lists its rows in
// src/areas/<area>/features.ts with these. Pure data.
//
// `backing` says where a feature's code lives today:
// module a feature module in src/areas/<area>/ (the registry starts it on its surfaces),
// app a part of the X runtime (request hub, native command, document-start timing, or a rule
// in src/inject/features.ts that has not been ported),
// plugin an old bundled plugin file that has not been ported; its switch is that file.
import type { FeatureSpec } from '../../../../waybetter/packages/runtime/src/featureTable.ts';
export type AreaId = 'compose' | 'reader' | 'profile' | 'chat' | 'media' | 'search' | 'notifications' | 'navigation';
/** A row: a flag id, or the id with whatever differs from the defaults (off, no surfaces, no settings). */
export type Row = string | (Omit<FeatureSpec, 'area' | 'backing' | 'default'> & { default?: boolean });
const rows = (area: AreaId, group: string, backing: 'app' | 'module', list: Row[]): FeatureSpec[] =>
list.map(row => ({ default: false, ...(typeof row === 'string' ? { id: row } : row), area, group, backing }));
/** Features whose code is part of the X runtime. */
export const app = (area: AreaId, group: string, list: Row[]) => rows(area, group, 'app', list);
/** Features that are feature modules of the area (src/areas/<area>/index.ts `MODULES`). */
export const modules = (area: AreaId, group: string, list: Row[]) => rows(area, group, 'module', list);
/**
* A bundled plugin that has not been ported: `id` is the flag it becomes, `name` its source file
* name (src-tauri/bundled-plugins/<name>.plugin.js). Its switch is the file's enabled state.
*/
export const plugin = (area: AreaId, group: string, id: string, name: string, permissions: string[]): FeatureSpec => ({
id, area, group, default: false, backing: 'plugin', file: `bt-${name}.plugin.js`,
label: `plugin.${name}.name`, description: `plugin.${name}.description`, permissions,
});
/**
* A module that replaces bundled plugin `name`: the one-time migration turns that plugin's enabled
* state into this flag, and the row keeps the plugin's words (`plugin.<name>.name/.description`).
*/
export const ported = (id: string, name: string, extra: Omit<Exclude<Row, string>, 'id'> = {}): Exclude<Row, string> => ({
id, supersedes: `bt-${name}.plugin.js`, label: `plugin.${name}.name`, description: `plugin.${name}.description`, ...extra,
});
/** Core flags: owned by no area. */
export const core = (group: string, list: Row[]): FeatureSpec[] =>
list.map(row => ({ default: true, ...(typeof row === 'string' ? { id: row } : row), area: null, group, backing: 'app' as const }));

View file

@ -0,0 +1,144 @@
// Search+ · Advanced search. A small form that writes X's own search operators for you: from:,
// to:, since:/until:, filter:media|links|replies, min_faves:, lang:. The result is an ordinary X
// query: put into X's search box, or opened as X's own search page. Nothing is sent anywhere else
// and there is no syntax of our own (src/core/searchOperators.ts has the operators).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import { buildSettingsForm, normalizeSettings, type SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import { normalizeQuery } from '../../core/searchOperators.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { SEARCH_INPUT, setReactInputValue } from '../../inject/searchChips.ts';
import { searchBarSection } from './bar.ts';
import { openSearch } from './openSearch.ts';
import { currentQuery } from './savedSearches.ts';
export type BuilderValues = { words: string; from: string; to: string; since: string; until: string; filter: string; minFaves: number; lang: string };
export const FILTERS = ['media', 'links', 'replies'] as const;
/** The form, drawn with the settings form's controls (nothing of it is stored). */
export const BUILDER_FIELDS: SettingsSchema = [
{ key: 'words', type: 'text', default: '', label: 'words', maxLength: 300 },
{ key: 'from', type: 'text', default: '', label: 'from', placeholder: '@', maxLength: 80 },
{ key: 'to', type: 'text', default: '', label: 'to', placeholder: '@', maxLength: 80 },
{ key: 'since', type: 'text', default: '', label: 'since', placeholder: 'YYYY-MM-DD', maxLength: 10 },
{ key: 'until', type: 'text', default: '', label: 'until', placeholder: 'YYYY-MM-DD', maxLength: 10 },
{ key: 'filter', type: 'select', default: '', label: 'filter', options: [{ value: '', label: 'filterAny' }, ...FILTERS.map(value => ({ value, label: `filter.${value}` }))] },
{ key: 'minFaves', type: 'number', default: 0, min: 0, max: 100_000_000, label: 'minFaves' },
{ key: 'lang', type: 'text', default: '', label: 'lang', hint: 'langHint', placeholder: 'en', maxLength: 3 },
];
const HANDLE = /^[A-Za-z0-9_]{1,15}$/;
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const LANG = /^[a-z]{2,3}$/;
const handles = (text: string) => [...new Set(text.split(/[\s,]+/).map(item => item.replace(/^@/, '')).filter(item => HANDLE.test(item)))];
/** `from:a`, or `(from:a OR from:b)` for several accounts. */
const people = (operator: 'from' | 'to', text: string) => {
const list = handles(text).map(handle => `${operator}:${handle}`);
return list.length > 1 ? `(${list.join(' OR ')})` : list[0] ?? '';
};
/** The X query for the form's values. A value that is not valid for its operator is left out. */
export function composeQuery(values: BuilderValues): string {
const lang = values.lang.trim().toLowerCase();
const likes = Math.floor(values.minFaves);
return normalizeQuery([
values.words,
people('from', values.from),
people('to', values.to),
DATE.test(values.since.trim()) ? `since:${values.since.trim()}` : '',
DATE.test(values.until.trim()) ? `until:${values.until.trim()}` : '',
(FILTERS as readonly string[]).includes(values.filter) ? `filter:${values.filter}` : '',
likes > 0 ? `min_faves:${likes}` : '',
LANG.test(lang) ? `lang:${lang}` : '',
].filter(Boolean).join(' '));
}
/** The form's values for a query: the operators the form knows go to their fields, the rest stays as words. */
export function readQuery(query: string): BuilderValues {
const values = normalizeSettings(BUILDER_FIELDS, null) as BuilderValues;
const words: string[] = [];
const from: string[] = [];
const to: string[] = [];
for (const token of normalizeQuery(query).match(/-?"[^"]*"|\S+/g) ?? []) {
const match = /^(from|to|since|until|filter|min_faves|lang):(.+)$/i.exec(token);
const operator = match?.[1]!.toLowerCase();
const value = match?.[2] ?? '';
if (operator === 'from' && HANDLE.test(value)) from.push(value);
else if (operator === 'to' && HANDLE.test(value)) to.push(value);
else if ((operator === 'since' || operator === 'until') && DATE.test(value) && !values[operator]) values[operator] = value;
else if (operator === 'filter' && (FILTERS as readonly string[]).includes(value.toLowerCase()) && !values.filter) values.filter = value.toLowerCase();
else if (operator === 'min_faves' && /^\d{1,9}$/.test(value) && !values.minFaves) values.minFaves = Number(value);
else if (operator === 'lang' && LANG.test(value.toLowerCase()) && !values.lang) values.lang = value.toLowerCase();
else words.push(token);
}
values.words = words.join(' ');
values.from = from.join(' ');
values.to = to.join(' ');
return values;
}
export const advancedSearch: FeatureModule<PluginApi> = {
id: 'search.advancedSearch',
start(ctx) {
const { win } = ctx;
const box = () => win.document.querySelector<HTMLInputElement>(SEARCH_INPUT);
let pending = 0;
ctx.defer(() => win.clearTimeout(pending));
const open = () => {
const h = ctx.ui.h;
const form = buildSettingsForm(h, BUILDER_FIELDS, readQuery(currentQuery(win, box())), key => ctx.text(key));
const preview = h('p', { class: 'wb-hint bt-query' });
const query = () => composeQuery(form.read() as BuilderValues);
const show = () => { preview.textContent = query() || ctx.text('previewEmpty'); };
const input = box();
const checked = (handle: { setError(message: string | null): void }) => {
const text = query();
if (!text) handle.setError(ctx.text('empty'));
return text;
};
ctx.ui.dialog({
title: ctx.text('title'),
message: ctx.text('intro'),
css: '.bt-query { margin-top: 14px; font-family: ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow-wrap: anywhere; }',
content: body => {
body.append(...form.nodes, preview);
body.addEventListener('input', show);
body.addEventListener('change', show);
show();
},
actions: [
{ label: ctx.text('cancel') },
// Only edits the text in X's box; X searches when you press Enter there.
...(input ? [{
label: ctx.text('fill'),
onClick: (handle: { setError(message: string | null): void }) => {
const text = checked(handle);
if (!text) return false;
input.focus();
setReactInputValue(input, text);
return undefined;
},
}] : []),
{
label: ctx.text('search'), tone: 'primary' as const, default: true,
onClick: handle => {
const text = checked(handle);
if (!text) return false;
// X's own search page for the query: a navigation, nothing more (./openSearch.ts).
win.clearTimeout(pending);
pending = openSearch(win, text);
return undefined;
},
},
],
});
};
const bar = searchBarSection(win, 20, () => [{ label: ctx.text('chip'), action: true, run: open }]);
ctx.defer(() => bar.dispose());
ctx.command({ id: 'advancedSearch.open', title: ctx.text('title'), keywords: 'advanced search builder operators from to since until filter media links replies likes language', run: open });
},
};

View file

@ -0,0 +1,160 @@
// Search+ · the strip under X's search box. While the box has focus, the features that offer
// something there (saved searches, the advanced search) each add their chips to one strip, under
// the operator chips when those are below the box. A chip only runs its feature's own action; the
// strip itself never touches X's input.
//
// One strip per page, shared: the first section creates it, the last one leaving removes it with
// its listeners. Each feature drops its section in `ctx.defer`.
import { adoptStyles } from '../../../../../waybetter/packages/runtime/src/styles.ts';
import { SEARCH_INPUT, SEARCH_OPS_HOST_ID, STRIP_COLORS_CSS, isSearchInput, paintStrip } from '../../inject/searchChips.ts';
export const SEARCH_BAR_HOST_ID = 'bt-search-plus-bar';
export type BarChip = {
label: string;
/** Tooltip (the whole query of a saved search). */
title?: string;
/** An action of the strip (pin, advanced search) rather than a thing to open. */
action?: boolean;
run(input: HTMLInputElement): void;
};
/** The chips a feature shows for the focused search box, in order. */
export type BarSection = (input: HTMLInputElement) => BarChip[];
export type BarHandle = { /** Draws the strip again (the feature's data changed). */ refresh(): void; dispose(): void };
type Bar = { sections: { order: number; section: BarSection }[]; refresh(): void; dispose(): void };
const bars = new WeakMap<Document, Bar>();
const CSS = `
:host{all:initial}
.bar{${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 system-ui,-apple-system,"Segoe UI",sans-serif}
button{all:unset;cursor:pointer;padding:5px 10px;border-radius:9999px;border:1px solid var(--line);color:var(--fg);white-space:nowrap;max-width:220px;overflow:hidden;text-overflow:ellipsis}
button:hover,button:focus-visible{color:var(--accent);border-color:var(--accent)}
button.action{color:var(--muted);border-style:dashed}
`;
function createBar(win: Window, selector: string): Bar {
const doc = win.document;
let host: HTMLElement | null = null;
let root: ShadowRoot | null = null;
let current: HTMLInputElement | null = null;
let hideTimer: number | undefined;
const hide = () => { host?.remove(); host = null; root = null; };
const place = () => {
if (!host || !current) return;
const rect = current.getBoundingClientRect();
// Under the operator chips when they are below the box too (they go above it when there is room).
const ops = doc.getElementById(SEARCH_OPS_HOST_ID)?.getBoundingClientRect();
const top = ops && ops.height > 0 && ops.top >= rect.bottom ? ops.bottom + 6 : rect.bottom + 10;
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: `${Math.round(top)}px`,
});
};
const render = () => {
const input = current;
if (!input) return hide();
const chips = bar.sections.flatMap(item => item.section(input));
if (!chips.length) return hide();
if (!host) {
host = doc.createElement('div');
host.id = SEARCH_BAR_HOST_ID;
root = host.attachShadow({ mode: 'closed' });
const strip = doc.createElement('div');
strip.className = 'bar';
strip.setAttribute('role', 'group');
strip.setAttribute('aria-label', 'Search+');
root.append(strip);
// 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 strip = root!.querySelector('.bar') as HTMLElement;
paintStrip(strip, win, input);
strip.replaceChildren(...chips.map(chip => {
const button = doc.createElement('button');
button.type = 'button';
if (chip.action) button.className = 'action';
button.textContent = chip.label;
if (chip.title) button.title = chip.title;
button.addEventListener('click', () => { chip.run(input); render(); });
return button;
}));
place();
// The operator chips may be drawn after this strip in the same event: settle under them.
win.requestAnimationFrame(place);
};
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 (current && target(event) === current) render(); };
const onMove = () => place();
doc.addEventListener('focusin', onFocusIn, true);
doc.addEventListener('focusout', onFocusOut, true);
doc.addEventListener('input', onInput, true);
win.addEventListener('resize', onMove);
win.addEventListener('scroll', onMove, true);
const bar: Bar = {
sections: [],
refresh() {
if (!current && isSearchInput(doc.activeElement, selector)) current = doc.activeElement;
render();
},
dispose() {
win.clearTimeout(hideTimer);
doc.removeEventListener('focusin', onFocusIn, true);
doc.removeEventListener('focusout', onFocusOut, true);
doc.removeEventListener('input', onInput, true);
win.removeEventListener('resize', onMove);
win.removeEventListener('scroll', onMove, true);
current = null;
hide();
},
};
return bar;
}
/** Adds a feature's chips to the strip (lower `order` first). Dispose it when the feature stops. */
export function searchBarSection(win: Window, order: number, section: BarSection, selector = SEARCH_INPUT): BarHandle {
const doc = win.document;
let bar = bars.get(doc);
if (!bar) {
bar = createBar(win, selector);
bars.set(doc, bar);
}
const shared = bar;
const entry = { order, section };
shared.sections.push(entry);
shared.sections.sort((a, b) => a.order - b.order);
shared.refresh();
let active = true;
return {
refresh() { if (active) shared.refresh(); },
dispose() {
if (!active) return;
active = false;
shared.sections.splice(shared.sections.indexOf(entry), 1);
if (shared.sections.length) return shared.refresh();
bars.delete(doc);
shared.dispose();
},
};
}

View file

@ -0,0 +1,24 @@
// Search+: its rows of the feature table (docs/AREA-PLUGINS.md). `FEATURES` is what its card lists;
// `POWER` are the flags Power User turns on besides the defaults. A flag id never changes once it
// shipped. New words go to ./messages.en.json; modules to ./index.ts.
import type { FeatureSpec } from '../../../../../waybetter/packages/runtime/src/featureTable.ts';
import { modules, type Row } from '../rows.ts';
/** A new feature of this area: its words are `plugin.search-plus.feature.<name>.*` (./messages.en.json). */
const added = (name: string, extra: Omit<Exclude<Row, string>, 'id'> = {}): Row => ({
id: `search.${name}`, label: `plugin.search-plus.feature.${name}.label`, description: `plugin.search-plus.feature.${name}.description`, ...extra,
});
export const FEATURES: readonly FeatureSpec[] = [
...modules('search', '', [
// The two flags that were Tweaks: the operator chips (src/inject/searchChips.ts) and the Explore rule.
{ id: 'searchOperators', default: true }, 'hideExploreContent',
added('savedSearches', { settings: true, keywords: 'saved searches pin query', permissions: ['storage', 'ui', 'commands'] }),
added('advancedSearch', { keywords: 'advanced search builder operators', permissions: ['ui', 'commands'] }),
added('latestDefault', { surfaces: ['search'], keywords: 'latest tab top results' }),
]),
];
/** Flags Power User turns on besides the defaults (this area's advanced features). */
export const POWER: readonly string[] = ['search.savedSearches', 'search.advancedSearch'];

View file

@ -0,0 +1,10 @@
// Search+ · Hide Explore content. Explore's trending topics only: the `trend` testid never renders
// in the primary column on other pages, so search stays usable and other pages are unaffected.
// The rule moved here unchanged from src/inject/features.ts (`buildFeatureCss`).
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
export const EXPLORE_CSS = 'div[data-testid="primaryColumn"] [data-testid="trend"] {\n display: none !important;\n}';
export const hideExploreContent: FeatureModule<PluginApi> = { id: 'hideExploreContent', start(ctx) { ctx.css(EXPLORE_CSS); } };

View file

@ -0,0 +1,13 @@
// Search+: its feature modules (docs/AREA-PLUGINS.md; Navigation+ in ../navigation is the reference).
// One module per `backing: 'module'` row of ./features.ts; the registry starts each only while its
// flag is on, the area is on and the page is on one of its surfaces.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { advancedSearch } from './advancedSearch.ts';
import { hideExploreContent } from './hideExploreContent.ts';
import { latestDefault } from './latestDefault.ts';
import { savedSearches } from './savedSearches.ts';
import { searchOperators } from './searchOperators.ts';
export const MODULES: ReadonlyArray<FeatureModule<PluginApi>> = [searchOperators, hideExploreContent, savedSearches, advancedSearch, latestDefault];

View file

@ -0,0 +1,55 @@
// Search+ · Latest by default. X opens search results on "Top"; with this on, a new search opens on
// "Latest" instead, by selecting X's own Latest tab once per search (a navigation click, the same
// kind the deck's column rule makes for For you / Following). A search that names its tab (`f=…`:
// Latest, People, Media, Lists) is left alone, and so is going back to Top by hand.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
/** X's Latest tab of a results page: a tab link whose address carries `f=live`. No words are read. */
export const LATEST_TAB = '[data-testid="primaryColumn"] [role="tablist"] a[role="tab"][href*="f=live"]';
export type SearchPage = { query: string; tab: string | null };
/** The search a page shows (`/search?q=…`), or null when it is not a results page. */
export function searchPage(pathname: string, search: string): SearchPage | null {
if (!/^\/search\/?$/.test(pathname)) return null;
const params = new URLSearchParams(search);
const query = (params.get('q') ?? '').trim();
return query ? { query, tab: params.get('f') } : null;
}
/**
* Whether to select Latest now. `settled` is the query already decided for (switched once, opened
* on a tab of its own, or returned to Top by hand): that one is never switched again.
*/
export function wantsLatest(page: SearchPage | null, settled: string | null): boolean {
return !!page && page.tab === null && page.query !== settled;
}
/** True when the tab link belongs to this search (X may still show the previous search's tabs). */
export function tabIsFor(href: string | null, query: string): boolean {
try { return (new URL(href ?? '', 'https://x.com').searchParams.get('q') ?? '').trim() === query; } catch { return false; }
}
export const latestDefault: FeatureModule<PluginApi> = {
id: 'search.latestDefault',
start(ctx) {
const { win } = ctx;
let settled: string | null = null;
const check = () => {
const page = searchPage(win.location.pathname ?? '', win.location.search ?? '');
if (!page) return;
if (page.tab !== null) { settled = page.query; return; }
if (!wantsLatest(page, settled)) return;
const tab = win.document.querySelector<HTMLElement>(LATEST_TAB);
// Not drawn yet (or still the previous search's tabs): the next frame asks again.
if (!tab || !tabIsFor(tab.getAttribute('href'), page.query)) return;
settled = page.query;
tab.click();
};
ctx.watch(check);
ctx.onRouteChange(check);
check();
},
};

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,28 @@
// Search+ · opening X's own search page for a query. A navigation, nothing more.
//
// Through X's router when the page has one (the state X's own links push, then the event its
// router listens to: the same mechanism Chat+ uses to open a conversation), so the timeline is not
// loaded again from scratch. If X did not take it (the page's title is still the old one after a
// moment) the address is loaded the plain way, which is also what happens without the history API.
import { buildSearchUrl } from '../../core/searchOperators.ts';
type Win = Window & typeof globalThis;
const ORIGIN = 'https://x.com';
/** How long X's router gets to show the new page before the address is loaded the plain way. */
export const ROUTER_WAIT_MS = 2000;
/** Returns the timer of the fallback check (0 when none is pending), for the caller to clear when it stops. */
export function openSearch(win: Win, query: string): number {
const url = buildSearchUrl(query);
const canRoute = win.location.origin === ORIGIN && typeof win.history?.pushState === 'function' && typeof win.PopStateEvent === 'function';
if (!canRoute || win.location.href === url) { win.location.assign(url); return 0; }
const title = win.document.title;
const state = { key: Math.random().toString(36).slice(2, 8), state: undefined };
win.history.pushState(state, '', url.slice(ORIGIN.length));
win.dispatchEvent(new win.PopStateEvent('popstate', { state }));
return win.setTimeout(() => {
if (win.location.href === url && win.document.title === title) win.location.assign(url);
}, ROUTER_WAIT_MS);
}

View file

@ -0,0 +1,128 @@
// Search+ · Saved searches. A local list of searches you pin: each is a chip under X's search box
// and an entry of the "Saved searches" command (Ctrl+K). Opening one is a navigation to X's own
// search page for that query, nothing else. The list lives in this feature's settings (one search
// per line, `Name => query` to give it a name), in this tab's page storage: it never leaves the app.
import type { FeatureContext, FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts';
import { normalizeQuery } from '../../core/searchOperators.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { SEARCH_INPUT } from '../../inject/searchChips.ts';
import { searchBarSection, type BarChip } from './bar.ts';
import { openSearch } from './openSearch.ts';
export type SavedSearch = { name: string; query: string };
export const MAX_SAVED = 50;
/** Chips shown under the box; the rest is in the list (the command, or the last chip). */
export const MAX_CHIPS = 8;
const SEPARATOR = ' => ';
export const SAVED_SCHEMA: SettingsSchema = [
{ key: 'searches', type: 'list', default: [], label: 'list', hint: 'listHint', maxItems: MAX_SAVED, maxLength: 300 },
];
const same = (a: string, b: string) => normalizeQuery(a).toLowerCase() === normalizeQuery(b).toLowerCase();
/** One stored line: `query`, or `Name => query`. Null for a line without a query. */
export function parseSaved(line: string): SavedSearch | null {
const at = line.indexOf(SEPARATOR);
const query = normalizeQuery(at < 0 ? line : line.slice(at + SEPARATOR.length));
if (!query) return null;
const name = at < 0 ? '' : line.slice(0, at).trim();
return { name: name || query, query };
}
/** The saved searches of the stored lines: no empty ones, each query once, at most `MAX_SAVED`. */
export function savedList(lines: readonly string[]): SavedSearch[] {
const out: SavedSearch[] = [];
for (const line of lines) {
const item = parseSaved(line);
if (item && !out.some(other => same(other.query, item.query))) out.push(item);
if (out.length >= MAX_SAVED) break;
}
return out;
}
export const isPinned = (lines: readonly string[], query: string) => savedList(lines).some(item => same(item.query, query));
/** The lines after pinning `query` (added at the end) or unpinning it (its line removed). */
export function togglePinned(lines: readonly string[], query: string): string[] {
const text = normalizeQuery(query);
if (!text) return [...lines];
if (isPinned(lines, text)) return lines.filter(line => { const item = parseSaved(line); return !item || !same(item.query, text); });
return [...lines, text];
}
/** What is being searched right now: the text in X's search box, else the query of a results page. */
export function currentQuery(win: Pick<Window, 'location' | 'document'>, input?: { value: string } | null): string {
const typed = normalizeQuery(input?.value ?? '');
if (typed) return typed;
if (!/^\/search\/?$/.test(win.location.pathname ?? '')) return '';
return normalizeQuery(new URLSearchParams(win.location.search ?? '').get('q') ?? '');
}
/** The chips under the box: the saved searches, "more" when they do not all fit, pin or unpin for the current query. */
export function savedChips(saved: readonly SavedSearch[], query: string, words: (key: string, params?: Record<string, string | number>) => string, act: { open(item: SavedSearch): void; toggle(query: string): void; list(): void }): BarChip[] {
const chips: BarChip[] = saved.slice(0, MAX_CHIPS).map(item => ({ label: item.name, title: item.query, run: () => act.open(item) }));
if (saved.length > MAX_CHIPS) chips.push({ label: words('more', { count: saved.length - MAX_CHIPS }), action: true, run: () => act.list() });
if (query) {
const pinned = saved.some(item => same(item.query, query));
chips.push({ label: pinned ? words('unpin') : words('pin'), title: query, action: true, run: () => act.toggle(query) });
}
return chips;
}
type Ctx = FeatureContext<PluginApi>;
export const savedSearches: FeatureModule<PluginApi> = {
id: 'search.savedSearches',
settings: SAVED_SCHEMA,
start(ctx: Ctx) {
const { win } = ctx;
const lines = () => ctx.settings.get().searches as string[];
// X's own search page for the query: a navigation, nothing more (./openSearch.ts).
let pending = 0;
ctx.defer(() => win.clearTimeout(pending));
const open = (item: SavedSearch) => { win.clearTimeout(pending); pending = openSearch(win, item.query); };
const toggle = (query: string) => {
const pinned = isPinned(lines(), query);
if (!pinned && savedList(lines()).length >= MAX_SAVED) { ctx.api.toast(ctx.text('full', { count: MAX_SAVED })); return; }
const saved = ctx.settings.set({ searches: togglePinned(lines(), query) });
ctx.api.toast(!saved ? ctx.text('failed') : pinned ? ctx.text('unpinned') : ctx.text('pinned'));
};
const list = () => {
const saved = savedList(lines());
const h = ctx.ui.h;
const dialog = ctx.ui.dialog({
title: ctx.text('title'),
width: 'sm',
css: '.bt-saved { display: flex; flex-direction: column; gap: 8px; } .bt-saved .wb-btn { justify-content: flex-start; overflow: hidden; text-overflow: ellipsis; }',
content: body => {
if (!saved.length) { body.append(h('p', { class: 'wb-hint' }, ctx.text('empty'))); return; }
body.append(h('div', { class: 'bt-saved' }, saved.map(item =>
h('button', { type: 'button', class: 'wb-btn wb-secondary', title: item.query, onclick: () => { dialog.close(); open(item); } }, item.name))));
},
actions: [
{ label: ctx.text('edit'), tone: 'plain', onClick: () => { ctx.settings.open(); } },
{ label: ctx.text('close'), tone: 'primary', default: true },
],
});
};
const bar = searchBarSection(win, 10, input => savedChips(savedList(lines()), currentQuery(win, input), ctx.text, { open, toggle, list }));
ctx.defer(() => bar.dispose());
ctx.settings.onChange(() => bar.refresh());
ctx.command({ id: 'savedSearches.open', title: ctx.text('title'), keywords: 'saved searches pinned queries open', run: list });
ctx.command({
id: 'savedSearches.pin',
title: ctx.text('pinCommand'),
keywords: 'save pin unpin this search query',
run: () => {
const query = currentQuery(win, win.document.querySelector<HTMLInputElement>(SEARCH_INPUT));
if (query) toggle(query); else ctx.api.toast(ctx.text('nothing'));
},
});
},
};

View file

@ -0,0 +1,14 @@
// Search+ · Search operators. The chips under X's search box (src/inject/searchChips.ts, this
// area's file), started and stopped by the registry with the flag they always had.
import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts';
import type { PluginApi } from '../../inject/pluginApi.ts';
import { installSearchChips } from '../../inject/searchChips.ts';
export const searchOperators: FeatureModule<PluginApi> = {
id: 'searchOperators',
start(ctx) {
const chips = installSearchChips(ctx.win.document, ctx.win);
ctx.defer(() => chips.dispose());
},
};

View file

@ -0,0 +1,42 @@
// Which parts of X a page is: the surfaces a feature module may name in the table (`surfaces`).
// A feature with surfaces runs only while the page is on one of them; one without runs on every
// page (except X's chat, which is a heavy page: only a feature marked `heavy` runs there).
// Pure: a pathname in, surface ids out.
//
// timeline any page with a post timeline (home, a profile, a post page, search, bookmarks, lists)
// home /home
// status an opened post
// profile a profile and its tabs
// notifications /notifications and its tabs
// search /search
// explore /explore and its tabs
// bookmarks /i/bookmarks
// chat /messages and /i/chat
// viewer the photo or video viewer of a post
// composer the full-page composer (/compose/...)
// settings /settings
// other anything else
import { routeKind } from '../fixes/route.ts';
export const X_SURFACES = ['timeline', 'home', 'status', 'profile', 'notifications', 'search', 'explore', 'bookmarks', 'chat', 'viewer', 'composer', 'settings', 'other'] as const;
export type XSurface = typeof X_SURFACES[number];
export function surfacesOf(pathname: string): XSurface[] {
const path = pathname.replace(/\/+$/, '') || '/';
if (/^\/(?:messages|i\/chat)(?:\/|$)/i.test(path)) return ['chat'];
if (/^\/[A-Za-z0-9_]{1,15}\/status\/\d+\/(?:photo|video)\/\d+$/.test(path)) return ['status', 'viewer', 'timeline'];
if (/^\/compose(?:\/|$)/.test(path)) return ['composer'];
if (/^\/settings(?:\/|$)/.test(path)) return ['settings'];
if (/^\/search(?:\/|$)/.test(path)) return ['search', 'timeline'];
if (/^\/explore(?:\/|$)/.test(path)) return ['explore'];
if (/^\/i\/bookmarks(?:\/|$)/.test(path)) return ['bookmarks', 'timeline'];
if (/^\/(?:i\/lists\/\d+|[A-Za-z0-9_]{1,15}\/lists|i\/communities\/\d+|[A-Za-z0-9_]{1,15}\/communities)(?:\/|$)/.test(path)) return ['timeline'];
switch (routeKind(path)) {
case 'home': return ['home', 'timeline'];
case 'status': return ['status', 'timeline'];
case 'profile': return ['profile', 'timeline'];
case 'notifications': return ['notifications'];
default: return ['other'];
}
}

View file

@ -0,0 +1,82 @@
// The one table of everything the owner can switch in wayBetter for X (docs/AREA-PLUGINS.md): the
// eight area plugins, the features each owns, the core flags no plugin owns, and the three modes.
// The page runtime (which flags exist and who owns them), the panel (the cards, the Fixes list,
// the first-run screen) and the native migration list (src-tauri/src/areas.rs, generated from
// here by scripts/build-areas.ts) all read it, so they cannot disagree.
//
// This file only puts the parts together. Each area's rows are in src/areas/<area>/features.ts
// (that area's file), the core flags in ./core.ts. Pure data: no DOM.
import type { AreaSpec, FeatureSpec, FeatureTable, ModeSpec } from '../../../../waybetter/packages/runtime/src/featureTable.ts';
import { CORE_FEATURES } from './core.ts';
import type { AreaId } from './rows.ts';
import { FEATURES as COMPOSE, POWER as COMPOSE_POWER } from './compose/features.ts';
import { FEATURES as READER, POWER as READER_POWER } from './reader/features.ts';
import { FEATURES as PROFILE, POWER as PROFILE_POWER } from './profile/features.ts';
import { FEATURES as CHAT, POWER as CHAT_POWER } from './chat/features.ts';
import { FEATURES as MEDIA, POWER as MEDIA_POWER } from './media/features.ts';
import { FEATURES as SEARCH, POWER as SEARCH_POWER } from './search/features.ts';
import { FEATURES as NOTIFICATIONS, POWER as NOTIFICATIONS_POWER } from './notifications/features.ts';
import { FEATURES as NAVIGATION, POWER as NAVIGATION_POWER } from './navigation/features.ts';
export type { AreaId };
export { X_ELSEWHERE } from './core.ts';
const area = (id: AreaId, name: string, icon: string): AreaSpec => ({
id, name, icon,
description: `plugin.${id}-plus.description`,
// The file it ships as once it is a plugin file; the owner of its palette commands today.
owner: `bt-${id}-plus.plugin.js`,
namespace: `${id}-plus`,
});
export const X_AREAS: readonly AreaSpec[] = [
area('compose', 'Compose+', 'M3 13l.6-2.6L10.5 3.5l2 2-6.9 6.9zM9 5l2 2'),
area('reader', 'Reader+', 'M3 4h10M3 8h10M3 12h6'),
area('profile', 'Profile+', 'M8 7.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5zM3 13.5a5 5 0 0 1 10 0'),
area('chat', 'Chat+', 'M2.5 3.5h11v7h-6l-3 2.5v-2.5h-2z'),
area('media', 'Media+', 'M2.5 3.5h11v9h-11zM7 6l3 2-3 2z'),
area('search', 'Search+', 'M7 11.5a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.5 10.5l3 3'),
area('notifications', 'Notifications+', 'M4 11V7a4 4 0 0 1 8 0v4l1 1.5H3zM6.5 13.5a1.5 1.5 0 0 0 3 0'),
area('navigation', 'Navigation+', 'M2.5 3h3v10h-3zM8 4.5h5.5M8 8h5.5M8 11.5h3.5'),
];
export const X_FEATURES: readonly FeatureSpec[] = [
...CORE_FEATURES,
...COMPOSE, ...READER, ...PROFILE, ...CHAT, ...MEDIA, ...SEARCH, ...NOTIFICATIONS, ...NAVIGATION,
];
const allAreasOff = Object.fromEntries(X_AREAS.map(item => [`area.${item.id}`, false]));
const on = (flags: readonly string[]) => Object.fromEntries(flags.map(flag => [flag, true]));
/**
* What Advanced turns on besides the defaults: the calm features that came with the area plugins.
* Each only adds something (a chip, a button, a marker, a list); none hides content or changes what
* X does. They are a mode's choice, not the rows' defaults, so a setup from before the area plugins
* keeps exactly what it had until its owner picks a mode.
*/
export const X_ADVANCED: readonly string[] = [
'compose.postingAs', 'compose.lengthMeter',
'reader.readMarker', 'reader.cleanLinks', 'reader.copyAsMarkdown', 'reader.exactTimestamps', 'reader.readingTime', 'reader.threadReader',
'profile.accountAge', 'profile.hoverPeek',
'chat.bookmarks', 'chat.searchLoaded', 'chat.pins',
'media.videoSpeed', 'media.pictureInPicture', 'media.altText',
'search.savedSearches', 'search.advancedSearch',
'notifications.keywordHighlight',
];
/** Power User: Advanced plus the rest of each area's `POWER` list. Never a feature that hides, collapses or filters posts. */
export const X_POWER: readonly string[] = [...new Set([
...X_ADVANCED,
...COMPOSE_POWER, ...READER_POWER, ...PROFILE_POWER, ...CHAT_POWER, ...MEDIA_POWER, ...SEARCH_POWER, ...NOTIFICATIONS_POWER, ...NAVIGATION_POWER,
])];
export const X_MODES: readonly ModeSpec[] = [
// Only the fixes and the shell: X looks the way X ships it (no logo, no wording, every area off).
{ id: 'basic', name: 'modes.basic.name', description: 'modes.basic.description', flags: { ...allAreasOff, logoBrush: false, twitterWording: false } },
// Every area on: the defaults and the calm new features (`X_ADVANCED`).
{ id: 'advanced', name: 'modes.advanced.name', description: 'modes.advanced.description', recommended: true, flags: on(X_ADVANCED) },
// Advanced plus each area's advanced features (`POWER`); decks and workspaces are the shell's.
{ id: 'power', name: 'modes.power.name', description: 'modes.power.description', flags: on(X_POWER) },
];
export const X_TABLE: FeatureTable = { areas: X_AREAS, features: X_FEATURES, modes: X_MODES };