24 Commits
1.7.5 ... 1.8.1

Author SHA1 Message Date
IndieKKY
d7085ba75e chore: release 1.8.1 2024-02-18 10:33:24 +08:00
IndieKKY
b8d8b8fe06 模型更新 2024-02-18 10:33:00 +08:00
IndieKKY
d42844ac3c 不限制最大字数 2024-01-26 13:21:10 +08:00
IndieKKY
e66f85ff9f chore: release 1.8.0 2024-01-20 13:35:42 +08:00
IndieKKY
d97af83c9e 支持gemini 2024-01-20 13:35:26 +08:00
IndieKKY
c70fa81482 chore: release 1.7.11 2024-01-20 13:31:00 +08:00
IndieKKY
4dbce345c2 chore: release 1.7.10 2024-01-20 13:21:55 +08:00
IndieKKY
aa098df6a5 支持gemini 2024-01-20 13:21:44 +08:00
IndieKKY
fa99fa8b3d chore: release 1.7.9 2024-01-20 13:19:03 +08:00
IndieKKY
5078baca1b 支持gemini 2024-01-20 13:18:39 +08:00
IndieKKY
771a802728 支持gemini 2024-01-20 11:39:21 +08:00
IndieKKY
9038bf7128 文章视图加逗号 2024-01-20 10:31:59 +08:00
IndieKKY
f01e175b4e 保存下载类型选择 2024-01-20 10:21:27 +08:00
IndieKKY
8098d7cf9b 保存列表/文章视图选择 2024-01-20 10:19:47 +08:00
IndieKKY
728e4dce84 chore: release 1.7.8 2023-12-24 09:05:41 +08:00
IndieKKY
a54b4a7e5f youtube caption 调整 2023-12-24 09:02:13 +08:00
IndieKKY
8a908ecf99 主颜色调整 2023-12-24 09:01:18 +08:00
IndieKKY
bdc7823965 chore: release 1.7.7 2023-11-28 19:45:30 +08:00
IndieKKY
8d1bac4623 添加字幕搜索功能 2023-11-28 19:43:58 +08:00
IndieKKY
9f486b7269 readme 2023-11-28 10:46:59 +08:00
IndieKKY
e10de9bc48 version 2023-11-28 10:35:51 +08:00
IndieKKY
dd7ce4ab38 readme 2023-11-28 10:34:20 +08:00
IndieKKY
250da4fd28 添加firefox支持 2023-11-28 10:30:42 +08:00
IndieKKY
65861829e2 增加模型选择 2023-11-28 10:23:35 +08:00
27 changed files with 712 additions and 105 deletions

View File

