-
-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathinputSuggester.ts
More file actions
195 lines (161 loc) · 4.74 KB
/
inputSuggester.ts
File metadata and controls
195 lines (161 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { FuzzySuggestModal } from "obsidian";
import type { FuzzyMatch, App } from "obsidian";
import { log, toError } from "src/logger/logManager";
import { normalizeDisplayItem } from "../suggesters/utils";
type SuggestRender<T> = (value: T, el: HTMLElement) => void;
type Options = {
limit: FuzzySuggestModal<string>["limit"];
emptyStateText: FuzzySuggestModal<string>["emptyStateText"];
placeholder: Parameters<
FuzzySuggestModal<string>["setPlaceholder"]
>[0] extends string
? string
: never;
renderItem: SuggestRender<string> | undefined;
};
/**
* Similar to GenericSuggester, except users can write their own input, and it gets added to the list of suggestions.
*/
export default class InputSuggester extends FuzzySuggestModal<string> {
private resolvePromise: (value: string) => void;
private rejectPromise: (reason?: unknown) => void;
public promise: Promise<string>;
private resolved: boolean;
private renderItem?: SuggestRender<string>;
private displayItems: string[];
private items: string[];
private warnedOnEmptyDisplay = false;
public static Suggest(
app: App,
displayItems: string[],
items: string[],
options: Partial<Options> = {}
) {
const newSuggester = new InputSuggester(
app,
displayItems,
items,
options
);
return newSuggester.promise;
}
public constructor(
app: App,
displayItems: string[],
items: string[],
options: Partial<Options> = {}
) {
super(app);
this.items = items;
this.displayItems = displayItems.map((value) => normalizeDisplayItem(value));
this.promise = new Promise<string>((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
});
this.renderItem = options.renderItem;
this.inputEl.addEventListener("keydown", (event: KeyboardEvent) => {
// chooser is undocumented & not officially a part of the Obsidian API, hence the precautions in using it.
if (event.code !== "Tab" || !("chooser" in this)) {
return;
}
const { values, selectedItem } = this.chooser as {
values: {
item: string;
match: { score: number; matches: unknown[] };
}[];
selectedItem: number;
[key: string]: unknown;
};
const { value } = this.inputEl;
this.inputEl.value = values[selectedItem].item ?? value;
});
if (options.placeholder) this.setPlaceholder(options.placeholder);
if (typeof options.limit === "number") {
this.limit = options.limit;
}
if (options.emptyStateText)
this.emptyStateText = options.emptyStateText;
if (this.displayItems.length !== this.items.length) {
this.displayItems = this.items.map((item, index) => {
const displayItem = this.displayItems[index];
return normalizeDisplayItem(displayItem ?? item);
});
}
this.warnIfEmptyDisplay();
this.open();
}
getItemText(item: string): string {
if (item === this.inputEl.value) return item;
const index = this.items.indexOf(item);
const displayItem = index >= 0 ? this.displayItems[index] : undefined;
return normalizeDisplayItem(displayItem ?? item);
}
getItems(): string[] {
return this.items;
}
getSuggestions(query: string): FuzzyMatch<string>[] {
const suggestions = super.getSuggestions(query);
const customValue = this.inputEl.value;
if (!customValue) return suggestions;
if (this.items.includes(customValue)) {
return suggestions;
}
const alreadyPresent = suggestions.some(
(suggestion) => suggestion.item === customValue
);
if (alreadyPresent) {
return suggestions;
}
suggestions.push({
item: customValue,
match: {
score: Number.NEGATIVE_INFINITY,
matches: [],
},
});
return suggestions;
}
selectSuggestion(
value: FuzzyMatch<string>,
evt: MouseEvent | KeyboardEvent
) {
this.resolved = true;
super.selectSuggestion(value, evt);
}
renderSuggestion(value: FuzzyMatch<string>, el: HTMLElement): void {
if (!this.renderItem) {
super.renderSuggestion(value, el);
return;
}
try {
el.empty();
this.renderItem(value.item, el);
} catch (error) {
const err = toError(error);
err.message = `Custom renderItem threw an error; falling back to default rendering. ${err.message}`;
log.logWarning(err);
el.empty();
super.renderSuggestion(value, el);
}
}
onChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {
this.resolved = true;
this.resolvePromise(item);
}
onClose() {
super.onClose();
if (!this.resolved) this.rejectPromise("no input given.");
}
private warnIfEmptyDisplay(): void {
if (this.warnedOnEmptyDisplay) return;
const hasEmptyDisplay = this.displayItems.some(
(displayItem) => displayItem.length === 0,
);
if (hasEmptyDisplay) {
this.warnedOnEmptyDisplay = true;
log.logWarning(
"QuickAdd suggester received empty display values. Check your displayItems mapping.",
);
}
}
}