Skip to content

A platform for community discussion. Free, open, simple.

DEV: Convert caret-position from JQuery to vanilla JS (#41428)

David Taylor1599e156d229
diff --git a/frontend/discourse/app/instance-initializers/jquery-plugins.js b/frontend/discourse/app/instance-initializers/jquery-plugins.js
deleted file mode 100644
index fd878df2fba..00000000000
--- a/frontend/discourse/app/instance-initializers/jquery-plugins.js
+++ /dev/null
@@ -1,18 +0,0 @@
-import $ from "jquery";
-import { caret, caretPosition } from "discourse/lib/caret-position";
-
-let jqueryPluginsConfigured = false;
-
-export default {
- initialize() {
- if (jqueryPluginsConfigured) {
- return;
- }
-
- // Initialize caretPosition
- $.fn.caret = caret;
- $.fn.caretPosition = caretPosition;
-
- jqueryPluginsConfigured = true;
- },
-};
diff --git a/frontend/discourse/app/lib/caret-position.js b/frontend/discourse/app/lib/caret-position.js
index 4dc3d967545..5dea0851228 100644
--- a/frontend/discourse/app/lib/caret-position.js
+++ b/frontend/discourse/app/lib/caret-position.js
@@ -1,11 +1,4 @@
-/* eslint-disable ember/no-jquery */
-import $ from "jquery";
-
-// This was heavily modified by us over the years, and mostly written by us
-// except for the little snippet from StackOverflow
-//
-// http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
-let clone = null;
+import domUtils from "discourse/lib/dom-utils";
function getCaret(el) {
if (el.selectionStart) {
@@ -14,151 +7,117 @@ function getCaret(el) {
return 0;
}
-export function caret(elem) {
- return getCaret(elem || this[0]);
-}
-
-/**
- retrieve the caret position in a textarea
-**/
-export function caretPosition(options) {
- let after,
- before,
- getStyles,
- guard,
- html,
- important,
- insertSpaceAfterBefore,
- letter,
- makeCursor,
- p,
- pPos,
- pos,
- styles,
- textarea,
- val;
- if (clone) {
- clone.remove();
- }
- textarea = $(this);
-
- getStyles = function (el) {
- if (el.currentStyle) {
- return el.currentStyle;
- } else {
- return document.defaultView.getComputedStyle(el, "");
+// Retrieve the pixel coordinates of the caret within a textarea, relative to
+// the textarea itself. It works by rendering an off-screen clone of the
+// textarea's content and measuring where the caret would land.
+export function caretCoordinates(element, options) {
+ const styles = getComputedStyle(element);
+ const important = (prop) => styles.getPropertyValue(prop);
+ const isRTL = document.documentElement.classList.contains("rtl");
+
+ const clone = document.createElement("div");
+ const p = document.createElement("p");
+ clone.appendChild(p);
+ document.body.appendChild(clone);
+
+ try {
+ Object.assign(clone.style, {
+ boxSizing: "content-box",
+ border: "1px solid black",
+ padding: important("padding"),
+ resize: important("resize"),
+ maxHeight: important("height"),
+ overflowY: "auto",
+ wordWrap: "break-word",
+ position: "absolute",
+ left: isRTL ? "auto" : "-7000px",
+ right: isRTL ? "-7000px" : "auto",
+ width: important("width"),
+ height: important("height"),
+ });
+
+ Object.assign(p.style, {
+ margin: 0,
+ padding: 0,
+ wordWrap: "break-word",
+ letterSpacing: important("letter-spacing"),
+ fontFamily: important("font-family"),
+ fontSize: important("font-size"),
+ lineHeight: important("line-height"),
+ });
+
+ const pos =
+ options && (options.pos || options.pos === 0)
+ ? options.pos
+ : getCaret(element);
+
+ let val = element.value.replace("\r", "");
+ if (options && options.key) {
+ val = val.substring(0, pos) + options.key + val.substring(pos);
}
- };
-
- important = function (prop) {
- return styles.getPropertyValue(prop);
- };
-
- styles = getStyles(textarea[0]);
- clone = $("<div><p></p></div>").appendTo("body");
- p = clone.find("p");
-
- let isRTL = $("html").hasClass("rtl");
- clone.css({
- border: "1px solid black",
- padding: important("padding"),
- resize: important("resize"),
- "max-height": textarea.height() + "px",
- "overflow-y": "auto",
- "word-wrap": "break-word",
- position: "absolute",
- left: isRTL ? "auto" : "-7000px",
- right: isRTL ? "-7000px" : "auto",
- });
-
- p.css({
- margin: 0,
- padding: 0,
- "word-wrap": "break-word",
- "letter-spacing": important("letter-spacing"),
- "font-family": important("font-family"),
- "font-size": important("font-size"),
- "line-height": important("line-height"),
- });
-
- clone.width(textarea.width());
- clone.height(textarea.height());
-
- pos =
- options && (options.pos || options.pos === 0)
- ? options.pos
- : getCaret(textarea[0]);
-
- val = textarea.val().replace("\r", "");
- if (options && options.key) {
- val = val.substring(0, pos) + options.key + val.substring(pos);
- }
- before = pos - 1;
- after = pos;
- insertSpaceAfterBefore = false;
-
- // if before and after are \n insert a space
- if (val[before] === "\n" && val[after] === "\n") {
- insertSpaceAfterBefore = true;
- }
-
- guard = function (v) {
- let buf;
- buf = v.replace(/</g, "&lt;");
- buf = buf.replace(/>/g, "&gt;");
- buf = buf.replace(/[ ]/g, "&#x200b;&nbsp;&#x200b;");
- return buf.replace(/\n/g, "<br />");
- };
-
- makeCursor = function (index, klass, color) {
- let l;
- l = val.substring(index, index + 1);
- if (l === "\n") {
- return "<br>";
- }
- return (
- "<span class='" +
- klass +
- "' style='background-color:" +
- color +
- "; margin:0; padding: 0'>" +
- guard(l) +
- "</span>"
- );
- };
-
- html = "";
-
- if (before >= 0) {
- html +=
- guard(val.substring(0, pos - 1)) +
- makeCursor(before, "before", "#d0ffff");
- if (insertSpaceAfterBefore) {
- html += makeCursor(0, "post-before", "#d0ffff");
+ const before = pos - 1;
+ const after = pos;
+
+ // if before and after are \n insert a space
+ const insertSpaceAfterBefore = val[before] === "\n" && val[after] === "\n";
+
+ const guard = function (v) {
+ let buf = v.replace(/</g, "&lt;");
+ buf = buf.replace(/>/g, "&gt;");
+ buf = buf.replace(/[ ]/g, "&#x200b;&nbsp;&#x200b;");
+ return buf.replace(/\n/g, "<br />");
+ };
+
+ const makeCursor = function (index, klass, color) {
+ const l = val.substring(index, index + 1);
+ if (l === "\n") {
+ return "<br>";
+ }
+ return (
+ "<span class='" +
+ klass +
+ "' style='background-color:" +
+ color +
+ "; margin:0; padding: 0'>" +
+ guard(l) +
+ "</span>"
+ );
+ };
+
+ let html = "";
+
+ if (before >= 0) {
+ html +=
+ guard(val.substring(0, pos - 1)) +
+ makeCursor(before, "before", "#d0ffff");
+ if (insertSpaceAfterBefore) {
+ html += makeCursor(0, "post-before", "#d0ffff");
+ }
}
- }
- if (after >= 0) {
- html += makeCursor(after, "after", "#ffd0ff");
- if (after - 1 < val.length) {
- html += guard(val.substring(after + 1));
+ if (after >= 0) {
+ html += makeCursor(after, "after", "#ffd0ff");
+ if (after - 1 < val.length) {
+ html += guard(val.substring(after + 1));
+ }
}
- }
- p.html(html);
- clone.scrollTop(textarea.scrollTop());
- letter = p.find("span:first");
- pos = letter.offset();
- if (letter.hasClass("before")) {
- pos.left = pos.left + letter.width();
- }
+ p.innerHTML = html;
+ clone.scrollTop = element.scrollTop;
- pPos = p.offset();
- let position = {
- left: pos.left - pPos.left,
- top: pos.top - pPos.top - clone.scrollTop(),
- };
+ const letter = p.querySelector("span");
+ const letterOffset = domUtils.offset(letter);
+ let left = letterOffset.left;
+ if (letter.classList.contains("before")) {
+ left += letter.offsetWidth;
+ }
- clone.remove();
- return position;
+ const pOffset = domUtils.offset(p);
+ return {
+ left: left - pOffset.left,
+ top: letterOffset.top - pOffset.top - clone.scrollTop,
+ };
+ } finally {
+ clone.remove();
+ }
}
diff --git a/frontend/discourse/app/lib/textarea-text-manipulation.js b/frontend/discourse/app/lib/textarea-text-manipulation.js
index 37a9cffb577..bba1a984d15 100644
--- a/frontend/discourse/app/lib/textarea-text-manipulation.js
+++ b/frontend/discourse/app/lib/textarea-text-manipulation.js
@@ -6,6 +6,7 @@ import { next, schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
import $ from "jquery";
+import { caretCoordinates } from "discourse/lib/caret-position";
import { bind } from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import escapeRegExp from "discourse/lib/escape-regexp";
@@ -1068,8 +1069,7 @@ export class TextareaAutocompleteHandler {
}
getCaretCoords(start) {
- // @ts-ignore
- return this.$textarea.caretPosition({ pos: start + 1 });
+ return caretCoordinates(this.textarea, { pos: start + 1 });
}
async inCodeBlock() {
diff --git a/frontend/discourse/app/lib/utilities.js b/frontend/discourse/app/lib/utilities.js
index cdd2030571b..185496727bf 100644
--- a/frontend/discourse/app/lib/utilities.js
+++ b/frontend/discourse/app/lib/utilities.js
@@ -1,7 +1,6 @@
-/* eslint-disable ember/no-jquery */
import { cancel } from "@ember/runloop";
-import $ from "jquery";
import * as AvatarUtils from "discourse/lib/avatar-utils";
+import { caretCoordinates } from "discourse/lib/caret-position";
import deprecated from "discourse/lib/deprecated";
import escape from "discourse/lib/escape";
import getURL from "discourse/lib/get-url";
@@ -674,8 +673,7 @@ export function mergeSortedLists(list1, list2, comparator) {
}
export function getCaretPosition(element, options) {
- const jqueryElement = $(element);
- const position = jqueryElement.caretPosition(options);
+ const position = caretCoordinates(element, options);
// Get the position of the textarea on the page
const textareaRect = element.getBoundingClientRect();
diff --git a/frontend/discourse/tests/unit/lib/caret-position-test.js b/frontend/discourse/tests/unit/lib/caret-position-test.js
new file mode 100644
index 00000000000..7d42a3813e4
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/caret-position-test.js
@@ -0,0 +1,163 @@
+import { module, test } from "qunit";
+import { caretCoordinates } from "discourse/lib/caret-position";
+
+function withTextarea(css, callback) {
+ const textarea = document.createElement("textarea");
+ Object.assign(textarea.style, {
+ position: "absolute",
+ top: "0",
+ left: "0",
+ boxSizing: "content-box",
+ border: "1px solid black",
+ padding: "5px",
+ width: "300px",
+ height: "150px",
+ fontFamily: "monospace",
+ fontSize: "14px",
+ lineHeight: "18px",
+ letterSpacing: "normal",
+ ...css,
+ });
+ document.body.appendChild(textarea);
+ try {
+ return callback(textarea);
+ } finally {
+ textarea.remove();
+ }
+}
+
+module("Unit | Lib | caret-position", function () {
+ test("returns finite coordinates across a range of inputs", function (assert) {
+ const cases = [
+ { value: "", pos: 0 },
+ { value: "a", pos: 1 },
+ { value: "hello world", pos: 5 },
+ { value: "line one\nline two\nline three", pos: 20 },
+ { value: "trailing spaces ", pos: 18 },
+ { value: "html <b> & </b> chars", pos: 8 },
+ { value: "café résumé 😀 🎉", pos: 7 },
+ { value: "x".repeat(400), pos: 250 },
+ ];
+
+ for (const { value, pos } of cases) {
+ withTextarea({}, (textarea) => {
+ textarea.value = value;
+ const { left, top } = caretCoordinates(textarea, { pos });
+
+ assert.true(
+ Number.isFinite(left),
+ `left is a finite number for ${JSON.stringify(value)}@${pos}`
+ );
+ assert.true(
+ Number.isFinite(top),
+ `top is a finite number for ${JSON.stringify(value)}@${pos}`
+ );
+ });
+ }
+ });
+
+ test("caret moves rightward as its position advances along a line", function (assert) {
+ withTextarea({}, (textarea) => {
+ textarea.value = "hello world";
+
+ const positions = [0, 3, 6, 9];
+ const coords = positions.map((pos) =>
+ caretCoordinates(textarea, { pos })
+ );
+
+ for (let i = 1; i < coords.length; i++) {
+ assert.true(
+ coords[i].left > coords[i - 1].left,
+ `left increases from pos ${positions[i - 1]} to ${positions[i]}`
+ );
+ assert.strictEqual(
+ coords[i].top,
+ coords[0].top,
+ `top is unchanged within the same line at pos ${positions[i]}`
+ );
+ }
+ });
+ });
+
+ test("caret drops down and returns to the left margin across lines", function (assert) {
+ withTextarea({}, (textarea) => {
+ // indices: a a a a a \n b b
+ textarea.value = "aaaaa\nbb";
+
+ const endOfLine1 = caretCoordinates(textarea, { pos: 5 });
+ const startOfLine2 = caretCoordinates(textarea, { pos: 6 });
+
+ assert.true(
+ startOfLine2.top > endOfLine1.top,
+ "caret on line 2 is below caret on line 1"
+ );
+ assert.true(
+ startOfLine2.left < endOfLine1.left,
+ "caret at the start of line 2 is left of the end of line 1"
+ );
+ });
+ });
+
+ test("a soft-wrapped long line pushes the caret down", function (assert) {
+ withTextarea({ width: "120px" }, (textarea) => {
+ textarea.value =
+ "one two three four five six seven eight nine ten eleven twelve";
+
+ const start = caretCoordinates(textarea, { pos: 0 });
+ const end = caretCoordinates(textarea, { pos: textarea.value.length });
+
+ assert.true(
+ end.top > start.top,
+ "caret at the end of a wrapped line sits below the start"
+ );
+ });
+ });
+
+ test("falls back to selectionStart when no pos is given", function (assert) {
+ withTextarea({}, (textarea) => {
+ textarea.value = "hello world";
+ textarea.setSelectionRange(6, 6);
+
+ const fromSelection = caretCoordinates(textarea);
+ const fromExplicitPos = caretCoordinates(textarea, { pos: 6 });
+
+ assert.strictEqual(
+ fromSelection.left,
+ fromExplicitPos.left,
+ "left matches the explicit position"
+ );
+ assert.strictEqual(
+ fromSelection.top,
+ fromExplicitPos.top,
+ "top matches the explicit position"
+ );
+ });
+ });
+
+ test("accounts for a virtual character from options.key", function (assert) {
+ withTextarea({}, (textarea) => {
+ textarea.value = "ab";
+
+ const { left, top } = caretCoordinates(textarea, { pos: 1, key: "X" });
+
+ assert.true(Number.isFinite(left), "left is finite with a virtual key");
+ assert.true(Number.isFinite(top), "top is finite with a virtual key");
+ });
+ });
+
+ test("returns finite coordinates in RTL", function (assert) {
+ document.documentElement.classList.add("rtl");
+ try {
+ withTextarea({}, (textarea) => {
+ textarea.value = "مرحبا بالعالم\nsecond line";
+
+ const { left, top } = caretCoordinates(textarea, { pos: 4 });
+
+ assert.true(Number.isFinite(left), "left is finite in RTL");
+ assert.true(Number.isFinite(top), "top is finite in RTL");
+ });
+ } finally {
+ document.documentElement.classList.remove("rtl");
+ }
+ });
+});