Skip to content

feat: declare DOM event data and filters as JS snippets - #26845

Merged
mcollovati merged 16 commits into
mainfrom
25658-event-data-snippets-simplified
Nov 9, 2026
Merged

mcollovati merged 16 commits into
mainfrom
25658-event-data-snippets-simplified

Conversation

@mcollovati

@mcollovati mcollovati commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related to #25658
Related to #25661

new feature · flow-server, flow-client · apps that use a Content Security Policy without unsafe-eval and need event data or event filters

Background — event data and filters. A DOM listener can send extra values with the event and can ignore events that do not match a filter. Both are JavaScript expressions written as strings, which the browser compiles with new Function. A Content Security Policy without unsafe-eval blocks this, so the event is lost.

Event data and filters can now be declared in a @JsDefinition interface, like other JS snippets. The build adds them to the bundle, so the browser compiles nothing. Flow's own always-true filter, preventDefault() and stopPropagation() also stop compiling strings.

@JsExpression("return event.key === $0;")
DomEventFilter isKey(String key);

element.addEventListener("keydown", e -> submit())
        .setFilterExpression(FILTERS.isKey("Enter"));

Risks:

  • ⚠️ Public API: new DomEventData<T> and DomEventFilter, DomListenerRegistration.addEventData(DomEventData) and setFilterExpression(DomEventFilter), DomEvent.getEventData(DomEventData).
  • ⚠️ Behaviour change: preventDefault() and stopPropagation() are no longer reported as string JavaScript in CSP mode, because the browser no longer compiles them.
  • ❓ Open question: the declared filter is setFilterExpression(DomEventFilter), not a setFilter overload as the "overload, not a new name" rule in CONVENTIONS.md asks. An overload made setFilter(null) ambiguous, which broke existing code that clears a filter.
  • ❓ Open question: this is an alternative to feat: declare DOM event data and filters as JS snippets #25661, with the same API and a simpler ElementListenerMap. One of the two should be closed.
  • ✅ No breaking change, security, memory, serialization, threading, performance or migration concerns.

Context. The first commit is #25661 squashed. The second keeps the string expressions as keys, as on main, so the server does not translate event data keys back.

  • Added DomEventData and DomEventFilter, declared with @JsExpression and called with event and element.
  • Declared snippets are keyed by @ and a hash of their function and captures.
    • Snippets with only plain captures are shared through the constant pool; snippets that capture an element are sent for that element only, with the node id it has when the settings are sent.
  • The client runs 1, event.preventDefault() and event.stopPropagation() without compiling them.
  • Added unit tests for the server and the client, EventDataCapturesIT, and a wire protocol section in the guidelines.

String event data and filters keep the expression as their key again, as
before the snippets were added. So the browser sends their values under
the expression, and the server does not translate the keys back.

A declared snippet is keyed by "@" and a short hash of its function and
captures, computed once when the snippet is created. Its settings are an
object with the function id, the debounce settings, the side effect and
the captures. A snippet whose captures are all plain values is shared
through the constant pool. A snippet that captures, for example, an
element is sent for that element only.

Related to #25658
Flow sends three event expressions of its own: the always-true filter
"1", which it adds for a debounce without a filter and when filtered and
unfiltered listeners share an event type, and "event.preventDefault()"
and "event.stopPropagation()". The browser compiled them from strings,
so under a Content Security Policy without unsafe-eval the event was
lost, and for "1" the server did not even log a warning. The client now
runs the three directly, and the server no longer reports
preventDefault() and stopPropagation() as string JavaScript.

Related to #25658
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Memory footprint

Compared with the base commit 30455f2.

