diff --git a/app/src/DashboardPage.js b/app/src/DashboardPage.js
index 02fc542c..83be2cee 100644
--- a/app/src/DashboardPage.js
+++ b/app/src/DashboardPage.js
@@ -158,7 +158,7 @@ export function DashboardPage() {
const navigate = useNavigate();
const {searchStr, setSearchStr, activeTags} = useSearch();
- const {suggestions, handleResultSelect, resultRenderer} = useSearchSuggestions();
+ const {suggestions, handleResultSelect, resultRenderer, loading} = useSearchSuggestions();
const {status} = useContext(StatusContext);
let title = 'Dashboard';
@@ -199,6 +199,7 @@ export function DashboardPage() {
results={suggestions}
handleResultSelect={handleResultSelect}
resultRenderer={resultRenderer}
+ loading={loading}
/>
@@ -222,6 +223,7 @@ export function DashboardPage() {
results={suggestions}
handleResultSelect={handleResultSelect}
resultRenderer={resultRenderer}
+ loading={loading}
/>
diff --git a/app/src/Tags.js b/app/src/Tags.js
index 4b18a1d3..9259bfc1 100644
--- a/app/src/Tags.js
+++ b/app/src/Tags.js
@@ -70,7 +70,7 @@ export function useTags() {
}
return tags.filter(i => i.name.toLowerCase().includes(name)
- || fuzzyMatch(lowerName, i.name.toLowerCase()))
+ || fuzzyMatch(lowerName, i.name.toLowerCase(), 2))
}
const NameToTagLabel = ({name, to, ...props}) => {
diff --git a/app/src/api.js b/app/src/api.js
index 7adfa51e..fb703ecb 100644
--- a/app/src/api.js
+++ b/app/src/api.js
@@ -1025,10 +1025,10 @@ export async function searchSuggestions(search_str) {
if (response.ok) {
const content = await response.json();
- const fileGroups = content['file_groups'];
- const zimsEstimates = content['zims_estimates'];
- const channels = content['channels'];
- const domains = content['domains'];
+ const fileGroups = content.file_groups;
+ const zimsEstimates = content.zims_estimates;
+ const channels = content.channels;
+ const domains = content.domains;
return {
fileGroups,
zimsEstimates,
diff --git a/app/src/components/Archive.js b/app/src/components/Archive.js
index 3793925c..ee48e548 100644
--- a/app/src/components/Archive.js
+++ b/app/src/components/Archive.js
@@ -493,7 +493,6 @@ function ArchivesPage() {
);
const searchInput = input with a Clear button.
@@ -537,6 +538,7 @@ export function SearchResultsInput({
results={results}
resultRenderer={resultRenderer}
className='search-input'
+ loading={loading}
/>
{clearable === true && {clearButton}
}
diff --git a/app/src/components/Search.js b/app/src/components/Search.js
index f4fb5adf..a0bb8e14 100644
--- a/app/src/components/Search.js
+++ b/app/src/components/Search.js
@@ -1,7 +1,7 @@
import React, {useEffect, useState} from "react";
import {createSearchParams, Route, Routes, useNavigate} from "react-router-dom";
import {FilesSearchView} from "./Files";
-import {usePages, useQuery} from "../hooks/customHooks";
+import {useLatestRequest, usePages, useQuery} from "../hooks/customHooks";
import {ZimSearchView} from "./Zim";
import {searchEstimate, searchSuggestions} from "../api";
import {fuzzyMatch, normalizeEstimate, TabLinks} from "./Common";
@@ -19,6 +19,7 @@ const suggestedApps = [
{location: '/admin/wrol', title: 'WROL Mode', description: 'Enable or disable WROL Mode'},
];
+
export function useSearchSuggestions() {
const navigate = useNavigate();
const {searchParams} = useQuery();
@@ -26,75 +27,78 @@ export function useSearchSuggestions() {
const searchStr = searchParams.get('q');
+ const {data, sendRequest, loading} = useLatestRequest(500);
const [suggestions, setSuggestions] = useState(null);
- const fetchSuggestions = async () => {
- if (searchStr && searchStr.length > 0) {
- const lowerSearchStr = searchStr.toLowerCase();
- try {
- const newSuggestions = await searchSuggestions(searchStr);
- const matchingApps = suggestedApps.filter(i =>
- i.title.toLowerCase().includes(lowerSearchStr)
- || fuzzyMatch(i.title.toLowerCase(), lowerSearchStr));
+ const normalizeSuggestions = (newSuggestions) => {
+ // Convert the suggestions from the Backend to what the Semantic expects.
+ const lowerSearchStr = searchStr.toLowerCase();
+ const matchingApps = suggestedApps.filter(i =>
+ i.title.toLowerCase().includes(lowerSearchStr)
+ || fuzzyMatch(i.title.toLowerCase(), lowerSearchStr));
- const zimSum = newSuggestions.zimsEstimates.reduce((i, j) => i + j['estimate'], 0);
+ const zimSum = newSuggestions.zimsEstimates.reduce((i, j) => i + j['estimate'], 0).toString();
- // Suggested results are ordered.
- let matchingSuggestions = {};
- if (newSuggestions.fileGroups > 0) {
- matchingSuggestions.fileGroups = {
- name: 'Files', results: [
- {description: newSuggestions.fileGroups, type: 'files'}
- ]
- };
- }
- if (zimSum > 0) {
- matchingSuggestions.zimsSum = {
- name: 'Zims', results: [
- {description: zimSum, type: 'zims'}
- ],
- }
- }
- if (newSuggestions.channels && newSuggestions.channels.length > 0) {
- matchingSuggestions.channels = {
- name: 'Channels', results: newSuggestions.channels.map(i => {
- return {type: 'channel', description: i['name'], id: i['id']}
- })
- }
- }
- if (newSuggestions.domains && newSuggestions.domains.length > 0) {
- matchingSuggestions.domains = {
- name: 'Domains', results: newSuggestions.domains.map(i => {
- return {type: 'domain', description: i.domain, id: i['id'], domain: i.domain}
- })
- }
- }
-
- matchingSuggestions.tags = {
- name: 'Tags', results: fuzzyMatchTagsByName(searchStr).map(i => {
- return {type: 'tag', description: i.name}
- })
- }
-
- if (matchingApps && matchingApps.length > 0) {
- matchingSuggestions.apps = {name: 'Apps', results: matchingApps};
- }
-
- console.debug('matchingSuggestions', matchingSuggestions);
- setSuggestions(matchingSuggestions);
- } catch (e) {
- console.error(e);
- console.error('Failed to get search suggestions');
- }
- } else {
- setSuggestions(null);
+ // Suggested results are ordered.
+ let matchingSuggestions = {};
+ if (newSuggestions.fileGroups > 0) {
+ matchingSuggestions.fileGroups = {
+ name: 'Files', results: [
+ {title: newSuggestions.fileGroups.toString(), type: 'files'}
+ ]
+ };
}
+ if (zimSum > 0) {
+ matchingSuggestions.zimsSum = {
+ name: 'Zims', results: [
+ {title: zimSum, type: 'zims'}
+ ],
+ }
+ }
+ if (newSuggestions.channels && newSuggestions.channels.length > 0) {
+ matchingSuggestions.channels = {
+ name: 'Channels', results: newSuggestions.channels.map(i => {
+ return {type: 'channel', title: i['name'], id: i['id']}
+ })
+ }
+ }
+ if (newSuggestions.domains && newSuggestions.domains.length > 0) {
+ matchingSuggestions.domains = {
+ name: 'Domains', results: newSuggestions.domains.map(i => {
+ return {type: 'domain', title: i.domain, id: i['id'], domain: i.domain}
+ })
+ }
+ }
+
+ matchingSuggestions.tags = {
+ name: 'Tags', results: fuzzyMatchTagsByName(searchStr).map(i => {
+ return {type: 'tag', title: i.name}
+ })
+ }
+
+ if (matchingApps && matchingApps.length > 0) {
+ matchingSuggestions.apps = {name: 'Apps', results: matchingApps};
+ }
+
+ console.debug('matchingSuggestions', matchingSuggestions);
+ setSuggestions(matchingSuggestions);
}
React.useEffect(() => {
- fetchSuggestions();
- }, [searchStr]);
+ if (data) {
+ normalizeSuggestions(data);
+ }
+ }, [JSON.stringify(data)]);
+ React.useEffect(() => {
+ if (!searchStr || searchStr.length === 0) {
+ console.debug('Not getting suggestions because there is no search.');
+ return;
+ }
+
+ // Use the useLatestRequest to handle user typing.
+ sendRequest(searchSuggestions(searchStr));
+ }, [searchStr, sendRequest]);
const handleResultSelect = ({result}) => {
if (!result) {
@@ -108,7 +112,7 @@ export function useSearchSuggestions() {
} else if (result['type'] === 'domain') {
return navigate(`/archive?domain=${result['domain']}`);
} else if (result['type'] === 'tag') {
- return navigate(`/search?tag=${encodeURIComponent(result['description'])}`);
+ return navigate(`/search?tag=${encodeURIComponent(result['title'])}`);
} else if (result['type'] === 'files') {
return navigate(`/search?q=${encodeURIComponent(searchStr)}`);
} else if (result['type'] === 'zims') {
@@ -119,20 +123,20 @@ export function useSearchSuggestions() {
const resultRenderer = ({type, title, description}) => {
if (type === 'tag') {
- return ;
+ return ;
}
// No specific renderer, use the generic.
- if (title) {
+ if (description) {
return <>
{title}
{description}
>
}
- return {description}
+ return {title}
};
- return {suggestions, searchStr, handleResultSelect, resultRenderer}
+ return {suggestions, searchStr, handleResultSelect, resultRenderer, loading}
}
export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false, model) => {
diff --git a/app/src/components/Videos.js b/app/src/components/Videos.js
index 7871ecf6..7e3be167 100644
--- a/app/src/components/Videos.js
+++ b/app/src/components/Videos.js
@@ -184,7 +184,6 @@ function VideosPage() {
const searchInput = ;
diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js
index 1e99c757..3b7fd662 100644
--- a/app/src/hooks/customHooks.js
+++ b/app/src/hooks/customHooks.js
@@ -63,6 +63,44 @@ export const useRecurringTimeout = (callback, delay) => {
}, [delay])
}
+export const useLatestRequest = (delay = 300) => {
+ // A hook which cancels older requests and will only set `data` to the latest response's data.
+
+ const [data, setData] = React.useState(null);
+ const latestRequestRef = React.useRef(0);
+ const debounceTimerRef = React.useRef(null);
+ const [loading, setLoading] = React.useState(false);
+
+ const sendRequest = React.useCallback((fetchCoroutine) => {
+ if (debounceTimerRef.current) {
+ clearTimeout(debounceTimerRef.current);
+ }
+
+ debounceTimerRef.current = setTimeout(async () => {
+ setLoading(true);
+ const requestId = ++latestRequestRef.current;
+
+ try {
+ const result = await fetchCoroutine;
+
+ if (requestId === latestRequestRef.current) {
+ setData(result);
+ }
+ } catch (error) {
+ console.error('Request failed:', error);
+ setData(null);
+ } finally {
+ if (requestId === latestRequestRef.current) {
+ setLoading(false);
+ }
+ }
+ }, delay);
+ }, [delay]);
+
+ return {data, sendRequest, loading};
+};
+
+
export const useQuery = () => {
const [searchParams, setSearchParams] = useSearchParams();