Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 78 additions & 32 deletions src/attr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,50 +34,96 @@ export function attr<K extends string>(proto: Record<K, attrValue>, 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<Element>()
const initializedAttrs = new WeakMap<Element, Set<string>>()
const implicitAttrsState = new WeakMap<Element, 'in-progress' | 'completed'>()
export function initializeAttrs(instance: HTMLElement, names?: Iterable<string>): 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 = (<Record<PropertyKey, unknown>>(<unknown>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<string>
if (explicit) {
namesToInit = names as Iterable<string>
} 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 = (<Record<PropertyKey, unknown>>(<unknown>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)
}
}
}
}
Expand Down
59 changes: 58 additions & 1 deletion test/attr.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
{
Expand Down Expand Up @@ -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<ManualAttrTest>(
html`<manual-attr-test data-foo="from-attr" data-bar="from-attr" />`
)

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<ManualAttrTest>(html`<manual-attr-test />`)

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<ManualAttrTest>(html`<manual-attr-test />`)

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<ManualAttrTest>(html`<manual-attr-test />`)

// @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 {
Expand Down