Skip to content

Commit

Permalink
fix: warn and revert to prev index when selecting invalid index (#6543)
Browse files Browse the repository at this point in the history
  • Loading branch information
vursen authored Aug 15, 2024
1 parent 296df14 commit 3fde459
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,19 @@ public enum Orientation {
*/
public Tabs() {
setSelectedIndex(-1);
getElement().addPropertyChangeListener(SELECTED,
event -> updateSelectedTab(event.isUserOriginated()));
getElement().addPropertyChangeListener(SELECTED, event -> {
int oldIndex = selectedTab != null ? indexOf(selectedTab) : -1;
int newIndex = getSelectedIndex();
if (newIndex >= getTabCount()) {
LoggerFactory.getLogger(getClass()).warn(String.format(
"The selected index is out of range: %d. Reverting to the previous index: %d.",
newIndex, oldIndex));
setSelectedIndex(oldIndex);
return;
}

updateSelectedTab(event.isUserOriginated());
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.html.Div;
Expand Down Expand Up @@ -102,6 +106,41 @@ public void selectTabByIndex() {
assertThat("Selected index is invalid", tabs.getSelectedIndex(), is(2));
}

@Test
public void selectInvalidIndex_previousIndexIsReverted() {
Tab tab = new Tab("Tab");
Tabs tabs = new Tabs(tab);

// Select index out of range
tabs.setSelectedIndex(10);
Assert.assertEquals(0, tabs.getSelectedIndex());

// Deselect the active tab
tabs.setSelectedIndex(-1);
// Select index out of range
tabs.setSelectedIndex(10);
Assert.assertEquals(-1, tabs.getSelectedIndex());
}

@Test
public void selectInvalidIndex_warningIsShown() {
Tab tab = new Tab("Tab");
Tabs tabs = new Tabs(tab);

Logger mockedLogger = Mockito.mock(Logger.class);
try (MockedStatic<LoggerFactory> context = Mockito
.mockStatic(LoggerFactory.class)) {
context.when(() -> LoggerFactory.getLogger(Tabs.class))
.thenReturn(mockedLogger);

// Select index out of range
tabs.setSelectedIndex(10);

Mockito.verify(mockedLogger, Mockito.times(1)).warn(
"The selected index is out of range: 10. Reverting to the previous index: 0.");
}
}

@Test
public void shouldThrowWhenTabToSelectIsNotChild() {
thrown.expect(IllegalArgumentException.class);
Expand Down

0 comments on commit 3fde459

Please sign in to comment.