Skip to content

Commit b6cf69c

Browse files
committed
a method to create a DocumentFragment from an HTML string literal
(with working components)
1 parent 42f0176 commit b6cf69c

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

src/ElementComponent.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* If not, see <https://www.gnu.org/licenses/>.
1616
*/
1717
import {NodeComponent} from "./NodeComponent.js";
18+
import {DocumentComponent} from "./DocumentComponent.js";
1819

1920
/**
2021
* Non-readonly non-method keys
@@ -134,6 +135,23 @@ export abstract class ElementComponent<T extends Element> extends NodeComponent<
134135
return this;
135136
}
136137

138+
/**
139+
* Template literal tag function that accepts HTML code with components in a
140+
* string literal and returns a {@link DocumentComponent}
141+
*/
142+
public tag(strings: TemplateStringsArray, ...components: NodeComponent<any>[]): DocumentComponent {
143+
const ids = Array.from({length: components.length}, () => crypto.randomUUID());
144+
const doc = new DocumentComponent(strings.reduce((acc, str, index) => {
145+
acc += str;
146+
if (index < components.length)
147+
acc += `<slot name="${ids[index]}"></slot>`;
148+
return acc;
149+
}, ""));
150+
for (const [index, component] of components.entries())
151+
component.slot(ids[index]!, doc.node);
152+
return doc;
153+
}
154+
137155
/**
138156
* Set element property
139157
* @param name property name

0 commit comments

Comments
 (0)