From 9292e594b9111316efeedc48e8c2e83f97d5f457 Mon Sep 17 00:00:00 2001 From: Ultroncn <82553854+Ultroncn@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:21:35 +0000 Subject: [PATCH 1/2] fix(initializeAttrs): allow manually initializing additional attrs after @controller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #207 initializeAttrs guarded re-initialization with a per-element flag, so once @controller had initialized the @attr-decorated names, a later call with additional names — for example, from the element's own connectedCallback, the documented pattern for attrs without the @attr decorator — was silently ignored and those properties were never bound to their data-* attributes. Track initialized names per element instead of a single flag: a later call now initializes just the names that have not been initialized yet, while names that were already initialized are left alone (which keeps the re-initialization guard that attributeChangedCallback relies on). Names are marked before their descriptor is defined so a re-entrant call cannot define the same name twice. --- src/attr.ts | 21 ++++++++++++++++++--- test/attr.ts | 45 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 2d7472fc..9bf4aa65 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -34,15 +34,30 @@ 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. */ -const initialized = new WeakSet() +const initializedAttrs = 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) { + // 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 = { diff --git a/test/attr.ts b/test/attr.ts index 7eab85bf..0a921dee 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,49 @@ describe('Attr', () => { }) }) + describe('manual initialization', () => { + @controller + class ManualAttrTest extends HTMLElement { + @attr foo = 'hello' + bar = 'default' + + 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') + }) + }) + describe('naming', () => { @controller class NamingAttrTest extends HTMLElement { From e3e488e18878ebde05c30a5ac9653ac65a24937a Mon Sep 17 00:00:00 2001 From: Ultroncn <82553854+Ultroncn@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:26:41 +0000 Subject: [PATCH 2/2] fix(initializeAttrs): short-circuit implicit init once in progress or done Reflecting a missing decorated default back to an attribute synchronously invokes attributeChangedCallback, which calls initializeAttrs again with no names. Each re-entrant call rescanned every decorated name, making initialization quadratic with nested calls, and every later observed mutation rescanned them too. Track implicit initialization per element (in-progress/completed) and short-circuit implicit calls on either state, so only the outermost call scans the decorated names. Explicit calls are never short-circuited and still initialize the names they are given. If the loop throws part-way, the state is dropped so a later implicit call retries the remaining names. --- src/attr.ts | 103 +++++++++++++++++++++++++++++++++------------------ test/attr.ts | 14 +++++++ 2 files changed, 81 insertions(+), 36 deletions(-) diff --git a/src/attr.ts b/src/attr.ts index 9bf4aa65..1236d811 100644 --- a/src/attr.ts +++ b/src/attr.ts @@ -39,8 +39,16 @@ export function attr(proto: Record, key: K): voi * 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 initializedAttrs = new WeakMap>() +const implicitAttrsState = new WeakMap() export function initializeAttrs(instance: HTMLElement, names?: Iterable): void { let initialized = initializedAttrs.get(instance) if (!initialized) { @@ -49,50 +57,73 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable) } const proto = Object.getPrototypeOf(instance) const prefix = proto?.constructor?.attrPrefix ?? 'data-' - if (!names) names = meta(proto, attrKey) - for (const key of names) { - // 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): 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 0a921dee..8a163bba 100644 --- a/test/attr.ts +++ b/test/attr.ts @@ -130,6 +130,7 @@ describe('Attr', () => { class ManualAttrTest extends HTMLElement { @attr foo = 'hello' bar = 'default' + baz = 'third' connectedCallback() { initializeAttrs(this, ['bar']) @@ -166,6 +167,19 @@ describe('Attr', () => { 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', () => {