File size: 7,196 Bytes
4446d89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
<svelte:options accessors={true} />

<script lang="ts">
	import type { Gradio } from "@gradio/utils";
	import { BlockTitle } from "@gradio/atoms";
	import { Block } from "@gradio/atoms";
	import { StatusTracker } from "@gradio/statustracker";
	import type { LoadingStatus } from "@gradio/statustracker";
	import { tick } from "svelte";
	import type { Entry } from "./QuickSearchEntry/Types";
	import QuickSearchEntry from "./QuickSearchEntry/QuickSearchEntry.svelte";
	import type { QuickSearchResults } from "./Types";
	import { queryString, httpGet, throttle } from "./lib/ViewUtils";

	export let gradio: Gradio<{
		change: never;
		submit: never;
		input: never;
	}>;
	export let label = "Textbox";
	export let elem_id = "";
	export let elem_classes: string[] = [];
	export let visible = true;
	export let value = "";
	export let placeholder = "";
	export let show_label: boolean;
	export let scale: number | null = null;
	export let min_width: number | undefined = undefined;
	export let loading_status: LoadingStatus | undefined = undefined;
	export let value_is_output = false;
	export let interactive: boolean;
	export let rtl = false;

	export let url: string = "https://huggingface.co/api/quicksearch";
	export let position: "absolute" | "fixed" = "absolute";

	let entries: Entry[] = [];
	let isOpen = false;
	let lastQuery: string | null = null;
	let numResults = 0;
	let selectedEntryIdx = -1;
	let searchController = new AbortController();

	const THROTTLE_DELAY = 300;

	let el: HTMLTextAreaElement | HTMLInputElement;
	const container = true;

	function handle_change(): void {
		gradio.dispatch("change");
		if (!value_is_output) {
			gradio.dispatch("input");
		}
	}

	async function handle_keypress(e: KeyboardEvent): Promise<void> {
		await tick();
		if (e.key === "Enter") {
			e.preventDefault();
			gradio.dispatch("submit");
		}
	}
	
	async function handleFocus() {
		if (lastQuery === null) {
			await performSearch();
		}
		isOpen = true;
	}
	
	const handleInput = throttle(async () => {
		isOpen = true;
		await tick(); // Let parent component change searchParams such as orgFilters first
		await performSearch();
	}, THROTTLE_DELAY);

	function isSelected(selectedEntryIdx: number, entry: Entry) {
		return entries[selectedEntryIdx]?.id === entry.id && entries[selectedEntryIdx]?.type === entry.type;
	}

	function handleClickEntry(entry: Entry) {
		selectedEntryIdx = entries.findIndex(e => e.id === entry.id && e.type === entry.type);
		console.log(entry);
	}

	$: if (value === null) value = "";

	// When the value changes, dispatch the change event via handle_change()
	// See the docs for an explanation: https://svelte.dev/docs/svelte-components#script-3-$-marks-a-statement-as-reactive
	$: value, handle_change();
	
	async function performSearch() {
		const input = value.trim();
		if (input !== lastQuery) {
			const res = await fetchResults(input);
			if (res.isError) {
				if (!res.aborted) {
					console.error(`QuickSearch Error: ${res.error}`);
				}
				return;
			}

			const resEntries = getResultEntries(res.payload as QuickSearchResults);
			entries = [
				...resEntries,
			];
			console.log(entries);
			numResults = resEntries.length;
			lastQuery = input;
		}
	}
	
	async function fetchResults(input: string = "") {
		searchController.abort(); /// Cancel previous function call if exists
		searchController = new AbortController();

		const res = await httpGet<QuickSearchResults>(
			url +
				queryString({
					q: input,
					type: ["model", "org", "user"],
				}),
			{ signal: searchController.signal }
		);

		return res;
	}

	function getResultEntries(results: QuickSearchResults | null): Entry[] {
		const modelEntries: Entry[] = results.models.map(m => ({
			href: undefined,
			id: m.id,
			_id: m._id,
			label: m.id,
			type: "model",
		}));
		
		const orgEntries: Entry[] = results.orgs.map(o => ({
			href: undefined,
			id: o.name,
			_id: o._id,
			imgUrl: o.avatarUrl,
			label: o.fullname,
			type: "org",
		}));

		const userEntries: Entry[] = results.users.map(u => ({
			href: undefined,
			id: u.user,
			_id: u._id,
			imgUrl: u.avatarUrl.startsWith("/") ? `https://huggingface.co${u.avatarUrl}` : u.avatarUrl,
			label: u.user,
			type: "user",
			description: u.fullname,
		}));

		return [
			...modelEntries,
			...orgEntries,
			...userEntries,
		];
	}
