Vaadin get/set cursor position / selection start/end in Textfield

583 Views Asked by At

I know there was in Vaadin7 (8) some methods the get / set the cursor position of the textfield from server side.

I'm using Vaadin Flow v21, but there are no such methods. How can I get/set the cursor position from server side synchronously? To set it seens to work fine using some javascript, but I cannot read the actual cursor position, since it is only going async. How to do it sync?

I try to read like this:

public int getSelectionStart() throws InterruptedException
{
    Future<Integer> value = UI.getCurrent().getPage().executeJs(
            "return $0.shadowRoot.querySelector('[part=\"value\"]').selectionStart;"
            , getElement()).toCompletableFuture(Integer.class);

    final int[] val = new int[1];

    Thread t = new Thread(() ->
    {
        Integer result = null;
        try
        {
            result = value.get();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        val[0] = result == null ? 0 : result;
    });

    t.start();
    t.join();

    return val[0];
};

But above method gives me exception, that the ongoing UI session request has not been closed yet, so basically it cannot execute the javascript, unless I end the request.

This is how I set cursor position, which seems to work since I don't want to get any return value back, so ending the request is going to execute the script and set the proper cursor position.

public void setSelectionStart(int pos)
{
    UI.getCurrent().getPage().executeJs("$0.shadowRoot.querySelector('[part=\"value\"]').setSelectionRange($1, $1);", getElement(), pos);
}

Thanks for any help / suggestion!

1

There are 1 best solutions below

1
On

I hope the documentation for RPC return values could help here: https://vaadin.com/docs/latest/flow/element-api/client-server-rpc/#return-values