diff --git a/app/src/App.js b/app/src/App.js
index 7ca3ba5e..b0fd943c 100644
--- a/app/src/App.js
+++ b/app/src/App.js
@@ -21,6 +21,7 @@ import {SemanticToastContainer} from "react-semantic-toasts-2";
import {FilePreviewProvider} from "./components/FilePreview";
import {TagsProvider} from "./Tags";
import {ZimRoute} from "./components/Zim";
+import {SearchSuggestionsProvider} from "./components/Search";
function PageNotFound() {
const {t} = useContext(ThemeContext);
@@ -61,13 +62,19 @@ function HelpPage() {
}
function Root() {
- return <>
-
-
-
- >
+ return
+
+
+
+
+
+
+
+
+
+
}
const router = createBrowserRouter(createRoutesFromElements(
-
-
- {/* Context and style to handle switching between mobile/computer. */}
-
- {/* Toasts can be on any page. */}
-
-
-
-
-
-
-
-
-
+ return
+ {/* Context and style to handle switching between mobile/computer. */}
+
+ {/* Toasts can be on any page. */}
+
+
+
+
+
}
diff --git a/app/src/DashboardPage.js b/app/src/DashboardPage.js
index 83be2cee..04ff4f24 100644
--- a/app/src/DashboardPage.js
+++ b/app/src/DashboardPage.js
@@ -22,7 +22,7 @@ import {refreshFiles} from "./api";
import _ from "lodash";
import {TagsDashboard} from "./Tags";
import {Upload} from "./components/Upload";
-import {SearchView, useSearch, useSearchSuggestions} from "./components/Search";
+import {SearchSuggestionsContext, SearchView, useSearch} from "./components/Search";
import {KiwixRestartMessage, OutdatedZimsMessage} from "./components/Zim";
import {useSettings, useWROLMode} from "./hooks/customHooks";
import {FileSearchFilterButton} from "./components/Files";
@@ -158,7 +158,7 @@ export function DashboardPage() {
const navigate = useNavigate();
const {searchStr, setSearchStr, activeTags} = useSearch();
- const {suggestions, handleResultSelect, resultRenderer, loading} = useSearchSuggestions();
+ const {suggestionsResults, handleResultSelect, resultRenderer, loading} = useContext(SearchSuggestionsContext);
const {status} = useContext(StatusContext);
let title = 'Dashboard';
@@ -196,7 +196,7 @@ export function DashboardPage() {
placeholder='Search everywhere...'
onClear={() => navigate('/')}
style={{marginBottom: '2em'}}
- results={suggestions}
+ results={suggestionsResults}
handleResultSelect={handleResultSelect}
resultRenderer={resultRenderer}
loading={loading}
@@ -220,7 +220,7 @@ export function DashboardPage() {
placeholder='Search everywhere...'
onClear={() => navigate('/')}
style={{marginBottom: '2em'}}
- results={suggestions}
+ results={suggestionsResults}
handleResultSelect={handleResultSelect}
resultRenderer={resultRenderer}
loading={loading}
diff --git a/app/src/api.js b/app/src/api.js
index fb703ecb..216c45a7 100644
--- a/app/src/api.js
+++ b/app/src/api.js
@@ -1003,22 +1003,6 @@ export async function fetchDecoded(vinNumber) {
}
}
-export async function searchEstimate(search_str, tagNames) {
- const body = {search_str: search_str, tag_names: tagNames};
- const response = await apiPost(`${API_URI}/search_estimate`, body);
- if (response.status === 200) {
- const content = await response.json();
- const zims = content['zims'];
- let zimSum = 0;
- zims.map(i => zimSum += i['estimate']);
- return {
- file_groups: content['file_groups'],
- zims: zims,
- zimSum: zimSum,
- }
- }
-}
-
export async function searchSuggestions(search_str) {
const body = {search_str: search_str};
const response = await apiPost(`${API_URI}/search_suggestions`, body);
diff --git a/app/src/components/Archive.js b/app/src/components/Archive.js
index ee48e548..d1c5fae8 100644
--- a/app/src/components/Archive.js
+++ b/app/src/components/Archive.js
@@ -492,10 +492,10 @@ function ArchivesPage() {
!!searchStr,
);
- const searchInput = ;
return <>
diff --git a/app/src/components/Channels.js b/app/src/components/Channels.js
index 4a8514e3..c02e064c 100644
--- a/app/src/components/Channels.js
+++ b/app/src/components/Channels.js
@@ -510,15 +510,14 @@ export function ChannelsPage() {
- setSearchStr('')}
- onChange={setSearchStr}
- onSubmit={null}
+ setSearchStr('')}
+ onChange={setSearchStr}
+ onSubmit={null}
/>
diff --git a/app/src/components/Common.js b/app/src/components/Common.js
index ea2963a0..b301da92 100644
--- a/app/src/components/Common.js
+++ b/app/src/components/Common.js
@@ -538,7 +538,7 @@ export function SearchResultsInput({
onResultSelect={localHandleResultSelect}
value={value}
size={size}
- results={!loading && results ? results : loadingResults}
+ results={!loading && !_.isEmpty(results) ? results : loadingResults}
resultRenderer={resultRenderer}
className='search-input'
loading={loading}
diff --git a/app/src/components/Search.js b/app/src/components/Search.js
index f767f6d8..c9040700 100644
--- a/app/src/components/Search.js
+++ b/app/src/components/Search.js
@@ -1,4 +1,4 @@
-import React, {useEffect, useState} from "react";
+import React, {useContext, useEffect, useState} from "react";
import {createSearchParams, Route, Routes, useNavigate} from "react-router-dom";
import {FilesSearchView} from "./Files";
import {useLatestRequest, usePages, useQuery} from "../hooks/customHooks";
@@ -9,6 +9,15 @@ import _ from "lodash";
import {TagsContext} from "../Tags";
import {Header as SHeader} from "semantic-ui-react";
+export const SearchSuggestionsContext = React.createContext({
+ suggestionsResults: {},
+ suggestions: {},
+ suggestionsSums: {},
+ handleResultSelect: null,
+ resultRenderer: null,
+ loading: false,
+});
+
const SUGGESTED_APPS = [
{location: '/more/otp', title: 'One Time Pad', description: 'Encrypt and Decrypt messages'},
{location: '/inventory', title: 'Inventory', description: 'Track and organize your food storage'},
@@ -29,17 +38,19 @@ export function useSearchSuggestions() {
const searchStr = searchParams.get('q');
const {data, sendRequest, loading} = useLatestRequest(500);
- const [suggestions, setSuggestions] = useState(null);
+ const [suggestionsResults, setSuggestionsResults] = useState({});
+ const [suggestions, setSuggestions] = useState({});
+ const [suggestionsSums, setSuggestionsSums] = useState({});
- const normalizeSuggestions = (newSuggestions) => {
+ const normalizeSuggestionsResults = (newSuggestions) => {
// Convert the suggestions from the Backend to what the Semantic expects.
const lowerSearchStr = searchStr.toLowerCase();
- let matchingSuggestions = {};
+ let results = {};
// Suggested results are ordered.
if (newSuggestions.fileGroups > 0) {
- matchingSuggestions.fileGroups = {
+ results.fileGroups = {
name: 'Files', results: [
{
title: newSuggestions.fileGroups.toString(),
@@ -50,23 +61,23 @@ export function useSearchSuggestions() {
};
}
- const zimSum = newSuggestions.zimsEstimates.reduce((i, j) => i + j['estimate'], 0).toString();
+ const zimSum = newSuggestions.zimsEstimates.reduce((i, j) => i + j['estimate'], 0);
if (zimSum > 0) {
- matchingSuggestions.zimsSum = {
+ results.zimsSum = {
name: 'Zims', results: [
- {title: zimSum, type: 'zims', location: `/search/zim?q=${encodeURIComponent(searchStr)}`}
+ {title: zimSum.toString(), type: 'zims', location: `/search/zim?q=${encodeURIComponent(searchStr)}`}
],
}
}
if (newSuggestions.channels && newSuggestions.channels.length > 0) {
- matchingSuggestions.channels = {
+ results.channels = {
name: 'Channels', results: newSuggestions.channels.map(i => {
return {type: 'channel', title: i['name'], id: i['id'], location: `/videos/channel/${i.id}/video`}
})
}
}
if (newSuggestions.domains && newSuggestions.domains.length > 0) {
- matchingSuggestions.domains = {
+ results.domains = {
name: 'Domains', results: newSuggestions.domains.map(i => {
return {
type: 'domain',
@@ -81,9 +92,9 @@ export function useSearchSuggestions() {
const matchingTags = fuzzyMatchTagsByName(searchStr);
if (matchingTags && matchingTags.length > 0) {
- matchingSuggestions.tags = {
+ results.tags = {
name: 'Tags', results: matchingTags.map(i => {
- return {type: 'tag', title: i.name, location: `/search?tag=${encodeURIComponent(i.title)}`}
+ return {type: 'tag', title: i.name, location: `/search?tag=${encodeURIComponent(i.name)}`}
})
}
}
@@ -92,16 +103,24 @@ export function useSearchSuggestions() {
i.title.toLowerCase().includes(lowerSearchStr)
|| fuzzyMatch(i.title.toLowerCase(), lowerSearchStr));
if (matchingApps && matchingApps.length > 0) {
- matchingSuggestions.apps = {name: 'Apps', results: matchingApps};
+ results.apps = {name: 'Apps', results: matchingApps};
}
- console.debug('matchingSuggestions', matchingSuggestions);
- setSuggestions(matchingSuggestions);
+ setSuggestionsResults(results);
+ setSuggestionsSums({
+ fileGroups: newSuggestions.fileGroups,
+ zims: zimSum,
+ channels: newSuggestions.channels.length,
+ domains: newSuggestions.domains.length,
+ tags: matchingTags.length,
+ apps: matchingApps.length,
+ })
}
React.useEffect(() => {
if (data) {
- normalizeSuggestions(data);
+ setSuggestions(data);
+ normalizeSuggestionsResults(data);
}
}, [JSON.stringify(data)]);
@@ -110,7 +129,9 @@ export function useSearchSuggestions() {
console.debug('Not getting suggestions because there is no search.');
return;
}
- setSuggestions(undefined);
+ setSuggestions({});
+ setSuggestionsSums({});
+ setSuggestionsResults({});
// Use the useLatestRequest to handle user typing.
sendRequest(async () => await searchSuggestions(searchStr));
@@ -133,7 +154,15 @@ export function useSearchSuggestions() {
return {title}
};
- return {suggestions, searchStr, handleResultSelect, resultRenderer, loading}
+ return {suggestions, suggestionsResults, suggestionsSums, searchStr, handleResultSelect, resultRenderer, loading}
+}
+
+export const SearchSuggestionsProvider = (props) => {
+ const value = useSearchSuggestions();
+
+ return
+ {props.children}
+
}
export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false, model) => {
@@ -196,51 +225,14 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
}
-export const useSearchEstimate = (search_str, activeTags) => {
- const [fileGroups, setFileGroups] = useState('?');
- const [zims, setZims] = useState(null);
- const [zimsSum, setZimsSum] = useState('?');
-
- const localFetchSearchEstimate = async () => {
- if (!search_str && (!activeTags || activeTags.length === 0)) {
- return;
- }
- try {
- const estimates = await searchEstimate(search_str, activeTags);
- console.debug('estimates', estimates);
- setFileGroups(estimates['file_groups']);
- setZimsSum(estimates['zimSum']);
- setZims(estimates['zims']);
- } catch (e) {
- console.error('Failed to fetch estimates');
- console.error(e);
- setFileGroups(null);
- setZimsSum(null);
- setZims(null);
- }
- }
-
- const debouncedEstimate = _.debounce(async () => await localFetchSearchEstimate(), 800);
-
- useEffect(() => {
- debouncedEstimate();
-
- return () => debouncedEstimate.cancel();
- }, [search_str, JSON.stringify(activeTags)]);
-
- return {fileGroups, zimsSum, zims}
-}
-
export function SearchView() {
- const {searchStr, activeTags} = useSearch();
- const estimates = useSearchEstimate(searchStr, activeTags);
+ const {suggestionsSums, suggestions} = useContext(SearchSuggestionsContext);
let filesTabName = 'Files';
let zimsTabName = 'Zims';
- if (estimates) {
- const {fileGroups, zimsSum} = estimates;
- filesTabName = `Files (${normalizeEstimate(fileGroups)})`;
- zimsTabName = `Zims (${normalizeEstimate(zimsSum)})`;
+ if (!_.isEmpty(suggestionsSums)) {
+ filesTabName = `Files (${normalizeEstimate(suggestionsSums.fileGroups)})`;
+ zimsTabName = `Zims (${normalizeEstimate(suggestionsSums.zims)})`;
}
const links = [
@@ -252,7 +244,7 @@ export function SearchView() {
}/>
- }/>
+ }/>
}
diff --git a/app/src/components/Videos.js b/app/src/components/Videos.js
index 7e3be167..c477059a 100644
--- a/app/src/components/Videos.js
+++ b/app/src/components/Videos.js
@@ -181,7 +181,7 @@ function VideosPage() {
!!searchStr,
);
- const searchInput = {
export const ZimSearchView = ({estimates}) => {
const [activeIndex, setActiveIndex] = React.useState(null);
const {searchStr, activeTags, setTags} = useSearch();
- const {zims} = estimates;
+ const {zimsEstimates} = estimates;
const handleClick = (index, activeIndex_) => {
setActiveIndex(index === activeIndex_ ? -1 : index);
}
- let body = ;
- if (zims && zims.length === 0) {
- body = ;
- } else if (zims) {
- body = zims.map((i, index) => ;
+ if (!_.isEmpty(zimsEstimates)) {
+ body = zimsEstimates.map((i, index) => {
export const StatusProvider = (props) => {
const value = useStatusInterval();
- return
+ const statusValue = React.useMemo(() => value, [value]);
+
+ return
{props.children}
}
diff --git a/modules/zim/test/test_api.py b/modules/zim/test/test_api.py
index d82fb256..1ad70503 100644
--- a/modules/zim/test/test_api.py
+++ b/modules/zim/test/test_api.py
@@ -108,31 +108,6 @@ def test_zim_crud(test_client, test_session, test_directory, test_zim):
assert test_session.query(Zim).count() == 0
-def test_zim_tag_estimate(test_client, test_session, test_zim, tag_factory):
- """Global search estimate returns Zim estimates."""
- tag1, tag2 = tag_factory(), tag_factory()
- test_session.commit()
-
- content = dict(search_str=None, tag_names=[tag1.name, ])
- request, response = test_client.post('/api/search_estimate', content=json.dumps(content))
- assert response.status_code == HTTPStatus.OK
- assert response.json['zims'] and response.json['zims'][0]['estimate'] == 0
-
- # Entries can be tagged in the API.
- content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
- request, response = test_client.post('/api/zim/tag', content=json.dumps(content))
- assert response.status_code == HTTPStatus.CREATED
- # Create other Tags directly.
- test_zim.tag_entry(tag2.name, 'one')
- test_zim.tag_entry(tag1.name, 'two')
- test_session.commit()
-
- content = dict(search_str=None, tag_names=[tag1.name, ])
- request, response = test_client.post('/api/search_estimate', content=json.dumps(content))
- assert response.status_code == HTTPStatus.OK
- assert response.json['zims'] and response.json['zims'][0]['estimate'] == 2
-
-
def test_zim_tag_and_untag(test_client, test_session, test_zim, tag_factory):
"""Zim entries can be Tagged and Untagged."""
tag1, tag2 = tag_factory(), tag_factory()
diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py
index 29855ad8..3771fb45 100644
--- a/wrolpi/root_api.py
+++ b/wrolpi/root_api.py
@@ -488,45 +488,6 @@ async def post_vin_number_decoder(_: Request, body: schema.VINDecoderRequest):
return json_response(dict(vin=vin))
-@api_bp.post('/search_estimate')
-@validate(schema.SearchEstimateRequest)
-async def post_search_estimate(_: Request, body: schema.SearchEstimateRequest):
- """Estimates the count of items of a search (FileGroups, Zim articles, etc.).
-
- If tag_names are provided, then the estimates are actual counts."""
- from modules.zim.models import Zims
-
- if not body.search_str and not body.tag_names:
- return response.empty(HTTPStatus.BAD_REQUEST)
-
- file_groups_estimate = await estimate_search(body.search_str, body.tag_names)
-
- if body.tag_names:
- # Get actual count of entries tagged with the tag names.
- zims_estimates = list()
- for zim, count in Zims.entries_with_tags(body.tag_names).items():
- d = dict(
- estimate=count,
- **zim.__json__(),
- )
- zims_estimates.append(d)
- else:
- # Get estimates using libzim.
- zims_estimates = list()
- for zim, estimate in Zims.estimate(body.search_str).items():
- d = dict(
- estimate=estimate,
- **zim.__json__(),
- )
- zims_estimates.append(d)
-
- ret = dict(
- file_groups=file_groups_estimate,
- zims=zims_estimates,
- )
- return json_response(ret)
-
-
@api_bp.post('/restart')
async def post_restart(_: Request):
if DOCKERIZED:
diff --git a/wrolpi/test/test_root_api.py b/wrolpi/test/test_root_api.py
index 0dd38379..f96fc46a 100644
--- a/wrolpi/test/test_root_api.py
+++ b/wrolpi/test/test_root_api.py
@@ -467,26 +467,6 @@ async def test_post_vin_number_decoder(test_async_client):
'years': '1995'}
-def test_search_str_estimate(test_session, test_client, test_directory, test_zim, example_pdf):
- """Get the search result estimates."""
- test_session.commit()
-
- request, response = test_client.post('/api/files/refresh')
- assert response.status_code == HTTPStatus.NO_CONTENT
-
- content = dict(search_str='example')
- request, response = test_client.post('/api/search_estimate', content=json.dumps(content))
- assert response.status_code == HTTPStatus.OK
-
- assert response.json['file_groups'] == 1
- assert len(response.json['zims']) == 1
- assert_dict_contains(response.json['zims'][0],
- dict(
- estimate=1,
- path=str(test_zim.path.relative_to(test_directory)),
- ))
-
-
@pytest.mark.asyncio
async def test_search_suggestions(test_session, test_async_client, channel_factory, archive_factory, tag_factory,
zim_factory):