From 9384c1419af12700bb628af3705294ad401b53bd Mon Sep 17 00:00:00 2001 From: IndieKKY Date: Sun, 6 Oct 2024 18:28:20 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/MoreBtn.tsx | 6 +- src/hooks/useSubtitle.ts | 6 +- src/hooks/useSubtitleService.ts | 18 +++--- src/hooks/useTranslate.ts | 8 +-- src/messaging/layer2/useMessaging.ts | 8 +-- src/messaging/messaging-typings.d.ts | 28 +++++++++ src/pages/MainPage.tsx | 8 +-- src/pages/OptionsPage.tsx | 2 +- src/typings.d.ts | 88 +++++++++++++++++----------- 9 files changed, 111 insertions(+), 61 deletions(-) create mode 100644 src/messaging/messaging-typings.d.ts diff --git a/src/components/MoreBtn.tsx b/src/components/MoreBtn.tsx index d523d34..1d2037a 100644 --- a/src/components/MoreBtn.tsx +++ b/src/components/MoreBtn.tsx @@ -18,7 +18,7 @@ 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 useMessaging from '../messaging/layer2/useMessaging' interface Props { placement: Placement } @@ -70,7 +70,7 @@ const MoreBtn = (props: Props) => { const title = useAppSelector(state => state.env.title) const curSummaryType = useAppSelector(state => state.env.tempData.curSummaryType) - const {sendInject} = useMessage() + const {sendInject} = useMessaging() const downloadCallback = useCallback((download: boolean) => { if (data == null) { @@ -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) => { diff --git a/src/hooks/useSubtitle.ts b/src/hooks/useSubtitle.ts index 01164e7..6399a4a 100644 --- a/src/hooks/useSubtitle.ts +++ b/src/hooks/useSubtitle.ts @@ -2,16 +2,16 @@ 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 useMessaging from '../messaging/layer2/useMessaging' const useSubtitle = () => { const dispatch = useAppDispatch() const reviewed = useAppSelector(state => state.env.tempData.reviewed) const reviewAction = useAppSelector(state => state.env.reviewAction) const reviewActions = useAppSelector(state => state.env.tempData.reviewActions) - const {sendInject} = useMessage() + const {sendInject} = useMessaging() const move = useCallback((time: number, togglePause: boolean) => { - sendInject(MESSAGE_TO_INJECT_MOVE, {time, togglePause}) + sendInject('MOVE', {time, togglePause}) //review action if (reviewed === undefined && !reviewAction) { diff --git a/src/hooks/useSubtitleService.ts b/src/hooks/useSubtitleService.ts index 7422386..dc742ea 100644 --- a/src/hooks/useSubtitleService.ts +++ b/src/hooks/useSubtitleService.ts @@ -20,7 +20,7 @@ import {EVENT_EXPAND, GEMINI_TOKENS, TOTAL_HEIGHT_MAX, TOTAL_HEIGHT_MIN, WORDS_M 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 useMessaging from '../messaging/layer2/useMessaging' /** * Service是单例,类似后端的服务概念 @@ -44,7 +44,7 @@ const useSubtitleService = () => { const autoTranslate = useAppSelector(state => state.env.autoTranslate) const reviewed = useAppSelector(state => state.env.tempData.reviewed) const reviewActions = useAppSelector(state => state.env.tempData.reviewActions) - const {sendInject} = useMessage() + const {sendInject} = useMessaging() //如果reviewActions达到15次,则设置reviewed为false useEffect(() => { @@ -79,7 +79,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 +94,9 @@ const useSubtitleService = () => { useAsyncEffect(async () => { // 初始获取列表 - sendInject(MESSAGE_TO_INJECT_REFRESH_VIDEO_INFO, {force: true}) + sendInject('REFRESH_VIDEO_INFO', {force: true}) // 初始获取设置信息 - sendInject(MESSAGE_TO_INJECT_GET_VIDEO_ELEMENT_INFO, {}).then(info => { + sendInject('GET_VIDEO_ELEMENT_INFO', {}).then(info => { dispatch(setNoVideo(info.noVideo)) if (envData.sidePanel) { // get screen height @@ -192,7 +192,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 +200,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]) } diff --git a/src/hooks/useTranslate.ts b/src/hooks/useTranslate.ts index b7e68fd..05953e8 100644 --- a/src/hooks/useTranslate.ts +++ b/src/hooks/useTranslate.ts @@ -137,7 +137,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 +207,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 +264,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 +332,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 diff --git a/src/messaging/layer2/useMessaging.ts b/src/messaging/layer2/useMessaging.ts index 4f5259b..be1d68f 100644 --- a/src/messaging/layer2/useMessaging.ts +++ b/src/messaging/layer2/useMessaging.ts @@ -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 (method: string, params?: any) => { + const sendExtension = useCallback(async (method: K, params?: Extract['params']): Promise['return']> => { // wait const pmh = await msgWaiter.wait() as Layer1Protocol // send message @@ -14,13 +14,13 @@ 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 (method: string, params?: any): Promise => { + const sendInject = useCallback(async (method: K, params?: Extract['params']): Promise['return']> => { return await sendExtension('ROUTE', { tags: [TAG_TARGET_INJECT], method, diff --git a/src/messaging/messaging-typings.d.ts b/src/messaging/messaging-typings.d.ts new file mode 100644 index 0000000..b0da6fe --- /dev/null +++ b/src/messaging/messaging-typings.d.ts @@ -0,0 +1,28 @@ +interface Message { + method: string + params: T + return: R +} + +interface ExtensionMessage extends Message { +} + +interface InjectMessage extends Message { +} + +interface AppMessage extends Message { +} + + + + + +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 diff --git a/src/pages/MainPage.tsx b/src/pages/MainPage.tsx index 86df2a8..76d63de 100644 --- a/src/pages/MainPage.tsx +++ b/src/pages/MainPage.tsx @@ -3,12 +3,12 @@ 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 useMessaging from '../messaging/layer2/useMessaging' import {setFold} from '../redux/envReducer' function App() { @@ -16,12 +16,12 @@ function App() { const fold = useAppSelector(state => state.env.fold) const eventBus = useContext(EventBusContext) const totalHeight = useAppSelector(state => state.env.totalHeight) - const {sendInject} = useMessage() + const {sendInject} = useMessaging() const envData = useAppSelector(state => state.env.envData) const foldCallback = useCallback(() => { dispatch(setFold(!fold)) - sendInject(MESSAGE_TO_INJECT_FOLD, {fold: !fold}) + sendInject('FOLD', {fold: !fold}) }, [dispatch, fold, sendInject]) // handle event diff --git a/src/pages/OptionsPage.tsx b/src/pages/OptionsPage.tsx index 33dd28a..dbe2452 100644 --- a/src/pages/OptionsPage.tsx +++ b/src/pages/OptionsPage.tsx @@ -143,7 +143,7 @@ const OptionsPage = () => { askEnabled: askEnabledValue, })) toast.success('保存成功') - sendExtension(MESSAGE_TO_EXTENSION_CLOSE_SIDE_PANEL) + sendExtension('CLOSE_SIDE_PANEL') // 3秒后关闭 setTimeout(() => { window.close() diff --git a/src/typings.d.ts b/src/typings.d.ts index 84e759f..07f81cb 100644 --- a/src/typings.d.ts +++ b/src/typings.d.ts @@ -1,46 +1,21 @@ -interface Message { - method: string; - params: T; -} - -interface ExtensionMessage extends Message { -} - -interface InjectMessage extends Message { -} - -interface AppMessage extends Message { -} - - - - - -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 - - - - - - +//extension interface ExtensionCloseSidePanelMessage extends ExtensionMessage<{}> { method: 'CLOSE_SIDE_PANEL'; } interface ExtensionAddTaskMessage extends ExtensionMessage<{ taskDef: TaskDef }> { method: 'ADD_TASK'; + return: Task } interface ExtensionGetTaskMessage extends ExtensionMessage<{ taskId: string }> { method: 'GET_TASK'; + return: { + code: 'ok' + task: Task + } | { + code: 'not_found' + } } interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> { @@ -49,6 +24,53 @@ interface ExtensionShowFlagMessage extends ExtensionMessage<{ show: boolean }> { 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 + interface MessageResponse { success: boolean; data?: T;