// x-counter.js —— 带 Shadow DOM 的自定义元素
import { formatCount, nextCount, parseStep } from './main.js';
export class XCounter extends HTMLElement {
static observedAttributes = ['step'];
#count = 0;
#step = 1;
constructor() {
super();
this.attachShadow({ mode: 'open' }).innerHTML = `
0
`;
}
connectedCallback() {
if (!this.hasAttribute('role')) this.setAttribute('role', 'group');
this.shadowRoot.addEventListener('click', this.#onClick);
this.#render();
}
disconnectedCallback() {
this.shadowRoot.removeEventListener('click', this.#onClick);
}
attributeChangedCallback(name, _oldValue, newValue) {
if (name === 'step') this.#step = parseStep(newValue);
this.#render();
}
get count() {
return this.#count;
}
#onClick = (event) => {
const button = event.target.closest('button');
if (!button) return;
const delta = button.dataset.action === 'inc' ? this.#step : -this.#step;
this.#count = nextCount(this.#count, delta);
this.#render();
this.dispatchEvent(
new CustomEvent('count-change', {
detail: { count: this.#count },
bubbles: true,
composed: true,
}),
);
};
#render() {
const value = this.shadowRoot?.querySelector('[part="value"]');
if (value) value.textContent = formatCount(this.#count);
}
}
if (typeof customElements !== 'undefined' && !customElements.get('x-counter')) {
customElements.define('x-counter', XCounter);
}