feat: Markdown text is now parsed correctly when pasted

This commit is contained in:
Aman Harwara
2024-03-14 19:01:39 +05:30
parent 56813909bb
commit c5ca4a9857
7 changed files with 185 additions and 1 deletions

View File

@@ -109,6 +109,7 @@
},
"dependencies": {
"@ariakit/react": "^0.3.9",
"@lexical/clipboard": "0.13.1",
"@lexical/headless": "0.13.1",
"@lexical/list": "0.13.1",
"@lexical/rich-text": "0.13.1",

View File

@@ -36,6 +36,7 @@ import AutoLinkPlugin from './Plugins/AutoLinkPlugin/AutoLinkPlugin'
import DatetimePlugin from './Plugins/DateTimePlugin/DateTimePlugin'
import PasswordPlugin from './Plugins/PasswordPlugin/PasswordPlugin'
import { MergeSiblingListsPlugin } from './Plugins/MergeSiblingListsPlugin'
import { MarkdownPastePlugin } from './Plugins/MarkdownPastePlugin'
type BlocksEditorProps = {
onChange?: (value: string, preview: string) => void
@@ -142,6 +143,7 @@ export const BlocksEditor: FunctionComponent<BlocksEditorProps> = ({
<DatetimePlugin />
<PasswordPlugin />
<AutoLinkPlugin />
<MarkdownPastePlugin />
{!readonly && floatingAnchorElem && (
<>
<DraggableBlockPlugin anchorElem={floatingAnchorElem} />

View File

@@ -0,0 +1,50 @@
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { objectKlassEquals } from '@lexical/utils'
import { COMMAND_PRIORITY_LOW, PASTE_COMMAND, PasteCommandType } from 'lexical'
import { useEffect } from 'react'
import { $convertFromMarkdownString } from '../Lexical/Utils/MarkdownImport'
import { MarkdownTransformers } from '../MarkdownTransformers'
export function MarkdownPastePlugin() {
const [editor] = useLexicalComposerContext()
useEffect(() => {
return editor.registerCommand(
PASTE_COMMAND,
(event: PasteCommandType | DragEvent) => {
let dataTransfer: null | DataTransfer = null
if (objectKlassEquals(event, DragEvent)) {
dataTransfer = (event as DragEvent).dataTransfer
} else if (objectKlassEquals(event, ClipboardEvent)) {
dataTransfer = (event as ClipboardEvent).clipboardData
}
if (dataTransfer === null) {
return false
}
const hasFiles = dataTransfer.types.includes('Files')
const hasHTML = dataTransfer.types.includes('text/html')
const hasText = dataTransfer.types.includes('text/plain')
if (hasHTML || hasFiles || !hasText) {
return false
}
const textContent = dataTransfer.getData('text/plain')
try {
$convertFromMarkdownString(textContent, MarkdownTransformers, undefined, true)
return true
} catch (error) {
console.error(error)
}
return false
},
COMMAND_PRIORITY_LOW,
)
}, [editor])
return null
}