Re: [w3c/editing] Expose event.getTargetRanges() in oncompositionstart (and possibly oncompositionend as well) (Issue #511)

michael left a comment (w3c/editing#511)

Here's how a reasoanable API (without breaking backwards compatibility) could look like, so I can handle this properly.

```js
let before_input_selection;

function onbeforeinput(event) {
  if (event.isComposing) {
    // skip: handled by oncompositionstart/end
  } else {
    // handle any other inputs, including replacements using event.getTargetRanges()
  }
}

function oncompositionstart(event) {
  before_input_selection = __getModelSelectionFromTargetRange(event.getTargetRanges()[0]);
}

function oncompositionend(event) {
  // Step 1 - I need a way to roll back the DOM changes to have a clean slate for step 3
  // NOTE: I tried document.execCommand('undo') here, which would basically do the
  // same thing, it works in Chrome but breaks in weird ways in Safari/Firefox.
  event.resetDOM(); 
  // Step 2 - Set the model selection to the state right after the composition started 
  // (where no changes were applied yet - e.g. to the word the composition started from)
  doc.selection = before_input_selection;
  // Step 3 - Apply the final composition to (this will replace the contents of before_input_selection)
  const tr = doc.tr;
  tr.insert_text(event.data);
  // this applies the change to the model, and triggers an incremental rerender of the affected part of the document
  doc.apply(tr);
  // Now my incremental reactive rendering can happen reliably, knowing that the DOM is in the same state as before the composition started.
}
```

My approach here treats the complete composition as a single input to be applied to my internal model. My model would not reflect the in-between inputs during composition.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/w3c/editing/issues/511#issuecomment-3542223429
You are receiving this because you are subscribed to this thread.

Message ID: <w3c/editing/issues/511/3542223429@github.com>

Received on Monday, 17 November 2025 14:44:37 UTC