Last active
May 20, 2021 13:13
-
-
Save cawabunga/69e88e0a6371d87a70f84b70d1b1c824 to your computer and use it in GitHub Desktop.
Replace new lines with <br /> in slate.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import type { SlatePlugin } from '@udecode/slate-plugins-core'; | |
const NEW_LINE = '\n'; | |
const NEW_LINE_ENCODED = encodeURIComponent(NEW_LINE); | |
const NEW_LINE_ENCODED_TWICE = encodeURIComponent(NEW_LINE_ENCODED); | |
export const createNewLineRenderPlugin = (): SlatePlugin => ({ | |
renderLeaf: (editor) => ({ children, leaf }) => { | |
if (typeof children === 'string' && leaf.text.includes(NEW_LINE)) { | |
return ( | |
<> | |
{children | |
.split(NEW_LINE_ENCODED_TWICE) | |
.map((content, index, arr) => { | |
return ( | |
<React.Fragment key={index}> | |
{content} | |
{index !== arr.length - 1 && <br />} | |
</React.Fragment> | |
); | |
})} | |
</> | |
); | |
} | |
return children; | |
}, | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { SlatePlugin } from '@udecode/slate-plugins-core'; | |
const NEW_LINE = '\n'; | |
const NEW_LINE_ENCODED = encodeURIComponent(NEW_LINE); | |
/** | |
* It doesn't work properly, it consumes marks, because `children` is always encoded `leaf.text` | |
* Reference: https://github.com/udecode/slate-plugins/blob/8d6bc2aedfc66dd80bfdccffc980a734a729ea17/packages/serializers/html-serializer/src/serializer/serializeHTMLFromNodes.ts#L138 | |
*/ | |
export const createNewLineSerializerPlugin = (): SlatePlugin => ({ | |
serialize: { | |
leaf: ({ children }) => { | |
return children.replace( | |
new RegExp(NEW_LINE_ENCODED, 'g'), | |
encodeURIComponent('<br />'), | |
); | |
}, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment