From dce7e2c439414d2708573858d5ed9ce84c5d2580 Mon Sep 17 00:00:00 2001 From: Justin Weiss Date: Thu, 22 Mar 2018 14:54:35 -0700 Subject: [PATCH] Allow null return values, which will skip serializing that node (#1699) Sometimes, I have nodes that only make sense temporarily, so it doesn't make sense to serialize them. Following the pattern in React, explicitly returning `null` from a serialzation rule should result in that node (and its children) not making it into the serialized document. --- packages/slate-html-serializer/src/index.js | 4 +- .../test/serialize/null-rule.js | 41 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 packages/slate-html-serializer/test/serialize/null-rule.js diff --git a/packages/slate-html-serializer/src/index.js b/packages/slate-html-serializer/src/index.js index 94e88dfd8..032380288 100644 --- a/packages/slate-html-serializer/src/index.js +++ b/packages/slate-html-serializer/src/index.js @@ -325,7 +325,7 @@ class Html { serialize = (value, options = {}) => { const { document } = value - const elements = document.nodes.map(this.serializeNode) + const elements = document.nodes.map(this.serializeNode).filter(el => el) if (options.render === false) return elements const html = renderToStaticMarkup({elements}) @@ -351,6 +351,7 @@ class Html { for (const rule of this.rules) { if (!rule.serialize) continue const ret = rule.serialize(node, children) + if (ret === null) return if (ret) return addKey(ret) } @@ -372,6 +373,7 @@ class Html { for (const rule of this.rules) { if (!rule.serialize) continue const ret = rule.serialize(mark, children) + if (ret === null) return if (ret) return addKey(ret) } diff --git a/packages/slate-html-serializer/test/serialize/null-rule.js b/packages/slate-html-serializer/test/serialize/null-rule.js new file mode 100644 index 000000000..f419ea500 --- /dev/null +++ b/packages/slate-html-serializer/test/serialize/null-rule.js @@ -0,0 +1,41 @@ +/** @jsx h */ + +import React from 'react' +import h from '../helpers/h' + +export const rules = [ + { + serialize(obj, children) { + if (obj.object == 'block' && obj.type == 'paragraph') { + return React.createElement('p', {}, children) + } + + if (obj.object == 'inline' && obj.type == 'link') { + return React.createElement('a', {}, children) + } + + if (obj.object == 'inline' && obj.type == 'comment') { + return null + } + + if (obj.object == 'block' && obj.type == 'quote') { + return null + } + }, + }, +] + +export const input = ( + + + + Something skipped Here + + Skipped + + +) + +export const output = ` +

Something Here

+`.trim()