Просмотр исходного кода

Merge pull request #8213 from weseek/feat/133066-able-to-change-text-format-using-button

feat: Make button changes text format  in editor
soma 2 лет назад
Родитель
Сommit
e04b330fe2

+ 26 - 10
packages/editor/src/components/CodeMirrorEditor/Toolbar/TextFormatTools.tsx

@@ -2,6 +2,8 @@ import { useCallback, useState } from 'react';
 
 import { Collapse } from 'reactstrap';
 
+import type { GlobalCodeMirrorEditorKey } from '../../../consts';
+import { useCodeMirrorEditorIsolated } from '../../../stores';
 
 import styles from './TextFormatTools.module.scss';
 
@@ -30,44 +32,58 @@ const TextFormatToolsToggler = (props: TogglarProps): JSX.Element => {
   );
 };
 
-export const TextFormatTools = (): JSX.Element => {
+type TextFormatToolsType = {
+  editorKey: string | GlobalCodeMirrorEditorKey,
+}
+
+export const TextFormatTools = (props: TextFormatToolsType): JSX.Element => {
+  const { editorKey } = props;
   const [isOpen, setOpen] = useState(false);
+  const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(editorKey);
 
   const toggle = useCallback(() => {
     setOpen(bool => !bool);
   }, []);
 
+  const onClickInsertMarkdownElements = (prefix: string, suffix: string) => {
+    codeMirrorEditor?.insertMarkdownElements(prefix, suffix);
+  };
+
+  const onClickInsertPrefix = (prefix: string, noSpaceIfPrefixExists?: boolean) => {
+    codeMirrorEditor?.insertPrefix(prefix, noSpaceIfPrefixExists);
+  };
+
   return (
     <div className="d-flex">
       <TextFormatToolsToggler isOpen={isOpen} onClick={toggle} />
 
       <Collapse isOpen={isOpen} horizontal>
         <div className="d-flex px-1 gap-1" style={{ width: '220px' }}>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertMarkdownElements('**', '**')}>
             <span className="material-symbols-outlined fs-5">format_bold</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertMarkdownElements('*', '*')}>
             <span className="material-symbols-outlined fs-5">format_italic</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertMarkdownElements('~', '~')}>
             <span className="material-symbols-outlined fs-5">format_strikethrough</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertPrefix('#', true)}>
             <span className="material-symbols-outlined fs-5">block</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertMarkdownElements('`', '`')}>
             <span className="material-symbols-outlined fs-5">code</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertPrefix('-')}>
             <span className="material-symbols-outlined fs-5">format_list_bulleted</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertPrefix('1.')}>
             <span className="material-symbols-outlined fs-5">format_list_numbered</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertPrefix('>')}>
             <span className="material-symbols-outlined fs-5">block</span>
           </button>
-          <button type="button" className="btn btn-toolbar-button">
+          <button type="button" className="btn btn-toolbar-button" onClick={() => onClickInsertPrefix('- [ ]')}>
             <span className="material-symbols-outlined fs-5">checklist</span>
           </button>
         </div>

+ 3 - 5
packages/editor/src/components/CodeMirrorEditor/Toolbar/Toolbar.tsx

@@ -1,6 +1,6 @@
 import { memo } from 'react';
 
-import { AcceptedUploadFileType } from '../../../consts';
+import type { GlobalCodeMirrorEditorKey, AcceptedUploadFileType } from '../../../consts';
 
 import { AttachmentsDropup } from './AttachmentsDropup';
 import { DiagramButton } from './DiagramButton';
@@ -9,11 +9,10 @@ import { TableButton } from './TableButton';
 import { TemplateButton } from './TemplateButton';
 import { TextFormatTools } from './TextFormatTools';
 
-
 import styles from './Toolbar.module.scss';
 
 type Props = {
-  editorKey: string,
+  editorKey: string | GlobalCodeMirrorEditorKey,
   onFileOpen: () => void,
   acceptedFileType: AcceptedUploadFileType
 }
