🚸 Rewrite the markdown deserializer to improve br… (#1198)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Refactor** - Updated markdown handling and serialization libraries for improved performance and accuracy in text formatting. - **New Features** - Enhanced rich text and markdown conversion capabilities, providing users with more reliable and seamless text formatting options. - **Documentation** - Added detailed documentation for markdown to rich text conversion and vice versa, ensuring easier understanding and implementation for developers. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
36
packages/lib/markdown/convertRichTextToMarkdown.ts
Normal file
36
packages/lib/markdown/convertRichTextToMarkdown.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { TElement } from '@udecode/plate-common'
|
||||
import serialize from './serializer/serialize'
|
||||
import { defaultNodeTypes } from './serializer/ast-types'
|
||||
|
||||
export const convertRichTextToMarkdown = (
|
||||
richText: TElement[],
|
||||
options?: { flavour?: 'common' | 'whatsapp' }
|
||||
) => {
|
||||
const test = richText
|
||||
.reduce<string[]>((acc, node) => {
|
||||
if (node.type === 'variable') {
|
||||
return [
|
||||
...acc,
|
||||
...node.children.reduce<string[]>((acc, node) => {
|
||||
const serializedElement = serialize(node, {
|
||||
nodeTypes: defaultNodeTypes,
|
||||
flavour: options?.flavour,
|
||||
}) as string
|
||||
if (!serializedElement || serializedElement === '<br>\n\n')
|
||||
return [...acc, '\n']
|
||||
return [...acc, serializedElement]
|
||||
}, []),
|
||||
]
|
||||
}
|
||||
const serializedElement = serialize(node, {
|
||||
nodeTypes: defaultNodeTypes,
|
||||
flavour: options?.flavour,
|
||||
})
|
||||
if (!serializedElement || serializedElement === '<br>\n\n')
|
||||
return [...acc, '\n']
|
||||
return [...acc, serializedElement]
|
||||
}, [])
|
||||
.join('')
|
||||
|
||||
return test.endsWith('\n') ? test.slice(0, -1) : test
|
||||
}
|
||||
Reference in New Issue
Block a user