Skip to content
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

Move defaultEventNames into Schema #662

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 22 additions & 1 deletion docs/reference/actions.md
Expand Up @@ -52,7 +52,7 @@ Stimulus lets you shorten the action descriptors for some common element/event p
<button data-action="gallery#next">…</button>
```

The full set of these shorthand pairs is as follows:
The built-in set of these shorthand pairs is as follows:

Element | Default Event
----------------- | -------------
Expand All @@ -65,6 +65,27 @@ input type=submit | click
select | change
textarea | input

This built-in set can be extended with the `Application.registerDefaultEventNames` method, for example to associate default event names with custom elements.

<meta data-controller="callout" data-callout-text-value="custom-button">

```js
import { Application } from "@hotwired/stimulus"

const app = new Application()
app.registerDefaultEventNames({ "custom-button": "click" })
app.start()
```

The above allows you to omit the event name on custom buttons:

<meta data-controller="callout" data-callout-text-value="gallery#next">

```html
<custom-button data-action="gallery#next">…</custom-button>
```

Custom default event names must be registered before calling `start()`, or the application will not be able to add the correct event listeners.

## KeyboardEvent Filter

Expand Down
23 changes: 8 additions & 15 deletions src/core/action.ts
Expand Up @@ -23,7 +23,7 @@ export class Action {
this.element = element
this.index = index
this.eventTarget = descriptor.eventTarget || element
this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name")
this.eventName = descriptor.eventName || getDefaultEventNameForElement(element, schema) || error("missing event name")
this.eventOptions = descriptor.eventOptions || {}
this.identifier = descriptor.identifier || error("missing identifier")
this.methodName = descriptor.methodName || error("missing method name")
Expand Down Expand Up @@ -86,20 +86,13 @@ export class Action {
}
}

const defaultEventNames: { [tagName: string]: (element: Element) => string } = {
a: () => "click",
button: () => "click",
form: () => "submit",
details: () => "toggle",
input: (e) => (e.getAttribute("type") == "submit" ? "click" : "input"),
select: () => "change",
textarea: () => "input",
}

export function getDefaultEventNameForElement(element: Element): string | undefined {
const tagName = element.tagName.toLowerCase()
if (tagName in defaultEventNames) {
return defaultEventNames[tagName](element)
function getDefaultEventNameForElement(element: Element, schema: Schema): string | undefined {
let eventName = schema.defaultEventNames[element.localName]
if (typeof eventName === 'function') {
return eventName(element)
}
if (typeof eventName === 'string') {
return eventName
}
}

Expand Down
14 changes: 13 additions & 1 deletion src/core/application.ts
Expand Up @@ -22,7 +22,7 @@ export class Application implements ErrorHandler {
return application
}

constructor(element: Element = document.documentElement, schema: Schema = defaultSchema) {
constructor(element: Element = document.documentElement, schema: Schema = cloneDefaultSchema()) {
this.element = element
this.schema = schema
this.dispatcher = new Dispatcher(this)
Expand Down Expand Up @@ -53,6 +53,10 @@ export class Application implements ErrorHandler {
this.actionDescriptorFilters[name] = filter
}

registerDefaultEventNames(extensions: Schema['defaultEventNames']) {
Object.assign(this.schema.defaultEventNames, extensions)
}

load(...definitions: Definition[]): void
load(definitions: Definition[]): void
load(head: Definition | Definition[], ...rest: Definition[]) {
Expand Down Expand Up @@ -116,3 +120,11 @@ function domReady() {
}
})
}

function cloneDefaultSchema(): Schema {
return {
...defaultSchema,
keyMappings: { ...defaultSchema.keyMappings },
defaultEventNames: { ...defaultSchema.defaultEventNames }
}
}
10 changes: 10 additions & 0 deletions src/core/schema.ts
Expand Up @@ -5,6 +5,7 @@ export interface Schema {
targetAttributeForScope(identifier: string): string
outletAttributeForScope(identifier: string, outlet: string): string
keyMappings: { [key: string]: string }
defaultEventNames: { [tagName: string]: string | ((element: Element) => string) }
}

export const defaultSchema: Schema = {
Expand All @@ -29,6 +30,15 @@ export const defaultSchema: Schema = {
// [0-9]
...objectFromEntries("0123456789".split("").map((n) => [n, n])),
},
defaultEventNames: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
defaultEventNames: {
defaultEventMappings: {

Since we use the term mappings already, might be nice to align with that naming?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Obsoleted by 2ddac5f

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ended up dropping 2ddac5f so this is relevant again. I'm open to renaming it.

a: "click",
button: "click",
form: "submit",
details: "toggle",
input: (element) => (element.getAttribute("type") == "submit" ? "click" : "input"),
select: "change",
textarea: "input",
}
}

function objectFromEntries(array: [string, any][]): object {
Expand Down
20 changes: 20 additions & 0 deletions src/tests/modules/core/action_custom_default_event_tests.ts
@@ -0,0 +1,20 @@
import { TestApplication } from "../../cases/application_test_case"
import { LogControllerTestCase } from "../../cases/log_controller_test_case"
import { Schema, defaultSchema } from "../../../core/schema"
import { Application } from "../../../core/application"

export default class ActionKeyboardFilterTests extends LogControllerTestCase {
schema: Schema = {
...defaultSchema,
defaultEventNames: { ...defaultSchema.defaultEventNames, "some-element": () => "click" },
}
application: Application = new TestApplication(this.fixtureElement, this.schema)

identifier = "c"
fixtureHTML = `<some-element data-controller="c" data-action="c#log"></some-element>`

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