Skip to content

Commit

Permalink
feat(vue): codegen handles void elements
Browse files Browse the repository at this point in the history
  • Loading branch information
Akryum committed Apr 22, 2022
1 parent ca13bc5 commit 9b324ea
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
1 change: 1 addition & 0 deletions examples/vue3/src/components/CodeGen.story.vue
Expand Up @@ -36,6 +36,7 @@ function onClick (event) {
>
<Variant
title="html"
icon="carbon:code"
:init-state="() => ({
object: { foo: 'bar' },
})"
Expand Down
3 changes: 3 additions & 0 deletions packages/histoire/src/client/app/codegen/const.ts
@@ -0,0 +1,3 @@
export const voidElements = [
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'
]
9 changes: 6 additions & 3 deletions packages/histoire/src/client/app/codegen/vue3.ts
Expand Up @@ -7,6 +7,7 @@ import { pascal } from 'case'
import { createAutoBuildingObject, indent } from './util'
import { serializeJs } from './serialize-js'
import type { Variant } from '../types'
import { voidElements } from './const'

export async function generateSourceCode (variant: Variant) {
const vnode = variant.slots().default?.({ state: variant.state ?? {} }) ?? []
Expand Down Expand Up @@ -186,7 +187,7 @@ async function printVNode (vnode: VNode): Promise<{ lines: string[], isText?: bo
} else if (Array.isArray(vnode.children)) {
for (const child of vnode.children) {
const result = await printVNode(child)
childLines.push(...result.lines)
childLines.push(...result.lines)
if (result.isText) {
isChildText = true
}
Expand Down Expand Up @@ -242,6 +243,8 @@ async function printVNode (vnode: VNode): Promise<{ lines: string[], isText?: bo
}
}

const isVoid = voidElements.includes(tagName.toLowerCase())

if (childLines.length > 0) {
if (childLines.length === 1 && tag.length === 1 && !attrs.length && isChildText) {
lines.push(`${tag[0]}${childLines[0]}</${tagName}>`)
Expand All @@ -252,9 +255,9 @@ async function printVNode (vnode: VNode): Promise<{ lines: string[], isText?: bo
}
} else if (tag.length > 1) {
lines.push(...tag)
lines.push('/>')
lines.push(isVoid ? '>' : '/>')
} else {
lines.push(`${tag[0]} />`)
lines.push(`${tag[0]}${isVoid ? '' : ' /'}>`)
}
} else if (vnode?.shapeFlag & 1 << 4) {
for (const child of vnode.children) {
Expand Down

0 comments on commit 9b324ea

Please sign in to comment.