Files
kiss-translator/src/views/Selection/index.js

89 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-10-23 18:02:42 +08:00
import { useState, useEffect } from "react";
2023-10-26 12:24:24 +08:00
import TranBtn from "./TranBtn";
import TranBox from "./TranBox";
2023-10-24 17:58:37 +08:00
import { shortcutRegister } from "../../libs/shortcut";
2023-11-11 17:22:43 +08:00
import { sleep } from "../../libs/utils";
2023-10-23 18:02:42 +08:00
2023-10-24 17:58:37 +08:00
export default function Slection({ tranboxSetting, transApis }) {
2023-10-23 18:02:42 +08:00
const [showBox, setShowBox] = useState(false);
const [showBtn, setShowBtn] = useState(false);
2023-10-24 17:58:37 +08:00
const [selectedText, setSelText] = useState("");
2023-10-23 18:02:42 +08:00
const [text, setText] = useState("");
const [position, setPosition] = useState({ x: 0, y: 0 });
2023-10-25 11:20:05 +08:00
const [boxSize, setBoxSize] = useState({ w: 600, h: 400 });
2023-10-24 17:58:37 +08:00
const [boxPosition, setBoxPosition] = useState({
x: (window.innerWidth - 600) / 2,
2023-10-25 11:20:05 +08:00
y: (window.innerHeight - 400) / 2,
2023-10-24 17:58:37 +08:00
});
2023-10-23 18:02:42 +08:00
2023-11-11 17:22:43 +08:00
async function handleMouseup(e) {
await sleep(10);
2023-10-24 17:58:37 +08:00
const selectedText = window.getSelection()?.toString()?.trim() || "";
if (!selectedText) {
setShowBtn(false);
return;
}
setSelText(selectedText);
setShowBtn(true);
2023-10-23 18:02:42 +08:00
setPosition({ x: e.clientX, y: e.clientY });
}
const handleClick = (e) => {
e.stopPropagation();
setShowBtn(false);
2023-10-24 17:58:37 +08:00
setText(selectedText);
if (!showBox) {
2023-10-23 18:02:42 +08:00
setShowBox(true);
}
};
useEffect(() => {
window.addEventListener("mouseup", handleMouseup);
return () => {
window.removeEventListener("mouseup", handleMouseup);
};
}, []);
2023-10-24 17:58:37 +08:00
useEffect(() => {
const clearShortcut = shortcutRegister(
tranboxSetting.tranboxShortcut,
() => {
setShowBox((pre) => !pre);
}
);
return () => {
clearShortcut();
};
}, [tranboxSetting.tranboxShortcut, setShowBox]);
2023-10-23 18:02:42 +08:00
return (
<>
{showBox && (
<TranBox
2023-10-24 17:58:37 +08:00
text={text}
setText={setText}
boxSize={boxSize}
setBoxSize={setBoxSize}
boxPosition={boxPosition}
setBoxPosition={setBoxPosition}
2023-10-23 18:02:42 +08:00
tranboxSetting={tranboxSetting}
2023-10-24 17:58:37 +08:00
transApis={transApis}
2023-10-23 18:02:42 +08:00
setShowBox={setShowBox}
/>
)}
{showBtn && (
<TranBtn
position={position}
tranboxSetting={tranboxSetting}
onClick={handleClick}
/>
)}
</>
);
}