Skip to content
Closed
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
"extends": "developit",
"rules": {
"prefer-const": 0,
"no-fallthrough": 0
"no-fallthrough": 0,
"prefer-rest-params": 0,
"func-style": 0
}
},
"jest": {
Expand Down
32 changes: 27 additions & 5 deletions packages/babel-plugin-htm/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
const useBuiltIns = options.useBuiltIns;
const inlineVNodes = options.monomorphic || pragma===false;

const symbol = Symbol();

function dottedIdentifier(keypath) {
const path = keypath.split('.');
let out;
Expand Down Expand Up @@ -73,7 +75,26 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
return t.callExpression(pragma, [tag, props].concat(children));
}

function flatten(props, result = []) {
const { [symbol]: head, ...tail } = props;
if (head) head.forEach(obj => {
flatten(obj, result);
});
if (Object.keys(tail).length > 0) {
result.push(tail);
}
return result;
}

function spreadNode(args, state) {
if (args.length > 0 && t.isNode(args[0])) {
args.unshift({});
}

// 'Object.assign(x)', can be collapsed to 'x'.
if (args.length === 1) {
return propsNode(args[0]);
}
// '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]);
Expand All @@ -83,8 +104,6 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
}

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

return t.isNode(props) ? props : t.objectExpression(
Object.keys(props).map(key => {
let value = props[key];
Expand All @@ -111,7 +130,7 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
return t.isNode(child) ? child : transform(child, state);
}
const newTag = typeof tag === 'string' ? t.stringLiteral(tag) : tag;
const newProps = !Array.isArray(props) ? propsNode(props) : spreadNode(props, state);
const newProps = props ? spreadNode(flatten(props), state) : t.nullLiteral();
const newChildren = t.arrayExpression(children.map(childMapper));
return createVNode(newTag, newProps, newChildren);
}
Expand All @@ -125,7 +144,7 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
function treeify(statics, expr) {
const assign = Object.assign;
try {
Object.assign = function(...objs) { return objs; };
Object.assign = function(...objs) { return { [symbol]: objs }; };
return html(statics, ...expr);
}
finally {
Expand All @@ -147,7 +166,10 @@ export default function htmBabelPlugin({ types: t }, options = {}) {
const expr = path.node.quasi.expressions;

const tree = treeify(statics, expr);
path.replaceWith(transform(tree, state));
const node = !Array.isArray(tree)
? transform(tree, state)
: t.arrayExpression(tree.map(root => transform(root, state)));
path.replaceWith(node);
}
}
}
Expand Down
233 changes: 90 additions & 143 deletions src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,174 +11,121 @@
* limitations under the License.
*/

const CACHE = {};

const stringify = JSON.stringify;

export default function html(statics) {
let key = '.';
for (let i=0; i<statics.length; i++) key += statics[i].length + ',' + statics[i];
const tpl = CACHE[key] || (CACHE[key] = build(statics));

// eslint-disable-next-line prefer-rest-params
return tpl(this, arguments);
}

const TAG_START = 60;
const TAG_END = 62;
const EQUALS = 61;
const QUOTE_DOUBLE = 34;
const QUOTE_SINGLE = 39;
const TAB = 9;
const NEWLINE = 10;
const RETURN = 13;
const SPACE = 32;
const SLASH = 47;

const MODE_WHITESPACE = 0;
const MODE_SLASH = 0;
const MODE_TEXT = 1;
const MODE_TAGNAME = 9;
const MODE_ATTRIBUTE = 13;
const MODE_SKIP = 47;
const MODE_WHITESPACE = 2;
const MODE_TAGNAME = 3;
const MODE_ATTRIBUTE = 4;

/** Create a template function given strings from a tagged template. */
const build = (statics) => {
let mode = MODE_WHITESPACE;
let out = 'return ';
const htm = function(statics) {
const root = [];
const stack = [];
let mode = MODE_TEXT;
let buffer = '';
let field = '';
let hasChildren = 0;
let props = '';
let propsClose = '';
let spreadClose = '';
let quote = 0;
let slash, charCode, inTag, propName, propHasValue;
let quote = '';
let args = root;
let char, propName;

const commit = () => {
if (!inTag) {
if (field || (buffer = buffer.replace(/^\s*\n\s*|\s*\n\s*$/g,''))) {
if (hasChildren++) out += ',';
out += field || stringify(buffer);
}
if (mode === MODE_TEXT && (buffer = buffer.replace(/^\s*\n\s*|\s*\n\s*$/g, ''))) {
args.push(buffer);
}
else if (mode === MODE_TAGNAME) {
if (hasChildren++) out += ',';
out += 'h(' + (field || stringify(buffer));
else if (mode === MODE_TAGNAME && buffer) {
args[0] = buffer;
mode = MODE_WHITESPACE;
}
else if (mode === MODE_ATTRIBUTE || (mode === MODE_WHITESPACE && buffer === '...')) {
if (mode === MODE_WHITESPACE) {
if (!spreadClose) {
spreadClose = ')';
if (!props) props = 'Object.assign({}';
else props = 'Object.assign(' + props;
}
props += propsClose + ',' + field;
propsClose = '';
}
else if (propName) {
if (!props) props += '{';
else props += ',' + (propsClose ? '' : '{');
propsClose = '}';
props += stringify(propName) + ':';
props += field || ((propHasValue || buffer) && stringify(buffer)) || 'true';
propName = '';
}
propHasValue = false;
else if (mode === MODE_WHITESPACE && buffer) {
(args[1] = args[1] || {})[buffer] = true;
}
else if (mode === MODE_WHITESPACE) {
mode = MODE_ATTRIBUTE;
// we're in an attribute name
propName = buffer;
buffer = field = '';
commit();
mode = MODE_WHITESPACE;
else if (mode === MODE_ATTRIBUTE && propName) {
(args[1] = args[1] || {})[propName] = buffer;
propName = '';
}
buffer = field = '';
buffer = '';
};

for (let i=0; i<statics.length; i++) {
if (i > 0) {
if (!inTag) commit();
field = `$[${i}]`;
commit();
if (i) {
if (mode === MODE_TEXT) {
commit();
args.push(arguments[i]);
}
else if (mode === MODE_TAGNAME) {
args[0] = arguments[i];
mode = MODE_WHITESPACE;
}
else if (mode === MODE_WHITESPACE && buffer === '...') {
args[1] = Object.assign(args[1] || {}, arguments[i]);
}
else if (mode === MODE_ATTRIBUTE && propName) {
(args[1] = args[1] || {})[propName] = arguments[i];
propName = '';
}
buffer = '';
}

for (let j=0; j<statics[i].length; j++) {
charCode = statics[i].charCodeAt(j);
for (let j=0; j<arguments[0][i].length; j++) {
char = arguments[0][i][j];

if (!inTag) {
if (charCode === TAG_START) {
if (mode === MODE_TEXT) {
if (char === '<') {
// commit buffer
commit();
inTag = 1;
spreadClose = propsClose = props = '';
slash = propHasValue = false;
stack.push(args);
args = ['', null];
buffer = '';
mode = MODE_TAGNAME;
continue;
}
else {
buffer += char;
}
}
else {
if (charCode === QUOTE_SINGLE || charCode === QUOTE_DOUBLE) {
if (quote === charCode) {
quote = 0;
continue;
}
if (quote === 0) {
quote = charCode;
continue;
}
else if (quote) {
if (char === quote) {
quote = '';
}

if (quote === 0) {
switch (charCode) {
case TAG_END:
commit();
if (mode !== MODE_SKIP) {
if (!props) {
out += ',null';
}
else {
out += ',' + props + propsClose + spreadClose;
}
}
if (slash) {
out += ')';
}
inTag = 0;
props = '';
mode = MODE_TEXT;
continue;
case EQUALS:
mode = MODE_ATTRIBUTE;
propHasValue = true;
propName = buffer;
buffer = '';
continue;
case SLASH:
if (!slash) {
slash = true;
// </foo>
if (mode === MODE_TAGNAME && !buffer.trim()) {
buffer = field = '';
mode = MODE_SKIP;
}
}
continue;
case TAB:
case NEWLINE:
case RETURN:
case SPACE:
// <a disabled>
commit();
mode = MODE_WHITESPACE;
continue;
}
else {
buffer += char;
}
}
else if (char === '"' || char === "'") {
quote = char;
}
else if (char === '>') {
commit();
mode = MODE_TEXT;
}
else if (!mode) {
// Ignore everything until the tag ends
}
else if (char === '=') {
mode = MODE_ATTRIBUTE;
propName = buffer;
buffer = '';
}
else if (char === '/') {
commit();
if (mode === MODE_TAGNAME) {
// no tag name before the slash
args = stack.pop();
}
// eslint-disable-next-line prefer-spread
mode = this.apply(null, args); // Use 'mode' as a temporary variable
(args = stack.pop()).push(mode);
mode = MODE_SLASH;
}
else if (char === ' ' || char === '\t' || char === '\n' || char === '\r') {
// <a disabled>
commit();
mode = MODE_WHITESPACE;
}
else {
buffer += char;
}
buffer += statics[i].charAt(j);
}
}
commit();
return Function('h', '$', out);
return root.length < 2 ? root[0] : root;
};

export default htm;
8 changes: 8 additions & 0 deletions test/index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ describe('htm', () => {
expect(html`<div/>`).toEqual({ tag: 'div', props: null, children: [] });
expect(html`<span />`).toEqual({ tag: 'span', props: null, children: [] });
});

test('multiple root elements', () => {
expect(html`<a /><b></b><c><//>`).toEqual([
{ tag: 'a', props: null, children: [] },
{ tag: 'b', props: null, children: [] },
{ tag: 'c', props: null, children: [] }
]);
});

test('single dynamic tag name', () => {
expect(html`<${'foo'} />`).toEqual({ tag: 'foo', props: null, children: [] });
Expand Down