choojs / hyperx

🏷 - tagged template string virtual dom builder
BSD 2-Clause "Simplified" License
1.01k stars 48 forks source link

Add support for comments #44

Closed tornqvist closed 7 years ago

tornqvist commented 7 years ago

Large views written in hyperx can easily become quite messy, especially with nested expressions. Comments can help clear things up and later be removed in production using tools such as hyperxify or yo-yoify. Comments are disabled by default so as not to brake any existing implementations, though the result will differ as hyperx currently can't handle comments at all and output gets kind of messed up. With this change comments will simply be excluded unless otherwise specified in the options.

See an example implementation in bel: https://github.com/tornqvist/bel/commit/dc647d5070d6da7b3d73694423ff06d11832cfc4

Before:

const { createElement }  = require('bel')
const hyperx = require('hyperx')
const hx = hyperx(createElement)
const tree = hx`<div><!--this is a comment --></div>`
tree.toString() // => '<div><!-- this="this" is="is" a="a" comment="comment" --="--"></!--></div>'

After:

const { createElement }  = require('bel')
const hyperx = require('hyperx')
const hx = hyperx(createElement, {comments: true})
const tree = hx`<div><!-- this is a comment --></div>`
tree.toString() // => '<div><!-- this is a comment --></div>'

Since the comment element is kind of special and I didn't want to mess around with the structure, a comment node is represented with the tag !-- and the (fake) attribute comment:

function createElement(tag, props, children) {
  console.log(arguments) // [ '0': '!--', '1': { comment: ' this is a comment ' }, '2': undefined ]
}
const hx = hyperx(createElement, {comments: true})
hx`<!-- this is a comment -->`