Grid and scrollToIndex()

Hello!

I have the following use case: from the url, the app can retrieve the id of an item to display directly if present in the grid.
No issue to achieve that.

But if that item is present at the bottom of the grid, well the selection is well made but invisible to the user (the data are well displayed below the grid as expected of course).

That’s why the function grid.scrollToIndex() exists, but it is really unconvenient… how can I get the index of my item?
I can iterate over the entire collection via grid.getListDataView().getItem(int index) and make sure the returned item is equal to the selected one but… yeah… not efficient and I’m not even sure that index = the expected index of the method .scrollToIndex().

So how to deal with that?

Are you using a ListDataProvider or a CallbackDataProvider?

A ListDataProvider

Then you should be able to call scrollToIndex with the index in the list

Yes it works but there is a lack of scrollToItem(myItem)

for (int i = 0; i < grid.getListDataView().getItemCount(); i++) {
if (myItem.equals(grid.getListDataView().getItem(i))) {
grid.scrollToIndex(i);
}
}

no other way to retrieve this index

But you pass the list initially then you can call

grid.scrollToIndex(list.indexOf(myItem));

The problem is: I don’t have access to this list at this point. I’m using the crudui plugin https://alejandro.app.fi/crud-ui-demo/

Well yes, I could store it as attribute of my Route class

but this is not perfect because a sort can be made just after the grid.setItems();

Yes indeed this is a problem.

:wave: When do you need to trigger the scroll event? We do it in a selection listener, if the event is not user originated.

Currently I’m doing this:

                    grid.select(myItem);
                    for (int i = 0; i < grid.getListDataView().getItemCount(); i++) {
                        if (myItem.equals(grid.getListDataView().getItem(i))) {
                            grid.scrollToIndex(i);
                        }
                    }

So there is a selection listener but the scroll is not triggered if I remove the for loop

This seems to work:

var list = IntStream.range(0, 1000).boxed().collect(Collectors.toList());
ListDataProvider<Integer> listDataProvider = new ListDataProvider<>(list);
grid.setItems(listDataProvider);
grid.addSortListener(gridGridSortOrderSortEvent -> {
   var o = grid.asSingleSelect().getValue();
   grid.scrollToIndex(list.indexOf(o));
});

Ok, your point is “It’s possible to decouple the index of the list AND the grid sort: even if the grid is sorted, the index remains the same for each item”, right?

Sorry, I was wrong. I still need to do this to get the correct index:

var integers = dataView.getItems().collect(Collectors.toList());
grid.scrollToIndex(integers.indexOf(o));