0

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!

Anna Koskinen
  • 1,362
  • 3
  • 22
user1536873
  • 81
  • 1
  • 10

1 Answers1

1

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

Jouni
  • 2,830
  • 15
  • 12
  • Well, @ClientCallable could be something useful, if I can set some javascript event on client side on the textfield, that every keypress should call a server side method to set the current caret position. But since I'm using keypressed server side event also, I have to test which event comes first. May be I have to register the javascript on keydown, since it should trigger before keypressed. Thanks! – user1536873 Dec 08 '21 at 07:03