372 lines
22 KiB
Markdown
372 lines
22 KiB
Markdown
# Writing a wayBetter for X plugin
|
|
|
|
Plugins are BetterDiscord-style: one `*.plugin.js` file, a class with `start()` and `stop()`.
|
|
Install one from **wayBetter → Store**, drop the file on the wayBetter window, open a
|
|
`waybetter://install` link, or copy it into **wayBetter → Plugins → Open folder** and press
|
|
**Rescan**. Everything except copying by hand shows the install screen first (see
|
|
[Installing](#installing-links-files-and-the-store)). It starts and stops live, on every X page.
|
|
|
|
To start from a working example, open **wayBetter → Make** (example plugins, the UI kit gallery and
|
|
the live theme API), or scaffold a file or a TypeScript project with
|
|
`npm create waybetter plugin -- --name "My Plugin"` (add `--ts`).
|
|
|
|
## The smallest plugin
|
|
|
|
```js
|
|
/**
|
|
* @name Hide Trends
|
|
* @description Hides the right-column trends box.
|
|
* @version 1.0.0
|
|
* @author you
|
|
* @permissions network:none
|
|
*/
|
|
module.exports = class HideTrends {
|
|
start() { wayBetter.api.injectCSS('hide-trends', '[data-testid="sidebarColumn"] section { display: none }'); }
|
|
stop() { wayBetter.api.clearCSS('hide-trends'); }
|
|
};
|
|
```
|
|
|
|
The header comment is required: `@name`, `@description`, `@version`, `@author`, and it should
|
|
declare `@permissions` (next section).
|
|
|
|
## Permissions
|
|
|
|
A header declares what the plugin uses from the gated part of the API:
|
|
|
|
| Permission | Unlocks | Shown as |
|
|
| --- | --- | --- |
|
|
| `storage` | `api.storage(ns)` | Storage |
|
|
| `ui` | `api.ui`, `api.toast`, `scope.ui` | Dialogs |
|
|
| `clipboard` | `api.copyText` | Clipboard |
|
|
| `account` | `api.account()` (the signed-in handle, name, avatar) | Your account |
|
|
| `users` | `api.users` (what X's own responses said about accounts) | Account details |
|
|
| `commands` | `api.commands`, `scope.commands` (command palette entries) | Commands |
|
|
| `network` / `network:none` | nothing: a declaration (see below) | Internet / No network |
|
|
|
|
Everything else needs no permission: `injectCSS`/`clearCSS`, `adoptCSS`, `waitFor`, `observe`, `onRouteChange`,
|
|
`onKey`, `scope()` (css, adoptCSS, on, observe, add, defer, dispose, onThemeChange), `theme`, `tweet`,
|
|
`isTypingTarget`. Separate names with commas or spaces (`@permissions storage, ui, network:none`);
|
|
`none` alone means no gated API.
|
|
|
|
While the plugin's module body, constructor, `start()` and `stop()` run, `window.wayBetter.api` is
|
|
**that plugin's view**: a gated member it did not declare throws a `PluginPermissionError` such as
|
|
`my.plugin.js: api.copyText needs the "clipboard" permission. Add it to the plugin's header:
|
|
@permissions clipboard`. Keep the reference you read there (`const api = window.wayBetter.api` in
|
|
`start()`, or a scope) and use it in your callbacks. The install screen, the Store and the Plugins
|
|
list show the permissions; a header with an unknown permission is refused at install.
|
|
|
|
A plugin **without** a `@permissions` line is *legacy*: it gets the whole API as before and the app
|
|
labels it "Legacy · full page access". New plugins should always declare.
|
|
|
|
**What permissions are, honestly.** A plugin is JavaScript in the X page. It can read and change
|
|
the page, call `fetch`, reach `window.wayBetter` directly, and nothing running in the page can stop
|
|
code that tries to get around a check. Permissions are two things: a declaration you (and store
|
|
reviewers) read before installing, and a guard rail that makes honest code fail loudly when it uses
|
|
something it did not declare. They are not a sandbox. `network:none` is a promise: at install time
|
|
the app scans the code and refuses a file that declares `network:none` but calls `fetch`,
|
|
`XMLHttpRequest`, `WebSocket`, `EventSource` or `sendBeacon`; minified or obfuscated code can hide
|
|
calls from a scan, so read what you install.
|
|
|
|
## Clean up with a scope
|
|
|
|
A scope collects everything a plugin adds and undoes it in one call, so `stop()` leaves X exactly
|
|
as it was:
|
|
|
|
```js
|
|
module.exports = class Example {
|
|
start() {
|
|
const api = wayBetter.api;
|
|
this.scope = api.scope();
|
|
this.scope.css('example', '.my-note { opacity: .6 }');
|
|
this.scope.observe('article[data-testid="tweet"]', article => { /* decorate each post */ });
|
|
this.scope.onKey((event, tweet) => {
|
|
if (event.key === 'c' && tweet) api.copyText(api.tweet(tweet).url);
|
|
});
|
|
}
|
|
stop() { this.scope.dispose(); }
|
|
};
|
|
```
|
|
|
|
## API: `window.wayBetter.api`
|
|
|
|
Everything is local to the page: no network requests, no account actions. (`window.BetterTwttr`
|
|
is the same object, kept for older plugins.)
|
|
|
|
| Helper | What it does |
|
|
| --- | --- |
|
|
| `injectCSS(id, css)` / `clearCSS(id)` | Adds, replaces or removes a `<style>` by id. Should X's Content-Security-Policy ever refuse inline styles, the same rules are applied as an adopted stylesheet instead. |
|
|
| `adoptCSS(root, css)` | Styles a shadow root your plugin created (or the document) with a constructed stylesheet: X's CSP cannot refuse it, it is parsed once, and it stays with the root when X moves its host. Returns `{ sheet, adopted, update(css), remove() }` (a `<style>` element where the browser has no constructable sheets). Prefer it over a `<style>` inside your shadow root. |
|
|
| `waitFor(selector, timeoutMs = 15000)` | Resolves with the first match, rejects on timeout. |
|
|
| `storage(namespace)` | JSON storage in the X tab: `get(key, fallback)`, `set(key, value)` (returns `false` if it could not store), `remove(key)`, `keys()`. Namespaces are 1–64 of `[a-z0-9._-]`. |
|
|
| `onRouteChange((href, previous) => …)` | Called after X changes page. Returns a dispose function. |
|
|
| `observe(selector, element => …, root?)` | Calls back once per matching element, now and for every one X renders later (batched per frame). Returns a dispose function. |
|
|
| `onKey((event, focusedTweet) => …)` | Single-key shortcuts. Skipped while typing, with Ctrl/Meta/Alt held, and inside X's `g` chords. `focusedTweet` is the post focused with j/k, or `null`. |
|
|
| `tweet(element)` | Reads the post around `element`: `{ id, url, handle, name, text, time, media, element }`. `text` has emoji as characters and t.co links as the destination X shows. |
|
|
| `account()` | The signed-in account read from X's own account button: `{ handle, name, avatar }` or `null`. |
|
|
| `users.get(handle)` | What X's own responses said about a user this session: `{ xUserId, handle, blue, verifiedType, following }`. Each field is `null` when X hasn't said it yet (unknown, never guessed). Returns `null` for a handle not seen yet. |
|
|
| `copyText(text)` | Copies to the clipboard; resolves `true` / `false`. |
|
|
| `toast(message, ms?)` | A short status message at the bottom of the page (the UI kit's toast). |
|
|
| `ui` | Toasts, alerts, confirmations, prompts and dialogs in the current theme. See below. |
|
|
| `theme` | The active theme as values: `current()` and `onChange(fn)`. See below. |
|
|
| `commands` | Entries in the command palette (Ctrl+K) that run in this tab. See below. |
|
|
| `scope()` | A cleanup bag: `css`, `adoptCSS` (removed on dispose), `on(target, type, fn, options)`, `observe`, `onRouteChange`, `onKey`, `onThemeChange(fn)`, `ui`, `commands`, `add(node)`, `defer(fn)` and `dispose()`. |
|
|
|
|
`wayBetter.open(section?)` opens the wayBetter panel. Load errors appear in `wayBetter.errors`.
|
|
|
|
## Dialogs and toasts: `api.ui`
|
|
|
|
Use `this.scope.ui` (the same kit, but everything it opened closes on `scope.dispose()`, so
|
|
`stop()` never leaves a dialog behind). Dialogs look like X's own and follow the current theme:
|
|
background, text, borders, the filled button, corners and font, and they update live when the
|
|
theme or X's Display setting changes.
|
|
|
|
```js
|
|
const ui = this.scope.ui;
|
|
|
|
ui.toast('Link copied');
|
|
ui.toast('Saved', { tone: 'success' }); // neutral, info, success, warning, danger
|
|
ui.toast('Post hidden', { duration: 6000, action: { label: 'Undo', onClick: () => this.undo() } });
|
|
|
|
await ui.alert({ title: 'Done', message: 'Your list was exported.', tone: 'success' });
|
|
|
|
if (await ui.confirm({ title: 'Delete this note?', message: 'This cannot be undone.', confirmLabel: 'Delete', danger: true })) {
|
|
this.store.remove(handle);
|
|
}
|
|
|
|
const name = await ui.prompt({
|
|
title: 'Rename list', label: 'Name', value: current, placeholder: 'At least 3 characters',
|
|
validate: value => value.trim().length < 3 ? 'Use at least 3 characters.' : null,
|
|
});
|
|
if (name !== null) this.rename(name); // null = cancelled
|
|
```
|
|
|
|
A settings dialog, built with `ui.h` (a safe element builder: strings become text, `on…`
|
|
functions become listeners, no `innerHTML`):
|
|
|
|
```js
|
|
const h = ui.h;
|
|
const hideTrends = h('input', { type: 'checkbox', checked: settings.trends });
|
|
const words = h('textarea', { class: 'wb-mono', rows: 4, placeholder: 'one per line' });
|
|
const dialog = ui.dialog({
|
|
title: 'My plugin',
|
|
message: 'What should be hidden?',
|
|
content: body => body.append(
|
|
h('label', { class: 'wb-check' }, hideTrends, h('span', null, 'Hide trends', h('small', null, 'The right column only.'))),
|
|
h('label', { class: 'wb-field' }, h('span', { class: 'wb-label' }, 'Muted words'), words),
|
|
),
|
|
actions: [
|
|
{ label: 'Cancel' },
|
|
{ label: 'Save', tone: 'primary', default: true, onClick: handle => {
|
|
if (!this.store.set('settings', { trends: hideTrends.checked, words: words.value })) {
|
|
handle.setError('Could not save.');
|
|
return false; // keeps the dialog open
|
|
}
|
|
} },
|
|
],
|
|
});
|
|
// dialog.element, dialog.body, dialog.close(result), await dialog.closed
|
|
```
|
|
|
|
| Call | Returns |
|
|
| --- | --- |
|
|
| `toast(message, { tone, duration, action })` | `{ element, close(), closed }`. `duration` in ms, `0` stays until closed; 3.2 s by default, 6 s with an action. |
|
|
| `alert({ title, message, tone, okLabel })` | `Promise<void>` |
|
|
| `confirm({ title, message, confirmLabel, cancelLabel, danger })` | `Promise<boolean>`; Esc, Cancel and a backdrop click are `false`. |
|
|
| `prompt({ title, message, label, value, placeholder, validate, multiline, maxLength })` | `Promise<string \| null>`; `validate` returns an error message to refuse a value. |
|
|
| `dialog({ title, message, content, actions, width, css, closeOnBackdrop, onClose })` | `{ element, body, open, closed, close(result), setError(text), setBusy(bool) }` |
|
|
| `modal(options)` | The primitive under all of them (adds `role`, `dismissible`, `initialFocus`, `stackActions`). |
|
|
|
|
`content` is text, a node, or `body => { … }`. An action is `{ label, tone: 'primary' | 'secondary'
|
|
| 'danger' | 'plain', onClick(handle), value, default, autoFocus, disabled }`; `onClick` may be
|
|
async and returns `false` to keep the dialog open. `width` is px or `sm` / `md` / `lg`.
|
|
|
|
How they behave:
|
|
|
|
- Focus moves into the dialog, Tab and Shift+Tab stay inside it, and focus goes back where it was
|
|
when it closes. Esc dismisses. Enter in a one-line field runs the `default` action (Ctrl+Enter
|
|
in a text area). A `danger` confirmation starts on Cancel.
|
|
- Clicking the backdrop dismisses alerts and confirmations, never prompts or dialogs (unless
|
|
`closeOnBackdrop: true`), so typed text is not lost.
|
|
- Keys typed in a dialog never reach X's shortcuts or `onKey` handlers.
|
|
- A second dialog stacks on top (the one below becomes inert until it closes). Up to four toasts
|
|
stack; hovering or focusing one holds it.
|
|
- Screen readers get `role="dialog"` / `role="alertdialog"`, `aria-modal`, the title as the label
|
|
and the message as the description. Toasts are a polite live region; danger toasts are alerts.
|
|
- With "reduce motion" on in the system, nothing animates.
|
|
- Dialogs live in a Shadow DOM, so X's CSS cannot change them and your document CSS cannot style
|
|
their content either: use the built-in classes (`wb-field`, `wb-label`, `wb-hint`, `wb-check`,
|
|
`wb-input`, `wb-mono`, `wb-divider`, `wb-row`, `wb-muted`) or pass `css` to the dialog.
|
|
|
|
## Matching the theme: `api.theme`
|
|
|
|
```js
|
|
const { colors, radius, font, mode, siteDefault } = wayBetter.api.theme.current();
|
|
this.scope.onThemeChange(theme => this.redraw(theme));
|
|
```
|
|
|
|
`colors` has `bg`, `surface`, `elevated`, `border`, `text`, `muted`, `accent`, `onAccent`,
|
|
`inverse` and `onInverse` (X's filled Post button and its label) and `page`, all `#rrggbb`.
|
|
`radius` and `buttonRadius` are px, `font` is a `font-family` stack, `mode` is `light` or `dark`.
|
|
With "X default" selected these are X's own colors for Default or Lights out. The same values
|
|
are CSS variables on `:root`, for plugin CSS:
|
|
|
|
```css
|
|
.my-badge { background: var(--wb-surface); color: var(--wb-muted); border: 1px solid var(--wb-border);
|
|
border-radius: var(--wb-radius); font-family: var(--wb-font); }
|
|
.my-badge a { color: var(--wb-accent); }
|
|
```
|
|
|
|
Variables: `--wb-bg`, `--wb-surface`, `--wb-elevated`, `--wb-border`, `--wb-text`, `--wb-muted`,
|
|
`--wb-accent`, `--wb-on-accent`, `--wb-inverse`, `--wb-on-inverse`, `--wb-page`, `--wb-radius`,
|
|
`--wb-button-radius`, `--wb-font`, `--wb-mode`, and one stack per font role: `--wb-font-interface`,
|
|
`--wb-font-post`, `--wb-font-heading`, `--wb-font-numbers`, `--wb-font-mono`, `--wb-font-chrome`,
|
|
`--wb-font-dialog` (the UI kit uses `--wb-font-dialog`). `current().fonts` has the same roles with
|
|
`{ stack, weight, size, tracking, tabular, inherited }` (weight/tracking `null` = unchanged).
|
|
|
|
## Commands in the palette: `api.commands`
|
|
|
|
A plugin can put its actions in the app's command palette (Ctrl+K). They are listed under the
|
|
plugin's name, found by title and keywords, and run **in the X tab you were using**, inside your
|
|
plugin (the palette only asks that tab to call your `run`):
|
|
|
|
```js
|
|
/**
|
|
* @name Quiet Hours
|
|
* @version 1.0.0
|
|
* @permissions storage, ui, commands, network:none
|
|
*/
|
|
module.exports = class QuietHours {
|
|
start() {
|
|
const api = wayBetter.api;
|
|
this.scope = api.scope();
|
|
this.scope.commands.register({
|
|
id: 'toggle', // unique in your plugin: letters, digits, . _ - (≤ 64)
|
|
title: 'Toggle quiet hours', // shown in the palette (≤ 80 characters kept)
|
|
keywords: ['mute', 'night', 'calm'],// string or list (≤ 160 characters kept)
|
|
shortcut: 'Alt+Shift+Q', // optional: works while this X tab has focus, not while typing
|
|
run: () => this.toggle(), // may return a Promise; errors are caught and logged
|
|
});
|
|
}
|
|
stop() { this.scope.dispose(); } // removes the command (it would go anyway, see below)
|
|
toggle() { /* … */ }
|
|
};
|
|
```
|
|
|
|
- `scope.commands.register(def)` belongs to your plugin and is removed on `scope.dispose()`.
|
|
`api.commands.register(def)` returns a dispose function. Registering the same `id` again replaces
|
|
the entry.
|
|
- When the app stops a plugin (turned off, removed, reloaded) it also removes every command that
|
|
plugin registered, even ones it forgot. Commands registered in the constructor or `start()`
|
|
belong to the plugin automatically; a scope created there keeps that
|
|
owner for later registrations (after an `await`, in a callback). Commands registered anywhere
|
|
else are listed under "Plugins".
|
|
- Limits: 16 commands per plugin, 48 per tab. What leaves the page is only `{ id, title, keywords }`
|
|
(strings, capped); your `run` never does. With a `@permissions` line, declare `commands`.
|
|
- Focus Mode ("Toggle Focus Mode", "Focus Mode settings…"), Thread Reader ("Read this thread") and
|
|
Hide Blue Checks ("Hide Blue Checks settings…") register commands; see their source.
|
|
|
|
## Your words in the app's language: `api.i18n`
|
|
|
|
`api.i18n` is bound to your plugin. Register your strings per language (English is the fallback)
|
|
and look them up; the app's language changes live, so re-render on `onChange`:
|
|
|
|
```js
|
|
const i18n = window.wayBetter.api.i18n;
|
|
i18n.register({
|
|
en: { saved: 'Saved {count, plural, one {# note} other {# notes}}' },
|
|
tr: { saved: '{count, plural, one {# not} other {# not}} kaydedildi' },
|
|
});
|
|
window.wayBetter.api.ui.toast(i18n.t('saved', { count: 2 }));
|
|
this.scope.defer(i18n.onChange(() => this.render()));
|
|
i18n.locale; i18n.dir; // 'tr', 'ltr' ('rtl' for Arabic, Persian, Hebrew, Urdu)
|
|
i18n.number(1234.5); i18n.date(Date.now(), { dateStyle: 'medium' }); i18n.relative(-3, 'minute');
|
|
```
|
|
|
|
Messages use the syntax in [TRANSLATING.md](https://git.crt.fyi/CRT/better-twttr/src/branch/main/docs/TRANSLATING.md) (placeholders, plurals, select). Values
|
|
are inserted as text, never HTML. The UI kit's own buttons (OK, Cancel…) already follow the app's
|
|
language. Not a permission: every plugin has `api.i18n`. The bundled plugins are translated in the
|
|
app's catalogs (`plugin.<file name>.*`), so your file's name is its namespace there too.
|
|
|
|
## Live reload (developer mode)
|
|
|
|
Settings → Developer → **Developer mode** (off by default). While it is on, the app watches the
|
|
plugins folder, `custom.css` and one theme file you pick, and applies a saved change to every X tab
|
|
at once:
|
|
|
|
- **Plugins**: an enabled `*.plugin.js` you save is checked for syntax first (in the app, never
|
|
run); if it parses, the old version is stopped (`stop()`, its commands removed) and the new one
|
|
started. A syntax error keeps the running version and is shown as `file:line:column — message`.
|
|
An error thrown while the new version starts is shown as a toast in the X tab with the file and
|
|
line (reloaded plugins are evaluated as `wb-dev/<file>`, so DevTools stack traces name your file).
|
|
- **`custom.css`** and the **theme file** (a theme `.json`, e.g. from `npm create waybetter theme`
|
|
or Appearance → Export) apply instantly. The theme file is shown as a preview in every X tab and
|
|
is never saved; turning developer mode off (or "Stop watching") gives the tabs your theme back.
|
|
JSON errors are shown with line and column.
|
|
- Order: theme, then custom CSS, then plugins by file name. A file counts as changed once it has
|
|
stayed the same for 250 ms, so an editor's multi-step save reloads once.
|
|
- Errors are listed in Settings → Developer and in a small chip in the titlebar.
|
|
|
|
The watcher is native, reads only those files, and gives X tabs nothing new: they receive the same
|
|
start/stop/CSS/theme scripts the app always sends.
|
|
|
|
## Good manners
|
|
|
|
- Never make network requests and never act on the account (like, follow, post, delete). Say so:
|
|
`@permissions … network:none`.
|
|
- Use `observe` / `scope` instead of your own `MutationObserver` or timers: callbacks are batched
|
|
per frame and `dispose()` removes everything, which keeps X fast.
|
|
- `stop()` must undo everything, including per-element changes.
|
|
- Settings go in `api.storage('your-plugin')`; settings dialogs and confirmations go through
|
|
`scope.ui`.
|
|
|
|
## Area plugins, and the plugin files to learn from
|
|
|
|
What the app itself offers is grouped into eight **area plugins**: Compose+, Reader+, Profile+,
|
|
Chat+, Media+, Search+, Notifications+ and Navigation+. Each is one card in **wayBetter → Plugins**
|
|
with a switch for the whole area and a toggle for every feature. The 46 switches that used to be
|
|
"Tweaks" and thirteen of the fourteen plugins the app shipped as files (Thread Reader, Exact
|
|
Timestamps, Clean Links, Copy as Markdown, Alt-text Reminder, User Notes, Muted Regex, Reading
|
|
Time, Media Grid Focus, Keyboard Plus, Hide Blue Checks, Focus Mode and Reply Guard) are features of
|
|
their area now. They are compiled into the app as feature modules
|
|
(`apps/desktop/src/areas/<area>/`; `docs/AREA-PLUGINS.md` in the repository is the contract) and use
|
|
the same `api` a plugin file gets. Emoji Picker is still a plugin file.
|
|
|
|
On an update, a plugin file that became a feature is handled once: if you had it on, its feature is
|
|
on and the file is gone; if you had edited the file, your copy stays, keeps its on/off state, and
|
|
the built-in feature stays off until you choose it. Its settings and notes stay where they were.
|
|
|
|
The fourteen files are still in `apps/desktop/src-tauri/bundled-plugins/` as complete, readable
|
|
examples of the plugin API: Hide Blue Checks, Muted Regex, User Notes, Thread Reader, Focus Mode and
|
|
Reply Guard use the UI kit. More ideas, and the rules they are measured against, are in
|
|
[PLUGIN-IDEAS.md](./PLUGIN-IDEAS.md). A plugin you install yourself (the Store, a dropped file, the
|
|
folder) is listed under the area cards and stays off until you turn it on.
|
|
|
|
## Installing: links, files and the Store
|
|
|
|
Owner-approved (2026-09-28): besides copying files into the plugins folder, a plugin or theme can be
|
|
installed three ways, and each one goes through the same **install screen** in the app's own window
|
|
(never in an X tab):
|
|
|
|
- **Drop the file** (`.plugin.js` or a theme `.json`) on the wayBetter window.
|
|
- **Open a link** `waybetter://install?kind=plugin&url=<https URL>` (or `kind=theme`). The URL must
|
|
be https on `waybetter.fyi`, `cdn1.crt.fyi` or `git.crt.fyi` (raw files only), without
|
|
credentials or a port; the app downloads it itself (no redirects, no cookies, 2 MB cap).
|
|
- **The Store** (wayBetter → Store): a catalog signed with the store's Ed25519 key; the app verifies
|
|
the signature and then each download's SHA-256 and size against it.
|
|
|
|
The screen shows the name, author, version, where it came from, the SHA-256, the declared
|
|
permissions (or the legacy badge), what the source scan found, and the exact code (for themes, a
|
|
live preview, the file and its CSS). Install stays disabled for a moment and Enter never confirms
|
|
it. Nothing is written before you press Install; a plugin installed this way is only turned on if
|
|
you leave "Turn it on now" checked (off by default for legacy plugins and when the scan found
|
|
something). Updating a plugin keeps its on/off state. Web pages and X tabs cannot install anything:
|
|
the install commands belong to the app's local window only, and a link only opens the screen.
|
|
|
|
To publish in the Store (<https://waybetter.fyi/store/>), add one folder in a pull request: see
|
|
<https://waybetter.fyi/store/submit/> (the steps are also in `docs/STORE.md` in the source repository).
|
|
|
|
## Trust
|
|
|
|
A plugin runs inside the X page with the page's own access. Install only code you trust, the same
|
|
way you would a browser extension. Permissions tell you what it says it uses from wayBetter; the
|
|
code preview tells you what it does.
|