Extends
HTMLTextAreaElement.setRangeTextwith Myers diff-powered cursor and selection tracking.
textarea-track-mode monkey-patches the browser's native HTMLTextAreaElement.prototype.setRangeText method to add a new "track" selection mode. When set to "track", text changes are processed using the Myers Diff algorithm to accurately calculate and map active cursor positions and selection ranges; preventing cursor jumps during complex text edits between cursors' position.
This package relies on the Myers class provided by acdhemtos/myers-diff.
Ensure ./Myers.js is loaded before importing or running textarea-track.js.
Load Myers.js followed by textarea-track.js:
<script src="https://cdn.jsdelivr.net/gh/acdhemtos/myers-diff/Myers.js"></script>
<script src="./textarea-track.js"></script>import './Myers.js'; // From acdhemtos/myers-diff
import './textarea-track.js'; // Extends HTMLTextAreaElement.prototype.setRangeTextOnce imported, textarea-track.js automatically patches HTMLTextAreaElement.prototype.setRangeText. You can pass "track" as the selectionMode parameter.
const textarea = document.querySelector('textarea');
textarea.value = "Hello world!";
// Set cursor after "Hello"
textarea.setSelectionRange(5, 5);
// Replace entire text or a segment while tracking existing cursor position
textarea.setRangeText("Hello brave new world!", 0, textarea.value.length, "track");
// Cursor automatically adjusts to the correct relative position!