refactor: more TS code

This commit is contained in:
Tristan Yang
2022-07-22 21:19:49 +08:00
parent 6427af90ef
commit dae0b80ee0
20 changed files with 81 additions and 88 deletions
+2 -2
View File
@@ -126,8 +126,8 @@ export const channelApi = createApi({
content: string | object; content: string | object;
type: ContentTypeKey; type: ContentTypeKey;
properties?: object; properties?: object;
from_uid: number; from_uid?: number;
ignoreLocal: boolean; ignoreLocal?: boolean;
} }
>({ >({
query: ({ id, content, type = "text", properties = {} }) => ({ query: ({ id, content, type = "text", properties = {} }) => ({
+2 -2
View File
@@ -116,14 +116,14 @@ export const messageApi = createApi({
} }
} }
}), }),
getFavoriteDetails: builder.query<Archive, number>({ getFavoriteDetails: builder.query<Archive, string>({
query: (id) => ({ query: (id) => ({
url: `/favorite/${id}` url: `/favorite/${id}`
}), }),
async onQueryStarted(id, { dispatch, queryFulfilled, getState }) { async onQueryStarted(id, { dispatch, queryFulfilled, getState }) {
try { try {
const { data } = await queryFulfilled; 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); const messages = normalizeArchiveData(data, id, loginUid);
dispatch(populateFavorite({ id, messages })); dispatch(populateFavorite({ id, messages }));
} catch (err) { } catch (err) {
+3 -2
View File
@@ -2,8 +2,9 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit";
// import BASE_URL from "../config"; // import BASE_URL from "../config";
export interface Favorite { export interface Favorite {
id: number; id: string;
messages: any[]; created_at?: number;
messages?: any[];
} }
const initialState: Favorite[] = []; const initialState: Favorite[] = [];
+2 -5
View File
@@ -40,9 +40,6 @@ const Avatar: FC<Props> = ({ url = "", name = "unknown name", type = "user", ...
return <img src={src} onError={handleError} {...rest} />; return <img src={src} onError={handleError} {...rest} />;
}; };
export default memo(Avatar, (prevs, nexts) => { export default memo(Avatar, (prev, next) => {
// const prevKey = prevs.url + prevs.name; return prev.url == next.url;
// const nextKey = nexts.url + nexts.name;
// return prevKey == nextKey;
return prevs.url == nexts.url;
}); });
+2 -1
View File
@@ -5,6 +5,7 @@ import Avatar from "./Avatar";
import useConfig from "../hook/useConfig"; import useConfig from "../hook/useConfig";
import { useAppSelector } from "../../app/store"; import { useAppSelector } from "../../app/store";
import { FC } from "react"; import { FC } from "react";
import { AgoraConfig } from "../../types/server";
const StyledWrapper = styled.div` const StyledWrapper = styled.div`
background-color: #f4f4f5; background-color: #f4f4f5;
@@ -79,7 +80,7 @@ const CurrentUser: FC<Props> = () => {
<span className="id">#{uid}</span> <span className="id">#{uid}</span>
</div> </div>
</div> </div>
{agoraConfig.enabled && ( {(agoraConfig as AgoraConfig)?.enabled && (
<div className="settings"> <div className="settings">
<img src={soundIcon} className="icon" alt="mic icon" /> <img src={soundIcon} className="icon" alt="mic icon" />
<img src={micIcon} className="icon" alt="sound icon" /> <img src={micIcon} className="icon" alt="sound icon" />
-1
View File
@@ -7,7 +7,6 @@ const Styled = styled.div`
border-radius: 6px; border-radius: 6px;
width: 370px; width: 370px;
height: 66px; height: 66px;
/* height: fit-content; */
* { * {
user-select: text; user-select: text;
} }
+1 -4
View File
@@ -55,7 +55,7 @@ const FileMessage: FC<Props> = ({
}); });
const { stopUploading, data, uploadFile, progress, isSuccess: uploadSuccess } = useUploadFile(); const { stopUploading, data, uploadFile, progress, isSuccess: uploadSuccess } = useUploadFile();
const fromUser = useAppSelector((store) => store.users.byId[from_uid]); const fromUser = useAppSelector((store) => store.users.byId[from_uid]);
const { size, name, content_type } = properties ?? {}; const { size = 0, name, content_type } = properties ?? {};
useEffect(() => { useEffect(() => {
const handleUpSend = async ({ const handleUpSend = async ({
url, url,
@@ -129,7 +129,6 @@ const FileMessage: FC<Props> = ({
uploading={sending} uploading={sending}
progress={progress} progress={progress}
properties={{ ...imageSize, ...properties }} properties={{ ...imageSize, ...properties }}
size={size}
content={content} content={content}
download={download} download={download}
thumbnail={thumbnail} thumbnail={thumbnail}
@@ -142,7 +141,6 @@ const FileMessage: FC<Props> = ({
<div className="info"> <div className="info">
<span className="name">{name}</span> <span className="name">{name}</span>
<span className="details"> <span className="details">
{/* <Progress value={30} width={"80%"} /> */}
{sending ? ( {sending ? (
<Progress value={progress} width={"80%"} /> <Progress value={progress} width={"80%"} />
) : ( ) : (
@@ -158,7 +156,6 @@ const FileMessage: FC<Props> = ({
)} )}
</span> </span>
</div> </div>
{/* <IconClose className="cancel" /> */}
{sending ? ( {sending ? (
<IconClose className="cancel" onClick={handleCancel} /> <IconClose className="cancel" onClick={handleCancel} />
) : ( ) : (
+2 -12
View File
@@ -130,12 +130,7 @@ const ForwardModal: FC<IProps> = ({ mids, closeModal }) => {
{selectedChannels.map((cid) => { {selectedChannels.map((cid) => {
return ( return (
<li key={cid} className="item"> <li key={cid} className="item">
<Channel <Channel key={cid} id={cid} interactive={false} />
key={cid}
id={cid}
interactive={false}
// avatarSize={40}
/>
<CloseIcon <CloseIcon
className="remove" className="remove"
onClick={removeSelected.bind(null, cid, "channel")} onClick={removeSelected.bind(null, cid, "channel")}
@@ -146,12 +141,7 @@ const ForwardModal: FC<IProps> = ({ mids, closeModal }) => {
{selectedMembers.map((uid) => { {selectedMembers.map((uid) => {
return ( return (
<li key={uid} className="item"> <li key={uid} className="item">
<User <User key={uid} uid={uid} interactive={false} />
key={uid}
uid={uid}
interactive={false}
// avatarSize={40}
/>
<CloseIcon className="remove" onClick={removeSelected.bind(null, uid, "user")} /> <CloseIcon className="remove" onClick={removeSelected.bind(null, uid, "user")} />
</li> </li>
); );
+20 -37
View File
@@ -11,13 +11,16 @@ import {
useLazyGetSMTPConfigQuery, useLazyGetSMTPConfigQuery,
useLazyGetLoginConfigQuery useLazyGetLoginConfigQuery
} from "../../app/services/server"; } from "../../app/services/server";
import { AgoraConfig, FirebaseConfig, LoginConfig, SMTPConfig } from "../../types/server";
// config: smtp agora login firebase // config: smtp agora login firebase
let originalValue: null | object = null; type ConfigType = "smtp" | "agora" | "login" | "firebase";
type ConfigMap = Record<ConfigType, AgoraConfig | FirebaseConfig | LoginConfig | SMTPConfig>;
export default function useConfig(config = "smtp") { type valuesOf<T> = T[keyof T];
let originalValue: valuesOf<ConfigMap> | undefined = undefined;
// type valueOf<T,config as ConfigType> = T[config];
export default function useConfig(config: keyof ConfigMap = "smtp") {
const [changed, setChanged] = useState(false); const [changed, setChanged] = useState(false);
const [values, setValues] = useState<object>({}); const [values, setValues] = useState<valuesOf<ConfigMap> | undefined>(undefined);
const [updateLoginConfig, { isSuccess: LoginUpdated }] = useUpdateLoginConfigMutation(); const [updateLoginConfig, { isSuccess: LoginUpdated }] = useUpdateLoginConfigMutation();
const [updateSMTPConfig, { isSuccess: SMTPUpdated }] = useUpdateSMTPConfigMutation(); const [updateSMTPConfig, { isSuccess: SMTPUpdated }] = useUpdateSMTPConfigMutation();
const [getAgoraConfig, { data: agoraConfig }] = useLazyGetAgoraConfigQuery(); const [getAgoraConfig, { data: agoraConfig }] = useLazyGetAgoraConfigQuery();
@@ -27,63 +30,43 @@ export default function useConfig(config = "smtp") {
const [getFirebaseConfig, { data: firebaseConfig }] = useLazyGetFirebaseConfigQuery(); const [getFirebaseConfig, { data: firebaseConfig }] = useLazyGetFirebaseConfigQuery();
const [updateFirebaseConfig, { isSuccess: FirebaseUpdated }] = useUpdateFirebaseConfigMutation(); const [updateFirebaseConfig, { isSuccess: FirebaseUpdated }] = useUpdateFirebaseConfigMutation();
// const datas = {
// login: {},
// smtp: {},
// agora: {},
// firebase: {}
// };
const updateFns = { const updateFns = {
login: updateLoginConfig, login: updateLoginConfig,
smtp: updateSMTPConfig, smtp: updateSMTPConfig,
agora: updateAgoraConfig, agora: updateAgoraConfig,
firebase: updateFirebaseConfig firebase: updateFirebaseConfig
}; };
const refetchs = { const requests = {
smtp: getSMTPConfig, smtp: getSMTPConfig,
agora: getAgoraConfig, agora: getAgoraConfig,
firebase: getFirebaseConfig, firebase: getFirebaseConfig,
login: getLoginConfig login: getLoginConfig
}; };
const updateds = { const updates = {
login: LoginUpdated, login: LoginUpdated,
smtp: SMTPUpdated, smtp: SMTPUpdated,
agora: AgoraUpdated, agora: AgoraUpdated,
firebase: FirebaseUpdated firebase: FirebaseUpdated
}; };
// const data = datas[config];
const updateConfig = updateFns[config]; const updateConfig = updateFns[config];
const refetch = refetchs[config]; const refetch = requests[config];
const updated = updateds[config]; const updated = updates[config];
const reset = () => { const reset = () => {
setValues(originalValue); setValues(undefined);
}; };
const toggleEnable = () => { const toggleEnable = () => {
setValues((prev) => { setValues((prev) => {
return { ...prev, enabled: !prev.enabled }; if (prev && "enabled" in prev) {
return { ...prev, enabled: !prev.enabled };
}
return prev;
}); });
}; };
useEffect(() => { useEffect(() => {
switch (config) { refetch();
case "firebase": }, []);
getFirebaseConfig();
break;
case "agora":
getAgoraConfig();
break;
case "smtp":
getSMTPConfig();
break;
case "login":
getLoginConfig();
break;
default:
break;
}
}, [config]);
useEffect(() => { useEffect(() => {
if (updated) { if (updated) {
@@ -100,7 +83,7 @@ export default function useConfig(config = "smtp") {
}, [smtpConfig, firebaseConfig, loginConfig, agoraConfig]); }, [smtpConfig, firebaseConfig, loginConfig, agoraConfig]);
useEffect(() => { useEffect(() => {
// 空对象 // 空对象
if (Object.keys(values).length == 0) return; if (!values || Object.keys(values).length == 0) return;
if (!isEqual(originalValue, values)) { if (!isEqual(originalValue, values)) {
setChanged(true); setChanged(true);
} else { } else {
+9 -1
View File
@@ -15,7 +15,15 @@ export default function useForwardMessage() {
] = useSendChannelMsgMutation(); ] = useSendChannelMsgMutation();
const [sendUserMsg, { isLoading: userSending, isSuccess: userSuccess, isError: userError }] = const [sendUserMsg, { isLoading: userSending, isSuccess: userSuccess, isError: userError }] =
useSendMsgMutation(); useSendMsgMutation();
const forwardMessage = async ({ mids = [], users = [], channels = [] }) => { const forwardMessage = async ({
mids,
users,
channels
}: {
mids: number[];
users: number[];
channels: number[];
}) => {
setForwarding(true); setForwarding(true);
const { data: archive_id } = await createArchive(mids); const { data: archive_id } = await createArchive(mids);
if (users.length) { if (users.length) {
+10 -8
View File
@@ -3,14 +3,11 @@ import {
useGetGithubAuthConfigQuery, useGetGithubAuthConfigQuery,
useUpdateGithubAuthConfigMutation useUpdateGithubAuthConfigMutation
} from "../../app/services/server"; } from "../../app/services/server";
import { GithubAuthConfig } from "../../types/server";
interface GithubAuthConfig {
client_id: string;
}
export default function useGithubAuthConfig() { export default function useGithubAuthConfig() {
const [changed, setChanged] = useState(false); const [changed, setChanged] = useState(false);
const [config, setConfig] = useState({}); const [config, setConfig] = useState<GithubAuthConfig | undefined>(undefined);
const { data } = useGetGithubAuthConfigQuery(undefined, { const { data } = useGetGithubAuthConfigQuery(undefined, {
refetchOnMountOrArgChange: true refetchOnMountOrArgChange: true
}); });
@@ -24,13 +21,18 @@ export default function useGithubAuthConfig() {
useEffect(() => { useEffect(() => {
setChanged(isSuccess ? false : JSON.stringify(data) !== JSON.stringify(config)); setChanged(isSuccess ? false : JSON.stringify(data) !== JSON.stringify(config));
}, [data, config, isSuccess]); }, [data, config, isSuccess]);
const updateGithubAuthConfig = (obj) => { const updateGithubAuthConfig = (obj: Partial<GithubAuthConfig>) => {
setConfig((prev) => { setConfig((prev) => {
return { ...prev, ...obj }; if (prev) {
return { ...prev, ...obj };
}
return obj;
}); });
}; };
const updateGithubAuthConfigToServer = async () => { const updateGithubAuthConfigToServer = async () => {
await updateAuthConfig(config); if (config) {
await updateAuthConfig(config);
}
}; };
return { return {
config, config,
+1 -1
View File
@@ -24,7 +24,7 @@ interface SendMessageDTO {
to: number; to: number;
} }
const useSendMessage = (props: Props) => { const useSendMessage = (props?: Props) => {
const { context = "user", from, to = null } = props || {}; const { context = "user", from, to = null } = props || {};
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const stageFiles = useAppSelector((store) => store.ui.uploadFiles[`${context}_${to}`] || []); const stageFiles = useAppSelector((store) => store.ui.uploadFiles[`${context}_${to}`] || []);
+3 -3
View File
@@ -22,8 +22,8 @@ const useUserOperation = ({ uid, cid }: IProps) => {
const { copy } = useCopy(); const { copy } = useCopy();
const { user, channel, loginUser } = useAppSelector((store) => { const { user, channel, loginUser } = useAppSelector((store) => {
return { return {
user: store.users.byId[uid], user: typeof uid !== "undefined" ? store.users.byId[uid] : uid,
channel: store.channels.byId[cid], channel: typeof cid !== "undefined" ? store.channels.byId[cid] : cid,
loginUser: store.authData.user loginUser: store.authData.user
}; };
}); });
@@ -62,7 +62,7 @@ const useUserOperation = ({ uid, cid }: IProps) => {
const copyEmail = (email: string) => { const copyEmail = (email: string) => {
const isString = typeof email == "string"; const isString = typeof email == "string";
const finalEmail = isString ? email || user?.email : user?.email; const finalEmail = isString ? email || user?.email : user?.email;
copy(finalEmail); copy(finalEmail || "");
hideAll(); hideAll();
}; };
+6 -1
View File
@@ -6,6 +6,7 @@ import IconUnknown from "../assets/icons/file.unknown.svg";
import IconDoc from "../assets/icons/file.doc.svg"; import IconDoc from "../assets/icons/file.doc.svg";
import IconCode from "../assets/icons/file.code.svg"; import IconCode from "../assets/icons/file.code.svg";
import IconImage from "../assets/icons/file.image.svg"; import IconImage from "../assets/icons/file.image.svg";
import { Archive } from "../types/resource";
export const isImage = (file_type = "", size = 0) => { export const isImage = (file_type = "", size = 0) => {
return file_type.startsWith("image") && size <= FILE_IMAGE_SIZE; return file_type.startsWith("image") && size <= FILE_IMAGE_SIZE;
@@ -169,7 +170,11 @@ export const getFileIcon = (type: string, name = "") => {
} }
return icon; 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 []; if (!data || !filePath) return [];
const { messages, users } = data; const { messages, users } = data;
const getUrls = (uid, { content, content_type, file_id, thumbnail_id, filePath, avatar }) => { const getUrls = (uid, { content, content_type, file_id, thumbnail_id, filePath, avatar }) => {
+5 -1
View File
@@ -27,7 +27,11 @@ import { StyledUsers, StyledChannelChat, StyledHeader } from "./styled";
import InviteModal from "../../../common/component/InviteModal"; import InviteModal from "../../../common/component/InviteModal";
import LoadMore from "../LoadMore"; import LoadMore from "../LoadMore";
import { useAppSelector } from "../../../app/store"; 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 { values: agoraConfig } = useConfig("agora");
const { const {
list: msgIds, list: msgIds,
+1 -1
View File
@@ -14,7 +14,7 @@ interface Props {
header: ReactElement; header: ReactElement;
aside: ReactElement | null; aside: ReactElement | null;
users?: ReactElement; users?: ReactElement;
dropFiles: [File]; dropFiles: File[];
context: "channel" | "user"; context: "channel" | "user";
to: number; to: number;
} }
+9 -2
View File
@@ -6,6 +6,7 @@ import Toggle from "../../../common/component/styled/Toggle";
import Label from "../../../common/component/styled/Label"; import Label from "../../../common/component/styled/Label";
import SaveTip from "../../../common/component/SaveTip"; import SaveTip from "../../../common/component/SaveTip";
import useConfig from "../../../common/hook/useConfig"; import useConfig from "../../../common/hook/useConfig";
import { FirebaseConfig } from "../../../types/server";
export default function ConfigFirebase() { export default function ConfigFirebase() {
const { values, toggleEnable, updateConfig, setValues, reset, changed } = useConfig("firebase"); const { values, toggleEnable, updateConfig, setValues, reset, changed } = useConfig("firebase");
@@ -20,8 +21,14 @@ export default function ConfigFirebase() {
return { ...prev, [type]: newValue }; return { ...prev, [type]: newValue };
}); });
}; };
// if (!values) return null; if (!values) return null;
const { token_url, project_id, private_key, client_email, enabled = false } = values ?? {}; const {
token_url,
project_id,
private_key,
client_email,
enabled = false
} = values as FirebaseConfig;
return ( return (
<StyledContainer> <StyledContainer>
<div className="inputs"> <div className="inputs">
-1
View File
@@ -49,7 +49,6 @@ export default function Logins() {
}; };
const handleGithubAuthChange = (evt) => { const handleGithubAuthChange = (evt) => {
const { key } = evt.target.dataset; const { key } = evt.target.dataset;
console.log("ggg", key, evt.target.value);
if (key) { if (key) {
updateGithubAuthConfig({ [key]: evt.target.value }); updateGithubAuthConfig({ [key]: evt.target.value });
} }
+1 -1
View File
@@ -34,7 +34,7 @@ export interface CreateChannelDTO {
is_public: boolean; is_public: boolean;
} }
export interface ChannelDTO extends Pick<Channel, "owner" | "description" | "name"> { export interface ChannelDTO extends Partial<Pick<Channel, "owner" | "description" | "name">> {
id: number; id: number;
} }
+2 -2
View File
@@ -6,8 +6,8 @@ export interface Server {
description: string; description: string;
} }
export interface GithubAuthConfig { export interface GithubAuthConfig {
client_id: string; client_id?: string;
client_secret: string; // todo: check security problem! client_secret?: string;
} }
export interface FirebaseConfig { export interface FirebaseConfig {
enabled: boolean; enabled: boolean;