Skip to content

refactor attr into attrable #251

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 24, 2022
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
{
"path": "lib/index.js",
"import": "{controller, attr, target, targets}",
"limit": "2.5kb"
"limit": "2.6kb"
},
{
"path": "lib/abilities.js",
Expand Down
96 changes: 0 additions & 96 deletions src/attr.ts

This file was deleted.

114 changes: 114 additions & 0 deletions src/attrable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import type {CustomElementClass} from './custom-element.js'
import type {ControllableClass} from './controllable.js'
import {controllable} from './controllable.js'
import {dasherize, mustDasherize} from './dasherize.js'
import {createMark} from './mark.js'
import {createAbility} from './ability.js'

const attrChangedCallback = Symbol()

export interface Attrable {
[key: PropertyKey]: unknown
[attrChangedCallback](changed: Map<PropertyKey, unknown>): void
}

export interface AttrableClass {
new (): Attrable
}

const Identity = (v: unknown) => v
let setFromMutation = false
const attrs = new WeakMap<Element, Map<string, PropertyKey>>()

const handleMutations = (mutations: MutationRecord[]) => {
for (const mutation of mutations) {
if (mutation.type === 'attributes') {
const name = mutation.attributeName!
const el = mutation.target as Element & {[key: PropertyKey]: unknown}
const key = attrs.get(el)?.get(name)
if (key) {
setFromMutation = true
el[key] = el.getAttribute(name)
setFromMutation = false
}
}
}
}
const observer = new MutationObserver(handleMutations)

const [attr, getAttr, initializeAttrs] = createMark<Element & Attrable>(
({name}) => mustDasherize(name, '@attr'),
(instance: Element & Attrable, {name, kind, access}) => {
let cast: typeof Identity | typeof Boolean | typeof Number | typeof String = Identity
let initialValue: unknown
if (access.get) {
initialValue = access.get.call(instance)
} else if ('value' in access && kind !== 'method') {
initialValue = access.value
}
let value = initialValue
const attributeName = dasherize(name)
const setCallback = (kind === 'method' ? access.value : access.set) || Identity
const getCallback = access.get || (() => value)
if (!attrs.get(instance)) attrs.set(instance, new Map())
attrs.get(instance)!.set(attributeName, name)
if (typeof value === 'number') {
cast = Number
} else if (typeof value === 'boolean') {
cast = Boolean
} else if (typeof value === 'string') {
cast = String
}
const queue = new Map()
const requestAttrChanged = async (newValue: unknown) => {
queue.set(name, newValue)
if (queue.size > 1) return
await Promise.resolve()
const changed = new Map(queue)
queue.clear()
instance[attrChangedCallback](changed)
}
return {
get() {
const has = instance.hasAttribute(attributeName)
if (has) {
return cast === Boolean ? has : cast(instance.getAttribute(attributeName))
}
return cast(getCallback.call(instance))
},
set(newValue: unknown) {
const isInitial = newValue === null
if (isInitial) newValue = initialValue
const same = Object.is(value, newValue)
value = newValue
setCallback.call(instance, value)
if (setFromMutation || same || isInitial) return
requestAttrChanged(newValue)
}
}
}
)

export {attr, getAttr, attrChangedCallback}
export const attrable = createAbility(
<T extends CustomElementClass>(Class: T): T & ControllableClass & AttrableClass =>
class extends controllable(Class) {
[key: PropertyKey]: unknown
constructor() {
super()
initializeAttrs(this)
observer.observe(this, {attributeFilter: Array.from(getAttr(this)).map(dasherize)})
}

[attrChangedCallback](changed: Map<PropertyKey, unknown>) {
if (!this.isConnected) return
for (const [name, value] of changed) {
if (typeof value === 'boolean') {
this.toggleAttribute(dasherize(name), value)
} else {
this.setAttribute(dasherize(name), String(value))
}
}
}
}
)
4 changes: 3 additions & 1 deletion src/controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import {CatalystDelegate} from './core.js'
import type {CustomElementClass} from './custom-element.js'
import {attrable} from './attrable.js'
import {actionable} from './actionable.js'

/**
* Controller is a decorator to be used over a class that extends HTMLElement.
* It will automatically `register()` the component in the customElement
* registry, as well as ensuring `bind(this)` is called on `connectedCallback`,
* wrapping the classes `connectedCallback` method if needed.
*/
export function controller(classObject: CustomElementClass): void {
new CatalystDelegate(actionable(classObject))
new CatalystDelegate(actionable(attrable(classObject)))
}
4 changes: 0 additions & 4 deletions src/core.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {register} from './register.js'
import {defineObservedAttributes, initializeAttrs} from './attr.js'
import type {CustomElementClass} from './custom-element.js'

const symbol = Symbol.for('catalyst')
Expand Down Expand Up @@ -40,7 +39,6 @@ export class CatalystDelegate {
}
})

defineObservedAttributes(classObject)
register(classObject)
}

Expand All @@ -51,7 +49,6 @@ export class CatalystDelegate {
connectedCallback(instance: HTMLElement, connectedCallback: () => void) {
instance.toggleAttribute('data-catalyst', true)
customElements.upgrade(instance)
initializeAttrs(instance)
connectedCallback?.call(instance)
}

Expand All @@ -66,7 +63,6 @@ export class CatalystDelegate {
newValue: string | null,
attributeChangedCallback: (...args: unknown[]) => void
) {
initializeAttrs(instance)
if (name !== 'data-catalyst' && attributeChangedCallback) {
attributeChangedCallback.call(instance, name, oldValue, newValue)
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ export {register} from './register.js'
export {findTarget, findTargets} from './findtarget.js'
export {target, targets} from './target.js'
export {controller} from './controller.js'
export {attr, initializeAttrs, defineObservedAttributes} from './attr.js'
export {attr, getAttr, attrable, attrChangedCallback} from './attrable.js'
Loading