wayBetter for X
This commit is contained in:
commit
df5dff619e
720 changed files with 147465 additions and 0 deletions
202
apps/desktop/src/inject/drafts.ts
Normal file
202
apps/desktop/src/inject/drafts.ts
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
// "Drafts" button in X's composer toolbar. Clicking it only asks native code (the narrow
|
||||
// `drafts_picker_open` command) to show the drafts popover right under the button: a local
|
||||
// webview layered over this tab, so X stays visible. The page reports the button's rect in its own
|
||||
// viewport and never reads the vault; the popover lists drafts and native code inserts the chosen
|
||||
// text into the marked composer.
|
||||
//
|
||||
// On a post page, an empty reply composer also asks `drafts_hint` (yes/no, for the webview's own
|
||||
// URL) and shows a "Continue your draft?" chip when a captured draft for this conversation exists.
|
||||
import { t } from './i18n.ts';
|
||||
import { COMPOSER_SELECTOR, identifyComposer, isExcludedComposerPath } from '../observer/composer.ts';
|
||||
import { watchDom } from './domHub.ts';
|
||||
|
||||
export const TOOLBAR_SELECTOR = '[data-testid="toolBar"]';
|
||||
export const BUTTON_ATTR = 'data-bt-drafts-button';
|
||||
export const HINT_ATTR = 'data-bt-drafts-hint';
|
||||
/** Must match `compose::TARGET_ATTRIBUTE` in src-tauri. */
|
||||
export const TARGET_ATTR = 'data-bt-draft-target';
|
||||
const ICON = 'M6 3h9l5 5v12a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zm8 1.5V9h4.5M8 13h8M8 17h5';
|
||||
const FALLBACK_TINT = 'rgb(29, 155, 240)';
|
||||
/** Scrolls this soon after opening are layout settling, not the user moving away. */
|
||||
const SCROLL_GRACE_MS = 250;
|
||||
/** How long a hint answer for a post page is reused before asking again. */
|
||||
const HINT_TTL_MS = 30_000;
|
||||
|
||||
/** `x`/`y`: the anchor's left and bottom edge in the tab's viewport; `width`/`height`: its size. */
|
||||
export type PickerRequest = { kind: 'post' | 'reply' | 'quote' | null; x: number; y: number; width?: number; height?: number };
|
||||
type Invoke = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||
|
||||
/** The single composer editor that shares a composer area with this toolbar, if any. */
|
||||
export function editorForToolbar(toolbar: Element): HTMLElement | null {
|
||||
let area: Element | null = toolbar.parentElement;
|
||||
for (let depth = 0; area && depth < 40; depth++, area = area.parentElement) {
|
||||
const editors = area.querySelectorAll<HTMLElement>(COMPOSER_SELECTOR);
|
||||
if (editors.length === 1) return editors[0];
|
||||
if (editors.length > 1) return null;
|
||||
if (area.matches('main,body,[data-testid="primaryColumn"]')) return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The request for an anchor element's viewport rect (whole CSS px). */
|
||||
export function anchorRequest(rect: { left: number; top: number; width: number; height: number }, kind: PickerRequest['kind']): PickerRequest {
|
||||
return { kind, x: Math.round(rect.left), y: Math.round(rect.top + rect.height), width: Math.round(rect.width), height: Math.round(rect.height) };
|
||||
}
|
||||
|
||||
/** A post page, where an inline reply composer belongs to exactly one conversation. */
|
||||
export function isPostPath(pathname: string): boolean {
|
||||
return /^\/(?!i\/)[^/]+\/status\/\d+(?:\/|$)/.test(pathname);
|
||||
}
|
||||
|
||||
/** `rgb(r, g, b)` / `rgba(r, g, b, a)` with the given alpha; the fallback tint for anything else. */
|
||||
export function withAlpha(color: string, alpha: number): string {
|
||||
const match = /^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/.exec(color);
|
||||
const [r, g, b] = match ? match.slice(1, 4) : ['29', '155', '240'];
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
}
|
||||
|
||||
/** X's own icon color in this toolbar (it follows the user's accent), so the button fits in. */
|
||||
function toolbarTint(win: Window, row: Element): string {
|
||||
const icon = row.querySelector('svg');
|
||||
const color = icon ? win.getComputedStyle(icon).color : '';
|
||||
return /^rgba?\(/.test(color) ? color : FALLBACK_TINT;
|
||||
}
|
||||
|
||||
function makeButton(doc: Document, tint: string, onClick: (anchor: HTMLElement) => void): HTMLElement {
|
||||
const button = doc.createElement('button');
|
||||
button.type = 'button';
|
||||
button.setAttribute(BUTTON_ATTR, '');
|
||||
button.setAttribute('aria-label', t('x.drafts.button'));
|
||||
button.setAttribute('aria-haspopup', 'dialog');
|
||||
button.title = t('x.drafts.title');
|
||||
button.style.cssText = `background:none;border:0;padding:0;margin:0 2px;width:34px;height:34px;min-width:34px;cursor:pointer;color:${tint};display:inline-flex;align-items:center;justify-content:center;border-radius:9999px;transition:background-color .15s ease;outline-offset:1px;`;
|
||||
button.innerHTML = `<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${ICON}"/></svg>`;
|
||||
const hover = withAlpha(tint, 0.1);
|
||||
button.addEventListener('mouseenter', () => { button.style.backgroundColor = hover; });
|
||||
button.addEventListener('mouseleave', () => { button.style.backgroundColor = 'transparent'; });
|
||||
button.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onClick(button);
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
function makeHint(doc: Document, tint: string, onClick: (anchor: HTMLElement) => void): HTMLElement {
|
||||
const chip = doc.createElement('button');
|
||||
chip.type = 'button';
|
||||
chip.setAttribute(HINT_ATTR, '');
|
||||
chip.setAttribute('aria-haspopup', 'dialog');
|
||||
chip.title = t('x.drafts.hintTitle');
|
||||
chip.style.cssText = `display:inline-flex;align-items:center;gap:6px;height:26px;min-width:0;flex:0 1 auto;margin:0 4px;padding:0 10px 0 8px;border-radius:9999px;border:1px solid ${withAlpha(tint, 0.35)};background:${withAlpha(tint, 0.1)};color:${tint};font:600 13px/1 inherit;font-family:inherit;white-space:nowrap;overflow:hidden;cursor:pointer;transition:background-color .15s ease,opacity .2s ease;`;
|
||||
const dot = doc.createElement('span');
|
||||
dot.style.cssText = `width:6px;height:6px;flex:none;border-radius:50%;background:${tint};box-shadow:0 0 0 3px ${withAlpha(tint, 0.2)};`;
|
||||
const label = doc.createElement('span');
|
||||
label.textContent = t('x.drafts.hint');
|
||||
label.style.cssText = 'overflow:hidden;text-overflow:ellipsis;';
|
||||
chip.append(dot, label);
|
||||
chip.addEventListener('mouseenter', () => { chip.style.backgroundColor = withAlpha(tint, 0.18); });
|
||||
chip.addEventListener('mouseleave', () => { chip.style.backgroundColor = withAlpha(tint, 0.1); });
|
||||
chip.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onClick(chip);
|
||||
chip.remove();
|
||||
});
|
||||
return chip;
|
||||
}
|
||||
|
||||
export type DraftsButtonHandle = { rescan(): void; dispose(): void };
|
||||
|
||||
export function installDraftsButton(win: Window, invoke: Invoke | undefined): DraftsButtonHandle {
|
||||
const doc = win.document;
|
||||
let active = true;
|
||||
/** Post path -> hint answer (pending or settled), so X's re-renders do not ask again. */
|
||||
const hints = new Map<string, { at: number; answer: Promise<boolean> }>();
|
||||
let stopWatching: (() => void) | null = null;
|
||||
|
||||
// While the popover is open, scrolling X moves the button away from it: close the popover. The
|
||||
// page gets focus back when the popover closes for any other reason, which ends the watch.
|
||||
const watchWhileOpen = () => {
|
||||
stopWatching?.();
|
||||
const openedAt = win.performance.now();
|
||||
const onScroll = () => {
|
||||
if (win.performance.now() - openedAt < SCROLL_GRACE_MS) return;
|
||||
stop();
|
||||
invoke?.('drafts_popover_dismiss').catch(() => {});
|
||||
};
|
||||
const stop = () => {
|
||||
win.removeEventListener('scroll', onScroll, true);
|
||||
win.removeEventListener('focus', stop);
|
||||
win.clearTimeout(timer);
|
||||
if (stopWatching === stop) stopWatching = null;
|
||||
};
|
||||
const timer = win.setTimeout(stop, 10 * 60_000);
|
||||
win.addEventListener('scroll', onScroll, { capture: true, passive: true });
|
||||
win.addEventListener('focus', stop);
|
||||
stopWatching = stop;
|
||||
};
|
||||
|
||||
const open = (anchor: HTMLElement) => {
|
||||
const toolbar = anchor.closest(TOOLBAR_SELECTOR);
|
||||
const editor = toolbar ? editorForToolbar(toolbar) : null;
|
||||
if (!editor || !invoke) return;
|
||||
for (const marked of doc.querySelectorAll(`[${TARGET_ATTR}]`)) marked.removeAttribute(TARGET_ATTR);
|
||||
editor.setAttribute(TARGET_ATTR, '');
|
||||
const context = identifyComposer(editor, win.location);
|
||||
invoke('drafts_picker_open', { request: anchorRequest(anchor.getBoundingClientRect(), context?.kind ?? null) })
|
||||
.then(watchWhileOpen)
|
||||
.catch(error => console.warn('[wayBetter for X] drafts popover unavailable', error));
|
||||
};
|
||||
|
||||
const offerHint = (row: Element, button: HTMLElement, editor: HTMLElement, tint: string) => {
|
||||
const path = win.location.pathname;
|
||||
if (!invoke || !isPostPath(path) || editor.textContent?.trim() || row.querySelector(`[${HINT_ATTR}]`)) return;
|
||||
const now = win.performance.now();
|
||||
let cached = hints.get(path);
|
||||
if (!cached || now - cached.at > HINT_TTL_MS) {
|
||||
cached = { at: now, answer: invoke('drafts_hint').then(value => value === true, () => false) };
|
||||
hints.set(path, cached);
|
||||
}
|
||||
void cached.answer.then(yes => {
|
||||
// Still the same page, still empty, still on screen, still no chip.
|
||||
if (!yes || !active || win.location.pathname !== path || !button.isConnected || editor.textContent?.trim() || row.querySelector(`[${HINT_ATTR}]`)) return;
|
||||
const chip = makeHint(doc, tint, open);
|
||||
button.after(chip);
|
||||
// Typing means the user is writing something new here: the offer goes away.
|
||||
editor.addEventListener('input', () => chip.remove(), { once: true });
|
||||
});
|
||||
};
|
||||
|
||||
const scan = () => {
|
||||
if (!active || isExcludedComposerPath(win.location.pathname)) return;
|
||||
for (const toolbar of doc.querySelectorAll(TOOLBAR_SELECTOR)) {
|
||||
const editor = editorForToolbar(toolbar);
|
||||
if (!editor) continue;
|
||||
// X's icon row (media, GIF, poll, emoji, ...) is the toolbar's first flex child.
|
||||
const row = toolbar.querySelector('[role="tablist"]') ?? toolbar.firstElementChild ?? toolbar;
|
||||
let button = toolbar.querySelector<HTMLElement>(`[${BUTTON_ATTR}]`);
|
||||
if (!button) {
|
||||
button = makeButton(doc, toolbarTint(win, row), open);
|
||||
row.appendChild(button);
|
||||
}
|
||||
offerHint(row, button, editor, button.style.color || FALLBACK_TINT);
|
||||
}
|
||||
};
|
||||
// Shared body observer + frame (domHub.ts); composers on chat pages are excluded anyway.
|
||||
const watch = watchDom(win as Window & typeof globalThis, scan, { offOnChat: true });
|
||||
const start = () => { if (!active || !doc.body) return; scan(); };
|
||||
if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', start, { once: true });
|
||||
else start();
|
||||
return {
|
||||
rescan: scan,
|
||||
dispose() {
|
||||
active = false;
|
||||
doc.removeEventListener('DOMContentLoaded', start);
|
||||
watch.dispose();
|
||||
stopWatching?.();
|
||||
for (const node of doc.querySelectorAll(`[${BUTTON_ATTR}],[${HINT_ATTR}]`)) node.remove();
|
||||
for (const marked of doc.querySelectorAll(`[${TARGET_ATTR}]`)) marked.removeAttribute(TARGET_ATTR);
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue