-
-
Notifications
You must be signed in to change notification settings - Fork 523
/
Copy pathindex.jsx
323 lines (310 loc) · 14.2 KB
/
index.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { readDir, BaseDirectory, readTextFile, exists } from '@tauri-apps/api/fs';
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
import { appWindow, currentMonitor } from '@tauri-apps/api/window';
import { appConfigDir, join } from '@tauri-apps/api/path';
import { convertFileSrc } from '@tauri-apps/api/tauri';
import { Spacer, Button } from '@nextui-org/react';
import { AiFillCloseCircle } from 'react-icons/ai';
import React, { useState, useEffect } from 'react';
import { listen } from '@tauri-apps/api/event';
import { BsPinFill } from 'react-icons/bs';
import LanguageArea from './components/LanguageArea';
import SourceArea from './components/SourceArea';
import TargetArea from './components/TargetArea';
import { osType } from '../../utils/env';
import { useConfig } from '../../hooks';
import { store } from '../../utils/store';
import { info } from 'tauri-plugin-log-api';
import * as builtinTranslateServices from '../../services/translate';
import { ServiceSourceType, ServiceType, whetherAvailableService } from '../../utils/service_instance';
let blurTimeout = null;
let resizeTimeout = null;
let moveTimeout = null;
const listenBlur = () => {
return listen('tauri://blur', () => {
if (appWindow.label === 'translate') {
if (blurTimeout) {
clearTimeout(blurTimeout);
}
info('Blur');
// 100ms后关闭窗口,因为在 windows 下拖动窗口时会先切换成 blur 再立即切换成 focus
// 如果直接关闭将导致窗口无法拖动
blurTimeout = setTimeout(async () => {
info('Confirm Blur');
await appWindow.close();
}, 100);
}
});
};
let unlisten = listenBlur();
// 取消 blur 监听
const unlistenBlur = () => {
unlisten.then((f) => {
f();
});
};
// 监听 focus 事件取消 blurTimeout 时间之内的关闭窗口
void listen('tauri://focus', () => {
info('Focus');
if (blurTimeout) {
info('Cancel Close');
clearTimeout(blurTimeout);
}
});
// 监听 move 事件取消 blurTimeout 时间之内的关闭窗口
void listen('tauri://move', () => {
info('Move');
if (blurTimeout) {
info('Cancel Close');
clearTimeout(blurTimeout);
}
});
export default function Translate() {
const [closeOnBlur] = useConfig('translate_close_on_blur', true);
const [alwaysOnTop] = useConfig('translate_always_on_top', false);
const [windowPosition] = useConfig('translate_window_position', 'mouse');
const [rememberWindowSize] = useConfig('translate_remember_window_size', false);
const [translateServiceInstanceList, setTranslateServiceInstanceList] = useConfig('translate_service_list', [
'deepl',
'bing',
'yandex',
'google',
]);
const [hideLanguage] = useConfig('hide_language', false);
const [pined, setPined] = useState(false);
const [pluginList, setPluginList] = useState(null);
const [serviceInstanceConfigMap, setServiceInstanceConfigMap] = useState(null);
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const onDragEnd = async (result) => {
if (!result.destination) return;
const items = reorder(translateServiceInstanceList, result.source.index, result.destination.index);
setTranslateServiceInstanceList(items);
};
// 是否自动关闭窗口
useEffect(() => {
if (closeOnBlur !== null && !closeOnBlur) {
unlistenBlur();
}
}, [closeOnBlur]);
// 是否默认置顶
useEffect(() => {
if (alwaysOnTop !== null && alwaysOnTop) {
appWindow.setAlwaysOnTop(true);
unlistenBlur();
setPined(true);
}
}, [alwaysOnTop]);
// 保存窗口位置
useEffect(() => {
if (windowPosition !== null && windowPosition === 'pre_state') {
const unlistenMove = listen('tauri://move', async () => {
if (moveTimeout) {
clearTimeout(moveTimeout);
}
moveTimeout = setTimeout(async () => {
if (appWindow.label === 'translate') {
let position = await appWindow.outerPosition();
const monitor = await currentMonitor();
const factor = monitor.scaleFactor;
position = position.toLogical(factor);
await store.set('translate_window_position_x', parseInt(position.x));
await store.set('translate_window_position_y', parseInt(position.y));
await store.save();
}
}, 100);
});
return () => {
unlistenMove.then((f) => {
f();
});
};
}
}, [windowPosition]);
// 保存窗口大小
useEffect(() => {
if (rememberWindowSize !== null && rememberWindowSize) {
const unlistenResize = listen('tauri://resize', async () => {
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(async () => {
if (appWindow.label === 'translate') {
let size = await appWindow.outerSize();
const monitor = await currentMonitor();
const factor = monitor.scaleFactor;
size = size.toLogical(factor);
await store.set('translate_window_height', parseInt(size.height));
await store.set('translate_window_width', parseInt(size.width));
await store.save();
}
}, 100);
});
return () => {
unlistenResize.then((f) => {
f();
});
};
}
}, [rememberWindowSize]);
const loadPluginList = async () => {
const serviceTypeList = ['translate', 'tts', 'recognize', 'collection'];
let temp = {};
for (const serviceType of serviceTypeList) {
temp[serviceType] = {};
if (await exists(`plugins/${serviceType}`, { dir: BaseDirectory.AppConfig })) {
const plugins = await readDir(`plugins/${serviceType}`, { dir: BaseDirectory.AppConfig });
for (const plugin of plugins) {
const infoStr = await readTextFile(`plugins/${serviceType}/${plugin.name}/info.json`, {
dir: BaseDirectory.AppConfig,
});
let pluginInfo = JSON.parse(infoStr);
if ('icon' in pluginInfo) {
const appConfigDirPath = await appConfigDir();
const iconPath = await join(
appConfigDirPath,
`/plugins/${serviceType}/${plugin.name}/${pluginInfo.icon}`
);
pluginInfo.icon = convertFileSrc(iconPath);
}
temp[serviceType][plugin.name] = pluginInfo;
}
}
}
setPluginList({ ...temp });
};
useEffect(() => {
loadPluginList();
if (!unlisten) {
unlisten = listen('reload_plugin_list', loadPluginList);
}
}, []);
const loadServiceInstanceConfigMap = async () => {
const config = {};
for (const serviceInstanceKey of translateServiceInstanceList) {
config[serviceInstanceKey] = (await store.get(serviceInstanceKey)) ?? {};
}
setServiceInstanceConfigMap({ ...config });
};
useEffect(() => {
if (translateServiceInstanceList !== null) {
loadServiceInstanceConfigMap();
}
}, [translateServiceInstanceList]);
return (
pluginList && (
<div
className={`bg-background h-screen w-screen ${osType === 'Linux' && 'rounded-[10px] border-1 border-default-100'
}`}
>
<div
className='fixed top-[5px] left-[5px] right-[5px] h-[30px]'
data-tauri-drag-region='true'
/>
<div className={`h-[35px] w-full flex ${osType === 'Darwin' ? 'justify-end' : 'justify-between'}`}>
<Button
isIconOnly
size='sm'
variant='flat'
disableAnimation
className='my-auto bg-transparent'
onPress={() => {
if (pined) {
if (closeOnBlur) {
unlisten = listenBlur();
}
appWindow.setAlwaysOnTop(false);
} else {
unlistenBlur();
appWindow.setAlwaysOnTop(true);
}
setPined(!pined);
}}
>
<BsPinFill className={`text-[20px] ${pined ? 'text-primary' : 'text-default-400'}`} />
</Button>
<Button
isIconOnly
size='sm'
variant='flat'
disableAnimation
className={`my-auto ${osType === 'Darwin' && 'hidden'} bg-transparent`}
onPress={() => {
void appWindow.close();
}}
>
<AiFillCloseCircle className='text-[20px] text-default-400' />
</Button>
</div>
<div className={`${osType === 'Linux' ? 'h-[calc(100vh-37px)]' : 'h-[calc(100vh-35px)]'} px-[8px]`}>
<div className='h-full overflow-y-auto'>
<div>
<SourceArea pluginList={pluginList} />
</div>
<div className={`${hideLanguage && 'hidden'}`}>
<LanguageArea />
<Spacer y={2} />
</div>
<DragDropContext onDragEnd={onDragEnd}>
<Droppable
droppableId='droppable'
direction='vertical'
>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.droppableProps}
>
{translateServiceInstanceList !== null && serviceInstanceConfigMap !== null &&
translateServiceInstanceList.filter(serviceInstanceKey => {
return whetherAvailableService(
serviceInstanceKey,
{
[ServiceSourceType.PLUGIN]: pluginList[ServiceType.TRANSLATE],
[ServiceSourceType.BUILDIN]: builtinTranslateServices
}
)
}).map((serviceInstanceKey, index) => {
const config = serviceInstanceConfigMap[serviceInstanceKey] ?? {};
const enable = config['enable'] ?? true;
return enable ? (
<Draggable
key={serviceInstanceKey}
draggableId={serviceInstanceKey}
index={index}
>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
>
<TargetArea
{...provided.dragHandleProps}
index={index}
name={serviceInstanceKey}
translateServiceInstanceList={translateServiceInstanceList}
pluginList={pluginList}
serviceInstanceConfigMap={serviceInstanceConfigMap}
/>
<Spacer y={2} />
</div>
)}
</Draggable>
) : (
<></>
);
})}
</div>
)}
</Droppable>
</DragDropContext>
</div>
</div>
</div>
)
);
}