Created
May 16, 2019 14:25
-
-
Save AStaroverov/56448f9baa560b4b7489ecf8ca0c36c8 to your computer and use it in GitHub Desktop.
preHTML - wrapper function fo dynamic tags lit-html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { html } from 'lit-element'; | |
import { TemplateResult } from 'lit-html'; | |
let str: string; | |
let valuesLength: number; | |
const cacheTemplateStringsToPreparedTemplateStrings = new WeakMap<TemplateStringsArray, string[]>(); | |
const cacheTemplateStringsToNeedlessValuesIndexes = new WeakMap<TemplateStringsArray, number[]>(); | |
// Сonvert dynamic tags to template strings | |
// exmaple: <${'div'}>${'this is example'}</${'div'}> => <div>${'this is example'}</div> | |
export function preHTML (strings: TemplateStringsArray, ...values: any[]): TemplateResult { | |
// check cache !important return equal link at first argument | |
if (cacheTemplateStringsToPreparedTemplateStrings.has(strings)) { | |
return html( | |
cacheTemplateStringsToPreparedTemplateStrings.get(strings) as any, | |
...dropIndexes(values, cacheTemplateStringsToNeedlessValuesIndexes.get(strings)) | |
); | |
} | |
const needlessIndexes: number[] = []; | |
const newStrings: string[] = []; | |
valuesLength = values.length; | |
for (var i = 0; i < strings.length; i += 1) { | |
str = strings[i]; | |
while ( | |
str[str.length - 1] === '<' // open tag | |
|| (str[str.length - 2] === '<' && str[str.length - 1] === '/') // close tag | |
) { | |
needlessIndexes.push(i); | |
str += values[i] + strings[++i]; | |
} | |
newStrings.push(str); | |
} | |
cacheTemplateStringsToPreparedTemplateStrings.set(strings, newStrings); | |
cacheTemplateStringsToNeedlessValuesIndexes.set(strings, needlessIndexes); | |
return html(newStrings as any, ...dropIndexes(values, needlessIndexes)); | |
} | |
function dropIndexes (arr: any[], indexes: number[]): any[] { | |
let j = 0; | |
const newArr = []; | |
for (var i = 0; i < arr.length; i += 1) { | |
if (indexes[j] === i) { | |
j += 1; | |
} else { | |
newArr.push(arr[i]); | |
} | |
} | |
return newArr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment