feat: leave channel

This commit is contained in:
zerosoul
2022-05-16 23:14:04 +08:00
parent d2c06d69b8
commit 4f6aad0406
12 changed files with 450 additions and 179 deletions
+1
View File
@@ -10,6 +10,7 @@ const whiteList = [
"checkInviteTokenValid",
"getGoogleAuthConfig",
"getLoginConfig",
"getServerVersion",
"getServer",
"getOpenid",
"getMetamaskNonce",
+185 -170
View File
@@ -1,177 +1,192 @@
import { createApi } from '@reduxjs/toolkit/query/react';
import { createApi } from "@reduxjs/toolkit/query/react";
// import toast from "react-hot-toast";
import baseQuery from './base.query';
import BASE_URL, { ContentTypes } from '../config';
import { updateChannel } from '../slices/channels';
import { removeMessage } from '../slices/message';
import { removeChannelSession } from '../slices/message.channel';
import { removeReactionMessage } from '../slices/message.reaction';
import { onMessageSendStarted } from './handlers';
import baseQuery from "./base.query";
import BASE_URL, { ContentTypes } from "../config";
import { updateChannel, removeChannel } from "../slices/channels";
import { removeMessage } from "../slices/message";
import { removeChannelSession } from "../slices/message.channel";
import { removeReactionMessage } from "../slices/message.reaction";
import { onMessageSendStarted } from "./handlers";
export const channelApi = createApi({
reducerPath: 'channelApi',
baseQuery,
refetchOnFocus: true,
endpoints: (builder) => ({
getChannels: builder.query({
query: () => ({ url: `group` })
reducerPath: "channelApi",
baseQuery,
refetchOnFocus: true,
endpoints: (builder) => ({
getChannels: builder.query({
query: () => ({ url: `group` }),
}),
getChannel: builder.query({
query: (id) => ({ url: `group/${id}` }),
}),
leaveChannel: builder.query({
query: (id) => ({ url: `group/${id}/leave` }),
async onQueryStarted(gid, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(removeChannel(gid));
} catch {
console.log("channel update failed");
}
},
}),
createChannel: builder.mutation({
query: (data) => ({
url: "group",
method: "POST",
body: data,
}),
}),
updateChannel: builder.mutation({
query: ({ id, ...data }) => ({
url: `group/${id}`,
method: "PUT",
body: data,
}),
async onQueryStarted(
{ id, name, description },
{ dispatch, queryFulfilled }
) {
// id: who send to ,from_uid: who sent
const patchResult = dispatch(updateChannel({ id, name, description }));
try {
await queryFulfilled;
} catch {
console.log("channel update failed");
patchResult.undo();
}
},
}),
getHistoryMessages: builder.query({
query: ({ gid, mid = 0, limit = 50 }) => ({
url: `/group/${gid}/history?before=${mid}&limit=${limit}`,
}),
// async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
// const {
// ui: { channelSetting },
// channelMessage,
// } = getState();
// try {
// await queryFulfilled;
// dispatch(removeChannel(id));
// if (id == channelSetting) {
// dispatch(toggleChannelSetting());
// }
// // 删掉该channel下的所有消息&reaction
// const mids = channelMessage[id];
// if (mids) {
// dispatch(removeChannelSession(id));
// dispatch(removeMessage(mids));
// dispatch(removeReactionMessage(mids));
// }
// } catch {
// console.log("remove channel error");
// }
// },
}),
createInviteLink: builder.query({
query: (gid) => ({
headers: {
"content-type": "text/plain",
accept: "text/plain",
},
url: `/group/${gid}/create_invite_link`,
responseHandler: (response) => response.text(),
}),
transformResponse: (link) => {
// 替换掉域名
const invite = new URL(link);
return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`;
},
}),
removeChannel: builder.query({
query: (id) => ({
url: `group/${id}`,
method: "DELETE",
}),
async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
const { channelMessage } = getState();
try {
await queryFulfilled;
// 删掉该channel下的所有消息&reaction
const mids = channelMessage[id];
if (mids) {
dispatch(removeChannelSession(id));
dispatch(removeMessage(mids));
dispatch(removeReactionMessage(mids));
}
} catch {
console.log("remove channel error");
}
},
}),
sendChannelMsg: builder.mutation({
query: ({ id, content, type = "text", properties = "" }) => ({
headers: {
"content-type": ContentTypes[type],
"X-Properties": properties
? btoa(unescape(encodeURIComponent(JSON.stringify(properties))))
: "",
},
url: `group/${id}/send`,
method: "POST",
body: type == "file" ? JSON.stringify(content) : content,
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, "channel");
},
}),
addMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/add`,
method: "POST",
body: members,
}),
}),
removeMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/remove`,
method: "POST",
body: members,
}),
}),
updateIcon: builder.mutation({
query: ({ gid, image }) => ({
headers: {
"content-type": "image/png",
},
url: `/group/${gid}/avatar`,
method: "POST",
body: image,
}),
async onQueryStarted({ gid }, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(
updateChannel({
id: gid,
icon: `${BASE_URL}/resource/group_avatar?gid=${gid}&t=${new Date().getTime()}`,
})
);
} catch (error) {
console.log("err", error);
}
},
}),
}),
getChannel: builder.query({
query: (id) => ({ url: `group/${id}` })
}),
createChannel: builder.mutation({
query: (data) => ({
url: 'group',
method: 'POST',
body: data
})
}),
updateChannel: builder.mutation({
query: ({ id, ...data }) => ({
url: `group/${id}`,
method: 'PUT',
body: data
}),
async onQueryStarted({ id, name, description }, { dispatch, queryFulfilled }) {
// id: who send to ,from_uid: who sent
const patchResult = dispatch(updateChannel({ id, name, description }));
try {
await queryFulfilled;
} catch {
console.log('channel update failed');
patchResult.undo();
}
}
}),
getHistoryMessages: builder.query({
query: ({ gid, mid = 0, limit = 50 }) => ({
url: `/group/${gid}/history?before=${mid}&limit=${limit}`
})
// async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
// const {
// ui: { channelSetting },
// channelMessage,
// } = getState();
// try {
// await queryFulfilled;
// dispatch(removeChannel(id));
// if (id == channelSetting) {
// dispatch(toggleChannelSetting());
// }
// // 删掉该channel下的所有消息&reaction
// const mids = channelMessage[id];
// if (mids) {
// dispatch(removeChannelSession(id));
// dispatch(removeMessage(mids));
// dispatch(removeReactionMessage(mids));
// }
// } catch {
// console.log("remove channel error");
// }
// },
}),
createInviteLink: builder.query({
query: (gid) => ({
headers: {
'content-type': 'text/plain',
accept: 'text/plain'
},
url: `/group/${gid}/create_invite_link`,
responseHandler: (response) => response.text()
}),
transformResponse: (link) => {
// 替换掉域名
const invite = new URL(link);
return `${location.origin}${invite.pathname}${invite.search}${invite.hash}`;
}
}),
removeChannel: builder.query({
query: (id) => ({
url: `group/${id}`,
method: 'DELETE'
}),
async onQueryStarted(id, { dispatch, getState, queryFulfilled }) {
const { channelMessage } = getState();
try {
await queryFulfilled;
// 删掉该channel下的所有消息&reaction
const mids = channelMessage[id];
if (mids) {
dispatch(removeChannelSession(id));
dispatch(removeMessage(mids));
dispatch(removeReactionMessage(mids));
}
} catch {
console.log('remove channel error');
}
}
}),
sendChannelMsg: builder.mutation({
query: ({ id, content, type = 'text', properties = '' }) => ({
headers: {
'content-type': ContentTypes[type],
'X-Properties': properties
? btoa(unescape(encodeURIComponent(JSON.stringify(properties))))
: ''
},
url: `group/${id}/send`,
method: 'POST',
body: type == 'file' ? JSON.stringify(content) : content
}),
async onQueryStarted(param1, param2) {
await onMessageSendStarted.call(this, param1, param2, 'channel');
}
}),
addMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/add`,
method: 'POST',
body: members
})
}),
removeMembers: builder.mutation({
query: ({ id, members }) => ({
url: `group/${id}/members/remove`,
method: 'POST',
body: members
})
}),
updateIcon: builder.mutation({
query: ({ gid, image }) => ({
headers: {
'content-type': 'image/png'
},
url: `/group/${gid}/avatar`,
method: 'POST',
body: image
}),
async onQueryStarted({ gid }, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(
updateChannel({
id: gid,
icon: `${BASE_URL}/resource/group_avatar?gid=${gid}&t=${new Date().getTime()}`
})
);
} catch (error) {
console.log('err', error);
}
}
})
})
});
export const {
useLazyCreateInviteLinkQuery,
useCreateInviteLinkQuery,
useLazyGetHistoryMessagesQuery,
useGetChannelQuery,
useUpdateChannelMutation,
useLazyRemoveChannelQuery,
useGetChannelsQuery,
useCreateChannelMutation,
useSendChannelMsgMutation,
useAddMembersMutation,
useRemoveMembersMutation,
useUpdateIconMutation
useLazyLeaveChannelQuery,
useLazyCreateInviteLinkQuery,
useCreateInviteLinkQuery,
useLazyGetHistoryMessagesQuery,
useGetChannelQuery,
useUpdateChannelMutation,
useLazyRemoveChannelQuery,
useGetChannelsQuery,
useCreateChannelMutation,
useSendChannelMsgMutation,
useAddMembersMutation,
useRemoveMembersMutation,
useUpdateIconMutation,
} = channelApi;
-4
View File
@@ -40,7 +40,6 @@ const channelsSlice = createSlice({
},
updateChannel(state, action) {
const ignoreInPublic = ["add_member", "remove_member"];
// console.log("set channels store", action);
const { id, operation, members = [], ...rest } = action.payload;
const currChannel = state.byId[id];
if (
@@ -48,7 +47,6 @@ const channelsSlice = createSlice({
(currChannel.is_public && ignoreInPublic.includes(operation))
)
return;
switch (operation) {
case "remove_member":
{
@@ -71,9 +69,7 @@ const channelsSlice = createSlice({
console.log("add member to channel", [..._set]);
state.byId[id].members = [..._set];
}
break;
default:
state.byId[id] = { ...state.byId[id], ...rest };
break;
@@ -0,0 +1,53 @@
import { useEffect } from "react";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import useLeaveChannel from "../../hook/useLeaveChannel";
import Modal from "../Modal";
import StyledModal from "../styled/Modal";
import Button from "../styled/Button";
export default function LeaveConfirmModal({ id, closeModal, handleNextStep }) {
const navigateTo = useNavigate();
const { isOwner, leaving, leaveChannel, leaveSuccess } = useLeaveChannel(id);
useEffect(() => {
if (leaveSuccess) {
toast.success("Leave channel successfully!");
closeModal();
navigateTo("/chat");
}
}, [leaveSuccess]);
if (!id) return null;
return (
<Modal id="modal-modal">
<StyledModal
className="compact"
title="Leave Channel"
description={
isOwner
? "You have to transfer the ownership first"
: "Are you sure want to leave this channel?"
}
buttons={
<>
<Button
onClick={closeModal.bind(null, undefined)}
className="cancel"
>
Cancel
</Button>
{isOwner ? (
<Button onClick={handleNextStep} className="main">
Next
</Button>
) : (
<Button onClick={leaveChannel} className="danger">
{leaving ? "Leaving" : `Leave`}
</Button>
)}
</>
}
></StyledModal>
</Modal>
);
}
@@ -0,0 +1,111 @@
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import styled from "styled-components";
import { useNavigate } from "react-router-dom";
import Modal from "../Modal";
import useLeaveChannel from "../../hook/useLeaveChannel";
import StyledModal from "../styled/Modal";
import Button from "../styled/Button";
import Contact from "../Contact";
const UserList = styled.ul`
display: flex;
flex-direction: column;
max-height: 260px;
padding: 16px 0;
overflow-y: scroll;
.user {
cursor: pointer;
display: flex;
align-items: center;
padding: 0 8px;
width: -webkit-fill-available;
&:hover,
&.selected {
background: rgba(116, 127, 141, 0.1);
}
> a {
width: 100%;
}
}
`;
export default function TransferOwnerModal({
id,
closeModal,
withLeave = true,
}) {
const {
transferOwner,
otherMembers,
leaving,
leaveChannel,
leaveSuccess,
transferSuccess,
transfering,
} = useLeaveChannel(id);
const [uid, setUid] = useState(null);
const navigateTo = useNavigate();
const handleSelectUser = (uid) => {
setUid(uid);
};
const handleTransferAndLeave = async () => {
if (!uid) return;
await transferOwner(uid);
if (withLeave) {
await leaveChannel();
}
};
useEffect(() => {
if (transferSuccess && leaveSuccess) {
toast.success("Leave channel successfully!");
closeModal();
navigateTo("/chat");
}
}, [leaveSuccess, transferSuccess, withLeave]);
if (!id) return null;
const operating = leaving || transfering;
return (
<Modal id="modal-modal">
<StyledModal
className="compact"
title="Transfer Ownership"
description={"This cannot be undone."}
buttons={
<>
<Button
onClick={closeModal.bind(null, undefined)}
className="cancel"
>
Cancel
</Button>
<Button
disabled={!uid}
onClick={handleTransferAndLeave}
className="danger"
>
{operating ? "Assigning" : `Assign and Leave`}
</Button>
</>
}
>
<UserList>
{otherMembers.map((id) => {
// const { uid } = u;
return (
<li
key={id}
className={`user ${uid == id ? "selected" : ""}`}
onClick={handleSelectUser.bind(null, id)}
>
<Contact uid={id} interactive={false} />
</li>
);
})}
</UserList>
</StyledModal>
</Modal>
);
}
@@ -0,0 +1,23 @@
import { useState } from "react";
// import styled from "styled-components";
import TransferOwnerModal from "./TransferOwnerModal";
import LeaveConfirmModal from "./LeaveConfirmModal";
export default function LeaveChannel({
id = null,
isOwner = false,
closeModal,
}) {
const [transferOwner, setTransferOwner] = useState(isOwner);
const handleNextStep = () => {
setTransferOwner(true);
};
if (transferOwner)
return <TransferOwnerModal id={id} closeModal={closeModal} />;
return (
<LeaveConfirmModal
id={id}
closeModal={closeModal}
handleNextStep={handleNextStep}
/>
);
}
@@ -115,6 +115,7 @@ export default function StyledSettingContainer({
{dangers.length ? (
<ul className="items danger">
{dangers.map((d) => {
if (!d) return null;
const { title, handler } = d;
return (
<li key={title} onClick={handler} className="item">
+1 -1
View File
@@ -1,7 +1,7 @@
import styled from "styled-components";
const StyledButton = styled.button`
cursor: pointer;
padding: 10px 18px;
padding: 8px 14px;
border: none;
box-sizing: border-box;
box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
+10 -2
View File
@@ -6,6 +6,14 @@ const Styled = styled.div`
border-radius: 8px;
background-color: #fff;
min-width: 440px;
&.compact {
padding: 16px;
min-width: 406px;
.title,
.desc {
text-align: left;
}
}
.title {
text-align: center;
font-weight: 600;
@@ -19,10 +27,10 @@ const Styled = styled.div`
font-size: 14px;
line-height: 20px;
color: #6b7280;
padding-bottom: 32px;
margin-bottom: 8px;
}
.btns {
padding-top: 32px;
padding-top: 16px;
width: 100%;
display: flex;
justify-content: flex-end;
+39
View File
@@ -0,0 +1,39 @@
// import React from 'react'
import { useSelector } from "react-redux";
import {
useUpdateChannelMutation,
useLazyLeaveChannelQuery,
} from "../../app/services/channel";
export default function useLeaveChannel(cid = null) {
const { channel, loginUid } = useSelector((store) => {
return { channel: store.channels.byId[cid], loginUid: store.authData.uid };
});
const [
update,
{ isLoading: transfering, isSuccess: transferSuccess },
] = useUpdateChannelMutation();
const [
leave,
{ isLoading: leaving, isSuccess: leaveSuccess },
] = useLazyLeaveChannelQuery();
const transferOwner = (uid = null) => {
if (!uid) return;
update({ id: cid, owner: uid });
};
const leaveChannel = () => {
if (!cid) return;
leave(cid);
};
const isOwner = loginUid == channel.owner;
const otherMembers = channel.members.filter((m) => m != loginUid);
return {
otherMembers,
transferOwner,
leaveChannel,
leaving,
leaveSuccess,
isOwner,
transfering,
transferSuccess,
};
}
@@ -25,6 +25,7 @@ export default function DeleteConfirmModal({ id, closeModal }) {
return (
<Modal id="modal-modal">
<StyledModal
className="compact"
title="Delete Channel"
description="Are you sure want to delete this channel?"
buttons={
+25 -2
View File
@@ -1,13 +1,22 @@
import { useState } from "react";
import { useSelector } from "react-redux";
import { useParams, useNavigate, useSearchParams } from "react-router-dom";
import LeaveChannel from "../../common/component/LeaveChannel";
import StyledSettingContainer from "../../common/component/StyledSettingContainer";
import DeleteConfirmModal from "./DeleteConfirmModal";
import useNavs from "./navs";
let from = null;
export default function ChannelSetting() {
const { cid } = useParams();
const { isAdmin, loginUid, channel } = useSelector((store) => {
return {
loginUid: store.authData.uid,
isAdmin: store.contacts.byId[store.authData.uid]?.is_admin,
channel: store.channels.byId[cid],
};
});
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { cid } = useParams();
const navs = useNavs(cid);
const flatenNavs = navs
.map(({ items }) => {
@@ -17,6 +26,7 @@ export default function ChannelSetting() {
const navKey = searchParams.get("nav");
from = from ?? (searchParams.get("f") || "/");
const [deleteConfirm, setDeleteConfirm] = useState(false);
const [leaveConfirm, setLeaveConfirm] = useState(false);
const close = () => {
navigate(from);
from = null;
@@ -24,8 +34,14 @@ export default function ChannelSetting() {
const toggleDeleteConfrim = () => {
setDeleteConfirm((prev) => !prev);
};
const toggleLeaveConfrim = () => {
setLeaveConfirm((prev) => !prev);
};
if (!cid) return null;
const currNav = flatenNavs.find((n) => n.name == navKey) || flatenNavs[0];
const canDelete = isAdmin || channel.owner == loginUid;
const canLeave = !channel.is_public;
return (
<>
<StyledSettingContainer
@@ -34,7 +50,11 @@ export default function ChannelSetting() {
title="Channel Setting"
navs={navs}
dangers={[
{
canLeave && {
title: "Leave Channel",
handler: toggleLeaveConfrim,
},
canDelete && {
title: "Delete Channel",
handler: toggleDeleteConfrim,
},
@@ -45,6 +65,9 @@ export default function ChannelSetting() {
{deleteConfirm && (
<DeleteConfirmModal closeModal={toggleDeleteConfrim} id={cid} />
)}
{leaveConfirm && (
<LeaveChannel closeModal={toggleLeaveConfrim} id={cid} />
)}
</>
);
}