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
-1
View File
@@ -10,7 +10,6 @@ interface Props {
}
const Avatar: FC<Props> = ({ url = "", name = "unknown name", type = "user", ...rest }) => {
// console.log("avatar url", url);
const [src, setSrc] = useState("");
const handleError = (err: SyntheticEvent<HTMLImageElement>) => {
-1
View File
@@ -96,7 +96,6 @@ const AvatarUploader: FC<Props> = ({
multiple={false}
onChange={handleUpload}
type="file"
// todo: xss
accept="image/*"
name="avatar"
id="avatar"
@@ -1,6 +1,5 @@
import { FC, useState } from "react";
import styled from "styled-components";
// import { NavLink } from "react-router-dom";
import ChannelModal from "./ChannelModal";
import InviteModal from "./InviteModal";
import IconChat from "../../assets/icons/placeholder.chat.svg";
+4 -4
View File
@@ -1,16 +1,16 @@
import { FC, MouseEvent, ReactElement } from "react";
import { FC, ReactElement } from "react";
import StyledMenu from "./styled/Menu";
export interface Item {
title: string;
icon?: string | ReactElement;
handler: (e: MouseEvent) => void;
handler: (param: any) => void;
underline?: boolean;
danger?: boolean;
}
interface Props {
items: Item[];
items: (Item | boolean | undefined)[];
hideMenu?: () => void;
}
@@ -18,7 +18,7 @@ const ContextMenu: FC<Props> = ({ items = [], hideMenu = null }) => {
return (
<StyledMenu>
{items.map((item) => {
if (!item) return null;
if (typeof item === "boolean" || !item) return null;
const {
title,
icon = null,
@@ -135,12 +135,11 @@ const AddMembers: FC<Props> = ({ cid = 0, closeModal }) => {
if (!channel) return null;
const { members: uids } = channel;
const userIds = users.map(({ uid }) => uid);
const userIds = users.map((u) => u?.uid || 0);
return (
<Styled>
<div className="filter">
{/* {selects && selects.length > 0 && ( */}
<ul className="selects">
{selects.map((uid) => {
return (
@@ -158,7 +157,6 @@ const AddMembers: FC<Props> = ({ cid = 0, closeModal }) => {
onChange={handleFilterInput}
/>
</ul>
{/* )} */}
</div>
<ul className="users">
{userIds.map((uid) => {
+3 -9
View File
@@ -38,14 +38,10 @@ const Message: FC<IProps> = ({
const [edit, setEdit] = useState(false);
const avatarRef = useRef(null);
const { getPinInfo } = usePinMessage(context == "channel" ? contextId : 0);
const {
message = {},
reactionMessageData,
usersData
} = useAppSelector((store) => {
const { message, reactionMessageData, usersData } = useAppSelector((store) => {
return {
reactionMessageData: store.reactionMessage,
message: store.message[mid] || {},
message: store.message[mid],
usersData: store.users.byId
};
});
@@ -104,7 +100,7 @@ const Message: FC<IProps> = ({
interactive
placement="right"
trigger="click"
content={<Profile uid={fromUid} type="card" cid={contextId} />}
content={<Profile uid={fromUid || 0} type="card" cid={contextId} />}
>
<div className="avatar" data-uid={fromUid} ref={avatarRef}>
<Avatar url={currUser?.avatar} name={currUser?.name} />
@@ -164,11 +160,9 @@ const Message: FC<IProps> = ({
{!edit && !readOnly && (
<Commands
content_type={content_type}
context={context}
contextId={contextId}
mid={mid}
from_uid={fromUid}
toggleEditMessage={toggleEditMessage}
/>
)}
@@ -8,16 +8,17 @@ import ForwardedMessage from "./ForwardedMessage";
import MarkdownRender from "../MarkdownRender";
import FileMessage from "../FileMessage";
import URLPreview from "./URLPreview";
import { ContentType } from "../../../types/message";
type Props = {
context: "user" | "channel";
to?: number;
from_uid?: number;
created_at: number;
created_at?: number;
properties?: object;
content_type;
content_type: ContentType;
content: string;
download: string;
thumbnail: string;
download?: string;
thumbnail?: string;
edited?: boolean | number;
};
const renderContent = ({
@@ -1,42 +0,0 @@
// import React from 'react'
import { useEditorRef } from "@udecode/plate";
import { Transforms } from "slate";
import { ReactEditor } from "slate-react";
import styled from "styled-components";
import iconClose from "../../../assets/icons/close.circle.svg?url";
const StylePicture = styled.picture`
position: relative;
display: flex;
width: fit-content;
max-width: 240px;
max-height: 240px;
img {
width: 100%;
object-fit: cover;
}
.remove {
background: none;
position: absolute;
top: 0;
right: -20px;
}
`;
export default function ImageElement({ attributes, children, element }) {
const editor = useEditorRef();
const path = ReactEditor.findPath(editor, element);
const handleRemoveImage = () => {
Transforms.removeNodes(editor, { at: path });
};
return (
<StylePicture {...attributes}>
{children}
<img src={element.url}></img>
<button className="remove" onClick={handleRemoveImage}>
<img src={iconClose} alt="icon close" />
</button>
</StylePicture>
);
}
-12
View File
@@ -28,18 +28,6 @@ export const CONFIG = {
allow: [ELEMENT_IMAGE, ELEMENT_PARAGRAPH]
}
}
// {
// hotkey: "mod+shift+enter",
// before: true,
// },
// {
// hotkey: "enter",
// query: {
// start: true,
// end: true,
// allow: KEYS_HEADING,
// },
// },
]
}
},
+10 -27
View File
@@ -1,4 +1,4 @@
import { useRef, useEffect, useState, useCallback } from "react";
import { useRef, useEffect, useState, useCallback, ClipboardEvent } from "react";
import { useKey } from "rooks";
import { Editor, Transforms } from "slate";
import {
@@ -9,19 +9,11 @@ import {
createNodeIdPlugin,
createParagraphPlugin,
createSoftBreakPlugin,
// createComboboxPlugin,
createMentionPlugin,
// comboboxSelectors,
// getMentionOnSelectItem,
findMentionInput,
// removeMentionInput,
// isSelectionInMentionInput,
createPlugins,
ELEMENT_PARAGRAPH,
getPlateEditorRef,
// usePlateEditorRef,
// ELEMENT_IMAGE,
// useComboboxControls,
MentionCombobox
} from "@udecode/plate";
import { createComboboxPlugin } from "@udecode/plate-combobox";
@@ -48,7 +40,7 @@ const Plugins = ({
}) => {
// const { getMenuProps, getItemProps } = useComboboxControls();
const [context, to] = id.split("_");
const { addStageFile } = useUploadFile({ context, id: to });
const { addStageFile } = useUploadFile({ context, id: Number(to) });
const enableMentions = members.length > 0;
const userData = useAppSelector((store) => store.users.byId);
const [msgs, setMsgs] = useState([]);
@@ -61,7 +53,7 @@ const Plugins = ({
};
const plateEditor = getPlateEditorRef(`${TEXT_EDITOR_PREFIX}_${id}`);
useEffect(() => {
const handlePasteEvent = (evt) => {
const handlePasteEvent = (evt: ClipboardEvent) => {
const files = [...evt.clipboardData.files];
if (files.length) {
const filesData = files.map((file) => {
@@ -89,6 +81,7 @@ const Plugins = ({
useKey(
"Enter",
(evt) => {
if (!plateEditor) return;
// 是否在at操作
const mentionInputs = findMentionInput(plateEditor);
if (mentionInputs || evt.shiftKey || evt.ctrlKey || evt.altKey || evt.isComposing) {
@@ -106,7 +99,6 @@ const Plugins = ({
});
},
{
// eventTypes: ["keydown"],
target: editableRef,
when: !cmdKey
}
@@ -154,12 +146,12 @@ const Plugins = ({
);
const handleChange = useCallback(
async (val) => {
async (val: any) => {
console.log("tmps changed", val);
const tmps = [];
const getMixedText = (children) => {
const mentions = [];
const arr = children.map(({ type, text, uid }) => {
const getMixedText = (children: any) => {
const mentions: any = [];
const arr = children.map(({ type, text, uid }: any) => {
if (type == "mention") {
mentions.push(uid);
return ` @${uid} `;
@@ -208,7 +200,6 @@ const Plugins = ({
<Styled className="input" ref={editableRef}>
<Plate
id={`${TEXT_EDITOR_PREFIX}_${id}`}
// key={`${TEXT_EDITOR_PREFIX}_${id}`}
onChange={handleChange}
editableProps={{ ...initialProps, style: { userSelect: "text" } }}
initialValue={initialValue}
@@ -216,9 +207,7 @@ const Plugins = ({
>
{enableMentions ? (
<MentionCombobox
// component={StyledCombobox}
onRenderItem={({ item }) => {
console.log("wtf", item);
if (!item || !item.data) return null;
return <User key={item.data.uid} uid={item.data.uid} interactive={false} />;
}}
@@ -245,14 +234,14 @@ const Plugins = ({
);
};
export const useMixedEditor = (key) => {
export const useMixedEditor = (key: string) => {
const editorRef = getPlateEditorRef(`${TEXT_EDITOR_PREFIX}_${key}`);
const focus = () => {
if (editorRef) {
ReactEditor.focus(editorRef);
}
};
const insertText = (txt) => {
const insertText = (txt: string) => {
console.log("eref", editorRef);
if (editorRef) {
ReactEditor.focus(editorRef);
@@ -265,9 +254,3 @@ export const useMixedEditor = (key) => {
};
};
export default Plugins;
// export default memo(Plugins, (prev, next) => {
// return (
// prev.id == next.id &&
// JSON.stringify(prev.initialValue) == JSON.stringify(next.initialValue)
// );
// });
@@ -1,6 +0,0 @@
const nodeTypes = {
paragraph: "p",
image: "img"
};
export default nodeTypes;
@@ -1,27 +0,0 @@
import {
ELEMENT_PARAGRAPH
// TElement,
} from "@udecode/plate";
// import { Text } from 'slate'
export const createElement = (text = "", { type = ELEMENT_PARAGRAPH, mark } = {}) => {
const leaf = { text };
if (mark) {
leaf[mark] = true;
}
return {
type,
children: [leaf]
};
};
export const getNodesWithRandomId = (nodes = []) => {
let _id = 10000;
nodes.forEach((node) => {
node.id = _id;
_id++;
});
return nodes;
};
-1
View File
@@ -7,7 +7,6 @@ interface Props {
children?: ReactNode;
}
// todo: check memory leak
const Modal: FC<Props> = ({ id = "root-modal", mask = true, children }) => {
const [wrapper, setWrapper] = useState<HTMLDivElement | null>(null);
+1 -1
View File
@@ -85,7 +85,7 @@ const renderContent = (data: MessagePayload) => {
res = reactStringReplace(content, /(\s{1}@[0-9]+\s{1})/g, (match, idx) => {
console.log("match", match);
const uid = match.trim().slice(1);
return <Mention popover={false} key={idx} uid={uid} />;
return <Mention popover={false} key={idx} uid={+uid} />;
});
break;
case ContentTypes.markdown:
@@ -54,7 +54,7 @@ export default function EditFileDetails({
updateName
}: {
name: string;
closeModal: () => void;
closeModal: (p?: any) => void;
updateName: (name: string) => void;
}) {
const [fileName, setFileName] = useState(name);
@@ -28,7 +28,7 @@ export default function UploadFileList({
setEditInfo((prev) => (prev ? null : info));
};
const handleOpenEditModal = (idx: number) => {
const info = stageFiles[idx];
const info = stageFiles[`${idx}`];
if (!info) return;
toggleModalVisible({ ...info, index: idx });
@@ -55,7 +55,7 @@ export default function UploadFileList({
)}
<Styled>
{stageFiles.map(({ name, url, size, type }, idx) => {
{stageFiles.map(({ name, url, size, type }, idx: number) => {
return (
<li className="file" key={url}>
<div className="preview">
@@ -136,7 +136,7 @@ const StyledSettingContainer: FC<Props> = ({
{dangers.length ? (
<ul className="items danger">
{dangers.map((d) => {
if (!d) return null;
if (typeof d === "boolean" || !d) return null;
const { title, handler } = d;
return (
<li key={title} onClick={handler} className="item">
+1 -1
View File
@@ -73,7 +73,7 @@ const UsersModal: FC<Props> = ({ closeModal }) => {
{users && (
<ul className="users">
{users.map((u) => {
const { uid } = u;
const { uid = 0 } = u || {};
return (
<li key={uid} className="user">
<NavLink onClick={closeModal} to={`/chat/dm/${uid}`}>
+2 -1
View File
@@ -1,3 +1,4 @@
import { InputHTMLAttributes } from "react";
import styled from "styled-components";
const Styled = styled.input`
@@ -34,6 +35,6 @@ const Styled = styled.input`
}
`;
export default function StyledCheckbox(props) {
export default function StyledCheckbox(props: InputHTMLAttributes<HTMLInputElement>) {
return <Styled readOnly {...props} type="checkbox" />;
}
+28 -13
View File
@@ -1,11 +1,6 @@
import {
useState,
FC,
DetailedHTMLProps,
InputHTMLAttributes
} from 'react';
import { HiEye, HiEyeOff } from 'react-icons/hi';
import styled from 'styled-components';
import { useState, FC, DetailedHTMLProps, InputHTMLAttributes } from "react";
import { HiEye, HiEyeOff } from "react-icons/hi";
import styled from "styled-components";
const StyledWrapper = styled.div`
width: 100%;
@@ -81,21 +76,41 @@ const StyledInput = styled.input`
}
`;
interface Props extends DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> {
interface Props
extends DetailedHTMLProps<
Pick<
InputHTMLAttributes<HTMLInputElement>,
| "placeholder"
| "className"
| "type"
| "autoFocus"
| "id"
| "value"
| "name"
| "required"
| "readOnly"
| "onChange"
| "onBlur"
| "pattern"
| "disabled"
>,
HTMLInputElement
> {
prefix?: string;
ref?: any;
}
const Input: FC<Props> = ({ type = 'text', prefix = '', className, ...rest }) => {
const Input: FC<Props> = ({ type = "text", prefix = "", className, ...rest }) => {
const [inputType, setInputType] = useState(type);
const togglePasswordVisible = () => {
setInputType((prev) => (prev == 'password' ? 'text' : 'password'));
setInputType((prev) => (prev == "password" ? "text" : "password"));
};
return type == 'password' ? (
return type == "password" ? (
<StyledWrapper className={className}>
<StyledInput type={inputType} className={`inner ${className}`} {...rest} />
<div className="view" onClick={togglePasswordVisible}>
{inputType == 'password' ? <HiEyeOff color="#78787c"/> : <HiEye color="#78787c"/>}
{inputType == "password" ? <HiEyeOff color="#78787c" /> : <HiEye color="#78787c" />}
</div>
</StyledWrapper>
) : prefix ? (
+15 -7
View File
@@ -1,4 +1,4 @@
import { useState, useId } from "react";
import { useState, useId, FC } from "react";
import styled from "styled-components";
const StyledForm = styled.form`
@@ -61,17 +61,24 @@ const StyledForm = styled.form`
}
}
`;
type Props = {
options: string[];
values: (string | number)[];
defaultValue?: string | number;
onChange?: (param: any) => void;
value: object | number | string;
};
const VALUE_NOT_SET = {};
const VALUES_NOT_SET = {};
const VALUE_NOT_SET = "";
const VALUES_NOT_SET: string[] = [];
export default function Radio({
const Radio: FC<Props> = ({
options,
values = VALUES_NOT_SET,
value = VALUE_NOT_SET,
defaultValue = undefined,
defaultValue = "",
onChange = undefined
}) {
}) => {
const id = useId();
const [fallbackValue, setFallbackValue] = useState(defaultValue);
@@ -104,4 +111,5 @@ export default function Radio({
))}
</StyledForm>
);
}
};
export default Radio;
+1 -1
View File
@@ -24,7 +24,7 @@ export default function useFavMessage({
return "error" in resp;
};
const removeFavorite = (id: number) => {
const removeFavorite = (id: string) => {
if (!id) return;
removeFav(id);
};
+5 -2
View File
@@ -77,9 +77,12 @@ const useUserOperation = ({ uid, cid }: IProps) => {
};
const isAdmin = !!loginUser?.is_admin;
const loginUid = loginUser?.uid;
const canDeleteChannel = cid && !channel?.is_public && isAdmin;
const canDeleteChannel = !!cid && !channel?.is_public && isAdmin;
const canRemoveFromChannel =
cid && !channel?.is_public && (isAdmin || channel?.owner == loginUid) && uid != channel?.owner;
!!cid &&
!channel?.is_public &&
(isAdmin || channel?.owner == loginUid) &&
uid != channel?.owner;
const canCall: boolean = (agoraConfig as AgoraConfig)?.enabled && loginUid != uid;
const canRemove: boolean = isAdmin && loginUid != uid && !cid;