</script>

<Block
	{visible}
	{elem_id}
	{elem_classes}
	{scale}
	{min_width}
	allow_overflow={false}
	padding={true}
>
	{#if loading_status}
		<StatusTracker
			autoscroll={gradio.autoscroll}
			i18n={gradio.i18n}
			{...loading_status}
		/>
	{/if}

	<label class:container>
		<BlockTitle {show_label} info={undefined}>{label}</BlockTitle>

		<input
			data-testid="textbox"
			type="text"
			class="scroll-hide"
			bind:value
			bind:this={el}
			{placeholder}
			disabled={!interactive}
			dir={rtl ? "rtl" : "ltr"}
			on:focus={handleFocus}
			on:keypress={handle_keypress}
			on:input={handleInput}
		/>
		{#if isOpen}
			<div class="{position} z-40 w-full md:min-w-[24rem]">
				<ul
					class="mt-1 max-h-[calc(100vh-100px)] w-full divide-y divide-gray-100 overflow-hidden overflow-y-auto rounded-lg border border-gray-100 bg-white text-sm shadow-lg dark:divide-gray-900"
				>
					{#if !numResults}
						<QuickSearchEntry
							entry={{
								id: "no-result",
								label: "No results found :(",
								type: "no-results",
							}}
							isSelected={false}
							onClick={() => {}}
						/>
					{/if}

					{#if entries.some(x => x.type === "model")}
						{#each entries.filter(x => ["model", "all-models"].includes(x.type)) as entry}
							<li>
								<QuickSearchEntry {entry} isSelected={isSelected(selectedEntryIdx, entry)} onClick={handleClickEntry} />
							</li>
						{/each}
					{/if}
					
					{#if entries.some(x => x.type === "org")}
						{#each entries.filter(x => x.type === "org") as entry}
							<li>
								<QuickSearchEntry {entry} isSelected={isSelected(selectedEntryIdx, entry)} onClick={handleClickEntry} />
							</li>
						{/each}
					{/if}

					{#if entries.some(x => x.type === "user")}
						{#each entries.filter(x => x.type === "user") as entry}
							<li>
								<QuickSearchEntry {entry} isSelected={isSelected(selectedEntryIdx, entry)} onClick={handleClickEntry} />
							</li>
						{/each}
					{/if}
				</ul>
			</div>
		{/if}
	</label>
</Block>

<style>
	label {
		display: block;
		width: 100%;
	}

	input {
		display: block;
		position: relative;
		outline: none !important;
		box-shadow: var(--input-shadow);
		background: var(--input-background-fill);
		padding: var(--input-padding);
		width: 100%;
		color: var(--body-text-color);
		font-weight: var(--input-text-weight);
		font-size: var(--input-text-size);
		line-height: var(--line-sm);
		border: none;
	}
	.container > input {
		border: var(--input-border-width) solid var(--input-border-color);
		border-radius: var(--input-radius);
	}
	input:disabled {
		-webkit-text-fill-color: var(--body-text-color);
		-webkit-opacity: 1;
		opacity: 1;
	}

	input:focus {
		box-shadow: var(--input-shadow-focus);
		border-color: var(--input-border-color-focus);
	}

	input::placeholder {
		color: var(--input-placeholder-color);
	}
</style>