Skip to content

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

PERF: Use insertText more efficiently in `replaceText` (#28880)

David Taylora7cd2207048b
diff --git a/app/assets/javascripts/discourse/app/mixins/textarea-text-manipulation.js b/app/assets/javascripts/discourse/app/mixins/textarea-text-manipulation.js
index fe1122aa7f5..2914a049b9f 100644
--- a/app/assets/javascripts/discourse/app/mixins/textarea-text-manipulation.js
+++ b/app/assets/javascripts/discourse/app/mixins/textarea-text-manipulation.js
@@ -149,16 +149,21 @@ export default Mixin.create({
});
if (opts.index && opts.regex) {
- let i = -1;
- const newValue = val.replace(opts.regex, (match) => {
- i++;
- return i === opts.index ? newVal : match;
- });
+ if (!opts.regex.global) {
+ throw new Error("Regex must be global");
+ }
+
+ const regex = new RegExp(opts.regex);
+ let match;
+ for (let i = 0; i <= opts.index; i++) {
+ match = regex.exec(val);
+ }
- this._insertAt(0, val.length, newValue);
+ if (match) {
+ this._insertAt(match.index, match.index + match[0].length, newVal);
+ }
} else {
- const replacedValue = val.replace(oldVal, newVal);
- this._insertAt(0, val.length, replacedValue);
+ this._insertAt(needleStart, needleStart + oldVal.length, newVal);
}
if (
@@ -332,7 +337,11 @@ export default Mixin.create({
_insertAt(start, end, text) {
this._textarea.setSelectionRange(start, end);
this._textarea.focus();
- document.execCommand("insertText", false, text);
+ if (start !== end && text === "") {
+ document.execCommand("delete", false);
+ } else {
+ document.execCommand("insertText", false, text);
+ }
},
extractTable(text) {