refactor: markdown UX

This commit is contained in:
zerosoul
2022-03-28 20:47:17 +08:00
parent 774bf2c335
commit ffb53e14d4
30 changed files with 1485 additions and 574 deletions
@@ -0,0 +1,40 @@
// 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>
);
}
+53
View File
@@ -0,0 +1,53 @@
import { ELEMENT_IMAGE, ELEMENT_PARAGRAPH } from "@udecode/plate";
export const CONFIG = {
editableProps: {
spellCheck: false,
autoFocus: true,
placeholder: "Type…",
},
trailingBlock: { type: ELEMENT_PARAGRAPH },
softBreak: {
options: {
rules: [
{
hotkey: "shift+enter",
query: {
allow: [ELEMENT_IMAGE, ELEMENT_PARAGRAPH],
},
},
],
},
},
exitBreak: {
options: {
rules: [
{
hotkey: "mod+enter",
query: {
allow: [ELEMENT_IMAGE, ELEMENT_PARAGRAPH],
},
},
// {
// hotkey: "mod+shift+enter",
// before: true,
// },
// {
// hotkey: "enter",
// query: {
// start: true,
// end: true,
// allow: KEYS_HEADING,
// },
// },
],
},
},
selectOnBackspace: {
options: {
query: {
allow: [ELEMENT_IMAGE],
},
},
},
};
+163
View File
@@ -0,0 +1,163 @@
import { useRef, useState, useCallback } from "react";
import { useKey } from "rooks";
import { Editor, Transforms } from "slate";
import {
createPlateUI,
Plate,
createExitBreakPlugin,
createTrailingBlockPlugin,
createNodeIdPlugin,
createParagraphPlugin,
createImagePlugin,
createSoftBreakPlugin,
createPlugins,
ELEMENT_PARAGRAPH,
getPlateActions,
// usePlateEditorRef,
ELEMENT_IMAGE,
// usePlateStore
} from "@udecode/plate";
import Styled from "./styled";
import ImageElement from "./ImageElement";
import { CONFIG } from "./config";
export const TEXT_EDITOR_PREFIX = "rustchat_text_editor";
let components = createPlateUI({
[ELEMENT_IMAGE]: ImageElement,
// customize your components by plugin key
});
const initialValue = [{ type: ELEMENT_PARAGRAPH, children: [{ text: "" }] }];
const Plugins = ({
id = "",
placeholder = "Write some markdown...",
sendMessages,
}) => {
// const plateEditor = usePlateEditorRef(`${TEXT_EDITOR_PREFIX}_${id}`);
const [msgs, setMsgs] = useState([]);
const [cmdKey, setCmdKey] = useState(false);
const editableRef = useRef(null);
// const editor = useEditorRef();
const initialProps = {
...CONFIG.editableProps,
className: "box",
placeholder,
};
useKey(
"Enter",
(evt) => {
console.log("enter keypress", evt);
if (evt.shiftKey || evt.ctrlKey || evt.altKey || evt.isComposing) {
return true;
}
evt.preventDefault();
sendMessages(msgs);
// 清空
const plateEditor = getPlateActions(`${TEXT_EDITOR_PREFIX}_${id}`).editor;
Transforms.delete(plateEditor, {
at: {
anchor: Editor.start(plateEditor, []),
focus: Editor.end(plateEditor, []),
},
});
},
{
// eventTypes: ["keydown"],
target: editableRef,
when: !cmdKey,
}
);
useKey(
[91, 93],
(evt) => {
setCmdKey(evt.type == "keydown");
console.log("cmd", evt.type);
},
{
eventTypes: ["keydown", "keyup"],
target: editableRef,
}
);
const plugins = createPlugins(
[
createParagraphPlugin(),
createImagePlugin(),
createNodeIdPlugin(),
createSoftBreakPlugin(CONFIG.softBreak),
createTrailingBlockPlugin(CONFIG.trailingBlock),
createExitBreakPlugin(CONFIG.exitBreak),
],
{
components,
}
);
const handleChange = useCallback(
async (val) => {
console.log("tmps changed");
const tmps = [];
for await (const v of val) {
if (v.type == "img") {
// img
const resp = await fetch(v.url);
const value = await resp.blob();
tmps.push({ type: "image", value });
} else {
// text
const prev = tmps[tmps.length - 1];
if (!prev) {
tmps.push([{ type: "text", value: v.children[0].text }]);
} else {
if (Array.isArray(prev)) {
tmps[tmps.length - 1].push({
type: "text",
value: v.children[0].text,
});
} else {
tmps.push([{ type: "text", value: v.children[0].text }]);
}
}
}
}
const arr = tmps.map((tmp) => {
return Array.isArray(tmp)
? { type: "text", value: tmp.map((t) => t.value).join("\n") }
: tmp;
});
const msgs = arr.filter(({ value }) => !!value);
setMsgs(msgs);
console.log("tmps", val, msgs);
},
[msgs]
);
// useEffect(() => {
// return () => {
// if (plateEditor) {
// // 清空
// Transforms.delete(plateEditor, {
// at: {
// anchor: Editor.start(plateEditor, []),
// focus: Editor.end(plateEditor, []),
// },
// });
// }
// };
// }, [plateEditor]);
return (
<Styled className="input" ref={editableRef}>
<Plate
onChange={handleChange}
id={`${TEXT_EDITOR_PREFIX}_${id}`}
editableProps={{ ...initialProps, style: { userSelect: "text" } }}
initialValue={initialValue}
plugins={plugins}
></Plate>
</Styled>
);
};
export default Plugins;
// export default memo(Plugins, (prevs, nexts) => {
// console.log("placeholder", prevs.placeholder, nexts.placeholder);
// return prevs.placeholder == nexts.placeholder;
// });
@@ -0,0 +1,21 @@
import {
createBasicElementsPlugin,
createImagePlugin,
createParagraphPlugin,
createSelectOnBackspacePlugin,
} from "@udecode/plate";
import { CONFIG } from "./config";
const basicElements = [
createParagraphPlugin(), // paragraph element
];
export const PLUGINS = {
basicElements,
basicNodes: [...basicElements],
image: [
createBasicElementsPlugin(),
createImagePlugin(),
createSelectOnBackspacePlugin(CONFIG.selectOnBackspace),
],
};
+19
View File
@@ -0,0 +1,19 @@
import styled from "styled-components";
const Styled = styled.div`
max-height: 50vh;
overflow: auto;
font-weight: 400;
font-size: 14px;
line-height: 20px;
color: #475467;
> .box {
display: flex;
flex-direction: column;
gap: 16px;
p {
padding: 0;
}
}
`;
export default Styled;
@@ -0,0 +1,6 @@
const nodeTypes = {
paragraph: "p",
image: "img",
};
export default nodeTypes;
@@ -0,0 +1,30 @@
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;
};