添加字幕搜索功能

This commit is contained in:
IndieKKY
2023-11-28 13:53:01 +08:00
parent 9f486b7269
commit 8d1bac4623
13 changed files with 403 additions and 29 deletions

View File

@@ -0,0 +1,58 @@
import {useAppDispatch, useAppSelector} from './redux'
import {useEffect, useMemo} from 'react'
import {setSearchResult, setSearchText, } from '../redux/envReducer'
import {Search} from '../util/search'
interface Document {
idx: number
s: string // searchKeys
}
const useSearchService = () => {
const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData)
const data = useAppSelector(state => state.env.data)
const searchText = useAppSelector(state => state.env.searchText)
const {reset, search} = useMemo(() => Search('idx', 's', 256, {
cnSearchEnabled: envData.cnSearchEnabled
}), [envData.cnSearchEnabled]) // 搜索实例
// reset search
useEffect(() => {
const startTime = Date.now()
const docs: Document[] = []
for (const item of data?.body??[]) {
docs.push({
idx: item.idx,
s: item.content,
})
}
reset(docs)
// 清空搜索文本
dispatch(setSearchText(''))
// 日志
const endTime = Date.now()
console.debug(`[Search]reset ${docs.length} docs, cost ${endTime-startTime}ms`)
}, [data?.body, dispatch, reset])
// search text
useEffect(() => {
const searchResult: Set<number> = new Set()
if (searchText) {
// @ts-expect-error
const documents: Document[] | undefined = search(searchText)
if (documents != null) {
for (const document of documents) {
searchResult.add(document.idx)
}
}
}
dispatch(setSearchResult(searchResult))
}, [dispatch, search, searchText])
}
export default useSearchService