/** * @name User Notes * @description Private notes on accounts: "Add private note" in a profile's ··· menu opens a note editor; the note shows under the bio (click it to edit) and in hover cards. Notes stay in this app's local storage and are never sent anywhere. * @version 1.3.1 * @author wayBetter * @permissions storage, ui, network:none */ const HANDLE = /^@([A-Za-z0-9_]{1,15})$/; // i18n:begin // This plugin's English words. Translations live in the app's catalogs (plugin..*, // docs/TRANSLATING.md); a plugin of your own can also pass { en: {...}, tr: {...} } to register. const MESSAGES = { "en": { "hoverPrefix": "Your note: ", "boxLabel": "Your private note about {handle}. Edit", "label": "Your private note", "placeholder": "Only you can see this.", "areaLabel": "Private note about {handle}", "title": "Note about {handle}", "message": "Private: kept on this device only, never sent anywhere. Ctrl+Enter saves.", "delete": "Delete", "deleteTitle": "Delete this note?", "deleteMessage": "Your note about {handle} will be removed from this device.", "deleted": "Note deleted", "cancel": "Cancel", "save": "Save", "saveFailed": "Could not save (storage unavailable).", "edit": "Edit private note", "add": "Add private note" } }; // 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 UserNotes { start() { const api = window.wayBetter.api; this.scope = api.scope(); i18n = api.i18n || null; if (i18n) i18n.register(MESSAGES); if (i18n) this.scope.defer(i18n.onChange(() => { for (const label of document.querySelectorAll('.bt-note-label')) label.textContent = t('label'); for (const block of document.querySelectorAll('.bt-note-hover')) block.dataset.prefix = t('hoverPrefix'); })); this.store = api.storage('user-notes'); // Colors come from the active theme (`--wb-*`, set by wayBetter on :root) with neutral fallbacks. this.scope.css('user-notes', ` .bt-note { margin: 12px 0 4px; padding: 8px 12px; border-radius: 10px; cursor: pointer; white-space: pre-wrap; overflow-wrap: anywhere; border: 1px dashed var(--wb-border, rgba(127,127,127,.5)); background: rgba(255, 212, 0, .08); color: var(--wb-text, inherit); font: 400 14px/1.4 var(--wb-font, system-ui, sans-serif); } .bt-note:hover { background: rgba(255, 212, 0, .14); } .bt-note:focus-visible { outline: 2px solid var(--wb-accent, rgb(29,155,240)); outline-offset: 2px; } .bt-note-label { display: block; margin-bottom: 2px; font-size: 12px; font-weight: 700; color: var(--wb-muted, inherit); } .bt-note-hover { margin-top: 8px; padding: 6px 8px; border-radius: 8px; background: rgba(255, 212, 0, .12); white-space: pre-wrap; font: 400 13px/1.4 var(--wb-font, system-ui, sans-serif); } .bt-note-hover::before { content: attr(data-prefix); font-weight: 700; } `); // Profile header: a written note shows under the bio (or the name when there is no bio). Notes are // written in a dialog opened from the profile's ··· menu or by clicking the note. this.scope.observe('[data-testid="primaryColumn"] [data-testid="UserName"]', name => this.mountProfile(name)); // Remember that the ··· (userActions) button of the open profile was pressed, so the menu X opens // next in #layers is that profile's menu. this.menuFor = null; this.scope.on(document, 'pointerdown', event => { const button = event.target?.closest?.('[data-testid="primaryColumn"] [data-testid="userActions"]'); this.menuFor = button ? this.handleIn(document.querySelector('[data-testid="primaryColumn"] [data-testid="UserName"]')) : null; }, true); this.scope.observe('#layers [role="menu"]', menu => this.mountMenuItem(menu)); this.scope.observe('[data-testid="HoverCard"] [data-testid="UserDescription"], [data-testid="HoverCard"] [data-testid^="UserAvatar-Container-"]', node => this.mountHover(node)); // X keeps the profile header mounted across profile-to-profile navigation. const refresh = () => this.refreshProfiles(); let timer = 0; this.scope.onRouteChange(() => { refresh(); clearTimeout(timer); timer = setTimeout(refresh, 800); }); this.scope.defer(() => clearTimeout(timer)); } stop() { this.scope.dispose(); for (const node of document.querySelectorAll('.bt-note, .bt-note-hover')) node.remove(); } refreshProfiles() { for (const name of document.querySelectorAll('[data-testid="primaryColumn"] [data-testid="UserName"]')) this.mountProfile(name); } handleIn(root) { // The "@handle" is its own span; the block's full text also holds the name and badges ("Follows you"). for (const span of root?.querySelectorAll('span') || []) { const match = HANDLE.exec((span.textContent || '').trim()); if (match) return match[1].toLowerCase(); } return null; } mountProfile(name) { const handle = this.handleIn(name); if (!handle) return null; const anchor = name.parentElement?.querySelector('[data-testid="UserDescription"]') || name; const column = name.closest('[data-testid="primaryColumn"]') || document; const saved = this.store.get(handle, ''); let current = null; for (const old of column.querySelectorAll('.bt-note')) { if (!current && saved && old.dataset.handle === handle && old.previousElementSibling === anchor && old.querySelector('.bt-note-text')?.textContent === saved) current = old; else old.remove(); } if (current || !saved) return current; const box = document.createElement('div'); box.className = 'bt-note'; box.dataset.handle = handle; box.tabIndex = 0; box.setAttribute('role', 'button'); box.setAttribute('aria-label', t('boxLabel', { handle: `@${handle}` })); const label = document.createElement('span'); label.className = 'bt-note-label'; label.textContent = t('label'); const text = document.createElement('span'); text.className = 'bt-note-text'; text.textContent = saved; box.append(label, text); box.addEventListener('click', event => { event.stopPropagation(); this.edit(handle); }); box.addEventListener('keydown', event => { if (event.key !== 'Enter' && event.key !== ' ') return; event.preventDefault(); event.stopPropagation(); this.edit(handle); }); anchor.after(box); return box; } /** The note editor: a themed dialog from the UI kit (closed by `scope.dispose()` on stop). */ edit(handle) { if (this.editor?.open) return; const ui = this.scope.ui; const saved = this.store.get(handle, ''); const area = ui.h('textarea', { rows: 5, maxLength: 4000, placeholder: t('placeholder'), 'aria-label': t('areaLabel', { handle: `@${handle}` }) }); area.value = saved; const save = text => { const ok = text.trim() ? this.store.set(handle, text) : (this.store.remove(handle), true); if (ok) this.refreshProfiles(); return ok; }; this.editor = ui.dialog({ title: t('title', { handle: `@${handle}` }), message: t('message'), content: area, actions: [ ...(saved ? [{ label: t('delete'), tone: 'plain', onClick: async () => { const sure = await ui.confirm({ title: t('deleteTitle'), message: t('deleteMessage', { handle: `@${handle}` }), confirmLabel: t('delete'), danger: true }); if (!sure) return false; save(''); ui.toast(t('deleted')); return undefined; }, }] : []), { label: t('cancel') }, { label: t('save'), tone: 'primary', default: true, onClick: dialog => { if (!save(area.value)) { dialog.setError(t('saveFailed')); return false; } return undefined; }, }, ], }); } mountMenuItem(menu) { const handle = this.menuFor; this.menuFor = null; if (!handle || menu.querySelector('.bt-note-item')) return; const template = menu.querySelector('[role="menuitem"]'); if (!template) return; // A copy of X's own first item keeps X's look; copies carry none of X's handlers. const item = template.cloneNode(true); item.classList.add('bt-note-item'); item.removeAttribute('data-testid'); item.removeAttribute('href'); item.setAttribute('role', 'menuitem'); item.setAttribute('tabindex', '0'); const label = [...item.querySelectorAll('span')].reverse().find(span => !span.children.length && span.textContent.trim()); if (label) label.textContent = this.store.get(handle, '') ? t('edit') : t('add'); const path = item.querySelector('svg path'); if (path) { for (const extra of [...item.querySelectorAll('svg path')].slice(1)) extra.remove(); path.setAttribute('d', 'M14.23 2.854c.98-.977 2.56-.977 3.54 0l3.38 3.378c.97.977.97 2.559 0 3.536L9.91 20.999H3v-6.91L14.23 2.854zm2.12 1.414c-.19-.195-.51-.195-.7 0L5 14.917V19h4.08L19.73 8.354c.2-.196.2-.512 0-.708l-3.38-3.378zM14.75 19h6.25v2h-6.25v-2z'); } const choose = event => { event.preventDefault(); event.stopPropagation(); // Close X's menu the way a click outside it would, then open the note under the bio. const mask = document.querySelector('#layers [data-testid="mask"]'); if (mask) mask.click(); else document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); this.edit(handle); }; item.addEventListener('click', choose, true); item.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') choose(event); }); template.before(item); } mountHover(node) { const card = node.closest('[data-testid="HoverCard"]'); if (!card || card.querySelector('.bt-note-hover')) return; const handle = this.handleIn(card); const note = handle && this.store.get(handle, ''); if (!note) return; const block = document.createElement('div'); block.className = 'bt-note-hover'; block.dataset.prefix = t('hoverPrefix'); block.textContent = note; (card.querySelector('[data-testid="UserDescription"]') || node).after(block); } };