import { tick } from 'svelte'; import { activeChips, extractCompletedTokens, overriding, parseQuery, parseToken, removeMatchedWord, selectTokenState, suggestTokens, toggleChipState, type FilterChip, type SessionFilter, type TokenMatch, } from './session-filter'; export class FilterInput { #query: () => string; #setQuery: (value: string) => void; #input: () => HTMLInputElement | undefined; #defaults: () => SessionFilter | undefined; #offset: () => number | null; #cursor = $state(0); #dismissed = $state(null); #index = $state(0); #signature = ''; #order: (keyof SessionFilter)[] = []; typed = $state({}); slice = $derived.by(() => { const query = this.#query(); const offset = this.#offset(); if (offset === null) return null; return { offset, text: query.slice(offset) }; }); parsed = $derived.by(() => parseQuery(this.slice ? this.slice.text : this.#query()), ); /** Combined typed chips and any complete unpromoted token currently in the box. */ activeTyped = $derived.by(() => overriding(this.typed, this.parsed.filter)); defaults = $derived.by(() => this.#defaults()); effective = $derived.by(() => this.defaults ? overriding(this.defaults, this.activeTyped) : this.activeTyped, ); chips = $derived.by(() => { if (!this.defaults || !this.slice) return []; return activeChips(this.defaults, this.activeTyped); }); hasTyped = $derived.by(() => this.chips.some((chip) => chip.typed)); suggestions: TokenMatch | null = $derived.by(() => { const query = this.#query(); if (!this.slice || this.#dismissed === query) return null; const match = suggestTokens( this.slice.text, Math.max(0, this.#cursor - this.slice.offset), ); return match ? { start: match.start + this.slice.offset, end: match.end + this.slice.offset, items: match.items, } : null; }); activeIndex = $derived.by(() => this.suggestions ? Math.min(this.#index, this.suggestions.items.length - 1) : 0, ); constructor(options: { query: () => string; setQuery: (value: string) => void; input: () => HTMLInputElement | undefined; defaults: () => SessionFilter | undefined; offset?: () => number | null; }) { this.#query = options.query; this.#setQuery = options.setQuery; this.#input = options.input; this.#defaults = options.defaults; this.#offset = options.offset ?? (() => 0); } #commitTyped(next: SessionFilter) { this.typed = next; this.#order = this.#order.filter((key) => next[key] !== undefined); for (const key of Object.keys(next) as (keyof SessionFilter)[]) { if (next[key] !== undefined && !this.#order.includes(key)) this.#order.push(key); } } syncCursor = () => { let query = this.#query(); if (this.slice) { const extracted = extractCompletedTokens(this.slice.text); if (extracted.changed) { this.#commitTyped(overriding(this.typed, extracted.filter)); query = query.slice(0, this.slice.offset) + extracted.query; const pos = this.slice.offset + extracted.query.length; this.#setQuery(query); this.#cursor = pos; queueMicrotask(() => this.#input()?.setSelectionRange(pos, pos)); } } this.#cursor = this.#input()?.selectionStart ?? query.length; if (this.#dismissed !== null && this.#dismissed !== query) this.#dismissed = null; const sig = this.suggestions ? `${this.suggestions.start}:${this.suggestions.end}:${this.suggestions.items.map((item) => item.token).join(',')}` : ''; if (sig !== this.#signature) { this.#signature = sig; this.#index = 0; } }; setActive(index: number) { this.#index = index; } async pick(token: string) { const match = this.suggestions; const parsed = parseToken(token); if (!match || !parsed) return; const next = removeMatchedWord(this.#query(), match); this.#commitTyped({ ...this.typed, [parsed.key]: parsed.value }); this.#dismissed = null; this.#index = 0; this.#signature = ''; this.#setQuery(next.query); this.#cursor = next.cursor; await tick(); const input = this.#input(); input?.focus(); input?.setSelectionRange(next.cursor, next.cursor); } #removeBoxTokens() { if (!this.slice) return; const extracted = extractCompletedTokens(`${this.slice.text} `); if (extracted.changed) this.#setQuery( this.#query().slice(0, this.slice.offset) + extracted.query.trimEnd(), ); } async flip(chip: FilterChip) { this.#commitTyped(toggleChipState(this.activeTyped, chip)); this.#removeBoxTokens(); this.#dismissed = null; this.#index = 0; this.#signature = ''; await tick(); this.#input()?.focus(); this.syncCursor(); } select(token: string) { this.#commitTyped(selectTokenState(this.activeTyped, token, this.defaults)); this.#removeBoxTokens(); this.#dismissed = null; this.#index = 0; this.#signature = ''; } clear() { this.typed = {}; this.#order = []; this.#removeBoxTokens(); this.#dismissed = null; this.#index = 0; this.#signature = ''; } /** Handles typeahead keys and Backspace-to-pop-chip on empty input; returns true when consumed. */ handleKey( event: KeyboardEvent, options: { arrows?: boolean; enter?: boolean; escape?: boolean } = {}, ): boolean { if ( event.key === 'Backspace' && this.slice && this.slice.text === '' && this.#order.length > 0 ) { event.preventDefault(); const last = this.#order[this.#order.length - 1]; const next = { ...this.typed }; delete next[last]; this.#commitTyped(next); return true; } const match = this.suggestions; if (!match) return false; const len = match.items.length; if ( options.arrows && (event.key === 'ArrowDown' || (event.ctrlKey && event.key === 'n')) ) { event.preventDefault(); this.#index = (this.activeIndex + 1) % len; return true; } if ( options.arrows && (event.key === 'ArrowUp' || (event.ctrlKey && event.key === 'p')) ) { event.preventDefault(); this.#index = (this.activeIndex - 1 + len) % len; return true; } if (event.key === 'Tab') { event.preventDefault(); if (event.shiftKey) this.#index = (this.activeIndex + 1) % len; else void this.pick(match.items[this.activeIndex].token); return true; } if (options.enter && event.key === 'Enter') { event.preventDefault(); void this.pick(match.items[this.activeIndex].token); return true; } if (options.escape && event.key === 'Escape') { event.preventDefault(); this.#dismissed = this.#query(); return true; } return false; } }