Scenario Metric Base Head Change
Empty UI Heap retained per UI 7,064 B 7,064 B no change
Empty UI Serialized session with one UI 21,263 B 21,353 B $\color{red}\textbf{+90 B}$ (+0.4%)
UI with 200 component rows Heap retained per UI 690,656 B 690,656 B no change
UI with 200 component rows Serialized session with one UI 437,880 B 438,370 B $\color{red}\textbf{+490 B}$ (+0.1%)
UI with 200 form rows added in the latest round trip Heap retained per UI 1,862,736 B 1,862,728 B −8 B (ignored)
UI with 200 form rows added in the latest round trip Serialized session with one UI 1,394,389 B 1,395,079 B $\color{red}\textbf{+690 B}$ (+0.0%)
UI with 200 form rows Heap retained per UI 1,817,776 B 1,817,776 B no change
UI with 200 form rows Serialized session with one UI 1,349,418 B 1,350,108 B $\color{red}\textbf{+690 B}$ (+0.1%)
Scenarios
  • Empty UI (empty-ui): A UI with no components, which is the cost of every UI.
  • UI with 200 component rows (ui-with-200-component-rows): A UI with 200 rows, each a div with a class name and a style, holding a span, an input with a value change listener and a button with a click listener.
  • UI with 200 form rows added in the latest round trip (ui-with-200-form-rows-added-in-latest-round-trip): The UI with 200 form rows, with the rows added in the latest round trip, as when navigating to a view, so that the response kept for resending holds all of them.
  • UI with 200 form rows (ui-with-200-form-rows): A UI with 200 rows, each a layout with a theme and several styles, holding a text field and a combo box bound to a bean with a binder and a button with a click listener. The fields are web components with several properties and a synchronized value, and the combo box has client callable methods, as Vaadin components that load data do.

Measured by UIMemoryFootprintTest. Differences under 10 B are ignored.

@github-actions github-actions Bot added the +0.1.0 label Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 1 677 files  + 2   1 765 suites  +2   2h 8m 55s ⏱️ - 7m 45s
13 321 tests +46  13 253 ✅ +46  68 💤 ±0  0 ❌ ±0 
13 955 runs  +46  13 887 ✅ +46  68 💤 ±0  0 ❌ ±0 

Results for commit 15a6f65. ± Comparison against base commit 30455f2.

♻️ This comment has been updated with latest results.

@mcollovati

mcollovati commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Type of change

  • Feature

How to test

  1. Open flow-tests/test-default/src/main/java/com/vaadin/flow/test/dom/EventDataCapturesView.java at /event-data-captures.
  2. Click Report event data.
  3. The text captured label appears below the buttons. The value comes from a declared DomEventData.
  4. Click Filtered by capture with the left mouse button.
  5. The text primary appears. The listener with the same declared filter, captured for the right button, does not run.

To check the CSP side, run the repro/event-data-snippets branch of https://github.com/mcollovati/skeleton-starter-flow-spring with this Flow branch installed, and with a policy that has no unsafe-eval:

  1. Open /event-data-side-effects.
  2. Press the buttons of cases S1 (preventDefault()), S4 (debounce(400) without a filter) and S5 (filtered and unfiltered listeners on one button).
  3. All three reach the server, and the browser reports no CSP violation. Only S6, which uses a string filter on purpose, is blocked.
What changed in detail

The first commit is #25661 at 2f424de599, squashed. The second and third commits are the changes on top of it.

  • String event data and filters keep the expression as their key, as on main. The browser sends their values under the expression, so EventRpcHandler is the same as on main.
  • A declared snippet has the key @ followed by a hash of its function id and its captures. The key is computed once, when the snippet is created.
    • If a capture is not a plain value, for example an element, the hash uses a random id, so two such snippets never share a key.
  • The settings of a declared snippet are an object: f (function id), d (debounce settings), s (side effect, optional) and c (captures, optional).
    • A snippet with only plain captures is shared through the constant pool.
    • A snippet that captures an element or a component is sent for its element only, through ParameterizedConstantPoolKey. Its captures are encoded each time the settings are sent, so the node id is correct also after a refresh with @PreserveOnRefresh.
  • In ElementListenerMap, a sealed Entry type with the records ExpressionEntry and SnippetEntry describes each event data and filter. The PR's map that translated event data names back to expressions (eventDataNames) is removed.
  • The client runs the filter 1, event.preventDefault() and event.stopPropagation() from a small map of built-in functions, before it would compile a string. A declared filter combined with preventDefault() or stopPropagation() uses the s key and no string.
API changes

New:

  • DomEventData<T>: event data declared in a @JsDefinition interface.
  • DomEventFilter: an event filter declared in a @JsDefinition interface.
  • DomListenerRegistration.addEventData(DomEventData<?>) and DomListenerRegistration.setFilterExpression(DomEventFilter).
  • DomEvent.getEventData(DomEventData<T>): reads the value of declared event data.

Internal, but public:

  • ConstantPoolKey.calculateHash(String).
  • ParameterizedConstantPoolKey.
  • JsCall.createSnippetKey() and JsCall.hasOnlyPlainSnippetCaptures().
