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;
type: ContentTypeKey;
properties?: object;
from_uid: number;
ignoreLocal: boolean;
from_uid?: number;
ignoreLocal?: boolean;
}
>({
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) => ({
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) {
+3 -2
View File
@@ -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[] = [];
+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} />;
};
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;
});
+2 -1
View File
@@ -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<Props> = () => {
<span className="id">#{uid}</span>
</div>
</div>
{agoraConfig.enabled && (
{(agoraConfig as AgoraConfig)?.enabled && (
<div className="settings">
<img src={soundIcon} className="icon" alt="mic icon" />
<img src={micIcon} className="icon" alt="sound icon" />
-1
View File
@@ -7,7 +7,6 @@ const Styled = styled.div`
border-radius: 6px;
width: 370px;
height: 66px;
/* height: fit-content; */
* {
user-select: text;
}
+1 -4
View File
@@ -55,7 +55,7 @@ const FileMessage: FC<Props> = ({
});
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<Props> = ({
uploading={sending}
progress={progress}
properties={{ ...imageSize, ...properties }}
size={size}
content={content}
download={download}
thumbnail={thumbnail}
@@ -142,7 +141,6 @@ const FileMessage: FC<Props> = ({
<div className="info">
<span className="name">{name}</span>
<span className="details">
{/* <Progress value={30} width={"80%"} /> */}
{sending ? (
<Progress value={progress} width={"80%"} />
) : (
@@ -158,7 +156,6 @@ const FileMessage: FC<Props> = ({
)}
</span>
</div>
{/* <IconClose className="cancel" /> */}
{sending ? (
<IconClose className="cancel" onClick={handleCancel} />
) : (
+2 -12
View File
@@ -130,12 +130,7 @@ const ForwardModal: FC<IProps> = ({ mids, closeModal }) => {
{selectedChannels.map((cid) => {
return (
<li key={cid} className="item">
<Channel
key={cid}
id={cid}
interactive={false}
// avatarSize={40}
/>
<Channel key={cid} id={cid} interactive={false} />
<CloseIcon
className="remove"
onClick={removeSelected.bind(null, cid, "channel")}
@@ -146,12 +141,7 @@ const ForwardModal: FC<IProps> = ({ mids, closeModal }) => {
{selectedMembers.map((uid) => {
return (
<li key={uid} className="item">
<User
key={uid}
uid={uid}
interactive={false}
// avatarSize={40}
/>
<User key={uid} uid={uid} interactive={false} />
<CloseIcon className="remove" onClick={removeSelected.bind(null, uid, "user")} />
</li>
);
+20 -37
View File
@@ -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<ConfigType, AgoraConfig | FirebaseConfig | LoginConfig | SMTPConfig>;
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 [values, setValues] = useState<object>({});
const [values, setValues] = useState<valuesOf<ConfigMap> | 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 {
+9 -1
View File
@@ -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) {
+10 -8
View File
@@ -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<GithubAuthConfig | undefined>(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<GithubAuthConfig>) => {
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,
+1 -1
View File
@@ -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}`] || []);
+3 -3
View File
@@ -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();
};
+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 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 }) => {
+5 -1
View File
@@ -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,
+1 -1
View File
@@ -14,7 +14,7 @@ interface Props {
header: ReactElement;
aside: ReactElement | null;
users?: ReactElement;
dropFiles: [File];
dropFiles: File[];
context: "channel" | "user";
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 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 (
<StyledContainer>
<div className="inputs">
-1
View File
@@ -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 });
}
+1 -1
View File
@@ -34,7 +34,7 @@ export interface CreateChannelDTO {
is_public: boolean;
}
export interface ChannelDTO extends Pick<Channel, "owner" | "description" | "name"> {
export interface ChannelDTO extends Partial<Pick<Channel, "owner" | "description" | "name">> {
id: number;
}
+2 -2
View File
@@ -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;