wayBetter for X
This commit is contained in:
commit
2f1e35ba20
720 changed files with 147465 additions and 0 deletions
51
apps/desktop/src/areas/reader/cleanLinks.ts
Normal file
51
apps/desktop/src/areas/reader/cleanLinks.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
232
apps/desktop/src/areas/reader/collapseVerified.ts
Normal file
232
apps/desktop/src/areas/reader/collapseVerified.ts
Normal 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);
|
||||
},
|
||||
};
|
||||
82
apps/desktop/src/areas/reader/copyAsMarkdown.ts
Normal file
82
apps/desktop/src/areas/reader/copyAsMarkdown.ts
Normal 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('>', `> `);
|
||||
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(); });
|
||||
},
|
||||
};
|
||||
83
apps/desktop/src/areas/reader/css.ts
Normal file
83
apps/desktop/src/areas/reader/css.ts
Normal 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');
|
||||
}
|
||||
99
apps/desktop/src/areas/reader/exactTimestamps.ts
Normal file
99
apps/desktop/src/areas/reader/exactTimestamps.ts
Normal 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');
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
44
apps/desktop/src/areas/reader/features.ts
Normal file
44
apps/desktop/src/areas/reader/features.ts
Normal 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'];
|
||||
26
apps/desktop/src/areas/reader/followingTimelineDefault.ts
Normal file
26
apps/desktop/src/areas/reader/followingTimelineDefault.ts
Normal 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();
|
||||
},
|
||||
};
|
||||
55
apps/desktop/src/areas/reader/fullNumbers.ts
Normal file
55
apps/desktop/src/areas/reader/fullNumbers.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
16
apps/desktop/src/areas/reader/hideBookmarkButton.ts
Normal file
16
apps/desktop/src/areas/reader/hideBookmarkButton.ts
Normal 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);
|
||||
},
|
||||
};
|
||||
36
apps/desktop/src/areas/reader/hideViewCounts.ts
Normal file
36
apps/desktop/src/areas/reader/hideViewCounts.ts
Normal 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);
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
45
apps/desktop/src/areas/reader/index.ts
Normal file
45
apps/desktop/src/areas/reader/index.ts
Normal 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,
|
||||
];
|
||||
125
apps/desktop/src/areas/reader/languageFilter.ts
Normal file
125
apps/desktop/src/areas/reader/languageFilter.ts
Normal 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));
|
||||
},
|
||||
};
|
||||
1
apps/desktop/src/areas/reader/messages.en.json
Normal file
1
apps/desktop/src/areas/reader/messages.en.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{}
|
||||
147
apps/desktop/src/areas/reader/mutedRegex.ts
Normal file
147
apps/desktop/src/areas/reader/mutedRegex.ts
Normal 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 });
|
||||
},
|
||||
};
|
||||
16
apps/desktop/src/areas/reader/pages.ts
Normal file
16
apps/desktop/src/areas/reader/pages.ts
Normal 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;
|
||||
}
|
||||
69
apps/desktop/src/areas/reader/quickMute.ts
Normal file
69
apps/desktop/src/areas/reader/quickMute.ts
Normal 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 });
|
||||
},
|
||||
};
|
||||
144
apps/desktop/src/areas/reader/readMarker.ts
Normal file
144
apps/desktop/src/areas/reader/readMarker.ts
Normal 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 });
|
||||
},
|
||||
};
|
||||
55
apps/desktop/src/areas/reader/readingTime.ts
Normal file
55
apps/desktop/src/areas/reader/readingTime.ts
Normal 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(); });
|
||||
},
|
||||
};
|
||||
16
apps/desktop/src/areas/reader/sortRepliesRecent.ts
Normal file
16
apps/desktop/src/areas/reader/sortRepliesRecent.ts
Normal 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());
|
||||
},
|
||||
};
|
||||
212
apps/desktop/src/areas/reader/threadReader.ts
Normal file
212
apps/desktop/src/areas/reader/threadReader.ts
Normal 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(``, '');
|
||||
}
|
||||
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'))),
|
||||
});
|
||||
},
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue