Skip to content

Instantly share code, notes, and snippets.

@cawabunga
Last active May 20, 2021 13:13
Show Gist options
  • Save cawabunga/69e88e0a6371d87a70f84b70d1b1c824 to your computer and use it in GitHub Desktop.
Save cawabunga/69e88e0a6371d87a70f84b70d1b1c824 to your computer and use it in GitHub Desktop.
Replace new lines with <br /> in slate.js
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;
},
});
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