diff --git a/src/attr.ts b/src/attr.ts index 2d7472fc..1236d811 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -34,50 +34,96 @@ export function attr(proto: Record, key: K): voi * * This is automatically called as part of `@controller`. If a class uses the * `@controller` decorator it should not call this manually. + * + * Calling it again only initializes the property names that have not been + * initialized yet, so a class may pass additional names (for example, from + * its own `connectedCallback`) after `@controller` already initialized the + * decorated ones. + * + * Implicit calls (no names given) short-circuit once the decorated names + * are being initialized or are already done: reflecting a missing default + * value back to an attribute synchronously invokes `attributeChangedCallback`, + * which calls this again, and without the short-circuit each re-entrant call + * would rescan every decorated name. Explicit calls are never short-circuited + * and always initialize the names they are given. */ -const initialized = new WeakSet() +const initializedAttrs = new WeakMap>() +const implicitAttrsState = new WeakMap() export function initializeAttrs(instance: HTMLElement, names?: Iterable): void { - if (initialized.has(instance)) return - initialized.add(instance) + let initialized = initializedAttrs.get(instance) + if (!initialized) { + initialized = new Set() + initializedAttrs.set(instance, initialized) + } const proto = Object.getPrototypeOf(instance) const prefix = proto?.constructor?.attrPrefix ?? 'data-' - if (!names) names = meta(proto, attrKey) - for (const key of names) { - const value = (>(instance))[key] - const name = mustDasherize(`${prefix}${key}`) - let descriptor: PropertyDescriptor = { - configurable: true, - get(this: HTMLElement): string { - return this.getAttribute(name) || '' - }, - set(this: HTMLElement, newValue: string) { - this.setAttribute(name, newValue || '') - } - } - if (typeof value === 'number') { - descriptor = { + const explicit = names != null + let namesToInit: Iterable + if (explicit) { + namesToInit = names as Iterable + } else { + const state = implicitAttrsState.get(instance) + if (state === 'in-progress' || state === 'completed') return + implicitAttrsState.set(instance, 'in-progress') + namesToInit = meta(proto, attrKey) + } + let completed = false + try { + for (const key of namesToInit) { + // Skip names that were already initialized (for example, by an earlier + // call from `@controller`, or by `attributeChangedCallback`). Mark the + // name before defining its descriptor so a re-entrant call — for + // example, one triggered by reflecting the default value back to an + // attribute — does not define it twice. + if (initialized.has(key)) continue + initialized.add(key) + const value = (>(instance))[key] + const name = mustDasherize(`${prefix}${key}`) + let descriptor: PropertyDescriptor = { configurable: true, - get(this: HTMLElement): number { - return Number(this.getAttribute(name) || 0) + get(this: HTMLElement): string { + return this.getAttribute(name) || '' }, set(this: HTMLElement, newValue: string) { - this.setAttribute(name, newValue) + this.setAttribute(name, newValue || '') } } - } else if (typeof value === 'boolean') { - descriptor = { - configurable: true, - get(this: HTMLElement): boolean { - return this.hasAttribute(name) - }, - set(this: HTMLElement, newValue: boolean) { - this.toggleAttribute(name, newValue) + if (typeof value === 'number') { + descriptor = { + configurable: true, + get(this: HTMLElement): number { + return Number(this.getAttribute(name) || 0) + }, + set(this: HTMLElement, newValue: string) { + this.setAttribute(name, newValue) + } + } + } else if (typeof value === 'boolean') { + descriptor = { + configurable: true, + get(this: HTMLElement): boolean { + return this.hasAttribute(name) + }, + set(this: HTMLElement, newValue: boolean) { + this.toggleAttribute(name, newValue) + } } } + Object.defineProperty(instance, key, descriptor) + if (key in instance && !instance.hasAttribute(name)) { + descriptor.set!.call(instance, value) + } } - Object.defineProperty(instance, key, descriptor) - if (key in instance && !instance.hasAttribute(name)) { - descriptor.set!.call(instance, value) + completed = true + } finally { + if (!explicit) { + if (completed) { + implicitAttrsState.set(instance, 'completed') + } else { + // The loop threw part-way: drop the state so a later implicit call + // retries the names that were not initialized yet. + implicitAttrsState.delete(instance) + } } } } diff --git a/test/attr.ts b/test/attr.ts index 7eab85bf..8a163bba 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -1,6 +1,6 @@ import {expect, fixture, html} from '@open-wc/testing' import {controller} from '../src/controller.js' -import {attr} from '../src/attr.js' +import {attr, initializeAttrs} from '../src/attr.js' describe('Attr', () => { { @@ -125,6 +125,63 @@ describe('Attr', () => { }) }) + describe('manual initialization', () => { + @controller + class ManualAttrTest extends HTMLElement { + @attr foo = 'hello' + bar = 'default' + baz = 'third' + + connectedCallback() { + initializeAttrs(this, ['bar']) + } + } + + it('initializes attrs passed manually in connectedCallback, even though @controller already initialized the decorated ones', async () => { + const instance = await fixture( + html`` + ) + + expect(instance).to.have.property('foo', 'from-attr') + expect(instance).to.have.property('bar', 'from-attr') + expect(instance).to.have.attribute('data-bar', 'from-attr') + }) + + it('reflects the default value of a manually initialized attr when no attribute is present', async () => { + const instance = await fixture(html``) + + expect(instance).to.have.property('foo', 'hello') + expect(instance).to.have.property('bar', 'default') + expect(instance).to.have.attribute('data-bar', 'default') + }) + + it('does not re-initialize attrs that were already initialized', async () => { + const instance = await fixture(html``) + + initializeAttrs(instance, ['bar']) + initializeAttrs(instance) + + instance.bar = 'changed' + expect(instance).to.have.attribute('data-bar', 'changed') + instance.setAttribute('data-bar', 'also-changed') + await Promise.resolve() + expect(instance).to.have.property('bar', 'also-changed') + }) + + it('still initializes additional names passed explicitly after implicit initialization completes', async () => { + const instance = await fixture(html``) + + // @controller already initialized the decorated names; the implicit + // fast path must not short-circuit this explicit call. + initializeAttrs(instance, ['baz']) + + expect(instance).to.have.property('baz', 'third') + expect(instance).to.have.attribute('data-baz', 'third') + instance.baz = 'changed' + expect(instance).to.have.attribute('data-baz', 'changed') + }) + }) + describe('naming', () => { @controller class NamingAttrTest extends HTMLElement {