Extracted local autocompleter download function

This commit is contained in:
KoloMl 2024-08-31 21:11:53 +04:00
parent 0fe6cd7842
commit 997b1bbe8a
2 changed files with 28 additions and 16 deletions

View file

@ -8,7 +8,7 @@ import { getTermContexts } from './match_query';
import store from './utils/store';
import { TermContext } from './query/lex';
import { $$ } from './utils/dom';
import { fetchSuggestions, SuggestionsPopup, TermSuggestion } from './utils/suggestions';
import { fetchLocalAutocomplete, fetchSuggestions, SuggestionsPopup, TermSuggestion } from './utils/suggestions';
let inputField: HTMLInputElement | null = null,
originalTerm: string | undefined,
@ -118,13 +118,13 @@ function listenAutocomplete() {
let serverSideSuggestionsTimeout: number | undefined;
let localAc: LocalAutocompleter | null = null;
let localFetched = false;
let isLocalLoading = false;
document.addEventListener('focusin', fetchLocalAutocomplete);
document.addEventListener('focusin', loadAutocompleteFromEvent);
document.addEventListener('input', event => {
popup.hide();
fetchLocalAutocomplete(event);
loadAutocompleteFromEvent(event);
window.clearTimeout(serverSideSuggestionsTimeout);
if (!(event.target instanceof HTMLInputElement)) return;
@ -195,20 +195,14 @@ function listenAutocomplete() {
}
});
function fetchLocalAutocomplete(event: Event) {
function loadAutocompleteFromEvent(event: Event) {
if (!(event.target instanceof HTMLInputElement)) return;
if (!localFetched && event.target.dataset && 'ac' in event.target.dataset) {
const now = new Date();
const cacheKey = `${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}`;
if (!isLocalLoading && event.target.dataset.ac) {
isLocalLoading = true;
localFetched = true;
fetch(`/autocomplete/compiled?vsn=2&key=${cacheKey}`, { credentials: 'omit', cache: 'force-cache' })
.then(handleError)
.then(resp => resp.arrayBuffer())
.then(buf => {
localAc = new LocalAutocompleter(buf);
fetchLocalAutocomplete().then(autocomplete => {
localAc = autocomplete;
});
}
}

View file

@ -1,6 +1,7 @@
import { makeEl } from './dom.ts';
import { mouseMoveThenOver } from './events.ts';
import { handleError } from './requests.ts';
import { LocalAutocompleter } from './local-autocompleter.ts';
export interface TermSuggestion {
label: string;
@ -163,3 +164,20 @@ export async function fetchSuggestions(endpoint: string, targetTerm: string) {
return promisedSuggestions;
}
export function purgeSuggestionsCache() {
cachedSuggestions.clear();
}
export async function fetchLocalAutocomplete(): Promise<LocalAutocompleter> {
const now = new Date();
const cacheKey = `${now.getUTCFullYear()}-${now.getUTCMonth()}-${now.getUTCDate()}`;
return await fetch(`/autocomplete/compiled?vsn=2&key=${cacheKey}`, {
credentials: 'omit',
cache: 'force-cache',
})
.then(handleError)
.then(resp => resp.arrayBuffer())
.then(buf => new LocalAutocompleter(buf));
}