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
13 changes: 8 additions & 5 deletions src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@

const CACHE = {};

const stringify = JSON.stringify;

export default function html(statics) {
const key = statics.length + 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
Expand Down Expand Up @@ -55,12 +58,12 @@ const build = (statics) => {
if (!inTag) {
if (field || (buffer = buffer.replace(/^\s*\n\s*|\s*\n\s*$/g,''))) {
if (hasChildren++) out += ',';
out += field || JSON.stringify(buffer);
out += field || stringify(buffer);
}
}
else if (mode === MODE_TAGNAME) {
if (hasChildren++) out += ',';
out += 'h(' + (field || JSON.stringify(buffer));
out += 'h(' + (field || stringify(buffer));
mode = MODE_WHITESPACE;
}
else if (mode === MODE_ATTRIBUTE || (mode === MODE_WHITESPACE && buffer === '...')) {
Expand All @@ -77,8 +80,8 @@ const build = (statics) => {
if (!props) props += '{';
else props += ',' + (propsClose ? '' : '{');
propsClose = '}';
props += JSON.stringify(propName) + ':';
props += field || ((propHasValue || buffer) && JSON.stringify(buffer)) || 'true';
props += stringify(propName) + ':';
props += field || ((propHasValue || buffer) && stringify(buffer)) || 'true';
propName = '';
}
propHasValue = false;
Expand Down
2 changes: 2 additions & 0 deletions test/index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,7 @@ describe('htm', () => {
test('cache key should be unique', () => {
html`<a b="${'foo'}" />`;
expect(html`<a b="\0" />`).toEqual(h('a', { b: '\0' }));
expect(html`<a>${''}9aaaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}0${''}aaaaaaaaa${''}</a>`);
expect(html`<a>${''}0${''}aaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}.8aaaaaaaa${''}</a>`);
});
});