Skip to content

feat: Add optional value to event options#895

Open
tchiadeu wants to merge 2 commits into
hotwired:mainfrom
tchiadeu:action_options_custom_value
Open

feat: Add optional value to event options#895
tchiadeu wants to merge 2 commits into
hotwired:mainfrom
tchiadeu:action_options_custom_value

Conversation

@tchiadeu

Copy link
Copy Markdown

Allow action options to capture a string value with :name(value)

Summary

Action options currently only express booleans: :name yields true and :!name yields false. This PR adds a parenthesized syntax, :name(value), that captures a string value and passes it to the option's registerActionOptions callback. This makes options parameterizable (e.g. a throttle delay) without having to smuggle the value through a separate data attribute.

Motivation

Custom action options are a natural place to configure event handling behavior, but the boolean-only value made it impossible to express something like "throttle to 500ms" inline in the descriptor. Users had to fall back to reading a data attribute inside the callback.

Usage

<div
  data-controller="gallery"
  data-action="scroll->gallery#layout:throttled(500)"
></div>
let lastInvokedAt = 0;

application.registerActionOption("throttled", ({ value }) => {
  const wait = Number(value);
  const elapsed = Date.now() - lastInvokedAt;

  if (elapsed > wait) {
    lastInvokedAt = Date.now();
    return true;
  } else {
    return false;
  }
});

Captured values are always strings, so convert them as needed (e.g. Number(value)).

What changed

  • parseEventOptions (src/core/action_descriptor.ts) now detects a name(value) token via regex and assigns the captured string; tokens without parentheses keep the existing boolean behavior (nametrue, !namefalse).
  • Widened ActionDescriptorFilterOptions.value from boolean to boolean | string.
  • Documented the syntax and updated the callback-argument table in docs/reference/actions.md.

Backward compatibility

Fully backward compatible. Boolean options are unchanged; only the new parenthesized form produces a string. Unknown string options are ignored by addEventListener just like unknown boolean options.

Tests

Added event_options_tests.ts coverage for: a parenthesized value reaching the callback as a string, a string value mixed with a boolean option in the same descriptor, and a value driving whether the action runs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant