Skip to content
138 changes: 60 additions & 78 deletions packages/babel-plugin-htm/index.mjs
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
import htm from 'htm';

// htm() uses the HTML parser, which serializes attribute values.
// this is a problem, because composite values here can be made up
// of strings and AST nodes, which serialize to [object Object].
// Since the handoff from AST node handling to htm() is synchronous,
// this global lookup will always reflect the corresponding
// AST-derived values for the current htm() invocation.
let currentExpressions;

/**
* @param {Babel} babel
* @param {object} options
* @param {string} [options.pragma=h] JSX/hyperscript pragma.
* @param {string} [options.tag=html] The tagged template "tag" function name to process.
* @param {boolean} [options.monomorphic=false] Output monomorphic inline objects instead of using String literals.
* @param {boolean} [options.useBuiltIns=false] Use the native Object.assign instead of trying to polyfill it.
* @param {boolean} [options.variableArity=true] If `false`, always passes exactly 3 arguments to the pragma function.
*/
export default function htmBabelPlugin({ types: t }, options = {}) {
const pragma = options.pragma===false ? false : dottedIdentifier(options.pragma || 'h');
const useBuiltIns = options.useBuiltIns;
const inlineVNodes = options.monomorphic || pragma===false;

function dottedIdentifier(keypath) {
Expand Down Expand Up @@ -55,6 +49,11 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
}

function createVNode(tag, props, children) {
// Never pass children=[[]].
if (children.elements.length === 1 && t.isArrayExpression(children.elements[0]) && children.elements[0].elements.length === 0) {
children = children.elements[0];
}

if (inlineVNodes) {
return t.objectExpression([
options.monomorphic && t.objectProperty(propertyName('type'), t.numericLiteral(1)),
Expand All @@ -64,93 +63,75 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
options.monomorphic && t.objectProperty(propertyName('text'), t.nullLiteral())
].filter(Boolean));
}

return t.callExpression(pragma, [tag, props, children]);
}

let isVNode = t.isCallExpression;
if (inlineVNodes) {
isVNode = node => {
if (!t.isObjectExpression(node)) return false;
return node.properties[0].value.value!==3;
};
}

function childMapper(child, index, children) {
// JSX-style whitespace: (@TODO: remove? doesn't match the browser version)
if (typeof child==='string' && child.trim().length===0 || child==null) {
if (index===0 || index===children.length-1) return null;
}
if (typeof child==='string' && isVNode(children[index-1]) && isVNode(children[index+1])) {
child = child.trim();
}
if (typeof child==='string') {
const matches = child.match(/\$\$\$_h_\[(\d+)\]/);
if (matches) return currentExpressions[matches[1]];
return stringValue(child);
// Passing `{variableArity:false}` always produces `h(tag, props, children)` - where `children` is always an Array.
// Otherwise, the default is `h(tag, props, ...children)`.
if (options.variableArity !== false) {
children = children.elements;
}
return child;
}

function h(tag, props) {
if (typeof tag==='string') {
const matches = tag.match(/\$\$\$_h_\[(\d+)\]/);
if (matches) tag = currentExpressions[matches[1]];
else tag = t.stringLiteral(tag);
return t.callExpression(pragma, [tag, props].concat(children));
}

function spreadNode(args, state) {
// 'Object.assign({}, x)', can be collapsed to 'x'.
if (args.length === 2 && !t.isNode(args[0]) && Object.keys(args[0]).length === 0) {
return propsNode(args[1]);
}
const helper = useBuiltIns ? dottedIdentifier('Object.assign') : state.addHelper('extends');
return t.callExpression(helper, args.map(propsNode));
}

function propsNode(props) {
if (props == null) return t.nullLiteral();

//const propsNode = props==null || Object.keys(props).length===0 ? t.nullLiteral() : t.objectExpression(
const propsNode = t.objectExpression(
return t.isNode(props) ? props : t.objectExpression(
Object.keys(props).map(key => {
let value = props[key];
if (typeof value==='string') {
const tokenizer = /\$\$\$_h_\[(\d+)\]/g;
let token, lhs, root, index=0, lastIndex=0;
const append = expr => {
if (lhs) expr = t.binaryExpression('+', lhs, expr);
root = lhs = expr;
};
while ((token = tokenizer.exec(value))) {
append(t.stringLiteral(value.substring(index, token.index)));
append(currentExpressions[token[1]]);
index = token.index;
lastIndex = tokenizer.lastIndex;
}
if (lastIndex < value.length) {
append(t.stringLiteral(value.substring(lastIndex)));
}
value = root;
value = t.stringLiteral(value);
}
else if (typeof value==='boolean') {
value = t.booleanLiteral(value);
}
return t.objectProperty(propertyName(key), value);
})
);
}

// recursive iteration of possibly nested arrays of children.
let children = [];
if (arguments.length>2) {
const stack = [];
// eslint-disable-next-line prefer-rest-params
for (let i=arguments.length; i-->2; ) stack.push(arguments[i]);
while (stack.length) {
const child = stack.pop();
if (Array.isArray(child)) {
for (let i=child.length; i--; ) stack.push(child[i]);
}
else if (child!=null) {
children.push(child);
}
function transform(node, state) {
if (node === undefined) return t.identifier('undefined');
if (node == null) return t.nullLiteral();

const { tag, props, children } = node;
function childMapper(child) {
if (typeof child==='string') {
return stringValue(child);
}
children = children.map(childMapper).filter(Boolean);
return t.isNode(child) ? child : transform(child, state);
}
children = t.arrayExpression(children);

return createVNode(tag, propsNode, children);
const newTag = typeof tag === 'string' ? t.stringLiteral(tag) : tag;
const newProps = !Array.isArray(props) ? propsNode(props) : spreadNode(props, state);
const newChildren = t.arrayExpression(children.map(childMapper));
return createVNode(newTag, newProps, newChildren);
}

function h(tag, props, ...children) {
return { tag, props, children };
}

const html = htm.bind(h);

function treeify(statics, expr) {
const assign = Object.assign;
try {
Object.assign = function(...objs) { return objs; };
return html(statics, ...expr);
}
finally {
Object.assign = assign;
}
}

// The tagged template tag function name we're looking for.
// This is static because it's generally assigned via htm.bind(h),
Expand All @@ -159,13 +140,14 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
return {
name: 'htm',
visitor: {
TaggedTemplateExpression(path) {
TaggedTemplateExpression(path, state) {
const tag = path.node.tag.name;
if (htmlName[0]==='/' ? patternStringToRegExp(htmlName).test(tag) : tag === htmlName) {
const statics = path.node.quasi.quasis.map(e => e.value.raw);
const expr = path.node.quasi.expressions;
currentExpressions = expr;
path.replaceWith(html(statics, ...expr.map((p, i) => `$$$_h_[${i}]`)));

const tree = treeify(statics, expr);
path.replaceWith(transform(tree, state));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const build = (statics) => {
if (!spreadClose) {
spreadClose = ')';
if (!props) props = 'Object.assign({}';
else props = 'Object.assign({},' + props;
else props = 'Object.assign(' + props;
}
props += propsClose + ',' + field;
propsClose = '';
Expand Down
148 changes: 137 additions & 11 deletions test/babel.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('htm/babel', () => {
htmBabelPlugin
]
}).code
).toBe(`h("div",{id:"hello"},["hello"]);`);
).toBe(`h("div",{id:"hello"},"hello");`);
});

test('basic transformation with variable', () => {
Expand All @@ -27,34 +27,160 @@ describe('htm/babel', () => {
htmBabelPlugin
]
}).code
).toBe(`var name="world";h("div",{id:"hello"},["hello, ",name]);`);
).toBe(`var name="world";h("div",{id:"hello"},"hello, ",name);`);
});

test('inline vnode transformation: (pragma:false)', () => {
test('basic nested transformation', () => {
expect(
transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
transform('html`<a b=${2} ...${{ c: 3 }}>d: ${4}</a>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
pragma: false
useBuiltIns: true
}]
]
}).code
).toBe(`var name="world",vnode={tag:"div",props:{id:"hello"},children:["hello, ",name]};`);
).toBe(`h("a",Object.assign({b:2},{c:3}),"d: ",4);`);
});

test('monomorphic transformation', () => {

test('spread a single variable', () => {
expect(
transform('html`<a ...${foo}></a>`;', {
babelrc: false,
compact: true,
plugins: [
htmBabelPlugin
]
}).code
).toBe(`h("a",foo);`);
});

test('spread two variables', () => {
expect(
transform('html`<a ...${foo} ...${bar}></a>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
useBuiltIns: true
}]
]
}).code
).toBe(`h("a",Object.assign({},foo,bar));`);
});

