parent
077953976c
commit
5e975b6825
@ -0,0 +1,88 @@
|
|||||||
|
import type { TimerHandle, TimerScheduler } from '$timer';
|
||||||
|
|
||||||
|
export interface TypeaheadOptions {
|
||||||
|
readonly timers: TimerScheduler;
|
||||||
|
readonly key: () => string;
|
||||||
|
readonly timeout?: () => number;
|
||||||
|
readonly meta?: Readonly<Record<string, unknown>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TypeaheadText<TItem> = (item: TItem) => string;
|
||||||
|
|
||||||
|
export interface TypeaheadSearchOptions<TItem> extends TypeaheadOptions {
|
||||||
|
readonly getText: TypeaheadText<TItem>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TypeaheadBuffer {
|
||||||
|
private search = '';
|
||||||
|
private timer: TimerHandle | null = null;
|
||||||
|
|
||||||
|
constructor(private readonly options: TypeaheadOptions) {}
|
||||||
|
|
||||||
|
get value(): string {
|
||||||
|
return this.search;
|
||||||
|
}
|
||||||
|
|
||||||
|
push(key: string): string | null {
|
||||||
|
if (key.length !== 1) return null;
|
||||||
|
|
||||||
|
this.search += key.toLowerCase();
|
||||||
|
this.scheduleReset();
|
||||||
|
|
||||||
|
return this.search;
|
||||||
|
}
|
||||||
|
|
||||||
|
reset(): void {
|
||||||
|
this.search = '';
|
||||||
|
this.cancelTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy(): void {
|
||||||
|
this.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleReset(): void {
|
||||||
|
this.cancelTimer();
|
||||||
|
this.timer = this.options.timers.schedule(
|
||||||
|
this.options.key(),
|
||||||
|
this.options.timeout?.() ?? 500,
|
||||||
|
() => {
|
||||||
|
this.search = '';
|
||||||
|
this.timer = null;
|
||||||
|
},
|
||||||
|
{ replace: true, meta: this.options.meta }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private cancelTimer(): void {
|
||||||
|
if (this.timer) {
|
||||||
|
this.timer.cancel();
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Typeahead<TItem = HTMLElement> extends TypeaheadBuffer {
|
||||||
|
constructor(private readonly searchOptions: TypeaheadSearchOptions<TItem>) {
|
||||||
|
super(searchOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
handle(key: string, items: readonly TItem[]): TItem | null {
|
||||||
|
const query = this.push(key);
|
||||||
|
if (query === null) return null;
|
||||||
|
return matchTypeahead(items, query, this.searchOptions.getText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchTypeahead<TItem>(
|
||||||
|
items: readonly TItem[],
|
||||||
|
query: string,
|
||||||
|
getText: TypeaheadText<TItem>
|
||||||
|
): TItem | null {
|
||||||
|
return (
|
||||||
|
items.find((item) => {
|
||||||
|
const text = getText(item);
|
||||||
|
return text.toLowerCase().startsWith(query);
|
||||||
|
}) ?? null
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Reference in new issue