diff --git a/app/src/DashboardPage.js b/app/src/DashboardPage.js
index 62166c38..a62c8995 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} from "./components/Search";
+import {SearchView, useSearch, useSearchSuggestions} from "./components/Search";
import {KiwixRestartMessage, OutdatedZimsMessage} from "./components/Zim";
import {useSettings, useWROLMode} from "./hooks/customHooks";
import {FileSearchFilterButton} from "./components/Files";
@@ -158,6 +158,7 @@ export function DashboardPage() {
const navigate = useNavigate();
const {searchStr, setSearchStr, activeTags} = useSearch();
+ const {suggestions} = useSearchSuggestions();
const {status} = useContext(StatusContext);
let title = 'Dashboard';
@@ -196,6 +197,7 @@ export function DashboardPage() {
actionIcon='search'
onClear={() => navigate('/')}
style={{marginBottom: '2em'}}
+ results={suggestions}
/>
@@ -217,6 +219,7 @@ export function DashboardPage() {
actionIcon='search'
onClear={() => navigate('/')}
style={{marginBottom: '2em'}}
+ results={suggestions}
/>
diff --git a/app/src/api.js b/app/src/api.js
index 219ef240..89a72827 100644
--- a/app/src/api.js
+++ b/app/src/api.js
@@ -1019,6 +1019,20 @@ export async function searchEstimate(search_str, tagNames) {
}
}
+export async function searchSuggestions(search_str) {
+ const body = {search_str: search_str};
+ const response = await apiPost(`${API_URI}/search_suggestions`, body);
+ if (response.ok) {
+ const content = await response.json();
+ const channels = content['channels'];
+ const domains = content['domains'];
+ return {
+ channels,
+ domains,
+ }
+ }
+}
+
export async function getOutdatedZims() {
const response = await apiGet(`${API_URI}/zim/outdated`);
if (response.status === 200) {
diff --git a/app/src/components/Common.js b/app/src/components/Common.js
index 9bbb5b8e..7008c1a2 100644
--- a/app/src/components/Common.js
+++ b/app/src/components/Common.js
@@ -412,9 +412,11 @@ export function SearchInput({
autoFocus = false,
onClear = null,
onChange = null,
+ results = null,
...props
}) {
const [value, setValue] = useState(searchStr || '');
+ const navigate = useNavigate();
const handleChange = (e) => {
if (e) {
@@ -453,6 +455,22 @@ export function SearchInput({
}
}
+ const localHandleResultSelect = (e, {result}) => {
+ if (e) {
+ e.preventDefault();
+ }
+
+ if (!result) {
+ return;
+ }
+
+ if (result['type'] === 'channel') {
+ navigate(`/videos/channel/${result['id']}/video`);
+ } else if (result['type'] === 'domain') {
+ navigate(`/archive?domain=${result['domain']}`);
+ }
+ }
+
if ((action || actionIcon) && searchStr && searchStr === value && clearable) {
action = ;
} else if (actionIcon) {
@@ -462,13 +480,15 @@ export function SearchInput({
}
return
}
diff --git a/app/src/components/Search.js b/app/src/components/Search.js
index 7df36836..66997794 100644
--- a/app/src/components/Search.js
+++ b/app/src/components/Search.js
@@ -3,9 +3,46 @@ import {createSearchParams, Route, Routes, useNavigate} from "react-router-dom";
import {FilesSearchView} from "./Files";
import {usePages, useQuery} from "../hooks/customHooks";
import {ZimSearchView} from "./Zim";
-import {searchEstimate} from "../api";
+import {searchEstimate, searchSuggestions} from "../api";
import {normalizeEstimate, TabLinks} from "./Common";
+export function useSearchSuggestions() {
+ const {searchParams} = useQuery();
+ const searchStr = searchParams.get('q');
+
+ const [suggestions, setSuggestions] = useState(null);
+
+ const fetchSuggestions = async () => {
+ if (searchStr && searchStr.length > 0) {
+ try {
+ const i = await searchSuggestions(searchStr);
+ const newSuggestions = {
+ channels: {
+ name: 'Channels', results: i['channels'].map(i => {
+ return {title: i['name'], id: i['id'], type: 'channel'}
+ })
+ },
+ domains: {
+ name: 'Domains', results: i['domains'].map(i => {
+ return {title: i['domain'], id: i['id'], type: 'domain'}
+ })
+ },
+ };
+ setSuggestions(newSuggestions);
+ } catch (e) {
+ console.error(e);
+ console.error('Failed to get search suggestions');
+ }
+ }
+ }
+
+ React.useEffect(() => {
+ fetchSuggestions();
+ }, [searchStr]);
+
+ return {suggestions, searchStr}
+}
+
export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false, model) => {
const navigate = useNavigate();
diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py
index 615edc5c..176382fd 100644
--- a/wrolpi/root_api.py
+++ b/wrolpi/root_api.py
@@ -544,6 +544,22 @@ async def post_shutdown(_: Request):
return response.empty(HTTPStatus.NO_CONTENT)
+@api_bp.post('/search_suggestions')
+@validate(schema.SearchSuggestionsRequest)
+async def post_search_suggestions(_: Request, body: schema.SearchSuggestionsRequest):
+ """Used by the Global search to suggest links to the user."""
+ from modules.videos.channel.lib import search_channels_by_name
+ from modules.archive.lib import search_domains_by_name
+
+ channels = sorted(search_channels_by_name(body.search_str), key=lambda i: i.name)
+ domains = sorted(search_domains_by_name(body.search_str), key=lambda i: i.domain)
+ ret = dict(
+ channels=channels,
+ domains=domains,
+ )
+ return json_response(ret)
+
+
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
diff --git a/wrolpi/schema.py b/wrolpi/schema.py
index 35a7bc0d..baa3b18c 100644
--- a/wrolpi/schema.py
+++ b/wrolpi/schema.py
@@ -141,3 +141,8 @@ class VINDecoderResponse:
class SearchEstimateRequest:
search_str: Optional[str] = None
tag_names: List[str] = field(default_factory=lambda: list())
+
+
+@dataclass
+class SearchSuggestionsRequest:
+ search_str: Optional[str] = None
diff --git a/wrolpi/test/test_root_api.py b/wrolpi/test/test_root_api.py
index d9fab2cb..081b2333 100644
--- a/wrolpi/test/test_root_api.py
+++ b/wrolpi/test/test_root_api.py
@@ -487,6 +487,32 @@ def test_search_str_estimate(test_session, test_client, test_directory, test_zim
))
+@pytest.mark.asyncio
+async def test_search_suggestions(test_session, test_async_client, channel_factory, archive_factory):
+ channel_factory(name='Foo')
+ channel_factory(name='Fool')
+ channel_factory(name='Bar')
+ archive_factory(domain='foo.com')
+ archive_factory(domain='bar.com')
+ test_session.commit()
+
+ body = dict(search_str='foo')
+ request, response = await test_async_client.post('/api/search_suggestions', json=body)
+ assert response.status_code == HTTPStatus.OK
+ assert response.json['channels'] == [{'directory': 'Foo', 'id': 1, 'name': 'Foo', 'url': 'https://example.com/Foo'},
+ {'directory': 'Fool',
+ 'id': 2,
+ 'name': 'Fool',
+ 'url': 'https://example.com/Fool'}]
+ assert response.json['domains'] == [{'directory': 'archive/foo.com', 'domain': 'foo.com', 'id': 1}]
+
+ body = dict(search_str='bar')
+ request, response = await test_async_client.post('/api/search_suggestions', json=body)
+ assert response.status_code == HTTPStatus.OK
+ assert response.json['channels'] == [{'directory': 'Bar', 'id': 3, 'name': 'Bar', 'url': 'https://example.com/Bar'}]
+ assert response.json['domains'] == [{'directory': 'archive/bar.com', 'domain': 'bar.com', 'id': 2}]
+
+
def test_recursive_errors():
"""Errors are reported recursively."""