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,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) });
},
};