Calling editor.setSelectedText in system test
Our team is updating our Rails 7.0.8 app to Trix 2.0.7 from 1.3.1, which introduced a failure in one of our system tests that calls setSelectedRange:
content = "Hello world"
fill_in_rich_text_area with: content
find(:rich_text_area).execute_script("this.editor.setSelectedRange(#{content.length})")
On 1.3.1, this worked as expected; the text area was filled and then selection was moved to the end. On 2.0.7, the setSelectedRange call doesn't work; the selection stays at [0,0].
I haven't been able to find the root cause, and haven't found a way to get setSelectedRange working, but replacing fill_in_rich_text_area with Capybara's set method works around the issue:
content = "Hello world"
find(:rich_text_area).set(content)
I'm curious if there's a known change to loadHTML (called by fill_in_rich_text_area) or setSelectedRange in 2.x that might have caused this behavior, but I understand this isn't necessarily a Trix bug, so feel free to close this as you see fit. I mainly wanted to note the issue and workaround for anyone else who might encounter it.
Details
- Trix version: 2.0.7
- Browser name and version: Chrome 119.0.6045.159 (via system test)
- Operating system: macOS 14.1
@jcbpl no changes that I'm aware of. Hard to say what's going on, but if there has been a regression a failing test might help to pinpoint the issue.
Thanks. I'm not very familiar with Trix's tests, but I'm able to reproduce in Chrome using a simple Stimulus controller:
// trix_debug.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
ready() {
this.element.editor.loadHTML("Hello world")
this.element.editor.setSelectedRange([0,5])
}
}
Included via:
<%= form.rich_text_area :content, data: { controller: "trix-debug", action: "trix-initialize->trix-debug#ready" } %>
"Hello" is selected when using 1.3.1 but not when using 2.0.7.
As an additional clue, I discovered that adding this.element.focus() causes setSelectedRange to work:
this.element.editor.loadHTML("Hello world")
this.element.focus()
this.element.editor.setSelectedRange([0,5])
Adding find(:rich_text_area).click to the system test also works there. But I'm not sure if that explains the issue.