This commit is contained in:
IndieKKY
2024-10-06 18:28:20 +08:00
parent 50e6579116
commit 9384c1419a
9 changed files with 111 additions and 61 deletions

View File

@@ -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) => {

View File

@@ -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) {

View File

@@ -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])
}

View File

@@ -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

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 sendExtension = useCallback(async <M extends AllExtensionMessages | 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,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 <T = any>(method: string, params?: any): Promise<T> => {
const sendInject = useCallback(async <M extends AllInjectMessages, K extends M['method']>(method: K, params?: Extract<M, { method: K }>['params']): Promise<Extract<M, { method: K }>['return']> => {
return await sendExtension('ROUTE', {
tags: [TAG_TARGET_INJECT],
method,

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> extends Message<T> {
}
interface InjectMessage<T = any> extends Message<T> {
}
interface AppMessage<T = any> extends Message<T> {
}
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,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

View File

@@ -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()

88
src/typings.d.ts vendored
View File

@@ -1,46 +1,21 @@
interface Message<T = any> {
method: string;
params: T;
}
interface ExtensionMessage<T = any> extends Message<T> {
}
interface InjectMessage<T = any> extends Message<T> {
}
interface AppMessage<T = any> extends Message<T> {
}
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<T = any> {
success: boolean;
data?: T;