From 333c4378faa74ca81ff78672e4fcc5cc96b3735c Mon Sep 17 00:00:00 2001 From: yutent Date: Mon, 6 Mar 2023 15:27:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=81=E5=AD=98=E6=AD=A4=E4=BB=93=E5=BA=93,?= =?UTF-8?q?=20=E8=BF=81=E7=A7=BB=E5=88=B0=E6=96=B0=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core.js | 91 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 85 insertions(+), 6 deletions(-) diff --git a/src/core.js b/src/core.js index 860e52a..fbb26a2 100644 --- a/src/core.js +++ b/src/core.js @@ -3,9 +3,23 @@ * @author yutent * @date 2023/03/03 11:21:44 */ +const finalize = Symbol('finalize') +const RESET_CSS_STYLE = css` + * { + box-sizing: border-box; + margin: 0; + padding: 0; + } + ::before, + ::after { + box-sizing: border-box; + } +` export function css(strs, ...args) { - let output = '' + let output = ` + + ` let tmp = Array.from(strs) while (tmp.length) { output += tmp.shift() + (args.shift() || '') @@ -50,14 +64,61 @@ function getTemplate(html) { return template.content.cloneNode(true) } -export class Compoent extends HTMLElement { +function adoptStyles(root, styles = '') { + let sheet = new CSSStyleSheet() + if (typeof styles === 'string') { + styles = [styles] + } else { + styles = styles.flat(Infinity) + } + styles = (RESET_CSS_STYLE + styles.join(' ')).trim() + sheet.replaceSync(styles) + root.adoptedStyleSheets.push(sheet) +} + +function render(root, html) { + root.appendChild(getTemplate(html)) +} + +export class Component extends HTMLElement { static get observedAttributes() { - console.log(this.properties) - return [] + this[finalize]() + + let list = [] + this.elemProps.forEach((it, prop) => { + list.push(prop) + }) + return list } constructor() { super() + this.created && this.created() + } + + static [finalize]() { + if (this.finalized) { + return + } + + this.finalized = true + + this.elemProps = new Map() + + for (let k in this.props) { + let prop = Symbol(k) + let options = this.props[k] + this.elemProps.set(k, prop) + Object.defineProperty(this.prototype, k, { + get() { + return this[prop] || options.default + }, + set(val) { + this[prop] = val + }, + enumerable: false + }) + } } render() { @@ -66,10 +127,28 @@ export class Compoent extends HTMLElement { connectedCallback() { Object.defineProperty(this, 'root', { - value: this.attachShadow({ mode: 'open' }), + value: this.shadowRoot || this.attachShadow({ mode: 'open' }), enumerable: false }) - this.root.appendChild(getTemplate(this.render())) + adoptStyles(this.root, this.constructor.styles) + + render(this.root, this.render()) + + this.mounted && this.mounted() + } + + disconnectedCallback() { + console.log('>>>>') + } + + attributeChangedCallback(name, old, val) { + if (old === val) { + return + } + } + + adoptedCallback() { + // } }