refactor: guest mode

This commit is contained in:
Tristan Yang
2022-09-02 08:59:19 +08:00
parent 3247de57db
commit 265bf11ad0
20 changed files with 140 additions and 366 deletions
-11
View File
@@ -10,22 +10,11 @@ import { fillUsers } from "../slices/users";
import { fillFootprint } from "../slices/footprint"; import { fillFootprint } from "../slices/footprint";
import { fillFileMessage } from "../slices/message.file"; import { fillFileMessage } from "../slices/message.file";
import { fillUI } from "../slices/ui"; import { fillUI } from "../slices/ui";
import { useAppSelector } from "../store";
const useRehydrate = () => { const useRehydrate = () => {
const [iterated, setIterated] = useState(false); const [iterated, setIterated] = useState(false);
const dispatch = useDispatch(); const dispatch = useDispatch();
const { isGuest } = useAppSelector((store) => {
return {
isGuest: store.authData.user?.create_by == "guest"
};
});
const rehydrate = async () => { const rehydrate = async () => {
// 如果是游客,直接忽略
if (isGuest) {
setIterated(true);
return;
}
const rehydrateData = { const rehydrateData = {
channels: [], channels: [],
users: [], users: [],
-3
View File
@@ -46,9 +46,6 @@ listenerMiddleware.startListening({
// console.log("effect opt", action); // console.log("effect opt", action);
if (!window.CACHE && prefix !== "__rtkq") return; if (!window.CACHE && prefix !== "__rtkq") return;
const currentState = listenerApi.getState() as RootState; const currentState = listenerApi.getState() as RootState;
// 如果是guest,则忽略
const isGuest = currentState.authData.user?.create_by === "guest";
if (isGuest) return;
const state = prefix == "__rtkq" ? null : currentState[prefix]; const state = prefix == "__rtkq" ? null : currentState[prefix];
switch (prefix) { switch (prefix) {
case "__rtkq": case "__rtkq":
+4
View File
@@ -12,6 +12,7 @@ import { User } from "../../types/user";
interface State { interface State {
initialized: boolean; initialized: boolean;
guest: boolean;
user: User | undefined; user: User | undefined;
token: string; token: string;
expireTime: number; expireTime: number;
@@ -20,6 +21,7 @@ interface State {
const loginUser = localStorage.getItem(KEY_LOGIN_USER) || ""; const loginUser = localStorage.getItem(KEY_LOGIN_USER) || "";
const initialState: State = { const initialState: State = {
initialized: true, initialized: true,
guest: false,
user: loginUser ? JSON.parse(loginUser) : undefined, user: loginUser ? JSON.parse(loginUser) : undefined,
token: localStorage.getItem(KEY_TOKEN) || "", token: localStorage.getItem(KEY_TOKEN) || "",
expireTime: Number(localStorage.getItem(KEY_EXPIRE) || +new Date()), expireTime: Number(localStorage.getItem(KEY_EXPIRE) || +new Date()),
@@ -28,6 +30,7 @@ const initialState: State = {
const emptyState: State = { const emptyState: State = {
initialized: true, initialized: true,
guest: false,
user: undefined, user: undefined,
token: "", token: "",
expireTime: +new Date(), expireTime: +new Date(),
@@ -43,6 +46,7 @@ const authDataSlice = createSlice({
const { uid } = user; const { uid } = user;
state.initialized = initialized; state.initialized = initialized;
state.user = user; state.user = user;
// state.guest = user.create_by == "guest";
state.token = token; state.token = token;
state.refreshToken = refresh_token; state.refreshToken = refresh_token;
// 当前时间往后推expire时长 // 当前时间往后推expire时长
+16 -4
View File
@@ -1,6 +1,7 @@
import React, { FC, ReactElement } from "react"; import { FC, ReactElement, useEffect } from "react";
import { Navigate } from "react-router-dom"; import { Navigate } from "react-router-dom";
import { useGetInitializedQuery } from "../../app/services/auth"; import { useGetInitializedQuery, useLazyGuestLoginQuery } from "../../app/services/auth";
import { useGetLoginConfigQuery } from "../../app/services/server";
import { useAppSelector } from "../../app/store"; import { useAppSelector } from "../../app/store";
interface Props { interface Props {
@@ -9,11 +10,22 @@ interface Props {
} }
const RequireAuth: FC<Props> = ({ children, redirectTo = "/login" }) => { const RequireAuth: FC<Props> = ({ children, redirectTo = "/login" }) => {
const { isLoading } = useGetInitializedQuery(); const { data: loginConfig, isLoading: fetchingLoginConfig } = useGetLoginConfigQuery();
const { isLoading: checkingInitial } = useGetInitializedQuery();
const [guestLogin] = useLazyGuestLoginQuery();
const { token, initialized } = useAppSelector((store) => store.authData); const { token, initialized } = useAppSelector((store) => store.authData);
if (isLoading) return null; useEffect(() => {
// 已初始化 , 没token,并且开启了guest,则guest自动登录
if (initialized && !token && loginConfig?.guest) {
guestLogin();
}
}, [token, initialized, loginConfig]);
// 初始化和login配置检查
if (checkingInitial || fetchingLoginConfig) return null;
// 未初始化 则先走setup 流程 // 未初始化 则先走setup 流程
if (!initialized) return <Navigate to={`/onboarding`} replace />; if (!initialized) return <Navigate to={`/onboarding`} replace />;
// 开启guest 并且没token 则等待guest登录结果
if (loginConfig?.guest && !token) return null;
return token ? children : <Navigate to={redirectTo} replace />; return token ? children : <Navigate to={redirectTo} replace />;
}; };
+55
View File
@@ -0,0 +1,55 @@
// import React from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { resetAuthData } from "../../app/slices/auth.data";
import { useAppSelector } from "../../app/store";
import Button from "../../common/component/styled/Button";
import useLogout from "../../common/hook/useLogout";
const Styled = styled.div`
display: flex;
align-items: center;
flex-direction: column;
.title {
font-style: normal;
font-weight: 700;
font-size: 30px;
line-height: 38px;
color: #344054;
}
.details {
display: flex;
flex-direction: column;
.desc {
margin: 12px 0;
font-weight: 400;
font-size: 14px;
line-height: 20px;
color: #98a2b3;
}
}
`;
// type Props = {};
const GuestBlankPlaceholder = () => {
const dispatch = useDispatch();
const { clearLocalData } = useLogout();
const navigateTo = useNavigate();
const serverName = useAppSelector((store) => store.server.name);
const handleSignIn = () => {
dispatch(resetAuthData());
clearLocalData();
navigateTo("/login");
};
return (
<Styled>
<h2 className="title">Welcome to {serverName} server</h2>
<div className="details">
<span className="desc">Please sign in to send a message</span>
<Button onClick={handleSignIn} className="small">{`Sign In`}</Button>
</div>
</Styled>
);
};
export default GuestBlankPlaceholder;
@@ -2,10 +2,10 @@
// import { NavLink } from "react-router-dom"; // import { NavLink } from "react-router-dom";
import useMessageFeed from "../../../common/hook/useMessageFeed"; import useMessageFeed from "../../../common/hook/useMessageFeed";
import ChannelIcon from "../../../common/component/ChannelIcon"; import ChannelIcon from "../../../common/component/ChannelIcon";
import Layout from "../../chat/Layout"; import Layout from "../Layout";
import { renderMessageFragment } from "../../chat/utils"; import { renderMessageFragment } from "../utils";
import { StyledChannelChat, StyledHeader } from "./styled"; import { StyledChannelChat, StyledHeader } from "./styled";
import LoadMore from "../../chat/LoadMore"; import LoadMore from "../LoadMore";
import { useAppSelector } from "../../../app/store"; import { useAppSelector } from "../../../app/store";
type Props = { type Props = {
cid?: number; cid?: number;
@@ -39,7 +39,7 @@ const Session: FC<IProps> = ({ id, mid }) => {
return ( return (
<li className="session"> <li className="session">
<NavLink className={`nav`} to={`/v/c/${id}`}> <NavLink className={`nav`} to={`/chat/channel/${id}`}>
<div className="icon"> <div className="icon">
<Avatar className="icon" type="channel" name={name} url={icon} /> <Avatar className="icon" type="channel" name={name} url={icon} />
</div> </div>
@@ -5,10 +5,8 @@ import Session from "./Session";
import { useAppSelector } from "../../../app/store"; import { useAppSelector } from "../../../app/store";
export interface ChatSession { export interface ChatSession {
key: string; key: string;
type: "user" | "channel";
id: number; id: number;
mid?: number; mid?: number;
unread?: number;
} }
type Props = {}; type Props = {};
const SessionList: FC<Props> = () => { const SessionList: FC<Props> = () => {
-3
View File
@@ -141,8 +141,5 @@ const Styled = styled.article`
} }
} }
} }
&.readonly .main .chat {
height: calc(100vh - 62px - 18px);
}
`; `;
export default Styled; export default Styled;
+15 -6
View File
@@ -11,12 +11,16 @@ import UsersModal from "../../common/component/UsersModal";
import ChannelModal from "../../common/component/ChannelModal"; import ChannelModal from "../../common/component/ChannelModal";
import SessionList from "./SessionList"; import SessionList from "./SessionList";
import { useAppSelector } from "../../app/store"; import { useAppSelector } from "../../app/store";
import GuestBlankPlaceholder from "./GuestBlankPlaceholder";
import GuestChannelChatInfo from "./GuestChannelChatInfo";
import GuestSessionList from "./GuestSessionList";
export default function ChatPage() { export default function ChatPage() {
const [channelModalVisible, setChannelModalVisible] = useState(false); const [channelModalVisible, setChannelModalVisible] = useState(false);
const [usersModalVisible, setUsersModalVisible] = useState(false); const [usersModalVisible, setUsersModalVisible] = useState(false);
const { channel_id = 0, user_id = 0 } = useParams(); const { channel_id = 0, user_id = 0 } = useParams();
const { sessionUids } = useAppSelector((store) => { const { sessionUids, isGuest } = useAppSelector((store) => {
return { return {
isGuest: store.authData.guest,
sessionUids: store.userMessage.ids sessionUids: store.userMessage.ids
}; };
}); });
@@ -43,14 +47,19 @@ export default function ChatPage() {
<ChannelModal closeModal={toggleChannelModalVisible} personal={true} /> <ChannelModal closeModal={toggleChannelModalVisible} personal={true} />
)} )}
{usersModalVisible && <UsersModal closeModal={toggleUsersModalVisible} />} {usersModalVisible && <UsersModal closeModal={toggleUsersModalVisible} />}
<StyledWrapper> <StyledWrapper className={isGuest ? "guest" : ""}>
<div className="left"> <div className="left">
<Server /> <Server readonly={isGuest} />
<SessionList tempSession={tmpSession} /> {isGuest ? <GuestSessionList /> : <SessionList tempSession={tmpSession} />}
</div> </div>
<div className={`right ${placeholderVisible ? "placeholder" : ""}`}> <div className={`right ${placeholderVisible ? "placeholder" : ""}`}>
{placeholderVisible && <BlankPlaceholder />} {placeholderVisible && (isGuest ? <GuestBlankPlaceholder /> : <BlankPlaceholder />)}
{channel_id !== 0 && <ChannelChat cid={+channel_id} />} {channel_id !== 0 &&
(isGuest ? (
<GuestChannelChatInfo cid={+channel_id} />
) : (
<ChannelChat cid={+channel_id} />
))}
{user_id !== 0 && <DMChat uid={+user_id} />} {user_id !== 0 && <DMChat uid={+user_id} />}
</div> </div>
</StyledWrapper> </StyledWrapper>
+3
View File
@@ -3,6 +3,9 @@ const StyledWrapper = styled.div`
display: flex; display: flex;
height: 100%; height: 100%;
padding: 8px 48px 10px 0; padding: 8px 48px 10px 0;
&.guest {
padding-right: 0;
}
> .left { > .left {
background-color: #fff; background-color: #fff;
position: relative; position: relative;
-20
View File
@@ -1,20 +0,0 @@
// import React from "react";
import styled from "styled-components";
const Styled = styled.div`
display: flex;
align-items: center;
font-size: 28px;
font-weight: bold;
color: #ccc;
padding: 50px;
height: calc(100vh - 24px);
text-transform: uppercase;
letter-spacing: 2px;
`;
// type Props = {};
const BlankPlaceholder = () => {
return <Styled>Guest Mode</Styled>;
};
export default BlankPlaceholder;
-20
View File
@@ -1,20 +0,0 @@
// import React from "react";
import styled from "styled-components";
const Styled = styled.div`
display: flex;
align-items: center;
font-size: 28px;
font-weight: bold;
color: orange;
padding: 50px;
height: calc(100vh - 24px);
text-transform: uppercase;
letter-spacing: 2px;
`;
// type Props = {};
const OffTip = () => {
return <Styled>Guest Mode Off</Styled>;
};
export default OffTip;
-65
View File
@@ -1,65 +0,0 @@
// import React from 'react';
import { useParams } from "react-router-dom";
import StyledWrapper from "./styled";
import Loading from "../../common/component/Loading";
import Manifest from "../../common/component/Manifest";
import Server from "../../common/component/Server";
import BlankPlaceholder from "./BlankPlaceholder";
import { useAppSelector } from "../../app/store";
import usePreload from "../../common/hook/usePreload";
import SessionList from "./SessionList";
import ChannelChat from "./ChannelChat";
// const routes = ["/setting", "/setting/channel/:cid"];
export default function GuestHomePage() {
const { cid = 0 } = useParams();
const placeholderVisible = cid == 0;
const {
ui: { ready }
} = useAppSelector((store) => {
return {
ui: store.ui
};
});
const { loading } = usePreload();
if (loading || !ready) {
return <Loading reload={true} fullscreen={true} />;
}
return (
<>
<Manifest />
<StyledWrapper>
<div className="left">
<Server readonly />
<SessionList />
</div>
<div className={`right ${placeholderVisible ? "placeholder" : ""}`}>
{placeholderVisible && <BlankPlaceholder />}
{cid !== 0 && <ChannelChat cid={+cid} />}
</div>
</StyledWrapper>
</>
);
}
// import Server from "../../common/component/Server";
// import ChannelChat from "./ChannelChat";
// import SessionList from "./SessionList";
// export default function ChatPage() {
// const { channel_id = 0 } = useParams();
// const placeholderVisible = channel_id == 0 ;
// return (
// <>
// <StyledWrapper>
// <div className="left">
// <Server />
// <SessionList tempSession={tmpSession} />
// </div>
// <div className={`right ${placeholderVisible ? "placeholder" : ""}`}>
// {placeholderVisible && <BlankPlaceholder />}
// {channel_id !== 0 && <ChannelChat cid={+channel_id} />}
// </div>
// </StyledWrapper>
// </>
// );
// }
-160
View File
@@ -1,160 +0,0 @@
import styled from "styled-components";
const StyledWrapper = styled.div`
display: flex;
height: 100%;
padding: 8px;
background: var(---navs-bg);
> .left {
background-color: #fff;
position: relative;
display: flex;
flex-direction: column;
min-width: 268px;
box-shadow: inset -1px 0px 0px rgba(0, 0, 0, 0.05);
height: 100%;
overflow: auto;
border-radius: 16px 0 0 16px;
.list {
margin: 12px 8px;
.title {
padding: 0 8px;
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 4px;
cursor: pointer;
> .txt {
user-select: none;
display: flex;
align-items: center;
gap: 5px;
font-weight: bold;
font-size: 12px;
line-height: 20px;
color: #78787c;
}
.icon {
transition: transform 0.5s ease;
transform-origin: center;
}
.add_icon {
width: 18px;
height: 18px;
}
}
> .nav {
display: flex;
flex-direction: column;
gap: 4px;
a {
text-decoration: none;
}
.session {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 4px 8px;
border-radius: 4px;
&:hover,
&.active {
background: rgba(116, 127, 141, 0.1);
}
.avatar {
/* todo */
}
.details {
display: flex;
flex-direction: column;
width: 100%;
.up {
display: flex;
justify-content: space-between;
align-items: center;
.name {
font-weight: 600;
font-size: 14px;
line-height: 20px;
color: #52525b;
max-width: 112px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
time {
white-space: nowrap;
font-weight: 500;
font-size: 12px;
line-height: 18px;
color: #78787c;
}
}
.down {
display: flex;
justify-content: space-between;
.msg {
min-height: 18px;
font-weight: normal;
font-size: 12px;
line-height: 18px;
color: #78787c;
white-space: nowrap;
overflow: hidden;
width: 140px;
text-overflow: ellipsis;
}
> .badge {
color: #fff;
height: 20px;
min-width: 20px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
background: #1fe1f9;
font-weight: 900;
font-size: 10px;
line-height: 10px;
&.dot {
min-width: unset;
width: 6px;
height: 6px;
padding: 0;
}
&.mute {
background: #bfbfbf;
}
}
}
}
}
/* drop files effect */
.drop_over {
box-shadow: inset 0 0 0 2px #52edff;
}
}
&.collapse {
.title .icon {
transform: rotate(-90deg);
}
> .nav > .link:not(.active) {
display: none;
}
}
}
}
> .right {
border-radius: 0 16px 16px 0;
width: 100%;
&.placeholder {
background-color: #fff;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
}
`;
export default StyledWrapper;
+39 -34
View File
@@ -22,6 +22,7 @@ export default function HomePage() {
const { pathname } = useLocation(); const { pathname } = useLocation();
const { const {
loginUid, loginUid,
guest,
ui: { ui: {
ready, ready,
rememberedNavs: { chat: chatPath, user: userPath } rememberedNavs: { chat: chatPath, user: userPath }
@@ -29,7 +30,9 @@ export default function HomePage() {
} = useAppSelector((store) => { } = useAppSelector((store) => {
return { return {
ui: store.ui, ui: store.ui,
loginUid: store.authData.user?.uid
loginUid: store.authData.user?.uid,
guest: store.authData.guest
}; };
}); });
const { loading } = usePreload(); const { loading } = usePreload();
@@ -53,39 +56,41 @@ export default function HomePage() {
<> <>
<Manifest /> <Manifest />
<Notification /> <Notification />
<StyledWrapper> <StyledWrapper className={guest ? "guest" : ""}>
<div className={`col left`}> {!guest && (
{loginUid && <User uid={loginUid} />} <div className={`col left`}>
<nav className="link_navs"> {loginUid && <User uid={loginUid} />}
<NavLink <nav className="link_navs">
className={() => { <NavLink
return `link ${isChattingPage ? "active" : ""}`; className={() => {
}} return `link ${isChattingPage ? "active" : ""}`;
to={chatNav} }}
> to={chatNav}
<Tooltip tip="Chat"> >
<ChatIcon /> <Tooltip tip="Chat">
</Tooltip> <ChatIcon />
</NavLink> </Tooltip>
<NavLink className="link" to={userNav}> </NavLink>
<Tooltip tip="Members"> <NavLink className="link" to={userNav}>
<UserIcon /> <Tooltip tip="Members">
</Tooltip> <UserIcon />
</NavLink> </Tooltip>
<NavLink className="link" to={"/favs"}> </NavLink>
<Tooltip tip="Saved Items"> <NavLink className="link" to={"/favs"}>
<FavIcon /> <Tooltip tip="Saved Items">
</Tooltip> <FavIcon />
</NavLink> </Tooltip>
<NavLink className="link" to={"/files"}> </NavLink>
<Tooltip tip="Files"> <NavLink className="link" to={"/files"}>
<FolderIcon /> <Tooltip tip="Files">
</Tooltip> <FolderIcon />
</NavLink> </Tooltip>
</nav> </NavLink>
{/* <div className="divider"></div> */} </nav>
<Menu /> {/* <div className="divider"></div> */}
</div> <Menu />
</div>
)}
<div className="col right"> <div className="col right">
<Outlet /> <Outlet />
</div> </div>
+3
View File
@@ -55,6 +55,9 @@ const StyledWrapper = styled.div`
} }
} }
} }
&.guest > .col.right {
margin: 0 8px;
}
`; `;
export default StyledWrapper; export default StyledWrapper;
+1 -34
View File
@@ -23,13 +23,9 @@ import RequireAuth from "../common/component/RequireAuth";
import RequireNoAuth from "../common/component/RequireNoAuth"; import RequireNoAuth from "../common/component/RequireNoAuth";
import Meta from "../common/component/Meta"; import Meta from "../common/component/Meta";
import HomePage from "./home"; import HomePage from "./home";
import GeustPage from "./guest";
// import GuestChannelChatPage from "./guest/ChannelChat";
import ChatPage from "./chat"; import ChatPage from "./chat";
import Loading from "../common/component/Loading"; import Loading from "../common/component/Loading";
import store, { useAppSelector } from "../app/store"; import store, { useAppSelector } from "../app/store";
import OffTip from "./guest/OffTip";
import GuestOnly from "../common/component/GuestOnly";
let toastId: string; let toastId: string;
const PageRoutes = () => { const PageRoutes = () => {
const { const {
@@ -93,34 +89,13 @@ const PageRoutes = () => {
/> />
<Route path="/invite" element={<InvitePage />} /> <Route path="/invite" element={<InvitePage />} />
<Route path="/onboarding" element={<OnboardingPage />} /> <Route path="/onboarding" element={<OnboardingPage />} />
{/* guest mode */}
<Route path="/v">
<Route
index
element={
<GuestOnly>
<GeustPage />
</GuestOnly>
}
/>
<Route
path="c/:cid"
element={
<GuestOnly>
<GeustPage />
</GuestOnly>
}
/>
<Route path="off" element={<OffTip />} />
</Route>
<Route <Route
path="/" path="/"
element={ element={
// <Suspense fallback={<Loading />}>
<RequireAuth> <RequireAuth>
<HomePage /> <HomePage />
</RequireAuth> </RequireAuth>
// </Suspense>
} }
> >
<Route path="setting"> <Route path="setting">
@@ -203,15 +178,7 @@ const PageRoutes = () => {
); );
}; };
// const local_key = "AUTH_DATA";
export default function ReduxRoutes() { export default function ReduxRoutes() {
// const [authData, setAuthData] = useState(
// JSON.parse(localStorage.getItem(local_key))
// );
// const updateAuthData = (data) => {
// localStorage.setItem(local_key, JSON.stringify(data));
// setAuthData(data);
// };
return ( return (
<Provider store={store}> <Provider store={store}>
<Meta /> <Meta />