-
Notifications
You must be signed in to change notification settings - Fork 424
/
action.ts
53 lines (45 loc) · 1.8 KB
/
action.ts
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
import { ActionDescriptor, parseDescriptorString, stringifyEventTarget } from "./action_descriptor"
import { Token } from "@stimulus/mutation-observers"
export class Action {
readonly element: Element
readonly index: number
readonly eventTarget: EventTarget
readonly eventName: string
readonly identifier: string
readonly methodName: string
static forToken(token: Token) {
return new this(token.element, token.index, parseDescriptorString(token.content))
}
constructor(element: Element, index: number, descriptor: Partial<ActionDescriptor>) {
this.element = element
this.index = index
this.eventTarget = descriptor.eventTarget || element
this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name")
this.identifier = descriptor.identifier || error("missing identifier")
this.methodName = descriptor.methodName || error("missing method name")
}
toString() {
const eventNameSuffix = this.eventTargetName ? `@${this.eventTargetName}` : ""
return `${this.eventName}${eventNameSuffix}->${this.identifier}#${this.methodName}`
}
private get eventTargetName() {
return stringifyEventTarget(this.eventTarget)
}
}
const defaultEventNames: { [tagName: string]: (element: Element) => string } = {
"a": e => "click",
"button": e => "click",
"form": e => "submit",
"input": e => e.getAttribute("type") == "submit" ? "click" : "change",
"select": e => "change",
"textarea": e => "change"
}
export function getDefaultEventNameForElement(element: Element): string | undefined {
const tagName = element.tagName.toLowerCase()
if (tagName in defaultEventNames) {
return defaultEventNames[tagName](element)
}
}
function error(message: string): never {
throw new Error(message)
}