-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathMainLayout.tsx
More file actions
514 lines (495 loc) · 17.7 KB
/
MainLayout.tsx
File metadata and controls
514 lines (495 loc) · 17.7 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import {
Button,
ConfigProvider,
Dropdown,
Empty,
Input,
Layout,
Menu,
Message,
Modal,
Space,
Typography,
} from "@arco-design/web-react";
import type { RefTextAreaType } from "@arco-design/web-react/es/Input";
import {
IconCheckCircle,
IconCloseCircle,
IconDesktop,
IconDown,
IconLanguage,
IconLink,
IconMoonFill,
IconSunFill,
} from "@arco-design/web-react/icon";
import type { ReactNode } from "react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAppContext } from "@App/pages/store/AppContext";
import { RiFileCodeLine, RiImportLine, RiPlayListAddLine, RiTerminalBoxLine, RiTimerLine } from "react-icons/ri";
import { scriptClient } from "@App/pages/store/features/script";
import { useDropzone, type FileWithPath } from "react-dropzone";
import { systemConfig } from "@App/pages/store/global";
import i18n, { matchLanguage } from "@App/locales/locales";
import "./index.css";
import { arcoLocale } from "@App/locales/arco";
import { prepareScriptByCode } from "@App/pkg/utils/script";
import { saveHandle } from "@App/pkg/utils/filehandle-db";
import { makeBlobURL } from "@App/pkg/utils/utils";
// --- 工具函数移出组件外,避免每次 Render 重新定义 ---
const formatUrl = async (url: string) => {
try {
const newUrl = new URL(url.replace(/\/$/, ""));
const { hostname, pathname } = newUrl;
// 判断是否为脚本猫脚本页
if (hostname === "scriptcat.org" && /script-show-page\/\d+$/.test(pathname)) {
const scriptId = pathname.match(/\d+$/)![0];
// 请求脚本信息
const scriptInfo = await fetch(`https://scriptcat.org/api/v2/scripts/${scriptId}`)
.then((res) => {
return res.json();
})
.then((json) => {
return json;
});
const { code, data, msg } = scriptInfo;
if (code !== 0) {
// 无脚本访问权限
return { success: false, msg };
} else {
// 返回脚本实际安装地址
const scriptName = data.name;
return `https://scriptcat.org/scripts/code/${scriptId}/${scriptName}.user.js`;
}
} else {
return url;
}
} catch {
return url;
}
};
// 提供一个简单的字串封装(非加密用)
const simpleDigestMessage = async (message: string) => {
const encoder = new TextEncoder();
const data = encoder.encode(message);
return crypto.subtle.digest("SHA-1", data as BufferSource).then((hashBuffer) => {
const hashArray = new Uint8Array(hashBuffer);
let hex = "";
for (let i = 0; i < hashArray.length; i++) {
const byte = hashArray[i];
hex += `${byte < 16 ? "0" : ""}${byte.toString(16)}`;
}
return hex;
});
};
type TImportStat = {
success: number;
fail: number;
msg: string[];
};
const importByUrls = async (urls: string[]): Promise<TImportStat | undefined> => {
if (urls.length == 0) {
return;
}
const results = (await Promise.allSettled(
urls.map(async (url) => {
const formattedResult = await formatUrl(url);
if (formattedResult instanceof Object) {
return await Promise.resolve(formattedResult);
} else {
return await scriptClient.do("importByUrl", formattedResult);
}
})
// this.do 只会resolve 不会reject
)) as PromiseFulfilledResult<{ success: boolean; msg: string }>[];
const stat = { success: 0, fail: 0, msg: [] as string[] };
results.forEach(({ value }, index) => {
if (value.success) {
stat.success++;
} else {
stat.fail++;
stat.msg.push(`#${index + 1}: ${value.msg}`);
}
});
return stat;
};
const getSafePopupParent = (p: Element) => {
p = (p.closest("button")?.parentNode as Element) || p; // 確保 ancestor 沒有 button 元素
p = (p.closest("span")?.parentNode as Element) || p; // 確保 ancestor 沒有 span 元素
p = (p.closest(".arco-form-item-control-children")?.parentNode as Element) || p; // 確保 ancestor 沒有 .form-item-control-children 元素
p = (p.closest(".arco-collapse-item-content")?.parentNode as Element) || p; // 確保 ancestor 沒有 .arco-collapse-item-content 元素
p = (p.closest(".arco-card")?.parentNode as Element) || p; // 確保 ancestor 沒有 .arco-card 元素
p = (p.closest("aside")?.parentNode as Element) || p; // 確保 ancestor 沒有 aside 元素
return p;
};
// --- 子组件:提取拖拽遮罩以优化性能 ---
const DropzoneOverlay: React.FC<{ active: boolean; text: string }> = React.memo(({ active, text }) => {
if (!active) return null;
return (
<div
className="sc-inset-0"
style={{
position: "absolute",
zIndex: 100,
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "grey",
fontSize: 36,
backdropFilter: "blur(4px)",
background: "var(--color-fill-2)",
opacity: 0.8,
}}
>
{text}
</div>
);
});
DropzoneOverlay.displayName = "DropzoneOverlay";
const MainLayout: React.FC<{
children: ReactNode;
className: string;
pageName?: string;
}> = ({ children, className, pageName }) => {
const [modal, contextHolder] = Modal.useModal();
const { colorThemeState, updateColorTheme } = useAppContext();
const importRef = useRef<RefTextAreaType>(null);
const [importVisible, setImportVisible] = useState(false);
const [showLanguage, setShowLanguage] = useState(false);
const { t } = useTranslation();
const showImportResult = (stat: TImportStat) => {
if (!stat) return;
modal.info!({
title: t("script_import_result"),
content: (
<Space direction="vertical" style={{ width: "100%" }}>
<div style={{ textAlign: "center" }}>
<Space size="small" style={{ fontSize: 18 }}>
<IconCheckCircle style={{ color: "green" }} />
{stat.success}
{""}
<IconCloseCircle style={{ color: "red" }} />
{stat.fail}
</Space>
</div>
{stat.msg.length > 0 && (
<>
<b>{t("failure_info") + ":"}</b>
{stat.msg}
</>
)}
</Space>
),
});
};
const importByUrlsLocal = async (urls: string[]): Promise<void> => {
const stat = await importByUrls(urls);
if (stat) showImportResult(stat);
};
const onDrop = (acceptedFiles: FileWithPath[]) => {
// 本地的文件在当前页面处理,打开安装页面,将FileSystemFileHandle传递过去
// 实现本地文件的监听
const stat: TImportStat = { success: 0, fail: 0, msg: [] };
Promise.all(
acceptedFiles.map(async (aFile) => {
try {
// 解析看看是不是一个标准的script文件
// 如果是,则打开安装页面
let fileHandle = aFile.handle;
if (!fileHandle) {
// 如果是file,直接使用blob的形式安装
if (aFile instanceof FileSystemFileHandle) {
fileHandle = aFile;
} else if (aFile instanceof File) {
// 清理 import-local files 避免同文件不再触发onChange
(document.getElementById("import-local") as HTMLInputElement).value = "";
const blob = new Blob([aFile], { type: "text/javascript" });
const url = makeBlobURL({ blob, persistence: false }) as string; // 生成一个临时的URL
const result = await scriptClient.importByUrl(url);
if (result.success) {
stat.success++;
} else {
stat.fail++;
stat.msg.push(...result.msg);
}
return;
} else {
throw new Error("Invalid Local File Access");
}
}
const file = await fileHandle.getFile();
if (!file.name || !file.size) {
throw new Error("No Read Access Right for File");
}
// 先检查内容,后弹出安装页面
const checkOk = await Promise.allSettled([
file.text().then((code) => prepareScriptByCode(code, `file:///*resp-check*/${file.name}`)),
simpleDigestMessage(`f=${file.name}\ns=${file.size},m=${file.lastModified}`),
]);
if (checkOk[0].status === "rejected" || !checkOk[0].value || checkOk[1].status === "rejected") {
throw new Error(t("script_import_failed"));
}
const fid = checkOk[1].value;
await saveHandle(fid, fileHandle); // fileHandle以DB方式传送至安装页面
// 打开安装页面
const installWindow = window.open(`/src/install.html?file=${fid}`, "_blank");
if (!installWindow) {
throw new Error(t("install_page_open_failed"));
}
stat.success++;
} catch (e: any) {
stat.fail++;
stat.msg.push(e.message);
}
})
).then(() => {
showImportResult(stat);
});
};
const { getRootProps, getInputProps, isDragActive } = useDropzone({
accept: { "text/javascript": [".js"] },
onDrop,
noClick: true,
noKeyboard: true,
});
// 当dragzone使用时,在<body>加入.dragzone-active,控制CSS行为
// 只改CSS,不要改动React元件的任何状态,否则会触发重绘计算
useEffect(() => {
document.body.classList.toggle("dragzone-active", isDragActive);
}, [isDragActive]);
// 使用 useMemo 缓存语言列表,避免每次重绘都执行循环,然后生成新的参考
const languageList = useMemo(() => {
const list = Object.keys(i18n.store.data)
.filter((key) => key !== "ach-UG")
.map((key) => ({
key,
title: i18n.store.data[key].title as string,
}));
return [...list, { key: "help", title: t("help_translate") }];
}, [t]);
useEffect(() => {
// 当没有匹配语言时显示语言按钮
matchLanguage().then((result) => {
if (!result) {
setShowLanguage(true);
}
});
}, []);
const handleImport = async () => {
const urls = importRef.current!.dom.value.split("\n").filter((v) => v);
importByUrlsLocal(urls); // 异步却不用等候?
setImportVisible(false); // 不等待 importByUrlsLocal?
};
return (
<ConfigProvider
renderEmpty={() => {
return <Empty description={t("no_data")} />;
}}
locale={arcoLocale(i18n.language)}
componentConfig={{
Select: {
getPopupContainer: (node) => {
return getSafePopupParent(node as Element);
},
},
}}
getPopupContainer={(node) => {
return getSafePopupParent(node.parentNode as Element);
}}
>
{contextHolder}
<Layout className={"tw-min-h-screen"}>
<Layout.Header
style={{
height: "50px",
borderBottom: "1px solid var(--color-neutral-3)",
}}
className="tw-flex tw-items-center tw-justify-between tw-px-4"
>
<Modal
title={t("import_link")}
visible={importVisible}
onOk={handleImport}
onCancel={() => {
setImportVisible(false);
}}
>
<Input.TextArea
ref={importRef}
rows={8}
placeholder={t("import_script_placeholder")}
defaultValue=""
onKeyDown={(e) => {
if (e.ctrlKey && e.key === "Enter") {
e.preventDefault();
handleImport();
}
}}
/>
</Modal>
<div className="tw-flex tw-flex-row tw-items-center">
<img style={{ height: "40px" }} src="/assets/logo.png" alt="ScriptCat" />
<Typography.Title heading={4} className="!tw-m-0">
{"ScriptCat"}
</Typography.Title>
</div>
<Space size="small" className="action-tools">
{pageName === "options" && (
<Dropdown
droplist={
<Menu style={{ maxHeight: "100%", width: "calc(100% + 10px)" }}>
<Menu.Item key="/script/editor">
<a href="#/script/editor">
<RiFileCodeLine /> {t("create_user_script")}
</a>
</Menu.Item>
<Menu.Item key="background">
<a href="#/script/editor?template=background">
<RiTerminalBoxLine /> {t("create_background_script")}
</a>
</Menu.Item>
<Menu.Item key="crontab">
<a href="#/script/editor?template=crontab">
<RiTimerLine /> {t("create_scheduled_script")}
</a>
</Menu.Item>
<Menu.Item
key="import_local"
onClick={() => {
if ("showOpenFilePicker" in window) {
// 使用新的文件打开接口,解决无法监听本地文件的问题
//@ts-ignore
window
.showOpenFilePicker({
multiple: true,
types: [
{
description: "JavaScript",
accept: { "text/javascript": [".js"] },
},
],
})
.then((handles: any) => {
onDrop(handles as FileWithPath[]);
});
} else {
// 旧的方式,无法监听本地文件变更
document.getElementById("import-local")?.click();
}
}}
>
<RiImportLine /> {t("import_by_local")}
</Menu.Item>
<Menu.Item
key="link"
onClick={() => {
setImportVisible(true);
}}
>
<IconLink /> {t("import_link")}
</Menu.Item>
</Menu>
}
position="bl"
>
<Button
type="text"
size="small"
style={{
color: "var(--color-text-1)",
}}
className="!tw-text-size-sm"
>
<RiPlayListAddLine /> {t("create_script")} <IconDown />
</Button>
</Dropdown>
)}
<Dropdown
droplist={
<Menu
onClickMenuItem={(key) => {
const theme = key as "auto" | "light" | "dark";
updateColorTheme(theme);
}}
selectedKeys={[colorThemeState]}
>
<Menu.Item key="light">
<IconSunFill /> {t("light")}
</Menu.Item>
<Menu.Item key="dark">
<IconMoonFill /> {t("dark")}
</Menu.Item>
<Menu.Item key="auto">
<IconDesktop /> {t("system_follow")}
</Menu.Item>
</Menu>
}
position="bl"
>
<Button
type="text"
size="small"
icon={
<>
{colorThemeState === "auto" && <IconDesktop />}
{colorThemeState === "light" && <IconSunFill />}
{colorThemeState === "dark" && <IconMoonFill />}
</>
}
style={{
color: "var(--color-text-1)",
}}
className="!tw-text-lg"
/>
</Dropdown>
{showLanguage && (
<Dropdown
droplist={
<Menu>
{languageList.map((value) => (
<Menu.Item
key={value.key}
onClick={() => {
if (value.key === "help") {
window.open("https://crowdin.com/project/scriptcat", "_blank");
return;
}
systemConfig.setLanguage(value.key);
Message.success(t("language_change_tip", { lng: value.key })!);
}}
>
{value.title}
</Menu.Item>
))}
</Menu>
}
>
<Button
type="text"
size="small"
iconOnly
icon={<IconLanguage />}
style={{
color: "var(--color-text-1)",
}}
className="!tw-text-lg"
></Button>
</Dropdown>
)}
</Space>
</Layout.Header>
<Layout
className={`tw-bottom-0 tw-w-full ${className}`}
style={{ background: "var(--color-fill-2)" }}
{...getRootProps({})}
>
<input id="import-local" {...getInputProps({ style: { display: "none" } })} />
{/* 性能关键:抽离遮罩组件,只有 active 变化时此小组件重绘 */}
<DropzoneOverlay active={isDragActive} text={t("drag_script_here_to_upload")} />
{children}
</Layout>
</Layout>
</ConfigProvider>
);
};
export default MainLayout;