Skip to content

Commit

Permalink
fix(react): heading with links not rendered
Browse files Browse the repository at this point in the history
  • Loading branch information
jpedroschmitz committed Oct 14, 2021
1 parent 336b282 commit ccd701d
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/react-renderer/src/RichText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from './defaultElements';
import { RenderText } from './RenderText';
import { getElements } from './util/getElements';
import { elementIsEmpty } from './util/elementIsEmpty';

function RenderNode({
node,
Expand Down Expand Up @@ -65,15 +66,15 @@ function RenderElement({
const { nodeId, nodeType } = rest;

/**
* Checks if element has empty text, so it can be removed.
* Checks if the element is empty, so that it can be removed.
*
* Elements that can be removed with empty text are defined in `defaultRemoveEmptyElements`
*/
if (
defaultRemoveEmptyElements?.[
elementKeys[type] as keyof RemoveEmptyElementType
] &&
children[0].text === ''
elementIsEmpty({ children })
) {
return <Fragment />;
}
Expand Down
32 changes: 32 additions & 0 deletions packages/react-renderer/src/util/elementIsEmpty.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {
ElementNode,
isElement,
isText,
Text,
} from '@graphcms/rich-text-types';

export function elementIsEmpty({
children,
}: {
children: (ElementNode | Text)[];
}): boolean {
// Checks if the children array has more than one element.
// It may have a link inside, that's why we need to check this condition.
if (children.length > 1) {
const hasText = children.filter(function f(child): boolean | number {
if (isText(child) && child.text !== '') {
return true;
}

if (isElement(child)) {
return (child.children = child.children.filter(f)).length;
}

return false;
});

return hasText.length > 0 ? false : true;
} else if (children[0].text === '') return true;

return true;
}
10 changes: 10 additions & 0 deletions packages/react-renderer/test/RichText.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,22 @@ describe('@graphcms/rich-text-react-renderer', () => {
expect(container).toMatchInlineSnapshot(`
<div>
<h2>
<a
href="https://graphcms.com"
>
Testing Link
</a>
</h2>
<h2>
<a
href="https://graphcms.com"
>
Link
</a>
2
</h2>
<table>
<tbody>
<tr>
Expand Down
20 changes: 20 additions & 0 deletions packages/react-renderer/test/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,26 @@ export const emptyContent: RichTextContent = [
},
],
},
{
type: 'heading-two',
children: [
{
text: '',
},
{
href: 'https://graphcms.com',
type: 'link',
children: [
{
text: 'Link',
},
],
},
{
text: ' 2',
},
],
},
{
type: 'heading-one',
children: [
Expand Down

0 comments on commit ccd701d

Please sign in to comment.