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

174 lines
7.9 KiB
JavaScript

/**
* @name Reply Guard
* @description Asks before you reply to an old post (older than 30 days by default) and, if you turn it on, to someone you don't follow. Answer "Reply anyway" and X's own reply box opens as usual; nothing is ever sent for you. Uses only the post's date and what X's own responses said about who you follow (unknown never asks). Alt+Shift+R edits settings.
* @version 1.1.0
* @author wayBetter
* @permissions storage, ui, account, users, 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": {
"day": "{count, plural, one {# day} other {# days}}",
"month": "{count, plural, one {# month} other {# months}}",
"year": "{count, plural, one {# year} other {# years}}",
"old": "This post is {age} old.",
"stranger": "You don't follow {handle}.",
"confirmTitle": "Reply to this post?",
"replyAnyway": "Reply anyway",
"cancel": "Cancel",
"title": "Reply Guard",
"message": "Ask before replying to old posts or to people you do not follow. Nothing is sent for you: “Reply anyway” opens X's own reply box.",
"days": "Ask for posts older than (days)",
"daysHint": "0 turns this check off.",
"strangers": "Ask before replying to someone you don't follow",
"strangersHint": "Only when X has already said you do not follow them.",
"save": "Save",
"daysInvalid": "Enter a whole number of days from 0 to 3650.",
"saveFailed": "Could not save (storage unavailable).",
"saved": "Reply Guard: settings saved"
}
};
// 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 ReplyGuard {
static DEFAULTS = { oldDays: 30, strangers: false };
static DAY = 24 * 60 * 60 * 1000;
static normalize(saved) {
const source = saved && typeof saved === 'object' ? saved : {};
const days = Number(source.oldDays);
return {
oldDays: Number.isFinite(days) ? Math.max(0, Math.min(3650, Math.round(days))) : ReplyGuard.DEFAULTS.oldDays,
strangers: typeof source.strangers === 'boolean' ? source.strangers : ReplyGuard.DEFAULTS.strangers,
};
}
/** "3 years", "5 months", "45 days" for an age in days. */
static formatAge(days) {
if (days >= 365) return t('year', { count: Math.floor(days / 365) });
if (days >= 60) return t('month', { count: Math.floor(days / 30) });
return t('day', { count: Math.max(1, Math.floor(days)) });
}
/**
* Pure decision: why a reply to this post deserves a question, or null. `ctx`: `time` (ISO date of
* the post or null), `now` (ms), `following` (true / false / null = not known), `own` (the post is yours).
* Unknown values never ask.
*/
static reason(settings, ctx) {
if (ctx.own) return null;
const reasons = [];
const posted = ctx.time ? Date.parse(ctx.time) : NaN;
if (settings.oldDays > 0 && Number.isFinite(posted)) {
const days = (ctx.now - posted) / ReplyGuard.DAY;
if (days >= settings.oldDays) reasons.push(t('old', { age: ReplyGuard.formatAge(days) }));
}
if (settings.strangers && ctx.following === false) reasons.push(t('stranger', { handle: `@${ctx.handle}` }));
return reasons.length ? reasons.join(' ') : null;
}
start() {
const api = window.wayBetter.api;
i18n = api.i18n || null;
if (i18n) i18n.register(MESSAGES);
this.api = api;
this.store = api.storage('reply-guard');
this.scope = api.scope();
this.settings = ReplyGuard.normalize(this.store.get('settings', null));
this.allowed = null;
// Capture on window runs before X's own handlers: the click (or X's "r" shortcut) is held until
// you answer, then X's own reply button is clicked for you, which only opens X's reply box.
this.scope.on(window, 'click', event => {
const button = event.target?.closest?.('article[data-testid="tweet"] [data-testid="reply"]');
if (button) this.intercept(event, button);
}, true);
this.scope.on(window, 'keydown', event => {
if (event.key !== 'r' || event.ctrlKey || event.metaKey || event.altKey || event.repeat) return;
if (api.isTypingTarget(event.target) || api.isTypingTarget(document.activeElement)) return;
const button = document.activeElement?.closest?.('article[data-testid="tweet"]')?.querySelector('[data-testid="reply"]');
if (button) this.intercept(event, button);
}, true);
this.scope.on(document, 'keydown', event => {
if (event.altKey && event.shiftKey && !event.ctrlKey && !event.metaKey && event.code === 'KeyR') {
if (api.isTypingTarget(document.activeElement)) return;
event.preventDefault();
event.stopPropagation();
this.openSettings();
}
}, true);
}
stop() {
this.scope.dispose();
this.allowed = null;
}
intercept(event, button) {
if (this.allowed === button) { this.allowed = null; return; }
const article = button.closest('article[data-testid="tweet"]');
const tweet = this.api.tweet(article);
if (!tweet) return;
const viewer = this.api.account()?.handle;
const why = ReplyGuard.reason(this.settings, {
time: tweet.time,
now: Date.now(),
handle: tweet.handle,
following: this.settings.strangers ? this.api.users.get(tweet.handle)?.following ?? null : null,
own: !!viewer && viewer.toLowerCase() === tweet.handle.toLowerCase(),
});
if (!why) return;
event.preventDefault();
event.stopImmediatePropagation();
if (this.asking) return;
this.asking = true;
this.scope.ui.confirm({ title: t('confirmTitle'), message: why, confirmLabel: t('replyAnyway'), cancelLabel: t('cancel') }).then(ok => {
this.asking = false;
if (!ok || !button.isConnected) return;
// click() dispatches synchronously: the capture listener sees `allowed` and lets this one through.
this.allowed = button;
try { button.click(); } finally { this.allowed = null; }
});
}
openSettings() {
if (this.dialog?.open) return;
const ui = this.scope.ui;
const h = ui.h;
const days = h('input', { type: 'number', min: 0, max: 3650, step: 1, value: String(this.settings.oldDays), 'aria-describedby': 'rg-days-hint' });
const strangers = h('input', { type: 'checkbox', checked: this.settings.strangers });
this.dialog = ui.dialog({
title: t('title'),
message: t('message'),
content: body => body.append(
h('label', { class: 'wb-field' }, h('span', { class: 'wb-label' }, t('days')), days,
h('p', { class: 'wb-hint', id: 'rg-days-hint' }, t('daysHint'))),
h('label', { class: 'wb-check' }, strangers, h('span', null, t('strangers'),
h('small', null, t('strangersHint')))),
),
actions: [
{ label: t('cancel') },
{
label: t('save'), tone: 'primary', default: true,
onClick: handle => {
const value = Number(days.value);
if (!Number.isInteger(value) || value < 0 || value > 3650) {
days.setAttribute('aria-invalid', 'true');
handle.setError(t('daysInvalid'));
return false;
}
this.settings = ReplyGuard.normalize({ oldDays: value, strangers: strangers.checked });
if (!this.store.set('settings', this.settings)) { handle.setError(t('saveFailed')); return false; }
ui.toast(t('saved'), { tone: 'success' });
return undefined;
},
},
],
});
}
};