refactor: lots updates

This commit is contained in:
zerosoul
2022-03-14 11:32:00 +08:00
parent 5d363b5a5f
commit 46cfda76d0
83 changed files with 2018 additions and 1486 deletions
+4 -1
View File
@@ -1,7 +1,8 @@
import { useState, useEffect } from "react";
import { getInitials, getInitialsAvatar } from "../utils";
export default function Avatar({ url, name = "unkonw name", ...rest }) {
const [src, setSrc] = useState(url);
// console.log("avatar url", url);
const [src, setSrc] = useState("");
const handleError = () => {
const tmp = getInitialsAvatar({
initials: getInitials(name),
@@ -14,6 +15,8 @@ export default function Avatar({ url, name = "unkonw name", ...rest }) {
initials: getInitials(name),
});
setSrc(tmp);
} else {
setSrc(url);
}
}, [url, name]);
+15 -15
View File
@@ -15,6 +15,9 @@ import { addChannel } from "../../../app/slices/channels";
import { useCreateChannelMutation } from "../../../app/services/channel";
export default function ChannelModal({ personal = false, closeModal }) {
const { conactsData, loginUid } = useSelector((store) => {
return { conactsData: store.contacts.byId, loginUid: store.authData.uid };
});
const navigateTo = useNavigate();
const dispatch = useDispatch();
const [data, setData] = useState({
@@ -28,9 +31,7 @@ export default function ChannelModal({ personal = false, closeModal }) {
createChannel,
{ isSuccess, isError, isLoading, data: newChannel },
] = useCreateChannelMutation();
const currentUser = useSelector((state) => {
return state.authData.user;
});
const handleToggle = () => {
const { is_public } = data;
setData((prev) => {
@@ -48,6 +49,7 @@ export default function ChannelModal({ personal = false, closeModal }) {
}
createChannel(data);
};
useEffect(() => {
if (isError) {
toast.error("create new channel failed");
@@ -83,7 +85,8 @@ export default function ChannelModal({ personal = false, closeModal }) {
console.log({ data });
};
console.log("contacts", contacts);
if (!currentUser) return null;
const loginUser = conactsData[loginUid];
if (!loginUser) return null;
const { name, members, is_public } = data;
return (
<Modal>
@@ -142,17 +145,14 @@ export default function ChannelModal({ personal = false, closeModal }) {
<ChannelIcon personal={!is_public} className="icon" />
</div>
</div>
{/* admin or */}
{
<div className="private">
<span className="txt normal">Private Channel</span>
<StyledToggle
data-checked={!is_public}
data-disabled={!currentUser?.is_admin}
onClick={handleToggle}
/>
</div>
}
<div className="private">
<span className="txt normal">Private Channel</span>
<StyledToggle
data-checked={!is_public}
data-disabled={!loginUser?.is_admin}
onClick={handleToggle}
/>
</div>
<div className="btns">
<Button onClick={closeModal} className="normal cancel">
Cancel
@@ -4,7 +4,7 @@ import toast from "react-hot-toast";
import { useNavigate, useMatch } from "react-router-dom";
import { useDispatch } from "react-redux";
import { toggleChannelSetting } from "../../../app/slices/ui";
import { deleteChannel } from "../../../app/slices/channels";
import { removeChannel } from "../../../app/slices/channels";
import Modal from "../Modal";
// import BASE_URL from "../../app/config";
import { useLazyRemoveChannelQuery } from "../../../app/services/channel";
@@ -15,14 +15,14 @@ export default function DeleteConfirmModal({ id, closeModal }) {
const navigateTo = useNavigate();
const dispatch = useDispatch();
const pathMatched = useMatch(`/chat/channel/${id}`);
const [removeChannel, { isLoading, isSuccess }] = useLazyRemoveChannelQuery();
const [deleteChannel, { isLoading, isSuccess }] = useLazyRemoveChannelQuery();
const handleDelete = () => {
removeChannel(id);
deleteChannel(id);
};
useEffect(() => {
if (isSuccess) {
toast.success("delete channel successfully!");
dispatch(deleteChannel(id));
dispatch(removeChannel(id));
dispatch(toggleChannelSetting());
if (pathMatched) {
navigateTo("/chat");
@@ -1,7 +1,6 @@
import { useState, useEffect } from "react";
import styled from "styled-components";
import toast from "react-hot-toast";
// import { useSelector } from "react-redux";
import {
useGetChannelQuery,
useUpdateChannelMutation,
+6 -13
View File
@@ -2,13 +2,14 @@ import Overview from "./Overview";
import ManageMembers from "../ManageMembers";
import { useSelector } from "react-redux";
const useNavs = (channelId) => {
const { channels, contacts } = useSelector((store) => {
const { channels, contactIds } = useSelector((store) => {
return {
channels: store.channels,
contacts: store.contacts,
channels: store.channels.byId,
contactIds: store.contacts.ids,
};
});
const ids = channels[channelId]?.members || [];
let ids = channels[channelId]?.members ?? [];
ids = ids.length == 0 ? contactIds : ids;
const navs = [
{
title: "General",
@@ -38,15 +39,7 @@ const useNavs = (channelId) => {
{
name: "members",
title: "Members",
component: (
<ManageMembers
members={
ids.length == 0
? contacts
: contacts.filter((c) => ids.includes(c.uid))
}
/>
),
component: <ManageMembers members={ids} />,
},
],
},
+6 -7
View File
@@ -65,9 +65,8 @@ export default function Contact({
popover = false,
compact = false,
}) {
const contacts = useSelector((store) => store.contacts);
if (!contacts) return null;
const currUser = contacts.find((c) => c.uid == uid);
const curr = useSelector((store) => store.contacts.byId[uid]);
if (!curr) return null;
return (
<StyledWrapper
className={`${interactive ? "interactive" : ""} ${
@@ -81,16 +80,16 @@ export default function Contact({
disabled={!popover}
placement="left"
trigger="click"
content={<Profile data={currUser} type="card" />}
content={<Profile uid={uid} type="card" />}
>
<div className="avatar">
<Avatar url={currUser?.avatar} name={currUser?.name} alt="avatar" />
<Avatar url={curr?.avatar} name={curr?.name} alt="avatar" />
<div
className={`status ${currUser?.online ? "online" : "offline"}`}
className={`status ${curr?.online ? "online" : "offline"}`}
></div>
</div>
</Tippy>
{!compact && <span className="name">{currUser?.name}</span>}
{!compact && <span className="name">{curr?.name}</span>}
</StyledWrapper>
);
}
+2 -6
View File
@@ -1,6 +1,5 @@
import { useRef } from "react";
import styled from "styled-components";
import { useSelector } from "react-redux";
import { NavLink } from "react-router-dom";
import { useOutsideClick } from "rooks";
import useFilteredUsers from "../hook/useFilteredUsers";
@@ -55,15 +54,12 @@ const StyledWrapper = styled.div`
export default function ContactsModal({ closeModal }) {
const wrapperRef = useRef();
const { contacts, updateInput, input } = useFilteredUsers();
const currentUser = useSelector((state) => {
return state.authData.user;
});
useOutsideClick(wrapperRef, closeModal);
const handleSearch = (evt) => {
updateInput(evt.target.value);
console.log("www");
// updateInput(evt.target.value);
};
if (!currentUser) return null;
return (
<Modal>
<StyledWrapper ref={wrapperRef}>
+20 -18
View File
@@ -57,11 +57,13 @@ const StyledWrapper = styled.div`
}
}
`;
export default function CurrentUser({ expand = true }) {
const { user } = useSelector((store) => store.authData);
export default function CurrentUser() {
const currUser = useSelector((store) => {
return store.contacts.byId[store.authData.uid];
});
if (!user) return null;
const { uid, name, avatar } = user;
if (!currUser) return null;
const { uid, name, avatar } = currUser;
return (
<StyledWrapper>
<div className="profile">
@@ -71,20 +73,20 @@ export default function CurrentUser({ expand = true }) {
<span className="id">#{uid}</span>
</div>
</div>
{expand && (
<div className="settings">
<img
src="https://static.nicegoodthings.com/project/rustchat/icon.speaker.svg"
className="icon"
alt="mic icon"
/>
<img
src="https://static.nicegoodthings.com/project/rustchat/icon.mic.svg"
className="icon"
alt="sound icon"
/>
</div>
)}
{/* {expand && ( */}
<div className="settings">
<img
src="https://static.nicegoodthings.com/project/rustchat/icon.speaker.svg"
className="icon"
alt="mic icon"
/>
<img
src="https://static.nicegoodthings.com/project/rustchat/icon.mic.svg"
className="icon"
alt="sound icon"
/>
</div>
{/* )} */}
</StyledWrapper>
);
}
+6 -3
View File
@@ -1,6 +1,7 @@
import { useState, useRef, useEffect } from "react";
import styled from "styled-components";
import { useOutsideClick } from "rooks";
import { useSelector } from "react-redux";
import toast from "react-hot-toast";
import useCopy from "../hook/useCopy";
import { useLazyDeleteContactQuery } from "../../app/services/contact";
@@ -85,6 +86,7 @@ const StyledWrapper = styled.section`
}
`;
export default function ManageMembers({ members = [] }) {
const contacts = useSelector((store) => store.contacts);
const [copied, copy] = useCopy();
const [remove, { isSuccess: removeSuccess }] = useLazyDeleteContactQuery();
const wrapperRef = useRef(null);
@@ -111,6 +113,7 @@ export default function ManageMembers({ members = [] }) {
const handleCopy = (str) => {
copy(str);
};
const uids = !members || members.length == 0 ? contacts.ids : members;
return (
<StyledWrapper>
<div className="intro">
@@ -121,12 +124,12 @@ export default function ManageMembers({ members = [] }) {
</p>
</div>
<ul className="members">
{members.map((m) => {
const { name, email, uid, is_admin } = m;
{uids.map((uid) => {
const { name, email, is_admin } = contacts.byId[uid];
return (
<li key={uid} className="member">
<div className="left">
<Contact compact uid={uid} name={name} interactive={false} />
<Contact compact uid={uid} interactive={false} />
<div className="info">
<span className="name">{name}</span>
<span className="email">{email}</span>
+9 -18
View File
@@ -1,9 +1,9 @@
import { useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import toast from "react-hot-toast";
// import toast from "react-hot-toast";
import { useOutsideClick } from "rooks";
import { setReplyMessage } from "../../../app/slices/message.pending";
import { addReplyingMessage } from "../../../app/slices/message";
import StyledMenu from "../StyledMenu";
import DeleteMessageConfirm from "./DeleteMessageConfirm";
import EmojiPicker from "./EmojiPicker";
@@ -41,10 +41,8 @@ const StyledCmds = styled.ul`
`;
export default function Commands({
contextId = 0,
message = null,
mid = 0,
uid = 0,
reactions = [],
from_uid = 0,
menuVisible,
toggleMenu,
emojiPopVisible,
@@ -54,12 +52,12 @@ export default function Commands({
const dispatch = useDispatch();
const [deleteModalVisible, setDeleteModalVisible] = useState(false);
const currUid = useSelector((store) => store.authData.user.uid);
const currUid = useSelector((store) => store.authData.uid);
const menuRef = useRef(null);
const handleReply = () => {
if (contextId) {
dispatch(setReplyMessage({ id: contextId, msg: message }));
dispatch(addReplyingMessage({ id: contextId, mid }));
}
// toast.success("cooming soon");
};
@@ -78,13 +76,9 @@ export default function Commands({
/>
</li>
{emojiPopVisible && (
<EmojiPicker
reactions={reactions}
mid={mid}
hidePicker={toggleEmojiPopover}
/>
<EmojiPicker mid={mid} hidePicker={toggleEmojiPopover} />
)}
{currUid == uid ? (
{currUid == from_uid ? (
<li className="cmd" onClick={toggleEditMessage}>
<img
src="https://static.nicegoodthings.com/project/rustchat/icon.edit.svg"
@@ -110,7 +104,7 @@ export default function Commands({
{/* <li className="item">Edit Message</li> */}
<li className="item underline">Pin Message</li>
<li className="item">Reply</li>
{currUid == uid && (
{currUid == from_uid && (
<li className="item danger" onClick={toggleDeleteModal}>
Delete Message
</li>
@@ -118,10 +112,7 @@ export default function Commands({
</StyledMenu>
)}
{deleteModalVisible && (
<DeleteMessageConfirm
closeModal={toggleDeleteModal}
message={{ mid, ...message }}
/>
<DeleteMessageConfirm closeModal={toggleDeleteModal} mid={mid} />
)}
</StyledCmds>
);
@@ -7,7 +7,7 @@ import StyledModal from "../styled/Modal";
import Button from "../styled/Button";
import Modal from "../Modal";
import PreviewMessage from "./PreviewMessage";
export default function LogoutConfirmModal({ closeModal, message = null }) {
export default function DeleteMessageConfirmModal({ closeModal, mid = 0 }) {
// const dispatch = useDispatch();
const [deleteMessage, { isLoading, isSuccess }] = useLazyDeleteMessageQuery();
const handleDelete = (evt) => {
@@ -21,8 +21,7 @@ export default function LogoutConfirmModal({ closeModal, message = null }) {
}
}, [isSuccess]);
if (!message) return;
const { mid, ...previewContent } = message;
if (!mid) return null;
return (
<Modal>
<StyledModal
@@ -38,7 +37,7 @@ export default function LogoutConfirmModal({ closeModal, message = null }) {
title="Delete Message"
description="Are you sure want to delete this message?"
>
<PreviewMessage data={previewContent} />
<PreviewMessage mid={mid} />
</StyledModal>
</Modal>
);
+19 -7
View File
@@ -3,7 +3,8 @@
import { useRef } from "react";
import styled from "styled-components";
import { useOutsideClick } from "rooks";
import { useLikeMessageMutation } from "../../../app/services/message";
import { useSelector } from "react-redux";
import { useReactMessageMutation } from "../../../app/services/message";
const StyledPicker = styled.div`
border: 1px solid rgba(0, 0, 0, 0.08);
border-radius: 6px;
@@ -32,13 +33,19 @@ const StyledPicker = styled.div`
}
`;
const emojis = {
thumb_up: "👍",
ok: "👌",
like: "❤️",
["U+1F44D"]: "👍",
["U+1F44C"]: "👌",
["U+2764"]: "❤️",
};
export default function EmojiPicker({ mid, reactions = [], hidePicker }) {
export default function EmojiPicker({ mid, hidePicker }) {
const wrapperRef = useRef(null);
const [reactMessage, { isLoading }] = useLikeMessageMutation();
const [reactMessage, { isLoading }] = useReactMessageMutation();
const { reactionData, currUid } = useSelector((store) => {
return {
reactionData: store.reactionMessage[mid],
currUid: store.authData.uid,
};
});
useOutsideClick(wrapperRef, hidePicker);
const handleReact = (action) => {
console.log("react", action);
@@ -48,9 +55,14 @@ export default function EmojiPicker({ mid, reactions = [], hidePicker }) {
<StyledPicker ref={wrapperRef}>
<ul className={`emojis ${isLoading ? "reacting" : ""}`}>
{Object.entries(emojis).map(([key, emoji]) => {
let reacted =
reactionData &&
reactionData[key] &&
reactionData[key].includes(currUid);
return (
<li
className={`emoji ${reactions.includes(key) ? "reacted" : ""}`}
className={`emoji ${reacted ? "reacted" : ""}`}
key={key}
onClick={handleReact.bind(null, key)}
>
+11 -5
View File
@@ -1,12 +1,16 @@
// import { useEffect, useRef, useState } from "react";
import dayjs from "dayjs";
// import { useSelector } from "react-redux";
import renderContent from "./renderContent";
import Avatar from "../Avatar";
import StyledWrapper from "./styled";
export default function PreviewMessage({ data = null }) {
if (!data) return null;
const { avatar, name, time, content_type, content } = data;
import { useSelector } from "react-redux";
export default function PreviewMessage({ mid = 0 }) {
const { msg, contactsData } = useSelector((store) => {
return { msg: store.message[mid], contactsData: store.contacts.byId };
});
if (!msg) return null;
const { from_uid, created_at, content_type, content } = msg;
const { name, avatar } = contactsData[from_uid];
return (
<StyledWrapper className={`preview`}>
<div className="avatar">
@@ -15,7 +19,9 @@ export default function PreviewMessage({ data = null }) {
<div className="details">
<div className="up">
<span className="name">{name}</span>
<i className="time">{dayjs(time).format("YYYY-MM-DD h:mm:ss A")}</i>
<i className="time">
{dayjs(created_at).format("YYYY-MM-DD h:mm:ss A")}
</i>
</div>
<div className={`down`}>{renderContent(content_type, content)}</div>
</div>
+54
View File
@@ -0,0 +1,54 @@
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import { emojis } from "./EmojiPicker";
const StyledWrapper = styled.span`
display: flex;
gap: 8px;
font-size: 16px;
/* align-items: center; */
.reaction {
position: relative;
display: flex;
align-items: center;
gap: 6px;
em {
font-size: 12px;
color: #999;
}
}
`;
export default function Reaction({ reactions = null }) {
// const {
// messageData,
// reactionMessageData,
// contactsData,
// loginedUser,
// } = useSelector((store) => {
// return {
// reactionMessageData: store.reactionMessage,
// messageData: store.message,
// contactsData: store.contacts.byId,
// loginedUser: store.authData.user,
// };
// });
if (!reactions) return null;
return (
<StyledWrapper className="reactions">
{Object.entries(reactions).map(([reaction, uids]) => {
return uids.length > 0 ? (
<i
className="reaction"
// data-count={count > 1 ? count : ""}
key={reaction}
>
{emojis[reaction]}
{uids.length > 1 ? <em>{`+${uids.length}`} </em> : null}
</i>
) : null;
})}
</StyledWrapper>
);
}
-8
View File
@@ -1,8 +0,0 @@
import React from "react";
import styled from "styled-components";
const Styled = styled.div`
display: flex;
`;
export default function Removed() {
return <Styled>Removed</Styled>;
}
+15
View File
@@ -0,0 +1,15 @@
import React from "react";
import styled from "styled-components";
import { useSelector } from "react-redux";
const Styled = styled.div`
color: #aaa;
font-size: 12px;
margin-bottom: -10px;
/* padding-left: 10px; */
`;
export default function Reply({ mid }) {
const data = useSelector((store) => store.message[mid]);
if (!data) return null;
return <Styled className="reply">{data.content}</Styled>;
}
+42 -72
View File
@@ -1,44 +1,34 @@
import React, { useEffect, useRef, useState } from "react";
import React, { useRef, useState, useEffect } from "react";
import dayjs from "dayjs";
import { useDispatch, useSelector } from "react-redux";
import { useSelector, useDispatch } from "react-redux";
import { useInViewRef } from "rooks";
import Tippy from "@tippyjs/react";
import Reaction from "./Reaction";
import Reply from "./Reply";
import Profile from "../Profile";
import Avatar from "../Avatar";
import { setChannelMsgRead } from "../../../app/slices/message.channel";
import { setUserMsgRead } from "../../../app/slices/message.user";
import { readMessage } from "../../../app/slices/message";
import StyledWrapper from "./styled";
import Commands from "./Commands";
import { emojis } from "./EmojiPicker";
import EditMessage from "./EditMessage";
import renderContent from "./renderContent";
function Message({
reply = null,
gid = "",
mid = "",
uid,
fromUid,
time,
content,
content_type = "text/plain",
unread = false,
pending,
edited = false,
likes = {},
}) {
function Message({ contextId = 0, mid = "" }) {
const [myRef, inView] = useInViewRef();
const [edit, setEdit] = useState(false);
const [emojiPopVisible, setEmojiPopVisible] = useState(false);
const [menuVisible, setMenuVisible] = useState(false);
const disptach = useDispatch();
const avatarRef = useRef(null);
const { contacts, loginedUser } = useSelector((store) => {
return {
contacts: store.contacts,
loginedUser: store.authData.user,
};
});
const { message = {}, reactionMessageData, contactsData } = useSelector(
(store) => {
return {
reactionMessageData: store.reactionMessage,
message: store.message[mid],
contactsData: store.contacts.byId,
};
}
);
const toggleMenu = () => {
setMenuVisible((prev) => !prev);
};
@@ -49,20 +39,30 @@ function Message({
setEmojiPopVisible((prev) => !prev);
};
// useEffect(() => {
// if (!unread) {
// if (!read) {
// avatarRef.current?.scrollIntoView();
// }
// }, [unread]);
// }, [read]);
// console.log("message", mid, messageData[mid]);
useEffect(() => {
if (inView && unread) {
const setMsgRead = gid ? setChannelMsgRead : setUserMsgRead;
disptach(setMsgRead({ id: gid || uid, mid }));
if (inView && !message.read) {
disptach(readMessage(mid));
}
}, [gid, mid, uid, unread, inView]);
if (!contacts) return null;
const currUser = contacts.find((c) => c.uid == fromUid) || {};
}, [mid, message, inView]);
if (!message) return null;
const {
reply_mid,
from_uid: fromUid,
created_at: time,
sending,
content,
content_type = "text/plain",
edited,
} = message;
const reactions = reactionMessageData[mid];
const currUser = contactsData[fromUid] || {};
return (
<StyledWrapper
ref={myRef}
@@ -74,36 +74,20 @@ function Message({
interactive
placement="left"
trigger="click"
content={<Profile data={currUser} type="card" />}
content={<Profile uid={fromUid} type="card" />}
>
<div className="avatar" data-uid={uid} ref={avatarRef}>
<div className="avatar" data-uid={fromUid} ref={avatarRef}>
<Avatar url={currUser.avatar} name={currUser.name} />
</div>
</Tippy>
<div className="details">
{reply && <div className="reply">{reply.content}</div>}
{reply_mid && <Reply mid={reply_mid} />}
<div className="up">
<span className="name">{currUser.name}</span>
<i className="time">{dayjs(time).format("YYYY-MM-DD h:mm:ss A")}</i>
{likes && (
<span className="likes">
{Object.entries(likes).map(([reaction, uids]) => {
return uids.length > 0 ? (
<i
className="like"
// data-count={count > 1 ? count : ""}
key={reaction}
>
{emojis[reaction]}
{uids.length > 1 ? <em>{`+${uids.length}`} </em> : null}
</i>
) : null;
})}
</span>
)}
{reactions && <Reaction reactions={reactions} />}
</div>
<div className={`down ${pending ? "pending" : ""}`}>
<div className={`down ${sending ? "sending" : ""}`}>
{edit ? (
<EditMessage
content={content}
@@ -117,23 +101,9 @@ function Message({
</div>
{!edit && (
<Commands
contextId={gid || uid}
message={{
mid,
from_uid: fromUid,
name: currUser.name,
avatar: currUser.avatar,
time,
content,
content_type,
}}
reactions={Object.entries(likes ?? {})
.filter(([, uids = []]) => uids.includes(loginedUser.uid))
.map(([reaction]) => {
return reaction;
})}
contextId={contextId}
mid={mid}
uid={fromUid}
from_uid={fromUid}
toggleMenu={toggleMenu}
menuVisible={menuVisible}
emojiPopVisible={emojiPopVisible}
+2 -31
View File
@@ -35,12 +35,7 @@ const StyledMsg = styled.div`
display: flex;
flex-direction: column;
gap: 8px;
.reply {
color: #aaa;
font-size: 12px;
margin-bottom: -10px;
/* padding-left: 10px; */
}
.up {
display: flex;
align-items: center;
@@ -57,30 +52,6 @@ const StyledMsg = styled.div`
font-size: 12px;
line-height: 18px;
}
.likes {
display: flex;
gap: 8px;
font-size: 16px;
/* align-items: center; */
.like {
position: relative;
display: flex;
align-items: center;
gap: 6px;
em {
font-size: 12px;
color: #999;
}
/* &:after {
content: attr(data-count);
position: absolute;
top: -4px;
right: -8px;
font-size: 12px;
color: #999;
} */
}
}
}
.down {
user-select: text;
@@ -95,7 +66,7 @@ const StyledMsg = styled.div`
color: #999;
font-size: 10px;
}
&.pending {
&.sending {
opacity: 0.5;
}
.img {
@@ -22,7 +22,10 @@ import {
clearAuthData,
updateLoginedUserByLogs,
} from "../../../app/slices/auth.data";
import { setUsersVersion, setAfterMid } from "../../../app/slices/visit.mark";
import {
updateUsersVersion,
updateAfterMid,
} from "../../../app/slices/visit.mark";
import { setReady } from "../../../app/slices/ui";
import useMessageHandler from "./useMessageHandler";
@@ -117,7 +120,7 @@ const NotificationHub = () => {
{
console.log("users snapshot");
const { version } = data;
dispatch(setUsersVersion({ version }));
dispatch(updateUsersVersion({ version }));
}
break;
case "users_log":
@@ -179,7 +182,7 @@ const NotificationHub = () => {
// 更新after_mid
if (data.detail.type == "normal") {
dispatch(setAfterMid({ mid: data.mid }));
dispatch(updateAfterMid({ mid: data.mid }));
}
}
break;
@@ -51,7 +51,7 @@ export default function useMessageHandler(currUser) {
dispatch(
addMessage({
id, // 自己发的 就不用标记未读
unread: !self,
read: !self,
...common,
})
);
+5 -3
View File
@@ -1,7 +1,7 @@
// import React from "react";
// import toast from "react-hot-toast";
// import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { NavLink } from "react-router-dom";
import { BsChatText } from "react-icons/bs";
import { RiUserAddLine } from "react-icons/ri";
@@ -62,9 +62,11 @@ const StyledWrapper = styled.div`
}
}
`;
export default function Profile({ data = null, type = "embed" }) {
export default function Profile({ uid = null, type = "embed" }) {
const data = useSelector((store) => store.contacts.byId[uid]);
if (!data) return null;
const { uid, name, email, avatar } = data;
// console.log("profile", data);
const { name, email, avatar } = data;
return (
<StyledWrapper className={type}>
<Avatar className="avatar" url={avatar} name={name} />
+5 -1
View File
@@ -34,6 +34,7 @@ const StyledWrapper = styled.div`
cursor: pointer;
}
.popup {
z-index: 999;
user-select: none;
box-shadow: 0px 20px 25px rgba(31, 41, 55, 0.1),
0px 10px 10px rgba(31, 41, 55, 0.04);
@@ -63,7 +64,9 @@ const StyledWrapper = styled.div`
}
`;
export default function Search() {
const currentUser = useSelector((store) => store.authData.user);
const currentUser = useSelector(
(store) => store.contacts.byId[store.authData.uid]
);
const [popupVisible, setPopupVisible] = useState(false);
const [channelModalVisible, setChannelModalVisible] = useState(false);
const [contactsModalVisible, setContactsModalVisible] = useState(false);
@@ -85,6 +88,7 @@ export default function Search() {
const handleCloseModal = () => {
setChannelModalVisible(false);
};
console.log("searching");
return (
<StyledWrapper>
{channelModalVisible && (
+28
View File
@@ -0,0 +1,28 @@
// import React from 'react'
import { useDispatch, useSelector } from "react-redux";
import { MdClose } from "react-icons/md";
import { removeReplyingMessage } from "../../../app/slices/message";
export default function Replying({ id, mid }) {
const { msg, contactsData } = useSelector((store) => {
return { contactsData: store.contacts.byId, msg: store.message[mid] };
});
const dispatch = useDispatch();
const removeReply = () => {
dispatch(removeReplyingMessage(id));
};
if (!msg) return null;
const { from_uid } = msg;
const user = contactsData[from_uid];
return (
<div className="reply">
<span className="txt">
Replying to
<em>{user?.name}</em>
</span>
<button className="close" onClick={removeReply}>
<MdClose size={20} color="#78787C" />
</button>
</div>
);
}
@@ -2,11 +2,8 @@ import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
// import toast from "react-hot-toast";
// import { useNavigate } from "react-router-dom";
// import { useSelector, useDispatch } from "react-redux";
import { useSendChannelMsgMutation } from "../../../../app/services/channel";
import { useSendMsgMutation } from "../../../../app/services/contact";
// import { addChannelMsg } from "../../../../app/slices/message.channel";
// import { addUserMsg } from "../../../../app/slices/message.user";
import Modal from "../../Modal";
import Button from "../../styled/Button";
@@ -19,7 +16,7 @@ export default function UploadModal({
closeModal,
}) {
// const dispatch = useDispatch();
const from_uid = useSelector((store) => store.authData.user.uid);
const from_uid = useSelector((store) => store.authData.uid);
const [
sendChannelMsg,
{ isLoading: channelSending },
+140 -132
View File
@@ -1,140 +1,148 @@
import { useState, useEffect, useRef } from 'react';
import { MdAdd, MdClose } from 'react-icons/md';
import TextareaAutosize from 'react-textarea-autosize';
import { useDispatch, useSelector } from 'react-redux';
import { useKey } from 'rooks';
import { useState, useEffect, useRef } from "react";
import { MdAdd } from "react-icons/md";
import TextareaAutosize from "react-textarea-autosize";
import { useDispatch, useSelector } from "react-redux";
import { useKey } from "rooks";
import { removeReplyMessage } from '../../../app/slices/message.pending';
import { useSendChannelMsgMutation } from '../../../app/services/channel';
import { useSendMsgMutation } from '../../../app/services/contact';
import { useReplyMessageMutation } from '../../../app/services/message';
import StyledSend from './styled';
import useFiles from './useFiles';
import UploadModal from './UploadModal';
import EmojiPicker from './EmojiPicker';
import { removeReplyingMessage } from "../../../app/slices/message";
import { useSendChannelMsgMutation } from "../../../app/services/channel";
import { useSendMsgMutation } from "../../../app/services/contact";
import { useReplyMessageMutation } from "../../../app/services/message";
import StyledSend from "./styled";
import useFiles from "./useFiles";
import UploadModal from "./UploadModal";
import EmojiPicker from "./EmojiPicker";
import Replying from "./Replying";
const Types = {
channel: '#',
user: '@'
channel: "#",
user: "@",
};
export default function Send({
name,
type = 'channel',
// 发给谁,或者是channel,或者是user
id = '',
dragFiles = []
name,
type = "channel",
// 发给谁,或者是channel,或者是user
id = "",
dragFiles = [],
}) {
const [replyMessage] = useReplyMessageMutation();
const { files, setFiles, resetFiles } = useFiles([]);
const inputRef = useRef();
const [shift, setShift] = useState(false);
const [enter, setEnter] = useState(false);
const [msg, setMsg] = useState('');
const dispatch = useDispatch();
// 谁发的
const {
from_uid,
reply = null,
contacts
} = useSelector((store) => {
return {
contacts: store.contacts,
from_uid: store.authData.user.uid,
reply: store.pendingMessage.reply[id]
};
});
useEffect(() => {
if (dragFiles.length) {
setFiles((prev) => [...prev, ...dragFiles]);
}
}, [dragFiles]);
const [replyMessage] = useReplyMessageMutation();
const { files, setFiles, resetFiles } = useFiles([]);
const inputRef = useRef();
const [shift, setShift] = useState(false);
const [enter, setEnter] = useState(false);
const [msg, setMsg] = useState("");
const dispatch = useDispatch();
// 谁发的
const { from_uid, replying_mid = null } = useSelector((store) => {
return {
from_uid: store.authData.uid,
replying_mid: store.message.replying[id],
};
});
useEffect(() => {
if (dragFiles.length) {
setFiles((prev) => [...prev, ...dragFiles]);
}
}, [dragFiles]);
const [sendMsg, { isLoading: userSending }] = useSendMsgMutation();
const [sendChannelMsg, { isLoading: channelSending }] = useSendChannelMsgMutation();
const sendMessage = type == 'channel' ? sendChannelMsg : sendMsg;
const sendingMessage = userSending || channelSending;
useKey(
'Shift',
(e) => {
console.log('shift', e.type);
setShift(e.type == 'keydown');
},
{ eventTypes: ['keydown', 'keyup'], target: inputRef }
);
const handleMsgChange = (evt) => {
if (enter && !shift) {
handleSendMessage();
} else {
setMsg(evt.target.value);
}
};
const handleInputKeydown = (e) => {
console.log('keydown event', e);
setEnter(e.key === 'Enter');
};
const selectEmoji = (emoji) => {
setMsg((prev) => `${prev}${emoji}`);
};
useEffect(() => {
inputRef.current.focus();
}, [msg, reply]);
const handleUpload = (evt) => {
setFiles([...evt.target.files]);
};
const handleSendMessage = () => {
if (!msg || !id || sendingMessage) return;
if (reply) {
replyMessage({ mid: reply.mid, content: msg });
dispatch(removeReplyMessage(id));
} else {
sendMessage({ id, content: msg, from_uid });
}
setMsg('');
};
const removeReply = () => {
dispatch(removeReplyMessage(id));
};
return (
<>
<StyledSend className={`send ${reply ? 'reply' : ''}`}>
{reply && (
<div className="reply">
<span className="txt">
Replying to
<em>{contacts.find((c) => c.uid == reply.from_uid)?.name}</em>
</span>
<button className="close" onClick={removeReply}>
<MdClose size={20} color="#78787C" />
</button>
</div>
)}
<div className="addon">
<MdAdd size={20} color="#78787C" />
<input multiple={true} onChange={handleUpload} type="file" name="file" id="file" />
</div>
<div className="input">
<TextareaAutosize
autoFocus
onFocus={(e) =>
e.currentTarget.setSelectionRange(e.currentTarget.value.length, e.currentTarget.value.length)
}
ref={inputRef}
className="content"
maxRows={8}
minRows={1}
onKeyDown={handleInputKeydown}
onChange={handleMsgChange}
value={msg}
placeholder={`${Types[type]}${name} 发消息`}
/>
</div>
<div className="emoji">
<EmojiPicker selectEmoji={selectEmoji} />
</div>
</StyledSend>
{files.length !== 0 && (
<UploadModal type={type} files={files} sendTo={id} closeModal={resetFiles} />
)}
</>
);
const [sendMsg, { isLoading: userSending }] = useSendMsgMutation();
const [
sendChannelMsg,
{ isLoading: channelSending },
] = useSendChannelMsgMutation();
const sendMessage = type == "channel" ? sendChannelMsg : sendMsg;
const sendingMessage = userSending || channelSending;
useKey(
"Shift",
(e) => {
console.log("shift", e.type);
setShift(e.type == "keydown");
},
{ eventTypes: ["keydown", "keyup"], target: inputRef }
);
const handleMsgChange = (evt) => {
if (enter && !shift) {
handleSendMessage();
} else {
setMsg(evt.target.value);
}
};
const handleInputKeydown = (e) => {
console.log("keydown event", e);
setEnter(e.key === "Enter");
};
const selectEmoji = (emoji) => {
setMsg((prev) => `${prev}${emoji}`);
};
useEffect(() => {
inputRef.current.focus();
}, [msg, replying_mid]);
const handleUpload = (evt) => {
setFiles([...evt.target.files]);
};
const handleSendMessage = () => {
if (!msg || !id || sendingMessage) return;
if (replying_mid) {
console.log("replying", replying_mid);
replyMessage({
id,
reply_mid: replying_mid,
content: msg,
context: type,
from_uid,
});
dispatch(removeReplyingMessage(id));
} else {
sendMessage({ id, content: msg, from_uid });
}
setMsg("");
};
return (
<>
<StyledSend className={`send ${replying_mid ? "reply" : ""}`}>
{replying_mid && <Replying mid={replying_mid} id={id} />}
<div className="addon">
<MdAdd size={20} color="#78787C" />
<input
multiple={true}
onChange={handleUpload}
type="file"
name="file"
id="file"
/>
</div>
<div className="input">
<TextareaAutosize
autoFocus
onFocus={(e) =>
e.currentTarget.setSelectionRange(
e.currentTarget.value.length,
e.currentTarget.value.length
)
}
ref={inputRef}
className="content"
maxRows={8}
minRows={1}
onKeyDown={handleInputKeydown}
onChange={handleMsgChange}
value={msg}
placeholder={`${Types[type]}${name} 发消息`}
/>
</div>
<div className="emoji">
<EmojiPicker selectEmoji={selectEmoji} />
</div>
</StyledSend>
{files.length !== 0 && (
<UploadModal
type={type}
files={files}
sendTo={id}
closeModal={resetFiles}
/>
)}
</>
);
}
+5 -3
View File
@@ -114,7 +114,9 @@ export default function MyAccount() {
uploadAvatar,
{ isSuccess: uploadSuccess },
] = useUpdateAvatarMutation();
const { user } = useSelector((store) => store.authData);
const loginUser = useSelector((store) => {
return store.contacts.byId[store.authData.uid];
});
useEffect(() => {
if (uploadSuccess) {
toast.success("update avatar successfully!");
@@ -127,8 +129,8 @@ export default function MyAccount() {
const closeBasicEditModal = () => {
setEditModal(null);
};
if (!user) return null;
const { uid, avatar, name, email } = user;
if (!loginUser) return null;
const { uid, avatar, name, email } = loginUser;
return (
<>
<StyledWrapper>
+4 -2
View File
@@ -66,7 +66,9 @@ const StyledWrapper = styled.div`
}
`;
export default function Overview() {
const currUser = useSelector((store) => store.authData.user);
const loginUser = useSelector((store) => {
return store.contacts.byId[store.authData.uid];
});
const [changed, setChanged] = useState(false);
const [values, setValues] = useState(null);
const { data, refetch } = useGetServerQuery();
@@ -119,7 +121,7 @@ export default function Overview() {
if (!values) return null;
const { name, description, logo } = values;
const isAdmin = currUser?.is_admin;
const isAdmin = loginUser?.is_admin;
return (
<StyledWrapper>
<div className="logo">
@@ -1,6 +1,5 @@
// import { useState, useEffect } from "react";
import StyledContainer from "./StyledContainer";
// import { useSelector } from "react-redux";
import Input from "../../styled/Input";
import Textarea from "../../styled/Textarea";
import Label from "../../styled/Label";
@@ -1,6 +1,5 @@
// import { useState, useEffect } from "react";
import StyledContainer from "./StyledContainer";
// import { useSelector } from "react-redux";
import Input from "../../styled/Input";
import Textarea from "../../styled/Textarea";
import Toggle from "../../styled/Toggle";
+1 -9
View File
@@ -4,16 +4,8 @@ import ConfigFirebase from "./config/Firebase";
import ConfigSMTP from "./config/SMTP";
import Notifications from "./Notifications";
import ManageMembers from "../ManageMembers";
import { useSelector } from "react-redux";
import ConfigAgora from "./config/Agora";
const useNavs = () => {
const { contacts } = useSelector((store) => {
return {
currUser: store.authData.user,
channels: store.channels,
contacts: store.contacts,
};
});
const navs = [
{
title: "General",
@@ -54,7 +46,7 @@ const useNavs = () => {
{
name: "members",
title: "Members",
component: <ManageMembers members={contacts} />,
component: <ManageMembers />,
},
],
},
+32
View File
@@ -0,0 +1,32 @@
import { useRef, useEffect } from "react";
// import { useDebounce } from "rooks";
function useChatScroll(dep) {
const ref = useRef();
// const updateScrollTop = useDebounce(() => {
// console.log("chat scroll", ref);
// if (ref.current) {
// setTimeout(() => {
// ref.current.scrollTop = ref.current.scrollHeight;
// }, 50);
// }
// }, 100);
// const updateScrollTop = () => {
// console.log("chat scroll", ref);
// if (ref.current) {
// setTimeout(() => {
// ref.current.scrollTop = ref.current.scrollHeight;
// }, 100);
// }
// };
useEffect(() => {
console.log("chat scroll", ref);
if (ref.current) {
setTimeout(() => {
ref.current.scrollTop = ref.current.scrollHeight;
}, 20);
}
}, [dep]);
return ref;
}
export default useChatScroll;
+3 -3
View File
@@ -2,8 +2,8 @@ import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
export default function useFilteredUsers() {
const [input, setInput] = useState("");
const contacts = useSelector((store) => store.contacts);
const [filteredUsers, setFilteredUsers] = useState(contacts);
const contacts = useSelector((store) => Object.values(store.contacts.byId));
const [filteredUsers, setFilteredUsers] = useState([]);
useEffect(() => {
if (!input) {
setFilteredUsers(contacts);
@@ -16,7 +16,7 @@ export default function useFilteredUsers() {
})
);
}
}, [input, contacts]);
}, [input]);
const updateInput = (val) => {
setInput(val);
};
+19 -15
View File
@@ -1,30 +1,34 @@
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useDispatch, batch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { clearAuthData } from "../../app/slices/auth.data";
import { clearMark } from "../../app/slices/visit.mark";
import { clearChannels } from "../../app/slices/channels";
import { clearContacts } from "../../app/slices/contacts";
import { clearChannelMsg } from "../../app/slices/message.channel";
import { clearUserMsg } from "../../app/slices/message.user";
import { clearPendingMsg } from "../../app/slices/message.pending";
import { resetAuthData } from "../../app/slices/auth.data";
import { resetFootprint } from "../../app/slices/footprint";
import { resetChannels } from "../../app/slices/channels";
import { resetContacts } from "../../app/slices/contacts";
import { resetChannelMsg } from "../../app/slices/message.channel";
import { resetUserMsg } from "../../app/slices/message.user";
import { resetReactionMessage } from "../../app/slices/message.reaction";
import { resetMessage } from "../../app/slices/message";
import { useLazyLogoutQuery } from "../../app/services/auth";
export default function useLogout() {
const dispatch = useDispatch();
const navigate = useNavigate();
const [logout, { isLoading, isSuccess }] = useLazyLogoutQuery();
const clearLocalData = () => {
dispatch(clearMark());
dispatch(clearChannelMsg());
dispatch(clearUserMsg());
dispatch(clearChannels());
dispatch(clearContacts());
dispatch(clearPendingMsg());
batch(() => {
dispatch(resetFootprint());
dispatch(resetChannelMsg());
dispatch(resetUserMsg());
dispatch(resetChannels());
dispatch(resetContacts());
dispatch(resetMessage());
dispatch(resetReactionMessage());
});
};
useEffect(() => {
if (isSuccess) {
dispatch(clearAuthData());
dispatch(resetAuthData());
navigate("/login");
}
}, [isSuccess]);