Skip to content

Commit

Permalink
chore: Update to Java 17 and refactor some code to use Java 17 features
Browse files Browse the repository at this point in the history
refactor: Extract Form and CustomChart classes to improve code organization
fix: Small adjustments to accessibility in Admin view
  • Loading branch information
TatuJLund committed Dec 15, 2024
1 parent e3abfa0 commit 7727136
Show file tree
Hide file tree
Showing 21 changed files with 185 additions and 203 deletions.
4 changes: 2 additions & 2 deletions vaadincreate-backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
<packaging>jar</packaging>

<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -39,7 +38,7 @@ private ProductDataServiceImpl() {
var categories = MockDataGenerator.createCategories();
categories.forEach(cat -> productDao.updateCategory(cat));
var savedCategories = productDao.getAllCategories().stream()
.collect(Collectors.toList());
.toList();
var products = MockDataGenerator.createProducts(savedCategories);
products.forEach(prod -> productDao.updateProduct(prod));
logger.info("Generated mock product data");
Expand Down
4 changes: 2 additions & 2 deletions vaadincreate-ui/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>

<licenses>
Expand Down
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.vaadin.tatu.vaadincreate;

import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.tatu.vaadincreate.auth.AccessControl;
Expand Down Expand Up @@ -97,7 +99,8 @@ private void handleValueChange(ValueChangeEvent<String> e) {
adminsNote.setCaption(
Utils.formatDate(mes.getDateStamp(), getLocale()));
adminsNote.setValue(mes.getMessage());
getEventBus().post(mes);
getEventBus().post(
new MessageEvent(mes.getMessage(), mes.getDateStamp()));
logger.info("Admin message updated");
}
}
Expand Down Expand Up @@ -158,17 +161,16 @@ public void enter(ViewChangeEvent event) {

@Override
public void eventFired(Object event) {
if (event instanceof Message) {
if (event instanceof MessageEvent message) {
Utils.access(ui, () -> {
if (adminsNoteField.isVisible()) {
adminsNoteField.setVisible(false);
adminsNote.setVisible(true);
editButton.setVisible(true);
}
Message mes = (Message) event;
adminsNote.setCaption(
Utils.formatDate(mes.getDateStamp(), getLocale()));
adminsNote.setValue(mes.getMessage());
Utils.formatDate(message.timeStamp(), getLocale()));
adminsNote.setValue(message.message());
});
}
}
Expand All @@ -193,5 +195,8 @@ private AppDataService getService() {
return VaadinCreateUI.get().getAppService();
}

public record MessageEvent(String message, LocalDateTime timeStamp) {
}

private static Logger logger = LoggerFactory.getLogger(AboutView.class);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.vaadin.tatu.vaadincreate.AboutView.MessageEvent;
import org.vaadin.tatu.vaadincreate.admin.AdminView;
import org.vaadin.tatu.vaadincreate.auth.AccessControl;
import org.vaadin.tatu.vaadincreate.auth.BasicAccessControl;
import org.vaadin.tatu.vaadincreate.auth.CurrentUser;
import org.vaadin.tatu.vaadincreate.backend.AppDataService;
import org.vaadin.tatu.vaadincreate.backend.ProductDataService;
import org.vaadin.tatu.vaadincreate.backend.UserService;
import org.vaadin.tatu.vaadincreate.backend.data.Message;
import org.vaadin.tatu.vaadincreate.backend.data.Product;
import org.vaadin.tatu.vaadincreate.backend.data.User;
import org.vaadin.tatu.vaadincreate.crud.BooksView;
Expand Down Expand Up @@ -223,13 +223,11 @@ public AppDataService getAppService() {

@Override
public void eventFired(Object event) {
if (event instanceof Message) {
Message message = (Message) event;

if (event instanceof MessageEvent message) {
access(() -> {
var note = new Notification(
Utils.formatDate(message.getDateStamp(), getLocale()),
message.getMessage(), Type.TRAY_NOTIFICATION, true);
Utils.formatDate(message.timeStamp(), getLocale()),
message.message(), Type.TRAY_NOTIFICATION, true);
note.show(getPage());
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@
import com.vaadin.ui.themes.ValoTheme;

@SuppressWarnings({ "serial", "java:S2160" })
public class CategoryManagementView extends VerticalLayout
implements TabView {
public class CategoryManagementView extends VerticalLayout implements TabView {

public static final String VIEW_NAME = "categories";

Expand All @@ -53,6 +52,10 @@ public void handleAction(Object sender, Object target) {
@SuppressWarnings("java:S5669")
public CategoryManagementView() {
setSizeFull();
var attributes = AttributeExtension.of(this);
attributes.setAttribute("role", "region");
attributes.setAttribute("aria-labelledby", "view-name");

list = new ComponentList<>(CategoryForm::new);

newCategoryButton = new Button(
Expand All @@ -63,13 +66,14 @@ public CategoryManagementView() {
newCategoryButton.setDisableOnClick(true);
newCategoryButton.setId("new-category");

var h4 = new Label(getTranslation(I18n.Category.EDIT_CATEGORIES));
h4.addStyleName(ValoTheme.LABEL_H4);
var viewName = new Label(getTranslation(I18n.Category.EDIT_CATEGORIES));
viewName.addStyleName(ValoTheme.LABEL_H4);
viewName.setId("view-name");

// Cancel the form when the user presses escape
addShortcutListener(new EscapeListener());

addComponents(h4, newCategoryButton, list);
addComponents(viewName, newCategoryButton, list);
setExpandRatio(list, 1);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public UserForm() {
username = new TextField(getTranslation(I18n.User.USERNAME));
username.setId("user-field");
var userNameExt = AttributeExtension.of(username);
userNameExt.setAttribute("autocomplete", "242343243");
userNameExt.setAttribute("autocomplete", "off");
var password = new PasswordField(getTranslation(I18n.PASSWORD));
password.setId("password-field");
password2 = new PasswordField(getTranslation(I18n.User.PASSWD_REPEAT));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.List;

import org.vaadin.tatu.vaadincreate.AttributeExtension;
import org.vaadin.tatu.vaadincreate.ConfirmDialog;
import org.vaadin.tatu.vaadincreate.VaadinCreateTheme;
import org.vaadin.tatu.vaadincreate.backend.data.User;
Expand Down Expand Up @@ -38,8 +39,13 @@ public class UserManagementView extends VerticalLayout implements TabView {
private Button cancel;

public UserManagementView() {
var attributes = AttributeExtension.of(this);
attributes.setAttribute("role", "region");
attributes.setAttribute("aria-labelledby", "view-name");

var title = new Label(getTranslation(I18n.User.EDIT_USERS));
title.addStyleName(ValoTheme.LABEL_H4);
title.setId("view-name");

form = new UserForm();
form.setEnabled(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,14 @@ public void attach() {
decimalFormat.setMaximumFractionDigits(2);
decimalFormat.setMinimumFractionDigits(2);
// Improve Grid browsing experience for screen reader users
JavaScript.eval("setTimeout(() => {"
+ "const body = document.querySelector('tbody.v-grid-body');"
+ "Array.from(body.getElementsByTagName('tr')).forEach(el => {"
+ "el.setAttribute('aria-live', 'polite');});"
+ "}, 1000);");
JavaScript.eval("""
setTimeout(() => {
const body = document.querySelector('tbody.v-grid-body');
Array.from(body.getElementsByTagName('tr')).forEach(el => {
el.setAttribute('aria-live', 'polite');
});
}, 1000);
""");
}

/**
Expand Down Expand Up @@ -238,25 +241,26 @@ private String createTooltip(Product book) {
}
var converter = new EuroConverter(
getTranslation(I18n.Grid.CANNOT_CONVERT));
StringBuilder unsanitized = new StringBuilder();
unsanitized.append("<div>")
.append(getDescriptionCaptionSpan(
getTranslation(I18n.PRODUCT_NAME)))
.append(" <b>").append(book.getProductName()).append("</b><br>")
.append(getDescriptionCaptionSpan(getTranslation(I18n.PRICE)))
.append(Utils.convertToPresentation(book.getPrice(), converter))
.append("<br>")
.append(getDescriptionCaptionSpan(
getTranslation(I18n.AVAILABILITY)))
.append(Utils.createAvailabilityIcon(book.getAvailability()))
.append("<br>")
.append(getDescriptionCaptionSpan(
getTranslation(I18n.IN_STOCK)))
.append(book.getStockCount()).append("<br>")
.append(getDescriptionCaptionSpan(
getTranslation(I18n.CATEGORIES)))
.append(formatCategories(book)).append("</div>");
return Utils.sanitize(unsanitized.toString());
String unsanitized = """
<div>
%s <b>%s</b><br>
%s %s<br>
%s %s<br>
%s %d<br>
%s %s
</div>
""".formatted(
getDescriptionCaptionSpan(getTranslation(I18n.PRODUCT_NAME)),
book.getProductName(),
getDescriptionCaptionSpan(getTranslation(I18n.PRICE)),
Utils.convertToPresentation(book.getPrice(), converter),
getDescriptionCaptionSpan(getTranslation(I18n.AVAILABILITY)),
Utils.createAvailabilityIcon(book.getAvailability()),
getDescriptionCaptionSpan(getTranslation(I18n.IN_STOCK)),
book.getStockCount(),
getDescriptionCaptionSpan(getTranslation(I18n.CATEGORIES)),
formatCategories(book));
return Utils.sanitize(unsanitized);
}

// Helper method to create a span with a caption
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -406,13 +406,13 @@ public Product getDraft() {

@Override
public void eventFired(Object event) {
if (event instanceof LockingEvent) {
var id = ((LockingEvent) event).getId();
if (event instanceof LockingEvent lockingEvent) {
var id = lockingEvent.id();
view.refreshProductAsync(id);
}
if (event instanceof BooksChanged) {
var product = ((BooksChanged) event).getProduct();
if (((BooksChanged) event).getChange() != BookChange.SAVE) {
if (event instanceof BooksChanged booksChanged) {
var product = booksChanged.product();
if (((BooksChanged) event).change() != BookChange.SAVE) {
return;
}
view.refreshProductAsync(product);
Expand All @@ -432,40 +432,14 @@ private ExecutorService getExecutor() {
}

/**
* Represents a change event for books. This class encapsulates the details
* Represents a change event for books. This record encapsulates the details
* of a change made to a book, including the product affected and the type
* of change.
*/
public static class BooksChanged {
public record BooksChanged(Product product, BookChange change) {
public enum BookChange {
SAVE, DELETE
}

private Product product;
private BookChange change;

public BooksChanged(Product product, BookChange change) {
this.product = product;
this.change = change;
}

/**
* Retrieves the changed product.
*
* @return the changed {@link Product} instance.
*/
public Product getProduct() {
return product;
}

/**
* Retrieves the current change associated with the book.
*
* @return the current BookChange instance.
*/
public BookChange getChange() {
return change;
}
}

private EventBus getEventBus() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@ public FilterField() {
resetButton.setButtonLabel(getTranslation(I18n.Books.CLEAR_TEXT));
var attributes = AttributeExtension.of(this);
attributes.setAttribute("autocomplete", "off");
attributes.setAttribute("role", "searchbox");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -312,14 +312,13 @@ private static <T> String convertValue(T value) {
if (value == null) {
return "";
}
if (value instanceof BigDecimal) {
if (value instanceof BigDecimal price) {
var euroConverter = new EuroConverter("");
return Utils.convertToPresentation((BigDecimal) value,
euroConverter);
return Utils.convertToPresentation(price, euroConverter);
}
if (value instanceof Availability) {
if (value instanceof Availability availability) {
return String.format("%s<span style='margin-right: 5px'>%s</span>",
Utils.createAvailabilityIcon((Availability) value),
Utils.createAvailabilityIcon(availability),
value.toString());
}
return value.toString();
Expand All @@ -334,7 +333,7 @@ private void clearDirtyIndicators() {
}

private void buildForm() {
var formLayout = new VerticalLayout();
var formLayout = new Form();
formLayout.setHeightFull();
formLayout.setMargin(false);
formLayout.addStyleName(VaadinCreateTheme.BOOKFORM_FORM);
Expand Down Expand Up @@ -378,14 +377,6 @@ private void buildForm() {
deleteButton);
formLayout.setExpandRatio(spacer, 1);

// Set ARIA attributes for the form to make it accessible
var attributes = AttributeExtension.of(formLayout);
attributes.setAttribute("tabindex", "0");
attributes.setAttribute("aria-label",
getTranslation(I18n.Books.PRODUCT_FORM));
attributes.setAttribute("role", "form");
attributes.setAttribute("aria-keyshortcuts", "Escape PageDown PageUp");

sidePanel.setContent(formLayout);
}

Expand Down Expand Up @@ -501,5 +492,30 @@ private void selectNextProduct(BooksPresenter presenter, BookGrid grid) {
}
}

/**
* A form component that extends VerticalLayout and sets ARIA attributes to
* enhance accessibility. The form is given a tabindex, an aria-label for
* screen readers, a role of "form", and aria-keyshortcuts for keyboard
* navigation.
*/
public class Form extends VerticalLayout {

/**
* Constructs a new Form instance and sets ARIA attributes to enhance
* accessibility.
*/
public Form() {
super();
// Set ARIA attributes for the form to make it accessible
var attributes = AttributeExtension.of(this);
attributes.setAttribute("tabindex", "0");
attributes.setAttribute("aria-label",
getTranslation(I18n.Books.PRODUCT_FORM));
attributes.setAttribute("role", "form");
attributes.setAttribute("aria-keyshortcuts",
"Escape PageDown PageUp");
}
}

private static Logger logger = LoggerFactory.getLogger(BookForm.class);
}
Loading

0 comments on commit 7727136

Please sign in to comment.