@@ -21,11 +20,10 @@ type Props = {
 export const Toolbar = memo((props: Props): JSX.Element => {
 
   const { editorKey, onFileOpen, acceptedFileType } = props;
-
   return (
     <div className={`d-flex gap-2 p-2 codemirror-editor-toolbar ${styles['codemirror-editor-toolbar']}`}>
       <AttachmentsDropup onFileOpen={onFileOpen} acceptedFileType={acceptedFileType} />
-      <TextFormatTools />
+      <TextFormatTools editorKey={editorKey} />
       <EmojiButton
         editorKey={editorKey}
       />

+ 8 - 0
packages/editor/src/services/codemirror-editor/use-codemirror-editor/use-codemirror-editor.ts

@@ -16,6 +16,8 @@ import { useAppendExtensions, type AppendExtensions } from './utils/append-exten
 import { useFocus, type Focus } from './utils/focus';
 import { useGetDoc, type GetDoc } from './utils/get-doc';
 import { useInitDoc, type InitDoc } from './utils/init-doc';
+import { useInsertMarkdownElements, type InsertMarkdowElements } from './utils/insert-markdown-elements';
+import { useInsertPrefix, type InsertPrefix } from './utils/insert-prefix';
 import { useInsertText, type InsertText } from './utils/insert-text';
 import { useReplaceText, type ReplaceText } from './utils/replace-text';
 import { useSetCaretLine, type SetCaretLine } from './utils/set-caret-line';
@@ -37,6 +39,8 @@ type UseCodeMirrorEditorUtils = {
   setCaretLine: SetCaretLine,
   insertText: InsertText,
   replaceText: ReplaceText,
+  insertMarkdownElements: InsertMarkdowElements,
+  insertPrefix: InsertPrefix,
 }
 export type UseCodeMirrorEditor = {
   state: EditorState | undefined;
@@ -89,6 +93,8 @@ export const useCodeMirrorEditor = (props?: UseCodeMirror): UseCodeMirrorEditor
   const setCaretLine = useSetCaretLine(view);
   const insertText = useInsertText(view);
   const replaceText = useReplaceText(view);
+  const insertMarkdownElements = useInsertMarkdownElements(view);
+  const insertPrefix = useInsertPrefix(view);
 
   return {
     state,
@@ -100,5 +106,7 @@ export const useCodeMirrorEditor = (props?: UseCodeMirror): UseCodeMirrorEditor
     setCaretLine,
     insertText,
     replaceText,
+    insertMarkdownElements,
+    insertPrefix,
   };
 };

+ 27 - 0
packages/editor/src/services/codemirror-editor/use-codemirror-editor/utils/insert-markdown-elements.ts

@@ -0,0 +1,27 @@
+import { useCallback } from 'react';
+
+import { EditorView } from '@codemirror/view';
+
+export type InsertMarkdowElements = (
+  prefix: string,
+  suffix: string,
+) => void;
+
+export const useInsertMarkdownElements = (view?: EditorView): InsertMarkdowElements => {
+
+  return useCallback((prefix, suffix) => {
+    const selection = view?.state.sliceDoc(
+      view?.state.selection.main.from,
+      view?.state.selection.main.to,
+    );
+    const cursorPos = view?.state.selection.main.head;
+    const insertText = view?.state.replaceSelection(prefix + selection + suffix);
+
+    if (insertText == null || cursorPos == null) {
+      return;
+    }
+    view?.dispatch(insertText);
+    view?.dispatch({ selection: { anchor: cursorPos + prefix.length } });
+    view?.focus();
+  }, [view]);
+};

+ 35 - 0
packages/editor/src/services/codemirror-editor/use-codemirror-editor/utils/insert-prefix.ts

@@ -0,0 +1,35 @@
+import { useCallback } from 'react';
+
+import { EditorView } from '@codemirror/view';
+
+export type InsertPrefix = (prefix: string, noSpaceIfPrefixExists?: boolean) => void;
+
+export const useInsertPrefix = (view?: EditorView): InsertPrefix => {
+  return useCallback((prefix: string, noSpaceIfPrefixExists = false) => {
+    if (view == null) {
+      return;
+    }
+
+    // get the line numbers of the selected range
+    const { from, to } = view.state.selection.main;
+    const startLine = view.state.doc.lineAt(from);
+    const endLine = view.state.doc.lineAt(to);
+
+    // Insert prefix for each line
+    const lines = [];
+    let insertTextLength = 0;
+    for (let i = startLine.number; i <= endLine.number; i++) {
+      const line = view.state.doc.line(i);
+      const insertText = noSpaceIfPrefixExists && line.text.startsWith(prefix)
+        ? prefix
+        : `${prefix} `;
+      insertTextLength += insertText.length;
+      lines.push({ from: line.from, insert: insertText });
+    }
+    view.dispatch({ changes: lines });
+
+    // move the cursor to the end of the selected line
+    view.dispatch({ selection: { anchor: endLine.to + insertTextLength } });
+    view.focus();
+  }, [view]);
+};