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

100 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";
2025-10-02 21:59:31 +08:00
import { useEffect, useState, useMemo } from "react";
2024-05-22 23:33:30 +08:00
import { apiTranslate } 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";
2024-04-17 10:03:56 +08:00
import Alert from "@mui/material/Alert";
2023-10-24 23:37:53 +08:00
export default function TranCont({
text,
fromLang,
toLang,
2025-10-02 21:59:31 +08:00
apiSlug,
2023-10-24 23:37:53 +08:00
transApis,
simpleStyle = false,
2023-10-24 23:37:53 +08:00
}) {
const i18n = useI18n();
const [trText, setTrText] = useState("");
2025-10-02 21:59:31 +08:00
const [loading, setLoading] = useState(false);
2023-10-24 23:37:53 +08:00
const [error, setError] = useState("");
2025-10-02 21:59:31 +08:00
const apiSetting = useMemo(
() => transApis.find((api) => api.apiSlug === apiSlug),
[transApis, apiSlug]
);
2023-10-24 23:37:53 +08:00
useEffect(() => {
2025-10-02 21:59:31 +08:00
if (!text?.trim() || !apiSetting) {
return;
}
2023-10-24 23:37:53 +08:00
(async () => {
try {
setLoading(true);
setTrText("");
setError("");
2025-09-01 18:56:48 +08:00
const [trText] = await apiTranslate({
2023-10-24 23:37:53 +08:00
text,
fromLang,
2025-10-02 21:59:31 +08:00
toLang,
2023-10-24 23:37:53 +08:00
apiSetting,
});
2025-10-02 21:59:31 +08:00
2025-09-01 18:56:48 +08:00
setTrText(trText);
2023-10-24 23:37:53 +08:00
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
})();
2025-10-02 21:59:31 +08:00
}, [text, fromLang, toLang, apiSetting]);
2023-10-24 23:37:53 +08:00
2024-04-16 00:54:37 +08:00
if (simpleStyle) {
return (
2025-10-02 21:59:31 +08:00
<Box>
2024-04-17 10:03:56 +08:00
{error ? (
<Alert severity="error">{error}</Alert>
) : loading ? (
<CircularProgress size={16} />
) : (
<Typography style={{ whiteSpace: "pre-line" }}>{trText}</Typography>
)}
2024-04-16 00:54:37 +08:00
</Box>
);
}
2023-10-24 23:37:53 +08:00
return (
2025-10-02 21:59:31 +08:00
<Box>
2024-04-15 18:04:35 +08:00
<TextField
size="small"
2025-10-15 22:04:03 +08:00
label={`${i18n("translated_text")} - ${apiSetting.apiName}`}
2024-04-15 18:04:35 +08:00
// 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
);
}