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
+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";