diff --git a/packages/ui-markdown-editor/src/plugins/withText.js b/packages/ui-markdown-editor/src/plugins/withText.js index 1992d4f..dbf850e 100644 --- a/packages/ui-markdown-editor/src/plugins/withText.js +++ b/packages/ui-markdown-editor/src/plugins/withText.js @@ -1,9 +1,8 @@ -import { Editor, Node } from 'slate'; -import { insertThematicBreak, isBlockHeading } from '../utilities/toolbarHelpers'; -import { HR } from '../utilities/schema' +import { Node } from 'slate'; +import { isBlockHeading } from '../utilities/toolbarHelpers'; +import { matchCases } from "utilities/matchCases"; export const withText = (editor) => { - // Inserts page break with dash const { insertText } = editor; editor.insertText = (text) => { insertText(text); @@ -11,12 +10,8 @@ export const withText = (editor) => { if(isBlockHeading(editor)){ return; } - const firstWord = currentNode.text; - if(firstWord !== '---'){ - return; - } - Editor.deleteBackward(editor, { unit: 'word' }); - insertThematicBreak(editor, HR); + const currentLine = currentNode.text; + matchCases(editor, currentLine); } return editor; } \ No newline at end of file diff --git a/packages/ui-markdown-editor/src/utilities/matchCases.js b/packages/ui-markdown-editor/src/utilities/matchCases.js new file mode 100644 index 0000000..76bd3b6 --- /dev/null +++ b/packages/ui-markdown-editor/src/utilities/matchCases.js @@ -0,0 +1,35 @@ +import { Transforms, Editor } from 'slate'; +import { H1, H2, H3, H4, H5, H6, HR } from "./schema"; +import { insertThematicBreak } from "./toolbarHelpers"; + +export const matchCases = (editor, currentLine) => { + + const matchHeadings = (editor, currentLine) => { + const headingMatchCase = currentLine.match(/(^\s*)#{1,6}\s/m); + if(!headingMatchCase) return; + + const count = (headingMatchCase[0].match(/#/g) || []).length; + if (count === 1) Transforms.setNodes(editor, { type: H1 }); + else if (count === 2) Transforms.setNodes(editor, { type: H2 }); + else if (count === 3) Transforms.setNodes(editor, { type: H3 }); + else if (count === 4) Transforms.setNodes(editor, { type: H4 }); + else if (count === 5) Transforms.setNodes(editor, { type: H5 }); + else if (count === 6) Transforms.setNodes(editor, { type: H6 }); + + Editor.deleteBackward(editor, { unit: 'word' }); + return; + } + + const matchPageBreak = (editor, currentLine)=>{ + const pageBreakMatchCase = currentLine.match(/(^\s*)([*-])(?:[\t ]*\2){2,}/m); + if(!pageBreakMatchCase) return + + Editor.deleteBackward(editor, { unit: 'word' }); + insertThematicBreak(editor, HR); + + return; + } + + matchHeadings(editor, currentLine); + matchPageBreak(editor, currentLine); +}