wayBetter for X
This commit is contained in:
commit
ae6ed24700
720 changed files with 147465 additions and 0 deletions
249
apps/desktop/src-tauri/bundled-plugins/thread-reader.plugin.js
Normal file
249
apps/desktop/src-tauri/bundled-plugins/thread-reader.plugin.js
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
/**
|
||||
* @name Thread Reader
|
||||
* @description Adds a "Read thread" button to 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.
|
||||
* @version 1.2.0
|
||||
* @author wayBetter
|
||||
* @permissions ui, clipboard, commands, network:none
|
||||
*/
|
||||
// i18n:begin
|
||||
// This plugin's English words. Translations live in the app's catalogs (plugin.<file name>.*,
|
||||
// docs/TRANSLATING.md); a plugin of your own can also pass { en: {...}, tr: {...} } to register.
|
||||
const MESSAGES = {
|
||||
"en": {
|
||||
"command": "Read this thread",
|
||||
"openFirst": "Open a post first: Thread Reader reads the thread of the post on screen.",
|
||||
"button": "Read thread",
|
||||
"nothing": "Nothing to read yet: wait for the post to load.",
|
||||
"title": "Thread",
|
||||
"loadMore": "Load more",
|
||||
"copyMarkdown": "Copy as Markdown",
|
||||
"copied": "Thread copied as Markdown",
|
||||
"copyFailed": "Copy failed",
|
||||
"close": "Close",
|
||||
"heading": "{name} ({handle}) · {count, plural, one {# post} other {# posts}}",
|
||||
"hint": "Only posts X has loaded are shown. “Load more” scrolls the page behind the reader."
|
||||
}
|
||||
};
|
||||
// i18n:end
|
||||
/** The words in the app's language (api.i18n); English before start() and outside the app. */
|
||||
let i18n = null;
|
||||
const t = (key, params = {}) => (i18n ? i18n.t(key, params) : String(MESSAGES.en[key] ?? key)
|
||||
.replace(/\{(\w+), plural, one \{([^{}]*)\} other \{([^{}]*)\}\}/g, (m, name, one, other) => (Number(params[name]) === 1 ? one : other).replace('#', String(params[name])))
|
||||
.replace(/\{(\w+)\}/g, (m, name) => (name in params ? String(params[name]) : m)));
|
||||
module.exports = class ThreadReader {
|
||||
start() {
|
||||
const api = window.wayBetter.api;
|
||||
i18n = api.i18n || null;
|
||||
if (i18n) i18n.register(MESSAGES);
|
||||
this.api = api;
|
||||
this.scope = api.scope();
|
||||
this.collected = new Map();
|
||||
this.scope.css('thread-reader', `
|
||||
.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; }
|
||||
`);
|
||||
this.scope.onRouteChange(() => this.sync());
|
||||
// The button shows only once the author's own replies (a thread) are on the page.
|
||||
this.scope.observe('[data-testid="primaryColumn"] article[data-testid="tweet"]', () => this.sync());
|
||||
this.scope.defer(() => this.close());
|
||||
if (i18n) this.scope.defer(i18n.onChange(() => { if (this.button) this.button.textContent = t('button'); }));
|
||||
this.sync();
|
||||
// Ctrl+K: read the thread of the post on screen (runs here, in this tab).
|
||||
if (this.scope.commands) {
|
||||
this.scope.commands.register({
|
||||
id: 'open', title: t('command'), keywords: 'thread reader unroll read markdown',
|
||||
run: () => (this.focalId() ? this.open() : this.api.toast(t('openFirst'))),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.scope.dispose();
|
||||
this.button = null;
|
||||
}
|
||||
|
||||
/** The post id of a plain post page (`/user/status/id`), not its photo/video viewer or lists. */
|
||||
static focalIdOf(pathname) {
|
||||
const match = /^\/[^/]+\/status\/(\d+)\/?$/.exec(String(pathname || ''));
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
focalId() {
|
||||
return ThreadReader.focalIdOf(location.pathname);
|
||||
}
|
||||
|
||||
/** True when the focal post's author has at least one more post rendered here (a thread). */
|
||||
hasThread(id) {
|
||||
const articles = document.querySelectorAll('[data-testid="primaryColumn"] article[data-testid="tweet"]');
|
||||
const tweets = Array.from(articles, article => this.api.tweet(article)).filter(Boolean);
|
||||
const focal = tweets.find(tweet => tweet.id === id);
|
||||
if (!focal) return false;
|
||||
const author = focal.handle.toLowerCase();
|
||||
return tweets.some(tweet => tweet.id !== id && tweet.handle.toLowerCase() === author);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
headerBar() {
|
||||
const back = document.querySelector('[data-testid="primaryColumn"] [data-testid="app-bar-back"]');
|
||||
const row = back?.parentElement?.parentElement;
|
||||
return row && row.querySelector('h2') && getComputedStyle(row).flexDirection === 'row' ? row : null;
|
||||
}
|
||||
|
||||
sync() {
|
||||
const id = this.focalId();
|
||||
if (!id || !this.hasThread(id)) {
|
||||
this.button?.remove();
|
||||
this.button = null;
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
const bar = this.headerBar();
|
||||
if (this.button?.isConnected && (bar ? this.button.parentElement === bar : true)) return;
|
||||
this.button?.remove();
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = bar ? 'bt-tr-open bt-tr-bar' : 'bt-tr-open';
|
||||
button.textContent = t('button');
|
||||
button.addEventListener('click', () => this.open());
|
||||
this.button = this.scope.add(button);
|
||||
// Without X's header (a layout X may change), fall back to the floating pill.
|
||||
(bar ?? document.body).appendChild(button);
|
||||
}
|
||||
|
||||
/** Tweets by the focal post's author that X currently renders on this page. */
|
||||
collect() {
|
||||
const id = this.focalId();
|
||||
if (!id) return;
|
||||
const articles = document.querySelectorAll('[data-testid="primaryColumn"] article[data-testid="tweet"]');
|
||||
const tweets = Array.from(articles, article => this.api.tweet(article)).filter(Boolean);
|
||||
const focal = tweets.find(tweet => tweet.id === id);
|
||||
const author = (focal?.handle ?? this.author ?? '').toLowerCase();
|
||||
if (!author) return;
|
||||
this.author = author;
|
||||
for (const tweet of tweets) {
|
||||
if (tweet.handle.toLowerCase() === author && !this.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'));
|
||||
this.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)] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ordered() {
|
||||
return [...this.collected.values()].sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1));
|
||||
}
|
||||
|
||||
/** The reader: a wide dialog from the UI kit, in the theme's colors with a serif reading face. */
|
||||
open() {
|
||||
if (this.reader?.open) return;
|
||||
this.collected = new Map();
|
||||
this.author = null;
|
||||
this.collect();
|
||||
if (!this.collected.size) { this.api.toast(t('nothing')); return; }
|
||||
const ui = this.scope.ui;
|
||||
this.reader = ui.dialog({
|
||||
title: t('title'),
|
||||
width: 680,
|
||||
closeOnBackdrop: true,
|
||||
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; }
|
||||
`,
|
||||
actions: [
|
||||
{ label: t('loadMore'), tone: 'plain', onClick: () => { window.scrollBy({ top: window.innerHeight * 1.5 }); return false; } },
|
||||
{
|
||||
label: t('copyMarkdown'),
|
||||
onClick: async () => {
|
||||
const ok = await this.api.copyText(this.markdown());
|
||||
ui.toast(ok ? t('copied') : t('copyFailed'), { tone: ok ? 'success' : 'danger' });
|
||||
return false;
|
||||
},
|
||||
},
|
||||
{ label: t('close'), tone: 'primary', default: true },
|
||||
],
|
||||
onClose: () => this.close(),
|
||||
});
|
||||
// Keep adding the author's posts as X renders more of the conversation.
|
||||
this.stopWatching = this.api.observe('[data-testid="primaryColumn"] article[data-testid="tweet"]', () => {
|
||||
const before = this.collected.size;
|
||||
this.collect();
|
||||
if (this.collected.size !== before) this.render();
|
||||
});
|
||||
this.render();
|
||||
}
|
||||
|
||||
render() {
|
||||
const reader = this.reader;
|
||||
if (!reader?.open) return;
|
||||
const posts = this.ordered();
|
||||
const title = reader.element.querySelector('.wb-title');
|
||||
if (title) title.textContent = t('heading', { name: posts[0].name, handle: `@${posts[0].handle}`, count: posts.length });
|
||||
const h = this.scope.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 => this.goTo(event, post) }, `${index + 1}/`));
|
||||
this.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' }, t('hint')),
|
||||
);
|
||||
}
|
||||
|
||||
/** A post number: close the reader and let X's own link to that post navigate in the app. */
|
||||
goTo(event, post) {
|
||||
const own = document.querySelector(`[data-testid="primaryColumn"] a[href="/${post.handle}/status/${post.id}"]`);
|
||||
if (!own) return;
|
||||
event.preventDefault();
|
||||
this.close();
|
||||
own.click();
|
||||
}
|
||||
|
||||
/** Text as text nodes; http(s) URLs become links. No HTML parsing. */
|
||||
appendLinkified(parent, text) {
|
||||
const parts = text.split(/(https?:\/\/\S+)/g);
|
||||
for (const part of parts) {
|
||||
if (/^https?:\/\/\S+$/.test(part)) {
|
||||
const link = document.createElement('a');
|
||||
link.href = part;
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
link.textContent = part;
|
||||
parent.appendChild(link);
|
||||
} else if (part) {
|
||||
parent.appendChild(document.createTextNode(part));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
markdown() {
|
||||
const posts = this.ordered();
|
||||
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';
|
||||
}
|
||||
|
||||
close() {
|
||||
this.stopWatching?.();
|
||||
this.stopWatching = null;
|
||||
const reader = this.reader;
|
||||
this.reader = null;
|
||||
if (reader?.open) reader.close();
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue