refactor: more TS code
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
// import React from 'react'
|
||||
import { useDispatch } from "react-redux";
|
||||
import { addMessage } from "../../app/slices/message";
|
||||
import { addMessage, MessagePayload } from "../../app/slices/message";
|
||||
import { addChannelMsg } from "../../app/slices/message.channel";
|
||||
import { addUserMsg } from "../../app/slices/message.user";
|
||||
|
||||
@@ -8,11 +8,10 @@ interface IProps {
|
||||
context: "channel" | "user";
|
||||
to: number;
|
||||
}
|
||||
|
||||
export default function useAddLocalFileMessage({ context, to }: IProps) {
|
||||
const dispatch = useDispatch();
|
||||
const addContextMessage = context == "channel" ? addChannelMsg : addUserMsg;
|
||||
const addLocalFileMessage = (data) => {
|
||||
const addLocalFileMessage = (data: MessagePayload) => {
|
||||
dispatch(addMessage(data));
|
||||
dispatch(addContextMessage({ id: to, mid: data.mid }));
|
||||
};
|
||||
|
||||
@@ -3,18 +3,6 @@ import { useRef, useEffect } from "react";
|
||||
|
||||
function useChatScroll<T extends HTMLElement>() {
|
||||
const ref = useRef<T>(null);
|
||||
// useEffect(() => {
|
||||
// console.log("chat scroll", ref);
|
||||
// if (ref.current) {
|
||||
// // setTimeout(() => {
|
||||
// if (ref.current) {
|
||||
// setTimeout(() => {
|
||||
// ref.current.scrollTop = ref.current.scrollHeight;
|
||||
// }, 500);
|
||||
// }
|
||||
// // }, 20);
|
||||
// }
|
||||
// }, [...deps]);
|
||||
useEffect(() => {
|
||||
if (ref.current) {
|
||||
console.log("chat scroll", ref);
|
||||
|
||||
@@ -38,13 +38,13 @@ const useCopy = (config: { enableToast: boolean } | void) => {
|
||||
if (!copied) {
|
||||
if (!isImage) {
|
||||
setCopied(copyToClipboard(text));
|
||||
inter = setTimeout(() => {
|
||||
inter = window.setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, 500);
|
||||
} else {
|
||||
copyImageToClipboard(text).then(() => {
|
||||
setCopied(true);
|
||||
inter = setTimeout(() => {
|
||||
inter = window.setTimeout(() => {
|
||||
setCopied(false);
|
||||
}, 500);
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ export default function useDeleteMessage() {
|
||||
remove
|
||||
// { isError, isLoading, isSuccess },
|
||||
] = useLazyDeleteMessageQuery();
|
||||
const deleteMessage = async (mids) => {
|
||||
const deleteMessage = async (mids: number[]) => {
|
||||
if (!mids) return;
|
||||
const _arr = Array.isArray(mids) ? mids : [mids];
|
||||
setDeleting(true);
|
||||
@@ -26,18 +26,12 @@ export default function useDeleteMessage() {
|
||||
const canDelete = (mids = []) => {
|
||||
if (!mids || mids.length == 0) return false;
|
||||
// 管理员
|
||||
if (loginUser.is_admin) return true;
|
||||
if (loginUser?.is_admin) return true;
|
||||
// 检查是否是自己的消息
|
||||
return mids.every((mid) => {
|
||||
return messageData[mid]?.from_uid == loginUser.uid;
|
||||
return messageData[mid]?.from_uid == loginUser?.uid;
|
||||
});
|
||||
};
|
||||
// useEffect(() => {
|
||||
// if (channel) {
|
||||
// setPins(channel.pinned_messages);
|
||||
// }
|
||||
// }, [channel]);
|
||||
|
||||
return {
|
||||
canDelete,
|
||||
isDeleting: deleting,
|
||||
|
||||
@@ -13,7 +13,7 @@ export default function useDraft({ context = "", id = "" }) {
|
||||
|
||||
const getUpdateDraft = (type = "mixed") => {
|
||||
const update = type == "mixed" ? updateDraftMixedText : updateDraftMarkdown;
|
||||
return (value) => {
|
||||
return (value: string) => {
|
||||
dispatch(update({ key: _key, value }));
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useLazyRemoveFavoriteQuery, useFavoriteMessageMutation } from "../../app/services/message";
|
||||
import { Favorite } from "../../app/slices/favorites";
|
||||
import { useAppSelector } from "../../app/store";
|
||||
|
||||
export default function useFavMessage({
|
||||
@@ -11,7 +12,7 @@ export default function useFavMessage({
|
||||
}) {
|
||||
const [removeFav] = useLazyRemoveFavoriteQuery();
|
||||
const [addFav] = useFavoriteMessageMutation();
|
||||
const [favorites, setFavorites] = useState([]);
|
||||
const [favorites, setFavorites] = useState<Favorite[]>([]);
|
||||
const { favs = [] } = useAppSelector((store) => {
|
||||
return { favs: store.favorites };
|
||||
});
|
||||
@@ -23,16 +24,16 @@ export default function useFavMessage({
|
||||
return !error;
|
||||
};
|
||||
|
||||
const removeFavorite = (id) => {
|
||||
const removeFavorite = (id: number) => {
|
||||
if (!id) return;
|
||||
removeFav(id);
|
||||
};
|
||||
|
||||
const isFavorited = (mid = null) => {
|
||||
if (!mid) return false;
|
||||
let mids = [];
|
||||
favorites.forEach((f) => {
|
||||
if (f.messages.length == 1) {
|
||||
let mids: number[] = [];
|
||||
favorites.forEach((f: Favorite) => {
|
||||
if (f?.messages?.length == 1) {
|
||||
const ids = f.messages.map((m) => m.from_mid);
|
||||
mids = [...mids, ...ids];
|
||||
}
|
||||
@@ -41,7 +42,7 @@ export default function useFavMessage({
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let filtereds = [];
|
||||
let filtereds: Favorite[] = [];
|
||||
filtereds = cid
|
||||
? favs.filter((f) => {
|
||||
if (!f.messages) return false;
|
||||
|
||||
@@ -56,7 +56,7 @@ export default function useMessageFeed({ context = "channel", id }: Props) {
|
||||
const [loadMoreChannelMsgs] = useLazyGetHistoryMessagesQuery();
|
||||
const [loadMoreDmMsgs] = useLazyGetDMHistoryMsg();
|
||||
const listRef = useRef<number[]>([]);
|
||||
const pageRef = useRef<object | null>(null);
|
||||
const pageRef = useRef<PageInfo | null>(null);
|
||||
const containerRef = useRef<HTMLElement | null>(null);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
const [appends, setAppends] = useState([]);
|
||||
@@ -141,12 +141,12 @@ export default function useMessageFeed({ context = "channel", id }: Props) {
|
||||
mid: firstMid,
|
||||
id
|
||||
});
|
||||
if (newList.length == 0) {
|
||||
if (newList?.length == 0) {
|
||||
setHasMore(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let pageInfo = null;
|
||||
let pageInfo: PageInfo;
|
||||
if (!currPageInfo) {
|
||||
// 初始化
|
||||
pageInfo = getFeedWithPagination({
|
||||
@@ -173,7 +173,7 @@ export default function useMessageFeed({ context = "channel", id }: Props) {
|
||||
oldScroll = container.scrollHeight - container.clientHeight;
|
||||
}
|
||||
},
|
||||
currPageInfo.isLast ? 10 : 800
|
||||
currPageInfo?.isLast ? 10 : 800
|
||||
);
|
||||
};
|
||||
const pullDown = () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { normalizeArchiveData, ArchiveMessage } from "../utils";
|
||||
import { normalizeArchiveData } from "../utils";
|
||||
import { useLazyGetArchiveMessageQuery } from "../../app/services/message";
|
||||
import { ArchiveMessage } from "../../types/resource";
|
||||
|
||||
export default function useNormalizeMessage() {
|
||||
const [filePath, setFilePath] = useState<string | null>(null);
|
||||
|
||||
@@ -7,9 +7,18 @@ import { addUserMsg, removeUserMsg } from "../../../app/slices/message.user";
|
||||
import { updateAfterMid } from "../../../app/slices/footprint";
|
||||
import { ContentTypes } from "../../../app/config";
|
||||
import { ChatEvent } from "../../../types/sse";
|
||||
import { AppDispatch, RootState } from "../../../app/store";
|
||||
|
||||
const handler = (data: ChatEvent, dispatch: AppDispatch, currState: RootState) => {
|
||||
import { AppDispatch } from "../../../app/store";
|
||||
type CurrentState = {
|
||||
ready: boolean;
|
||||
loginUid: number;
|
||||
readUsers: {
|
||||
[key: number]: number;
|
||||
};
|
||||
readChannels: {
|
||||
[key: number]: number;
|
||||
};
|
||||
};
|
||||
const handler = (data: ChatEvent, dispatch: AppDispatch, currState: CurrentState) => {
|
||||
const {
|
||||
mid,
|
||||
from_uid,
|
||||
@@ -41,7 +50,7 @@ const handler = (data: ChatEvent, dispatch: AppDispatch, currState: RootState) =
|
||||
break;
|
||||
}
|
||||
const { ready, loginUid, readUsers = {}, readChannels = {} } = currState;
|
||||
const to = typeof target.gid !== "undefined" ? "channel" : "user";
|
||||
const to = "gid" in target ? "channel" : "user";
|
||||
const appendMessage = to == "user" ? addUserMsg : addChannelMsg;
|
||||
const self = from_uid == loginUid;
|
||||
// 此处有点绕
|
||||
|
||||
@@ -22,13 +22,13 @@ import { updateUsersByLogs, updateUsersStatus } from "../../../app/slices/users"
|
||||
import { resetAuthData } from "../../../app/slices/auth.data";
|
||||
import chatMessageHandler from "./chat.handler";
|
||||
import store, { useAppDispatch, useAppSelector } from "../../../app/store";
|
||||
import { ServerEvent } from "../../../types/sse";
|
||||
import { ServerEvent, UsersStateEvent } from "../../../types/sse";
|
||||
|
||||
class RetriableError extends Error {}
|
||||
|
||||
class FatalError extends Error {}
|
||||
|
||||
const getQueryString = (params = {}) => {
|
||||
const getQueryString = (params: { [key: string]: string }) => {
|
||||
const sp = new URLSearchParams();
|
||||
Object.entries(params).forEach(([key, val]) => {
|
||||
if (val) {
|
||||
@@ -37,11 +37,6 @@ const getQueryString = (params = {}) => {
|
||||
});
|
||||
return sp.toString();
|
||||
};
|
||||
// const StreamStatus = {
|
||||
// waiting: "waiting",
|
||||
// initialized: "initialized",
|
||||
// streaming: "streaming",
|
||||
// };
|
||||
let inter: number | null = null;
|
||||
|
||||
export default function useStreaming() {
|
||||
@@ -53,7 +48,7 @@ export default function useStreaming() {
|
||||
} = useAppSelector((store) => store);
|
||||
const [renewToken] = useRenewMutation();
|
||||
const dispatch = useAppDispatch();
|
||||
const loginUid = authData.user?.uid;
|
||||
const loginUid = authData.user?.uid || 0;
|
||||
let initialized = false;
|
||||
let initializing = false;
|
||||
let controller = new AbortController();
|
||||
@@ -63,21 +58,20 @@ export default function useStreaming() {
|
||||
if (initialized || initializing) return;
|
||||
// 如果token快要过期,先renew
|
||||
const {
|
||||
authData: { token, expireTime = +new Date(), refreshToken }
|
||||
authData: { token = "", expireTime = +new Date(), refreshToken }
|
||||
} = store.getState();
|
||||
let api_token = token;
|
||||
const tokenAlmostExpire = dayjs().isAfter(new Date(expireTime - 20 * 1000));
|
||||
console.log("check token expire time", tokenAlmostExpire);
|
||||
if (tokenAlmostExpire) {
|
||||
const {
|
||||
data: { token: newToken },
|
||||
isError
|
||||
} = await renewToken({
|
||||
const resp = await renewToken({
|
||||
token,
|
||||
refresh_token: refreshToken
|
||||
});
|
||||
if (isError) return;
|
||||
api_token = newToken;
|
||||
if ("error" in resp) return;
|
||||
if ("data" in resp) {
|
||||
api_token = resp.data.token;
|
||||
}
|
||||
}
|
||||
|
||||
// 开始初始化
|
||||
@@ -85,8 +79,8 @@ export default function useStreaming() {
|
||||
await fetchEventSource(
|
||||
`${BASE_URL}/user/events?${getQueryString({
|
||||
"api-key": api_token,
|
||||
users_version: usersVersion,
|
||||
after_mid: afterMid
|
||||
users_version: `${usersVersion}`,
|
||||
after_mid: `${afterMid}`
|
||||
})}`,
|
||||
{
|
||||
openWhenHidden: true,
|
||||
@@ -186,7 +180,8 @@ export default function useStreaming() {
|
||||
case "users_state_changed":
|
||||
{
|
||||
let { type, ...rest } = data;
|
||||
const onlines = type == "users_state_changed" ? [rest] : rest.users;
|
||||
const onlines =
|
||||
type == "users_state_changed" ? [rest] : (rest as UsersStateEvent).users;
|
||||
dispatch(updateUsersStatus(onlines));
|
||||
}
|
||||
break;
|
||||
@@ -300,7 +295,7 @@ export default function useStreaming() {
|
||||
clearTimeout(inter);
|
||||
}
|
||||
// 重连
|
||||
inter = setTimeout(() => {
|
||||
inter = window.setTimeout(() => {
|
||||
initialized = false;
|
||||
startStreaming();
|
||||
}, 2000);
|
||||
@@ -323,7 +318,7 @@ export default function useStreaming() {
|
||||
}
|
||||
};
|
||||
|
||||
const setStreamingReady = (ready) => {
|
||||
const setStreamingReady = (ready: boolean) => {
|
||||
setReadyPullData(ready);
|
||||
};
|
||||
|
||||
|
||||
@@ -92,7 +92,8 @@ export const getInitialsAvatar = ({
|
||||
canvas.style.width = `${width}px`;
|
||||
canvas.style.height = `${height}px`;
|
||||
|
||||
const context = canvas.getContext("2d");
|
||||
const context = canvas.getContext("2d") as CanvasRenderingContext2D;
|
||||
|
||||
context.scale(devicePixelRatio, devicePixelRatio);
|
||||
context.rect(0, 0, canvas.width, canvas.height);
|
||||
context.fillStyle = background;
|
||||
@@ -115,7 +116,7 @@ export const getInitialsAvatar = ({
|
||||
* @param {Number} - chunksAmount
|
||||
* @return {Array} - an array of Blobs
|
||||
**/
|
||||
export function sliceFile(file, chunksAmount) {
|
||||
export function sliceFile(file: File | null, chunksAmount: number) {
|
||||
if (!file) return null;
|
||||
let byteIndex = 0;
|
||||
let chunks = [];
|
||||
@@ -194,7 +195,7 @@ export const normalizeArchiveData = (
|
||||
};
|
||||
return messages.map(
|
||||
({ source, mid, content, file_id, thumbnail_id, content_type, properties, from_user }) => {
|
||||
let user = { ...(users[from_user] || {}) };
|
||||
let user = users[from_user] ?? {};
|
||||
const { transformedContent, thumbnail, download, avatarUrl } = getUrls(uid, {
|
||||
content,
|
||||
content_type,
|
||||
|
||||
Reference in New Issue
Block a user