forked from hotwired/stimulus
/
action_descriptor.ts
69 lines (58 loc) · 1.81 KB
/
action_descriptor.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
export type ActionDescriptorFilters = Record<string, ActionDescriptorFilter>
export type ActionDescriptorFilter = (options: ActionDescriptorFilterOptions) => boolean
type ActionDescriptorFilterOptions = {
name: string
value: boolean
event: Event
element: Element
}
export const defaultActionDescriptorFilters: ActionDescriptorFilters = {
stop({ event, value }) {
if (value) event.stopPropagation()
return true
},
prevent({ event, value }) {
if (value) event.preventDefault()
return true
},
self({ event, value, element }) {
if (value) {
return element === event.target
} else {
return true
}
},
}
export interface ActionDescriptor {
eventTargetName: string
eventOptions: AddEventListenerOptions
eventName: string
identifier: string
methodName: string
keyFilter: string
}
// capture nos.: 1 1 2 2 3 3 4 4 5 5 6 6
const descriptorPattern = /^(?:(.+?)(?:\.(.+?))?(?:@(.+?))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/
export function parseActionDescriptorString(descriptorString: string): Partial<ActionDescriptor> {
const source = descriptorString.trim()
const matches = source.match(descriptorPattern) || []
let eventName = matches[1]
let keyFilter = matches[2]
if (keyFilter && !["keydown", "keyup", "keypress"].includes(eventName)) {
eventName += `.${keyFilter}`
keyFilter = ""
}
return {
eventTargetName: matches[3],
eventName,
eventOptions: matches[6] ? parseEventOptions(matches[6]) : {},
identifier: matches[4],
methodName: matches[5],
keyFilter,
}
}
function parseEventOptions(eventOptions: string): AddEventListenerOptions {
return eventOptions
.split(":")
.reduce((options, token) => Object.assign(options, { [token.replace(/^!/, "")]: !/^!/.test(token) }), {})
}