Skip to content

Instantly share code, notes, and snippets.

@luwes
Created March 24, 2019 01:00
Show Gist options
  • Save luwes/426945a067feaa77d817d018494069d0 to your computer and use it in GitHub Desktop.
Save luwes/426945a067feaa77d817d018494069d0 to your computer and use it in GitHub Desktop.
Static variable tag names for lit-html, lighterhtml, etc...
import { html } from 'lit-html';
const superhtml = tagRef(html)
const result = superhtml`<${MyComponent}>Woohoo</${MyComponent}>`;
export function tagRef(html) {
const cache = new WeakMap();
return (s, ...e) => {
const tagIndex = (t, i) =>
// checks for '*<' or '*</' and a valid tagname
/[^>]*<\/?$/.test(t) && /[\w-]+/.test(e[i]) && i;
const indices = s.map(tagIndex).filter(i => i !== false);
if (indices.length === 0) return html.call(null, s, ...e);
const isTagIndex = i => indices.indexOf(i) !== -1;
let strings = cache.get(s);
if (!strings) {
strings = s.reduce(
(acc, token, i) =>
isTagIndex(i - 1)
? acc // if prev was tag skip token, it was joined below
: isTagIndex(i)
? acc.concat([token, s[i + 1]].join(e[i]))
: acc.concat(token),
[]
);
cache.set(s, strings);
}
const exps = e.filter((_, i) => !isTagIndex(i));
return html.call(null, strings, ...exps);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment