dioxus icon indicating copy to clipboard operation
dioxus copied to clipboard

<textarea autofocus> places cursor at start if text is not empty

Open nerjs opened this issue 10 months ago • 1 comments

Problem When using a <textarea> with the autofocus attribute, the element correctly receives focus upon mounting. However, if the text is already present (either via initial_value or a Signal), the cursor is always placed at the beginning of the text.

This behavior feels unintuitive for editable fields — typically, users expect the cursor to be at the end of the existing content, or at least to have control over where it goes.

Steps To Reproduce

Steps to reproduce the behavior:

  • Create a <textarea autofocus> with a non-empty value.

  • Run the app.

  • Observe that the field gets focused, but the cursor is always at the beginning of the text.

Expected behavior

  • Either the cursor should default to the end of the text when the field is auto-focused and non-empty.

  • Or there should be a built-in way to specify cursor position (e.g. "start", "end", or a specific offset).

Environment:

  • Dioxus version: 0.6.3
  • Rust version: 1.85.1 (4eb161250 2025-03-15)
  • OS info: Linux Mint 22.1
  • uname -srp: Linux 6.8.0-56-generic x86_64
  • App platform: desktop

💡 Suggested Solution

Ideally, this should be handled entirely within Dioxus, without relying on JavaScript or platform-specific workarounds. A declarative, renderer-agnostic solution would be ideal — one that works consistently across web, desktop, mobile, etc.

Thanks for the awesome work on Dioxus! 🙌

nerjs avatar Apr 07 '25 21:04 nerjs

I don't think Dioxus should change this behavior. It may not be ideal for some apps, but it is the default behavior in the browser and most frameworks. Keeping behavior similar to browsers and other frameworks for most cases makes it easier to use external libraries in Dioxus and switch from another framework to Dioxus. You get the same behavior with plain html:

<!DOCTYPE html>
<body><textarea autofocus>some text is here</textarea></body>
</html>

and react: https://2332828.playcode.io (code at https://playcode.io/2332828)

Instead, I think Dioxus should provide an extension trait on the element ref returned by the onmounted event to let you modify the cursor within the element. Something closer to this API:

textarea {
   onmounted: |node| {
      node.set_cursor_position(text.lines().last().unwrap().len(), text.lines().count())
   }
}

ealmloff avatar Apr 08 '25 21:04 ealmloff