-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathactionable.ts
More file actions
58 lines (54 loc) · 2.18 KB
/
actionable.ts
File metadata and controls
58 lines (54 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import type {CustomElementClass, CustomElement} from './custom-element.js'
import type {ControllableClass} from './controllable.js'
import {registerTag, observeElementForTags, parseElementTags} from './tag-observer.js'
import {controllable, attachShadowCallback} from './controllable.js'
import {createAbility} from './ability.js'
const parseActionAttribute = (tag: string): [tagName: string, event: string, method: string] => {
const eventSep = tag.lastIndexOf(':')
const methodSep = Math.max(0, tag.lastIndexOf('#')) || tag.length
return [tag.slice(eventSep + 1, methodSep), tag.slice(0, eventSep), tag.slice(methodSep + 1) || 'handleEvent']
}
registerTag(
'data-action',
parseActionAttribute,
(el: Element, controller: Element | ShadowRoot, tag: string, event: string) => {
el.addEventListener(event, handleEvent)
}
)
const actionables = new WeakSet<CustomElement>()
// Bind a single function to all events to avoid anonymous closure performance penalty.
function handleEvent(event: Event) {
const el = event.currentTarget as Element
for (const [tag, type, method] of parseElementTags(el, 'data-action', parseActionAttribute)) {
if (event.type === type) {
type EventDispatcher = CustomElement & Record<string, (ev: Event) => unknown>
const controller = el.closest<EventDispatcher>(tag)!
if (actionables.has(controller) && typeof controller[method] === 'function') {
controller[method](event)
}
const root = el.getRootNode()
if (root instanceof ShadowRoot) {
const shadowController = root.host as EventDispatcher
if (shadowController.matches(tag) && actionables.has(shadowController)) {
if (typeof shadowController[method] === 'function') {
shadowController[method](event)
}
}
}
}
}
}
export const actionable = createAbility(
<T extends CustomElementClass>(Class: T): T & ControllableClass =>
class extends controllable(Class) {
constructor() {
super()
actionables.add(this)
observeElementForTags(this)
}
[attachShadowCallback](root: ShadowRoot) {
super[attachShadowCallback]?.(root)
observeElementForTags(root)
}
}
)