Skip to content

Commit 551f804

Browse files
authored
fix(richtext): rendering custom attributes (#344)
Fixes WDX-176 Fixes #343
1 parent dd8106b commit 551f804

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

packages/richtext/src/richtext.test.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1585,20 +1585,25 @@ describe('richTextResolver', () => {
15851585
expect(html).toBe('<h1 key="h1-0">Hello, world!</h1>');
15861586
});
15871587

1588-
it('should render a link with text and keys', () => {
1588+
it('should render a link with text, keys, and custom attrs', () => {
15891589
const link = {
15901590
type: 'paragraph',
15911591
content: [{
15921592
type: 'text',
15931593
text: 'Click me',
15941594
marks: [{
15951595
type: 'link',
1596-
attrs: { href: 'https://example.com' },
1596+
attrs: {
1597+
href: 'https://example.com',
1598+
custom: {
1599+
'data-custom': 'foo',
1600+
},
1601+
},
15971602
}],
15981603
}],
15991604
};
16001605
const html = richTextResolver<string>({ keyedResolvers: true }).render(link as unknown as StoryblokRichTextNode<string>);
1601-
expect(html).toBe('<p key="p-0"><a href="https://example.com" key="a-0">Click me</a></p>');
1606+
expect(html).toBe('<p key="p-0"><a href="https://example.com" key="a-0" data-custom="foo">Click me</a></p>');
16021607
});
16031608

16041609
it('should render text with multiple marks and keys', () => {

packages/richtext/src/utils/index.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { BlockAttributes } from '../types';
2+
13
export const SELF_CLOSING_TAGS = [
24
'area',
35
'base',
@@ -76,9 +78,13 @@ export const BLOCK_LEVEL_TAGS = [
7678
* ```
7779
*
7880
*/
79-
export const attrsToString = (attrs: Record<string, string> = {}) => Object.keys(attrs)
80-
.map(key => `${key}="${attrs[key]}"`)
81-
.join(' ');
81+
export const attrsToString = (attrs: BlockAttributes = {}) => {
82+
const { custom, ...attrsWithoutCustom } = attrs;
83+
const normalizedAttrs = { ...attrsWithoutCustom, ...custom };
84+
return Object.keys(normalizedAttrs)
85+
.map(key => `${key}="${normalizedAttrs[key]}"`)
86+
.join(' ');
87+
};
8288

8389
/**
8490
* Converts an object of attributes to a CSS style string.

0 commit comments

Comments
 (0)