ResizeObserver - a new handy API to configure your components based on their actual size

Viritin 2.8.9 now contains a handy class called ResizeObserver. You can use it to detect the rendered size of any component, so you can do further configuration that are optimal for your users. For exaple you probably want totally different set of columns for your Grid, if you are using it from a smarphone vs desktop. Or you might want to reconfigure those if user makes the grid narrower in a Splitlayout.

Even if you are just interested about the window/UI size, you can proabably replace two pretty similar code snippets with one (one for “ExtendedClientDetails”, on for page resize events).

Example/test UI:

Go and give it try, I’d like to contribute a similar helper to core soon, but input from apps using this PoC would help to get details right. An issue in the core if you want to thumb up or share insights: Add a mechanism to configure components based on their actual sizes · Issue #19129 · vaadin/flow · GitHub

6 Likes

I tested this and is working perfectly. Thanks @Matti


Here is a sample of how this ResizeObserver works

1 Like

I did a series of enhancements, javadocs and bug fixes to ResizeObserver. If you are using that I suggest to update your Viritin to version 2.10.3.

I was also considering to just drop it as a PR to Flow, but I think that approach is “overcomplicated” for the users. In the Flow enhancment issue I changed the API to exist directly in HasSize interface, so that it would practically be available through components. What do you think? Comment here or in the GH issue!

2 Likes

Trying to understand this nifty feature, does it serve the same purpose as FormLayout.ResponsiveStep ?

Yes, it’s more generic but in short when the size is changing you can call some Java code. For example hide a column when the grid is too small.

1 Like

Or even change the whole Grid component into something that is more suitable for mobile devices.

An example of the Grid column adjustment that @Jean-Christophe.1 mentioned can be seen in the test sources:

I’ve created something like this

public interface HasResponsiveView {

    default void enableResponsiveView(Component layout) {
        ResizeObserver.get().observe(layout, observation -> {
            if (observation.width() < 450) {
                mobileView();
            } else {
                desktopView();
            }
        });
    }

    void mobileView();

    void desktopView();

}

The advantage I see here is, two seperate views but using common features as much as possible. I do not have to muddle with too many CSS class names and/or media queries.

1 Like

Another week, another iteration. Now the same funtionality can be achieved directly from pretty much all V prefixed Viritin components, by hooking the logic to listen ResizeEvent’s directly to the components. Grid column example:

1 Like