refactor: more TS code

This commit is contained in:
Tristan Yang
2022-07-29 22:59:22 +08:00
parent 6bb7af46a0
commit 33c24baecb
52 changed files with 232 additions and 273 deletions
+2 -2
View File
@@ -17,8 +17,8 @@ import { getUnreadCount } from "../utils";
import { useAppSelector } from "../../../app/store";
interface IProps {
id: number;
setFiles: () => void;
toggleRemoveConfirm: () => void;
setFiles: (files: File[]) => void;
toggleRemoveConfirm: (id: number) => void;
}
const NavItem: FC<IProps> = ({ id, setFiles, toggleRemoveConfirm }) => {
const { pathname } = useLocation();
+3 -3
View File
@@ -3,13 +3,13 @@ import DeleteConfirmModal from "../../settingChannel/DeleteConfirmModal";
import NavItem from "./NavItem";
import { useAppSelector } from "../../../app/store";
export default function ChannelList({ setDropFiles }) {
const [currId, setCurrId] = useState(null);
export default function ChannelList({ setDropFiles }: { setDropFiles: (files: File[]) => void }) {
const [currId, setCurrId] = useState<number>();
const { channelIds } = useAppSelector((store) => {
return { channelIds: store.channels.ids };
});
const setRemoveChannel = (cid = undefined) => {
const setRemoveChannel = (cid?: number) => {
setCurrId(cid);
};
+1 -1
View File
@@ -17,7 +17,7 @@ import useMessageFeed from "../../../common/hook/useMessageFeed";
import { useAppSelector } from "../../../app/store";
type Props = {
uid: number;
dropFiles?: [File];
dropFiles?: File[];
};
const DMChat: FC<Props> = ({ uid = 0, dropFiles }) => {
const {
+3 -2
View File
@@ -15,6 +15,7 @@ import { renderPreviewMessage } from "../utils";
import User from "../../../common/component/User";
import { ContentTypes } from "../../../app/config";
import { useAppSelector } from "../../../app/store";
import { ArchiveMessage } from "../../../types/resource";
interface IProps {
uid: number;
mid?: number;
@@ -22,7 +23,7 @@ interface IProps {
setFiles: () => void;
}
const NavItem: FC<IProps> = ({ uid, mid = 0, unreads, setFiles }) => {
const [previewMsg, setPreviewMsg] = useState(null);
const [previewMsg, setPreviewMsg] = useState<ArchiveMessage>();
const { messages: normalizedMessages, normalizeMessage } = useNormalizeMessage();
const dispatch = useDispatch();
const pathMatched = useMatch(`/chat/dm/${uid}`);
@@ -63,7 +64,7 @@ const NavItem: FC<IProps> = ({ uid, mid = 0, unreads, setFiles }) => {
}, [currMsg]);
useEffect(() => {
if (normalizedMessages) {
setPreviewMsg(normalizedMessages.pop());
setPreviewMsg(normalizedMessages?.pop());
}
}, [normalizedMessages]);
+1 -1
View File
@@ -5,7 +5,7 @@ import { useAppSelector } from "../../../app/store";
interface Props {
uids: number[];
setDropFiles: () => void;
setDropFiles: (files: File[]) => void;
}
const DMList: FC<Props> = ({ uids, setDropFiles }) => {
+1 -1
View File
@@ -86,7 +86,7 @@ type Props = { cid?: number; uid?: number };
const FavList: FC<Props> = ({ cid = null, uid = null }) => {
const { favorites, removeFavorite } = useFavMessage({ cid, uid });
const handleRemove = (evt: MouseEvent<HTMLButtonElement>) => {
const { id } = evt.currentTarget.dataset;
const { id = "" } = evt.currentTarget.dataset;
console.log("remove fav", id);
removeFavorite(id);
};
+17 -6
View File
@@ -1,3 +1,4 @@
import { FC, ReactElement } from "react";
import Tippy from "@tippyjs/react";
import { useDispatch } from "react-redux";
import { useNavigate, useLocation, useMatch } from "react-router-dom";
@@ -7,8 +8,17 @@ import { removeUserSession } from "../../../app/slices/message.user";
import ContextMenu from "../../../common/component/ContextMenu";
import useUserOperation from "../../../common/hook/useUserOperation";
import { useAppSelector } from "../../../app/store";
export default function SessionContextMenu({
type Props = {
context: "user" | "channel";
id: number;
visible: boolean;
mid: number;
hide: () => void;
deleteChannel: (param: number) => void;
setInviteChannelId: (param: number) => void;
children: ReactElement;
};
const SessionContextMenu: FC<Props> = ({
context = "user",
id,
visible,
@@ -17,10 +27,10 @@ export default function SessionContextMenu({
deleteChannel,
setInviteChannelId,
children
}) {
}) => {
const { canCopyEmail, copyEmail, canDeleteChannel } = useUserOperation({
uid: context == "user" ? id : null,
cid: context == "channel" ? id : null
uid: context == "user" ? id : undefined,
cid: context == "channel" ? id : undefined
});
const [muteChannel] = useUpdateMuteSettingMutation();
const [updateReadIndex] = useReadMessageMutation();
@@ -114,4 +124,5 @@ export default function SessionContextMenu({
{children}
</Tippy>
);
}
};
export default SessionContextMenu;
+18 -8
View File
@@ -16,8 +16,8 @@ interface IProps {
type?: "user" | "channel";
id: number;
mid: number;
setDeleteChannelId: () => void;
setInviteChannelId: () => void;
setDeleteChannelId: (param: number) => void;
setInviteChannelId: (param: number) => void;
}
const Session: FC<IProps> = ({
type = "user",
@@ -52,12 +52,17 @@ const Session: FC<IProps> = ({
);
const { visible: contextMenuVisible, handleContextMenuEvent, hideContextMenu } = useContextMenu();
const [data, setData] = useState(null);
const [data, setData] = useState<{
name: string;
icon: string;
mid: number;
is_public: boolean;
}>();
const { messageData, userData, channelData, readIndex, loginUid, mids, muted } = useAppSelector(
(store) => {
return {
mids: type == "user" ? store.userMessage.byId[id] : store.channelMessage[id],
loginUid: store.authData.user?.uid,
loginUid: store.authData.user?.uid || 0,
readIndex:
type == "user" ? store.footprint.readUsers[id] : store.footprint.readChannels[id],
messageData: store.message,
@@ -71,10 +76,15 @@ const Session: FC<IProps> = ({
useEffect(() => {
const tmp = type == "user" ? userData[id] : channelData[id];
if (!tmp) return;
const { name, icon, avatar, is_public = true } = tmp;
const session =
type == "user" ? { name, icon: avatar, mid, is_public } : { name, icon, mid, is_public };
setData(session);
if ("avatar" in tmp) {
// user
const { name, avatar } = tmp;
setData({ name, icon: avatar, mid, is_public: true });
} else {
// channel
const { name, icon = "", is_public } = tmp;
setData({ name, icon, mid, is_public });
}
}, [id, mid, type, userData, channelData]);
if (!data) return null;
const previewMsg = messageData[mid] || {};
+28 -16
View File
@@ -1,14 +1,24 @@
import { FC } from "react";
import { useState, useEffect } from "react";
import Styled from "./styled";
import Session from "./Session";
import DeleteChannelConfirmModal from "../../settingChannel/DeleteConfirmModal";
import InviteModal from "../../../common/component/InviteModal";
import { useAppSelector } from "../../../app/store";
export default function SessionList({ tempSession = null }) {
const [deleteId, setDeleteId] = useState(null);
const [inviteChannelId, setInviteChannelId] = useState(null);
const [sessions, setSessions] = useState([]);
export interface ChatSession {
key: string;
type: "user" | "channel";
id: number;
mid?: number;
unread?: number;
}
type Props = {
tempSession: ChatSession;
};
const SessionList: FC<Props> = ({ tempSession }) => {
const [deleteId, setDeleteId] = useState<number>();
const [inviteChannelId, setInviteChannelId] = useState<number>();
const [sessions, setSessions] = useState<ChatSession[]>([]);
const { channelIDs, DMs, readChannels, readUsers, channelMessage, userMessage, loginUid } =
useAppSelector((store) => {
return {
@@ -26,7 +36,7 @@ export default function SessionList({ tempSession = null }) {
const cSessions = channelIDs.map((id) => {
const mids = channelMessage[id];
if (!mids || mids.length == 0) {
return { key: `channel_${id}`, mid: null, unreads: 0, id, type: "channel" };
return { key: `channel_${id}`, unreads: 0, id, type: "channel" };
}
const mid = [...mids].pop();
return { key: `channel_${id}`, id, mid, type: "channel" };
@@ -34,13 +44,15 @@ export default function SessionList({ tempSession = null }) {
const uSessions = DMs.map((id) => {
const mids = userMessage[id];
if (!mids || mids.length == 0) {
return { key: `user_${id}`, mid: null, unreads: 0, id, type: "user" };
return { key: `user_${id}`, unreads: 0, id, type: "user" };
}
const mid = [...mids].pop();
return { key: `user_${id}`, type: "user", id, mid };
});
const tmps = [...cSessions, ...uSessions].sort((a, b) => {
return b.mid - a.mid;
const tmps = [...(cSessions as ChatSession[]), ...(uSessions as ChatSession[])].sort((a, b) => {
const { mid: aMid = 0 } = a;
const { mid: bMid = 0 } = b;
return bMid - aMid;
});
setSessions(tempSession ? [tempSession, ...tmps] : tmps);
}, [
@@ -58,7 +70,7 @@ export default function SessionList({ tempSession = null }) {
<>
<Styled>
{sessions.map((s) => {
const { key, type, id, mid } = s;
const { key, type, id, mid = 0 } = s;
return (
<Session
key={key}
@@ -67,28 +79,28 @@ export default function SessionList({ tempSession = null }) {
mid={mid}
setInviteChannelId={setInviteChannelId}
setDeleteChannelId={setDeleteId}
className="session"
/>
);
})}
</Styled>
{deleteId && (
{!!deleteId && (
<DeleteChannelConfirmModal
id={deleteId}
closeModal={() => {
setDeleteId(null);
setDeleteId(0);
}}
/>
)}
{inviteChannelId && (
{!!inviteChannelId && (
<InviteModal
type="channel"
cid={inviteChannelId}
closeModal={() => {
setInviteChannelId(null);
setInviteChannelId(0);
}}
/>
)}
</>
);
}
};
export default SessionList;
+5 -7
View File
@@ -9,8 +9,6 @@ import AddIcon from "../../assets/icons/add.svg";
import BlankPlaceholder from "../../common/component/BlankPlaceholder";
import Server from "../../common/component/Server";
import Tooltip from "../../common/component/Tooltip";
// import User from "../../common/component/User";
// import CurrentUser from "../../common/component/CurrentUser";
import ChannelChat from "./ChannelChat";
import DMChat from "./DMChat";
import ChannelList from "./ChannelList";
@@ -20,8 +18,8 @@ import DMList from "./DMList";
import { useAppSelector } from "../../app/store";
export default function ChatPage() {
const [channelDropFiles, setChannelDropFiles] = useState([]);
const [userDropFiles, setUserDropFiles] = useState([]);
const [channelDropFiles, setChannelDropFiles] = useState<File[]>([]);
const [userDropFiles, setUserDropFiles] = useState<File[]>([]);
const { sessionUids } = useAppSelector((store) => {
return {
sessionUids: store.userMessage.ids
@@ -40,7 +38,7 @@ export default function ChatPage() {
const { currentTarget } = evt;
currentTarget.classList.toggle("collapse");
};
const tmpUid = sessionUids.findIndex((i) => i == +user_id) > -1 ? null : user_id;
const tmpUid = sessionUids.findIndex((i) => i == +user_id) > -1 ? 0 : +user_id;
// console.log("temp uid", tmpUid);
const placeholderVisible = !channel_id && !user_id;
return (
@@ -87,8 +85,8 @@ export default function ChatPage() {
</div>
<div className={`right ${placeholderVisible ? "placeholder" : ""}`}>
{placeholderVisible && <BlankPlaceholder />}
{channel_id && <ChannelChat cid={channel_id} dropFiles={channelDropFiles} />}
{user_id && <DMChat uid={user_id} dropFiles={userDropFiles} />}
{channel_id && <ChannelChat cid={+channel_id} dropFiles={channelDropFiles} />}
{user_id && <DMChat uid={+user_id} dropFiles={userDropFiles} />}
</div>
</StyledWrapper>
</>
+2 -2
View File
@@ -1,4 +1,4 @@
import React from "react";
import React, { ReactElement, ReactNode } from "react";
import dayjs from "dayjs";
import styled from "styled-components";
import reactStringReplace from "react-string-replace";
@@ -60,7 +60,7 @@ export const renderPreviewMessage = (message = null) => {
res = reactStringReplace(content, /(\s{1}@[0-9]+\s{1})/g, (match, idx) => {
console.log("match", match);
const uid = match.trim().slice(1);
return <Mention key={idx} uid={uid} textOnly={true} />;
return <Mention key={idx} uid={+uid} textOnly={true} />;
});
}
break;
+3 -7
View File
@@ -5,11 +5,11 @@ import dayjs from "dayjs";
import IconAudio from "../../assets/icons/file.audio.svg";
import IconVideo from "../../assets/icons/file.video.svg";
import IconUnknown from "../../assets/icons/file.unknown.svg";
// import IconDoc from "../../assets/icons/file.doc.svg";
import IconImage from "../../assets/icons/file.image.svg";
import IconChannel from "../../assets/icons/channel.svg";
import { ContentTypes } from "../../app/config";
import { useAppSelector } from "../../app/store";
import { Favorite } from "../../app/slices/favorites";
const Filters = [
{
icon: <IconUnknown className="icon" />,
@@ -21,11 +21,6 @@ const Filters = [
title: "Images",
filter: "image"
},
// {
// icon: <IconDoc className="icon" />,
// title: "Files",
// filter: "file",
// },
{
icon: <IconVideo className="icon" />,
title: "Videos",
@@ -40,7 +35,7 @@ const Filters = [
type filter = "audio" | "video" | "image" | "";
function FavsPage() {
const [filter, setFilter] = useState<filter>("");
const [favs, setFavs] = useState([]);
const [favs, setFavs] = useState<Favorite[]>([]);
const { favorites, channelData, userData } = useAppSelector((store) => {
return {
favorites: store.favorites,
@@ -132,6 +127,7 @@ function FavsPage() {
</div>
<div className="right">
{favs.map(({ id, created_at, messages }) => {
if (!messages || messages.length == 0) return null;
const [
{
source: { gid, uid }
+1 -1
View File
@@ -43,7 +43,7 @@ export default function usePreload() {
getFavorites();
}
}, [rehydrated]);
const canStreaming = loginUid && rehydrated && !!token;
const canStreaming = !!loginUid && rehydrated && !!token;
console.log("ttt", loginUid, rehydrated, token);
useEffect(() => {
+6 -2
View File
@@ -5,9 +5,14 @@ import { useLazyGetMetamaskNonceQuery } from "../../app/services/auth";
import metamaskSvg from "../../assets/icons/metamask.svg?url";
import { StyledSocialButton } from "./styled";
import Onboarding from "@metamask/onboarding";
import { LoginCredential } from "../../types/auth";
// import toast from "react-hot-toast";
export default function MetamaskLoginButton({ login }) {
export default function MetamaskLoginButton({
login
}: {
login: (params: LoginCredential) => void;
}) {
const [requesting, setRequesting] = useState(false);
const [accounts, setAccounts] = useState([]);
const [getNonce] = useLazyGetMetamaskNonceQuery();
@@ -64,7 +69,6 @@ export default function MetamaskLoginButton({ login }) {
return signature;
};
const handleMetamaskLogin = async () => {
console.log("wtfff", MetaMaskOnboarding.isMetaMaskInstalled());
if (MetaMaskOnboarding.isMetaMaskInstalled()) {
setRequesting(true);
try {
+14 -12
View File
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useState, FC } from "react";
import styled from "styled-components";
import toast from "react-hot-toast";
import { useDispatch } from "react-redux";
@@ -62,8 +62,11 @@ const StyledWrapper = styled.div`
margin-top: 24px;
}
`;
export default function AdminAccount({ serverName, nextStep }) {
type Props = {
serverName: string;
nextStep: () => void;
};
const AdminAccount: FC<Props> = ({ serverName, nextStep }) => {
const dispatch = useDispatch();
const [createAdmin, { isLoading: isSigningUp, error: signUpError }] = useCreateAdminMutation();
@@ -89,15 +92,13 @@ export default function AdminAccount({ serverName, nextStep }) {
// After logged in
useEffect(() => {
if (isLoggedIn) {
if (isLoggedIn && serverData) {
dispatch(updateInitialized(true));
setTimeout(() => {
// Set server name
updateServer({
...serverData,
name: serverName
});
}, 0);
// Set server name
updateServer({
...serverData,
name: serverName
});
}
}, [isLoggedIn]);
@@ -163,4 +164,5 @@ export default function AdminAccount({ serverName, nextStep }) {
</StyledButton>
</StyledWrapper>
);
}
};
export default AdminAccount;
+1 -1
View File
@@ -57,7 +57,7 @@ const StyledWrapper = styled.div`
}
`;
export default function DonePage({ serverName }) {
export default function DonePage({ serverName }: { serverName: string }) {
const navigate = useNavigate();
return (
+1 -1
View File
@@ -73,7 +73,7 @@ const StyledWrapper = styled.div`
}
`;
export default function InviteLink({ nextStep }) {
export default function InviteLink({ nextStep }: { nextStep: () => void }) {
const { link, linkCopied, copyLink } = useInviteLink();
return (
+9 -3
View File
@@ -1,3 +1,4 @@
import { FC } from "react";
import styled from "styled-components";
import toast from "react-hot-toast";
import StyledInput from "../../../common/component/styled/Input";
@@ -44,8 +45,12 @@ const StyledWrapper = styled.div`
margin-top: 24px;
}
`;
export default function ServerName({ serverName, setServerName, nextStep }) {
type Props = {
serverName: string;
setServerName: (name: string) => void;
nextStep: () => void;
};
const ServerName: FC<Props> = ({ serverName, setServerName, nextStep }) => {
return (
<StyledWrapper>
<span className="primaryText">Create a new server</span>
@@ -73,4 +78,5 @@ export default function ServerName({ serverName, setServerName, nextStep }) {
</StyledButton>
</StyledWrapper>
);
}
};
export default ServerName;
+1 -1
View File
@@ -43,7 +43,7 @@ const StyledWrapper = styled.div`
}
`;
export default function WelcomePage({ nextStep }) {
export default function WelcomePage({ nextStep }: { nextStep: () => void }) {
return (
<StyledWrapper>
<span className="primaryText">Welcome to your VoceChat!</span>
+3 -2
View File
@@ -4,6 +4,7 @@ import styled from "styled-components";
import StyledRadio from "../../../common/component/styled/Radio";
import StyledButton from "../../../common/component/styled/Button";
import { useGetLoginConfigQuery, useUpdateLoginConfigMutation } from "../../../app/services/server";
import { WhoCanSignUp } from "../../../types/server";
const StyledWrapper = styled.div`
height: 100%;
@@ -38,11 +39,11 @@ const StyledWrapper = styled.div`
}
`;
export default function WhoCanSignUp({ nextStep }) {
export default function SignUpSetting({ nextStep }: { nextStep: () => void }) {
const { data: loginConfig } = useGetLoginConfigQuery();
const [updateLoginConfig, { isSuccess, error }] = useUpdateLoginConfigMutation();
const [value, setValue] = useState(undefined);
const [value, setValue] = useState<WhoCanSignUp>();
// Sync to `value` when `loginConfig` is fetched
useEffect(() => {
+1 -2
View File
@@ -114,8 +114,7 @@ const RegWithUsername: FC = () => {
onChange={handleInput}
/>
<Button type="submit" disabled={isLoading || !username || isSuccess}>
{/* todo typo */}
{isLoading ? "Logining" : `Continue`}
{isLoading ? "Logging in" : `Continue`}
</Button>
</form>
</>
+2 -2
View File
@@ -1,4 +1,4 @@
// import { useState, useEffect } from "react";
import { ChangeEvent } from "react";
import StyledContainer from "./StyledContainer";
import Input from "../../../common/component/styled/Input";
import Textarea from "../../../common/component/styled/Textarea";
@@ -14,7 +14,7 @@ export default function ConfigFirebase() {
// const { token_url, description } = values;
updateConfig(values);
};
const handleChange = (evt) => {
const handleChange = (evt: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const newValue = evt.target.value;
const { type } = evt.target.dataset;
setValues((prev) => {
-8
View File
@@ -54,14 +54,6 @@ export default function Logins() {
updateGithubAuthConfig({ [key]: evt.target.value });
}
};
// const handleChange = (evt) => {
// const newValue = evt.target.value;
// const { type } = evt.target.dataset;
// const items = newValue ? newValue.split("\n") : [];
// setValues((prev) => {
// return { ...prev, [type]: items };
// });
// };
const handleToggle = (val) => {
setValues((prev) => {
return { ...prev, ...val };
+7 -6
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from "react";
import { useState, useEffect, ChangeEvent } from "react";
import styled from "styled-components";
const StyledTest = styled.div`
display: flex;
@@ -27,14 +27,15 @@ export default function ConfigSMTP() {
// const { token_url, description } = values;
updateConfig({ ...values, port: Number((values as SMTPConfig)?.port ?? 0) });
};
const handleChange = (evt) => {
const handleChange = (evt: ChangeEvent<HTMLInputElement>) => {
const newValue = evt.target.value;
const { type } = evt.target.dataset;
const { type = "" } = evt.target.dataset;
setValues((prev) => {
if (!prev) return prev;
return { ...prev, [type]: newValue };
});
};
const handleTestEmailChange = (evt) => {
const handleTestEmailChange = (evt: ChangeEvent<HTMLInputElement>) => {
const newValue = evt.target.value;
setTestEmail(newValue);
};
@@ -55,8 +56,8 @@ export default function ConfigSMTP() {
}
}, [isSuccess, isError]);
// if (!values) return null;
const { host, port, from, username, password, enabled = false } = values ?? {};
if (!values) return null;
const { host, port, from, username, password, enabled = false } = values as SMTPConfig;
console.log("values", values);
return (
<StyledContainer>
@@ -8,7 +8,7 @@ import Button from "../../common/component/styled/Button";
interface Props {
id: number;
closeModal: () => void;
closeModal: (cid?: number) => void;
}
const DeleteConfirmModal: FC<Props> = ({ id, closeModal }) => {