dev.....!

This commit is contained in:
Gabe Yuan
2023-08-31 13:38:06 +08:00
parent aa795e2731
commit 4486ad353c
15 changed files with 50 additions and 41 deletions

View File

@@ -10,7 +10,7 @@ import {
PROMPT_PLACE_TO, PROMPT_PLACE_TO,
KV_SALT_SYNC, KV_SALT_SYNC,
} from "../config"; } from "../config";
import { detectLang } from "../libs"; import { tryDetectLang } from "../libs";
import { sha256 } from "../libs/utils"; import { sha256 } from "../libs/utils";
/** /**
@@ -163,8 +163,8 @@ export const apiTranslate = async ({
} else if (translator === OPT_TRANS_OPENAI) { } else if (translator === OPT_TRANS_OPENAI) {
const res = await apiOpenaiTranslate(translator, q, to, from, setting); const res = await apiOpenaiTranslate(translator, q, to, from, setting);
trText = res?.choices?.[0].message.content; trText = res?.choices?.[0].message.content;
const sLang = await detectLang(q); const sLang = await tryDetectLang(q);
const tLang = await detectLang(trText); const tLang = await tryDetectLang(trText);
isSame = q === trText || (sLang && tLang && sLang === tLang); isSame = q === trText || (sLang && tLang && sLang === tLang);
} }

View File

@@ -9,7 +9,7 @@ import {
CMD_TOGGLE_STYLE, CMD_TOGGLE_STYLE,
} from "./config"; } from "./config";
import { getSettingWithDefault, tryInitDefaultData } from "./libs/storage"; import { getSettingWithDefault, tryInitDefaultData } from "./libs/storage";
import { trySyncAll } from "./libs/sync"; import { trySyncSettingAndRules } from "./libs/sync";
import { fetchData, fetchPool } from "./libs/fetch"; import { fetchData, fetchPool } from "./libs/fetch";
import { sendTabMsg } from "./libs/msg"; import { sendTabMsg } from "./libs/msg";
import { trySyncAllSubRules } from "./libs/subRules"; import { trySyncAllSubRules } from "./libs/subRules";
@@ -29,7 +29,7 @@ browser.runtime.onStartup.addListener(async () => {
console.log("browser onStartup"); console.log("browser onStartup");
// 同步数据 // 同步数据
await trySyncAll(true); await trySyncSettingAndRules(true);
// 清除缓存 // 清除缓存
const setting = await getSettingWithDefault(); const setting = await getSettingWithDefault();

View File

@@ -27,9 +27,14 @@ export function useStorage(key, defaultVal = null) {
useEffect(() => { useEffect(() => {
(async () => { (async () => {
setData(await storage.getObj(key)); const val = await storage.getObj(key);
if (val) {
setData(val);
} else if (defaultVal) {
await storage.setObj(key, defaultVal);
}
})(); })();
}, [key]); }, [key, defaultVal]);
return { data, save, update, remove }; return { data, save, update, remove };
} }

View File

@@ -1,6 +1,6 @@
import { useEffect } from "react"; import { useEffect } from "react";
import { useState } from "react"; import { useState } from "react";
import { detectLang } from "../libs"; import { tryDetectLang } from "../libs";
import { apiTranslate } from "../apis"; import { apiTranslate } from "../apis";
/** /**
@@ -22,8 +22,8 @@ export function useTranslate(q, rule, setting) {
try { try {
setLoading(true); setLoading(true);
const deLang = await detectLang(q); const deLang = await tryDetectLang(q);
if (toLang.includes(deLang)) { if (deLang && toLang.includes(deLang)) {
setSamelang(true); setSamelang(true);
} else { } else {
const [trText, isSame] = await apiTranslate({ const [trText, isSame] = await apiTranslate({

View File

@@ -1,5 +1,5 @@
import { isExt, isGm } from "./client"; import { isExt, isGm } from "./client";
import { sendMsg } from "./msg"; import { sendBgMsg } from "./msg";
import { taskPool } from "./pool"; import { taskPool } from "./pool";
import { import {
MSG_FETCH, MSG_FETCH,
@@ -172,7 +172,7 @@ export const fetchData = async (
export const fetchPolyfill = async (input, { isBg = false, ...opts } = {}) => { export const fetchPolyfill = async (input, { isBg = false, ...opts } = {}) => {
// 插件 // 插件
if (isExt && !isBg) { if (isExt && !isBg) {
const res = await sendMsg(MSG_FETCH, { input, opts }); const res = await sendBgMsg(MSG_FETCH, { input, opts });
if (res.error) { if (res.error) {
throw new Error(res.error); throw new Error(res.error);
} }
@@ -188,9 +188,9 @@ export const fetchPolyfill = async (input, { isBg = false, ...opts } = {}) => {
* @param {*} interval * @param {*} interval
* @param {*} limit * @param {*} limit
*/ */
export const fetchUpdate = async (interval, limit) => { export const updateFetchPool = async (interval, limit) => {
if (isExt) { if (isExt) {
const res = await sendMsg(MSG_FETCH_LIMIT, { interval, limit }); const res = await sendBgMsg(MSG_FETCH_LIMIT, { interval, limit });
if (res.error) { if (res.error) {
throw new Error(res.error); throw new Error(res.error);
} }
@@ -202,9 +202,9 @@ export const fetchUpdate = async (interval, limit) => {
/** /**
* 清空任务池 * 清空任务池
*/ */
export const fetchClear = async () => { export const clearFetchPool = async () => {
if (isExt) { if (isExt) {
const res = await sendMsg(MSG_FETCH_CLEAR); const res = await sendBgMsg(MSG_FETCH_CLEAR);
if (res.error) { if (res.error) {
throw new Error(res.error); throw new Error(res.error);
} }

View File

@@ -17,11 +17,11 @@ export const tryClearCaches = async () => {
* @param {*} q * @param {*} q
* @returns * @returns
*/ */
export const detectLang = async (q) => { export const tryDetectLang = async (q) => {
try { try {
const res = await browser?.i18n?.detectLanguage(q); const res = await browser?.i18n?.detectLanguage(q);
return res?.languages?.[0]?.language; return res?.languages?.[0]?.language;
} catch (err) { } catch (err) {
console.log("[detect lang]", err); console.log("[detect lang]", err.message);
} }
}; };

View File

@@ -6,8 +6,8 @@ import { browser } from "./browser";
* @param {*} args * @param {*} args
* @returns * @returns
*/ */
export const sendMsg = (action, args) => export const sendBgMsg = (action, args) =>
browser?.runtime?.sendMessage({ action, args }); browser.runtime.sendMessage({ action, args });
/** /**
* 发送消息给当前页面 * 发送消息给当前页面
@@ -16,6 +16,6 @@ export const sendMsg = (action, args) =>
* @returns * @returns
*/ */
export const sendTabMsg = async (action, args) => { export const sendTabMsg = async (action, args) => {
const tabs = await browser?.tabs.query({ active: true, currentWindow: true }); const tabs = await browser.tabs.query({ active: true, currentWindow: true });
return await browser?.tabs.sendMessage(tabs[0].id, { action, args }); return browser.tabs.sendMessage(tabs[0].id, { action, args });
}; };

View File

@@ -68,5 +68,5 @@ export const loadOrFetchSubRules = async (url) => {
if (rules?.length) { if (rules?.length) {
return rules; return rules;
} }
return await syncSubRules(url); return syncSubRules(url);
}; };

View File

@@ -117,12 +117,12 @@ export const syncShareRules = async ({ rules, syncUrl, syncKey }) => {
* 同步个人设置和规则 * 同步个人设置和规则
* @returns * @returns
*/ */
export const syncAll = async (isBg = false) => { export const syncSettingAndRules = async (isBg = false) => {
await syncSetting(isBg); await syncSetting(isBg);
await syncRules(isBg); await syncRules(isBg);
}; };
export const trySyncAll = async (isBg = false) => { export const trySyncSettingAndRules = async (isBg = false) => {
await trySyncSetting(isBg); await trySyncSetting(isBg);
await trySyncRules(isBg); await trySyncRules(isBg);
}; };

View File

@@ -10,7 +10,7 @@ import {
SHADOW_KEY, SHADOW_KEY,
} from "../config"; } from "../config";
import Content from "../views/Content"; import Content from "../views/Content";
import { fetchUpdate, fetchClear } from "./fetch"; import { updateFetchPool, clearFetchPool } from "./fetch";
import { debounce } from "./utils"; import { debounce } from "./utils";
/** /**
@@ -90,7 +90,7 @@ export class Translator {
constructor(rule, setting) { constructor(rule, setting) {
const { fetchInterval, fetchLimit } = setting; const { fetchInterval, fetchLimit } = setting;
fetchUpdate(fetchInterval, fetchLimit); updateFetchPool(fetchInterval, fetchLimit);
this._overrideAttachShadow(); this._overrideAttachShadow();
this._setting = setting; this._setting = setting;
@@ -241,7 +241,7 @@ export class Translator {
this._tranNodes.clear(); this._tranNodes.clear();
// 清空任务池 // 清空任务池
fetchClear(); clearFetchPool();
}; };
_reTranslate = debounce(() => { _reTranslate = debounce(() => {

View File

@@ -34,7 +34,12 @@ export const matchValue = (arr, val) => {
* @returns * @returns
*/ */
export const sleep = (delay) => export const sleep = (delay) =>
new Promise((resolve) => setTimeout(resolve, delay)); new Promise((resolve) => {
const timer = setTimeout(() => {
clearTimeout(timer);
resolve();
}, delay);
});
/** /**
* 防抖函数 * 防抖函数

View File

@@ -159,7 +159,7 @@ export default function Draggable({
y: position.y, y: position.y,
}); });
} }
}, [position]); }, [position.x, position.y, position.hide]);
const opacity = useMemo(() => { const opacity = useMemo(() => {
if (snapEdge) { if (snapEdge) {

View File

@@ -37,10 +37,6 @@ export default function Settings() {
}); });
}; };
if (!setting) {
return;
}
const { const {
uiLang, uiLang,
googleUrl, googleUrl,

View File

@@ -7,7 +7,7 @@ import Alert from "@mui/material/Alert";
import Link from "@mui/material/Link"; import Link from "@mui/material/Link";
import { URL_KISS_WORKER } from "../../config"; import { URL_KISS_WORKER } from "../../config";
import { useState } from "react"; import { useState } from "react";
import { syncAll } from "../../libs/sync"; import { syncSettingAndRules } from "../../libs/sync";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import { useAlert } from "../../hooks/Alert"; import { useAlert } from "../../hooks/Alert";
import SyncIcon from "@mui/icons-material/Sync"; import SyncIcon from "@mui/icons-material/Sync";
@@ -31,7 +31,7 @@ export default function SyncSetting() {
e.preventDefault(); e.preventDefault();
try { try {
setLoading(true); setLoading(true);
await syncAll(); await syncSettingAndRules();
alert.success(i18n("data_sync_success")); alert.success(i18n("data_sync_success"));
} catch (err) { } catch (err) {
console.log("[sync all]", err); console.log("[sync all]", err);

View File

@@ -10,7 +10,7 @@ import { useEffect, useState } from "react";
import { isGm } from "../../libs/client"; import { isGm } from "../../libs/client";
import { sleep } from "../../libs/utils"; import { sleep } from "../../libs/utils";
import CircularProgress from "@mui/material/CircularProgress"; import CircularProgress from "@mui/material/CircularProgress";
import { trySyncAll } from "../../libs/sync"; import { trySyncSettingAndRules } from "../../libs/sync";
import { AlertProvider } from "../../hooks/Alert"; import { AlertProvider } from "../../hooks/Alert";
import Link from "@mui/material/Link"; import Link from "@mui/material/Link";
import Divider from "@mui/material/Divider"; import Divider from "@mui/material/Divider";
@@ -27,6 +27,8 @@ export default function Options() {
let i = 0; let i = 0;
for (;;) { for (;;) {
if (window.APP_NAME === process.env.REACT_APP_NAME) { if (window.APP_NAME === process.env.REACT_APP_NAME) {
// 同步数据
await trySyncSettingAndRules();
setReady(true); setReady(true);
break; break;
} }
@@ -38,10 +40,11 @@ export default function Options() {
await sleep(1000); await sleep(1000);
} }
} else {
// 同步数据
await trySyncSettingAndRules();
setReady(true);
} }
// 同步数据
trySyncAll();
})(); })();
}, []); }, []);
@@ -75,7 +78,7 @@ export default function Options() {
); );
} }
if (isGm && !ready) { if (!ready) {
return ( return (
<center> <center>
<Divider> <Divider>