Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
a1a6981
update microbundle, add optimized UMD and CJS builds
developit Dec 16, 2018
26d2a67
Update test harness and reorganize tests a bit.
developit Dec 16, 2018
7eae456
Custom JSX parser and proper unit tests!
developit Dec 16, 2018
d5d682a
Remove commented out implementation
developit Dec 16, 2018
010680d
Merge branch 'master' into custom-jsx-parser
developit Dec 17, 2018
badaa7e
Add tests for corner cases
jviide Dec 17, 2018
65ad81f
JSON.stringify property names
jviide Dec 17, 2018
11cd2b4
Fix boolean attributes following non-boolean ones
jviide Dec 17, 2018
3c83583
Fix spread and boolean props
jviide Dec 17, 2018
e2dee42
Ensure unique cache keys, allow NUL characters
jviide Dec 17, 2018
f790339
Add missing @babel/core dep
developit Dec 17, 2018
4fb17ab
Reorganize build scripts into packages to fix htm/preact path
developit Dec 17, 2018
8a4e977
Fix trim to match JSX behavior
developit Dec 17, 2018
7f84081
Move tests to mjs
developit Dec 17, 2018
6cb4a7a
Merge pull request #39 from jviide/custom-jsx-parser
developit Dec 17, 2018
444c21e
Merge branch 'custom-jsx-parser' of github.com:developit/htm into cus…
developit Dec 17, 2018
b48005c
Fix multiple spread props in one element
jviide Dec 17, 2018
1a3aea0
Merge pull request #40 from jviide/custom-jsx-parser-02
developit Dec 17, 2018
4760c17
Merge branch 'custom-jsx-parser' of github.com:developit/htm into cus…
developit Dec 17, 2018
d4220b2
Keep track of characters needed to close the current props
jviide Dec 17, 2018
419f1a4
Fix text containing single or double quotes
jviide Dec 18, 2018
40cdc09
Make whitespace normalization less susceptible to ReDoS
jviide Dec 18, 2018
b4ac1bc
Merge pull request #41 from jviide/custom-jsx-parser-03
developit Dec 18, 2018
97bf4e6
expand cache key computation (skip ci)
developit Dec 18, 2018
c54b793
cheap unique cache key by joining static segments using a CSV of stat…
developit Dec 18, 2018
1cdac44
Super simple almost-perfect unique cache key generation that is extre…
developit Dec 18, 2018
88b7704
final key optimization
developit Dec 18, 2018
53d4f3b
Drop function names to avoid Terser bug [-50b]
developit Dec 18, 2018
77ac338
silly size optimization
developit Dec 18, 2018
cc55c0a
Add performance test
developit Dec 18, 2018
95cb084
Silly boolean -> int size optimization
developit Dec 18, 2018
e42f58d
Add benchmark for cached template usage
developit Dec 18, 2018
ac0655f
Use JSON.stringify for cache key generation
jviide Dec 18, 2018
13c3123
Create cache key by run-length encoding statics
jviide Dec 18, 2018
d517751
Merge pull request #42 from jviide/custom-jsx-parser-04
developit Dec 18, 2018
04cba18
Attempt to fix babel plugin
developit Dec 18, 2018
d27f465
Add support for non-literal template variables
jviide Dec 18, 2018
0391069
Use the $[] instead of $_h[] inside the generated functions
jviide Dec 19, 2018
df1895c
Add tests for property-then-spread and spread-then-property
jviide Dec 19, 2018
5944ac0
Make generated Object.assigns shorter when possible
jviide Dec 19, 2018
165c809
Simplify Babel plugin by removing object flattening
jviide Dec 19, 2018
92a421a
Add a test for not mutating spread variables
jviide Dec 19, 2018
129e793
Merge pull request #44 from jviide/babel-plugin-fix-redux
developit Dec 19, 2018
9a8c8f0
Merge pull request #45 from jviide/custom-jsx-parser-05
developit Dec 19, 2018
1a0607d
Fix a few exceptions noticed when running the default test suite agai…
developit Dec 20, 2018
1d2297d
Run the main test suite against the Babel plugin too
developit Dec 20, 2018
755ec29
Add `variableArity:false` option.
developit Dec 20, 2018
15eff25
Merge pull request #43 from developit/babel-plugin-fix-redux
developit Dec 20, 2018
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
40 changes: 29 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
"version": "1.0.1",
"description": "The Tagged Template syntax for Virtual DOM. Only browser-compatible syntax.",
"main": "dist/htm.js",
"umd:main": "dist/htm.js",
"umd:main": "dist/htm.umd.js",
"module": "dist/htm.mjs",
"scripts": {
"build": "npm run -s build:main && npm run -s build:preact && npm run -s build:babel",
"build:main": "microbundle src/index.mjs -f es,umd --no-sourcemap --target web",
"build:preact": "microbundle src/integrations/preact/index.mjs -o preact/index.js -f es,umd --external preact,htm --no-sourcemap --target web && cp src/integrations/preact/index.d.ts src/integrations/preact/package.json preact/ && npm run -s build:preact:standalone",
"build:preact:standalone": "microbundle src/integrations/preact/standalone.mjs -o preact/standalone.js -f es,umd --no-sourcemap --target web",
"build:main": "microbundle src/index.mjs -f es,umd --no-sourcemap --target web && microbundle src/cjs.mjs -f iife --no-sourcemap --target web",
"build:preact": "cd src/integrations/preact && npm run build",
"build:babel": "cd packages/babel-plugin-htm && npm run build",
"test": "eslint src/**/*.mjs test && npm run build && jest test",
"test": "eslint src/**/*.mjs test/**/*.mjs && npm run build && jest test",
"release": "npm run build && git checkout --detach && git add -f babel dist preact && git commit -am \"$npm_package_version\" && git tag $npm_package_version && git push --tags && git checkout master"
},
"files": [
Expand All @@ -22,18 +21,34 @@
"eslintConfig": {
"extends": "developit",
"rules": {
"prefer-const": 0
"prefer-const": 0,
"no-fallthrough": 0
}
},
"jest": {
"testURL": "http://localhost",
"testMatch": [
"**/__tests__/**/*.?(m)js?(x)",
"**/?(*.)(spec|test).?(m)js?(x)"
],
"transform": {
"\\.m?js$": "babel-jest"
},
"moduleFileExtensions": [
"mjs",
"js"
],
"moduleNameMapper": {
"^htm-babel-plugin$": "<rootDir>/packages/babel-plugin-htm/dist/babel-plugin-htm.js",
"^babel-plugin-htm$": "<rootDir>/packages/babel-plugin-htm/dist/babel-plugin-htm.js",
"^htm$": "<rootDir>/dist/htm.js",
"^htm/preact$": "<rootDir>/preact/index.js"
"^babel-plugin-htm$": "<rootDir>/packages/babel-plugin-htm/index.mjs",
"^htm$": "<rootDir>/src/index.mjs",
"^htm/preact$": "<rootDir>/src/integrations/preact/index.mjs"
}
},
"babel": {
"presets": [
"env"
]
},
"repository": "developit/htm",
"keywords": [
"Hyperscript Tagged Markup",
Expand All @@ -49,7 +64,10 @@
"license": "Apache-2.0",
"homepage": "https://github.com/developit/htm",
"devDependencies": {
"@babel/core": "^7.1.2",
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.1.6",
"babel-jest": "^23.6.0",
"babel-preset-env": "^1.7.0",
"eslint": "^5.2.0",
"eslint-config-developit": "^1.1.1",
"jest": "^23.4.2",
Expand Down
144 changes: 61 additions & 83 deletions packages/babel-plugin-htm/index.mjs
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
import { JSDOM } from 'jsdom';
const before = global.document;
global.document = new JSDOM().window.document;
const htm = require('htm');
global.document = before;

// 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;
import htm from 'htm';

/**
* @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 @@ -59,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 @@ -68,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 @@ -163,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
3 changes: 1 addition & 2 deletions packages/babel-plugin-htm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@
"license": "Apache-2.0",
"homepage": "https://github.com/developit/htm/tree/master/packages/babel-plugin-htm",
"dependencies": {
"htm": "^1.0.0",
"jsdom": "^11.12.0"
"htm": "^1.0.0"
},
"devDependencies": {
"microbundle": "^0.6.0"
Expand Down
3 changes: 3 additions & 0 deletions src/cjs.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import htm from './index.mjs';
if (typeof module != 'undefined') module.exports = htm;
else self.htm = htm;
Loading