Skip to content

Instantly share code, notes, and snippets.

@RyotaUshio
Created February 11, 2024 05:30
Show Gist options
  • Save RyotaUshio/a79209bf25ad30f1286e59b73223359b to your computer and use it in GitHub Desktop.
Save RyotaUshio/a79209bf25ad30f1286e59b73223359b to your computer and use it in GitHub Desktop.
Obsidian FuzzyInputSuggest
abstract class FuzzyInputSuggest<Item> extends AbstractInputSuggest<Ranked<Item>> {
plugin: MyPlugin;
inputEl: HTMLInputElement;
constructor(plugin: MyPlugin, inputEl: HTMLInputElement) {
super(plugin.app, inputEl);
this.inputEl = inputEl;
this.plugin = plugin;
}
abstract getItems(): Item[];
abstract getItemText(item: Item): string;
abstract getName(item: Item): string;
getSuggestions(query: string) {
const search = prepareFuzzySearch(query.trim());
const items = this.getItems();
const results: Ranked<Item>[] = [];
for (const item of items) {
const target = this.getItemText(item);
const match = search(target);
if (match) results.push({ match, item });
}
sortSearchResults(results);
return results;
}
renderSuggestion(rankedItem: Ranked<Item>, el: HTMLElement) {
const { item, match } = rankedItem;
renderResults(el, this.getItemText(item), match);
}
selectSuggestion(rankedItem: Ranked<Item>) {
const { item } = rankedItem;
this.inputEl.blur();
this.inputEl.value = this.getName(item);
this.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment