Skip to content

Commit

Permalink
feat: support nullish values for html rich text serializer functions
Browse files Browse the repository at this point in the history
  • Loading branch information
lihbr committed Jul 18, 2024
1 parent 5cff6b3 commit eff843a
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/richtext/utils/hastUtilToRichText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ type RichTextHTMLMapSerializerFunction = (
| RichTextHTMLMapSerializerShorthand
| RTNode
| RTInlineNode
| RTPartialInlineNode;
| RTPartialInlineNode
| null
| undefined;

/**
* Serializes an hast {@link Element} node matching the given HTML tag name or
Expand Down Expand Up @@ -209,8 +211,14 @@ export const hastUtilToRichText = (
context: { listType: lastListType },
});

// When the serializer returns a rich text node, we append it and return.
if (typeof shorthandOrNode === "object" && "type" in shorthandOrNode) {
if (!shorthandOrNode) {
// Exit on unhandled node.
return;
} else if (
typeof shorthandOrNode === "object" &&
"type" in shorthandOrNode
) {
// When the serializer returns a rich text node, we append it and return.
switch (shorthandOrNode.type) {
case RichTextNodeType.strong:
case RichTextNodeType.em:
Expand Down
17 changes: 17 additions & 0 deletions test/richtext/__snapshots__/htmlAsRichText.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,23 @@ exports[`transforms HTML to rich text > configuration > serializer > function se
]
`;

exports[`transforms HTML to rich text > configuration > serializer > function serializer > nullish 1`] = `
[
{
"direction": "ltr",
"spans": [],
"text": "lorem ipsum dolor sit amet",
"type": "paragraph",
},
{
"direction": "ltr",
"spans": [],
"text": "consectetur adipiscing elit",
"type": "paragraph",
},
]
`;

exports[`transforms HTML to rich text > configuration > serializer > function serializer > span nodes > full 1`] = `
[
{
Expand Down
11 changes: 11 additions & 0 deletions test/richtext/htmlAsRichText.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,17 @@ describe("transforms HTML to rich text", () => {
expectAsHTMLNotToMatchInput: true,
});

testHTMLAsRichTextHelper("nullish", {
input: /* html */ `<p data-heading>lorem ipsum dolor sit amet</p><p>consectetur adipiscing elit</p>`,
config: {
serializer: {
p: ({ node }) =>
"dataHeading" in node.properties ? null : "paragraph",
},
},
expectAsHTMLNotToMatchInput: true,
});

testHTMLAsRichTextHelper("text nodes", {
input: /* html */ `<div>lorem ipsum dolor sit amet</div>`,
config: {
Expand Down

0 comments on commit eff843a

Please sign in to comment.