Test coverage
  • ElementListenersTest: settings and keys of declared snippets, pooled and per-element settings, side effects, debounce, and the node id of a captured element when it is attached later or moved to another UI.
  • SimpleElementBindingStrategyEventDataTests.ts: the client runs declared snippets with their captures and side effects. A without unsafe-eval group replaces Function with a function that throws, and checks that 1, preventDefault() and stopPropagation() still work. These three tests fail without the last commit.
  • CspModeTest: preventDefault(), stopPropagation() and debounce(300) do not throw in strict mode.
  • EventDataCapturesIT: declared event data and two filters with different captures in a browser.
  • Run locally: all flow-server tests, all client tests, and the checks of the reproducer in a browser, also with a policy without unsafe-eval.

@mcollovati
mcollovati marked this pull request as ready for review November 4, 2026 14:39
@mcollovati mcollovati added the csp label Nov 4, 2026
@totally-not-ai

totally-not-ai Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Compared this with #25661, and I'd go ahead with this one: the public API is the same, string expressions keep their format from main, EventRpcHandler doesn't need to change, and ElementListenerMap ends up much smaller. A few possible cleanups and improvements:

  • Constant pool growth with plain captures: a snippet whose captures are all plain values is pooled under a key that includes those values. So something like setFilter(FILTERS.isRow(rowId)) on every row adds one pool entry per distinct value, and the pool is never cleaned up. This is no worse than string filters built by concatenation on main, but it would help to mention it in the DomEventData/DomEventFilter Javadoc and next to the "Nothing is ever evicted" constraint in wire-protocol.md.
  • New public helpers: ConstantPoolKey.calculateHash(String), ParameterizedConstantPoolKey, JsCall.createSnippetKey() and JsCall.hasOnlyPlainSnippetCaptures() are public but only used internally. Could some of them be package-private, or be moved behind an internal API?
  • Snippets that capture elements: their key is built from a random value, so two snippets created separately never share settings, even when they capture the same element. That's correct, but a sentence in the Javadoc would help users who create one per element.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed the changes — left 2 comments.

Finding
⚠️ The new setFilter overload makes setFilter(null) ambiguous, so existing callers stop compiling
📐 The existing setFilter/addEventData overloads are not updated to point at the new declared-JS variants

Both setFilter versions now take null to clear the filter, so a nullable
DomEventFilter variable can be passed. A plain setFilter(null) is
ambiguous between the two, and the Javadoc of setFilter(String) says to
cast it. The setFilter(String) Javadoc also points to the declared
version for a Content Security Policy without unsafe-eval.

Related to #25658
Declared event data and filters with plain captures are pooled, so each
distinct captured value adds a constant pool entry that is never
removed. The Javadoc and the wire protocol guide now say so. The string
versions of addEventData now point to addEventData(DomEventData).

Related to #25658
@mcollovati

mcollovati commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author
  • Constant pool growth: done in 165c4dc. The DomEventData and DomEventFilter Javadoc now says that each distinct plain captured value adds an entry that is never removed, and suggests reading a value that differs per element from the element instead. wire-protocol.md says the same in the section on declared event data and next to "Nothing is ever evicted". I did not change the code: sending captures per element would stop the growth, but then a shared filter like isKey("Enter") on many fields would be sent once per field instead of once.
  • New public helpers: they are public because they are called from other packages: JsCall uses ConstantPoolKey.calculateHash, ElementListenerMap uses ParameterizedConstantPoolKey, and DomEventData/DomEventFilter call createSnippetKey(). The first two are in com.vaadin.flow.internal, and the JsCall methods are marked "For internal use only", like encodeSnippetCaptures(). The key also has to be created once and kept on the snippet, because for non-plain captures it contains a random value. So I left them as they are.
  • Snippets that capture elements: the DomEventData Javadoc already says that with non-plain captures the value must be read with the same instance that was added to the listener. For DomEventFilter the key makes no difference you can see, because a filter has no value to read back. These settings are also sent for one element only, so the random key does not make the constant pool grow.

A right click fires no click event, so the listener filtered on the
secondary button could never run. The listeners now use mousedown, and
the test checks a left and a right click.

Related to #25658
A second setFilter overload made setFilter(null) ambiguous, which broke
existing code that clears a filter.

Related to #25658
Explain that event data from the same method with different arguments
sends separate values, and that reading the value with another instance
gives null unless all arguments are plain values.

