From d08b9a0ca6a3f67d9dc0789068e7c8a9bbef5c75 Mon Sep 17 00:00:00 2001 From: Robert Date: Mon, 11 Mar 2024 23:46:45 +0700 Subject: [PATCH] image upload --- src/widgets/action-editor/ui/ActionEditor.tsx | 94 ++++++++++++++++++- 1 file changed, 90 insertions(+), 4 deletions(-) diff --git a/src/widgets/action-editor/ui/ActionEditor.tsx b/src/widgets/action-editor/ui/ActionEditor.tsx index daec2b0..8242f09 100644 --- a/src/widgets/action-editor/ui/ActionEditor.tsx +++ b/src/widgets/action-editor/ui/ActionEditor.tsx @@ -1,10 +1,12 @@ import { useState } from "react"; +import { uploadFile } from "@/shared/lib/uploadFile"; import type { CommentAction } from "@/entities/action/schema"; import Tabs from "@mui/material/Tabs"; import Tab from "@mui/material/Tab"; import Box from "@mui/material/Box"; import { Button, TextField } from "@mui/material"; +import CircularProgress from "@mui/material/CircularProgress"; import TextFieldsIcon from "@mui/icons-material/TextFields"; import ImageIcon from "@mui/icons-material/Image"; @@ -56,6 +58,10 @@ export default function ActionEditor({ canExit = false, }: ActionEditorProps) { const [value, setValue] = useState(0); + const [loading, setLoading] = useState(false); + + const [imageUrl, setImageUrl] = useState(null); + console.log(imageUrl); const [action, setAction] = useState( initialAction ?? { @@ -66,9 +72,64 @@ export default function ActionEditor({ ); const handleChange = (_: React.SyntheticEvent, newValue: number) => { + if (loading) return; setValue(newValue); }; + async function handleFileChange( + event: React.ChangeEvent, + origin: "image" | "voice", + ) { + if (!event.target.files) return; + const file = event.target.files[0]; + + setLoading(true); + const fileUrl = await uploadFile(file); + + if (!fileUrl) { + alert("К сожалению, не удалось загрузить файл"); + setLoading(false); + return; + } + + if (origin === "image") { + setImageUrl(fileUrl); + } + + setLoading(false); + } + + function handleSave() { + if (!onSave) return; + + if (value === 0) { + if (!action.text) { + alert("Введите текст"); + return; + } + + onSave(actionIndex, { + actionType: action.actionType, + text: action.text, + fileUrls: [], + }); + } else if (value === 1) { + if (!imageUrl) { + alert("Добавьте картинку"); + return; + } + + onSave(actionIndex, { + actionType: action.actionType, + text: action.text === "" ? null : action.text, + fileUrls: [imageUrl], + }); + } else if (value === 2) { + alert("Unsupported"); + return; + } + } + return ( <>
@@ -106,7 +167,32 @@ export default function ActionEditor({ - In progress +
+ await handleFileChange(e, "image")} + /> + {loading && ( +
+ +
+ )} +
+ + + setAction((currentAction) => ({ + ...currentAction, + text: event.target.value, + })) + } + />
@@ -119,6 +205,7 @@ export default function ActionEditor({ {canExit && (