20 Commits

Author SHA1 Message Date
IndieKKY
44895a98a6 chore: release 1.11.2 2024-10-07 18:59:16 +08:00
IndieKKY
53d3522fd6 完善 2024-10-07 18:56:39 +08:00
IndieKKY
56bb936aaa 哔哔君 2024-10-07 18:15:20 +08:00
IndieKKY
d52a4e8378 fix 2024-10-07 09:43:38 +08:00
IndieKKY
f69bc7f040 优化 2024-10-07 09:36:48 +08:00
IndieKKY
5005806917 chore: release 1.11.1 2024-10-06 19:55:04 +08:00
IndieKKY
6928b5fa00 fix 2024-10-06 19:54:40 +08:00
IndieKKY
5ba2b9fd6d 优化 2024-10-06 19:22:01 +08:00
IndieKKY
d11b517d5e 优化 2024-10-06 19:18:42 +08:00
IndieKKY
2460b0b822 优化 2024-10-06 19:16:22 +08:00
IndieKKY
9bcf6ee48d 优化 2024-10-06 18:59:21 +08:00
IndieKKY
2bb5f41189 优化 2024-10-06 18:55:41 +08:00
IndieKKY
e5a645611b 优化 2024-10-06 18:48:52 +08:00
IndieKKY
97bd23bcc0 优化 2024-10-06 18:42:27 +08:00
IndieKKY
02aaba6a83 优化 2024-10-06 18:41:12 +08:00
IndieKKY
3e1e69f13e 优化 2024-10-06 18:36:23 +08:00
IndieKKY
9384c1419a 优化 2024-10-06 18:28:20 +08:00
IndieKKY
50e6579116 fix 2024-10-06 17:51:07 +08:00
IndieKKY
751961687b tmp 2024-10-06 17:42:15 +08:00
IndieKKY
5ce146803e 优化 2024-10-06 16:04:02 +08:00
43 changed files with 307 additions and 259 deletions

View File

@@ -65,7 +65,3 @@ node版本18.15.0
## 许可证
该项目采用 **MIT 许可证**,详情请参阅许可证文件。
## 截图
![完整截图](./screenshot/完整截图.png)

View File

@@ -1,7 +1,7 @@
<!DOCTYPE html>
<html lang="zh" data-theme="light">
<head>
<title>bilibili-subtitle - 哔哩哔哩字幕</title>
<title>哔哔君 - 哔哩哔哩字幕列表</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="icon" href="/favicon-128x128.png" sizes="128x128">

View File

