<!-- 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 -->
37 lines
1.2 KiB
TypeScript
37 lines
1.2 KiB
TypeScript
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
|
|
}
|