Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: avoid rendering extra div on doc #148

Merged
merged 3 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/richtext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,42 @@ import { BlockTypes, MarkTypes, type StoryblokRichTextNode, type StoryblokRichTe
import { StoryblokComponent } from '@storyblok/vue';

describe('richtext', () => {
describe('document', () => {
it('should not render any wrapper tag', () => {
const { render } = richTextResolver({});
const richdata = {
type: 'doc',
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Hey ',
},
],
},
{
type: 'doc',
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'nested',
},
],
},
],
},
],
};

const html = render(richdata as StoryblokRichTextNode<string>);
expect(html).toBe('<p>Hey </p><p>nested</p>');
});
});
describe('blocktypes', () => {
it('should render a paragraph', async () => {
const { render } = richTextResolver({});
Expand Down
10 changes: 7 additions & 3 deletions src/richtext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@ import { attrsToString, attrsToStyle, cleanObject, escapeHtml, SELF_CLOSING_TAGS
function defaultRenderFn<T = string | null>(tag: string, attrs: Record<string, any> = {}, children?: T): T {
const attrsString = attrsToString(attrs);
const tagString = attrsString ? `${tag} ${attrsString}` : tag;
const content = Array.isArray(children) ? children.join('') : children || '';

if (SELF_CLOSING_TAGS.includes(tag)) {
if (!tag) {
return content as unknown as T;
}
else if (SELF_CLOSING_TAGS.includes(tag)) {
return `<${tagString}>` as unknown as T;
}
return `<${tagString}>${Array.isArray(children) ? children.join('') : children || ''}</${tag}>` as unknown as T;
return `<${tagString}>${content}</${tag}>` as unknown as T;
}

/**
Expand Down Expand Up @@ -202,7 +206,7 @@ export function richTextResolver<T>(options: StoryblokRichTextOptions<T> = {}) {
};

const mergedResolvers = new Map<StoryblokRichTextNodeTypes, StoryblokRichTextNodeResolver<T>>([
[BlockTypes.DOCUMENT, nodeResolver('div')],
[BlockTypes.DOCUMENT, nodeResolver('')],
[BlockTypes.HEADING, headingResolver],
[BlockTypes.PARAGRAPH, nodeResolver('p')],
[BlockTypes.UL_LIST, nodeResolver('ul')],
Expand Down