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

Show how to set keyboard shortcuts for dialog actions #42

Merged
merged 2 commits into from
Aug 28, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.vaadin.recipes.recipe.dialogwithkeyboardshortcuts;

import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.ShortcutRegistration;
import com.vaadin.flow.component.Shortcuts;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.recipes.recipe.Metadata;
import com.vaadin.recipes.recipe.Recipe;

@Route("dialog-with-keyboard-shortcuts")
@Metadata(howdoI = "Show a dialog where Enter submits and Esc closes")
public class DialogWithKeyboardShortcuts extends Recipe {
public DialogWithKeyboardShortcuts() {
add(new Button("Show dialog", event -> showDialog()));
}

private void showDialog() {
Button okButton = new Button("OK");
Button cancelButton = new Button("Cancel");
HorizontalLayout buttons = new HorizontalLayout(okButton, cancelButton);

Dialog dialog = new Dialog(new Span("Dialog content goes here"), buttons);

dialog.setCloseOnEsc(true);
cancelButton.addClickListener(event -> dialog.close());

okButton.addClickListener(event -> {
Notification.show("Accepted");
dialog.close();
});
okButton.addClickShortcut(Key.ENTER);

// Prevent click shortcut of the OK button from also triggering when
// another button is focused
ShortcutRegistration shortcutRegistration = Shortcuts.addShortcutListener(buttons, () -> {
}, Key.ENTER).listenOn(buttons);
shortcutRegistration.setEventPropagationAllowed(false);
shortcutRegistration.setBrowserDefaultAllowed(true);

dialog.open();
}
}