From dae0b80ee0f0cd2337a75e45e283e97e6814a487 Mon Sep 17 00:00:00 2001 From: Tristan Yang Date: Fri, 22 Jul 2022 21:19:49 +0800 Subject: [PATCH] refactor: more TS code --- src/app/services/channel.ts | 4 +- src/app/services/message.ts | 4 +- src/app/slices/favorites.ts | 5 +- src/common/component/Avatar.tsx | 7 +-- src/common/component/CurrentUser.tsx | 3 +- src/common/component/FileBox/styled.tsx | 1 - src/common/component/FileMessage/index.tsx | 5 +- src/common/component/ForwardModal/index.tsx | 14 +---- src/common/hook/useConfig.ts | 57 ++++++++------------- src/common/hook/useForwardMessage.ts | 10 +++- src/common/hook/useGithubAuthConfig.ts | 18 ++++--- src/common/hook/useSendMessage.ts | 2 +- src/common/hook/useUserOperation.ts | 6 +-- src/common/utils.tsx | 7 ++- src/routes/chat/ChannelChat/index.tsx | 6 ++- src/routes/chat/Layout/index.tsx | 2 +- src/routes/setting/config/Firebase.tsx | 11 +++- src/routes/setting/config/Logins.tsx | 1 - src/types/channel.ts | 2 +- src/types/server.ts | 4 +- 20 files changed, 81 insertions(+), 88 deletions(-) diff --git a/src/app/services/channel.ts b/src/app/services/channel.ts index 2dabbdc8..e386ceb2 100644 --- a/src/app/services/channel.ts +++ b/src/app/services/channel.ts @@ -126,8 +126,8 @@ export const channelApi = createApi({ content: string | object; type: ContentTypeKey; properties?: object; - from_uid: number; - ignoreLocal: boolean; + from_uid?: number; + ignoreLocal?: boolean; } >({ query: ({ id, content, type = "text", properties = {} }) => ({ diff --git a/src/app/services/message.ts b/src/app/services/message.ts index b6c52888..1f144594 100644 --- a/src/app/services/message.ts +++ b/src/app/services/message.ts @@ -116,14 +116,14 @@ export const messageApi = createApi({ } } }), - getFavoriteDetails: builder.query({ + getFavoriteDetails: builder.query({ query: (id) => ({ url: `/favorite/${id}` }), async onQueryStarted(id, { dispatch, queryFulfilled, getState }) { try { const { data } = await queryFulfilled; - const loginUid = (getState() as RootState).authData.user.uid; + const loginUid = (getState() as RootState).authData.user?.uid; const messages = normalizeArchiveData(data, id, loginUid); dispatch(populateFavorite({ id, messages })); } catch (err) { diff --git a/src/app/slices/favorites.ts b/src/app/slices/favorites.ts index eb9f2d10..6bfb4ada 100644 --- a/src/app/slices/favorites.ts +++ b/src/app/slices/favorites.ts @@ -2,8 +2,9 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; // import BASE_URL from "../config"; export interface Favorite { - id: number; - messages: any[]; + id: string; + created_at?: number; + messages?: any[]; } const initialState: Favorite[] = []; diff --git a/src/common/component/Avatar.tsx b/src/common/component/Avatar.tsx index 588df387..8d55029b 100644 --- a/src/common/component/Avatar.tsx +++ b/src/common/component/Avatar.tsx @@ -40,9 +40,6 @@ const Avatar: FC = ({ url = "", name = "unknown name", type = "user", ... return ; }; -export default memo(Avatar, (prevs, nexts) => { - // const prevKey = prevs.url + prevs.name; - // const nextKey = nexts.url + nexts.name; - // return prevKey == nextKey; - return prevs.url == nexts.url; +export default memo(Avatar, (prev, next) => { + return prev.url == next.url; }); diff --git a/src/common/component/CurrentUser.tsx b/src/common/component/CurrentUser.tsx index 247767ad..533d1a3f 100644 --- a/src/common/component/CurrentUser.tsx +++ b/src/common/component/CurrentUser.tsx @@ -5,6 +5,7 @@ import Avatar from "./Avatar"; import useConfig from "../hook/useConfig"; import { useAppSelector } from "../../app/store"; import { FC } from "react"; +import { AgoraConfig } from "../../types/server"; const StyledWrapper = styled.div` background-color: #f4f4f5; @@ -79,7 +80,7 @@ const CurrentUser: FC = () => { #{uid} - {agoraConfig.enabled && ( + {(agoraConfig as AgoraConfig)?.enabled && (
mic icon sound icon diff --git a/src/common/component/FileBox/styled.tsx b/src/common/component/FileBox/styled.tsx index 2c52730b..67b6f1c8 100644 --- a/src/common/component/FileBox/styled.tsx +++ b/src/common/component/FileBox/styled.tsx @@ -7,7 +7,6 @@ const Styled = styled.div` border-radius: 6px; width: 370px; height: 66px; - /* height: fit-content; */ * { user-select: text; } diff --git a/src/common/component/FileMessage/index.tsx b/src/common/component/FileMessage/index.tsx index 8fef62dc..0c8c49e3 100644 --- a/src/common/component/FileMessage/index.tsx +++ b/src/common/component/FileMessage/index.tsx @@ -55,7 +55,7 @@ const FileMessage: FC = ({ }); const { stopUploading, data, uploadFile, progress, isSuccess: uploadSuccess } = useUploadFile(); const fromUser = useAppSelector((store) => store.users.byId[from_uid]); - const { size, name, content_type } = properties ?? {}; + const { size = 0, name, content_type } = properties ?? {}; useEffect(() => { const handleUpSend = async ({ url, @@ -129,7 +129,6 @@ const FileMessage: FC = ({ uploading={sending} progress={progress} properties={{ ...imageSize, ...properties }} - size={size} content={content} download={download} thumbnail={thumbnail} @@ -142,7 +141,6 @@ const FileMessage: FC = ({
{name} - {/* */} {sending ? ( ) : ( @@ -158,7 +156,6 @@ const FileMessage: FC = ({ )}
- {/* */} {sending ? ( ) : ( diff --git a/src/common/component/ForwardModal/index.tsx b/src/common/component/ForwardModal/index.tsx index 4a46c648..d7b9ead7 100644 --- a/src/common/component/ForwardModal/index.tsx +++ b/src/common/component/ForwardModal/index.tsx @@ -130,12 +130,7 @@ const ForwardModal: FC = ({ mids, closeModal }) => { {selectedChannels.map((cid) => { return (
  • - + = ({ mids, closeModal }) => { {selectedMembers.map((uid) => { return (
  • - +
  • ); diff --git a/src/common/hook/useConfig.ts b/src/common/hook/useConfig.ts index 8aa68abb..21395cd9 100644 --- a/src/common/hook/useConfig.ts +++ b/src/common/hook/useConfig.ts @@ -11,13 +11,16 @@ import { useLazyGetSMTPConfigQuery, useLazyGetLoginConfigQuery } from "../../app/services/server"; - +import { AgoraConfig, FirebaseConfig, LoginConfig, SMTPConfig } from "../../types/server"; // config: smtp agora login firebase -let originalValue: null | object = null; - -export default function useConfig(config = "smtp") { +type ConfigType = "smtp" | "agora" | "login" | "firebase"; +type ConfigMap = Record; +type valuesOf = T[keyof T]; +let originalValue: valuesOf | undefined = undefined; +// type valueOf = T[config]; +export default function useConfig(config: keyof ConfigMap = "smtp") { const [changed, setChanged] = useState(false); - const [values, setValues] = useState({}); + const [values, setValues] = useState | undefined>(undefined); const [updateLoginConfig, { isSuccess: LoginUpdated }] = useUpdateLoginConfigMutation(); const [updateSMTPConfig, { isSuccess: SMTPUpdated }] = useUpdateSMTPConfigMutation(); const [getAgoraConfig, { data: agoraConfig }] = useLazyGetAgoraConfigQuery(); @@ -27,63 +30,43 @@ export default function useConfig(config = "smtp") { const [getFirebaseConfig, { data: firebaseConfig }] = useLazyGetFirebaseConfigQuery(); const [updateFirebaseConfig, { isSuccess: FirebaseUpdated }] = useUpdateFirebaseConfigMutation(); - // const datas = { - // login: {}, - // smtp: {}, - // agora: {}, - // firebase: {} - // }; const updateFns = { login: updateLoginConfig, smtp: updateSMTPConfig, agora: updateAgoraConfig, firebase: updateFirebaseConfig }; - const refetchs = { + const requests = { smtp: getSMTPConfig, agora: getAgoraConfig, firebase: getFirebaseConfig, login: getLoginConfig }; - const updateds = { + const updates = { login: LoginUpdated, smtp: SMTPUpdated, agora: AgoraUpdated, firebase: FirebaseUpdated }; - // const data = datas[config]; const updateConfig = updateFns[config]; - const refetch = refetchs[config]; - const updated = updateds[config]; + const refetch = requests[config]; + const updated = updates[config]; const reset = () => { - setValues(originalValue); + setValues(undefined); }; const toggleEnable = () => { setValues((prev) => { - return { ...prev, enabled: !prev.enabled }; + if (prev && "enabled" in prev) { + return { ...prev, enabled: !prev.enabled }; + } + return prev; }); }; useEffect(() => { - switch (config) { - case "firebase": - getFirebaseConfig(); - break; - case "agora": - getAgoraConfig(); - break; - case "smtp": - getSMTPConfig(); - break; - case "login": - getLoginConfig(); - break; - - default: - break; - } - }, [config]); + refetch(); + }, []); useEffect(() => { if (updated) { @@ -100,7 +83,7 @@ export default function useConfig(config = "smtp") { }, [smtpConfig, firebaseConfig, loginConfig, agoraConfig]); useEffect(() => { // 空对象 - if (Object.keys(values).length == 0) return; + if (!values || Object.keys(values).length == 0) return; if (!isEqual(originalValue, values)) { setChanged(true); } else { diff --git a/src/common/hook/useForwardMessage.ts b/src/common/hook/useForwardMessage.ts index d595f878..7f5aa3d9 100644 --- a/src/common/hook/useForwardMessage.ts +++ b/src/common/hook/useForwardMessage.ts @@ -15,7 +15,15 @@ export default function useForwardMessage() { ] = useSendChannelMsgMutation(); const [sendUserMsg, { isLoading: userSending, isSuccess: userSuccess, isError: userError }] = useSendMsgMutation(); - const forwardMessage = async ({ mids = [], users = [], channels = [] }) => { + const forwardMessage = async ({ + mids, + users, + channels + }: { + mids: number[]; + users: number[]; + channels: number[]; + }) => { setForwarding(true); const { data: archive_id } = await createArchive(mids); if (users.length) { diff --git a/src/common/hook/useGithubAuthConfig.ts b/src/common/hook/useGithubAuthConfig.ts index 79678d9f..b2b261f8 100644 --- a/src/common/hook/useGithubAuthConfig.ts +++ b/src/common/hook/useGithubAuthConfig.ts @@ -3,14 +3,11 @@ import { useGetGithubAuthConfigQuery, useUpdateGithubAuthConfigMutation } from "../../app/services/server"; - -interface GithubAuthConfig { - client_id: string; -} +import { GithubAuthConfig } from "../../types/server"; export default function useGithubAuthConfig() { const [changed, setChanged] = useState(false); - const [config, setConfig] = useState({}); + const [config, setConfig] = useState(undefined); const { data } = useGetGithubAuthConfigQuery(undefined, { refetchOnMountOrArgChange: true }); @@ -24,13 +21,18 @@ export default function useGithubAuthConfig() { useEffect(() => { setChanged(isSuccess ? false : JSON.stringify(data) !== JSON.stringify(config)); }, [data, config, isSuccess]); - const updateGithubAuthConfig = (obj) => { + const updateGithubAuthConfig = (obj: Partial) => { setConfig((prev) => { - return { ...prev, ...obj }; + if (prev) { + return { ...prev, ...obj }; + } + return obj; }); }; const updateGithubAuthConfigToServer = async () => { - await updateAuthConfig(config); + if (config) { + await updateAuthConfig(config); + } }; return { config, diff --git a/src/common/hook/useSendMessage.ts b/src/common/hook/useSendMessage.ts index e3e63b2e..d445c9e0 100644 --- a/src/common/hook/useSendMessage.ts +++ b/src/common/hook/useSendMessage.ts @@ -24,7 +24,7 @@ interface SendMessageDTO { to: number; } -const useSendMessage = (props: Props) => { +const useSendMessage = (props?: Props) => { const { context = "user", from, to = null } = props || {}; const dispatch = useAppDispatch(); const stageFiles = useAppSelector((store) => store.ui.uploadFiles[`${context}_${to}`] || []); diff --git a/src/common/hook/useUserOperation.ts b/src/common/hook/useUserOperation.ts index 2c6c47ba..41017fce 100644 --- a/src/common/hook/useUserOperation.ts +++ b/src/common/hook/useUserOperation.ts @@ -22,8 +22,8 @@ const useUserOperation = ({ uid, cid }: IProps) => { const { copy } = useCopy(); const { user, channel, loginUser } = useAppSelector((store) => { return { - user: store.users.byId[uid], - channel: store.channels.byId[cid], + user: typeof uid !== "undefined" ? store.users.byId[uid] : uid, + channel: typeof cid !== "undefined" ? store.channels.byId[cid] : cid, loginUser: store.authData.user }; }); @@ -62,7 +62,7 @@ const useUserOperation = ({ uid, cid }: IProps) => { const copyEmail = (email: string) => { const isString = typeof email == "string"; const finalEmail = isString ? email || user?.email : user?.email; - copy(finalEmail); + copy(finalEmail || ""); hideAll(); }; diff --git a/src/common/utils.tsx b/src/common/utils.tsx index 3d4580b3..3a2ee3fc 100644 --- a/src/common/utils.tsx +++ b/src/common/utils.tsx @@ -6,6 +6,7 @@ import IconUnknown from "../assets/icons/file.unknown.svg"; import IconDoc from "../assets/icons/file.doc.svg"; import IconCode from "../assets/icons/file.code.svg"; import IconImage from "../assets/icons/file.image.svg"; +import { Archive } from "../types/resource"; export const isImage = (file_type = "", size = 0) => { return file_type.startsWith("image") && size <= FILE_IMAGE_SIZE; @@ -169,7 +170,11 @@ export const getFileIcon = (type: string, name = "") => { } return icon; }; -export const normalizeArchiveData = (data = null, filePath = null, uid = null) => { +export const normalizeArchiveData = ( + data: Archive | null, + filePath: string | null, + uid?: number +) => { if (!data || !filePath) return []; const { messages, users } = data; const getUrls = (uid, { content, content_type, file_id, thumbnail_id, filePath, avatar }) => { diff --git a/src/routes/chat/ChannelChat/index.tsx b/src/routes/chat/ChannelChat/index.tsx index 8b73a896..cd12f6a7 100644 --- a/src/routes/chat/ChannelChat/index.tsx +++ b/src/routes/chat/ChannelChat/index.tsx @@ -27,7 +27,11 @@ import { StyledUsers, StyledChannelChat, StyledHeader } from "./styled"; import InviteModal from "../../../common/component/InviteModal"; import LoadMore from "../LoadMore"; import { useAppSelector } from "../../../app/store"; -export default function ChannelChat({ cid = "", dropFiles = [] }) { +type Props = { + cid?: number; + dropFiles?: File[]; +}; +export default function ChannelChat({ cid = 0, dropFiles = [] }: Props) { const { values: agoraConfig } = useConfig("agora"); const { list: msgIds, diff --git a/src/routes/chat/Layout/index.tsx b/src/routes/chat/Layout/index.tsx index bbc0e617..47e53ac6 100644 --- a/src/routes/chat/Layout/index.tsx +++ b/src/routes/chat/Layout/index.tsx @@ -14,7 +14,7 @@ interface Props { header: ReactElement; aside: ReactElement | null; users?: ReactElement; - dropFiles: [File]; + dropFiles: File[]; context: "channel" | "user"; to: number; } diff --git a/src/routes/setting/config/Firebase.tsx b/src/routes/setting/config/Firebase.tsx index 6ee6c4f2..286c1f2b 100644 --- a/src/routes/setting/config/Firebase.tsx +++ b/src/routes/setting/config/Firebase.tsx @@ -6,6 +6,7 @@ import Toggle from "../../../common/component/styled/Toggle"; import Label from "../../../common/component/styled/Label"; import SaveTip from "../../../common/component/SaveTip"; import useConfig from "../../../common/hook/useConfig"; +import { FirebaseConfig } from "../../../types/server"; export default function ConfigFirebase() { const { values, toggleEnable, updateConfig, setValues, reset, changed } = useConfig("firebase"); @@ -20,8 +21,14 @@ export default function ConfigFirebase() { return { ...prev, [type]: newValue }; }); }; - // if (!values) return null; - const { token_url, project_id, private_key, client_email, enabled = false } = values ?? {}; + if (!values) return null; + const { + token_url, + project_id, + private_key, + client_email, + enabled = false + } = values as FirebaseConfig; return (
    diff --git a/src/routes/setting/config/Logins.tsx b/src/routes/setting/config/Logins.tsx index 89159702..f0fcff0a 100644 --- a/src/routes/setting/config/Logins.tsx +++ b/src/routes/setting/config/Logins.tsx @@ -49,7 +49,6 @@ export default function Logins() { }; const handleGithubAuthChange = (evt) => { const { key } = evt.target.dataset; - console.log("ggg", key, evt.target.value); if (key) { updateGithubAuthConfig({ [key]: evt.target.value }); } diff --git a/src/types/channel.ts b/src/types/channel.ts index 436c9401..4b64eca7 100644 --- a/src/types/channel.ts +++ b/src/types/channel.ts @@ -34,7 +34,7 @@ export interface CreateChannelDTO { is_public: boolean; } -export interface ChannelDTO extends Pick { +export interface ChannelDTO extends Partial> { id: number; } diff --git a/src/types/server.ts b/src/types/server.ts index e01a15c9..c7ae6c5f 100644 --- a/src/types/server.ts +++ b/src/types/server.ts @@ -6,8 +6,8 @@ export interface Server { description: string; } export interface GithubAuthConfig { - client_id: string; - client_secret: string; // todo: check security problem! + client_id?: string; + client_secret?: string; } export interface FirebaseConfig { enabled: boolean;