waybetter-for-x/apps/desktop/src-tauri/bundled-plugins/focus-mode.plugin.js
2026-09-30 23:01:13 +00:00

246 lines
12 KiB
JavaScript

/**
* @name Focus Mode
* @description Hides the parts of X that pull you away from reading: like/repost/reply/view counts, trends, "Who to follow", follower counts, or the whole right column. Alt+Shift+F turns it on and off; the toast that confirms it has a Settings button. Only hides what X already shows, locally; nothing on your account changes.
* @version 1.2.0
* @author wayBetter
* @permissions storage, ui, 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": {
"toggle": "Toggle Focus Mode",
"settingsCommand": "Focus Mode settings…",
"on": "Focus Mode on",
"off": "Focus Mode off",
"settings": "Settings",
"title": "Focus Mode",
"message": "Hide what pulls you away from reading. Alt+Shift+F turns Focus Mode on and off.",
"enabled": "Focus Mode is on",
"metrics": "Hide like, repost, reply and view counts",
"metricsHint": "The buttons keep working; only the numbers go.",
"trends": "Hide trends",
"whoToFollow": "Hide “Who to follow”",
"followCounts": "Hide follower and following counts",
"sidebar": "Hide the whole right column",
"sidebarHint": "Includes search, trends and suggestions.",
"cancel": "Cancel",
"save": "Save",
"saveFailed": "Could not save (storage unavailable)."
}
};
// 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 FocusMode {
static DEFAULTS = { enabled: true, metrics: true, trends: true, whoToFollow: true, followCounts: false, sidebar: false };
/** Settings from storage, with defaults for anything missing or not a boolean. */
static normalize(saved) {
const source = saved && typeof saved === 'object' ? saved : {};
const out = {};
for (const [key, fallback] of Object.entries(FocusMode.DEFAULTS)) out[key] = typeof source[key] === 'boolean' ? source[key] : fallback;
return out;
}
/**
* Selectors for a right-column module and the bordered card X draws around it (1px border, 16px
* corners and gap). Hiding only the module left that card behind as an empty box, so the card
* (its wrapper one or two levels up) goes too, but only when the module is all it holds.
* `base` is the module's landmark, `inside` what identifies it (optional). Pure, for tests.
*/
static sidebarModule(base, inside = '') {
const side = '[data-testid="sidebarColumn"]';
const target = inside ? `${base} ${inside}` : base;
return [
`${side} ${inside ? `${base}:has(${inside})` : base}`,
`${side} div:has(> ${target}):not(:has(> :not(${base})))`,
`${side} div:has(> div > ${target}):not(:has(> :not(div))):not(:has(> div > :not(${base})))`,
];
}
/** The CSS for `settings` (empty when Focus Mode is off or hides nothing). Pure, for tests. */
static css(settings) {
if (!settings.enabled) return '';
const rules = [];
const side = '[data-testid="sidebarColumn"]';
const hide = selectors => `${selectors.join(',\n')} { display: none !important; }`;
if (settings.metrics) {
// The numbers in each post's action bar (replies, reposts, likes, bookmarks, views); the buttons
// keep their place, so the bar does not jump.
rules.push(`article[data-testid="tweet"] [role="group"] [data-testid="app-text-transition-container"] { visibility: hidden !important; }`);
// The "· 1,234 Views" unit under an opened post, number, word and separator together (marked
// by markViews(); a views link outside the action bar is hidden even before it is marked).
rules.push(hide([
'article[data-testid="tweet"] [data-bt-fm-views]',
'article[data-testid="tweet"] [data-bt-fm-views-sep]',
'article[data-testid="tweet"] a[href$="/analytics"]:not([role="group"] a)',
]));
// Quote / repost / like counts under an opened post: the number goes without leaving a gap; the
// word stays as the link to who quoted, reposted or liked.
rules.push(hide(['quotes', 'retweets', 'likes'].map(kind => `article[data-testid="tweet"] a[href$="/${kind}"] [data-testid="app-text-transition-container"]`)));
}
if (settings.sidebar) {
rules.push(`${side} { visibility: hidden !important; }`);
} else {
if (settings.trends) {
rules.push(hide([
...FocusMode.sidebarModule('section[role="region"]', '[data-testid="trend"]'),
...FocusMode.sidebarModule('div[aria-label^="Timeline: Trending"]'),
`${side} div:has(> [data-testid="trend"])`,
]));
}
if (settings.whoToFollow) rules.push(hide(FocusMode.sidebarModule('aside[role="complementary"]', '[data-testid="UserCell"]')));
}
if (settings.followCounts) {
// Follower / following numbers on profiles and hover cards, without a gap; the words stay as
// the links to the lists. (`/<handle>/followers` links only: an @mention links to `/<handle>`,
// profile tabs are role="tab".)
const link = kind => `a[href$="/${kind}"]:not([href="/${kind}"]):not([role="tab"]) > span:first-child`;
rules.push(hide(['followers', 'verified_followers', 'following'].map(link)));
// X's text keeps white space (pre-wrap): the " " before "Followers" would stay as a gap.
rules.push(`${['followers', 'verified_followers', 'following'].map(kind => `a[href$="/${kind}"]:not([href="/${kind}"]):not([role="tab"])`).join(', ')} { white-space: nowrap !important; }`);
}
return rules.join('\n');
}
/**
* The views unit on an opened post's date line ("10:06 PM · Sep 28, 2026 · 1,234 Views"): walks up
* from the date link and returns the sibling holding the count (with the words after it) and the
* "·" separator before it, or null. DOM-shape only (tag, attributes, text), so tests can feed plain
* objects. Pure, for tests.
*/
static viewsParts(time) {
const isCount = el => el.getAttribute('data-testid') === 'app-text-transition-container'
|| (el.tagName === 'A' && /\/analytics\/?$/.test(el.getAttribute('href') || ''));
const has = (el, test) => test(el) || Array.from(el.children || []).some(child => has(child, test));
const isTime = el => el.tagName === 'TIME';
const isSeparator = el => /^[·•]$/.test((el.textContent || '').trim());
let node = time;
while (node.parentElement && node.tagName !== 'A') node = node.parentElement;
if (node.tagName !== 'A') node = time;
for (let depth = 0; depth < 4 && node && node.parentElement && node.parentElement.tagName !== 'ARTICLE'; depth += 1, node = node.parentElement) {
const separators = [];
for (let sib = node.nextElementSibling; sib; sib = sib.nextElementSibling) {
if (has(sib, isTime)) break;
if (isSeparator(sib)) { separators.push(sib); continue; }
if (!has(sib, isCount)) break;
// The count, then X's " " and "Views" when they are siblings of it, up to the next separator.
const unit = [sib];
for (let rest = sib.nextElementSibling; rest && !isSeparator(rest) && !has(rest, isTime); rest = rest.nextElementSibling) unit.push(rest);
return { unit, separators: separators.slice(-1) };
}
}
return null;
}
/** Marks the views unit of an opened post (focal posts print "time · date" in one link). */
markViews(time) {
if (!(time.textContent || '').includes('·')) return;
const parts = FocusMode.viewsParts(time);
if (!parts) return;
for (const el of parts.unit) el.setAttribute('data-bt-fm-views', '');
for (const el of parts.separators) el.setAttribute('data-bt-fm-views-sep', '');
}
start() {
const api = window.wayBetter.api;
i18n = api.i18n || null;
if (i18n) i18n.register(MESSAGES);
this.api = api;
this.store = api.storage('focus-mode');
this.scope = api.scope();
this.settings = FocusMode.normalize(this.store.get('settings', null));
this.apply();
this.scope.defer(() => api.clearCSS('focus-mode'));
// Re-marked when X re-renders the count (a new node) as well as when the date appears.
this.scope.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')) this.markViews(time);
});
this.scope.defer(() => {
for (const el of document.querySelectorAll('[data-bt-fm-views], [data-bt-fm-views-sep]')) {
el.removeAttribute('data-bt-fm-views');
el.removeAttribute('data-bt-fm-views-sep');
}
});
this.scope.on(document, 'keydown', event => {
if (!(event.altKey && event.shiftKey && !event.ctrlKey && !event.metaKey && event.code === 'KeyF')) return;
if (api.isTypingTarget(document.activeElement)) return;
event.preventDefault();
event.stopPropagation();
this.toggle();
}, true);
// Ctrl+K palette entries; they run here, in this tab (removed on stop with the scope).
if (this.scope.commands) {
this.scope.commands.register({ id: 'toggle', title: t('toggle'), keywords: 'focus distraction hide counts trends sidebar alt shift f', run: () => this.toggle() });
this.scope.commands.register({ id: 'settings', title: t('settingsCommand'), keywords: 'focus distraction configure options', run: () => this.openSettings() });
}
}
stop() {
this.scope.dispose();
}
apply() {
const css = FocusMode.css(this.settings);
if (css) this.api.injectCSS('focus-mode', css);
else this.api.clearCSS('focus-mode');
}
save(settings) {
this.settings = FocusMode.normalize(settings);
this.apply();
return this.store.set('settings', this.settings);
}
toggle() {
this.save({ ...this.settings, enabled: !this.settings.enabled });
// One toast for the latest state, not a stack of on/off/on.
this.notice?.close();
this.notice = this.scope.ui.toast(this.settings.enabled ? t('on') : t('off'), {
action: { label: t('settings'), onClick: () => this.openSettings() },
});
}
openSettings() {
if (this.dialog?.open) return;
const ui = this.scope.ui;
const h = ui.h;
const checks = {};
const check = (key, label, hint) => {
checks[key] = h('input', { type: 'checkbox', checked: this.settings[key] });
return h('label', { class: 'wb-check' }, checks[key], h('span', null, label, hint ? h('small', null, hint) : null));
};
this.dialog = ui.dialog({
title: t('title'),
message: t('message'),
content: body => body.append(
check('enabled', t('enabled')),
h('div', { class: 'wb-divider' }),
check('metrics', t('metrics'), t('metricsHint')),
check('trends', t('trends')),
check('whoToFollow', t('whoToFollow')),
check('followCounts', t('followCounts')),
check('sidebar', t('sidebar'), t('sidebarHint')),
),
actions: [
{ label: t('cancel') },
{
label: t('save'), tone: 'primary', default: true,
onClick: handle => {
const next = {};
for (const key of Object.keys(FocusMode.DEFAULTS)) next[key] = checks[key].checked;
if (!this.save(next)) { handle.setError(t('saveFailed')); return false; }
return undefined;
},
},
],
});
}
};