Matching tag names in FE, rather than in BE.

This commit is contained in:
Roland 2023-11-21 15:47:08 -07:00
parent 22237dfcbb
commit 2d16374421
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
6 changed files with 34 additions and 29 deletions

View file

@ -1,7 +1,7 @@
import React, {useEffect} from "react";
import {deleteTag, getTags, saveTag} from "./api";
import {Dimmer, Divider, Form, Grid, GridColumn, GridRow, Label, TableCell, TableRow,} from "semantic-ui-react";
import {APIButton, contrastingColor, ErrorMessage, scrollToTopOfElement} from "./components/Common";
import {APIButton, contrastingColor, ErrorMessage, fuzzyMatch, scrollToTopOfElement} from "./components/Common";
import {
Button,
FormInput,
@ -28,6 +28,7 @@ export const TagsContext = React.createContext({
SingleTag: null,
fetchTags: null,
findTagByName: null,
fuzzyMatchTagsByName: null,
tagNames: [],
tags: [],
});
@ -62,6 +63,16 @@ export function useTags() {
}
}
const fuzzyMatchTagsByName = (name) => {
const lowerName = name.toLowerCase();
if (!tags || tags.length === 0) {
return []
}
return tags.filter(i => i.name.toLowerCase().includes(name)
|| fuzzyMatch(lowerName, i.name.toLowerCase()))
}
const NameToTagLabel = ({name, to, ...props}) => {
const defaultTag = <Label size='large'>{name}</Label>;
const tag = findTagByName(name);
@ -128,7 +139,17 @@ export function useTags() {
fetchTags();
}, []);
return {tags, tagNames, NameToTagLabel, TagsGroup, TagsLinkGroup, fetchTags, findTagByName, SingleTag}
return {
tags,
tagNames,
NameToTagLabel,
TagsGroup,
TagsLinkGroup,
fetchTags,
findTagByName,
SingleTag,
fuzzyMatchTagsByName
}
}
export const useTagsInterval = () => {

View file

@ -1029,13 +1029,11 @@ export async function searchSuggestions(search_str) {
const zimsEstimates = content['zims_estimates'];
const channels = content['channels'];
const domains = content['domains'];
const tags = content['tags'];
return {
fileGroups,
zimsEstimates,
channels,
domains,
tags,
}
}
}

View file

@ -22,7 +22,7 @@ const suggestedApps = [
export function useSearchSuggestions() {
const navigate = useNavigate();
const {searchParams} = useQuery();
const {SingleTag} = React.useContext(TagsContext);
const {SingleTag, fuzzyMatchTagsByName} = React.useContext(TagsContext);
const searchStr = searchParams.get('q');
@ -69,13 +69,13 @@ export function useSearchSuggestions() {
})
}
}
if (newSuggestions.tags && newSuggestions.tags.length > 0) {
matchingSuggestions.tags = {
name: 'Tags', results: newSuggestions.tags.map(i => {
return {type: 'tag', description: i['name']}
})
}
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};
}
@ -108,7 +108,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['title'])}`);
return navigate(`/search?tag=${encodeURIComponent(result['description'])}`);
} else if (result['type'] === 'files') {
return navigate(`/search?q=${encodeURIComponent(searchStr)}`);
} else if (result['type'] === 'zims') {

View file

@ -556,11 +556,10 @@ async def post_search_suggestions(_: Request, body: schema.SearchSuggestionsRequ
if not body.search_str and not body.tag_names:
return response.empty(HTTPStatus.BAD_REQUEST)
file_groups, channels, domains, tags_ = await asyncio.gather(
file_groups, channels, domains = await asyncio.gather(
estimate_search(body.search_str, body.tag_names),
search_channels_by_name(body.search_str),
search_domains_by_name(body.search_str),
tags.search_tags_by_name(body.search_str),
)
if body.tag_names:
@ -587,7 +586,6 @@ async def post_search_suggestions(_: Request, body: schema.SearchSuggestionsRequ
zims_estimates=zims_estimates,
channels=channels,
domains=domains,
tags=tags_,
)
return json_response(ret)

View file

@ -1,9 +1,9 @@
import contextlib
import pathlib
from datetime import datetime
from typing import List, Dict, Tuple, Sequence
from typing import List, Dict, Tuple
from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger, asc
from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import relationship, Session
@ -461,13 +461,3 @@ def tag_names_to_zim_sub_select(tag_names: List[str], zim_id: int = None) -> Tup
HAVING array_agg(t.name)::TEXT[] @> %(tag_names)s::TEXT[]
'''
return stmt, params
@optional_session
async def search_tags_by_name(name: str, limit: int = 5, session: Session = None) -> Sequence[Tag]:
tags = session.query(Tag) \
.filter(Tag.name.ilike(f'%{name}%')) \
.order_by(asc(Tag.name)) \
.limit(limit) \
.all()
return tags

View file

@ -496,7 +496,6 @@ async def test_search_suggestions(test_session, test_async_client, channel_facto
archive_factory(domain='foo.com', contents='contents of foo')
archive_factory(domain='bar.com', contents='contents of bar')
zim_factory('test zim')
tag_factory()
test_session.commit()
body = dict(search_str='foo')
@ -525,7 +524,6 @@ async def test_search_suggestions(test_session, test_async_client, channel_facto
assert response.status_code == HTTPStatus.OK
assert response.json['channels'] == []
assert response.json['domains'] == []
assert response.json['tags'] == [{'color': '#111111', 'id': 1, 'name': 'one'}]
assert response.json['file_groups'] == 0
assert response.json['zims_estimates'][0]['estimate'] == 2