Skip to content
This repository was archived by the owner on May 19, 2023. It is now read-only.

Commit a503eef

Browse files
committed
feat(api): custom components
1 parent ec929a1 commit a503eef

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

src/index.ts

+21-5
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,33 @@ import { COMPONENT_FLAG, DIRECTIVE_PREFIX } from '@models/generics';
55
// This is generally used for browser builds only, but it can be accessed in bundling environments
66
const init = (element: HTMLElement | Document = document): void => {
77
const stateDirective = `${DIRECTIVE_PREFIX}state`;
8-
const componentElements = element.querySelectorAll(`[${stateDirective}]`);
8+
const tagDirective = `${DIRECTIVE_PREFIX}tag`;
9+
const componentElements = element.querySelectorAll(`[${stateDirective}], [${tagDirective}]`);
910
const uninitializedComponents = [...componentElements].filter(
1011
(el) => (el as HTMLElement)[COMPONENT_FLAG] === undefined
1112
);
13+
let needsReInit = false;
1214

1315
uninitializedComponents.forEach((uninitializedComponent) => {
14-
const stateExpression = uninitializedComponent.getAttribute(stateDirective);
15-
const state = new Function(`return ${stateExpression}`)() || {};
16-
const currentComponent = component(state);
17-
currentComponent.mount(uninitializedComponent as HTMLElement);
16+
if (uninitializedComponent.hasAttribute(tagDirective)) {
17+
const tag = uninitializedComponent.getAttribute(tagDirective)!;
18+
const customComponents = [...element.querySelectorAll(tag)];
19+
// @ts-expect-error: this is a template element
20+
const realElement = uninitializedComponent.content.firstElementChild;
21+
customComponents.forEach((customComponent) => {
22+
customComponent.replaceWith(realElement.cloneNode(true));
23+
});
24+
if (customComponents.length > 0) needsReInit = true;
25+
} else {
26+
const stateExpression = uninitializedComponent.getAttribute(stateDirective);
27+
const state = new Function(`return ${stateExpression}`)() || {};
28+
const currentComponent = component(state);
29+
30+
currentComponent.mount(uninitializedComponent as HTMLElement);
31+
}
1832
});
33+
34+
if (needsReInit) init(element);
1935
};
2036

2137
export { init, component };

0 commit comments

Comments
 (0)