Vaadin RTL support, get current direction

88 Views Asked by At

I need to add RTL languages support to my application. I know how to set the direction to RTL:

UI.getCurrent().setDirection(Direction.RIGHT_TO_LEFT)

but I also need to programmatically get this value in order to do some changes in the code.

How to get current Direction value in the view?

1

There are 1 best solutions below

0
On BEST ANSWER

Smells like a missing API, but for now, due to the async nature of executeJs, you might consider the following:

public void fetchPageDirection(SerializableConsumer<Direction> callback) {
    UI.getCurrent().getPage()
            .executeJs("return document.dir")
            .then(String.class, dir -> {
                Direction direction = getDirectionByClientName(dir);
                callback.accept(direction);
            });
}

private Direction getDirectionByClientName(String directionClientName) {
    return Arrays.stream(Direction.values())
            .filter(direction -> direction.getClientName().equals(directionClientName))
            .findFirst().orElse(Direction.LEFT_TO_RIGHT); // Default to LTR
}

After this PR is merged and released, you can just use the API with the same name from Page instance:

UI.getCurrent().getPage().fetchPageDirection(direction -> {
    doSomethingWithDirection(direction);
});