Skip to content

Commit

Permalink
Add registerDefaultEventName
Browse files Browse the repository at this point in the history
This allows configure default events for arbitrary elements.

Closes hotwired#660
  • Loading branch information
grncdr committed Feb 17, 2023
1 parent f7bfc35 commit 51cfd65
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/core/action.ts
Expand Up @@ -96,6 +96,14 @@ const defaultEventNames: { [tagName: string]: (element: Element) => string } = {
textarea: () => "input",
}

export function registerDefaultEventName(tagName: string, eventName: string | ((element: Element) => string)) {
if (typeof eventName === 'string') {
defaultEventNames[tagName] = () => eventName
} else {
defaultEventNames[tagName] = eventName
}
}

export function getDefaultEventNameForElement(element: Element): string | undefined {
const tagName = element.tagName.toLowerCase()
if (tagName in defaultEventNames) {
Expand Down
1 change: 1 addition & 0 deletions src/core/index.ts
@@ -1,3 +1,4 @@
export { registerDefaultEventName } from "./action"
export { ActionEvent } from "./action_event"
export { Application } from "./application"
export { Context } from "./context"
Expand Down
10 changes: 10 additions & 0 deletions src/tests/modules/core/action_tests.ts
@@ -1,5 +1,9 @@
import { registerDefaultEventName } from "../../../core"
import { LogControllerTestCase } from "../../cases/log_controller_test_case"

// must be done before the fixture element is constructed
registerDefaultEventName('some-element', 'click')

export default class ActionTests extends LogControllerTestCase {
identifier = "c"
fixtureHTML = `
Expand All @@ -14,13 +18,19 @@ export default class ActionTests extends LogControllerTestCase {
<svg id="svgRoot" data-controller="c" data-action="click->c#log">
<circle id="svgChild" data-action="mousedown->c#log" cx="5" cy="5" r="5">
</svg>
<some-element data-controller="c" data-action="c#log">Hm</some-element>
`

async "test default event"() {
await this.triggerEvent("button", "click")
this.assertActions({ name: "log", eventType: "click" })
}

async "test default event on custom element"() {
await this.triggerEvent("some-element", "click")
this.assertActions({ name: "log", eventType: "click" })
}

async "test bubbling events"() {
await this.triggerEvent("span", "click")
this.assertActions({ eventType: "click", currentTarget: this.findElement("button") })
Expand Down

0 comments on commit 51cfd65

Please sign in to comment.