@@ -19,7 +19,9 @@
## 下载扩展
[chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp)
- [chrome商店](https://chrome.google.com/webstore/detail/bciglihaegkdhoogebcdblfhppoilclp)
- [edge商店](https://microsoftedge.microsoft.com/addons/detail/lignnlhlpiefmcjkdkmfjdckhlaiajan)
- [firefox商店](https://addons.mozilla.org/zh-CN/firefox/addon/bilibili-subtitle)
## 使用说明

22
fixFirefox.cjs Normal file
View File

@@ -0,0 +1,22 @@
console.log('fixFirefox.js loaded');
const fs = require('fs')
const manifest = require('./dist/manifest.json')
manifest.web_accessible_resources[0].resources.push('index.html')
manifest.action.default_popup = 'popup.html'
//browser_specific_settings
manifest.browser_specific_settings = {
"gecko": {
"id": "bilibili-subtitle@indiekky"
}
}
//background
manifest.background = {
type: "module",
scripts: [manifest.background.service_worker]
}
//写回文件
fs.writeFileSync('./dist/manifest.json', JSON.stringify(manifest, null, 2))
console.log('fixFirefox.js done');

View File

@@ -1,7 +1,7 @@
{
"name": "哔哩哔哩字幕列表",
"description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!",
"version": "1.7.5",
"version": "1.8.1",
"manifest_version": 3,
"permissions": [
"storage"

View File

@@ -1,15 +1,16 @@
{
"private": true,
"name": "bilibili-subtitle",
"version": "1.7.5",
"version": "1.8.1",
"type": "module",
"description": "哔哩哔哩字幕列表",
"main": "index.js",
"scripts": {
"dev": "vite",
"build_chrome": "tsc && vite build -m production_chrome && pnpm run fixChrome",
"fix": "eslint --fix --quiet .",
"fixChrome": "node fixChrome.cjs"
"build": "tsc && vite build -m production_chrome",
"build_chrome": "pnpm run build && node fixChrome.cjs",
"build_firefox": "pnpm run build && node fixFirefox.cjs",
"fix": "eslint --fix --quiet ."
},
"author": "IndieKKY",
"license": "MIT",

10
pnpm-lock.yaml generated
View File

@@ -1,5 +1,9 @@
lockfileVersion: '6.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
dependencies:
'@crxjs/vite-plugin':
specifier: ^1.0.14
@@ -2386,6 +2390,7 @@ packages:
/iconv-lite@0.6.3:
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
engines: {node: '>=0.10.0'}
requiresBuild: true
dependencies:
safer-buffer: 2.1.2
optional: true
@@ -3392,6 +3397,7 @@ packages:
/pify@4.0.1:
resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==}
engines: {node: '>=6'}
requiresBuild: true
optional: true
/postcss-import@14.1.0(postcss@8.4.19):
@@ -3475,6 +3481,7 @@ packages:
/prr@1.0.1:
resolution: {integrity: sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==}
requiresBuild: true
optional: true
/punycode@2.1.1:
@@ -3802,10 +3809,12 @@ packages:
/safer-buffer@2.1.2:
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
requiresBuild: true
optional: true
/sax@1.2.4:
resolution: {integrity: sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==}
requiresBuild: true
optional: true
/scheduler@0.23.0:
@@ -3822,6 +3831,7 @@ packages:
/semver@5.7.1:
resolution: {integrity: sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==}
hasBin: true
requiresBuild: true
optional: true
/semver@6.3.0:

View File

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -15,6 +15,7 @@ import {handleJson} from '@kky002/kky-util'
import {useLocalStorage} from '@kky002/kky-hooks'
import {Toaster} from 'react-hot-toast'
import {setTheme} from './util/biz_util'
import useSearchService from './hooks/useSearchService'
function App() {
const dispatch = useAppDispatch()
@@ -72,6 +73,7 @@ function App() {
// services
useSubtitleService()
useTranslateService()
useSearchService()
return <div className={classNames('select-none', import.meta.env.VITE_ENV === 'web-dev'?'w-[350px]':'w-full')} style={{
height: fold?undefined:`${totalHeight}px`,

View File

@@ -3,18 +3,34 @@ import {
setAutoScroll,
setAutoTranslate,
setCheckAutoScroll,
setCompact,
setFoldAll,
setNeedScroll,
setPage,
setSegmentFold
setSearchText,
setSegmentFold,
setTempData
} from '../redux/envReducer'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {AiOutlineAim, FaRegArrowAltCircleDown, IoWarning, MdExpand, RiFileCopy2Line, RiTranslate} from 'react-icons/all'
import {
AiOutlineAim,
AiOutlineCloseCircle,
FaRegArrowAltCircleDown,
IoWarning,
MdExpand,
RiFileCopy2Line,
RiTranslate
} from 'react-icons/all'
import classNames from 'classnames'
import toast from 'react-hot-toast'
import SegmentCard from './SegmentCard'
import {HEADER_HEIGHT, PAGE_SETTINGS, SUMMARIZE_ALL_THRESHOLD, SUMMARIZE_TYPES, TITLE_HEIGHT} from '../const'
import {
HEADER_HEIGHT,
PAGE_SETTINGS,
SEARCH_BAR_HEIGHT,
SUMMARIZE_ALL_THRESHOLD,
SUMMARIZE_TYPES,
TITLE_HEIGHT
} from '../const'
import {FaClipboardList} from 'react-icons/fa'
import useTranslate from '../hooks/useTranslate'
import {getSummarize} from '../util/biz_util'
@@ -28,8 +44,7 @@ const Body = () => {
const segments = useAppSelector(state => state.env.segments)
const foldAll = useAppSelector(state => state.env.foldAll)
const envData = useAppSelector(state => state.env.envData)
const compact = useAppSelector(state => state.env.compact)
const apiKey = useAppSelector(state => state.env.envData.apiKey)
const compact = useAppSelector(state => state.env.tempData.compact)
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
const translateEnable = useAppSelector(state => state.env.envData.translateEnable)
const summarizeEnable = useAppSelector(state => state.env.envData.summarizeEnable)
@@ -41,13 +56,18 @@ const Body = () => {
const totalHeight = useAppSelector(state => state.env.totalHeight)
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
const title = useAppSelector(state => state.env.title)
const searchText = useAppSelector(state => state.env.searchText)
const normalCallback = useCallback(() => {
dispatch(setCompact(false))
dispatch(setTempData({
compact: false
}))
}, [dispatch])
const compactCallback = useCallback(() => {
dispatch(setCompact(true))
dispatch(setTempData({
compact: true
}))
}, [dispatch])
const posCallback = useCallback(() => {
@@ -55,6 +75,7 @@ const Body = () => {
}, [dispatch])
const onSummarizeAll = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (!apiKey) {
dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!')
@@ -77,7 +98,7 @@ const Body = () => {
}
toast.success(`已添加${segments_.length}个总结任务!`)
}
}, [addSummarizeTask, apiKey, curSummaryType, dispatch, segments])
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segments])
const onFoldAll = useCallback(() => {
dispatch(setFoldAll(!foldAll))
@@ -90,13 +111,14 @@ const Body = () => {
}, [dispatch, foldAll, segments])
const toggleAutoTranslateCallback = useCallback(() => {
if (envData.apiKey) {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (apiKey) {
dispatch(setAutoTranslate(!autoTranslate))
} else {
dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!')
}
}, [autoTranslate, dispatch, envData.apiKey])
}, [autoTranslate, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey])
const onEnableAutoScroll = useCallback(() => {
dispatch(setAutoScroll(true))
@@ -118,6 +140,15 @@ const Body = () => {
}
}, [curSummaryType, segments, title])
const onSearchTextChange = useCallback((e: any) => {
const searchText = e.target.value
dispatch(setSearchText(searchText))
}, [dispatch])
const onClearSearchText = useCallback(() => {
dispatch(setSearchText(''))
}, [dispatch])
// 自动滚动
useEffect(() => {
if (checkAutoScroll && curOffsetTop && autoScroll && !needScroll) {
@@ -132,6 +163,7 @@ const Body = () => {
}, [autoScroll, checkAutoScroll, curOffsetTop, dispatch, floatKeyPointsSegIdx, needScroll, totalHeight])
return <div className='relative'>
{/* title */}
<div className='absolute top-1 left-6 flex-center gap-1'>
<AiOutlineAim className='cursor-pointer' onClick={posCallback} title='滚动到视频位置'/>
{segments != null && segments.length > 0 &&
@@ -159,27 +191,39 @@ const Body = () => {
<IoWarning className='text-warning'/>
</div>}
</div>
{/* search */}
{envData.searchEnabled && <div className='px-2 py-1 flex flex-col relative'>
<input type='text' className='input input-xs bg-base-200' placeholder='搜索字幕内容' value={searchText} onChange={onSearchTextChange}/>
{searchText && <button className='absolute top-1 right-2 btn btn-ghost btn-xs btn-circle text-base-content/75' onClick={onClearSearchText}><AiOutlineCloseCircle/></button>}
</div>}
{/* auto scroll btn */}
{!autoScroll && <div
className='absolute z-[999] top-[96px] right-6 tooltip tooltip-left cursor-pointer rounded-full bg-primary/25 hover:bg-primary/75 text-primary-content p-1.5 text-xl'
data-tip='开启自动滚动'
onClick={onEnableAutoScroll}>
<FaRegArrowAltCircleDown className={autoScroll ? 'text-accent' : ''}/>
</div>}
{/* body */}
<div ref={bodyRef} onWheel={onWheel}
className={classNames('flex flex-col gap-1.5 overflow-y-auto select-text scroll-smooth', floatKeyPointsSegIdx != null && 'pb-[100px]')}
style={{
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT}px`
height: `${totalHeight - HEADER_HEIGHT - TITLE_HEIGHT - (envData.searchEnabled?SEARCH_BAR_HEIGHT:0)}px`
}}
>
{segments?.map((segment, segmentIdx) => <SegmentCard key={segment.startIdx} segment={segment} segmentIdx={segmentIdx} bodyRef={bodyRef}/>)}
{/* tip */}
<div className='flex flex-col items-center text-center pt-1 pb-2'>
<div className='font-semibold text-accent'>💡<span className='underline underline-offset-4'></span>💡</div>
<div className='text-sm desc px-2'><span className='text-amber-600 font-semibold'></span><span className='text-secondary/75 font-semibold'></span>🥳</div>
{(segments?.length??0) > 0 && <button className='mt-1.5 btn btn-xs btn-info' onClick={onCopy}>{SUMMARIZE_TYPES[curSummaryType].name}<RiFileCopy2Line/></button>}
</div>
<div className='flex flex-col items-center text-center py-2 mx-4 border-t border-t-base-300'>
<div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-subtitle.png' alt='youtube subtitle' className='w-8 h-8'/>Youtube Subtitle</div>
<div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'>Youtube</span></div>
<div className='font-semibold text-accent flex items-center gap-1'><img src='/youtube-caption.png' alt='youtube caption pro' className='w-8 h-8'/>YouTube Caption Pro</div>
<div className='text-sm px-2 desc'><span className='text-amber-600 font-semibold text-base'>YouTube</span></div>
<div className='flex gap-2'>
<a title='Chrome商店' href='https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf' onClick={(e) => {
e.preventDefault()

View File

@@ -4,11 +4,7 @@ import {getDisplay, getTransText} from '../util/biz_util'
import classNames from 'classnames'
const CompactSegmentItem = (props: {
item: {
from: number
to: number
content: string
}
item: TranscriptItem
idx: number
isIn: boolean
last: boolean
@@ -26,7 +22,7 @@ const CompactSegmentItem = (props: {
<span className={'pl-1 pr-0.5 py-0.5 cursor-pointer rounded-sm hover:bg-base-200'} onClick={moveCallback}>
<text className={classNames('font-medium', isIn ? 'text-primary underline' : '')}>{display.main}</text>
{display.sub && <text className='desc'>({display.sub})</text>}</span>
<span>{!last && ', '}</span>
<span className='text-base-content/75'>{!last && ','}</span>
</div>
}

View File

@@ -11,7 +11,7 @@ import {
import Popover from '../components/Popover'
import {Placement} from '@popperjs/core/lib/enums'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {setDownloadType, setEnvData, setPage} from '../redux/envReducer'
import {setEnvData, setPage, setTempData} from '../redux/envReducer'
import {EventBusContext} from '../Router'
import {EVENT_EXPAND, PAGE_SETTINGS} from '../const'
import {formatSrtTime, formatTime, formatVttTime} from '../util/util'
@@ -62,7 +62,7 @@ const MoreBtn = (props: Props) => {
const data = useAppSelector(state => state.env.data)
const envReady = useAppSelector(state => state.env.envReady)
const envData = useAppSelector(state => state.env.envData)
const downloadType = useAppSelector(state => state.env.downloadType)
const downloadType = useAppSelector(state => state.env.tempData.downloadType)
const [moreVisible, setMoreVisible] = useState(false)
const eventBus = useContext(EventBusContext)
const segments = useAppSelector(state => state.env.segments)
@@ -162,7 +162,9 @@ const MoreBtn = (props: Props) => {
}, [])
const selectCallback = useCallback((e: any) => {
dispatch(setDownloadType(e.target.value))
dispatch(setTempData({
downloadType: e.target.value,
}))
}, [dispatch])
const preventCallback = useCallback((e: any) => {
@@ -265,8 +267,8 @@ const MoreBtn = (props: Props) => {
e.stopPropagation()
openUrl('https://chromewebstore.google.com/detail/fiaeclpicddpifeflpmlgmbjgaedladf')
}}>
<img alt='youtube subtitle' src='/youtube-subtitle.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/>
Youtube Subtitle
<img alt='youtube subtitle' src='/youtube-caption.png' className='w-[20px] h-[20px] bg-white rounded-sm p-0.5'/>
Youtube Caption Pro
</a>
</li>
<li className='hover:bg-accent'>

View File

@@ -5,11 +5,7 @@ import {getDisplay, getTransText} from '../util/biz_util'
import classNames from 'classnames'
const NormalSegmentItem = (props: {
item: {
from: number
to: number
content: string
}
item: TranscriptItem
idx: number
isIn: boolean
moveCallback: (event: any) => void

View File

@@ -66,19 +66,20 @@ const Summarize = (props: {
const {segment, segmentIdx, summary, float} = props
const dispatch = useAppDispatch()
const apiKey = useAppSelector(state => state.env.envData.apiKey)
const envData = useAppSelector(state => state.env.envData)
const fontSize = useAppSelector(state => state.env.envData.fontSize)
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)
const {addSummarizeTask} = useTranslate()
const onGenerate = useCallback(() => {
const apiKey = envData.aiType === 'gemini'?envData.geminiApiKey:envData.apiKey
if (apiKey) {
addSummarizeTask(curSummaryType, segment).catch(console.error)
} else {
dispatch(setPage(PAGE_SETTINGS))
toast.error('需要先设置ApiKey!')
}
}, [addSummarizeTask, apiKey, curSummaryType, dispatch, segment])
}, [addSummarizeTask, curSummaryType, dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, segment])
const onCopy = useCallback(() => {
if (summary != null) {
@@ -138,7 +139,7 @@ const SegmentCard = (props: {
const summarizeFloat = useAppSelector(state => state.env.envData.summarizeFloat)
const fold = useAppSelector(state => state.env.fold)
const page = useAppSelector(state => state.env.page)
const compact = useAppSelector(state => state.env.compact)
const compact = useAppSelector(state => state.env.tempData.compact)
const floatKeyPointsSegIdx = useAppSelector(state => state.env.floatKeyPointsSegIdx)
const showCurrent = useMemo(() => curIdx != null && segment.startIdx <= curIdx && curIdx <= segment.endIdx, [curIdx, segment.endIdx, segment.startIdx])
const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType)

View File

@@ -1,4 +1,4 @@
import React, {useCallback, useEffect, useRef} from 'react'
import React, {useCallback, useEffect, useMemo, useRef} from 'react'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import useSubtitle from '../hooks/useSubtitle'
import {setCheckAutoScroll, setCurOffsetTop, setNeedScroll} from '../redux/envReducer'
@@ -7,21 +7,27 @@ import CompactSegmentItem from './CompactSegmentItem'
const SegmentItem = (props: {
bodyRef: any
item: {
from: number
to: number
content: string
}
item: TranscriptItem
idx: number
isIn: boolean
needScroll?: boolean
last: boolean
}) => {
const dispatch = useAppDispatch()
const {bodyRef, item, idx, isIn, needScroll, last} = props
const dispatch = useAppDispatch()
const ref = useRef<any>()
const {move} = useSubtitle()
const compact = useAppSelector(state => state.env.compact)
const compact = useAppSelector(state => state.env.tempData.compact)
const searchText = useAppSelector(state => state.env.searchText)
const searchResult = useAppSelector(state => state.env.searchResult)
const display = useMemo(() => {
if (searchText) {
return searchResult.has(item.idx) ? 'inline' : 'none'
} else {
return 'inline'
}
}, [item.idx, searchResult, searchText])
const moveCallback = useCallback((event: any) => {
if (event.altKey) { // 复制
@@ -47,7 +53,9 @@ const SegmentItem = (props: {
}
}, [dispatch, isIn])
return <span ref={ref}>
return <span ref={ref} style={{
display
}}>
{compact
? <CompactSegmentItem
item={item}

View File

@@ -58,15 +58,19 @@ const Settings = () => {
// const {value: autoScrollValue, onChange: setAutoScrollValue} = useEventChecked(envData.autoScroll)
const {value: translateEnableValue, onChange: setTranslateEnableValue} = useEventChecked(envData.translateEnable)
const {value: summarizeEnableValue, onChange: setSummarizeEnableValue} = useEventChecked(envData.summarizeEnable)
const {value: searchEnabledValue, onChange: setSearchEnabledValue} = useEventChecked(envData.searchEnabled)
const {value: cnSearchEnabledValue, onChange: setCnSearchEnabledValue} = useEventChecked(envData.cnSearchEnabled)
const {value: summarizeFloatValue, onChange: setSummarizeFloatValue} = useEventChecked(envData.summarizeFloat)
const [apiKeyValue, { onChange: onChangeApiKeyValue }] = useEventTarget({initialValue: envData.apiKey??''})
const [serverUrlValue, setServerUrlValue] = useState(envData.serverUrl)
const [geminiApiKeyValue, { onChange: onChangeGeminiApiKeyValue }] = useEventTarget({initialValue: envData.geminiApiKey??''})
const [languageValue, { onChange: onChangeLanguageValue }] = useEventTarget({initialValue: envData.language??LANGUAGE_DEFAULT})
const [modelValue, { onChange: onChangeModelValue }] = useEventTarget({initialValue: envData.model??MODEL_DEFAULT})
const [summarizeLanguageValue, { onChange: onChangeSummarizeLanguageValue }] = useEventTarget({initialValue: envData.summarizeLanguage??SUMMARIZE_LANGUAGE_DEFAULT})
const [hideOnDisableAutoTranslateValue, setHideOnDisableAutoTranslateValue] = useState(envData.hideOnDisableAutoTranslate)
const [themeValue, setThemeValue] = useState(envData.theme)
const [fontSizeValue, setFontSizeValue] = useState(envData.fontSize)
const [aiTypeValue, setAiTypeValue] = useState(envData.aiType)
const [transDisplayValue, setTransDisplayValue] = useState(envData.transDisplay)
const [wordsValue, setWordsValue] = useState<number | undefined>(envData.words??WORDS_DEFAULT)
const [fetchAmountValue, setFetchAmountValue] = useState(envData.fetchAmount??TRANSLATE_FETCH_DEFAULT)
@@ -89,6 +93,12 @@ const Settings = () => {
}
return list
}, [])
const apiKeySetted = useMemo(() => {
if (aiTypeValue === 'gemini') {
return !!geminiApiKeyValue
}
return !!apiKeyValue
}, [aiTypeValue, apiKeyValue, geminiApiKeyValue])
const onChangeHideOnDisableAutoTranslate = useCallback((e: any) => {
setHideOnDisableAutoTranslateValue(e.target.checked)
@@ -97,9 +107,11 @@ const Settings = () => {
const onSave = useCallback(() => {
dispatch(setEnvData({
autoExpand: autoExpandValue,
aiType: aiTypeValue,
apiKey: apiKeyValue,
serverUrl: serverUrlValue,
model: modelValue,
geminiApiKey: geminiApiKeyValue,
translateEnable: translateEnableValue,
language: languageValue,
hideOnDisableAutoTranslate: hideOnDisableAutoTranslateValue,
@@ -112,10 +124,12 @@ const Settings = () => {
fetchAmount: fetchAmountValue,
fontSize: fontSizeValue,
prompts: promptsValue,
searchEnabled: searchEnabledValue,
cnSearchEnabled: cnSearchEnabledValue,
}))
dispatch(setPage(PAGE_MAIN))
toast.success('保存成功')
}, [modelValue, promptsValue, fontSizeValue, apiKeyValue, autoExpandValue, dispatch, fetchAmountValue, hideOnDisableAutoTranslateValue, languageValue, serverUrlValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, themeValue, transDisplayValue, translateEnableValue, wordsValue])
}, [dispatch, aiTypeValue, geminiApiKeyValue, autoExpandValue, apiKeyValue, serverUrlValue, modelValue, translateEnableValue, languageValue, hideOnDisableAutoTranslateValue, themeValue, transDisplayValue, summarizeEnableValue, summarizeFloatValue, summarizeLanguageValue, wordsValue, fetchAmountValue, fontSizeValue, promptsValue, searchEnabledValue, cnSearchEnabledValue])
const onCancel = useCallback(() => {
dispatch(setPage(PAGE_MAIN))
@@ -161,6 +175,14 @@ const Settings = () => {
setFontSizeValue('large')
}, [])
const onSelOpenai = useCallback(() => {
setAiTypeValue('openai')
}, [])
const onSelGemini = useCallback(() => {
setAiTypeValue('gemini')
}, [])
return <div className='text-sm overflow-y-auto' style={{
height: fold?undefined:`${totalHeight-HEADER_HEIGHT}px`,
}}>
@@ -183,8 +205,15 @@ const Settings = () => {
<button onClick={onSelFontSize2} className={classNames('btn btn-xs no-animation', fontSizeValue === 'large'?'btn-active':'')}></button>
</div>
</FormItem>
<FormItem title='AI类型' tip='不同AI质量可能有差异'>
<div className="btn-group">
<button onClick={onSelOpenai} className={classNames('btn btn-xs no-animation', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
<button onClick={onSelGemini} className={classNames('btn btn-xs no-animation', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
</div>
</FormItem>
</Section>
<Section title='openai配置'>
{(!aiTypeValue || aiTypeValue === 'openai') && <Section title='openai配置'>
<FormItem title='ApiKey' htmlFor='apiKey'>
<input id='apiKey' type='text' className='input input-sm input-bordered w-full' placeholder='sk-xxx' value={apiKeyValue} onChange={onChangeApiKeyValue}/>
</FormItem>
@@ -235,10 +264,52 @@ const Settings = () => {
}}/>
</FormItem>)}
</div>}
</Section>
</Section>}
{aiTypeValue === 'gemini' && <Section title='gemini配置'>
<FormItem title='ApiKey' htmlFor='geminiApiKey'>
<input id='geminiApiKey' type='text' className='input input-sm input-bordered w-full' placeholder='xxx'
value={geminiApiKeyValue} onChange={onChangeGeminiApiKeyValue}/>
</FormItem>
<div className='flex justify-center'>
<a className='link text-xs' onClick={toggleMoreFold}>{moreFold ? '点击查看说明' : '点击折叠说明'}</a>
</div>
{!moreFold && <div>
<ul className='pl-3 list-decimal desc text-xs'>
<li><a className='link' href='https://makersuite.google.com/app/apikey' target='_blank'
rel="noreferrer">Google AI Studio</a> ()</li>
</ul>
</div>}
<div className='flex justify-center'>
<a className='link text-xs'
onClick={togglePromptsFold}>{promptsFold ? '点击查看提示词' : '点击折叠提示词'}</a>
</div>
{!promptsFold && <div>
{PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
<div>{item.name}</div>
<div className='link text-xs' onClick={() => {
setPromptsValue({
...promptsValue,
// @ts-expect-error
[item.type]: PROMPT_DEFAULTS[item.type] ?? ''
})
}}>
</div>
</div>} htmlFor={`prompt-${item.type}`}>
<textarea id={`prompt-${item.type}`} className='mt-2 textarea input-bordered w-full'
placeholder='留空使用默认提示词' value={promptsValue[item.type] ?? ''} onChange={(e) => {
setPromptsValue({
...promptsValue,
[item.type]: e.target.value
})
}}/>
</FormItem>)}
</div>}
</Section>}
<Section title={<div className='flex items-center'>
{!apiKeyValue && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/>
</div>}
</div>}>
@@ -273,7 +344,7 @@ const Settings = () => {
</Section>
<Section title={<div className='flex items-center'>
{!apiKeyValue && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/>
</div>}
</div>}>
@@ -300,6 +371,18 @@ const Settings = () => {
</div>
</FormItem>
</Section>
<Section title={<div className='flex items-center'>
</div>}>
<FormItem title='启用搜索' htmlFor='searchEnabled' tip='是否启用字幕搜索功能'>
<input id='searchEnabled' type='checkbox' className='toggle toggle-primary' checked={searchEnabledValue}
onChange={setSearchEnabledValue}/>
</FormItem>
<FormItem title='拼音搜索' htmlFor='cnSearchEnabled' tip='是否启用中文拼音搜索'>
<input id='cnSearchEnabled' type='checkbox' className='toggle toggle-primary' checked={cnSearchEnabledValue}
onChange={setCnSearchEnabledValue}/>
</FormItem>
</Section>
<div className='flex justify-center gap-5'>
<button className='btn btn-primary btn-sm' onClick={onSave}></button>
<button className='btn btn-sm' onClick={onCancel}></button>

View File

@@ -18,3 +18,16 @@ export const handleChatCompleteTask = async (task: Task) => {
throw new Error(`${task.resp.error.code as string??''} ${task.resp.error.message as string ??''}`)
}
}
export const handleGeminiChatCompleteTask = async (task: Task) => {
const data = task.def.data
const resp = await fetch('https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': task.def.extra.geminiApiKey,
},
body: JSON.stringify(data),
})
task.resp = await resp.json()
}

View File

@@ -1,5 +1,5 @@
import {TASK_EXPIRE_TIME} from '../const'
import {handleChatCompleteTask} from './openaiService'
import {handleChatCompleteTask, handleGeminiChatCompleteTask} from './openaiService'
export const tasksMap = new Map<string, Task>()
@@ -11,6 +11,9 @@ export const handleTask = async (task: Task) => {
case 'chatComplete':
await handleChatCompleteTask(task)
break
case 'geminiChatComplete':
await handleGeminiChatCompleteTask(task)
break
default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`任务类型不支持: ${task.def.type}`)

View File

@@ -141,6 +141,7 @@ export const TOTAL_HEIGHT_DEF = 520
export const TOTAL_HEIGHT_MAX = 800
export const HEADER_HEIGHT = 44
export const TITLE_HEIGHT = 24
export const SEARCH_BAR_HEIGHT = 32
export const WORDS_DEFAULT = import.meta.env.VITE_ENV === 'web-dev'?500:2000
export const WORDS_MIN = 500
@@ -157,8 +158,11 @@ export const MODELS = [{
code: 'gpt-3.5-turbo',
name: 'gpt-3.5-turbo',
}, {
code: 'gpt-3.5-turbo-16k',
name: 'gpt-3.5-turbo-16k',
code: 'gpt-3.5-turbo-0125',
name: 'gpt-3.5-turbo-0125',
}, {
code: 'gpt-3.5-turbo-1106',
name: 'gpt-3.5-turbo-1106',
}]
export const MODEL_DEFAULT = MODELS[0].code

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

View File

@@ -14,7 +14,7 @@ import {
setTotalHeight,
} from '../redux/envReducer'
import {EventBusContext} from '../Router'
import {EVENT_EXPAND, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_DEFAULT, WORDS_MAX, WORDS_MIN} from '../const'
import {EVENT_EXPAND, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_DEFAULT, WORDS_MIN} from '../const'
import {useInterval} from 'ahooks'
import {getWholeText} from '../util/biz_util'
@@ -157,7 +157,7 @@ const useSubtitleService = () => {
if (items != null) {
if (envData.summarizeEnable) { // 分段
let size = envData.words??WORDS_DEFAULT
size = Math.min(Math.max(size, WORDS_MIN), WORDS_MAX)
size = Math.max(size, WORDS_MIN)
segments = []
let transcriptItems: TranscriptItem[] = []

View File

@@ -82,23 +82,39 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{subtitles}}', lineStr)
const taskDef: TaskDef = {
type: 'chatComplete',
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
serverUrl: envData.serverUrl,
data: {
model: envData.model??MODEL_DEFAULT,
messages: [
{
role: 'user',
content: prompt,
data: envData.aiType === 'gemini'
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
],
temperature: 0,
n: 1,
stream: false,
},
:{
model: envData.model??MODEL_DEFAULT,
messages: [
{
role: 'user',
content: prompt,
}
],
temperature: 0,
n: 1,
stream: false,
},
extra: {
type: 'translate',
apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
startIdx,
size: lines.length,
}
@@ -117,10 +133,10 @@ const useTranslate = () => {
dispatch(addTaskId(task.id))
}
}
}, [data?.body, dispatch, envData.apiKey, envData.fetchAmount, envData.serverUrl, envData.prompts, title, language.name])
}, [data?.body, envData.fetchAmount, envData.prompts, envData.aiType, envData.serverUrl, envData.model, envData.apiKey, envData.geminiApiKey, language.name, title, dispatch])
const addSummarizeTask = useCallback(async (type: SummaryType, segment: Segment) => {
if (segment.text.length >= SUMMARIZE_THRESHOLD && envData.apiKey) {
if (segment.text.length >= SUMMARIZE_THRESHOLD) {
let subtitles = ''
for (const item of segment.items) {
subtitles += formatTime(item.from) + ' ' + item.content + '\n'
@@ -135,25 +151,41 @@ const useTranslate = () => {
prompt = prompt.replaceAll('{{segment}}', segment.text)
const taskDef: TaskDef = {
type: 'chatComplete',
type: envData.aiType === 'gemini'?'geminiChatComplete':'chatComplete',
serverUrl: envData.serverUrl,
data: {
model: envData.model??MODEL_DEFAULT,
messages: [
{
role: 'user',
content: prompt,
data: envData.aiType === 'gemini'
?{
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
maxOutputTokens: 2048
}
}
],
temperature: 0,
n: 1,
stream: false,
},
:{
model: envData.model??MODEL_DEFAULT,
messages: [
{
role: 'user',
content: prompt,
}
],
temperature: 0,
n: 1,
stream: false,
},
extra: {
type: 'summarize',
summaryType: type,
startIdx: segment.startIdx,
apiKey: envData.apiKey,
geminiApiKey: envData.geminiApiKey,
}
}
console.debug('addSummarizeTask', taskDef)
@@ -162,7 +194,7 @@ const useTranslate = () => {
const task = await chrome.runtime.sendMessage({type: 'addTask', taskDef})
dispatch(addTaskId(task.id))
}
}, [dispatch, envData.apiKey, envData.prompts, envData.serverUrl, summarizeLanguage.name, title])
}, [dispatch, envData.aiType, envData.apiKey, envData.geminiApiKey, envData.model, envData.prompts, envData.serverUrl, summarizeLanguage.name, title])
const handleTranslate = useMemoizedFn((task: Task, content: string) => {
let map: {[key: string]: string} = {}
@@ -221,7 +253,7 @@ const useTranslate = () => {
console.debug('getTask', taskResp.task)
const task: Task = taskResp.task
const taskType: string | undefined = task.def.extra?.type
const content = task.resp?.choices?.[0]?.message?.content?.trim()
const content = envData.aiType === 'gemini'?task.resp?.candidates[0]?.content?.parts[0]?.text?.trim():task.resp?.choices?.[0]?.message?.content?.trim()
if (task.status === 'done') {
// 异常提示
if (task.error) {
@@ -239,7 +271,7 @@ const useTranslate = () => {
} else {
dispatch(delTaskId(taskId))
}
}, [dispatch, handleSummarize, handleTranslate])
}, [dispatch, envData.aiType, handleSummarize, handleTranslate])
return {getFetch, getTask, addTask, addSummarizeTask}
}

View File

@@ -17,7 +17,6 @@ interface EnvState {
autoScroll?: boolean
checkAutoScroll?: boolean
curOffsetTop?: number
compact?: boolean // 是否紧凑视图
floatKeyPointsSegIdx?: number // segment的startIdx
noVideo?: boolean
@@ -25,7 +24,6 @@ interface EnvState {
curIdx?: number // 从0开始
needScroll?: boolean
currentTime?: number
downloadType?: string
infos?: any[]
curInfo?: any
curFetched?: boolean
@@ -35,9 +33,12 @@ interface EnvState {
title?: string
taskIds?: string[]
transResults: {[key: number]: TransResult}
transResults: { [key: number]: TransResult }
lastTransTime?: number
lastSummarizeTime?: number
searchText: string
searchResult: Set<number>
}
const initialState: EnvState = {
@@ -45,19 +46,24 @@ const initialState: EnvState = {
serverUrl: SERVER_URL_OPENAI,
translateEnable: true,
summarizeEnable: true,
autoExpand: true,
theme: 'light',
searchEnabled: true,
},
tempData: {
curSummaryType: 'overview',
},
totalHeight: TOTAL_HEIGHT_DEF,
autoScroll: true,
currentTime: import.meta.env.VITE_ENV === 'web-dev'? 30: undefined,
currentTime: import.meta.env.VITE_ENV === 'web-dev' ? 30 : undefined,
envReady: false,
tempReady: false,
fold: true,
data: import.meta.env.VITE_ENV === 'web-dev'? getDevData(): undefined,
data: import.meta.env.VITE_ENV === 'web-dev' ? getDevData() : undefined,
transResults: {},
searchText: '',
searchResult: new Set(),
}
export const slice = createSlice({
@@ -73,7 +79,7 @@ export const slice = createSlice({
setEnvReady: (state) => {
state.envReady = true
},
setTempData: (state, action: PayloadAction<TempData>) => {
setTempData: (state, action: PayloadAction<Partial<TempData>>) => {
state.tempData = {
...state.tempData,
...action.payload,
@@ -82,15 +88,18 @@ export const slice = createSlice({
setTempReady: (state) => {
state.tempReady = true
},
setSearchText: (state, action: PayloadAction<string>) => {
state.searchText = action.payload
},
setSearchResult: (state, action: PayloadAction<Set<number>>) => {
state.searchResult = action.payload
},
setFloatKeyPointsSegIdx: (state, action: PayloadAction<number | undefined>) => {
state.floatKeyPointsSegIdx = action.payload
},
setFoldAll: (state, action: PayloadAction<boolean>) => {
state.foldAll = action.payload
},
setCompact: (state, action: PayloadAction<boolean>) => {
state.compact = action.payload
},
setPage: (state, action: PayloadAction<string | undefined>) => {
state.page = action.payload
},
@@ -107,12 +116,12 @@ export const slice = createSlice({
state.lastSummarizeTime = action.payload
},
addTaskId: (state, action: PayloadAction<string>) => {
state.taskIds = [...(state.taskIds??[]), action.payload]
state.taskIds = [...(state.taskIds ?? []), action.payload]
},
delTaskId: (state, action: PayloadAction<string>) => {
state.taskIds = state.taskIds?.filter(id => id !== action.payload)
},
addTransResults: (state, action: PayloadAction<{[key: number]: TransResult}>) => {
addTransResults: (state, action: PayloadAction<{ [key: number]: TransResult }>) => {
// 不要覆盖TransResult里code为200的
for (const payloadKey in action.payload) {
const payloadItem = action.payload[payloadKey]
@@ -216,9 +225,6 @@ export const slice = createSlice({
setNoVideo: (state, action: PayloadAction<boolean>) => {
state.noVideo = action.payload
},
setDownloadType: (state, action: PayloadAction<string>) => {
state.downloadType = action.payload
},
setNeedScroll: (state, action: PayloadAction<boolean>) => {
state.needScroll = action.payload
},
@@ -252,6 +258,44 @@ export const slice = createSlice({
},
})
export const { setTempReady, setTempData, setUploadedTranscript, setTotalHeight, setCheckAutoScroll, setCurOffsetTop, setFloatKeyPointsSegIdx, setFoldAll, setCompact, setSegmentFold, setSummaryContent, setSummaryStatus, setSummaryError, setTitle, setSegments, setLastSummarizeTime, setPage, setLastTransTime, clearTransResults, addTransResults, addTaskId, delTaskId, setTaskIds, setDownloadType, setAutoTranslate, setAutoScroll, setNoVideo, setNeedScroll, setCurIdx, setEnvData, setEnvReady, setCurrentTime, setInfos, setCurInfo, setCurFetched, setData, setFold } = slice.actions
export const {
setTempReady,
setTempData,
setUploadedTranscript,
setTotalHeight,
setCheckAutoScroll,
setCurOffsetTop,
setFloatKeyPointsSegIdx,
setFoldAll,
setSegmentFold,
setSummaryContent,
setSummaryStatus,
setSummaryError,
setTitle,
setSegments,
setLastSummarizeTime,
setPage,
setLastTransTime,
clearTransResults,
addTransResults,
addTaskId,
delTaskId,
setTaskIds,
setAutoTranslate,
setAutoScroll,
setNoVideo,
setNeedScroll,
setCurIdx,
setEnvData,
setEnvReady,
setCurrentTime,
setInfos,
setCurInfo,
setCurFetched,
setData,
setFold,
setSearchText,
setSearchResult,
} = slice.actions
export default slice.reducer

14
src/typings.d.ts vendored
View File

@@ -1,9 +1,15 @@
interface EnvData {
autoExpand?: boolean
flagDot?: boolean
aiType?: 'openai' | 'gemini'
// openai
apiKey?: string
serverUrl?: string
model?: string
// gemini
geminiApiKey?: string
translateEnable?: boolean
language?: string
hideOnDisableAutoTranslate?: boolean
@@ -16,6 +22,10 @@ interface EnvData {
theme?: 'system' | 'light' | 'dark'
fontSize?: 'normal' | 'large'
// search
searchEnabled?: boolean
cnSearchEnabled?: boolean
prompts?: {
[key: string]: string
}
@@ -23,10 +33,12 @@ interface EnvData {
interface TempData {
curSummaryType: SummaryType
downloadType?: string
compact?: boolean // 是否紧凑视图
}
interface TaskDef {
type: 'chatComplete'
type: 'chatComplete' | 'geminiChatComplete'
serverUrl?: string
data: any
extra?: any

View File

@@ -253,7 +253,15 @@ export const extractJsonObject = (content: string) => {
const start = content.indexOf('```')
const end = content.lastIndexOf('```')
if (start >= 0 && end >= 0) {
content = content.slice(start + 3, end)
if (start === end) { // 异常情况
if (content.startsWith('```')) {
content = content.slice(3)
} else {
content = content.slice(0, -3)
}
} else {
content = content.slice(start + 3, end)
}
}
// get content between { and }
const start2 = content.indexOf('{')
@@ -269,7 +277,15 @@ export const extractJsonArray = (content: string) => {
const start = content.indexOf('```')
const end = content.lastIndexOf('```')
if (start >= 0 && end >= 0) {
content = content.slice(start + 3, end)
if (start === end) { // 异常情况
if (content.startsWith('```')) {
content = content.slice(3)
} else {
content = content.slice(0, -3)
}
} else {
content = content.slice(start + 3, end)
}
}
// get content between [ and ]
const start3 = content.indexOf('[')

125
src/util/pinyin_util.ts Normal file
View File

@@ -0,0 +1,125 @@
import pinyin from 'tiny-pinyin'
import {uniq} from 'lodash-es'
/**
* pinyin的返回结果
*/
interface Ret {
type: 1 | 2 | 3
source: string
target: string
}
interface Phase {
pinyin: boolean
list: Ret[]
}
/**
* 获取Phase列表(中英文分离列表)
*/
export const getPhases = (str: string) => {
const rets = pinyin.parse(str)
const phases: Phase[] = []
let curPinyin_ = false
let curPhase_: Ret[] = []
const addCurrentPhase = () => {
if (curPhase_.length > 0) {
phases.push({
pinyin: curPinyin_,
list: curPhase_,
})
}
}
// 遍历rets
for (const ret of rets) {
const newPinyin = ret.type === 2
// 如果跟旧的pinyin类型不同先保存旧的
if (newPinyin !== curPinyin_) {
addCurrentPhase()
// 重置
curPinyin_ = newPinyin
curPhase_ = []
}
// 添加新的
curPhase_.push(ret)
}
// 最后一个
addCurrentPhase()
return phases
}
/**
* 获取原子字符列表,如 tool tab 汉 字
*/
export const getAtoms = (str: string) => {
const phases = getPhases(str)
const atoms = []
for (const phase of phases) {
if (phase.pinyin) { // all words
atoms.push(...phase.list.map(e => e.source).filter(e => e))
} else { // split
atoms.push(...(phase.list.map((e: any) => e.source).join('').match(/\w+/g)??[]).filter((e: string) => e))
}
}
return atoms
}
const fixStrs = (atoms: string[]) => {
// 小写
atoms = atoms.map(e => e.toLowerCase())
// 去重
atoms = uniq(atoms)
// 返回
return atoms
}
export const getWords = (str: string) => {
// 获取全部原子字符
const atoms = getAtoms(str)
// fix
return fixStrs(atoms)
}
/**
* 我的世界Minecraft => ['wodeshijie', 'deshijie', 'shijie', 'jie'] + ['wdsj', 'dsj', 'sj', 'j']
*
* 1. only handle pinyin, other is ignored
*/
export const getWordsPinyin = (str: string) => {
let result: string[] = []
for (const phase of getPhases(str)) {
// only handle pinyin
if (phase.pinyin) { // 我的世界
// 获取全部原子字符
// 我的世界 => [我, 的, 世, 界]
const atoms: string[] = []
atoms.push(...phase.list.map(e => e.source).filter(e => e))
// 获取全部子串
// [我, 的, 世, 界] => [我的世界, 的世界, 世界, 界]
const allSubStr = []
for (let i = 0; i < atoms.length; i++) {
allSubStr.push(atoms.slice(i).join(''))
}
// pinyin version
const pinyinList = allSubStr.map((e: string) => pinyin.convertToPinyin(e))
result.push(...pinyinList)
// pinyin first version
const pinyinFirstList = allSubStr.map((e: string) => pinyin.parse(e).map((e: any) => e.type === 2?e.target[0]:null).filter(e => !!e).join(''))
result.push(...pinyinFirstList)
}
}
// fix
result = fixStrs(result)
return result
}

65
src/util/search.ts Normal file
View File

@@ -0,0 +1,65 @@
import * as JsSearch from 'js-search'
import {uniq} from 'lodash-es'
import {getWords, getWordsPinyin} from './pinyin_util'
const tokenize = (maxLength: number, content: string, options?: SearchOptions) => {
const result: string[] = []
// 最大长度
if (content.length > maxLength) {
content = content.substring(0, maxLength)
}
result.push(...getWords(content))
// check cn
if (options?.cnSearchEnabled) {
result.push(...getWordsPinyin(content))
}
// console.debug('[Search] tokenize:', str, '=>', result)
return uniq(result)
}
export interface SearchOptions {
cnSearchEnabled?: boolean
}
export const Search = (uidFieldName: string, index: string, maxLength: number, options?: SearchOptions) => {
let searchRef: JsSearch.Search | undefined// 搜索器
/**
* 重置索引
*/
const reset = (documents?: Object[]) => {
// 搜索器
searchRef = new JsSearch.Search(uidFieldName)
searchRef.tokenizer = {
tokenize: (str) => {
return tokenize(maxLength, str, options)
}
}
searchRef.addIndex(index)
// 检测添加文档
if (documents != null) {
searchRef.addDocuments(documents)
}
}
/**
* 添加文档
*/
const add = (document: Object) => {
searchRef?.addDocument(document)
}
/**
* 搜索
* @return 未去重
*/
const search = (text: string) => {
return searchRef?.search(text.toLowerCase())
}
return {reset, add, search}
}

View File

@@ -18,11 +18,13 @@ module.exports = {
light: {
...require("daisyui/src/colors/themes")["[data-theme=light]"],
"--rounded-btn": "0.15rem",
"primary": "rgb(0, 174, 236)",
},
}, {
dark: {
...require("daisyui/src/colors/themes")["[data-theme=dark]"],
"--rounded-btn": "0.15rem",
"primary": "rgb(0, 174, 236)",
}
}],
base: true,

View File

@@ -0,0 +1,66 @@
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { visualizer } from "rollup-plugin-visualizer";
import { crx } from "@crxjs/vite-plugin";
// manifest.json
var manifest_default = {
name: "\u54D4\u54E9\u54D4\u54E9\u5B57\u5E55\u5217\u8868",
description: "\u663E\u793AB\u7AD9\u89C6\u9891\u7684\u5B57\u5E55\u5217\u8868,\u53EF\u70B9\u51FB\u8DF3\u8F6C\u4E0E\u4E0B\u8F7D\u5B57\u5E55,\u5E76\u652F\u6301\u7FFB\u8BD1\u548C\u603B\u7ED3\u5B57\u5E55!",
version: "1.7.11",
manifest_version: 3,
permissions: [
"storage"
],
background: {
service_worker: "src/chrome/background.ts"
},
content_scripts: [
{
matches: ["https://www.bilibili.com/video/*", "https://www.bilibili.com/list/*"],
js: ["src/chrome/content-script.cjs"]
}
],
icons: {
"16": "favicon-16x16.png",
"32": "favicon-32x32.png",
"48": "favicon-48x48.png",
"128": "favicon-128x128.png"
},
action: {
default_popup: "index.html",
default_icon: {
"16": "favicon-16x16.png",
"32": "favicon-32x32.png",
"48": "favicon-48x48.png",
"128": "favicon-128x128.png"
}
}
};
// vite.config.ts
var vite_config_default = ({ mode }) => {
const plugins = [
react(),
visualizer()
];
if (mode === "production_chrome") {
plugins.push(crx({
manifest: manifest_default
}));
}
return defineConfig({
base: "/",
plugins,
css: {
modules: {
localsConvention: "camelCase"
}
}
});
};
export {
vite_config_default as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvZmVuZ3l1ZXhpYW5nL2RhdGEvcHJvamVjdC9iaWxpYmlsaS1zdWJ0aXRsZVwiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9maWxlbmFtZSA9IFwiL1VzZXJzL2Zlbmd5dWV4aWFuZy9kYXRhL3Byb2plY3QvYmlsaWJpbGktc3VidGl0bGUvdml0ZS5jb25maWcudHNcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfaW1wb3J0X21ldGFfdXJsID0gXCJmaWxlOi8vL1VzZXJzL2Zlbmd5dWV4aWFuZy9kYXRhL3Byb2plY3QvYmlsaWJpbGktc3VidGl0bGUvdml0ZS5jb25maWcudHNcIjtpbXBvcnQge2RlZmluZUNvbmZpZywgUGx1Z2luT3B0aW9ufSBmcm9tICd2aXRlJ1xuaW1wb3J0IHJlYWN0IGZyb20gJ0B2aXRlanMvcGx1Z2luLXJlYWN0J1xuaW1wb3J0IHt2aXN1YWxpemVyfSBmcm9tIFwicm9sbHVwLXBsdWdpbi12aXN1YWxpemVyXCI7XG5pbXBvcnQge2NyeH0gZnJvbSAnQGNyeGpzL3ZpdGUtcGx1Z2luJ1xuLy8gQHRzLWlnbm9yZVxuaW1wb3J0IG1hbmlmZXN0IGZyb20gJy4vbWFuaWZlc3QuanNvbidcblxuLy8gaHR0cHM6Ly92aXRlanMuZGV2L2NvbmZpZy9cbmV4cG9ydCBkZWZhdWx0ICh7bW9kZX0pID0+IHtcbiAgY29uc3QgcGx1Z2lucyA9IFtcbiAgICByZWFjdCgpLFxuICAgIHZpc3VhbGl6ZXIoKSBhcyBQbHVnaW5PcHRpb24sXG4gIF1cbiAgLy8gQHRzLWlnbm9yZVxuICBpZiAobW9kZSA9PT0gJ3Byb2R1Y3Rpb25fY2hyb21lJykge1xuICAgIHBsdWdpbnMucHVzaChjcngoe1xuICAgICAgbWFuaWZlc3QsXG4gICAgfSkpXG4gIH1cbiAgcmV0dXJuIGRlZmluZUNvbmZpZyh7XG4gICAgYmFzZTogJy8nLFxuICAgIHBsdWdpbnMsXG4gICAgY3NzOiB7XG4gICAgICBtb2R1bGVzOiB7XG4gICAgICAgIGxvY2Fsc0NvbnZlbnRpb246IFwiY2FtZWxDYXNlXCJcbiAgICAgIH1cbiAgICB9XG4gIH0pXG59XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQXdVLFNBQVEsb0JBQWlDO0FBQ2pYLE9BQU8sV0FBVztBQUNsQixTQUFRLGtCQUFpQjtBQUN6QixTQUFRLFdBQVU7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBS2xCLElBQU8sc0JBQVEsQ0FBQyxFQUFDLEtBQUksTUFBTTtBQUN6QixRQUFNLFVBQVU7QUFBQSxJQUNkLE1BQU07QUFBQSxJQUNOLFdBQVc7QUFBQSxFQUNiO0FBRUEsTUFBSSxTQUFTLHFCQUFxQjtBQUNoQyxZQUFRLEtBQUssSUFBSTtBQUFBLE1BQ2Y7QUFBQSxJQUNGLENBQUMsQ0FBQztBQUFBLEVBQ0o7QUFDQSxTQUFPLGFBQWE7QUFBQSxJQUNsQixNQUFNO0FBQUEsSUFDTjtBQUFBLElBQ0EsS0FBSztBQUFBLE1BQ0gsU0FBUztBQUFBLFFBQ1Asa0JBQWtCO0FBQUEsTUFDcEI7QUFBQSxJQUNGO0FBQUEsRUFDRixDQUFDO0FBQ0g7IiwKICAibmFtZXMiOiBbXQp9Cg==