element-vir
Version:
Heroic. Reactive. Declarative. Type safe. Web components without compromise.
43 lines (42 loc) • 1.32 kB
JavaScript
import { collapseWhiteSpace } from '@augment-vir/common';
/**
* Converts an HTML or SVG template into a raw string.
*
* @category Util
*/
export function convertTemplateToString(template) {
if ('templateString' in template) {
return template.templateString;
}
const { strings, values } = template;
if (!strings?.length && !values?.length) {
return '';
}
const valueList = [
...(values || []),
'', // this last empty string is so it's easier to deal with indexes
];
const stringsList = strings ?? [''];
const all = stringsList.map((stringValue, index) => {
const value = extractValue(stringValue, valueList[index]);
return `${stringValue}${value}`;
});
return collapseWhiteSpace(all.join(''));
}
function extractValue(previousString, value) {
if (value._$litType$ != undefined || value._$litDirective$ != undefined) {
// nested templates
return convertTemplateToString(value);
}
else if (Array.isArray(value)) {
// array of strings or templates.
const values = value.map((innerValue) => convertTemplateToString(innerValue));
return values.join('');
}
else if (previousString.endsWith('=')) {
return `"${value}"`;
}
else {
return value;
}
}