A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
refactor: Refactor the markdown editor and create useEditor to replace the original logic
robinee1c622348f3
diff --git a/ui/src/components/Editor/Editor.tsx b/ui/src/components/Editor/Editor.tsxdeleted file mode 100644index a1ac16a9..00000000--- a/ui/src/components/Editor/Editor.tsx+++ /dev/null@@ -1,114 +0,0 @@-import { useEffect, useRef, useState } from 'react';--import 'codemirror/lib/codemirror.css';-import type CodeMirror from 'codemirror';--export interface EditorInstance {- editor: CodeMirror.Editor | null;-}--export interface EditorProps {- onChange?(value: string): void;- onFocus?(): void;- onBlur?(): void;-}-const Editor = ({- value,- onChange,- onFocus,- onBlur,- editorPlaceholder,- getEditorInstance,- autoFocus,-}) => {- const elRef = useRef<HTMLDivElement>(null);- const [editor, setEditor] = useState<CodeMirror.Editor | null>(null);- const eventRef = useRef<EditorProps>();- const isMountedRef = useRef(false);-- useEffect(() => {- const el = elRef?.current;- if (!isMountedRef.current && el instanceof HTMLElement) {- isMountedRef.current = true;- import('codemirror').then(async ({ default: CodeMirror }) => {- await import('codemirror/mode/markdown/markdown');- await import('codemirror/addon/display/placeholder');-- const cm = CodeMirror(el, {- mode: 'markdown',- lineWrapping: true,- placeholder: editorPlaceholder,- });- if (autoFocus) {- cm.focus();- }- cm.on('change', (e) => {- const newValue = e.getValue();- eventRef.current?.onChange?.(newValue);- });-- cm.on('focus', () => {- eventRef.current?.onFocus?.();- });- cm.on('blur', () => {- eventRef.current?.onBlur?.();- });- setEditor(cm);- getEditorInstance(cm);- cm.setSize('100%', '100%');- cm.addKeyMap({- Enter: () => {- const cursor = cm.getCursor();- const text = cm.getLine(cursor.line);- const doc = cm.getDoc();-- const olRegexData = text.match(/^(\s{0,})(\d+)\.\s/);- const ulRegexData = text.match(/^(\s{0,})(-|\*)\s/);- const blockquoteData = text.match(/^>\s+?/g);-- if (olRegexData && text !== olRegexData[0]) {- const num = olRegexData[2];-- doc.replaceSelection(`\n${olRegexData[1]}${Number(num) + 1}. `);- } else if (ulRegexData && text !== ulRegexData[0]) {- doc.replaceSelection(`\n${ulRegexData[1]}${ulRegexData[2]} `);- } else if (blockquoteData && text !== blockquoteData[0]) {- doc.replaceSelection(`\n> `);- } else if (- text.trim() === '>' ||- text.trim().match(/^\d{1,}\.$/) ||- text.trim().match(/^(\*|-)$/)- ) {- doc.replaceRange(`\n`, { ...cursor, ch: 0 }, cursor);- } else {- doc.replaceSelection(`\n`);- }- },- });- });- }- }, [elRef]);-- useEffect(() => {- if (!editor) {- return;- }- if (editor.getValue() !== value) {- editor.setValue(value || '');- }- }, [editor, value]);-- useEffect(() => {- eventRef.current = {- onChange,- onFocus,- onBlur,- };- }, [onChange, onFocus, onBlur]);-- return (- <div className="md-editor position-relative w-100 h-100" ref={elRef} />- );-};--export default Editor;diff --git a/ui/src/components/Editor/ToolBars/blockquote.tsx b/ui/src/components/Editor/ToolBars/blockquote.tsxindex f950b548..4204d029 100644--- a/ui/src/components/Editor/ToolBars/blockquote.tsx+++ b/ui/src/components/Editor/ToolBars/blockquote.tsx@@ -1,10 +1,11 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const BlockQuote: FC<IEditorContext> = ({ editor, replaceLines }) => {+let context: IEditorContext;+const BlockQuote = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {@@ -13,8 +14,9 @@ const BlockQuote: FC<IEditorContext> = ({ editor, replaceLines }) => {tip: `${t('blockquote.text')} (Ctrl+Q)`,};- const handleClick = () => {- replaceLines((line) => {+ const handleClick = (ctx) => {+ context = ctx;+ context.replaceLines((line) => {const FIND_BLOCKQUOTE_RX = /^>\s+?/g;if (line === `> ${t('blockquote.text')}`) {@@ -26,7 +28,7 @@ const BlockQuote: FC<IEditorContext> = ({ editor, replaceLines }) => {}return line;}, 2);- editor?.focus();+ context.editor?.focus();};return <ToolItem {...item} onClick={handleClick} />;diff --git a/ui/src/components/Editor/ToolBars/bold.tsx b/ui/src/components/Editor/ToolBars/bold.tsxindex 5f142ca7..23864c54 100644--- a/ui/src/components/Editor/ToolBars/bold.tsx+++ b/ui/src/components/Editor/ToolBars/bold.tsx@@ -1,10 +1,11 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Bold: FC<IEditorContext> = ({ editor, wrapText }) => {+let context: IEditorContext;+const Bold = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'bold',@@ -13,9 +14,10 @@ const Bold: FC<IEditorContext> = ({ editor, wrapText }) => {};const DEFAULTTEXT = t('bold.text');- const handleClick = () => {- wrapText('**', '**', DEFAULTTEXT);- editor?.focus();+ const handleClick = (ctx) => {+ context = ctx;+ context.wrapText('**', '**', DEFAULTTEXT);+ context.editor?.focus();};return <ToolItem {...item} onClick={handleClick} />;diff --git a/ui/src/components/Editor/ToolBars/code.tsx b/ui/src/components/Editor/ToolBars/code.tsxindex 5e12195a..f0e0ff64 100644--- a/ui/src/components/Editor/ToolBars/code.tsx+++ b/ui/src/components/Editor/ToolBars/code.tsx@@ -1,4 +1,4 @@-import { FC, useEffect, useRef, useState, memo } from 'react';+import { useEffect, useRef, useState, memo } from 'react';import { Button, Form, Modal } from 'react-bootstrap';import { useTranslation } from 'react-i18next';@@ -130,7 +130,9 @@ const codeLanguageType = ['yaml','yml',];-const Code: FC<IEditorContext> = ({ editor, wrapText }) => {++let context: IEditorContext;+const Code = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {@@ -149,11 +151,12 @@ const Code: FC<IEditorContext> = ({ editor, wrapText }) => {const inputRef = useRef<HTMLTextAreaElement>(null);const SINGLELINEMAXLENGTH = 40;- const addCode = () => {- if (!editor) {- return;- }- const text = editor.getSelection();+ const addCode = (ctx) => {+ context = ctx;++ const { wrapText, editor } = context;++ const text = context.editor.getSelection();if (!text) {setVisible(true);@@ -161,7 +164,7 @@ const Code: FC<IEditorContext> = ({ editor, wrapText }) => {return;}if (text.length > SINGLELINEMAXLENGTH) {- wrapText('```\n', '\n```');+ context.wrapText('```\n', '\n```');} else {wrapText('`', '`');}@@ -175,9 +178,6 @@ const Code: FC<IEditorContext> = ({ editor, wrapText }) => {}, [visible]);const handleClick = () => {- if (!editor) {- return;- }if (!code.value.trim()) {setCode({...code,@@ -197,7 +197,7 @@ const Code: FC<IEditorContext> = ({ editor, wrapText }) => {} else {value = `\`${code.value}\``;}- editor.replaceSelection(value);+ context.editor.replaceSelection(value);setCode({value: '',isInvalid: false,@@ -207,7 +207,7 @@ const Code: FC<IEditorContext> = ({ editor, wrapText }) => {setVisible(false);};const onHide = () => setVisible(false);- const onExited = () => editor?.focus();+ const onExited = () => context.editor?.focus();return (<ToolItem {...item} onClick={addCode}>diff --git a/ui/src/components/Editor/ToolBars/heading.tsx b/ui/src/components/Editor/ToolBars/heading.tsxindex 620bf904..9c14271d 100644--- a/ui/src/components/Editor/ToolBars/heading.tsx+++ b/ui/src/components/Editor/ToolBars/heading.tsx@@ -1,11 +1,12 @@-import { FC, useState, memo } from 'react';+import { useState, memo } from 'react';import { Dropdown } from 'react-bootstrap';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Heading: FC<IEditorContext> = (context) => {+let context: IEditorContext;+const Heading = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const headerList = [{@@ -57,7 +58,8 @@ const Heading: FC<IEditorContext> = (context) => {}, level + 1);setShowState(false);};- const onAddHeader = () => {+ const onAddHeader = (ctx) => {+ context = ctx;if (isLocked) {return;}diff --git a/ui/src/components/Editor/ToolBars/hr.tsx b/ui/src/components/Editor/ToolBars/hr.tsxindex 1c0137c9..ac805cd7 100644--- a/ui/src/components/Editor/ToolBars/hr.tsx+++ b/ui/src/components/Editor/ToolBars/hr.tsx@@ -1,17 +1,20 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Hr: FC<IEditorContext> = ({ editor, appendBlock }) => {+let context: IEditorContext;+const Hr = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'hr',keyMap: ['Ctrl-R'],tip: `${t('hr.text')} (Ctrl+R)`,};- const handleClick = () => {+ const handleClick = (ctx) => {+ context = ctx;+ const { appendBlock, editor } = context;appendBlock('----------\n');editor?.focus();};diff --git a/ui/src/components/Editor/ToolBars/image.tsx b/ui/src/components/Editor/ToolBars/image.tsxindex 6a813963..4a6229f7 100644--- a/ui/src/components/Editor/ToolBars/image.tsx+++ b/ui/src/components/Editor/ToolBars/image.tsx@@ -1,13 +1,17 @@-import { FC, useEffect, useState, memo } from 'react';+import { useEffect, useState, memo } from 'react';import { Button, Form, Modal, Tab, Tabs } from 'react-bootstrap';import { useTranslation } from 'react-i18next';+import type { Editor } from 'codemirror';+import { Modal as AnswerModal } from '@/components';import ToolItem from '../toolItem';import { IEditorContext } from '../types';import { uploadImage } from '@/services';-const Image: FC<IEditorContext> = ({ editor }) => {+let context: IEditorContext;+const Image = () => {+ const [editor, setEditor] = useState<Editor>(null);const { t } = useTranslation('translation', { keyPrefix: 'editor' });const loadingText = `![${t('image.uploading')}...]()`;@@ -81,9 +85,6 @@ const Image: FC<IEditorContext> = ({ editor }) => {e.preventDefault();}const drop = async (_, e) => {- if (!editor) {- return;- }const fileList = e.dataTransfer.files;const bool = verifyImageSize(fileList);@@ -160,9 +161,6 @@ const Image: FC<IEditorContext> = ({ editor }) => {editor.replaceSelection(newHtml);};const handleClick = () => {- if (!editor) {- return;- }if (!link.value) {setLink({ ...link, isInvalid: true });return;@@ -180,15 +178,15 @@ const Image: FC<IEditorContext> = ({ editor }) => {setImageName({ ...imageName, value: '' });};useEffect(() => {- editor.on('dragenter', dragenter);- editor.on('dragover', dragover);- editor.on('drop', drop);- editor.on('paste', paste);+ editor?.on('dragenter', dragenter);+ editor?.on('dragover', dragover);+ editor?.on('drop', drop);+ editor?.on('paste', paste);return () => {- editor.off('dragenter', dragenter);- editor.off('dragover', dragover);- editor.off('drop', drop);- editor.off('paste', paste);+ editor?.off('dragenter', dragenter);+ editor?.off('dragover', dragover);+ editor?.off('drop', drop);+ editor?.off('paste', paste);};}, [editor]);@@ -198,11 +196,13 @@ const Image: FC<IEditorContext> = ({ editor }) => {}}, [link.value]);- const addLink = () => {+ const addLink = (ctx) => {+ context = ctx;+ setEditor(context.editor);if (!editor) {return;}- const text = editor?.getSelection();+ const text = context.editor?.getSelection();setImageName({ ...imageName, value: text });diff --git a/ui/src/components/Editor/ToolBars/indent.tsx b/ui/src/components/Editor/ToolBars/indent.tsxindex b5c73323..e3a21f17 100644--- a/ui/src/components/Editor/ToolBars/indent.tsx+++ b/ui/src/components/Editor/ToolBars/indent.tsx@@ -1,16 +1,20 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Indent: FC<IEditorContext> = ({ editor, replaceLines }) => {+let context: IEditorContext;+const Indent = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'indent',tip: t('indent.text'),};- const handleClick = () => {+ const handleClick = (ctx) => {+ context = ctx;+ const { editor, replaceLines } = context;+replaceLines((line) => {line = ` ${line}`;return line;diff --git a/ui/src/components/Editor/ToolBars/italic.tsx b/ui/src/components/Editor/ToolBars/italic.tsxindex 8d47a042..08cedfea 100644--- a/ui/src/components/Editor/ToolBars/italic.tsx+++ b/ui/src/components/Editor/ToolBars/italic.tsx@@ -1,10 +1,11 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Italic: FC<IEditorContext> = ({ editor, wrapText }) => {+let context: IEditorContext;+const Italic = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'italic',@@ -13,7 +14,9 @@ const Italic: FC<IEditorContext> = ({ editor, wrapText }) => {};const DEFAULTTEXT = t('italic.text');- const handleClick = () => {+ const handleClick = (ctx) => {+ context = ctx;+ const { editor, wrapText } = context;wrapText('*', '*', DEFAULTTEXT);editor?.focus();};diff --git a/ui/src/components/Editor/ToolBars/link.tsx b/ui/src/components/Editor/ToolBars/link.tsxindex 615a3b00..a6eb92a9 100644--- a/ui/src/components/Editor/ToolBars/link.tsx+++ b/ui/src/components/Editor/ToolBars/link.tsx@@ -1,11 +1,12 @@-import { FC, useEffect, useRef, useState, memo } from 'react';+import { useEffect, useRef, useState, memo } from 'react';import { Button, Form, Modal } from 'react-bootstrap';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Link: FC<IEditorContext> = ({ editor }) => {+let context: IEditorContext;+const Link = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'link',@@ -31,10 +32,11 @@ const Link: FC<IEditorContext> = ({ editor }) => {inputRef.current.focus();}}, [visible]);- const addLink = () => {- if (!editor) {- return;- }++ const addLink = (ctx) => {+ context = ctx;+ const { editor } = context;+const text = editor.getSelection();setName({ ...name, value: text });@@ -42,9 +44,8 @@ const Link: FC<IEditorContext> = ({ editor }) => {setVisible(true);};const handleClick = () => {- if (!editor) {- return;- }+ const { editor } = context;+if (!link.value) {setLink({ ...link, isInvalid: true });return;@@ -62,10 +63,14 @@ const Link: FC<IEditorContext> = ({ editor }) => {setName({ ...name, value: '' });};const onHide = () => setVisible(false);- const onExited = () => editor?.focus();+ const onExited = () => {+ const { editor } = context;+ editor.focus();+ };return (- <ToolItem {...item} onClick={addLink}>+ <>+ <ToolItem {...item} onClick={addLink} /><Modalshow={visible}onHide={onHide}@@ -112,7 +117,7 @@ const Link: FC<IEditorContext> = ({ editor }) => {</Button></Modal.Footer></Modal>- </ToolItem>+ </>);};diff --git a/ui/src/components/Editor/ToolBars/ol.tsx b/ui/src/components/Editor/ToolBars/ol.tsxindex 8f29605c..80d8d1db 100644--- a/ui/src/components/Editor/ToolBars/ol.tsx+++ b/ui/src/components/Editor/ToolBars/ol.tsx@@ -1,10 +1,11 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const OL: FC<IEditorContext> = ({ editor, replaceLines }) => {+let context: IEditorContext;+const OL = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'orderedList',@@ -12,10 +13,10 @@ const OL: FC<IEditorContext> = ({ editor, replaceLines }) => {tip: `${t('ordered_list.text')} (Ctrl+O)`,};- const handleClick = () => {- if (!editor) {- return;- }+ const handleClick = (ctx) => {+ context = ctx;+ const { editor, replaceLines } = context;+replaceLines((line, i) => {const FIND_OL_RX = /^(\s{0,})(\d+)\.\s/;diff --git a/ui/src/components/Editor/ToolBars/outdent.tsx b/ui/src/components/Editor/ToolBars/outdent.tsxindex 13870fbe..0da52efa 100644--- a/ui/src/components/Editor/ToolBars/outdent.tsx+++ b/ui/src/components/Editor/ToolBars/outdent.tsx@@ -1,17 +1,20 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Outdent: FC<IEditorContext> = ({ editor, replaceLines }) => {+let context: IEditorContext;+const Outdent = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'outdent',keyMap: ['Shift-Tab'],tip: t('outdent.text'),};- const handleClick = () => {+ const handleClick = (ctx) => {+ context = ctx;+ const { editor, replaceLines } = context;replaceLines((line) => {line = line.replace(/^(\s{0,})/, (_1, $1) => {return $1.length > 4 ? $1.substring(4) : '';diff --git a/ui/src/components/Editor/ToolBars/table.tsx b/ui/src/components/Editor/ToolBars/table.tsxindex 3efb7b87..7011fcf8 100644--- a/ui/src/components/Editor/ToolBars/table.tsx+++ b/ui/src/components/Editor/ToolBars/table.tsx@@ -1,10 +1,11 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const Table: FC<IEditorContext> = ({ editor }) => {+let context: IEditorContext;+const Table = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'table',@@ -63,7 +64,9 @@ const Table: FC<IEditorContext> = ({ editor }) => {return body;};- const handleClick = () => {+ const handleClick = (ctx) => {+ context = ctx;+ const { editor } = context;let table = '\n';table += makeHeader(2, tableData);diff --git a/ui/src/components/Editor/ToolBars/ul.tsx b/ui/src/components/Editor/ToolBars/ul.tsxindex 3fdd6482..2c8c2849 100644--- a/ui/src/components/Editor/ToolBars/ul.tsx+++ b/ui/src/components/Editor/ToolBars/ul.tsx@@ -1,10 +1,11 @@-import { FC, memo } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';import ToolItem from '../toolItem';import { IEditorContext } from '../types';-const UL: FC<IEditorContext> = ({ editor, replaceLines }) => {+let context: IEditorContext;+const UL = () => {const { t } = useTranslation('translation', { keyPrefix: 'editor' });const item = {label: 'unorderedList',@@ -12,10 +13,10 @@ const UL: FC<IEditorContext> = ({ editor, replaceLines }) => {tip: `${t('unordered_list.text')} (Ctrl+U)`,};- const handleClick = () => {- if (!editor) {- return;- }+ const handleClick = (ctx) => {+ context = ctx;+ const { editor, replaceLines } = context;+replaceLines((line) => {const FIND_UL_RX = /^(\s{0,})(-|\*)\s/;diff --git a/ui/src/components/Editor/Viewer.tsx b/ui/src/components/Editor/Viewer.tsxindex 357be508..cfaa20c4 100644--- a/ui/src/components/Editor/Viewer.tsx+++ b/ui/src/components/Editor/Viewer.tsx@@ -42,9 +42,11 @@ const Index = ({ value }, ref) => {htmlRender(previewRef.current);}, [html]);+useImperativeHandle(ref, () => {return {getHtml: () => html,+ element: previewRef.current,};});diff --git a/ui/src/components/Editor/index.tsx b/ui/src/components/Editor/index.tsxindex 66f9e33b..b6529300 100644--- a/ui/src/components/Editor/index.tsx+++ b/ui/src/components/Editor/index.tsx@@ -21,17 +21,15 @@ import {Image,Indent,Italice,- Link,+ Link as LinkItem,OL,Outdent,Table,UL,} from './ToolBars';-import { createEditorUtils, htmlRender } from './utils';+import { htmlRender, useEditor } from './utils';import Viewer from './Viewer';-import { CodeMirrorEditor, IEditorContext } from './types';import { EditorContext } from './EditorContext';-import Editor from './Editor';import './index.scss';@@ -64,24 +62,18 @@ const MDEditor: ForwardRefRenderFunction<EditorRef, Props> = (},ref,) => {- const [markdown, setMarkdown] = useState<string>(value || '');- const previewRef = useRef<{ getHtml } | null>(null);- const [editor, setEditor] = useState<CodeMirrorEditor | null>(null);- const [context, setContext] = useState<IEditorContext | null>(null);- const eventRef = useRef<EventRef>();-- useEffect(() => {- if (!editor) {- return;- }+ const editorRef = useRef<HTMLDivElement>(null);+ const previewRef = useRef<{ getHtml; element } | null>(null);- import('codemirror').then(({ default: codemirror }) => {- setContext({- editor,- ...createEditorUtils(codemirror, editor),- });- });- }, [editor]);+ const editor = useEditor({+ element: editorRef.current,+ onChange,+ onFocus,+ onBlur,+ placeholder: editorPlaceholder,+ autoFocus,+ });+ const [markdown, setMarkdown] = useState<string>(value || '');useEffect(() => {if (value !== markdown) {@@ -89,77 +81,62 @@ const MDEditor: ForwardRefRenderFunction<EditorRef, Props> = (}}, [value]);- useEffect(() => {- eventRef.current = {- onChange,- onFocus,- onBlur,- };- }, [onChange, onFocus, onBlur]);-- const getEditorInstance = (cm) => {- setEditor(cm);- };-const getHtml = () => {return previewRef.current?.getHtml();};- const handleChange = (val) => {- setMarkdown(val);- eventRef.current?.onChange?.(val);- };+ useImperativeHandle(ref, () => ({+ getHtml,+ }));- const handleFocus = () => {- eventRef.current?.onFocus?.();- };+ const handleChange = (val) => {+ const { ch } = editor.getCursor();- const handleBlur = () => {- eventRef.current?.onBlur?.();+ editor.replaceSelection(`${ch ? '\n' : ''}\`\`\`mermaid\n${val}\n\`\`\`\n`);};- useImperativeHandle(ref, () => ({- getHtml,- }));+ useEffect(() => {+ if (!editor) {+ return;+ }+ if (editor.getValue() !== value) {+ editor.setValue(value || '');+ }+ }, [editor, value]);return (<><div className={classNames('md-editor-wrap rounded', className)}>- <EditorContext.Provider value={context}>- {context && (- <PluginRender- type="editor"- className="toolbar-wrap px-3 d-flex align-items-center flex-wrap">- <Heading {...context} />- <Bold {...context} />- <Italice {...context} />- <div className="toolbar-divider" />- <Code {...context} />- <Link {...context} />- <BlockQuote {...context} />- <Image {...context} />- <Table {...context} />- <div className="toolbar-divider" />- <OL {...context} />- <UL {...context} />- <Indent {...context} />- <Outdent {...context} />- <Hr {...context} />- <div className="toolbar-divider" />- <Help />- </PluginRender>- )}+ <EditorContext.Provider value={editor}>+ <PluginRender+ type="editor"+ className="toolbar-wrap px-3 d-flex align-items-center flex-wrap"+ onChange={handleChange}+ previewElement={previewRef.current?.element}>+ <Heading />+ <Bold />+ <Italice />+ <div className="toolbar-divider" />+ <Code />+ <LinkItem />+ <BlockQuote />+ <Image />+ <Table />+ <div className="toolbar-divider" />+ <OL />+ <UL />+ <Indent />+ <Outdent />+ <Hr />+ <div className="toolbar-divider" />+ <Help />+ </PluginRender></EditorContext.Provider><div className="content-wrap">- <Editor- value={markdown}- autoFocus={autoFocus}- onChange={handleChange}- onFocus={handleFocus}- onBlur={handleBlur}- editorPlaceholder={editorPlaceholder}- getEditorInstance={getEditorInstance}+ <div+ className="md-editor position-relative w-100 h-100"+ ref={editorRef}/></div></div>diff --git a/ui/src/components/Editor/toolItem.tsx b/ui/src/components/Editor/toolItem.tsxindex 2af40682..22d52125 100644--- a/ui/src/components/Editor/toolItem.tsx+++ b/ui/src/components/Editor/toolItem.tsx@@ -2,10 +2,16 @@ import { FC, useContext, useEffect } from 'react';import { Dropdown, Button } from 'react-bootstrap';import { EditorContext } from './EditorContext';+import { IEditorContext } from './types';interface IProps {keyMap?: string[];- onClick?: () => void;+ onClick?: ({+ editor,+ wrapText,+ replaceLines,+ appendBlock,+ }: IEditorContext) => void;tip?: string;className?: string;as?: any;@@ -13,12 +19,16 @@ interface IProps {label?: string;disable?: boolean;isShow?: boolean;- onBlur?: () => void;+ onBlur?: ({+ editor,+ wrapText,+ replaceLines,+ appendBlock,+ }: IEditorContext) => void;}const ToolItem: FC<IProps> = (props) => {- const context = useContext(EditorContext);+ const editor = useContext(EditorContext);- const { editor } = context;const {label,tip,@@ -33,20 +43,26 @@ const ToolItem: FC<IProps> = (props) => {} = props;useEffect(() => {+ if (!editor) {+ return;+ }if (!keyMap) {return;}keyMap.forEach((key) => {- editor.addKeyMap({+ editor?.addKeyMap({[key]: () => {- if (typeof onClick === 'function') {- onClick();- }+ onClick?.({+ editor,+ wrapText: editor?.wrapText,+ replaceLines: editor?.replaceLines,+ appendBlock: editor?.appendBlock,+ });},});});- }, []);+ }, [editor]);const btnRender = () => (<Button@@ -59,20 +75,26 @@ const ToolItem: FC<IProps> = (props) => {tabIndex={-1}onClick={(e) => {e.preventDefault();- if (typeof onClick === 'function') {- onClick();- }+ onClick?.({+ editor,+ wrapText: editor?.wrapText,+ replaceLines: editor?.replaceLines,+ appendBlock: editor?.appendBlock,+ });}}onBlur={(e) => {e.preventDefault();- if (typeof onBlur === 'function') {- onBlur();- }+ onBlur?.({+ editor,+ wrapText: editor?.wrapText,+ replaceLines: editor?.replaceLines,+ appendBlock: editor?.appendBlock,+ });}}/>);- if (!context) {+ if (!editor) {return null;}return (diff --git a/ui/src/components/Editor/utils/index.ts b/ui/src/components/Editor/utils/index.tsindex e56073ef..19cba8b2 100644--- a/ui/src/components/Editor/utils/index.ts+++ b/ui/src/components/Editor/utils/index.ts@@ -1,80 +1,82 @@+import { useEffect, useState } from 'react';+import type { Editor, Position } from 'codemirror';import type CodeMirror from 'codemirror';+import 'codemirror/lib/codemirror.css';import 'katex/dist/katex.min.css';export function createEditorUtils(codemirror: typeof CodeMirror,editor: Editor,) {- return {- wrapText(before: string, after = before, defaultText) {- const range = editor.somethingSelected()- ? editor.listSelections()[0]- : editor.findWordAt(editor.getCursor());-- const from = range.from();- const to = range.to();- const text = editor.getRange(from, to) || defaultText;- const fromBefore = codemirror.Pos(from.line, from.ch - before.length);- const toAfter = codemirror.Pos(to.line, to.ch + after.length);-- if (- editor.getRange(fromBefore, from) === before &&- editor.getRange(to, toAfter) === after- ) {- editor.replaceRange(text, fromBefore, toAfter);- editor.setSelection(- fromBefore,- codemirror.Pos(fromBefore.line, fromBefore.ch + text.length),- );- } else {- editor.replaceRange(before + text + after, from, to);- const cursor = editor.getCursor();-- editor.setSelection(- codemirror.Pos(cursor.line, cursor.ch - after.length - text.length),- codemirror.Pos(cursor.line, cursor.ch - after.length),- );- }- },+ editor.wrapText = (before: string, after = before, defaultText) => {+ const range = editor.somethingSelected()+ ? editor.listSelections()[0]+ : editor.findWordAt(editor.getCursor());- replaceLines(replace: Parameters<Array<string>['map']>[0], symbolLen = 0) {- const [selection] = editor.listSelections();+ const from = range.from();+ const to = range.to();+ const text = editor.getRange(from, to) || defaultText;+ const fromBefore = codemirror.Pos(from.line, from.ch - before.length);+ const toAfter = codemirror.Pos(to.line, to.ch + after.length);- const range = [- codemirror.Pos(selection.from().line, 0),- codemirror.Pos(selection.to().line),- ] as const;- const lines = editor.getRange(...range).split('\n');-- editor.replaceRange(lines.map(replace).join('\n'), ...range);- const newRange = range;-- if (symbolLen > 0) {- newRange[0].ch = symbolLen;- }- editor.setSelection(...newRange);- },-- appendBlock(content: string): Position {+ if (+ editor.getRange(fromBefore, from) === before &&+ editor.getRange(to, toAfter) === after+ ) {+ editor.replaceRange(text, fromBefore, toAfter);+ editor.setSelection(+ fromBefore,+ codemirror.Pos(fromBefore.line, fromBefore.ch + text.length),+ );+ } else {+ editor.replaceRange(before + text + after, from, to);const cursor = editor.getCursor();- let emptyLine = -1;+ editor.setSelection(+ codemirror.Pos(cursor.line, cursor.ch - after.length - text.length),+ codemirror.Pos(cursor.line, cursor.ch - after.length),+ );+ }+ };+ editor.replaceLines = (+ replace: Parameters<Array<string>['map']>[0],+ symbolLen = 0,+ ) => {+ const [selection] = editor.listSelections();++ const range = [+ codemirror.Pos(selection.from().line, 0),+ codemirror.Pos(selection.to().line),+ ] as const;+ const lines = editor.getRange(...range).split('\n');++ editor.replaceRange(lines.map(replace).join('\n'), ...range);+ const newRange = range;++ if (symbolLen > 0) {+ newRange[0].ch = symbolLen;+ }+ editor.setSelection(...newRange);+ };+ editor.appendBlock = (content: string): Position => {+ const cursor = editor.getCursor();- for (let i = cursor.line; i < editor.lineCount(); i += 1) {- if (!editor.getLine(i).trim()) {- emptyLine = i;- break;- }- }- if (emptyLine === -1) {- editor.replaceRange('\n', codemirror.Pos(editor.lineCount()));- emptyLine = editor.lineCount();+ let emptyLine = -1;++ for (let i = cursor.line; i < editor.lineCount(); i += 1) {+ if (!editor.getLine(i).trim()) {+ emptyLine = i;+ break;}+ }+ if (emptyLine === -1) {+ editor.replaceRange('\n', codemirror.Pos(editor.lineCount()));+ emptyLine = editor.lineCount();+ }- editor.replaceRange(`\n${content}`, codemirror.Pos(emptyLine));- return codemirror.Pos(emptyLine + 1, 0);- },+ editor.replaceRange(`\n${content}`, codemirror.Pos(emptyLine));+ return codemirror.Pos(emptyLine + 1, 0);};}@@ -89,24 +91,24 @@ export function htmlRender(el: HTMLElement | null) {}});- import('mermaid').then(({ default: mermaid }) => {- mermaid.initialize({ startOnLoad: false });-- el.querySelectorAll('.language-mermaid').forEach((pre) => {- const flag = Date.now();- mermaid.render(- `theGraph${flag}`,- pre.textContent || '',- function (svgCode) {- const p = document.createElement('p');- p.className = 'text-center';- p.innerHTML = svgCode;-- pre.parentNode?.replaceChild(p, pre);- },- );- });- });+ // import('mermaid').then(({ default: mermaid }) => {+ // mermaid.initialize({ startOnLoad: false });++ // el.querySelectorAll('.language-mermaid').forEach((pre) => {+ // const flag = Date.now();+ // mermaid.render(+ // `theGraph${flag}`,+ // pre.textContent || '',+ // function (svgCode) {+ // const p = document.createElement('p');+ // p.className = 'text-center';+ // p.innerHTML = svgCode;++ // pre.parentNode?.replaceChild(p, pre);+ // },+ // );+ // });+ // });import('katex/contrib/auto-render/auto-render').then(({ default: render }) => {render(el, {@@ -156,3 +158,83 @@ export function htmlRender(el: HTMLElement | null) {}});}++export const useEditor = ({+ element,+ placeholder,+ autoFocus,+ onChange,+ onFocus,+ onBlur,+}) => {+ const [editor, setEditor] = useState<Editor>();++ const onEnter = (cm) => {+ const cursor = cm.getCursor();+ const text = cm.getLine(cursor.line);+ const doc = cm.getDoc();++ const olRegexData = text.match(/^(\s{0,})(\d+)\.\s/);+ const ulRegexData = text.match(/^(\s{0,})(-|\*)\s/);+ const blockquoteData = text.match(/^>\s+?/g);++ if (olRegexData && text !== olRegexData[0]) {+ const num = olRegexData[2];++ doc.replaceSelection(`\n${olRegexData[1]}${Number(num) + 1}. `);+ } else if (ulRegexData && text !== ulRegexData[0]) {+ doc.replaceSelection(`\n${ulRegexData[1]}${ulRegexData[2]} `);+ } else if (blockquoteData && text !== blockquoteData[0]) {+ doc.replaceSelection(`\n> `);+ } else if (+ text.trim() === '>' ||+ text.trim().match(/^\d{1,}\.$/) ||+ text.trim().match(/^(\*|-)$/)+ ) {+ doc.replaceRange(`\n`, { ...cursor, ch: 0 }, cursor);+ } else {+ doc.replaceSelection(`\n`);+ }+ };++ const init = async () => {+ const { default: codeMirror } = await import('codemirror');+ await import('codemirror/mode/markdown/markdown');+ await import('codemirror/addon/display/placeholder');++ const cm = codeMirror(element, {+ mode: 'markdown',+ lineWrapping: true,+ placeholder,+ focus: autoFocus,+ });+ setEditor(cm);++ createEditorUtils(codeMirror, cm);++ cm.on('change', (e) => {+ const newValue = e.getValue();+ onChange?.(newValue);+ });++ cm.on('focus', () => {+ onFocus?.();+ });+ cm.on('blur', () => {+ onBlur?.();+ });+ cm.setSize('100%', '100%');+ cm.addKeyMap({+ Enter: onEnter,+ });+ };++ useEffect(() => {+ if (!(element instanceof HTMLElement)) {+ return;+ }+ init();+ }, [element]);++ return editor;+};diff --git a/ui/src/components/PluginRender/index.tsx b/ui/src/components/PluginRender/index.tsxindex 1e23b4b1..5baef52e 100644--- a/ui/src/components/PluginRender/index.tsx+++ b/ui/src/components/PluginRender/index.tsx@@ -1,7 +1,6 @@import React, { FC, ReactNode, memo } from 'react';import PluginKite, { Plugin, PluginType } from '@/utils/pluginKit';-/*** Note:Please set at least either of the `slug_name` and `type` attributes, otherwise no plugins will be rendered.*@@ -20,7 +19,13 @@ interface Props {[prop: string]: any;}-const Index: FC<Props> = ({ slug_name, type, children, ...props }) => {+const Index: FC<Props> = ({+ slug_name,+ type,+ children,+ className,+ ...props+}) => {const pluginSlice: Plugin[] = [];const plugins = PluginKite.getPlugins();@@ -47,7 +52,7 @@ const Index: FC<Props> = ({ slug_name, type, children, ...props }) => {if (type === 'editor') {const nodes = React.Children.map(children, (child, index) => {- if (index === 0) {+ if (index === 15) {return (<>{child}@@ -55,16 +60,17 @@ const Index: FC<Props> = ({ slug_name, type, children, ...props }) => {const PluginFC = ps.component;return (// @ts-ignore- <PluginFC key={ps.info.slug_name} />+ <PluginFC key={ps.info.slug_name} {...props} />);})}+ <div className="toolbar-divider" /></>);}return child;});- return <div {...props}>{nodes}</div>;+ return <div className={className}>{nodes}</div>;}return (@@ -73,7 +79,7 @@ const Index: FC<Props> = ({ slug_name, type, children, ...props }) => {const PluginFC = ps.component;return (// @ts-ignore- <PluginFC key={ps.info.slug_name} {...props} />+ <PluginFC key={ps.info.slug_name} className={className} {...props} />);})}</>