@@ -12,7 +12,7 @@ const [major, minor, patch, label = '0'] = version
.split(/[.-]/)
export default defineManifest(async (env) => ({
"name": "哔哩哔哩字幕列表",
"name": "哔哔君 - 哔哩哔哩字幕列表",
"description": "显示B站视频的字幕列表,可点击跳转与下载字幕,并支持翻译和总结字幕!",
"version": `${major}.${minor}.${patch}`,
"manifest_version": 3,

View File

@@ -1,7 +1,7 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<title>哔哩哔哩字幕列表选项</title>
<title>哔君 - 哔哩哔哩字幕列表选项</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="icon" href="/favicon-16x16.png" sizes="16x16">

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "bilibili-subtitle",
"version": "1.11.0",
"version": "1.11.2",
"type": "module",
"description": "哔哩哔哩字幕列表",
"main": "index.js",

View File

@@ -1,11 +0,0 @@
<!DOCTYPE html>
<html lang="zh" style="width: 500px;">
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<img src="shot.jpg" style="width: 100%; object-fit: contain;"/>
</body>
</html>

BIN
public/bibijun.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 B

After

Width:  |  Height:  |  Size: 651 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 B

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 400 B

After

Width:  |  Height:  |  Size: 2.4 KiB

BIN
public/favicon-64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 B

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

View File

@@ -1,3 +0,0 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg t="1672795365953" class="icon" viewBox="0 0 1303 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2585"
width="254.4921875" height="200"><path d="M110.964364 1023.720727c-60.509091 0-109.847273-48.872727-109.847273-108.916363V109.009455C1.117091 48.965818 50.455273 0 110.964364 0h1081.902545c60.509091 0 109.847273 48.872727 109.847273 108.916364v805.794909c0 60.043636-49.338182 108.916364-109.847273 108.916363H110.964364z m0-927.650909c-6.609455 0-12.101818 5.771636-12.101819 12.939637v805.794909c0 7.168 5.492364 13.032727 12.101819 13.032727h1081.902545c6.609455 0 12.101818-5.864727 12.101818-13.032727V109.009455c0-7.168-5.492364-13.032727-12.101818-13.032728H110.964364z" fill="#00AEEC" p-id="2586"></path><path d="M1003.054545 520.098909a51.572364 51.572364 0 0 1-50.26909 52.689455h-80.058182a51.572364 51.572364 0 0 1-50.269091-52.689455c0-29.137455 22.434909-52.782545 50.269091-52.782545h80.058182c27.834182 0 50.269091 23.645091 50.26909 52.782545zM1096.610909 270.149818c0 28.858182-22.341818 52.410182-49.989818 52.410182H232.541091a51.293091 51.293091 0 0 1-50.082909-52.410182c0-29.044364 22.434909-52.503273 50.082909-52.503273h814.08c27.648 0 50.082909 23.458909 50.082909 52.503273zM768.744727 520.098909c0 28.858182-22.341818 52.410182-50.082909 52.410182H232.541091a51.293091 51.293091 0 0 1-50.082909-52.410182c0-29.044364 22.434909-52.503273 50.082909-52.503273H718.661818c27.648 0 50.082909 23.458909 50.082909 52.503273zM1096.610909 735.976727c0 29.044364-22.341818 52.503273-49.989818 52.503273H560.500364a51.293091 51.293091 0 0 1-50.082909-52.503273c0-28.951273 22.341818-52.410182 50.082909-52.410182h486.120727c27.648 0 50.082909 23.458909 50.082909 52.410182z" fill="#00AEEC" p-id="2587"></path></svg>

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 867 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 333 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 413 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 280 KiB

View File

@@ -1,7 +1,7 @@
<!DOCTYPE html>
<html lang="zh" data-theme="light">
<head>
<title>哔哩哔哩字幕列表</title>
<title>哔君 - 哔哩哔哩字幕列表</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="icon" href="/favicon-128x128.png" sizes="128x128">

View File

@@ -1,6 +1,6 @@
import {v4} from 'uuid'
import {handleTask, initTaskService, tasksMap} from './taskService'
import { MESSAGE_TO_EXTENSION_ADD_TASK, MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL, MESSAGE_TO_EXTENSION_GET_TASK, MESSAGE_TO_EXTENSION_SHOW_FLAG, MESSAGE_TO_INJECT_TOGGLE_DISPLAY, STORAGE_ENV} from '@/consts/const'
import { STORAGE_ENV} from '@/consts/const'
import ExtensionMessaging from '@/messaging/layer2/ExtensionMessaging'
import { TAG_TARGET_INJECT } from '@/messaging/const'
@@ -29,12 +29,12 @@ const closeSidePanel = async () => {
}
const methods: {
[key: string]: (params: any, context: MethodContext) => Promise<any>
[K in AllExtensionMessages['method']]: (params: Extract<AllExtensionMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
} = {
[MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL]: async (params, context) => {
CLOSE_SIDE_PANEL: async (params, context) => {
closeSidePanel()
},
[MESSAGE_TO_EXTENSION_ADD_TASK]: async (params, context) => {
ADD_TASK: async (params, context) => {
// 新建任务
const task: Task = {
id: v4(),
@@ -49,7 +49,7 @@ const methods: {
return task
},
[MESSAGE_TO_EXTENSION_GET_TASK]: async (params, context) => {
GET_TASK: async (params, context) => {
// 返回任务信息
const taskId = params.taskId
const task = tasksMap.get(taskId)
@@ -70,7 +70,7 @@ const methods: {
task,
}
},
[MESSAGE_TO_EXTENSION_SHOW_FLAG]: async (params, context) => {
SHOW_FLAG: async (params, context) => {
await setBadgeOk(context.tabId!, params.show)
},
}
@@ -78,7 +78,7 @@ const methods: {
const extensionMessaging = new ExtensionMessaging()
extensionMessaging.init(methods)
chrome.runtime.onMessage.addListener((event: MessageData, sender: chrome.runtime.MessageSender, sendResponse: (result: any) => void) => {
chrome.runtime.onMessage.addListener((event: any, sender: chrome.runtime.MessageSender, sendResponse: (result: any) => void) => {
// debug((sender.tab != null) ? `tab ${sender.tab.url ?? ''} => ` : 'extension => ', event)
// legacy
@@ -115,7 +115,7 @@ chrome.action.onClicked.addListener(async (tab) => {
})
} else {
closeSidePanel()
extensionMessaging.broadcastMessageExact([tab.id!], [TAG_TARGET_INJECT], MESSAGE_TO_INJECT_TOGGLE_DISPLAY).catch(console.error)
extensionMessaging.broadcastMessageExact([tab.id!], [TAG_TARGET_INJECT], 'TOGGLE_DISPLAY').catch(console.error)
}
})
})

View File

@@ -83,7 +83,8 @@ const Header = (props: {
}
}}>
<div className='shrink-0 flex items-center'>
<span className='shrink-0 text-[15px] font-medium pl-[16px] pr-[14px]'></span>
<img src="bibijun.png" alt="Logo" className="w-auto h-6 ml-2 mr-1" />
{/* <span className='shrink-0 text-[15px] font-medium pl-1 pr-[14px]'>字幕列表</span> */}
<MoreBtn placement={'right-start'}/>
</div>
<div className='flex gap-0.5 items-center mr-[16px]'>

View File

@@ -13,12 +13,12 @@ import {Placement} from '@popperjs/core/lib/enums'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {setEnvData, setTempData} from '../redux/envReducer'
import {EventBusContext} from '../Router'
import {EVENT_EXPAND, MESSAGE_TO_INJECT_DOWNLOAD_AUDIO} from '../consts/const'
import {EVENT_EXPAND} from '../consts/const'
import {formatSrtTime, formatTime, formatVttTime} from '../utils/util'
import {downloadText, openUrl} from '@kky002/kky-util'
import toast from 'react-hot-toast'
import {getSummarize} from '../utils/bizUtil'
import useMessage from '../messaging/layer2/useMessaging'
import { useMessage } from '@/hooks/message'
interface Props {
placement: Placement
}
@@ -162,7 +162,7 @@ const MoreBtn = (props: Props) => {
}, [curSummaryType, data, downloadType, segments, title, url])
const downloadAudioCallback = useCallback(() => {
sendInject(MESSAGE_TO_INJECT_DOWNLOAD_AUDIO, {})
sendInject('DOWNLOAD_AUDIO', {})
}, [])
const selectCallback = useCallback((e: any) => {

View File

@@ -1,27 +1,3 @@
export const MESSAGE_TARGET_EXTENSION = 'BilibiliExtension'
export const MESSAGE_TARGET_INJECT = 'BilibiliInject'
export const MESSAGE_TARGET_APP = 'BilibiliAPP'
export const MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL = 'closeSidePanel'
export const MESSAGE_TO_EXTENSION_ADD_TASK = 'addTask'
export const MESSAGE_TO_EXTENSION_GET_TASK = 'getTask'
export const MESSAGE_TO_EXTENSION_SHOW_FLAG = 'showFlag'
export const MESSAGE_TO_INJECT_TOGGLE_DISPLAY = 'toggleDisplay'
export const MESSAGE_TO_INJECT_FOLD = 'fold'
export const MESSAGE_TO_INJECT_MOVE = 'move'
export const MESSAGE_TO_INJECT_PLAY = 'play'
export const MESSAGE_TO_INJECT_DOWNLOAD_AUDIO = 'downloadAudio'
export const MESSAGE_TO_INJECT_GET_VIDEO_STATUS = 'getVideoStatus'
export const MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO = 'getVideoElementInfo'
export const MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO = 'refreshVideoInfo'
export const MESSAGE_TO_INJECT_UPDATETRANSRESULT = 'updateTransResult'
export const MESSAGE_TO_INJECT_HIDE_TRANS = 'hideTrans'
export const MESSAGE_TO_INJECT_GET_SUBTITLE = 'getSubtitle'
export const MESSAGE_TO_APP_SET_INFOS = 'setInfos'
export const MESSAGE_TO_APP_SET_VIDEO_INFO = 'setVideoInfo'
export const EVENT_EXPAND = 'expand'
export const APP_DOM_ID = 'bilibili-subtitle'

3
src/hooks/message.ts Normal file
View File

@@ -0,0 +1,3 @@
import useMessaging from "@/messaging/layer2/useMessaging";
export const useMessage = useMessaging<AllExtensionMessages, AllInjectMessages>

View File

@@ -1,7 +1,6 @@
import { setCurFetched, setCurInfo, setData, setInfos, setTitle, setUrl } from '@/redux/envReducer'
import { useMemo } from 'react'
import { useAppDispatch } from './redux'
import { MESSAGE_TO_APP_SET_INFOS, MESSAGE_TO_APP_SET_VIDEO_INFO } from '@/consts/const'
import useMessagingService from '@/messaging/layer2/useMessagingService'
const useMessageService = () => {
@@ -9,15 +8,15 @@ const useMessageService = () => {
//methods
const methods: {
[key: string]: (params: any, context: MethodContext) => Promise<any>
[K in AllAPPMessages['method']]: (params: Extract<AllAPPMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
} = useMemo(() => ({
[MESSAGE_TO_APP_SET_INFOS]: async (params: any, context: MethodContext) => {
SET_INFOS: async (params, context: MethodContext) => {
dispatch(setInfos(params.infos))
dispatch(setCurInfo(undefined))
dispatch(setCurFetched(false))
dispatch(setData(undefined))
},
[MESSAGE_TO_APP_SET_VIDEO_INFO]: async (params: any, context: MethodContext) => {
SET_VIDEO_INFO: async (params, context: MethodContext) => {
dispatch(setInfos(params.infos))
dispatch(setUrl(params.url))
dispatch(setTitle(params.title))

View File

@@ -1,8 +1,7 @@
import {useAppDispatch, useAppSelector} from './redux'
import React, {useCallback} from 'react'
import {setNeedScroll, setReviewAction, setTempData} from '../redux/envReducer'
import {MESSAGE_TO_INJECT_MOVE} from '../consts/const'
import useMessage from '../messaging/layer2/useMessaging'
import { useMessage } from './message'
const useSubtitle = () => {
const dispatch = useAppDispatch()
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
@@ -11,7 +10,7 @@ const useSubtitle = () => {
const {sendInject} = useMessage()
const move = useCallback((time: number, togglePause: boolean) => {
sendInject(MESSAGE_TO_INJECT_MOVE, {time, togglePause})
sendInject('MOVE', {time, togglePause})
//review action
if (reviewed === undefined && !reviewAction) {

View File

@@ -16,11 +16,10 @@ import {
setTempData,
} from '../redux/envReducer'
import {EventBusContext} from '../Router'
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE, MESSAGE_TO_INJECT_GET_VIDEO_STATUS, MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO, MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO, MESSAGE_TO_INJECT_HIDE_TRANS, MESSAGE_TO_INJECT_UPDATETRANSRESULT, TOTAL_HEIGHT_DEF} from '../consts/const'
import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_MIN, WORDS_RATE} from '../consts/const'
import {useAsyncEffect, useInterval} from 'ahooks'
import {getModelMaxTokens, getWholeText} from '../utils/bizUtil'
import {MESSAGE_TO_INJECT_GET_SUBTITLE} from '../consts/const'
import useMessage from '../messaging/layer2/useMessaging'
import { useMessage } from './message'
/**
* Service是单例类似后端的服务概念
@@ -79,7 +78,7 @@ const useSubtitleService = () => {
// 获取
useEffect(() => {
if (curInfo && !curFetched) {
sendInject(MESSAGE_TO_INJECT_GET_SUBTITLE, {info: curInfo}).then(data => {
sendInject('GET_SUBTITLE', {info: curInfo}).then(data => {
data?.body?.forEach((item: TranscriptItem, idx: number) => {
item.idx = idx
})
@@ -94,9 +93,12 @@ const useSubtitleService = () => {
useAsyncEffect(async () => {
// 初始获取列表
sendInject(MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO, {force: true})
// 初始获取设置信息
sendInject(MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO, {}).then(info => {
sendInject('REFRESH_VIDEO_INFO', {force: true})
}, [])
useAsyncEffect(async () => {
// 更新设置信息
sendInject('GET_VIDEO_ELEMENT_INFO', {}).then(info => {
dispatch(setNoVideo(info.noVideo))
if (envData.sidePanel) {
// get screen height
@@ -105,7 +107,7 @@ const useSubtitleService = () => {
dispatch(setTotalHeight(Math.min(Math.max(info.totalHeight, TOTAL_HEIGHT_MIN), TOTAL_HEIGHT_MAX)))
}
})
}, [envData.sidePanel])
}, [envData.sidePanel, infos])
// 更新当前位置
useEffect(() => {
@@ -192,7 +194,7 @@ const useSubtitleService = () => {
// 每0.5秒更新当前视频时间
useInterval(() => {
sendInject(MESSAGE_TO_INJECT_GET_VIDEO_STATUS, {}).then(status => {
sendInject('GET_VIDEO_STATUS', {}).then(status => {
dispatch(setCurrentTime(status.currentTime))
})
}, 500)
@@ -200,15 +202,15 @@ const useSubtitleService = () => {
// show translated text in the video
useEffect(() => {
if (hideOnDisableAutoTranslate && !autoTranslate) {
sendInject(MESSAGE_TO_INJECT_HIDE_TRANS, {})
sendInject('HIDE_TRANS', {})
return
}
const transResult = curIdx?transResults[curIdx]:undefined
if (transResult?.code === '200' && transResult.data) {
sendInject(MESSAGE_TO_INJECT_UPDATETRANSRESULT, {result: transResult.data})
sendInject('UPDATE_TRANS_RESULT', {result: transResult.data})
} else {
sendInject(MESSAGE_TO_INJECT_HIDE_TRANS, {})
sendInject('HIDE_TRANS', {})
}
}, [autoTranslate, curIdx, hideOnDisableAutoTranslate, transResults])
}

View File

@@ -16,8 +16,6 @@ import {
import {
LANGUAGE_DEFAULT,
LANGUAGES_MAP,
MESSAGE_TO_EXTENSION_ADD_TASK,
MESSAGE_TO_EXTENSION_GET_TASK,
PROMPT_DEFAULTS,
PROMPT_TYPE_ASK,
PROMPT_TYPE_TRANSLATE,
@@ -31,7 +29,7 @@ import toast from 'react-hot-toast'
import {useMemoizedFn} from 'ahooks/es'
import {extractJsonArray, extractJsonObject, getModel} from '../utils/bizUtil'
import {formatTime} from '../utils/util'
import useMessaging from '@/messaging/layer2/useMessaging'
import { useMessage } from './message'
const useTranslate = () => {
const dispatch = useAppDispatch()
const data = useAppSelector(state => state.env.data)
@@ -45,7 +43,7 @@ const useTranslate = () => {
const reviewed = useAppSelector(state => state.env.tempData.reviewed)
const reviewAction = useAppSelector(state => state.env.reviewAction)
const reviewActions = useAppSelector(state => state.env.tempData.reviewActions)
const {sendExtension} = useMessaging()
const {sendExtension} = useMessage()
/**
* 获取下一个需要翻译的行
* 会检测冷却
@@ -137,7 +135,7 @@ const useTranslate = () => {
}
})
dispatch(addTransResults(result))
const task = await sendExtension(MESSAGE_TO_EXTENSION_ADD_TASK, {taskDef})
const task = await sendExtension('ADD_TASK', {taskDef})
dispatch(addTaskId(task.id))
}
}
@@ -207,7 +205,7 @@ const useTranslate = () => {
console.debug('addSummarizeTask', taskDef)
dispatch(setSummaryStatus({segmentStartIdx: segment.startIdx, type, status: 'pending'}))
dispatch(setLastSummarizeTime(Date.now()))
const task = await sendExtension(MESSAGE_TO_EXTENSION_ADD_TASK, {taskDef})
const task = await sendExtension('ADD_TASK', {taskDef})
dispatch(addTaskId(task.id))
}
}, [dispatch, envData, summarizeLanguage.name, title])
@@ -264,7 +262,7 @@ const useTranslate = () => {
id,
status: 'pending'
}))
const task = await sendExtension(MESSAGE_TO_EXTENSION_ADD_TASK, {taskDef})
const task = await sendExtension('ADD_TASK', {taskDef})
dispatch(addTaskId(task.id))
}
}, [dispatch, envData, summarizeLanguage.name, title])
@@ -332,7 +330,7 @@ const useTranslate = () => {
})
const getTask = useCallback(async (taskId: string) => {
const taskResp = await sendExtension(MESSAGE_TO_EXTENSION_GET_TASK, {taskId})
const taskResp = await sendExtension('GET_TASK', {taskId})
if (taskResp.code === 'ok') {
console.debug('getTask', taskResp.task)
const task: Task = taskResp.task

View File

@@ -1,5 +1,4 @@
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, MESSAGE_TO_INJECT_DOWNLOAD_AUDIO, MESSAGE_TARGET_INJECT, MESSAGE_TO_APP_SET_INFOS, MESSAGE_TO_INJECT_TOGGLE_DISPLAY, STORAGE_ENV, MESSAGE_TO_EXTENSION_SHOW_FLAG } from '@/consts/const'
import { MESSAGE_TO_INJECT_FOLD, MESSAGE_TO_INJECT_MOVE, MESSAGE_TO_APP_SET_VIDEO_INFO, MESSAGE_TO_INJECT_GET_SUBTITLE, MESSAGE_TO_INJECT_GET_VIDEO_STATUS, MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO, MESSAGE_TO_INJECT_UPDATETRANSRESULT, MESSAGE_TO_INJECT_PLAY, MESSAGE_TO_INJECT_HIDE_TRANS, MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO } from '@/consts/const'
import { TOTAL_HEIGHT_DEF, HEADER_HEIGHT, TOTAL_HEIGHT_MIN, TOTAL_HEIGHT_MAX, IFRAME_ID, STORAGE_ENV } from '@/consts/const'
import InjectMessaging from '@/messaging/layer2/InjectMessaging'
const debug = (...args: any[]) => {
@@ -30,7 +29,7 @@ const debug = (...args: any[]) => {
}
const runtime: {
injectMessaging: InjectMessaging
injectMessaging: InjectMessaging<AllExtensionMessages, AllInjectMessages, AllAPPMessages>
// lastV?: string | null
// lastVideoInfo?: VideoInfo
@@ -98,7 +97,7 @@ const debug = (...args: any[]) => {
danmukuBox?.insertBefore(iframe, danmukuBox?.firstChild)
// show badge
runtime.injectMessaging.sendExtension(MESSAGE_TO_EXTENSION_SHOW_FLAG, {
runtime.injectMessaging.sendExtension('SHOW_FLAG', {
show: true
})
@@ -188,7 +187,7 @@ const debug = (...args: any[]) => {
debug('refreshVideoInfo: ', aid, cid, pages, subtitles)
//send setVideoInfo
runtime.injectMessaging.sendApp(MESSAGE_TO_APP_SET_VIDEO_INFO, {
runtime.injectMessaging.sendApp('SET_VIDEO_INFO', {
url: location.origin + location.pathname,
title,
aid,
@@ -225,7 +224,7 @@ const debug = (...args: any[]) => {
.then(res => res.json())
.then(res => {
// console.log('refreshSubtitles: ', aid, cid, res)
runtime.injectMessaging.sendApp(MESSAGE_TO_APP_SET_INFOS, {
runtime.injectMessaging.sendApp('SET_INFOS', {
infos: res.data.subtitle.subtitles
})
})
@@ -241,24 +240,24 @@ const debug = (...args: any[]) => {
}
const methods: {
[key: string]: (params: any, context: MethodContext) => Promise<any>
[K in AllInjectMessages['method']]: (params: Extract<AllInjectMessages, { method: K }>['params'], context: MethodContext) => Promise<any>
} = {
[MESSAGE_TO_INJECT_TOGGLE_DISPLAY]: async (params) => {
TOGGLE_DISPLAY: async (params) => {
const iframe = document.getElementById(IFRAME_ID) as HTMLIFrameElement | undefined
if (iframe != null) {
iframe.style.display = iframe.style.display === 'none' ? 'block' : 'none'
runtime.injectMessaging.sendExtension(MESSAGE_TO_EXTENSION_SHOW_FLAG, {
runtime.injectMessaging.sendExtension('SHOW_FLAG', {
show: iframe.style.display !== 'none'
})
} else {
createIframe()
}
},
[MESSAGE_TO_INJECT_FOLD]: async (params) => {
FOLD: async (params) => {
runtime.fold = params.fold
updateIframeHeight()
},
[MESSAGE_TO_INJECT_MOVE]: async (params) => {
MOVE: async (params) => {
const video = getVideoElement()
if (video != null) {
video.currentTime = params.time
@@ -267,14 +266,14 @@ const debug = (...args: any[]) => {
}
}
},
[MESSAGE_TO_INJECT_GET_SUBTITLE]: async (params) => {
GET_SUBTITLE: async (params) => {
let url = params.info.subtitle_url
if (url.startsWith('http://')) {
url = url.replace('http://', 'https://')
}
return await fetch(url).then(res => res.json())
},
[MESSAGE_TO_INJECT_GET_VIDEO_STATUS]: async (params) => {
GET_VIDEO_STATUS: async (params) => {
const video = getVideoElement()
if (video != null) {
return {
@@ -283,17 +282,17 @@ const debug = (...args: any[]) => {
}
}
},
[MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO]: async (params) => {
GET_VIDEO_ELEMENT_INFO: async (params) => {
refreshVideoElement()
return {
noVideo: runtime.videoElement == null,
totalHeight: runtime.videoElementHeight,
}
},
[MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO]: async (params) => {
REFRESH_VIDEO_INFO: async (params) => {
refreshVideoInfo(params.force)
},
[MESSAGE_TO_INJECT_UPDATETRANSRESULT]: async (params) => {
UPDATE_TRANS_RESULT: async (params) => {
runtime.showTrans = true
runtime.curTrans = params?.result
@@ -321,7 +320,7 @@ const debug = (...args: any[]) => {
}
text && (text.style.display = runtime.curTrans ? 'block' : 'none')
},
[MESSAGE_TO_INJECT_HIDE_TRANS]: async (params) => {
HIDE_TRANS: async (params) => {
runtime.showTrans = false
runtime.curTrans = undefined
@@ -330,7 +329,7 @@ const debug = (...args: any[]) => {
text.style.display = 'none'
}
},
[MESSAGE_TO_INJECT_PLAY]: async (params) => {
PLAY: async (params) => {
const { play } = params
const video = getVideoElement()
if (video != null) {
@@ -341,7 +340,7 @@ const debug = (...args: any[]) => {
}
}
},
[MESSAGE_TO_INJECT_DOWNLOAD_AUDIO]: async (params) => {
DOWNLOAD_AUDIO: async (params) => {
const html = document.getElementsByTagName('html')[0].innerHTML
const playInfo = JSON.parse(html.match(/window.__playinfo__=(.+?)<\/script/)?.[1] ?? '{}')
const audioUrl = playInfo.data.dash.audio[0].baseUrl

View File

@@ -4,7 +4,7 @@ import './index.less'
import store from './store'
import {Provider} from 'react-redux'
import Router from './Router'
import {APP_DOM_ID} from './consts/const'
import { APP_DOM_ID } from './consts/const'
const body = document.querySelector('body')
const app = document.createElement('div')

89
src/message-typings.d.ts vendored Normal file
View File

@@ -0,0 +1,89 @@
//extension
interface ExtensionCloseSidePanelMessage extends ExtensionMessage {
method: 'CLOSE_SIDE_PANEL';
}
interface ExtensionAddTaskMessage extends ExtensionMessage<{ taskDef: TaskDef }, Task> {
method: 'ADD_TASK';
}
interface ExtensionGetTaskMessage extends ExtensionMessage<{ taskId: string }, {
code: 'ok'
task: Task
} | {
code: 'not_found'
}> {
method: 'GET_TASK';
}
interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> {
method: 'SHOW_FLAG';
}
type AllExtensionMessages = ExtensionCloseSidePanelMessage | ExtensionAddTaskMessage | ExtensionGetTaskMessage | ExtensionShowFlagMessage
//inject
interface InjectToggleDisplayMessage extends InjectMessage<{}> {
method: 'TOGGLE_DISPLAY';
}
interface InjectFoldMessage extends InjectMessage<{ fold: boolean }> {
method: 'FOLD';
}
interface InjectMoveMessage extends InjectMessage<{ time: number, togglePause: boolean }> {
method: 'MOVE';
}
interface InjectGetSubtitleMessage extends InjectMessage<{ info: any }> {
method: 'GET_SUBTITLE';
}
interface InjectGetVideoStatusMessage extends InjectMessage<{}> {
method: 'GET_VIDEO_STATUS';
}
interface InjectGetVideoElementInfoMessage extends InjectMessage<{}> {
method: 'GET_VIDEO_ELEMENT_INFO';
}
interface InjectRefreshVideoInfoMessage extends InjectMessage<{ force: boolean }> {
method: 'REFRESH_VIDEO_INFO';
}
interface InjectUpdateTransResultMessage extends InjectMessage<{ result: string }> {
method: 'UPDATE_TRANS_RESULT';
}
interface InjectHideTransMessage extends InjectMessage<{}> {
method: 'HIDE_TRANS';
}
interface InjectPlayMessage extends InjectMessage<{ play: boolean }> {
method: 'PLAY';
}
interface InjectDownloadAudioMessage extends InjectMessage<{}> {
method: 'DOWNLOAD_AUDIO';
}
type AllInjectMessages = InjectToggleDisplayMessage | InjectFoldMessage | InjectMoveMessage | InjectGetSubtitleMessage | InjectGetVideoStatusMessage | InjectGetVideoElementInfoMessage | InjectRefreshVideoInfoMessage | InjectUpdateTransResultMessage | InjectHideTransMessage | InjectPlayMessage | InjectDownloadAudioMessage
//app
interface AppSetInfosMessage extends AppMessage<{ infos: any }> {
method: 'SET_INFOS';
}
interface AppSetVideoInfoMessage extends AppMessage<{ url: string, title: string, aid: number | null, pages: any, infos: any }> {
method: 'SET_VIDEO_INFO';
}
type AllAPPMessages = AppSetInfosMessage | AppSetVideoInfoMessage

View File

@@ -12,8 +12,5 @@ export type L2ResMsg<L2Res = any> = {
data?: L2Res
}
export const MESSAGE_TO_EXTENSION_HANDSHAKE = '_handshake'
export const MESSAGE_TO_EXTENSION_ROUTE = '_route'
export const TAG_TARGET_INJECT = 'target:inject'
export const TAG_TARGET_APP = 'target:app'

View File

@@ -1,5 +1,5 @@
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, MESSAGE_TO_EXTENSION_HANDSHAKE, MESSAGE_TO_EXTENSION_ROUTE } from '../const'
import { L2ReqMsg, L2ResMsg } from '../const'
type PortContext<L2ReqMsg, L2ResMsg> = {
id: string
@@ -12,22 +12,22 @@ type PortContext<L2ReqMsg, L2ResMsg> = {
tags?: string[] // 标签,用来筛选消息发送目标
}
type L2MethodHandler<L2ReqMsg, L2ResMsg> = (params: any, context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => Promise<any>
type L2MethodHandlers<L2ReqMsg, L2ResMsg> = {
[key: string]: L2MethodHandler<L2ReqMsg, L2ResMsg>
type L2MethodHandler<M extends ExtensionMessage, K, L2ReqMsg, L2ResMsg> = (params: Extract<M, { method: K }>['params'], context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => Promise<any>
type L2MethodHandlers<M extends ExtensionMessage, L2ReqMsg, L2ResMsg> = {
[K in M['method']]: L2MethodHandler<M, K, L2ReqMsg, L2ResMsg>
}
class ExtensionMessaging {
class ExtensionMessaging<M extends ExtensionMessage, AllInjectMessagesType extends InjectMessage, AllAPPMessagesType extends AppMessage> {
portIdToPort: Map<string, PortContext<L2ReqMsg, L2ResMsg>> = new Map()
methods?: L2MethodHandlers<L2ReqMsg, L2ResMsg>
methods?: L2MethodHandlers<M, L2ReqMsg, L2ResMsg>
debug = (...args: any[]) => {
console.debug('[Extension Messaging]', ...args)
}
init = (methods: L2MethodHandlers<L2ReqMsg, L2ResMsg>) => {
const innerMethods: L2MethodHandlers<L2ReqMsg, L2ResMsg> = {
[MESSAGE_TO_EXTENSION_HANDSHAKE]: async (params: any, context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => {
init = (methods: L2MethodHandlers<M, L2ReqMsg, L2ResMsg>) => {
const innerMethods: L2MethodHandlers<MessagingExtensionMessages, L2ReqMsg, L2ResMsg> = {
_HANDSHAKE: async (params, context: MethodContext, portContext: PortContext<L2ReqMsg, L2ResMsg>) => {
const tags = params.tags
let tabId = params.tabId
@@ -44,8 +44,8 @@ class ExtensionMessaging {
portContext.tags = tags
portContext.ready = true
},
[MESSAGE_TO_EXTENSION_ROUTE]: async (params: any, context: MethodContext) => {
return this.broadcastMessageExact([context.tabId!], params.tags, params.method, params.params)
_ROUTE: async (params, context: MethodContext) => {
return this.broadcastMessageExact([context.tabId!], params.tags, params.method as any, params.params)
},
}
@@ -59,17 +59,18 @@ class ExtensionMessaging {
// 创建消息处理器
const l1protocol = new Layer1Protocol<L2ReqMsg, L2ResMsg>(async (req: L2ReqMsg) => {
const { tabId } = portContext
const method = this.methods?.[req.method]
const method = this.methods?.[req.method as keyof typeof this.methods]
// console.log('msg>>>', tabId, req, method != null)
if (method != null) {
return method(req.params, {
from: req.from,
event: req,
tabId,
// sender: portContext.port.sender,
}, portContext).then(data => ({
}, portContext).then((data) => ({
code: 200,
data,
})).catch(err => {
})).catch((err) => {
console.error(err)
return {
code: 500,
@@ -97,7 +98,7 @@ class ExtensionMessaging {
//tags 如果为null则不检查tags如果为空数组则不会发送消息
//返回:最后一个响应(因此如果只发送给一个tab则返回的是该tab的响应)
broadcastMessageExact = async (tabIds: number[], tags: string[] | null, method: string, params?: any) => {
broadcastMessageExact = async <M extends AllInjectMessagesType | AllAPPMessagesType, K extends M['method']>(tabIds: number[], tags: string[] | null, method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
// 如果tags为空数组则不会发送消息
if (tags != null && tags.length === 0) {
return
@@ -120,13 +121,13 @@ class ExtensionMessaging {
return res?.data
}
broadcastMessage = async (ignoreTabIds: number[] | undefined | null, tags: string[], method: string, params?: any) => {
broadcastMessage = async <M extends AllInjectMessagesType | AllAPPMessagesType, K extends M['method']>(ignoreTabIds: number[] | undefined | null, tags: string[], method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
const tabs = await chrome.tabs.query({
discarded: false,
})
const tabIds: number[] = tabs.map(tab => tab.id).filter(tabId => tabId != null) as number[]
const filteredTabIds: number[] = tabIds.filter(tabId => !ignoreTabIds?.includes(tabId))
await this.broadcastMessageExact(filteredTabIds, tags, method, params)
return await this.broadcastMessageExact(filteredTabIds, tags, method, params)
}
}

View File

@@ -1,12 +1,12 @@
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, MESSAGE_TO_EXTENSION_HANDSHAKE, MESSAGE_TO_EXTENSION_ROUTE, TAG_TARGET_APP, TAG_TARGET_INJECT } from '../const'
import { L2ReqMsg, L2ResMsg, TAG_TARGET_APP, TAG_TARGET_INJECT } from '../const'
class InjectMessaging {
class InjectMessaging<AllExtensionMessagesType extends ExtensionMessage, AllInjectMessagesType extends InjectMessage, AllAPPMessagesType extends AppMessage> {
port?: chrome.runtime.Port
l1protocol?: Layer1Protocol<L2ReqMsg, L2ResMsg>
//类实例
methods?: {
[key: string]: (params: any, context: MethodContext) => Promise<L2ResMsg>
[K in AllInjectMessagesType['method']]: (params: Extract<AllInjectMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
}
debug = (...args: any[]) => {
@@ -23,7 +23,7 @@ class InjectMessaging {
// message: 'Target Error: ' + req.target,
// })
const method = this.methods?.[req.method]
const method = this.methods?.[req.method as keyof typeof this.methods]
if (method != null) {
return method(req.params, {
from: req.from,
@@ -59,7 +59,7 @@ class InjectMessaging {
}
init(methods: {
[key: string]: (params: any, context: MethodContext) => Promise<any>
[K in AllInjectMessagesType['method']]: (params: Extract<AllInjectMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
}) {
this.methods = methods
this.port = chrome.runtime.connect(import.meta.env.VITE_EXTENSION_ID, {
@@ -69,33 +69,29 @@ class InjectMessaging {
//握手
this.l1protocol.sendMessage({
from: 'inject',
method: MESSAGE_TO_EXTENSION_HANDSHAKE,
method: '_HANDSHAKE',
params: {
type: 'inject',
tags: [TAG_TARGET_INJECT],
},
})
}
sendExtension = async <T = any>(method: string, params?: any): Promise<T> => {
sendExtension = async <M extends AllExtensionMessagesType | MessagingExtensionMessages, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
return await this.l1protocol!.sendMessage({
from: 'inject',
method,
params: params ?? {},
}).then((res) => {
if (res.code === 200) {
return res.data as T
return res.data
} else {
throw new Error(res.msg)
}
})
}
sendApp = async <T>(method: string, params: any): Promise<T> => {
if (method === 'setVideoInfo') {
console.log('sendApp>>>', method, params)
}
return this.sendExtension(MESSAGE_TO_EXTENSION_ROUTE, {
sendApp = async <M extends AllAPPMessagesType, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
return this.sendExtension('_ROUTE' as any, {
tags: [TAG_TARGET_APP],
method,
params,

View File

@@ -1,10 +1,10 @@
import { msgWaiter } from './useMessagingService'
import { useCallback } from 'react'
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, MESSAGE_TO_EXTENSION_ROUTE, TAG_TARGET_INJECT } from '../const'
import { L2ReqMsg, L2ResMsg, TAG_TARGET_INJECT } from '../const'
const useMessaging = () => {
const sendExtension = useCallback(async <T = any>(method: string, params?: any) => {
const useMessaging = <AllExtensionMessagesType extends ExtensionMessage, AllInjectMessagesType extends InjectMessage>() => {
const sendExtension = useCallback(async <M extends AllExtensionMessagesType | MessagingExtensionMessages, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
// wait
const pmh = await msgWaiter.wait() as Layer1Protocol<L2ReqMsg, L2ResMsg>
// send message
@@ -14,14 +14,14 @@ const useMessaging = () => {
params: params ?? {},
})
if (res.code === 200) {
return res.data as T
return res.data
} else {
throw new Error(res.msg)
}
}, [])
const sendInject = useCallback(async <T = any>(method: string, params?: any): Promise<T> => {
return await sendExtension(MESSAGE_TO_EXTENSION_ROUTE, {
const sendInject = useCallback(async <M extends AllInjectMessagesType, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
return await sendExtension('_ROUTE' as any, {
tags: [TAG_TARGET_INJECT],
method,
params: params ?? {},

View File

@@ -1,7 +1,7 @@
import { useCallback, useMemo } from 'react'
import { Waiter } from '@kky002/kky-util'
import Layer1Protocol from '../layer1/Layer1Protocol'
import { L2ReqMsg, L2ResMsg, MESSAGE_TO_EXTENSION_HANDSHAKE, TAG_TARGET_APP } from '../const'
import { L2ReqMsg, L2ResMsg, TAG_TARGET_APP } from '../const'
const debug = (...args: any[]) => {
console.debug('[App Messaging]', ...args)
@@ -16,8 +16,8 @@ export const msgWaiter = new Waiter<Layer1Protocol<L2ReqMsg, L2ResMsg>>(() => ({
data: l1protocol!,
}), 100, 15000)
const useMessagingService = (methods?: {
[key: string]: (params: any, context: MethodContext) => Promise<any>
const useMessagingService = <AllAPPMessagesType extends AppMessage>(methods?: {
[K in AllAPPMessagesType['method']]: (params: Extract<AllAPPMessagesType, { method: K }>['params'], context: MethodContext) => Promise<any>
}) => {
const messageHandler = useCallback(async (req: L2ReqMsg): Promise<L2ResMsg> => {
debug(`[${req.from}] ${req.method}`, JSON.stringify(req))
@@ -28,7 +28,7 @@ const useMessagingService = (methods?: {
// msg: 'Target Error: ' + req.target,
// }
const method = methods?.[req.method]
const method = methods?.[req.method as keyof typeof methods]
if (method != null) {
return method(req.params, {
from: req.from,
@@ -77,7 +77,7 @@ const useMessagingService = (methods?: {
// 初始化
pmh.sendMessage({
from: 'app',
method: MESSAGE_TO_EXTENSION_HANDSHAKE,
method: '_HANDSHAKE',
params: {
tabId,
tags: [TAG_TARGET_APP],

28
src/messaging/messaging-typings.d.ts vendored Normal file
View File

@@ -0,0 +1,28 @@
interface Message<T = any, R = any> {
method: string
params: T
return: R
}
interface ExtensionMessage<T = any, R = any> extends Message<T, R> {
}
interface InjectMessage<T = any, R = any> extends Message<T, R> {
}
interface AppMessage<T = any, R = any> extends Message<T, R> {
}
interface ExtensionHandshakeMessage extends ExtensionMessage<{ tabId?: number, tags: string[] }> {
method: '_HANDSHAKE';
}
interface ExtensionRouteMessage extends ExtensionMessage<{ tags: string[], method: string, params: any }> {
method: '_ROUTE';
}
type MessagingExtensionMessages = ExtensionHandshakeMessage | ExtensionRouteMessage

View File

@@ -3,13 +3,13 @@ import {useAppDispatch, useAppSelector} from '../hooks/redux'
import Header from '../components/Header'
import Body from '../components/Body'
import useSubtitleService from '../hooks/useSubtitleService'
import {EVENT_EXPAND, MESSAGE_TO_INJECT_FOLD} from '../consts/const'
import {EVENT_EXPAND} from '../consts/const'
import {EventBusContext} from '../Router'
import useTranslateService from '../hooks/useTranslateService'
import {setTheme} from '../utils/bizUtil'
import useSearchService from '../hooks/useSearchService'
import useMessage from '../messaging/layer2/useMessaging'
import {setFold} from '../redux/envReducer'
import { useMessage } from '@/hooks/message'
function App() {
const dispatch = useAppDispatch()
@@ -21,7 +21,7 @@ function App() {
const foldCallback = useCallback(() => {
dispatch(setFold(!fold))
sendInject(MESSAGE_TO_INJECT_FOLD, {fold: !fold})
sendInject('FOLD', {fold: !fold})
}, [dispatch, fold, sendInject])
// handle event

View File

@@ -1,20 +1,17 @@
import React, {PropsWithChildren, useCallback, useMemo, useState} from 'react'
import {setEnvData, setTempData} from '../redux/envReducer'
import {setEnvData} from '../redux/envReducer'
import {useAppDispatch, useAppSelector} from '../hooks/redux'
import {
ASK_ENABLED_DEFAULT,
CUSTOM_MODEL_TOKENS,
DEFAULT_SERVER_URL_OPENAI,
GEMINI_TOKENS,
HEADER_HEIGHT,
LANGUAGE_DEFAULT,
LANGUAGES,
MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL,
MODEL_DEFAULT,
MODEL_MAP,
MODEL_TIP,
MODELS,
PAGE_MAIN,
PROMPT_DEFAULTS,
PROMPT_TYPES,
SUMMARIZE_LANGUAGE_DEFAULT,
@@ -29,18 +26,24 @@ import classNames from 'classnames'
import toast from 'react-hot-toast'
import {useBoolean, useEventTarget} from 'ahooks'
import {useEventChecked} from '@kky002/kky-hooks'
import useMessaging from '@/messaging/layer2/useMessaging'
import { useMessage } from '@/hooks/message'
import { FaChevronDown, FaChevronUp } from 'react-icons/fa'
const Section = (props: {
title: ShowElement
htmlFor?: string
} & PropsWithChildren) => {
const {title, htmlFor, children} = props
return <div className='flex flex-col gap-1'>
<label className='font-medium desc-lighter text-sm' htmlFor={htmlFor}>{title}</label>
<div className='flex flex-col gap-1 rounded py-2 px-2 bg-base-200/75'>{children}</div>
</div>
}
const OptionCard = ({ title, children, defaultExpanded = true }: { title: React.ReactNode; children: React.ReactNode; defaultExpanded?: boolean }) => {
const [isExpanded, setIsExpanded] = useState(defaultExpanded);
return (
<div className="card bg-base-200 shadow-xl mb-4">
<div className="card-body p-4">
<h2 className="card-title flex justify-between cursor-pointer" onClick={() => setIsExpanded(!isExpanded)}>
{title}
{isExpanded ? <FaChevronUp /> : <FaChevronDown />}
</h2>
{isExpanded && <div className="mt-4">{children}</div>}
</div>
</div>
);
};
const FormItem = (props: {
title: ShowElement
@@ -48,20 +51,22 @@ const FormItem = (props: {
htmlFor?: string
} & PropsWithChildren) => {
const {title, tip, htmlFor, children} = props
return <div className='flex items-center gap-2'>
<div className={classNames('basis-3/12 justify-end flex-center', tip && 'tooltip tooltip-right z-[100] underline underline-offset-2 decoration-dashed')} data-tip={tip}>
<label className='font-medium desc' htmlFor={htmlFor}>{title}</label>
return (
<div className='flex items-center gap-4 mb-2'>
<div className={classNames('w-1/3 text-right', tip && 'tooltip tooltip-right z-50')} data-tip={tip}>
<label className={classNames('font-medium', tip && 'border-b border-dotted border-current pb-[2px]')} htmlFor={htmlFor}>{title}</label>
</div>
<div className='w-2/3'>
{children}
</div>
</div>
<div className='basis-9/12 flex items-center'>
{children}
</div>
</div>
)
}
const OptionsPage = () => {
const dispatch = useAppDispatch()
const envData = useAppSelector(state => state.env.envData)
const {sendExtension} = useMessaging()
const {sendExtension} = useMessage()
const {value: sidePanelValue, onChange: setSidePanelValue} = useEventChecked(envData.sidePanel)
const {value: autoInsertValue, onChange: setAutoInsertValue} = useEventChecked(!envData.manualInsert)
const {value: autoExpandValue, onChange: setAutoExpandValue} = useEventChecked(envData.autoExpand)
@@ -143,7 +148,7 @@ const OptionsPage = () => {
askEnabled: askEnabledValue,
}))
toast.success('保存成功')
sendExtension(MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL)
sendExtension('CLOSE_SIDE_PANEL')
// 3秒后关闭
setTimeout(() => {
window.close()
@@ -202,9 +207,9 @@ const OptionsPage = () => {
setAiTypeValue('gemini')
}, [])
return <div className='flex justify-center'>
<div className="w-2/3 max-w-[600px] flex flex-col gap-3 p-2">
<Section title='通用配置'>
return (
<div className='container mx-auto max-w-3xl p-4'>
<OptionCard title="通用配置">
<FormItem title='侧边栏' htmlFor='sidePanel' tip='字幕列表是否显示在侧边栏'>
<input id='sidePanel' type='checkbox' className='toggle toggle-primary' checked={sidePanelValue}
onChange={setSidePanelValue}/>
@@ -219,37 +224,37 @@ const OptionsPage = () => {
</FormItem>}
<FormItem title='主题'>
<div className="btn-group">
<button onClick={onSelTheme1} className={classNames('btn btn-xs no-animation', (!themeValue || themeValue === 'system')?'btn-active':'')}></button>
<button onClick={onSelTheme2} className={classNames('btn btn-xs no-animation', themeValue === 'light'?'btn-active':'')}></button>
<button onClick={onSelTheme3} className={classNames('btn btn-xs no-animation', themeValue === 'dark'?'btn-active':'')}></button>
<button onClick={onSelTheme1} className={classNames('btn btn-sm no-animation', (!themeValue || themeValue === 'system')?'btn-active':'')}></button>
<button onClick={onSelTheme2} className={classNames('btn btn-sm no-animation', themeValue === 'light'?'btn-active':'')}></button>
<button onClick={onSelTheme3} className={classNames('btn btn-sm no-animation', themeValue === 'dark'?'btn-active':'')}></button>
</div>
</FormItem>
<FormItem title='字体大小'>
<div className="btn-group">
<button onClick={onSelFontSize1} className={classNames('btn btn-xs no-animation', (!fontSizeValue || fontSizeValue === 'normal')?'btn-active':'')}></button>
<button onClick={onSelFontSize2} className={classNames('btn btn-xs no-animation', fontSizeValue === 'large'?'btn-active':'')}></button>
<button onClick={onSelFontSize1} className={classNames('btn btn-sm no-animation', (!fontSizeValue || fontSizeValue === 'normal')?'btn-active':'')}></button>
<button onClick={onSelFontSize2} className={classNames('btn btn-sm no-animation', fontSizeValue === 'large'?'btn-active':'')}></button>
</div>
</FormItem>
<FormItem title='AI类型' tip='OPENAI质量更高'>
<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>
<button onClick={onSelOpenai} className={classNames('btn btn-sm', (!aiTypeValue || aiTypeValue === 'openai')?'btn-active':'')}>OpenAI</button>
<button onClick={onSelGemini} className={classNames('btn btn-sm', aiTypeValue === 'gemini'?'btn-active':'')}>Gemini</button>
</div>
</FormItem>
</Section>
</OptionCard>
{(!aiTypeValue || aiTypeValue === 'openai') && <Section title='openai配置'>
<FormItem title='ApiKey' htmlFor='apiKey'>
<OptionCard title="AI 配置">
{(!aiTypeValue || aiTypeValue === '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>
<FormItem title='服务器' htmlFor='serverUrl'>
</FormItem>}
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='服务器' htmlFor='serverUrl'>
<input id='serverUrl' type='text' className='input input-sm input-bordered w-full'
placeholder={DEFAULT_SERVER_URL_OPENAI} value={serverUrlValue}
onChange={e => setServerUrlValue(e.target.value)}/>
</FormItem>
<div>
<div className='desc text-xs text-center'>
</FormItem>}
{(!aiTypeValue || aiTypeValue === 'openai') && <div>
<div className='desc text-sm text-center'>
<div className='flex justify-center font-semibold'></div>
<div><a className='link link-primary' href='https://platform.openai.com/' target='_blank'
rel="noreferrer">访</a></div>
@@ -265,16 +270,16 @@ const OptionsPage = () => {
{/* rel='noreferrer'>点击设置</a></div> */}
{/* <div className='text-amber-600 flex justify-center items-center'><FaGripfire/>目前价格不到官方价格的6折<FaGripfire/></div> */}
</div>
</div>
<FormItem title='模型选择' htmlFor='modelSel' tip='注意不同模型有不同价格与token限制'>
</div>}
{(!aiTypeValue || aiTypeValue === 'openai') && <FormItem title='模型选择' htmlFor='modelSel' tip='注意不同模型有不同价格与token限制'>
<select id='modelSel' className="select select-sm select-bordered" value={modelValue}
onChange={onChangeModelValue}>
{MODELS.map(model => <option key={model.code} value={model.code}>{model.name}</option>)}
</select>
</FormItem>
<div className='desc text-xs'>
</FormItem>}
{(!aiTypeValue || aiTypeValue === 'openai') && <div className='desc text-sm'>
{MODEL_TIP}
</div>
</div>}
{modelValue === 'custom' && <FormItem title='模型名' htmlFor='customModel'>
<input id='customModel' type='text' className='input input-sm input-bordered w-full' placeholder='llama2'
value={customModelValue} onChange={onChangeCustomModelValue}/>
@@ -285,26 +290,23 @@ const OptionsPage = () => {
value={customModelTokensValue}
onChange={e => setCustomModelTokensValue(e.target.value ? parseInt(e.target.value) : undefined)}/>
</FormItem>}
</Section>}
{aiTypeValue === 'gemini' && <Section title='gemini配置'>
<FormItem title='ApiKey' htmlFor='geminiApiKey'>
{aiTypeValue === '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>
<div className='desc text-xs'>
</FormItem>}
{aiTypeValue === 'gemini' && <div>
<div className='desc text-sm'>
<div><a className='link link-primary' href='https://makersuite.google.com/app/apikey'
target='_blank'
rel="noreferrer">Google AI Studio</a> ()
</div>
<div className='text-xs text-error flex items-center'><IoWarning className='text-sm text-warning'/>!
<div className='text-sm text-error flex items-center'><IoWarning className='text-sm text-warning'/>!
</div>
</div>
</div>
</Section>}
</div>}
</OptionCard>
<Section title={<div className='flex items-center'>
<OptionCard title={<div className='flex items-center'>
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/>
@@ -323,24 +325,24 @@ const OptionsPage = () => {
<FormItem title='翻译条数' tip='每次翻译条数'>
<div className='flex-1 flex flex-col'>
<input type="range" min={TRANSLATE_FETCH_MIN} max={TRANSLATE_FETCH_MAX} step={TRANSLATE_FETCH_STEP} value={fetchAmountValue} className="range range-primary" onChange={onFetchAmountChange} />
<div className="w-full flex justify-between text-xs px-2">
<div className="w-full flex justify-between text-sm px-2">
{transFetchAmountList.map(amount => <span key={amount}>{amount}</span>)}
</div>
</div>
</FormItem>
<FormItem title='翻译显示'>
<div className="btn-group">
<button onClick={onSel1} className={classNames('btn btn-xs no-animation', (!transDisplayValue || transDisplayValue === 'originPrimary')?'btn-active':'')}></button>
<button onClick={onSel2} className={classNames('btn btn-xs no-animation', transDisplayValue === 'targetPrimary'?'btn-active':'')}></button>
<button onClick={onSel3} className={classNames('btn btn-xs no-animation', transDisplayValue === 'target'?'btn-active':'')}></button>
<button onClick={onSel1} className={classNames('btn btn-sm no-animation', (!transDisplayValue || transDisplayValue === 'originPrimary')?'btn-active':'')}></button>
<button onClick={onSel2} className={classNames('btn btn-sm no-animation', transDisplayValue === 'targetPrimary'?'btn-active':'')}></button>
<button onClick={onSel3} className={classNames('btn btn-sm no-animation', transDisplayValue === 'target'?'btn-active':'')}></button>
</div>
</FormItem>
<FormItem title='隐藏翻译' tip='取消自动翻译时,隐藏已翻译内容' htmlFor='hideOnDisableAutoTranslate'>
<input id='hideOnDisableAutoTranslate' type='checkbox' className='toggle toggle-primary' checked={hideOnDisableAutoTranslateValue}
onChange={onChangeHideOnDisableAutoTranslate}/>
</FormItem>
</Section>
<Section title={<div className='flex items-center'>
</OptionCard>
<OptionCard title={<div className='flex items-center'>
{!apiKeySetted && <div className='tooltip tooltip-right ml-1' data-tip='未设置ApiKey无法使用'>
<IoWarning className='text-sm text-warning'/>
@@ -363,17 +365,17 @@ const OptionsPage = () => {
<div className='flex-1 flex flex-col'>
<input id='words' type='number' className='input input-sm input-bordered w-full' placeholder={`默认为上限x${WORDS_RATE}`} value={wordsValue??''} onChange={e => setWordsValue(e.target.value?parseInt(e.target.value):undefined)}/>
{/* <input type="range" min={WORDS_MIN} max={WORDS_MAX} step={WORDS_STEP} value={wordsValue} className="range range-primary" onChange={onWordsChange} /> */}
{/* <div className="w-full flex justify-between text-xs px-2"> */}
{/* <div className="w-full flex justify-between text-sm px-2"> */}
{/* {wordsList.map(words => <span key={words}>{words}</span>)} */}
{/* </div> */}
</div>
</FormItem>
<div className='desc text-xs'>
<div className='desc text-sm'>
<span className='font-semibold font-mono'>{aiTypeValue === 'gemini'?GEMINI_TOKENS:(MODEL_MAP[modelValue??MODEL_DEFAULT]?.tokens??'未知')}</span>
</div>
</Section>
<Section title={<div className='flex items-center'>
</OptionCard>
<OptionCard title={<div className='flex items-center'>
</div>}>
<FormItem title='启用搜索' htmlFor='searchEnabled' tip='是否启用字幕搜索功能'>
@@ -384,23 +386,23 @@ const OptionsPage = () => {
<input id='cnSearchEnabled' type='checkbox' className='toggle toggle-primary' checked={cnSearchEnabledValue}
onChange={setCnSearchEnabledValue}/>
</FormItem>
</Section>
<Section title={<div className='flex items-center'>
</OptionCard>
<OptionCard title={<div className='flex items-center'>
</div>}>
<FormItem title='启用提问' htmlFor='askEnabled' tip='是否启用字幕提问功能'>
<input id='askEnabled' type='checkbox' className='toggle toggle-primary' checked={askEnabledValue}
onChange={setAskEnabledValue}/>
</FormItem>
</Section>
</OptionCard>
<Section title='提示词配置'>
<OptionCard title='提示词配置'>
<div className='flex justify-center'>
<a className='text-xs link link-primary' onClick={togglePromptsFold}>{promptsFold ? '展开' : '折叠'}</a>
<a className='text-sm link link-primary' onClick={togglePromptsFold}>{promptsFold ? '展开' : '折叠'}</a>
</div>
{!promptsFold && PROMPT_TYPES.map((item, idx) => <FormItem key={item.type} title={<div>
<div>{item.name}</div>
<div className='link text-xs' onClick={() => {
<div className='link text-sm' onClick={() => {
setPromptsValue({
...promptsValue,
// @ts-expect-error
@@ -417,20 +419,14 @@ const OptionsPage = () => {
})
}}/>
</FormItem>)}
</Section>
</OptionCard>
<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>
{/* <button className='btn btn-sm' onClick={() => {
dispatch(setTempData({
reviewed: undefined,
// reviewActions: 0
}))
}}>重置</button> */}
<div className='flex flex-col justify-center items-center gap-5 mt-6'>
<button className='btn btn-primary btn-wide' onClick={onSave}></button>
<button className='btn btn-wide' onClick={onCancel}></button>
</div>
</div>
</div>
)
}
export default OptionsPage
export default OptionsPage

19
src/typings.d.ts vendored
View File

@@ -1,22 +1,5 @@
type MessageFrom = 'extension' | 'inject' | 'app'
interface MessageData {
from: MessageFrom
target: string
method: string
params?: any
[key: string]: any
}
interface MessageResult {
success: boolean
code: number
message?: string
data?: any
}
interface MethodContext {
from: MessageFrom
from: 'extension' | 'inject' | 'app'
event: any
tabId?: number
// sender?: chrome.runtime.MessageSender | null

View File

@@ -2,7 +2,6 @@ import {APP_DOM_ID, CUSTOM_MODEL_TOKENS, MODEL_DEFAULT, MODEL_MAP, SUMMARIZE_TYP
import {isDarkMode} from '@kky002/kky-util'
import toast from 'react-hot-toast'
import {findIndex} from 'lodash-es'
export const debug = (...args: any[]) => {
console.debug('[APP]', ...args)
}