2
0

(whatsapp) Improve / fix markdown serializer

Forked remark-slate code to create Typebot's own serializer

Closes #1056
This commit is contained in:
Baptiste Arnaud
2024-01-08 08:40:25 +01:00
parent 7d6c964a0f
commit 244a29423b
11 changed files with 629 additions and 88 deletions

View File

@@ -0,0 +1,41 @@
import { TElement } from '@udecode/plate-common'
import serialize from './serialize'
import { defaultNodeTypes } from './ast-types'
export const convertRichTextToMarkdown = (
richText: TElement[],
options?: { flavour?: 'common' | 'whatsapp' }
) => {
let extraNewLinesCount = 0
const test = richText
.reduce<string[]>((acc, node) => {
if (node.type === 'variable' || node.type === 'inline-variable') {
return [
...acc,
...node.children.map(
(child) =>
serialize(child, {
nodeTypes: defaultNodeTypes,
flavour: options?.flavour,
}) as string
),
]
}
const serializedElement = serialize(node, {
nodeTypes: defaultNodeTypes,
flavour: options?.flavour,
})
if (!serializedElement || serializedElement === '<br>\n\n') {
if (extraNewLinesCount > 0) {
return [...acc, '']
}
extraNewLinesCount++
return acc
}
extraNewLinesCount = 0
return [...acc, serializedElement]
}, [])
.join('\n')
return test.endsWith('\n') ? test.slice(0, -2) : test
}