Related to #25658
A snippet key with plain captures is computed once, when the snippet is
created, but the captures are encoded each time they are sent. A
captured AtomicInteger or AtomicLong could change in between, so two
snippets could share a key while sending different values. Only the
boxed primitive types, BigInteger and BigDecimal now count as plain.

Related to #25658
Use the same wording for the shared function and the plain values in
both classes, and explain that filters from the same method still check
their own arguments.

Related to #25658
getEventData(DomEventData) now says when another instance can read the
value and when it gets null. The method Javadoc of addEventData and
setFilterExpression no longer describes how the browser shares one
function between snippets; the class Javadoc covers that.

Related to #25658
@cla-assistant

cla-assistant Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@cla-assistant

cla-assistant Bot commented Nov 5, 2026

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@mcollovati
mcollovati requested a review from heruan November 5, 2026 13:28
…pets-simplified

# Conflicts:
#	flow-server/src/test/java/com/vaadin/flow/js/JsDefinitionProxyTest.java
@mshabarov mshabarov moved this to 🔎Iteration reviews in Vaadin Flow | Hilla | Kits ongoing work Nov 9, 2026

@heruan heruan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Three notes from a closer read, nothing blocking the API. One defect on the server side of declared filters, one question on captured elements, one small suggestion on the client.

The browser sends the value that a filter returned, which does not have
to be a boolean, and also sends the values of filters that did not pass
when another filter of the event passed. JsonNode.booleanValue() throws
for anything but a boolean in Jackson 3, so such a value failed the
event for every listener of its type on the element.
The missing function threw inside the DOM event handler, so the event
was lost for every listener of its type on the element.
@sonarqubecloud

sonarqubecloud Bot commented Nov 9, 2026

Copy link
Copy Markdown

@mcollovati
mcollovati added this pull request to the merge queue Nov 9, 2026
Merged via the queue into main with commit ba9b4d5 Nov 9, 2026
53 checks passed
@mcollovati
mcollovati deleted the 25658-event-data-snippets-simplified branch November 9, 2026 13:56
@github-project-automation github-project-automation Bot moved this from 🔎Iteration reviews to Done in Vaadin Flow | Hilla | Kits ongoing work Nov 9, 2026
vaadin-bot added a commit to vaadin/docs that referenced this pull request Nov 9, 2026
Document DomEventData and DomEventFilter as a Content Security Policy
friendly alternative to the string-based addEventData() and setFilter()
expressions, on the Element Events page.

Documents vaadin/flow#26845 (`15a6f65954b851b1d3e1d81dfb6507a6b2c17185`).
@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Pull request created: #6606

Generated by Documentation Bot · agent · 154.8 AIC · ⊞ 11.7K

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Documentation Bot: Draft documentation pull request for this change: vaadin/docs#6606

Files updated:

  • articles/flow/component-internals/element-api/event-listener.adoc

It was written from the state of this pull request as you see it now. Please review it and mark it ready for review.

Generated by Documentation Bot for #26845 · agent · 154.8 AIC · ⊞ 11.7K · ◷

Artur- pushed a commit to vaadin/testbench that referenced this pull request Nov 10, 2026
#2393)

## Summary
With the current Flow `main`, `fireShortcut()` in UI unit tests triggers
every shortcut listener, whatever key and modifiers are passed. Six
`ShortcutsTest` cases fail ("not triggered on different key press /
modifiers").

## What changed
- vaadin/flow#26845 changed how the server decides whether a DOM event
filter passed. Flow used to call `booleanValue()` on the value sent for
the filter. It now checks whether that value is truthy
(`JavaScriptSemantics.isTrueish`).
- The mock event data built by `fireShortcut()` returned itself for a
filter key. That object node is always truthy, so every shortcut filter
passed.
- It now returns the match result as a `BooleanNode`. This works with
both the old check and the new one, so it is safe with the currently
published Flow snapshot too.

## Test summary
- Covered by the existing shortcut tests: they fail against Flow `main`
without this change and pass with it.
- All unit tests of `vaadin-testbench-unit`, `-junit5` and `-junit6`
pass against Flow `main` built locally.

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
@vaadin-bot

Copy link
Copy Markdown
Collaborator

This ticket/PR has been released with Vaadin 25.4.0-alpha6.

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

Projects

Development

Successfully merging this pull request may close these issues.

4 participants