2018-10-02 05:22:49 +08:00
|
|
|
import { TestElement, TestNode, NodeTypes, TestText } from './nodeOps'
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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 => {
|
|
|
|
return `${key}=${JSON.stringify(node.props[key])}`
|
|
|
|
})
|
|
|
|
.join(' ')
|
2018-10-02 05:50:02 +08:00
|
|
|
const newLine = indent ? `\n` : ``
|
2018-10-02 05:22:49 +08:00
|
|
|
const children = node.children.length
|
2018-10-02 05:50:02 +08:00
|
|
|
? newLine +
|
|
|
|
node.children.map(c => serialize(c, indent, depth + 1)).join(newLine) +
|
|
|
|
newLine
|
2018-10-02 05:22:49 +08:00
|
|
|
: ``
|
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}` : ``}>` +
|
|
|
|
`${children}` +
|
|
|
|
`${padding}</${node.tag}>`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2018-10-02 05:35:55 +08:00
|
|
|
function serializeText(node: TestText, indent: number, depth: number): string {
|
|
|
|
const padding = indent ? ` `.repeat(indent).repeat(depth) : ``
|
|
|
|
return padding + node.text
|
2018-10-02 05:22:49 +08:00
|
|
|
}
|