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

96 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-10-24 23:37:53 +08:00
import TextField from "@mui/material/TextField";
import Box from "@mui/material/Box";
import CircularProgress from "@mui/material/CircularProgress";
2023-10-25 11:13:56 +08:00
import Stack from "@mui/material/Stack";
2023-10-24 23:37:53 +08:00
import { useI18n } from "../../hooks/I18n";
2024-04-15 18:04:35 +08:00
import { DEFAULT_TRANS_APIS } from "../../config";
2023-10-24 23:37:53 +08:00
import { useEffect, useState } from "react";
2024-04-15 18:04:35 +08:00
import { apiTranslate, apiBaiduLangdetect } from "../../apis";
2023-10-26 12:24:24 +08:00
import CopyBtn from "./CopyBtn";
2024-04-16 00:54:37 +08:00
import Typography from "@mui/material/Typography";
2023-10-24 23:37:53 +08:00
export default function TranCont({
text,
translator,
fromLang,
toLang,
toLang2 = "en",
2023-10-24 23:37:53 +08:00
transApis,
2024-04-16 00:54:37 +08:00
simpleStyle,
2023-10-24 23:37:53 +08:00
}) {
const i18n = useI18n();
const [trText, setTrText] = useState("");
2024-04-15 18:04:35 +08:00
const [loading, setLoading] = useState(true);
2023-10-24 23:37:53 +08:00
const [error, setError] = useState("");
useEffect(() => {
(async () => {
try {
setLoading(true);
setTrText("");
setError("");
2024-04-15 18:04:35 +08:00
let to = toLang;
if (toLang !== toLang2 && toLang2 !== "none") {
const detectLang = await apiBaiduLangdetect(text);
if (detectLang === toLang) {
2024-04-15 18:04:35 +08:00
to = toLang2;
}
}
2023-10-27 13:55:24 +08:00
const apiSetting =
transApis[translator] || DEFAULT_TRANS_APIS[translator];
2023-10-24 23:37:53 +08:00
const tranRes = await apiTranslate({
text,
translator,
fromLang,
2024-04-15 18:04:35 +08:00
toLang: to,
2023-10-24 23:37:53 +08:00
apiSetting,
});
setTrText(tranRes[0]);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
})();
2024-04-15 18:04:35 +08:00
}, [text, translator, fromLang, toLang, toLang2, transApis]);
2023-10-24 23:37:53 +08:00
2024-04-16 00:54:37 +08:00
if (simpleStyle) {
return (
<Box>
<Typography style={{ whiteSpace: "pre-line" }}>{trText}</Typography>
</Box>
);
}
2023-10-24 23:37:53 +08:00
return (
2024-04-15 18:04:35 +08:00
<Box>
<TextField
size="small"
label={i18n("translated_text")}
// disabled
fullWidth
multiline
value={trText}
helperText={error}
InputProps={{
startAdornment: loading ? <CircularProgress size={16} /> : null,
endAdornment: (
<Stack
direction="row"
sx={{
position: "absolute",
right: 0,
top: 0,
}}
>
<CopyBtn text={trText} />
</Stack>
),
}}
/>
</Box>
2023-10-24 23:37:53 +08:00
);
}