add context menus

This commit is contained in:
Gabe Yuan
2023-11-21 11:20:05 +08:00
parent df4cfc0fbc
commit 433e811821
12 changed files with 156 additions and 29 deletions

View File

@@ -1,8 +1,9 @@
import { useState, useEffect } from "react";
import { useState, useEffect, useCallback } from "react";
import TranBtn from "./TranBtn";
import TranBox from "./TranBox";
import { shortcutRegister } from "../../libs/shortcut";
import { sleep } from "../../libs/utils";
import { MSG_TRANSLATE_SELECTED, DEFAULT_TRANSEL_SHORTCUT } from "../../config";
export default function Slection({ tranboxSetting, transApis }) {
const [showBox, setShowBox] = useState(false);
@@ -16,36 +17,47 @@ export default function Slection({ tranboxSetting, transApis }) {
y: (window.innerHeight - 400) / 2,
});
async function handleMouseup(e) {
await sleep(10);
const handleClick = (e) => {
e.stopPropagation();
setShowBtn(false);
setText(selectedText);
setShowBox(true);
};
const handleTranSelected = useCallback(() => {
setShowBtn(false);
const selectedText = window.getSelection()?.toString()?.trim() || "";
if (!selectedText) {
setShowBtn(false);
return;
}
setSelText(selectedText);
setShowBtn(true);
setPosition({ x: e.clientX, y: e.clientY });
}
const handleClick = (e) => {
e.stopPropagation();
setShowBtn(false);
setText(selectedText);
if (!showBox) {
setShowBox(true);
}
};
setShowBox(true);
}, []);
useEffect(() => {
async function handleMouseup(e) {
await sleep(10);
const selectedText = window.getSelection()?.toString()?.trim() || "";
setSelText(selectedText);
if (!selectedText) {
setShowBtn(false);
return;
}
!tranboxSetting.hideTranBtn && setShowBtn(true);
setPosition({ x: e.clientX, y: e.clientY });
}
window.addEventListener("mouseup", handleMouseup);
return () => {
window.removeEventListener("mouseup", handleMouseup);
};
}, []);
}, [tranboxSetting.hideTranBtn]);
useEffect(() => {
const clearShortcut = shortcutRegister(
@@ -58,7 +70,25 @@ export default function Slection({ tranboxSetting, transApis }) {
return () => {
clearShortcut();
};
}, [tranboxSetting.tranboxShortcut, setShowBox]);
}, [tranboxSetting.tranboxShortcut]);
useEffect(() => {
const clearShortcut = shortcutRegister(
tranboxSetting.transelShortcut || DEFAULT_TRANSEL_SHORTCUT,
handleTranSelected
);
return () => {
clearShortcut();
};
}, [tranboxSetting.transelShortcut, handleTranSelected]);
useEffect(() => {
window.addEventListener(MSG_TRANSLATE_SELECTED, handleTranSelected);
return () => {
window.removeEventListener(MSG_TRANSLATE_SELECTED, handleTranSelected);
};
}, [handleTranSelected]);
return (
<>