Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 51 additions & 79 deletions packages/babel-plugin-htm/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import htm from 'htm';
* @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.
*/
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 @@ -59,91 +60,60 @@ export default function htmBabelPlugin({ types: t }, options = {}) {

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') {
return stringValue(child);

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]);
}
return child;
const helper = useBuiltIns ? dottedIdentifier('Object.assign') : state.addHelper('extends');
return t.callExpression(helper, args.map(propsNode));
}

function h(tag, props) {
if (typeof tag==='string') {
tag = t.stringLiteral(tag);
}

let propsNode;

if (t.isObjectExpression(props)) {
propsNode = props;
for (let i in props) {
if (props.hasOwnProperty(i) && props[i] && props[i].type) {
for (let j=0; j<props.properties.length; j++) {
if (props.properties[j].start > props[i].start) {
props.properties.splice(j, 0, t.objectProperty(propertyName(i), props[i]));
break;
}
}
delete props[i];

function propsNode(props) {
return t.isNode(props) ? props : t.objectExpression(
Object.keys(props).map(key => {
let value = props[key];
if (typeof value==='string') {
value = t.stringLiteral(value);
}
}
}
else {
propsNode = t.objectExpression(
Object.keys(props).map(key => {
let value = props[key];
if (typeof value==='string') {
value = t.stringLiteral(value);
}
else if (typeof value==='boolean') {
value = t.booleanLiteral(value);
}
else if (typeof value==='number') {
value = t.stringLiteral(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);
else if (typeof value==='boolean') {
value = t.booleanLiteral(value);
}
return t.objectProperty(propertyName(key), value);
})
);
}

function transform({ tag, props, children }, state) {
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 @@ -152,12 +122,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;
path.replaceWith(html(statics, ...expr));

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
74 changes: 72 additions & 2 deletions test/babel.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,85 @@ describe('htm/babel', () => {
test('basic nested transformation', () => {
expect(
transform('html`<a b=${2} ...${{ c: 3 }}>d: ${4}</a>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
useBuiltIns: true
}]
]
}).code
).toBe(`h("a",Object.assign({b:2},{c:3}),["d: ",4]);`);
});

test('spread a single variable', () => {
expect(
transform('html`<a ...${foo}></a>`;', {
babelrc: false,
compact: true,
plugins: [
htmBabelPlugin
]
}).code
).toBe(`h("a",{b:2,c:3},["d: ",4]);`);
).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('html`<a b="1" ...${foo} c=${2} ...${{d:3}}></a>`;', {
babelrc: false,
compact: true,
plugins: [
[htmBabelPlugin, {
useBuiltIns: true
}]
]
}).code
).toBe(`h("a",Object.assign({b:"1"},foo,{c:2},{d:3}),[]);`);
});

test('inline vnode transformation: (pragma:false)', () => {
expect(
transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
Expand Down
6 changes: 6 additions & 0 deletions test/index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,10 @@ describe('htm', () => {
expect(html`<a>${''}9aaaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}0${''}aaaaaaaaa${''}</a>`);
expect(html`<a>${''}0${''}aaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}.8aaaaaaaa${''}</a>`);
});

test('do not mutate spread variables', () => {
const obj = {};
html`<a ...${obj} b="1" />`;
expect(obj).toEqual({});
});
});