refactor: more TS code

This commit is contained in:
Tristan Yang
2022-07-11 16:28:02 +08:00
parent c7eae47fb2
commit 45a147ae67
18 changed files with 132 additions and 113 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ export const firebaseConfig = {
appId: "1:526613312184:web:d13c92582baf470d487a4d",
measurementId: "G-82RQ3YSCP7"
};
export const ChatPrefixs = {
export const ChatPrefixes = {
channel: "#",
user: "@"
};
+1 -1
View File
@@ -3,7 +3,7 @@ import StyledMenu from "./styled/Menu";
export interface Item {
title: string;
icon: string;
icon?: string;
handler: (e: MouseEvent) => void;
underline?: boolean;
danger?: boolean;
@@ -15,7 +15,7 @@ const PreviewMessage: FC<Props> = ({ mid = 0 }) => {
});
if (!msg) return null;
const { from_uid, created_at, content_type, content, thumbnail, properties } = msg;
const { name, avatar } = usersData[from_uid];
const { name, avatar } = usersData[from_uid] || {};
return (
<StyledWrapper className={`preview`}>
<div className="avatar">
+1 -1
View File
@@ -143,7 +143,7 @@ export default function Reaction({ mid, reactions = null }) {
return (
<StyledWrapper className="reactions">
{Object.entries(reactions).map(([reaction, uids], idx) => {
const reacted = uids.findIndex((id) => id == currUid) > -1;
const reacted = uids.findIndex((id: number) => id == currUid) > -1;
return uids.length > 0 ? (
<span
onClick={handleReact.bind(null, reaction)}
+7 -7
View File
@@ -18,8 +18,6 @@ const StyledCompact = styled.a`
height: 48px;
border-radius: 4px;
img {
/* width: 100%;
height: 100%; */
object-fit: contain;
}
}
@@ -96,15 +94,17 @@ const StyledDetails = styled.a`
export default function URLPreview({ url = "" }) {
const [favicon, setFavicon] = useState("");
const [getInfo] = useLazyGetOGInfoQuery();
const [data, setData] = useState(null);
const [data, setData] = useState<{ title: string; description: string; ogImage: string } | null>(
null
);
useEffect(() => {
const getMetaData = async (url: string) => {
// todo
const { data } = await getInfo(url);
const title = data.title || data.site_name;
const description = data.description;
const ogImage = data.images.find((i) => !!i.url)?.url || "";
const favicon = data.favicon_url || `${new URL(url).origin}/favicon.ico`;
const title = data?.title || data?.site_name || "";
const description = data?.description || "";
const ogImage = data?.images.find((i) => !!i.url)?.url || "";
const favicon = data?.favicon_url || `${new URL(url).origin}/favicon.ico`;
setFavicon(favicon);
setData({ title, description, ogImage });
// console.log("wtf url", data);
+26 -14
View File
@@ -1,8 +1,7 @@
import React, { useRef, useState, useEffect } from "react";
import React, { useRef, useState, useEffect, FC } from "react";
import dayjs from "dayjs";
import isToday from "dayjs/plugin/isToday";
import isYesterday from "dayjs/plugin/isYesterday";
import { useSelector } from "react-redux";
import useInView from "./useInView";
import Tippy from "@tippyjs/react";
import Reaction from "./Reaction";
@@ -17,29 +16,37 @@ import Tooltip from "../Tooltip";
import ContextMenu from "./ContextMenu";
import useContextMenu from "../../hook/useContextMenu";
import usePinMessage from "../../hook/usePinMessage";
import { useAppSelector } from "../../../app/store";
// todo: move to root file
dayjs.extend(isToday);
dayjs.extend(isYesterday);
function Message({
interface IProps {
readOnly?: boolean;
contextId: number;
context?: "user" | "channel";
read?: boolean;
mid: number;
updateReadIndex: (any) => void;
}
const Message: FC<IProps> = ({
readOnly = false,
contextId = 0,
mid = "",
contextId,
mid,
context = "user",
updateReadIndex,
read = true
}) {
}) => {
const { visible: contextMenuVisible, handleContextMenuEvent, hideContextMenu } = useContextMenu();
const inviewRef = useInView();
const [edit, setEdit] = useState(false);
const avatarRef = useRef(null);
const { getPinInfo } = usePinMessage(context == "channel" ? contextId : null);
const { getPinInfo } = usePinMessage(context == "channel" ? contextId : 0);
const {
message = {},
reactionMessageData,
usersData
} = useSelector((store) => {
} = useAppSelector((store) => {
return {
reactionMessageData: store.reactionMessage,
message: store.message[mid] || {},
@@ -75,7 +82,7 @@ function Message({
}, [mid, read]);
const reactions = reactionMessageData[mid];
const currUser = usersData[fromUid] || {};
const currUser = usersData[fromUid];
// if (!message) return null;
let timePrefix = null;
const dayjsTime = dayjs(time);
@@ -104,7 +111,7 @@ function Message({
content={<Profile uid={fromUid} type="card" cid={contextId} />}
>
<div className="avatar" data-uid={fromUid} ref={avatarRef}>
<Avatar url={currUser.avatar} name={currUser.name} />
<Avatar url={currUser?.avatar} name={currUser?.name} />
</div>
</Tippy>
<ContextMenu
@@ -115,9 +122,14 @@ function Message({
visible={contextMenuVisible}
hide={hideContextMenu}
>
<div className="details" data-pin-tip={`pinned by ${usersData[pinInfo?.created_by]?.name}`}>
<div
className="details"
data-pin-tip={`pinned by ${
pinInfo?.created_by ? usersData[pinInfo.created_by]?.name : ""
}`}
>
<div className="up">
<span className="name">{currUser.name}</span>
<span className="name">{currUser?.name}</span>
<Tooltip
delay={200}
disabled={!timePrefix || readOnly}
@@ -166,7 +178,7 @@ function Message({
)}
</StyledWrapper>
);
}
};
export default React.memo(Message, (prevs, nexts) => {
return prevs.mid == nexts.mid;
});
+2 -2
View File
@@ -2,7 +2,7 @@ import { useEffect, useState, FC } from "react";
import useSendMessage from "../../hook/useSendMessage";
import useAddLocalFileMessage from "../../hook/useAddLocalFileMessage";
import { updateInputMode } from "../../../app/slices/ui";
import { ContentTypes, ChatPrefixs } from "../../../app/config";
import { ContentTypes, ChatPrefixes } from "../../../app/config";
import StyledSend from "./styled";
import UploadFileList from "./UploadFileList";
@@ -132,7 +132,7 @@ const Send: FC<IProps> = ({
setMarkdownFullscreen((prev) => !prev);
};
const name = context == "channel" ? channelsData[id]?.name : usersData[id]?.name;
const placeholder = `Send to ${ChatPrefixs[context]}${name} `;
const placeholder = `Send to ${ChatPrefixes[context]}${name} `;
const members =
context == "channel" ? (channelsData[id]?.is_public ? uids : channelsData[id]?.members) : [];
return (
+6 -2
View File
@@ -48,7 +48,11 @@ const getFeedWithPagination = (config: Config): PageInfo => {
};
let curScrollPos = 0;
let oldScroll = 0;
export default function useMessageFeed({ context = "channel", id = null }) {
type Props = {
context?: "channel" | "user";
id: number;
};
export default function useMessageFeed({ context = "channel", id }: Props) {
const [loadMoreChannelMsgs] = useLazyGetHistoryMessagesQuery();
const [loadMoreDmMsgs] = useLazyGetDMHistoryMsg();
const listRef = useRef<number[]>([]);
@@ -83,7 +87,7 @@ export default function useMessageFeed({ context = "channel", id = null }) {
}
}, [items, context, id]);
useEffect(() => {
const serverMids = mids.filter((id) => {
const serverMids = mids.filter((id: number) => {
const ts = +new Date();
return Math.abs(ts - id) > 10 * 1000;
});
+3 -3
View File
@@ -15,15 +15,15 @@ export default function usePinMessage(cid: number) {
const [unpin, { isError: isUnpinError, isLoading: isUnpinning, isSuccess: isUnpinSuccess }] =
useUnpinMessageMutation();
const pinMessage = (mid: number) => {
if (!mid || !cid) return;
if (!mid) return;
pin({ mid, gid: +cid });
};
const unpinMessage = (mid: number) => {
if (!mid || !cid) return;
if (!mid) return;
unpin({ mid, gid: +cid });
};
const getPinInfo = (mid: number) => {
if (!cid || !channel) return;
if (!channel) return;
const pins = channel.pinned_messages;
if (!pins || pins.length == 0) return;
const pinned = pins.find((p) => p.mid == mid);
+12 -8
View File
@@ -1,8 +1,7 @@
import { useState } from "react";
import { useState, FC, MouseEvent } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useDrop } from "react-dnd";
import { NativeTypes } from "react-dnd-html5-backend";
import { useSelector } from "react-redux";
import Tippy from "@tippyjs/react";
import useContextMenu from "../../../common/hook/useContextMenu";
import ContextMenu from "../../../common/component/ContextMenu";
@@ -15,8 +14,13 @@ import { useUpdateMuteSettingMutation } from "../../../app/services/user";
import StyledLink from "./styled";
import ChannelIcon from "../../../common/component/ChannelIcon";
import { getUnreadCount } from "../utils";
const NavItem = ({ id, setFiles, toggleRemoveConfirm }) => {
import { useAppSelector } from "../../../app/store";
interface IProps {
id: number;
setFiles: () => void;
toggleRemoveConfirm: () => void;
}
const NavItem: FC<IProps> = ({ id, setFiles, toggleRemoveConfirm }) => {
const { pathname } = useLocation();
const [inviteModalVisible, setInviteModalVisible] = useState(false);
const navigate = useNavigate();
@@ -29,7 +33,7 @@ const NavItem = ({ id, setFiles, toggleRemoveConfirm }) => {
handleContextMenuEvent,
hideContextMenu
} = useContextMenu();
const { channel, mids, messageData, readIndex, muted, loginUid } = useSelector((store) => {
const { channel, mids, messageData, readIndex, muted, loginUid } = useAppSelector((store) => {
return {
channel: store.channels.byId[id],
mids: store.channelMessage[id],
@@ -39,7 +43,7 @@ const NavItem = ({ id, setFiles, toggleRemoveConfirm }) => {
muted: store.footprint.muteChannels[id]
};
});
const handleChannelSetting = (evt) => {
const handleChannelSetting = (evt: MouseEvent<SVGElement>) => {
evt.preventDefault();
evt.stopPropagation();
const { id } = evt.currentTarget.dataset;
@@ -142,7 +146,7 @@ const NavItem = ({ id, setFiles, toggleRemoveConfirm }) => {
to={`/chat/channel/${id}`}
>
<div className={`name`} title={name}>
<ChannelIcon personal={!is_public} muted={muted} />
<ChannelIcon personal={!is_public} muted={!!muted} />
<span className={`txt ${unreads == 0 ? "read" : ""}`}>{name}</span>
</div>
<div className="icons">
@@ -174,7 +178,7 @@ const NavItem = ({ id, setFiles, toggleRemoveConfirm }) => {
<InviteModal
type="channel"
cid={id}
title={channel.name}
title={channel?.name}
closeModal={toggleInviteModalVisible}
/>
)}
+8 -4
View File
@@ -1,4 +1,4 @@
// import { useState, useEffect } from "react";
import { FC } from "react";
import { useDebounce } from "rooks";
import Tippy from "@tippyjs/react";
import FavList from "../FavList";
@@ -15,8 +15,11 @@ import LoadMore from "../LoadMore";
import { renderMessageFragment } from "../utils";
import useMessageFeed from "../../../common/hook/useMessageFeed";
import { useAppSelector } from "../../../app/store";
export default function DMChat({ uid = 0, dropFiles = [] }) {
type Props = {
uid: number;
dropFiles: [File];
};
const DMChat: FC<Props> = ({ uid = 0, dropFiles }) => {
const {
list: msgIds,
appends,
@@ -104,4 +107,5 @@ export default function DMChat({ uid = 0, dropFiles = [] }) {
</StyledDMChat>
</Layout>
);
}
};
export default DMChat;
+12 -6
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { useEffect, useState, FC } from "react";
import { NavLink, useNavigate, useMatch } from "react-router-dom";
import { useDrop } from "react-dnd";
import { useSelector, useDispatch } from "react-redux";
import { useDispatch } from "react-redux";
import { NativeTypes } from "react-dnd-html5-backend";
import dayjs from "dayjs";
@@ -16,13 +16,20 @@ dayjs.extend(relativeTime);
import { renderPreviewMessage } from "../utils";
import User from "../../../common/component/User";
import { ContentTypes } from "../../../app/config";
const NavItem = ({ uid, mid, unreads, setFiles }) => {
import { useAppSelector } from "../../../app/store";
interface IProps {
uid: number;
mid?: number;
unreads: number;
setFiles: () => void;
}
const NavItem: FC<IProps> = ({ uid, mid = 0, unreads, setFiles }) => {
const [previewMsg, setPreviewMsg] = useState(null);
const { messages: normalizedMessages, normalizeMessage } = useNormalizeMessage();
const dispatch = useDispatch();
const pathMatched = useMatch(`/chat/dm/${uid}`);
const [updateReadIndex] = useReadMessageMutation();
const { currMsg, currUser } = useSelector((store) => {
const { currMsg, currUser } = useAppSelector((store) => {
return {
currUser: store.users.byId[uid],
currMsg: store.message[mid]
@@ -73,7 +80,6 @@ const NavItem = ({ uid, mid, unreads, setFiles }) => {
}
};
if (!currUser) return null;
// console.log("preview msg", previewMsg, normalizedMessages);
return (
<Tippy
interactive
@@ -107,7 +113,7 @@ const NavItem = ({ uid, mid, unreads, setFiles }) => {
to={`/chat/dm/${uid}`}
onContextMenu={handleContextMenuEvent}
>
<User compact interactive={false} className="avatar" uid={uid} />
<User compact interactive={false} uid={uid} />
<div className="details">
<div className="up">
<span className="name">{currUser.name}</span>
-1
View File
@@ -102,7 +102,6 @@ export default function FavList({ cid = null, uid = null }) {
) : (
<ul className="list">
{favorites.map(({ id }) => {
console.log("favv", id);
return (
<li key={id} className="fav">
<FavoredMessage id={id} />
+25 -27
View File
@@ -1,4 +1,4 @@
import { useState, useRef, useEffect, FC, ReactElement } from "react";
import { useState, useRef, useEffect, FC, ReactElement, MouseEvent } from "react";
import { useDrop } from "react-dnd";
import { NativeTypes } from "react-dnd-html5-backend";
import ImagePreviewModal from "../../../common/component/ImagePreviewModal";
@@ -6,17 +6,17 @@ import Send from "../../../common/component/Send";
import Styled from "./styled";
import Operations from "./Operations";
import useUploadFile from "../../../common/hook/useUploadFile";
import { ChatPrefixs } from "../../../app/config";
import { ChatPrefixes } from "../../../app/config";
import { useAppSelector } from "../../../app/store";
interface Props {
children: ReactElement;
header: ReactElement;
aside: ReactElement | null;
users: ReactElement | null;
dropFiles: [];
context: string;
to: number | null;
users?: ReactElement;
dropFiles: [File];
context: "channel" | "user";
to: number;
}
const Layout: FC<Props> = ({
@@ -26,7 +26,7 @@ const Layout: FC<Props> = ({
users = null,
dropFiles = [],
context = "channel",
to = null
to
}) => {
const { addStageFile } = useUploadFile({ context, id: to });
const messagesContainer = useRef<HTMLDivElement>(null);
@@ -42,7 +42,6 @@ const Layout: FC<Props> = ({
() => ({
accept: [NativeTypes.FILE],
drop({ files }) {
console.log("drop files", files, context, to);
if (files.length) {
const filesData = files.map((file) => {
const { size, type, name } = file;
@@ -76,24 +75,23 @@ const Layout: FC<Props> = ({
useEffect(() => {
const container = messagesContainer?.current;
if (container) {
// 点击查看大图
container.addEventListener(
"click",
(evt) => {
console.log(evt);
const { target } = evt;
if (target.nodeName == "IMG" && target.classList.contains("preview")) {
const thumbnail = target.src;
const originUrl = target.dataset.origin || target.src;
const downloadLink = target.dataset.download || target.src;
const meta = JSON.parse(target.dataset.meta || "{}");
setPreviewImage({ thumbnail, originUrl, downloadLink, ...meta });
}
},
true
);
}
if (!container) return;
// 点击查看大图
container.addEventListener(
"click",
(evt) => {
const target = evt.target as HTMLImageElement;
if (!target) return;
if (target.nodeName == "IMG" && target.classList.contains("preview")) {
const thumbnail = target.src;
const originUrl = target.dataset.origin || target.src;
const downloadLink = target.dataset.download || target.src;
const meta = JSON.parse(target.dataset.meta || "{}");
setPreviewImage({ thumbnail, originUrl, downloadLink, ...meta });
}
},
true
);
}, []);
const name = context == "channel" ? channelsData[to]?.name : usersData[to]?.name;
@@ -116,7 +114,7 @@ const Layout: FC<Props> = ({
<div className={`drag_tip ${isActive ? "visible animate__animated animate__fadeIn" : ""}`}>
<div className={`box ${isActive ? "animate__animated animate__bounceIn" : ""}`}>
<div className="inner">
<h4 className="head">{`Send to ${ChatPrefixs[context]}${name}`}</h4>
<h4 className="head">{`Send to ${ChatPrefixes[context]}${name}`}</h4>
<span className="intro">Photos accept jpg, png, max size limit to 10M.</span>
</div>
</div>
-1
View File
@@ -111,7 +111,6 @@ const Styled = styled.article`
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
visibility: hidden;
/* pointer-events: none; */
&.visible {
visibility: visible;
}
+16 -19
View File
@@ -1,5 +1,4 @@
import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { useState, useEffect, FC } from "react";
import dayjs from "dayjs";
import { useDrop } from "react-dnd";
import { NativeTypes } from "react-dnd-html5-backend";
@@ -8,22 +7,29 @@ import ContextMenu from "./ContextMenu";
import getUnreadCount, { renderPreviewMessage } from "../utils";
import User from "../../../common/component/User";
import Avatar from "../../../common/component/Avatar";
import iconChannel from "../../../assets/icons/channel.svg?url";
// import iconChannel from "../../../assets/icons/channel.svg?url";
import IconLock from "../../../assets/icons/lock.svg";
import useContextMenu from "../../../common/hook/useContextMenu";
import { useNavigate, NavLink } from "react-router-dom";
import useUploadFile from "../../../common/hook/useUploadFile";
import { useAppSelector } from "../../../app/store";
// todo: move to root file
dayjs.extend(relativeTime);
export default function Session({
interface IProps {
type?: "user" | "channel";
id: number;
mid: number;
setDeleteChannelId: () => void;
setInviteChannelId: () => void;
}
const Session: FC<IProps> = ({
type = "user",
id,
mid,
setDeleteChannelId,
setInviteChannelId
}) {
}) => {
const navigate = useNavigate();
const { addStageFile } = useUploadFile({ context: type, id });
@@ -51,7 +57,7 @@ export default function Session({
const { visible: contextMenuVisible, handleContextMenuEvent, hideContextMenu } = useContextMenu();
const [data, setData] = useState(null);
const { messageData, userData, channelData, readIndex, loginUid, mids, muted } = useSelector(
const { messageData, userData, channelData, readIndex, loginUid, mids, muted } = useAppSelector(
(store) => {
return {
mids: type == "user" ? store.userMessage.byId[id] : store.channelMessage[id],
@@ -66,11 +72,6 @@ export default function Session({
}
);
const handleImageError = (evt) => {
evt.target.classList.add("channel_default");
evt.target.src = iconChannel;
};
useEffect(() => {
const tmp = type == "user" ? userData[id] : channelData[id];
if (!tmp) return;
@@ -108,14 +109,9 @@ export default function Session({
>
<div className="icon">
{type == "user" ? (
<User avatarSize={40} compact interactive={false} className="avatar" uid={id} />
<User avatarSize={40} compact interactive={false} uid={id} />
) : (
<Avatar className="icon" type="channel" name={name} url={icon} />
// <img
// className={`${icon ? "" : "channel_default"}`}
// onError={handleImageError}
// src={icon || iconChannel}
// />
)}
</div>
<div className="details">
@@ -140,4 +136,5 @@ export default function Session({
</ContextMenu>
</li>
);
}
};
export default Session;
+3 -15
View File
@@ -2,7 +2,7 @@ import React from "react";
import dayjs from "dayjs";
import styled from "styled-components";
import reactStringReplace from "react-string-replace";
import { useDispatch, useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { isImage } from "../../common/utils";
import { ContentTypes } from "../../app/config";
import Checkbox from "../../common/component/styled/Checkbox";
@@ -10,19 +10,7 @@ import Divider from "../../common/component/Divider";
import Message from "../../common/component/Message";
import { updateSelectMessages } from "../../app/slices/ui";
import Mention from "../../common/component/Message/Mention";
// function debounce(callback, wait = 2000, immediate = false) {
// let timeout = null;
// return function () {
// const callNow = immediate && !timeout;
// const next = () => callback.apply(this, arguments);
// clearTimeout(timeout);
// timeout = setTimeout(next, wait);
// if (callNow) {
// next();
// }
// };
// }
import { useAppSelector } from "../../app/store";
export function getUnreadCount({ mids = [], messageData = {}, loginUid = 0, readIndex = 0 }) {
// console.log({ mids, loginUid, readIndex });
@@ -130,7 +118,7 @@ const StyledWrapper = styled.div`
const MessageWrapper = ({ selectMode = false, context, id, mid, children, ...rest }) => {
const dispatch = useDispatch();
const selects = useSelector((store) => store.ui.selectMessages[`${context}_${id}`]);
const selects = useAppSelector((store) => store.ui.selectMessages[`${context}_${id}`]);
const selected = !!(selects && selects.find((s) => s == mid));
const toggleSelect = () => {
const operation = selected ? "remove" : "add";