From 9931fa4ce3b552a55a3fd39f5c51bf61f566bcee Mon Sep 17 00:00:00 2001 From: Sean Doyle Date: Tue, 6 Dec 2022 21:00:55 -0500 Subject: [PATCH] Action Descriptor Syntax: Support Outlet listeners The original [idea][] for this change was outlined in a comment on [hotwired/stimulus#576]. The problem --- Prior to this commit, any Outlet-powered references would need to manage event listeners from within the Stimulus Controller JavaScript. For example, consider the following HTML: ```html This dialog is managed through a disclosure button powered by an Outlet.
``` Clicking the `button[type="button"]` opens the `dialog` element by calling its [HTMLDialogElement.showModal()][] method. Consider the following `element` and `disclosure` controller implementations: ```js // element_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { showModal() { this.element.showModal() } } // disclosure_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { static outlets = ["element"] elementOutletConnected(controller, element) { this.element.setAttribute("aria-controls", element.id) this.element.setAttribute("aria-expanded", element.open) element.addEventListener("close", this.collapse) } elementOutletDisconnected() { element.removeEventListener("close", this.collapse) this.element.removeAttribute("aria-controls") this.element.removeAttribute("aria-expanded") } collapse = () => { this.element.setAttribute("aria-expanded", false) this.element.focus() } expand() { for (const elementOutlet of this.elementOutlets) { elementOutlet.showModal() this.element.setAttribute("aria-expanded", elementOutlet.element.open) } } } ``` Note the mirrored calls to add and remove [close][] event listeners. Whenever the `dialog` element closes, it'll dispatch a `close` event, which the `disclosure` controller will want to respond to. Attaching and removing event listeners whenever an element connects or disconnects is one of Stimulus's core capabilities, and declaring event listeners as part of `[data-action]` is idiomatic. In spite of those facts, the `disclosure` controller is responsible for the tedium of managing its own event listeners. The proposal --- To push those declarations out of the JavaScript and back into the HTML, this commit extends the Action Descriptor syntax to support declaring actions with `@`-prefixed controller identifiers, in the same way that `window` and `document` are special-cased. With that support, the HTML changes: ```diff This dialog is managed through a disclosure button powered by an Outlet.
``` And our `disclosure` controller has fewer responsibilities, and doesn't need to special-case the `collapse` function's binding: ```diff elementOutletConnected(controller, element) { this.element.setAttribute("aria-controls", element.id) this.element.setAttribute("aria-expanded", element.open) - element.addEventListener("close", this.collapse) } elementOutletDisconnected() { - element.removeEventListener("close", this.collapse) this.element.removeAttribute("aria-controls") this.element.removeAttribute("aria-expanded") } - collapse = () => { + collapse() { this.element.setAttribute("aria-expanded", false) this.element.focus() } ``` Risks --- Changing the action descriptor syntax has more long-term maintenance risks that other implementation changes. If we "spend" the syntax on this type of support, we're pretty stuck with it. Similarly, existing support for `window` and `document` as special symbols means that we'd need to make special considerations (or warnings) to support applications with `window`- and `document`-identified controllers. [hotwired/stimulus#576]: https://github.com/hotwired/stimulus/pull/576 [idea]: https://github.com/hotwired/stimulus/pull/576#issuecomment-1336214087 [HTMLDialogElement.showModal()]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal [close]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/close_event --- docs/reference/actions.md | 25 +++++++++ docs/reference/outlets.md | 25 +++++++++ examples/controllers/disclosure_controller.js | 27 ++++++++++ examples/controllers/element_controller.js | 7 +++ examples/index.js | 6 +++ examples/public/examples.css | 12 +++++ examples/public/main.css | 1 + examples/server.js | 1 + examples/views/disclosures.ejs | 16 ++++++ src/core/action.ts | 34 ++++++++---- src/core/action_descriptor.ts | 24 ++------- src/core/binding.ts | 13 ++++- src/core/binding_observer.ts | 2 +- src/core/dispatcher.ts | 36 ++++++++----- src/tests/controllers/outlet_controller.ts | 9 ++++ src/tests/modules/core/outlet_tests.ts | 54 +++++++++++++++++-- 16 files changed, 240 insertions(+), 52 deletions(-) create mode 100644 examples/controllers/disclosure_controller.js create mode 100644 examples/controllers/element_controller.js create mode 100644 examples/views/disclosures.ejs diff --git a/docs/reference/actions.md b/docs/reference/actions.md index 5c7e909b..34a65860 100644 --- a/docs/reference/actions.md +++ b/docs/reference/actions.md @@ -127,6 +127,31 @@ The list of supported modifier keys is shown below. | `meta` | Command key on MacOS | | `shift` | | +### Outlet Events + +Sometimes a controller needs to listen for events dispatched on elements made available through its [Outlets](./outlets). + +You can append an [outlet controller's identifier](./outlets#attributes-and-names) prefixed by `@` (along with any filter modifier) in an action descriptor to install the event listener on that outlet's element, as in the following example: + + + +```html + + + + A modal dialog + +``` + +In this example, the ` + + + A modal dialog + +``` + +In this example, the ` + + + + + +<%- include("layout/tail") %> diff --git a/src/core/action.ts b/src/core/action.ts index e009399b..db219fac 100644 --- a/src/core/action.ts +++ b/src/core/action.ts @@ -1,6 +1,6 @@ -import { ActionDescriptor, parseActionDescriptorString, stringifyEventTarget } from "./action_descriptor" +import { ActionDescriptor, parseActionDescriptorString } from "./action_descriptor" import { Token } from "../mutation-observers" -import { Schema } from "./schema" +import { Context } from "./context" import { camelize } from "./string_helpers" import { hasProperty } from "./utils" @@ -9,28 +9,28 @@ const allModifiers = ["meta", "ctrl", "alt", "shift"] export class Action { readonly element: Element readonly index: number - readonly eventTarget: EventTarget + private readonly eventTargetName: string | undefined readonly eventName: string readonly eventOptions: AddEventListenerOptions readonly identifier: string readonly methodName: string readonly keyFilter: string - readonly schema: Schema + readonly context: Context - static forToken(token: Token, schema: Schema) { - return new this(token.element, token.index, parseActionDescriptorString(token.content), schema) + static forToken(token: Token, context: Context) { + return new this(token.element, token.index, parseActionDescriptorString(token.content), context) } - constructor(element: Element, index: number, descriptor: Partial, schema: Schema) { + constructor(element: Element, index: number, descriptor: Partial, context: Context) { this.element = element this.index = index - this.eventTarget = descriptor.eventTarget || element + this.eventTargetName = descriptor.eventTargetName this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name") this.eventOptions = descriptor.eventOptions || {} this.identifier = descriptor.identifier || error("missing identifier") this.methodName = descriptor.methodName || error("missing method name") this.keyFilter = descriptor.keyFilter || "" - this.schema = schema + this.context = context } toString() { @@ -89,8 +89,20 @@ export class Action { return params } - private get eventTargetName() { - return stringifyEventTarget(this.eventTarget) + get schema() { + return this.context.schema + } + + get eventTargets(): EventTarget[] { + if (this.eventTargetName == "window") { + return [window] + } else if (this.eventTargetName == "document") { + return [document] + } else if (typeof this.eventTargetName == "string") { + return this.context.controller.outlets.findAll(this.eventTargetName) + } else { + return [this.element] + } } private get keyMappings() { diff --git a/src/core/action_descriptor.ts b/src/core/action_descriptor.ts index 35a4a211..53e76674 100644 --- a/src/core/action_descriptor.ts +++ b/src/core/action_descriptor.ts @@ -33,7 +33,7 @@ export const defaultActionDescriptorFilters: ActionDescriptorFilters = { } export interface ActionDescriptor { - eventTarget: EventTarget + eventTargetName: string eventOptions: AddEventListenerOptions eventName: string identifier: string @@ -41,8 +41,8 @@ export interface ActionDescriptor { keyFilter: string } -// capture nos.: 1 1 2 2 3 3 4 4 5 5 6 6 7 7 -const descriptorPattern = /^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/ +// capture nos.: 1 1 2 2 3 3 4 4 5 5 6 6 7 7 +const descriptorPattern = /^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(.+?))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/ export function parseActionDescriptorString(descriptorString: string): Partial { const source = descriptorString.trim() @@ -56,7 +56,7 @@ export function parseActionDescriptorString(descriptorString: string): Partial Object.assign(options, { [token.replace(/^!/, "")]: !/^!/.test(token) }), {}) } - -export function stringifyEventTarget(eventTarget: EventTarget) { - if (eventTarget == window) { - return "window" - } else if (eventTarget == document) { - return "document" - } -} diff --git a/src/core/binding.ts b/src/core/binding.ts index 33958667..cc7cfe50 100644 --- a/src/core/binding.ts +++ b/src/core/binding.ts @@ -16,8 +16,8 @@ export class Binding { return this.action.index } - get eventTarget(): EventTarget { - return this.action.eventTarget + get eventTargets(): EventTarget[] { + return this.action.eventTargets } get eventOptions(): AddEventListenerOptions { @@ -85,6 +85,7 @@ export class Binding { private willBeInvokedByEvent(event: Event): boolean { const eventTarget = event.target + const [actionEventTarget] = this.action.eventTargets if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) { return false @@ -98,6 +99,14 @@ export class Binding { return true } else if (eventTarget instanceof Element && this.element.contains(eventTarget)) { return this.scope.containsElement(eventTarget) + } else if (eventTarget instanceof Element && this.action.eventTargets.length == 0) { + return false + } else if ( + eventTarget instanceof Element && + actionEventTarget instanceof Element && + actionEventTarget != this.action.element + ) { + return this.action.eventTargets.includes(eventTarget) } else { return this.scope.containsElement(this.action.element) } diff --git a/src/core/binding_observer.ts b/src/core/binding_observer.ts index 62cc8355..7f2a97c5 100644 --- a/src/core/binding_observer.ts +++ b/src/core/binding_observer.ts @@ -79,7 +79,7 @@ export class BindingObserver implements ValueListObserverDelegate { // Value observer delegate parseValueForToken(token: Token): Action | undefined { - const action = Action.forToken(token, this.schema) + const action = Action.forToken(token, this.context) if (action.identifier == this.identifier) { return action } diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts index 04a3bb27..43d6dfac 100644 --- a/src/core/dispatcher.ts +++ b/src/core/dispatcher.ts @@ -38,11 +38,15 @@ export class Dispatcher implements BindingObserverDelegate { // Binding observer delegate bindingConnected(binding: Binding) { - this.fetchEventListenerForBinding(binding).bindingConnected(binding) + for (const eventListener of this.fetchEventListenersForBinding(binding)) { + eventListener.bindingConnected(binding) + } } bindingDisconnected(binding: Binding, clearEventListeners = false) { - this.fetchEventListenerForBinding(binding).bindingDisconnected(binding) + for (const eventListener of this.fetchEventListenersForBinding(binding)) { + eventListener.bindingDisconnected(binding) + } if (clearEventListeners) this.clearEventListenersForBinding(binding) } @@ -53,25 +57,29 @@ export class Dispatcher implements BindingObserverDelegate { } private clearEventListenersForBinding(binding: Binding) { - const eventListener = this.fetchEventListenerForBinding(binding) - if (!eventListener.hasBindings()) { - eventListener.disconnect() - this.removeMappedEventListenerFor(binding) + for (const eventListener of this.fetchEventListenersForBinding(binding)) { + if (!eventListener.hasBindings()) { + eventListener.disconnect() + this.removeMappedEventListenerFor(binding) + } } } private removeMappedEventListenerFor(binding: Binding) { - const { eventTarget, eventName, eventOptions } = binding - const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget) - const cacheKey = this.cacheKey(eventName, eventOptions) + const { eventTargets, eventName, eventOptions } = binding + + for (const eventTarget of eventTargets) { + const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget) + const cacheKey = this.cacheKey(eventName, eventOptions) - eventListenerMap.delete(cacheKey) - if (eventListenerMap.size == 0) this.eventListenerMaps.delete(eventTarget) + eventListenerMap.delete(cacheKey) + if (eventListenerMap.size == 0) this.eventListenerMaps.delete(eventTarget) + } } - private fetchEventListenerForBinding(binding: Binding): EventListener { - const { eventTarget, eventName, eventOptions } = binding - return this.fetchEventListener(eventTarget, eventName, eventOptions) + private fetchEventListenersForBinding(binding: Binding): EventListener[] { + const { eventTargets, eventName, eventOptions } = binding + return eventTargets.map((eventTarget) => this.fetchEventListener(eventTarget, eventName, eventOptions)) } private fetchEventListener( diff --git a/src/tests/controllers/outlet_controller.ts b/src/tests/controllers/outlet_controller.ts index b382f80c..69e10949 100644 --- a/src/tests/controllers/outlet_controller.ts +++ b/src/tests/controllers/outlet_controller.ts @@ -1,5 +1,7 @@ import { Controller } from "../../core/controller" +type OutletClickEvents = { event: Event; identifier: string } + class BaseOutletController extends Controller { static outlets = ["alpha"] @@ -26,6 +28,7 @@ export class OutletController extends BaseOutletController { namespacedEpsilonOutletDisconnectedCallCount: Number, } + outletClickEvents: OutletClickEvents[] = [] betaOutlet!: Controller | null betaOutlets!: Controller[] betaOutletElement!: Element | null @@ -91,4 +94,10 @@ export class OutletController extends BaseOutletController { if (this.hasDisconnectedClass) element.classList.add(this.disconnectedClass) this.namespacedEpsilonOutletDisconnectedCallCountValue++ } + + outletClicked(event: Event) { + const { identifier } = this + + this.outletClickEvents.push({ identifier, event }) + } } diff --git a/src/tests/modules/core/outlet_tests.ts b/src/tests/modules/core/outlet_tests.ts index fb87ba12..824c9d1d 100644 --- a/src/tests/modules/core/outlet_tests.ts +++ b/src/tests/modules/core/outlet_tests.ts @@ -13,8 +13,9 @@ export default class OutletTests extends ControllerTestCase(OutletController) {
-
-
+
-
+ -
+
@@ -366,4 +367,49 @@ export default class OutletTests extends ControllerTestCase(OutletController) { `expected "${alpha2.className}" to contain "disconnected"` ) } + + async "test action descriptor with @-prefixed does not attach event listener to host element"() { + await this.triggerEvent(this.element, "click") + + this.assert.equal(this.outletClickEvents.length, 0) + } + + async "test action descriptor with @-prefixed outlet-name attaches event listeners when the outlet element connects"() { + const epsilon1 = this.findElement("#epsilon1") + const epsilon2 = this.findElement("#epsilon2") + + await this.setAttribute(this.element, `data-${this.identifier}-namespaced--epsilon-outlet`, "#epsilon2") + await this.triggerEvent(epsilon1, "click") + await this.triggerEvent(epsilon2, "click") + + const [clickEpsilon2, ...rest] = this.outletClickEvents + this.assert.equal(clickEpsilon2.identifier, this.identifier) + this.assert.equal(clickEpsilon2.event.type, "click") + this.assert.equal(clickEpsilon2.event.target, epsilon2) + this.assert.equal(rest.length, 0) + } + + async "test action descriptor with @-prefixed outlet-name removes event listeners when the outlet element disconnects"() { + await this.removeAttribute(this.element, `data-${this.identifier}-namespaced--epsilon-outlet`) + await this.triggerEvent("#epsilon1", "click") + await this.triggerEvent("#epsilon2", "click") + + this.assert.equal(this.outletClickEvents.length, 0) + } + + async "test action descriptor with @-prefixed outlet-name removes event listeners when the action descriptor is removed"() { + await this.removeAttribute(this.element, "data-action") + await this.triggerEvent("#epsilon1", "click") + await this.triggerEvent("#epsilon2", "click") + + this.assert.equal(this.outletClickEvents.length, 0) + } + + get outletClickEvents() { + return this.controller.outletClickEvents + } + + get element() { + return this.controller.element + } }