From 1b8b61a8d98d9815354d4aacb444f7b0c8391401 Mon Sep 17 00:00:00 2001 From: Astrian Zheng Date: Wed, 21 May 2025 14:04:09 +1000 Subject: [PATCH] feat: implement parseTemplate utility and refactor component initialization --- src/main.ts | 30 ++++++++++++------------------ src/utils/index.ts | 5 +++++ src/utils/parseTemplate.ts | 16 ++++++++++++++++ 3 files changed, 33 insertions(+), 18 deletions(-) create mode 100644 src/utils/index.ts create mode 100644 src/utils/parseTemplate.ts diff --git a/src/main.ts b/src/main.ts index d707c90..35b7ada 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,3 +1,5 @@ +import { parseTemplate } from './utils/parseTemplate' + interface ComponentOptions { tag: string template: string @@ -57,6 +59,11 @@ export default (options: ComponentOptions) => { constructor() { super() + // initialize dom tree and append to shadow root + this._initialize() + } + + private _initState() { // copy state from options this._states = new Proxy( { ...(states || {}) }, @@ -118,12 +125,12 @@ export default (options: ComponentOptions) => { }, }, ) - - // initialize dom tree and append to shadow root - this._initialize() } private _initialize() { + // initialize state + this._initState() + // initialize shadow dom const shadow = this.attachShadow({ mode: 'open' }) @@ -133,21 +140,8 @@ export default (options: ComponentOptions) => { this.shadowRoot?.appendChild(styleElement) } - const parser = new DOMParser() - const doc = parser.parseFromString(template, 'text/html') - - const mainContent = doc.body.firstElementChild - let rootElement: Element - - if (mainContent) { - rootElement = document.importNode(mainContent, true) - shadow.appendChild(rootElement) - } else { - const container = document.createElement('div') - container.innerHTML = template - rootElement = container - shadow.appendChild(container) - } + const rootElement = parseTemplate(template) + shadow.appendChild(rootElement) this._processTemplateMacros(rootElement) } diff --git a/src/utils/index.ts b/src/utils/index.ts new file mode 100644 index 0000000..a6b382d --- /dev/null +++ b/src/utils/index.ts @@ -0,0 +1,5 @@ +import { parseTemplate } from './parseTemplate' + +export default { + parseTemplate, +} diff --git a/src/utils/parseTemplate.ts b/src/utils/parseTemplate.ts new file mode 100644 index 0000000..0da7669 --- /dev/null +++ b/src/utils/parseTemplate.ts @@ -0,0 +1,16 @@ +export function parseTemplate(template: string): Element { + const parser = new DOMParser() + const doc = parser.parseFromString(template, 'text/html') + + const mainContent = doc.body.firstElementChild + let rootElement: Element + + if (mainContent) rootElement = document.importNode(mainContent, true) + else { + const container = document.createElement('div') + container.innerHTML = template + rootElement = container + } + + return rootElement +}