Repair multi-attribute template position

This commit is contained in:
Tony Garnock-Jones 2023-12-20 21:29:42 +13:00
parent 672c82ac64
commit ccb939be19
1 changed files with 8 additions and 7 deletions

View File

@ -15,9 +15,10 @@ export function escape(s: string): string {
export type HtmlFragment = string | number | Node | Array<HtmlFragment>;
const tag = randomId(8, true);
const placeholderRe = new RegExp(`X-${tag}-(\\d+)-${tag}-X`, 'g');
const onePlaceholderRe = new RegExp(`x-${tag}-(\\d+)-${tag}-x`);
const allPlaceholdersRe = new RegExp(`x-${tag}-(\\d+)-${tag}-x`, 'g');
function placeholder(n: number): string {
return `X-${tag}-${n}-${tag}-X`;
return `x-${tag}-${n}-${tag}-x`;
}
function splitByPlaceholders(s: string): { constantParts: string[], placeholders: number[] } {
@ -25,10 +26,10 @@ function splitByPlaceholders(s: string): { constantParts: string[], placeholders
let lastConstantStart = 0;
const constantParts: string[] = [];
const placeholders: number[] = [];
while ((match = placeholderRe.exec(s)) !== null) {
while ((match = allPlaceholdersRe.exec(s)) !== null) {
constantParts.push(s.substring(lastConstantStart, match.index));
placeholders.push(parseInt(match[1], 10));
lastConstantStart = placeholderRe.lastIndex;
lastConstantStart = allPlaceholdersRe.lastIndex;
}
constantParts.push(s.substring(lastConstantStart));
return { constantParts, placeholders };
@ -82,8 +83,8 @@ function nodeInserter(n: number): PlaceholderAction {
function attributesInserter(n: number): PlaceholderAction {
return (vs, node) => {
const e = document.createElement('template');
e.innerHTML = `<x-dummy ${renderFragment(vs[n], true).join('')}></x-dummy>`;
Array.from(e.attributes).forEach(a =>
e.innerHTML = `<x-dummy ${renderFragment(vs[n], false).join('')}></x-dummy>`;
Array.from(e.content.firstElementChild!.attributes).forEach(a =>
(node as Element).setAttribute(a.name, a.value));
};
}
@ -146,7 +147,7 @@ export class HtmlFragmentBuilder {
for (let i = 0; i < e.attributes.length; i++) {
const attr = e.attributes[i];
const attrName = attr.name;
const nameIsPlaceholder = attrName.match(placeholderRe);
const nameIsPlaceholder = attrName.match(onePlaceholderRe);
if (nameIsPlaceholder !== null) {
e.removeAttributeNode(attr);
i--;