Skip to content
Merged
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
89 changes: 12 additions & 77 deletions src/ability.ts
Original file line number Diff line number Diff line change
@@ -1,82 +1,17 @@
import type {CustomElement} from './custom-element.js'

export interface Ability extends CustomElement {
[attachShadowCallback]?(shadowRoot: ShadowRoot): void
[attachInternalsCallback]?(internals: ElementInternals): void
}

export interface AbilityClass {
new (): Ability
observedAttributes?: string[]
formAssociated?: boolean
}

export const attachShadowCallback = Symbol()
export const attachInternalsCallback = Symbol()

type Decorator = (Class: AbilityClass) => AbilityClass
const abilityMarkers = new WeakMap<AbilityClass, Set<Decorator>>()
export const createAbility = (decorate: Decorator) => {
return (Class: AbilityClass): AbilityClass => {
if (!abilityMarkers.has(Class)) Class = abilitable(Class)
import type {CustomElementClass} from './custom-element.js'

type Decorator = (Class: CustomElementClass) => unknown
const abilityMarkers = new WeakMap<CustomElementClass, Set<Decorator>>()
export const createAbility = <TExtend, TClass extends CustomElementClass>(
decorate: (Class: TClass) => TExtend
): ((Class: TClass) => TExtend) => {
return (Class: TClass): TExtend => {
const markers = abilityMarkers.get(Class)
if (markers?.has(decorate)) return Class
const NewClass = decorate(Class as AbilityClass)
if (markers?.has(decorate as Decorator)) return Class as unknown as TExtend
const NewClass = decorate(Class) as TExtend
const newMarkers = new Set(markers)
newMarkers.add(decorate)
abilityMarkers.set(NewClass, newMarkers)
newMarkers.add(decorate as Decorator)
abilityMarkers.set(NewClass as unknown as CustomElementClass, newMarkers)
return NewClass
}
}

const shadows = new WeakMap<Ability, ShadowRoot | undefined>()
const internals = new WeakMap<Ability, ElementInternals>()
const internalsCalled = new WeakSet()
const abilitable = (Class: AbilityClass): AbilityClass =>
class extends Class {
constructor() {
super()
const shadowRoot = this.shadowRoot
if (shadowRoot && shadowRoot !== shadows.get(this)) this[attachShadowCallback](shadowRoot)
if (!internalsCalled.has(this)) {
try {
this.attachInternals()
} catch {
// Ignore errors
}
}
}

connectedCallback() {
super.connectedCallback?.()
this.setAttribute('data-catalyst', '')
}

attachShadow(...args: [init: ShadowRootInit]): ShadowRoot {
const shadowRoot = super.attachShadow(...args)
this[attachShadowCallback](shadowRoot)
return shadowRoot
}

[attachShadowCallback](shadowRoot: ShadowRoot) {
shadows.set(this, shadowRoot)
}

attachInternals(): ElementInternals {
if (internals.has(this) && !internalsCalled.has(this)) {
internalsCalled.add(this)
return internals.get(this)!
}
const elementInternals = super.attachInternals()
this[attachInternalsCallback](elementInternals)
internals.set(this, elementInternals)
return elementInternals
}

[attachInternalsCallback](elementInternals: ElementInternals) {
const shadowRoot = elementInternals.shadowRoot
if (shadowRoot && shadowRoot !== shadows.get(this)) {
this[attachShadowCallback](shadowRoot)
}
}
}
77 changes: 77 additions & 0 deletions src/controllable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import type {CustomElementClass, CustomElement} from './custom-element.js'
import {createAbility} from './ability.js'

export interface Controllable {
[attachShadowCallback]?(shadowRoot: ShadowRoot): void
[attachInternalsCallback]?(internals: ElementInternals): void
}
export interface ControllableClass {
// TS mandates Constructors that get mixins have `...args: any[]`
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (...args: any[]): Controllable
}

export const attachShadowCallback = Symbol()
export const attachInternalsCallback = Symbol()

const shadows = new WeakMap<Controllable, ShadowRoot | undefined>()
const internals = new WeakMap<Controllable, ElementInternals>()
const internalsCalled = new WeakSet()
export const controllable = createAbility(
<T extends CustomElementClass>(Class: T): T & ControllableClass =>
class extends Class {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore TypeScript doesn't like assigning static name
static get name() {
return Class.name
}

// TS mandates Constructors that get mixins have `...args: any[]`
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(...args: any[]) {
super(...args)
const shadowRoot = this.shadowRoot
if (shadowRoot && shadowRoot !== shadows.get(this)) this[attachShadowCallback](shadowRoot)
if (!internalsCalled.has(this)) {
try {
this.attachInternals()
} catch {
// Ignore errors
}
}
}

connectedCallback() {
this.setAttribute('data-catalyst', '')
super.connectedCallback?.()
}

attachShadow(...args: [init: ShadowRootInit]): ShadowRoot {
const shadowRoot = super.attachShadow(...args)
this[attachShadowCallback](shadowRoot)
return shadowRoot
}

[attachShadowCallback](this: CustomElement & Controllable, shadowRoot: ShadowRoot) {
shadows.set(this, shadowRoot)
}

attachInternals(): ElementInternals {
if (internals.has(this) && !internalsCalled.has(this)) {
internalsCalled.add(this)
return internals.get(this)!
}
const elementInternals = super.attachInternals()
this[attachInternalsCallback](elementInternals)
internals.set(this, elementInternals)
return elementInternals
}

[attachInternalsCallback](elementInternals: ElementInternals) {
const shadowRoot = elementInternals.shadowRoot
if (shadowRoot && shadowRoot !== shadows.get(this)) {
this[attachShadowCallback](shadowRoot)
}
}
}
)
5 changes: 4 additions & 1 deletion src/custom-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ export interface CustomElement extends HTMLElement {
}

export interface CustomElementClass {
new (): CustomElement
// TS mandates Constructors that get mixins have `...args: any[]`
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (...args: any[]): CustomElement
observedAttributes?: string[]
disabledFeatures?: string[]
formAssociated?: boolean
}
193 changes: 4 additions & 189 deletions test/ability.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {expect, fixture, html} from '@open-wc/testing'
import {restore, fake} from 'sinon'
import type {CustomElement} from '../src/custom-element.js'
import {createAbility, attachShadowCallback, attachInternalsCallback} from '../src/ability.js'
import {expect, fixture, html} from '@open-wc/testing'
import {restore} from 'sinon'
import {createAbility} from '../src/ability.js'

describe('ability', () => {
let calls: string[] = []
const calls: string[] = []
const fakeable = createAbility(
Class =>
class extends Class {
Expand Down Expand Up @@ -91,189 +91,4 @@ describe('ability', () => {
instance.connectedCallback!()
expect(calls).to.eql(['fakeable connectedCallback', 'fakeable connectedCallback'])
})

describe('subclass behaviour', () => {
const CoreTest = otherfakeable(fakeable(Element))
customElements.define('core-test', CoreTest)

let instance: CustomElement & typeof CoreTest
beforeEach(async () => {
instance = await fixture(html`<core-test />`)
})

it('applies keys from delegate onto subclass upon instantiation', () => {
expect(instance).to.have.property('foo')
expect((instance as unknown as Record<string, () => void>).foo()).to.equal('foo!')
expect(instance).to.have.property('bar')
expect((instance as unknown as Record<string, () => void>).bar()).to.equal('bar!')
})

for (const method of ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback']) {
it(`delegates to other ${method}s before class ${method}`, () => {
calls = []
;(instance as unknown as Record<string, () => void>)[method]()
expect(calls).to.eql([`otherfakeable ${method}`, `fakeable ${method}`])
})
}
})

describe('ability extension behaviour', () => {
describe('attachShadowCallback', () => {
let attachShadowFake: (shadow: ShadowRoot) => void
let shadow: ShadowRoot | null
beforeEach(() => {
shadow = null
attachShadowFake = fake()
})

const declarable = createAbility(
Class =>
class extends Class {
[attachShadowCallback](...args: [ShadowRoot]) {
super[attachShadowCallback]!(...args)
return attachShadowFake.apply(this, args)
}
}
)
customElements.define(
'declarative-shadow-ability',
declarable(
class extends HTMLElement {
constructor() {
super()
// Declarative shadows run before constructor() is available, but
// abilities run after element constructor
shadow = HTMLElement.prototype.attachShadow.call(this, {mode: 'closed'})
}
}
)
)
customElements.define(
'closed-shadow-ability',
declarable(
class extends HTMLElement {
constructor() {
super()
shadow = this.attachShadow({mode: 'closed'})
}
}
)
)
customElements.define(
'connected-shadow-ability',
declarable(
class extends HTMLElement {
connectedCallback() {
shadow = this.attachShadow({mode: 'closed'})
}
}
)
)
customElements.define('manual-shadow-ability', declarable(class extends HTMLElement {}))

customElements.define(
'disallowed-shadow-ability',
declarable(
class extends HTMLElement {
static disabledFeatures = ['shadow']
}
)
)

it('is called with shadowRoot of declarative ShadowDOM', async () => {
const instance = await fixture(html`<declarative-shadow-ability></declarative-shadow-ability>`)
expect(shadow).to.exist.and.be.instanceof(ShadowRoot)
expect(attachShadowFake).to.be.calledOnce.calledOn(instance).and.calledWithExactly(shadow)
})

it('is called with shadowRoot from attachShadow call', async () => {
const instance = await fixture(html`<manual-shadow-ability></manual-shadow-ability>`)
shadow = instance.attachShadow({mode: 'closed'})
expect(shadow).to.exist.and.be.instanceof(ShadowRoot)
expect(attachShadowFake).to.be.calledOnce.calledOn(instance).and.calledWithExactly(shadow)
})

it('is called with shadowRoot from attachInternals call', async () => {
const instance = await fixture(html`<closed-shadow-ability></closed-shadow-ability>`)
expect(shadow).to.exist.and.be.instanceof(ShadowRoot)
expect(attachShadowFake).to.be.calledOnce.calledOn(instance).and.calledWithExactly(shadow)
})

it('is called with shadowRoot from connectedCallback', async () => {
const instance = await fixture(html`<connected-shadow-ability></connected-shadow-ability>`)
expect(shadow).to.exist.and.be.instanceof(ShadowRoot)
expect(attachShadowFake).to.be.calledOnce.calledOn(instance).and.calledWithExactly(shadow)
})

it('does not error if shadowdom is disabled', async () => {
await fixture(html`<disabled-shadow-ability></disabled-shadow-ability>`)
expect(attachShadowFake).to.be.have.callCount(0)
})
})

describe('attachInternalsCallback', () => {
let attachInternalsFake: (internals: ElementInternals) => void
let internals: ElementInternals | null
beforeEach(() => {
internals = null
attachInternalsFake = fake()
})

const internable = createAbility(
Class =>
class extends Class {
[attachInternalsCallback](...args: [ElementInternals]) {
super[attachInternalsCallback]!(...args)
return attachInternalsFake.apply(this, args)
}
}
)
customElements.define(
'internals-ability',
internable(
class extends HTMLElement {
constructor() {
super()
internals = this.attachInternals()
}
}
)
)
customElements.define('manual-internals-ability', internable(class extends HTMLElement {}))

customElements.define(
'disallowed-internals-ability',
internable(
class extends HTMLElement {
static disabledFeatures = ['internals']
}
)
)

it('is called on constructor', async () => {
const instance = await fixture(html`<manual-internals-ability></manual-internals-ability>`)
expect(attachInternalsFake).to.be.calledOnce.calledOn(instance)
})

it('does not prevent attachInternals being called by userland class', async () => {
const instance = await fixture(html`<internals-ability></internals-ability>`)
expect(internals).to.exist.and.be.instanceof(ElementInternals)
expect(attachInternalsFake).to.be.calledOnce.calledOn(instance).and.calledWithExactly(internals)
})

it('errors if userland calls attachInternals more than once', async () => {
const instance = await fixture<CustomElement>(html`<manual-internals-ability></manual-internals-ability>`)
internals = instance.attachInternals()
expect(internals).to.exist.and.be.instanceof(ElementInternals)
expect(attachInternalsFake).to.be.calledOnce.calledOn(instance).and.calledWithExactly(internals)

expect(() => instance.attachInternals()).to.throw(DOMException)
})

it('does not error if element internals are disabled', async () => {
await fixture(html`<disallowed-internals-ability></disallowed-internals-ability>`)
expect(attachInternalsFake).to.have.callCount(0)
})
})
})
})
Loading