refactor: upload Modal

This commit is contained in:
zerosoul
2022-03-28 20:43:32 +08:00
parent 28bc1cfbcd
commit d07b0e9e91
7 changed files with 157 additions and 137 deletions
@@ -1,108 +0,0 @@
import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
// import toast from "react-hot-toast";
// import { useNavigate } from "react-router-dom";
import { useSendChannelMsgMutation } from "../../../../app/services/channel";
import { useSendMsgMutation } from "../../../../app/services/contact";
import Modal from "../../Modal";
import { formatBytes } from "../../../utils";
import Button from "../../styled/Button";
import StyledWrapper from "./styled";
export default function UploadModal({
type = "user",
sendTo = 0,
files = [],
closeModal,
}) {
// const dispatch = useDispatch();
const from_uid = useSelector((store) => store.authData.uid);
const [
sendChannelMsg,
{ isLoading: channelSending },
] = useSendChannelMsgMutation();
const [sendUserMsg, { isLoading: userSending }] = useSendMsgMutation();
const [properties, setProperties] = useState([]);
useEffect(() => {
files.forEach((file, idx) => {
const { name, size, type } = file;
setProperties((prevs) => {
prevs[idx] = { name, size, type };
return prevs;
});
// var fileReader = new FileReader();
// fileReader.onloadend = (e) => {
// let dataUrl = e.target.result;
// let tmp = new Image();
// tmp.src = dataUrl;
// tmp.onload = function () {
// console.log("image load", this.width, this.height);
// setProperties((prevs) => {
// prevs[idx].width = this.width;
// prevs[idx].height = this.height;
// return prevs;
// });
// };
// };
// fileReader.readAsDataURL(file);
});
}, [files]);
const handleUpload = () => {
const uploadFn = type == "user" ? sendUserMsg : sendChannelMsg;
uploadFn({
id: sendTo,
content: files[0],
properties: { ...properties[0], local_id: new Date().getTime() },
type: "image",
from_uid,
});
closeModal();
};
if (!sendTo) return null;
return (
<Modal>
<StyledWrapper
title={"Upload a file"}
description="Photos accept jpg, png, max size limit to 10M."
buttons={
<>
<Button className="cancel" onClick={closeModal}>
Cancel
</Button>
<Button
className="upload"
disabled={channelSending || userSending}
onClick={handleUpload}
>
{channelSending || userSending ? "Uploading" : `Upload`}
</Button>
</>
}
className="animate__animated animate__fadeInDown animate__faster"
>
<ul className="list">
{files.map((f, idx) => {
console.log({ f });
return (
<li key={idx} className="item">
<img
src={URL.createObjectURL(f)}
alt="thumb"
className="thumb"
/>
<div className="right">
<div className="name">
<span className="input">{f.name}</span>
{/* <i className="tip">(click title to change name)</i> */}
</div>
<i className="size">{formatBytes(f.size)}</i>
</div>
</li>
);
})}
</ul>
</StyledWrapper>
</Modal>
);
}
@@ -0,0 +1,34 @@
import { useState, useEffect } from "react";
import { formatBytes, isTreatAsImage, getFileIcon } from "../../utils";
export default function FileItem({ file = null }) {
const [icon, setIcon] = useState(null);
useEffect(() => {
if (file) {
const { type, name } = file;
if (isTreatAsImage(file)) {
setIcon(
<img src={URL.createObjectURL(file)} alt="thumb" className="thumb" />
);
return;
}
console.log("file type", type, name);
setIcon(getFileIcon(type, name));
}
}, [file]);
console.log("current file", file);
if (!file) return null;
const { name, size } = file;
return (
<li className="item">
{icon}
<div className="right">
<div className="name">
<span className="input">{name}</span>
{/* <i className="tip">(click title to change name)</i> */}
</div>
<i className="size">{formatBytes(size)}</i>
</div>
</li>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { useEffect } from "react";
import { useSelector } from "react-redux";
import FileItem from "./FileItem";
import useSendImageMessage from "../../hook/useSendImageMessage";
import useSendFileMessage from "../../hook/useSendFileMessage";
import Modal from "../Modal";
import Button from "../styled/Button";
import { isTreatAsImage } from "../../utils";
import StyledWrapper from "./styled";
export default function UploadModal({
type = "user",
sendTo = 0,
files = [],
closeModal,
}) {
const from_uid = useSelector((store) => store.authData.uid);
const {
sendImageMessage,
isSending: isSendingImage,
isSuccess: sendImageSuccess,
} = useSendImageMessage({
context: type,
from: from_uid,
to: sendTo,
});
const {
sendFileMessage,
progress,
isSending: isSendingFile,
isSuccess: sendFileSuccess,
} = useSendFileMessage({
context: type,
from: from_uid,
to: sendTo,
});
const handleUpload = () => {
const file = files[0];
// const { type } = file;
if (isTreatAsImage(file)) {
sendImageMessage(file);
} else {
sendFileMessage(file);
}
};
useEffect(() => {
if (sendFileSuccess || sendImageSuccess) {
closeModal();
}
}, [sendImageSuccess, sendFileSuccess]);
if (!sendTo) return null;
console.log("upload file modal", files, sendTo);
const isSending = isSendingFile || isSendingImage;
return (
<Modal>
<StyledWrapper
title={"Upload a file"}
description="Photos accept jpg, png, max size limit to 10M."
buttons={
<>
<Button className="cancel" onClick={closeModal}>
Cancel
</Button>
<Button
className="upload"
disabled={isSending}
onClick={handleUpload}
>
{isSending
? `Uploading (${Math.floor(progress * 100)}%)`
: `Upload`}
</Button>
</>
}
>
<ul className="list">
{files.map((f, idx) => {
console.log({ f });
return <FileItem key={idx} file={f} />;
})}
</ul>
</StyledWrapper>
</Modal>
);
}
@@ -1,5 +1,5 @@
import styled from "styled-components";
import StyledModal from "../../styled/Modal";
import StyledModal from "../styled/Modal";
const StyledWrapper = styled(StyledModal)`
.list {
padding-top: 32px;
+25 -2
View File
@@ -3,6 +3,7 @@ import { useDrop } from "react-dnd";
import { NativeTypes } from "react-dnd-html5-backend";
import styled from "styled-components";
import ImagePreviewModal from "../../common/component/ImagePreviewModal";
import UploadModal from "../../common/component/UploadModal";
const StyledWrapper = styled.article`
position: relative;
@@ -75,21 +76,35 @@ export default function Layout({
children,
header,
contacts = null,
setDragFiles,
dropFiles = [],
type = "channel",
to = null,
}) {
const messagesContainer = useRef(null);
const [files, setFiles] = useState([]);
const [previewImage, setPreviewImage] = useState(null);
const [{ isActive }, drop] = useDrop(() => ({
accept: [NativeTypes.FILE],
drop({ files }) {
console.log("drop files", files);
if (files.length) {
setDragFiles([...files]);
setFiles((prevs) => [...prevs, ...files]);
}
},
collect: (monitor) => ({
isActive: monitor.canDrop() && monitor.isOver(),
}),
}));
useEffect(() => {
if (dropFiles.length) {
setFiles((prevs) => [...prevs, ...dropFiles]);
}
}, [dropFiles]);
const resetFiles = () => {
setFiles([]);
};
const closePreviewModal = () => {
setPreviewImage(null);
};
@@ -144,6 +159,14 @@ export default function Layout({
</div>
</div>
</StyledWrapper>
{files.length !== 0 && (
<UploadModal
type={type}
files={files}
sendTo={to}
closeModal={resetFiles}
/>
)}
</>
);
}
+9 -25
View File
@@ -1,6 +1,6 @@
// import React from 'react';
import { useState } from "react";
import { NavLink, useParams } from "react-router-dom";
import { useParams } from "react-router-dom";
import { useSelector } from "react-redux";
import { MdAdd } from "react-icons/md";
@@ -8,7 +8,7 @@ import { AiOutlineCaretDown } from "react-icons/ai";
import StyledWrapper from "./styled";
import Search from "../../common/component/Search";
import Contact from "../../common/component/Contact";
// import Contact from "../../common/component/Contact";
import CurrentUser from "../../common/component/CurrentUser";
import ChannelChat from "./ChannelChat";
import DMChat from "./DMChat";
@@ -20,9 +20,8 @@ import DMList from "./DMList";
export default function ChatPage() {
const [channelDropFiles, setChannelDropFiles] = useState([]);
const [userDropFiles, setUserDropFiles] = useState([]);
const { contactsData, sessionUids } = useSelector((store) => {
const { sessionUids } = useSelector((store) => {
return {
contactsData: store.contacts.byId,
sessionUids: store.userMessage.ids,
};
});
@@ -40,7 +39,9 @@ export default function ChatPage() {
const listEle = currentTarget.parentElement.parentElement;
listEle.classList.toggle("collapse");
};
const tmpSessionUser = contactsData[user_id];
const tmpUid =
sessionUids.findIndex((i) => i == user_id) > -1 ? null : user_id;
console.log("temp uid", tmpUid);
return (
<>
{channelModalVisible && (
@@ -89,27 +90,10 @@ export default function ChatPage() {
/>
</h3>
<nav className="nav">
<DMList uids={sessionUids} setDropFiles={setUserDropFiles} />
{user_id && sessionUids.findIndex((i) => i == user_id) == -1 && (
<NavLink className="session" to={`/chat/dm/${user_id}`}>
<Contact
compact
interactive={false}
className="avatar"
uid={user_id}
<DMList
uids={tmpUid ? [...sessionUids, tmpUid] : sessionUids}
setDropFiles={setUserDropFiles}
/>
<div className="details">
<div className="up">
<span className="name">{tmpSessionUser.name}</span>
<time></time>
</div>
<div className="down">
<div className="msg"></div>
</div>
</div>
</NavLink>
)}
</nav>
</div>
<CurrentUser />
+1
View File
@@ -83,6 +83,7 @@ const StyledWrapper = styled.div`
display: flex;
justify-content: space-between;
.msg {
min-height: 18px;
font-weight: normal;
font-size: 12px;
line-height: 18px;