// Search+ ยท Advanced search. A small form that writes X's own search operators for you: from:, // to:, since:/until:, filter:media|links|replies, min_faves:, lang:. The result is an ordinary X // query: put into X's search box, or opened as X's own search page. Nothing is sent anywhere else // and there is no syntax of our own (src/core/searchOperators.ts has the operators). import type { FeatureModule } from '../../../../../waybetter/packages/runtime/src/featureModules.ts'; import { buildSettingsForm, normalizeSettings, type SettingsSchema } from '../../../../../waybetter/packages/runtime/src/settingsForm.ts'; import { normalizeQuery } from '../../core/searchOperators.ts'; import type { PluginApi } from '../../inject/pluginApi.ts'; import { SEARCH_INPUT, setReactInputValue } from '../../inject/searchChips.ts'; import { searchBarSection } from './bar.ts'; import { openSearch } from './openSearch.ts'; import { currentQuery } from './savedSearches.ts'; export type BuilderValues = { words: string; from: string; to: string; since: string; until: string; filter: string; minFaves: number; lang: string }; export const FILTERS = ['media', 'links', 'replies'] as const; /** The form, drawn with the settings form's controls (nothing of it is stored). */ export const BUILDER_FIELDS: SettingsSchema = [ { key: 'words', type: 'text', default: '', label: 'words', maxLength: 300 }, { key: 'from', type: 'text', default: '', label: 'from', placeholder: '@', maxLength: 80 }, { key: 'to', type: 'text', default: '', label: 'to', placeholder: '@', maxLength: 80 }, { key: 'since', type: 'text', default: '', label: 'since', placeholder: 'YYYY-MM-DD', maxLength: 10 }, { key: 'until', type: 'text', default: '', label: 'until', placeholder: 'YYYY-MM-DD', maxLength: 10 }, { key: 'filter', type: 'select', default: '', label: 'filter', options: [{ value: '', label: 'filterAny' }, ...FILTERS.map(value => ({ value, label: `filter.${value}` }))] }, { key: 'minFaves', type: 'number', default: 0, min: 0, max: 100_000_000, label: 'minFaves' }, { key: 'lang', type: 'text', default: '', label: 'lang', hint: 'langHint', placeholder: 'en', maxLength: 3 }, ]; const HANDLE = /^[A-Za-z0-9_]{1,15}$/; const DATE = /^\d{4}-\d{2}-\d{2}$/; const LANG = /^[a-z]{2,3}$/; const handles = (text: string) => [...new Set(text.split(/[\s,]+/).map(item => item.replace(/^@/, '')).filter(item => HANDLE.test(item)))]; /** `from:a`, or `(from:a OR from:b)` for several accounts. */ const people = (operator: 'from' | 'to', text: string) => { const list = handles(text).map(handle => `${operator}:${handle}`); return list.length > 1 ? `(${list.join(' OR ')})` : list[0] ?? ''; }; /** The X query for the form's values. A value that is not valid for its operator is left out. */ export function composeQuery(values: BuilderValues): string { const lang = values.lang.trim().toLowerCase(); const likes = Math.floor(values.minFaves); return normalizeQuery([ values.words, people('from', values.from), people('to', values.to), DATE.test(values.since.trim()) ? `since:${values.since.trim()}` : '', DATE.test(values.until.trim()) ? `until:${values.until.trim()}` : '', (FILTERS as readonly string[]).includes(values.filter) ? `filter:${values.filter}` : '', likes > 0 ? `min_faves:${likes}` : '', LANG.test(lang) ? `lang:${lang}` : '', ].filter(Boolean).join(' ')); } /** The form's values for a query: the operators the form knows go to their fields, the rest stays as words. */ export function readQuery(query: string): BuilderValues { const values = normalizeSettings(BUILDER_FIELDS, null) as BuilderValues; const words: string[] = []; const from: string[] = []; const to: string[] = []; for (const token of normalizeQuery(query).match(/-?"[^"]*"|\S+/g) ?? []) { const match = /^(from|to|since|until|filter|min_faves|lang):(.+)$/i.exec(token); const operator = match?.[1]!.toLowerCase(); const value = match?.[2] ?? ''; if (operator === 'from' && HANDLE.test(value)) from.push(value); else if (operator === 'to' && HANDLE.test(value)) to.push(value); else if ((operator === 'since' || operator === 'until') && DATE.test(value) && !values[operator]) values[operator] = value; else if (operator === 'filter' && (FILTERS as readonly string[]).includes(value.toLowerCase()) && !values.filter) values.filter = value.toLowerCase(); else if (operator === 'min_faves' && /^\d{1,9}$/.test(value) && !values.minFaves) values.minFaves = Number(value); else if (operator === 'lang' && LANG.test(value.toLowerCase()) && !values.lang) values.lang = value.toLowerCase(); else words.push(token); } values.words = words.join(' '); values.from = from.join(' '); values.to = to.join(' '); return values; } export const advancedSearch: FeatureModule = { id: 'search.advancedSearch', start(ctx) { const { win } = ctx; const box = () => win.document.querySelector(SEARCH_INPUT); let pending = 0; ctx.defer(() => win.clearTimeout(pending)); const open = () => { const h = ctx.ui.h; const form = buildSettingsForm(h, BUILDER_FIELDS, readQuery(currentQuery(win, box())), key => ctx.text(key)); const preview = h('p', { class: 'wb-hint bt-query' }); const query = () => composeQuery(form.read() as BuilderValues); const show = () => { preview.textContent = query() || ctx.text('previewEmpty'); }; const input = box(); const checked = (handle: { setError(message: string | null): void }) => { const text = query(); if (!text) handle.setError(ctx.text('empty')); return text; }; ctx.ui.dialog({ title: ctx.text('title'), message: ctx.text('intro'), css: '.bt-query { margin-top: 14px; font-family: ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow-wrap: anywhere; }', content: body => { body.append(...form.nodes, preview); body.addEventListener('input', show); body.addEventListener('change', show); show(); }, actions: [ { label: ctx.text('cancel') }, // Only edits the text in X's box; X searches when you press Enter there. ...(input ? [{ label: ctx.text('fill'), onClick: (handle: { setError(message: string | null): void }) => { const text = checked(handle); if (!text) return false; input.focus(); setReactInputValue(input, text); return undefined; }, }] : []), { label: ctx.text('search'), tone: 'primary' as const, default: true, onClick: handle => { const text = checked(handle); if (!text) return false; // X's own search page for the query: a navigation, nothing more (./openSearch.ts). win.clearTimeout(pending); pending = openSearch(win, text); return undefined; }, }, ], }); }; const bar = searchBarSection(win, 20, () => [{ label: ctx.text('chip'), action: true, run: open }]); ctx.defer(() => bar.dispose()); ctx.command({ id: 'advancedSearch.open', title: ctx.text('title'), keywords: 'advanced search builder operators from to since until filter media links replies likes language', run: open }); }, };