So this is a piece of the code responsible for the setup of my TreeGrid. As it is shown I’ve created listeners for each letter so that whenever I press a letter the item which label starts with that letter is selected. But the struggle I am facing is that even if the correct item is selected I cannot use the usual shortcuts for TreeGrid (the arrows for example which expand and collapse the grid) which I’ve concluded is due to the item not being on focus. So my question is - Is there a way to dynamically focus the cell/item which I’ve currently selected ?
import java.util.List;
import com.dhl.evo.web.components.navigation.tree.ItemContainer;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.Shortcuts;
import com.vaadin.flow.component.treegrid.TreeGrid;
import com.wexlog.wexsuite.commons.util.WsStringUtil;
class Scratch {
private final TreeGrid<ItemContainer> treeGrid = new TreeGrid<>();
private String lastSearchedKey = "";
private int lastFoundIndex = -1;
private void setUpTree(){
for (char c = 'a'; c <= 'z'; c++) {
String key = String.valueOf(c);
Shortcuts.addShortcutListener(treeGrid, () -> handleKeyPress(key), Key.of(key));
}
}
private void handleKeyPress(String _pressedKey) {
if (WsStringUtil.getNotNullString(_pressedKey).length() == 1) {
String lowerCasePressedKey = _pressedKey.toLowerCase();
if (!lowerCasePressedKey.equals(lastSearchedKey)) {
lastSearchedKey = lowerCasePressedKey;
lastFoundIndex = -1;
}
List<ItemContainer> visibleItems = getVisibleItems();
List<ItemContainer> matchingItems = visibleItems.stream()
.filter(item -> item.getLabel().toLowerCase().startsWith(lowerCasePressedKey))
.toList();
if (matchingItems.isEmpty()) {
return;
}
lastFoundIndex = (lastFoundIndex + 1) % matchingItems.size();
ItemContainer itemToSelect = matchingItems.get(lastFoundIndex);
treeGrid.select(itemToSelect);
int scrollToIndex = visibleItems.indexOf(itemToSelect);
if (scrollToIndex != -1) {
treeGrid.scrollToIndex(scrollToIndex);
}
}
}
}