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

feat: enable components to notify binder when validation state changes #13940

Merged
merged 21 commits into from
Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion .github/workflows/validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
types: [opened, synchronize, reopened]
jobs:
build:
timeout-minutes: 15
timeout-minutes: 20
taefi marked this conversation as resolved.
Show resolved Hide resolved
runs-on: ubuntu-latest
outputs:
matrix-unit: ${{ steps.set-matrix.outputs.matrix-unit }}
Expand Down
16 changes: 16 additions & 0 deletions flow-data/src/main/java/com/vaadin/flow/data/binder/Binder.java
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,13 @@ public interface BindingBuilder<BEAN, TARGET> extends Serializable {
* If the Binder is already bound to some bean, the newly bound field is
* associated with the corresponding bean property as described above.
* <p>
* If the bound field implements {@link HasValidator} and the returned
* validator by {@code getDefaultValidator} method is not {@code equals}
* to {@code Validator.alwaysPass()}, then the binding instance returned
* by this method will subscribe for field's
* {@code ValidationStatusChangeEvent}s and will {@code validate} itself
* upon receiving them.
* <p>
* The getter and setter can be arbitrary functions, for instance
* implementing user-defined conversion or validation. However, in the
* most basic use case you can simply pass a pair of method references
Expand Down Expand Up @@ -966,6 +973,15 @@ public Binding<BEAN, TARGET> bind(ValueProvider<BEAN, TARGET> getter,
}
this.binding = binding;

if (field instanceof HasValidator) {
HasValidator<FIELDVALUE> hasValidatorField = (HasValidator<FIELDVALUE>) field;
if (!Validator.alwaysPass()
.equals(hasValidatorField.getDefaultValidator())) {
hasValidatorField.addValidationStatusChangeListener(
event -> this.binding.validate());
}
}

return binding;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@

import java.io.Serializable;

import com.vaadin.flow.function.ValueProvider;
import com.vaadin.flow.shared.Registration;

/**
* A generic interface for field components and other user interface objects
* that have a user-editable value that should be validated.
Expand All @@ -41,4 +44,23 @@ public interface HasValidator<V> extends Serializable {
default Validator<V> getDefaultValidator() {
return Validator.alwaysPass();
}

/**
* Enables the implementing components to announce changes in their
* validation status to the observers.
*
* <strong>Note:</strong> This method should be overridden by the
* implementing classes e.g. components, to enable the {@link Binder}
* subscribing for their validation change events and revalidate.
*
* @see com.vaadin.flow.data.binder.Binder.BindingBuilderImpl#bind(ValueProvider,
* Setter)
* @since 23.2
*
* @return Registration of the added listener.
*/
default Registration addValidationStatusChangeListener(
ValidationStatusChangeListener<V> listener) {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2000-2022 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.data.binder;

import com.vaadin.flow.component.HasValue;

import java.io.Serializable;

/**
* The event to be processed when
* {@link ValidationStatusChangeListener#validationStatusChanged(ValidationStatusChangeEvent)}
* invoked.
*
* @since 23.2
*
* @param <V>
* the value type
*/
public class ValidationStatusChangeEvent<V> implements Serializable {

private final HasValue<?, V> source;
private final boolean newStatus;
mshabarov marked this conversation as resolved.
Show resolved Hide resolved

public ValidationStatusChangeEvent(HasValue<?, V> source,
boolean newStatus) {
this.source = source;
this.newStatus = newStatus;
}

public HasValue<?, V> getSource() {
return source;
}

public boolean getNewStatus() {
return newStatus;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright 2000-2022 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.data.binder;

import java.io.Serializable;

/**
* The listener interface for receiving {@link ValidationStatusChangeEvent}
mshabarov marked this conversation as resolved.
Show resolved Hide resolved
* events. The classes that are interested in processing a Validation status
* changed event of field components e.g.
* {@link com.vaadin.flow.data.binder.Binder.BindingBuilderImpl}, register
* implementation of this interface via
* {@link HasValidator#addValidationStatusChangeListener(ValidationStatusChangeListener)}
* which are called whenever such event is fired by the component class, e.g.
* {@code datePicker}.
*
* @since 23.2
*
* @see HasValidator
*/
@FunctionalInterface
public interface ValidationStatusChangeListener<V> extends Serializable {

/**
* Invoked when a ValidationStatusChangeEvent occurs.
*
* @param event
* the event to be processed
*/
void validationStatusChanged(ValidationStatusChangeEvent<V> event);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.vaadin.flow.data.binder;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.vaadin.flow.data.binder.testcomponents.TestHasValidatorDatePicker;
import com.vaadin.flow.component.HasValue;
import com.vaadin.flow.tests.data.bean.Person;

import static com.vaadin.flow.data.binder.testcomponents.TestHasValidatorDatePicker.INVALID_DATE_FORMAT;

public class BinderValidationStatusChangeListenerTest
extends BinderTestBase<Binder<Person>, Person> {

private static final String BIRTH_DATE_PROPERTY = "birthDate";

private final Map<HasValue<?, ?>, String> componentErrors = new HashMap<>();

@Before
public void setUp() {
binder = new Binder<>(Person.class) {
@Override
protected void handleError(HasValue<?, ?> field,
ValidationResult result) {
componentErrors.put(field, result.getErrorMessage());
}

@Override
protected void clearError(HasValue<?, ?> field) {
super.clearError(field);
componentErrors.remove(field);
}
};
item = new Person();
}

@Test
public void fieldWithHasValidatorDefaults_bindIsCalled_addValidationStatusListenerIsNotCalled() {
var field = Mockito.spy(
TestHasValidatorDatePicker.DatePickerHasValidatorDefaults.class);
Assert.assertEquals(Validator.alwaysPass(),
field.getDefaultValidator());
binder.bind(field, BIRTH_DATE_PROPERTY);
Mockito.verify(field, Mockito.times(0))
.addValidationStatusChangeListener(Mockito.any());
}

@Test
public void fieldWithHasValidatorOnlyAddListenerOverridden_bindIsCalled_addValidationStatusListenerIsNotCalled() {
var field = Mockito.spy(
TestHasValidatorDatePicker.DataPickerHasValidatorAddListenerOverridden.class);
Assert.assertEquals(Validator.alwaysPass(),
field.getDefaultValidator());
binder.bind(field, BIRTH_DATE_PROPERTY);
Mockito.verify(field, Mockito.times(0))
.addValidationStatusChangeListener(Mockito.any());
}

@Test
public void fieldWithHasValidatorFullyOverridden_bindIsCalled_binderAddsValidationStatusChangeListenerToField() {
var field = Mockito.spy(
TestHasValidatorDatePicker.DataPickerHasValidatorOverridden.class);
Assert.assertNotEquals(Validator.alwaysPass(),
field.getDefaultValidator());
binder.bind(field, BIRTH_DATE_PROPERTY);
Mockito.verify(field, Mockito.times(1))
.addValidationStatusChangeListener(Mockito.any());
}

@Test
public void fieldWithHasValidatorFullyOverridden_fieldValidationStatusChangesToFalse_binderHandleErrorIsCalled() {
var field = new TestHasValidatorDatePicker.DataPickerHasValidatorOverridden();
binder.bind(field, BIRTH_DATE_PROPERTY);
Assert.assertEquals(0, componentErrors.size());

field.fireValidationStatusChangeEvent(false);
Assert.assertEquals(1, componentErrors.size());
Assert.assertEquals(INVALID_DATE_FORMAT, componentErrors.get(field));
}

@Test
public void fieldWithHasValidatorFullyOverridden_fieldValidationStatusChangesToTrue_binderClearErrorIsCalled() {
var field = new TestHasValidatorDatePicker.DataPickerHasValidatorOverridden();
binder.bind(field, BIRTH_DATE_PROPERTY);
Assert.assertEquals(0, componentErrors.size());

field.fireValidationStatusChangeEvent(false);
Assert.assertEquals(1, componentErrors.size());
Assert.assertEquals(INVALID_DATE_FORMAT, componentErrors.get(field));

field.fireValidationStatusChangeEvent(true);
Assert.assertEquals(0, componentErrors.size());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.vaadin.flow.data.binder.testcomponents;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;

import com.vaadin.flow.data.binder.*;
import com.vaadin.flow.shared.Registration;

public class TestHasValidatorDatePicker {

public static final String INVALID_DATE_FORMAT = "Invalid date format";

public static class DatePickerHasValidatorDefaults extends TestDatePicker
implements HasValidator<LocalDate> {

protected boolean validationStatus = true;
}

public static class DataPickerHasValidatorGetDefaultValidatorOverridden
extends DatePickerHasValidatorDefaults {

@Override
public Validator<LocalDate> getDefaultValidator() {
return (value, context) -> validationStatus ? ValidationResult.ok()
: ValidationResult.error(INVALID_DATE_FORMAT);
}
}

public static class DataPickerHasValidatorAddListenerOverridden
extends DatePickerHasValidatorDefaults {

private final Collection<ValidationStatusChangeListener<LocalDate>> validationStatusListeners = new ArrayList<>();

@Override
public Registration addValidationStatusChangeListener(
ValidationStatusChangeListener<LocalDate> listener) {
validationStatusListeners.add(listener);
return () -> validationStatusListeners.remove(listener);
}

public void fireValidationStatusChangeEvent(
boolean newValidationStatus) {
if (validationStatus != newValidationStatus) {
validationStatus = newValidationStatus;
var event = new ValidationStatusChangeEvent<>(this,
newValidationStatus);
validationStatusListeners.forEach(
listener -> listener.validationStatusChanged(event));
}
}
}

public static class DataPickerHasValidatorOverridden
extends DataPickerHasValidatorAddListenerOverridden {

@Override
public Validator<LocalDate> getDefaultValidator() {
return (value, context) -> validationStatus ? ValidationResult.ok()
: ValidationResult.error("Invalid date format");
}
}
}