2019-06-20 21:28:37 +08:00
|
|
|
import {
|
|
|
|
TestElement,
|
|
|
|
TestNode,
|
|
|
|
NodeTypes,
|
|
|
|
TestText,
|
|
|
|
TestComment
|
|
|
|
} from './nodeOps'
|
2018-10-29 05:43:27 +08:00
|
|
|
import { isOn } from '@vue/shared'
|
2018-10-02 05:22:49 +08:00
|
|
|
|
2018-10-02 05:35:55 +08:00
|
|
|
export function serialize(
|
|
|
|
node: TestNode,
|
|
|
|
indent: number = 0,
|
|
|
|
depth: number = 0
|
|
|
|
): string {
|
2018-10-02 05:22:49 +08:00
|
|
|
if (node.type === NodeTypes.ELEMENT) {
|
2018-10-02 05:35:55 +08:00
|
|
|
return serializeElement(node, indent, depth)
|
2018-10-02 05:22:49 +08:00
|
|
|
} else {
|
2018-10-02 05:35:55 +08:00
|
|
|
return serializeText(node, indent, depth)
|
2018-10-02 05:22:49 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-27 06:08:56 +08:00
|
|
|
export function serializeInner(
|
|
|
|
node: TestElement,
|
|
|
|
indent: number = 0,
|
|
|
|
depth: number = 0
|
|
|
|
) {
|
|
|
|
const newLine = indent ? `\n` : ``
|
|
|
|
return node.children.length
|
|
|
|
? newLine +
|
|
|
|
node.children.map(c => serialize(c, indent, depth + 1)).join(newLine) +
|
|
|
|
newLine
|
|
|
|
: ``
|
|
|
|
}
|
|
|
|
|
2018-10-02 05:35:55 +08:00
|
|
|
function serializeElement(
|
|
|
|
node: TestElement,
|
|
|
|
indent: number,
|
|
|
|
depth: number
|
|
|
|
): string {
|
2018-10-02 05:22:49 +08:00
|
|
|
const props = Object.keys(node.props)
|
|
|
|
.map(key => {
|
2019-08-27 06:08:56 +08:00
|
|
|
const value = node.props[key]
|
2019-12-18 00:50:10 +08:00
|
|
|
return isOn(key) || value == null
|
|
|
|
? ``
|
|
|
|
: value === ``
|
2021-07-20 06:24:18 +08:00
|
|
|
? key
|
|
|
|
: `${key}=${JSON.stringify(value)}`
|
2018-10-02 05:22:49 +08:00
|
|
|
})
|
2019-10-12 22:55:35 +08:00
|
|
|
.filter(Boolean)
|
2018-10-02 05:22:49 +08:00
|
|
|
.join(' ')
|
2018-10-02 05:35:55 +08:00
|
|
|
const padding = indent ? ` `.repeat(indent).repeat(depth) : ``
|
2018-10-02 05:22:49 +08:00
|
|
|
return (
|
|
|
|
`${padding}<${node.tag}${props ? ` ${props}` : ``}>` +
|
2019-08-27 06:08:56 +08:00
|
|
|
`${serializeInner(node, indent, depth)}` +
|
2018-10-02 05:22:49 +08:00
|
|
|
`${padding}</${node.tag}>`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2019-06-20 21:28:37 +08:00
|
|
|
function serializeText(
|
|
|
|
node: TestText | TestComment,
|
|
|
|
indent: number,
|
|
|
|
depth: number
|
|
|
|
): string {
|
2018-10-02 05:35:55 +08:00
|
|
|
const padding = indent ? ` `.repeat(indent).repeat(depth) : ``
|
2019-06-20 21:28:37 +08:00
|
|
|
return (
|
|
|
|
padding +
|
|
|
|
(node.type === NodeTypes.COMMENT ? `<!--${node.text}-->` : node.text)
|
|
|
|
)
|
2018-10-02 05:22:49 +08:00
|
|
|
}
|