diff --git a/src/demo/hydration/deferred-composition-child.ts b/src/demo/hydration/deferred-composition-child.ts index 70b87ef..1e3ec1a 100644 --- a/src/demo/hydration/deferred-composition-child.ts +++ b/src/demo/hydration/deferred-composition-child.ts @@ -1,42 +1,25 @@ -/** - * An implementation of the `defer-hydration` community protocol which provides - * the name of the speaker in the underlying hydrated DOM. - */ -export class DeferredCompositionChild extends HTMLElement { - // Implement `defer-hydration` community protocol. - #hydrated = false; - public static observedAttributes = ['defer-hydration']; - public connectedCallback(): void { - if (!this.hasAttribute('defer-hydration')) this.#hydrate(); - } - public attributeChangedCallback( - name: string, _oldValue: string | null, newValue: string | null): void { - if (name === 'defer-hydration' && newValue === null) { - this.#hydrate(); - } - } - - // Hydrate some state. - #speaker!: string; - #hydrate(): void { - if (this.#hydrated) return; - this.#hydrated = true; +import { defineBaseComponent } from 'hydroactive'; - this.#speaker = this.querySelector('span#subject')!.textContent!; - console.log(`Hydrating ${this.#speaker}!`); - this.querySelector('span#target')!.textContent = 'HydroActive'; - } +/** Hydrates by reading the speaker's name from the DOM and exposing it. */ +export const DeferredCompositionChild = defineBaseComponent( + 'deferred-composition-child', + (host) => { + const speaker = host.query('span#subject').access().read(String); + console.log(`Hydrating ${speaker}!`); - // Return hydrated state. - public getSpeakerName(): string { - return this.#speaker; - } -} + host.query('span#target').access().write('HydroActive', String); -customElements.define('deferred-composition-child', DeferredCompositionChild); + return { + /** Provides hydrated speaker name. */ + getSpeakerName(): string { + return speaker; + } + }; + }, +); declare global { interface HTMLElementTagNameMap { - 'deferred-composition-child': DeferredCompositionChild; + 'deferred-composition-child': InstanceType; } } diff --git a/src/demo/hydration/deferred-composition.test.ts b/src/demo/hydration/deferred-composition.test.ts index 2f010c5..add7eb6 100644 --- a/src/demo/hydration/deferred-composition.test.ts +++ b/src/demo/hydration/deferred-composition.test.ts @@ -37,7 +37,7 @@ describe('deferred-composition', () => { document.body.append(el); const firstChild = el.querySelector('#first')! as - DeferredCompositionChild; + InstanceType; expect(isHydrated(firstChild)).toBeTrue(); expect(firstChild.querySelector('#target')!.textContent!) @@ -52,7 +52,7 @@ describe('deferred-composition', () => { hydrate(el, DeferredComposition); const secondChild = el.querySelector('#second')! as - DeferredCompositionChild; + InstanceType; expect(isHydrated(secondChild)).toBeTrue(); expect(secondChild.querySelector('#target')!.textContent!)