Skip to content

Commit 7d07f08

Browse files
totally-not-ai[bot]claudesissbruecker
authored
feat: add Button.setDownloadHandler to start a download on click (#10289)
## Summary A `Button` can now start a file download when it is clicked. You give it a `DownloadHandler`, and the server makes the file only when the browser asks for it. You no longer need to wrap the button in an anchor or write your own click-and-download code. Closes #7203 ## What changed - Added `Button.setDownloadHandler(DownloadHandler)` and `Button.getDownloadHandler()`. - Inside, the button uses `Download.onClick(component, handler)`. Setting a new handler removes the old one. Passing `null` turns the download off. - Click listeners still run as usual when a download handler is set. - The file is served only while the button is attached, visible and enabled. One exception: a button with disable-on-click disables itself before the browser requests the file, so the file is also served while the button is disabled by that click. Once the application sets the enabled state explicitly (e.g. `setEnabled(false)`) or a parent is disabled, the request is refused again. Use `handler.allowDisabled()` to serve the file regardless of the enabled state. - This change is backward-compatible: it only adds new methods. ## Use case An admin view has an "Export" button that creates a CSV report when the user clicks it. The report should only be built when the user actually downloads it. The button should also stay disabled until the server responds, so users cannot start many exports at once. ```java Button export = new Button("Export CSV"); export.setDisableOnClick(DisableOnClickMode.UNTIL_RESPONSE); export.setDownloadHandler(DownloadHandler.fromInputStream(event -> { byte[] csv = reportService.createCsv(); return new DownloadResponse(new ByteArrayInputStream(csv), "report.csv", "text/csv", csv.length); })); ``` ## API Changes 2 classes affected, 3 methods added ### com.vaadin.flow.component.button.Button ```java // Added public DownloadHandler getDownloadHandler() // null if clicking does not start a download public void setDownloadHandler(DownloadHandler downloadHandler) // null turns the download off ``` ### com.vaadin.flow.component.shared.internal.DisableOnClickController (internal) ```java // Added public boolean isDisabledByClick() // true while disabled by the click, until the enabled state is set explicitly or restored ``` ## Test summary **Button download handler:** - Old handler removed when a new one is set - No handler registered after setting `null` - Clicking downloads the handler's file in the browser (HTTP 200, expected content) - With disable on click, the file is served while the button is disabled by the click - When a click listener disables the button explicitly, or disables its parent, the download is refused (HTTP 403) - The controller reports disabled-by-click after a click, and clears it when the enabled state is set explicitly or restored after the round trip --------- Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Sascha Ißbrücker <sissbruecker@vaadin.com>
1 parent e115118 commit 7d07f08

6 files changed

Lines changed: 461 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright 2000-2026 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.flow.component.button.tests;
17+
18+
import java.io.ByteArrayInputStream;
19+
import java.nio.charset.StandardCharsets;
20+
21+
import com.vaadin.flow.component.button.Button;
22+
import com.vaadin.flow.component.html.Div;
23+
import com.vaadin.flow.router.Route;
24+
import com.vaadin.flow.server.streams.DownloadHandler;
25+
import com.vaadin.flow.server.streams.DownloadResponse;
26+
27+
@Route("vaadin-button/download-handler")
28+
public class DownloadHandlerButtonPage extends Div {
29+
static final String DOWNLOAD_BODY = "button-download-body";
30+
31+
public DownloadHandlerButtonPage() {
32+
Button button = new Button("Download");
33+
button.setId("download-button");
34+
button.setDownloadHandler(createDownloadHandler());
35+
36+
Button disableOnClick = new Button("Download, disable on click");
37+
disableOnClick.setId("download-disable-on-click-button");
38+
disableOnClick.setDisableOnClick(true);
39+
disableOnClick.setDownloadHandler(createDownloadHandler());
40+
41+
add(button, disableOnClick);
42+
}
43+
44+
private static DownloadHandler createDownloadHandler() {
45+
return DownloadHandler.fromInputStream(event -> new DownloadResponse(
46+
new ByteArrayInputStream(
47+
DOWNLOAD_BODY.getBytes(StandardCharsets.UTF_8)),
48+
"button.txt", "text/plain", DOWNLOAD_BODY.length()));
49+
}
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* Copyright 2000-2026 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.flow.component.button.tests;
17+
18+
import org.junit.Assert;
19+
import org.junit.Before;
20+
import org.junit.Test;
21+
22+
import com.vaadin.flow.component.button.testbench.ButtonElement;
23+
import com.vaadin.flow.testutil.TestPath;
24+
import com.vaadin.tests.AbstractComponentIT;
25+
26+
@TestPath("vaadin-button/download-handler")
27+
public class DownloadHandlerButtonIT extends AbstractComponentIT {
28+
29+
@Before
30+
public void init() {
31+
open();
32+
// Replace the client-side download helper with a shim that only
33+
// records the URL, so no save dialog opens
34+
executeScript("""
35+
window.__downloadUrl = null;
36+
window.Vaadin.Flow.download.start = url => {
37+
window.__downloadUrl = url;
38+
};
39+
""");
40+
}
41+
42+
@Test
43+
public void clickDownloadButton_downloadsFileFromHandler() {
44+
Assert.assertEquals("200|" + DownloadHandlerButtonPage.DOWNLOAD_BODY,
45+
clickAndDownload("download-button"));
46+
}
47+
48+
@Test
49+
public void clickDownloadButtonDisabledOnClick_downloadsFileWhileDisabled() {
50+
Assert.assertEquals("200|" + DownloadHandlerButtonPage.DOWNLOAD_BODY,
51+
clickAndDownload("download-disable-on-click-button"));
52+
Assert.assertFalse($(ButtonElement.class)
53+
.id("download-disable-on-click-button").isEnabled());
54+
}
55+
56+
/**
57+
* Clicks the button and fetches the URL that the click starts a download
58+
* from, returning the response status and body separated by {@code |}.
59+
*/
60+
private String clickAndDownload(String buttonId) {
61+
$(ButtonElement.class).id(buttonId).click();
62+
Assert.assertNotNull("Click did not start a download",
63+
executeScript("return window.__downloadUrl;"));
64+
65+
// click() waits until the server has handled the click, so a button
66+
// that disables itself on click is already disabled on the server
67+
// when the file is requested. In a real browser the download request
68+
// and the click event are sent independently, in no fixed order.
69+
executeScript("""
70+
window.__download = null;
71+
fetch(window.__downloadUrl).then(r => r.text().then(t => {
72+
window.__download = r.status + '|' + t;
73+
}));
74+
""");
75+
return (String) waitUntil(
76+
driver -> executeScript("return window.__download;"));
77+
}
78+
}

‎vaadin-button-flow-parent/vaadin-button-flow/src/main/java/com/vaadin/flow/component/button/Button.java‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package com.vaadin.flow.component.button;
1717

18+
import java.io.IOException;
1819
import java.util.Objects;
1920

2021
import com.vaadin.experimental.Feature;
@@ -38,6 +39,7 @@
3839
import com.vaadin.flow.component.UI;
3940
import com.vaadin.flow.component.dependency.JsModule;
4041
import com.vaadin.flow.component.dependency.NpmPackage;
42+
import com.vaadin.flow.component.download.Download;
4143
import com.vaadin.flow.component.html.Image;
4244
import com.vaadin.flow.component.shared.DisableOnClickMode;
4345
import com.vaadin.flow.component.shared.HasPrefix;
@@ -49,6 +51,11 @@
4951
import com.vaadin.flow.dom.Element;
5052
import com.vaadin.flow.dom.SignalBinding;
5153
import com.vaadin.flow.internal.nodefeature.SignalBindingFeature;
54+
import com.vaadin.flow.server.VaadinRequest;
55+
import com.vaadin.flow.server.VaadinResponse;
56+
import com.vaadin.flow.server.VaadinSession;
57+
import com.vaadin.flow.server.streams.DownloadEvent;
58+
import com.vaadin.flow.server.streams.DownloadHandler;
5259
import com.vaadin.flow.shared.Registration;
5360
import com.vaadin.flow.signals.Signal;
5461

@@ -72,6 +79,8 @@ public class Button extends Component
7279
private boolean iconAfterText;
7380
private final DisableOnClickController<Button> disableOnClickController = new DisableOnClickController<>(
7481
this);
82+
private DownloadHandler downloadHandler;
83+
private Registration downloadRegistration;
7584

7685
private final SignalPropertySupport<String> textSupport = SignalPropertySupport
7786
.create(this, this::textChangeHandler);
@@ -370,6 +379,112 @@ public void clickInClient() {
370379
getElement().callJsFunction("click");
371380
}
372381

382+
/**
383+
* Gets the handler that produces the file downloaded when the button is
384+
* clicked.
385+
*
386+
* @return the download handler, or {@code null} if clicking the button does
387+
* not start a download
388+
* @see #setDownloadHandler(DownloadHandler)
389+
* @since 25.4
390+
*/
391+
public DownloadHandler getDownloadHandler() {
392+
return downloadHandler;
393+
}
394+
395+
/**
396+
* Sets a handler that produces a file to download when the button is
397+
* clicked. The download starts in the browser as part of the click, and
398+
* click listeners still run as usual. Setting a new handler replaces the
399+
* previous one, and {@code null} stops the button from starting a download.
400+
* <p>
401+
* The handler runs only when the browser requests the file, once per click,
402+
* so you can create the content, file name and response headers at that
403+
* point. If the handler fails, the browser reports a failed download
404+
* instead of saving an empty file. Use the transfer callbacks of the
405+
* handler, for example
406+
* {@link com.vaadin.flow.server.streams.TransferProgressAwareHandler#whenComplete(com.vaadin.flow.function.SerializableConsumer)
407+
* whenComplete}, to react on the server when the transfer has finished or
408+
* failed.
409+
* <p>
410+
* The file is only served while the button is attached, visible and
411+
* enabled, so hiding or removing the button in a click listener makes the
412+
* download fail. The exception is a button with
413+
* {@link #setDisableOnClick(boolean) disable on click}: it disables itself
414+
* before the browser requests the file, so the file is also served while
415+
* the button is disabled by the click. Once the enabled state is set
416+
* explicitly, for example with {@code setEnabled(false)}, or a parent is
417+
* disabled, the file is no longer served while the button is disabled. To
418+
* serve the file regardless of the enabled state, pass
419+
* {@link DownloadHandler#allowDisabled() handler.allowDisabled()}.
420+
*
421+
* <pre>{@code
422+
* Button export = new Button("Export");
423+
* export.setDisableOnClick(DisableOnClickMode.UNTIL_RESPONSE);
424+
* export.setDownloadHandler(
425+
* DownloadHandler.fromInputStream(event -> createReport()));
426+
* }</pre>
427+
*
428+
* @param downloadHandler
429+
* the handler that produces the file, or {@code null} to not
430+
* start a download on click
431+
* @since 25.4
432+
*/
433+
public void setDownloadHandler(DownloadHandler downloadHandler) {
434+
if (downloadRegistration != null) {
435+
downloadRegistration.remove();
436+
downloadRegistration = null;
437+
}
438+
this.downloadHandler = downloadHandler;
439+
if (downloadHandler != null) {
440+
downloadRegistration = Download.onClick(this,
441+
allowDisabledByClick(downloadHandler));
442+
}
443+
}
444+
445+
/**
446+
* Wraps the handler so that it is also served while the button is disabled
447+
* by disable on click, which happens before the browser requests the file.
448+
* A button disabled explicitly, or inside a disabled parent, still refuses
449+
* the request unless the handler itself allows it.
450+
*/
451+
private DownloadHandler allowDisabledByClick(DownloadHandler delegate) {
452+
return new DownloadHandler() {
453+
@Override
454+
public void handleRequest(VaadinRequest request,
455+
VaadinResponse response, VaadinSession session,
456+
Element owner) throws IOException {
457+
delegate.handleRequest(request, response, session, owner);
458+
}
459+
460+
@Override
461+
public void handleDownloadRequest(DownloadEvent event)
462+
throws IOException {
463+
delegate.handleDownloadRequest(event);
464+
}
465+
466+
@Override
467+
public String getUrlPostfix() {
468+
return delegate.getUrlPostfix();
469+
}
470+
471+
@Override
472+
public boolean isAllowInert() {
473+
return delegate.isAllowInert();
474+
}
475+
476+
@Override
477+
public DisabledUpdateMode getDisabledUpdateMode() {
478+
Element parent = Button.this.getElement().getParent();
479+
if (disableOnClickController.isDisabledByClick()
480+
&& (parent == null || parent.isEnabled())) {
481+
return DisabledUpdateMode.ALWAYS;
482+
}
483+
return delegate.getDisabledUpdateMode();
484+
}
485+
};
486+
}
487+
373488
/**
374489
* Adds the given components as children of this component.
375490
* <p>

0 commit comments

Comments
 (0)