test('property followed by a spread', () => {
expect(
transform('html`<a b="1" ...${foo}></a>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
useBuiltIns: true
}]
]
}).code
).toBe(`h("a",Object.assign({b:"1"},foo));`);
});

test('spread followed by a property', () => {
expect(
transform('html`<a ...${foo} b="1"></a>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
useBuiltIns: true
}]
]
}).code
).toBe(`h("a",Object.assign({},foo,{b:"1"}));`);
});

test('mix-and-match spreads', () => {
expect(
transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
transform('html`<a b="1" ...${foo} c=${2} ...${{d:3}}></a>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
monomorphic: true
useBuiltIns: true
}]
]
}).code
).toBe(`var name="world",vnode={type:1,tag:"div",props:{id:"hello"},children:[{type:3,tag:null,props:null,children:null,text:"hello, "},name],text:null};`);
).toBe(`h("a",Object.assign({b:"1"},foo,{c:2},{d:3}));`);
});

describe('{variableArity:false}', () => {
test('should pass no children as an empty Array', () => {
expect(
transform('html`<div />`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
variableArity: false
}]
]
}).code
).toBe(`h("div",null,[]);`);
});

test('should pass children as an Array', () => {
expect(
transform('html`<div id=hello>hello</div>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
variableArity: false
}]
]
}).code
).toBe(`h("div",{id:"hello"},["hello"]);`);
});
});

describe('{pragma:false}', () => {
test('should transform to inline vnodes', () => {
expect(
transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
pragma: false
}]
]
}).code
).toBe(`var name="world",vnode={tag:"div",props:{id:"hello"},children:["hello, ",name]};`);
});
});

describe('{monomorphic:true}', () => {
test('should transform to monomorphic inline vnodes', () => {
expect(
transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
monomorphic: true
}]
]
}).code
).toBe(`var name="world",vnode={type:1,tag:"div",props:{id:"hello"},children:[{type:3,tag:null,props:null,children:null,text:"hello, "},name],text:null};`);
});
});

describe('main test suite', () => {
// Run all of the main tests against the Babel plugin:
const mod = require('fs').readFileSync(require('path').resolve(__dirname, 'index.test.mjs'), 'utf8').replace(/\\0/g, '\0');
const { code } = transform(mod.replace(/^\s*import\s*.+?\s*from\s+(['"]).*?\1[\s;]*$/im, 'const htm = function(){};'), {
babelrc: false,
plugins: [htmBabelPlugin]
});
eval(code);
});
});
Loading