Skip to content

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

DEV: resolve deprecation of jquery autocomplete (#35897)

Kelv54c3f5e0fe7a
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 7465d6c05fe..80005e3f52d 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2747,9 +2747,6 @@ en:
glimmer_post_stream_mode: "Control whether the new 'glimmer' post stream implementation is used. 'auto' will enable automatically once all your themes and plugins are ready."
glimmer_post_stream_mode_auto_groups: "Enable the new 'glimmer' post stream implementation in 'auto' mode for the specified user groups."
deactivate_widgets_rendering: "Disable the legacy widgets rendering engine. This will disable all widgets that have not been updated to Glimmer components, it will also force the Glimmer Post Stream to be enabled unconditionally regardless of the value of the `glimmer_post_stream_mode` setting."
- floatkit_autocomplete_composer: "Enable the Floatkit-based autocomplete menu in composer. This is an UI enhancement that will replace the current JQuery-based autocomplete menu."
- floatkit_autocomplete_input_fields: "Enable the Floatkit-based autocomplete menu for input fields in full page search and group selector fields. This is a UI enhancement that will replace the current jQuery-based autocomplete menu."
- floatkit_autocomplete_chat_composer: "Enable the Floatkit-based autocomplete menu in chat composer. This is a UI enhancement that will replace the current jQuery-based autocomplete menu."
experimental_form_templates: "Enable the form templates feature. Manage the templates at <a href='%{base_path}/admin/customize/form-templates'>Customize / Templates</a>."
show_preview_for_form_templates: "Enable the preview for form templates feature"
lazy_load_categories_groups: "Lazy load category information only for users of these groups. This improves performance on sites with many categories."
diff --git a/frontend/discourse/app/instance-initializers/jquery-plugins.js b/frontend/discourse/app/instance-initializers/jquery-plugins.js
index 44f9bf44058..fd878df2fba 100644
--- a/frontend/discourse/app/instance-initializers/jquery-plugins.js
+++ b/frontend/discourse/app/instance-initializers/jquery-plugins.js
@@ -1,5 +1,4 @@
import $ from "jquery";
-import autocomplete from "discourse/lib/autocomplete";
import { caret, caretPosition } from "discourse/lib/caret-position";
let jqueryPluginsConfigured = false;
@@ -10,9 +9,6 @@ export default {
return;
}
- // Initialize the autocomplete tool
- $.fn.autocomplete = autocomplete;
-
// Initialize caretPosition
$.fn.caret = caret;
$.fn.caretPosition = caretPosition;
diff --git a/frontend/discourse/app/lib/autocomplete.js b/frontend/discourse/app/lib/autocomplete.js
deleted file mode 100644
index f7a1a42ab4a..00000000000
--- a/frontend/discourse/app/lib/autocomplete.js
+++ /dev/null
@@ -1,836 +0,0 @@
-import { cancel } from "@ember/runloop";
-import { createPopper } from "@popperjs/core";
-import $ from "jquery";
-import discourseDebounce from "discourse/lib/debounce";
-import deprecated from "discourse/lib/deprecated";
-import { INPUT_DELAY, isTesting } from "discourse/lib/environment";
-import { iconHTML } from "discourse/lib/icon-library";
-import discourseLater from "discourse/lib/later";
-import { isDocumentRTL } from "discourse/lib/text-direction";
-import { TextareaAutocompleteHandler } from "discourse/lib/textarea-text-manipulation";
-import Site from "discourse/models/site";
-
-/**
- This is a jQuery plugin to support autocompleting values in our text fields.
-
- @module $.fn.autocomplete
-**/
-
-export const SKIP = "skip";
-export const CANCELLED_STATUS = "__CANCELLED";
-
-const ALLOWED_LETTERS_REGEXP = /[\s[{(/+]/;
-let _autoCompletePopper, _inputTimeout;
-let skipDeprecationWarningInTests = false;
-
-const keys = {
- backSpace: 8,
- tab: 9,
- enter: 13,
- shift: 16,
- ctrl: 17,
- alt: 18,
- esc: 27,
- space: 32,
- leftWindows: 91,
- rightWindows: 92,
- pageUp: 33,
- pageDown: 34,
- end: 35,
- home: 36,
- leftArrow: 37,
- upArrow: 38,
- rightArrow: 39,
- downArrow: 40,
- insert: 45,
- deleteKey: 46,
- zero: 48,
- a: 65,
- z: 90,
-};
-
-/**
- * Disables deprecation warning output during QUnit tests.
- *
- * USE ONLY FOR TESTING PURPOSES
- */
-export function disableDeprecationWarningInTests() {
- skipDeprecationWarningInTests = true;
-}
-
-/**
- * Enables deprecation warning output during QUnit tests.
- *
- * USE ONLY FOR TESTING PURPOSES
- */
-export function enableDeprecationWarningInTests() {
- skipDeprecationWarningInTests = false;
-}
-
-export default function (options) {
- if (!isTesting() || !skipDeprecationWarningInTests) {
- deprecated(
- "$.fn.autocomplete is deprecated and will be removed in a future release. Please use the DMultiSelect component or the DAutocomplete modifier instead.",
- {
- id: "discourse.jquery-autocomplete",
- since: "3.6.0.beta1-dev",
- url: "https://meta.discourse.org/t/385527",
- }
- );
- }
-
- if (this.length === 0) {
- return;
- }
-
- if (options === "destroy" || options.updateData) {
- cancel(_inputTimeout);
-
- this[0].removeEventListener("keydown", handleKeyDown);
- this[0].removeEventListener("keyup", handleKeyUp);
- this[0].removeEventListener("paste", handlePaste);
- this[0].removeEventListener("click", closeAutocomplete);
- window.removeEventListener("click", closeAutocomplete);
-
- if (options === "destroy") {
- return;
- }
- }
-
- if (options && options.cancel && this.data("closeAutocomplete")) {
- this.data("closeAutocomplete")();
- return this;
- }
-
- if (this.length !== 1) {
- if (window.console) {
- window.console.log(
- "WARNING: passed multiple elements to $.autocomplete, skipping."
- );
- if (window.Error) {
- window.console.log(new window.Error().stack);
- }
- }
- return this;
- }
-
- if (options && typeof options.preserveKey === "undefined") {
- options.preserveKey = true;
- }
-
- const disabled = options && options.disabled;
- let wrap = null;
- let autocompleteOptions = null;
- let selectedOption = null;
- let completeStart = null;
- let me = this;
- let div = null;
- let scrollElement = null;
- let prevTerm = null;
-
- // By default, when the autocomplete popup is rendered it has the
- // first suggestion 'selected', and pressing enter key inserts
- // the first suggestion into the input box.
- // If you want to stop that behavior, i.e. have the popup renders
- // with no suggestions selected, set the `autoSelectFirstSuggestion`
- // option to false.
- // With this option set to false, users will have to select
- // a suggestion via the up/down arrow keys and then press enter
- // to insert it.
- if (!("autoSelectFirstSuggestion" in options)) {
- options.autoSelectFirstSuggestion = true;
- }
-
- // input is handled differently
- const isInput = me[0].tagName === "INPUT" && !options.treatAsTextarea;
- let inputSelectedItems = [];
-
- /** @type {AutocompleteHandler} */
- options.textHandler ??= new TextareaAutocompleteHandler(me[0]);
-
- function handlePaste() {
- discourseLater(() => me.trigger("keydown"), 50);
- }
-
- function scrollAutocomplete() {
- if (!scrollElement && !div) {
- return;
- }
-
- const scrollingElement =
- scrollElement?.length > 0 ? scrollElement[0] : div[0];
- const selectedElement = getSelectedOptionElement();
- const selectedElementTop = selectedElement.offsetTop;
- const selectedElementBottom =
- selectedElementTop + selectedElement.clientHeight;
-
- // the top of the item is above the top of the scrollElement, so scroll UP
- if (selectedElementTop <= scrollingElement.scrollTop) {
- scrollingElement.scrollTo(0, selectedElementTop);
-
- // the bottom of the item is below the bottom of the div, so scroll DOWN
- } else if (
- selectedElementBottom >=
- scrollingElement.scrollTop + scrollingElement.clientHeight
- ) {
- scrollingElement.scrollTo(
- 0,
- scrollingElement.scrollTop + selectedElement.clientHeight
- );
- }
- }
-
- function closeAutocomplete() {
- _autoCompletePopper?.destroy();
- options.onClose?.();
- div?.hide()?.remove();
- div = null;
- scrollElement = null;
- completeStart = null;
- autocompleteOptions = null;
- prevTerm = null;
- _autoCompletePopper = null;
- }
-
- function addInputSelectedItem(item, triggerChangeCallback) {
- let transformed,
- transformedItem = item;
-
- if (options.transformComplete) {
- transformedItem = options.transformComplete(transformedItem);
- }
- // dump what we have in single mode, just in case
- if (options.single) {
- inputSelectedItems = [];
- }
- transformed = Array.isArray(transformedItem)
- ? transformedItem
- : [transformedItem || item];
-
- const divs = transformed.map((itm) => {
- let d = $(
- `<div class="item"><span>${itm}<a class="remove" href>${iconHTML(
- "xmark"
- )}</a></span></div>`
- );
- const $parent = me.parent();
- const prev = $parent.find(".item:last");
-
- if (prev.length === 0) {
- me.parent().prepend(d);
- } else {
- prev.after(d);
- }
-
- inputSelectedItems.push(itm);
- return d[0];
- });
-
- if (options.onChangeItems && triggerChangeCallback) {
- options.onChangeItems(inputSelectedItems);
- }
-
- $(divs)
- .find("a")
- .click(function () {
- closeAutocomplete();
- inputSelectedItems.splice(
- $.inArray(transformedItem, inputSelectedItems),
- 1
- );
- $(this).parent().parent().remove();
- if (options.single) {
- me.show();
- }
- if (options.onChangeItems) {
- options.onChangeItems(inputSelectedItems);
- }
- return false;
- });
- }
-
- let completeTerm = async function (term, event) {
- if (term) {
- if (isInput) {
- me.val("");
- if (options.single) {
- me.hide();
- }
- addInputSelectedItem(term, true);
- } else {
- if (options.transformComplete) {
- term = await options.transformComplete(term, event);
- }
-
- if (term) {
- // After completion is done our position for completeStart may have
- // drifted. This can happen if the TEXTAREA changed out-of-band between
- // the time autocomplete was first displayed and the time of completion
- // Specifically this may happen due to uploads which inject a placeholder
- // which is later replaced with a different length string.
- let pos = await guessCompletePosition({ completeTerm: true });
- let completeEnd = null;
- if (
- pos.completeStart !== undefined &&
- pos.completeEnd !== undefined
- ) {
- completeStart = pos.completeStart;
- completeEnd = pos.completeEnd;
- } else {
- completeStart = completeEnd =
- options.textHandler.getCaretPosition();
- }
-
- options.textHandler.replaceTerm(
- completeStart,
- completeEnd,
- (options.preserveKey ? options.key || "" : "") + term
- );
-
- if (options && options.afterComplete) {
- options.afterComplete(options.textHandler.getValue(), event);
- }
- }
- }
- }
- closeAutocomplete();
- };
-
- if (isInput) {
- const width = Math.max(this.width(), 200);
-
- if (options.updateData) {
- wrap = this.parent();
- wrap.find(".item").remove();
- me.show();
- } else {
- wrap = this.wrap(
- "<div class='ac-wrap clearfix" + (disabled ? " disabled" : "") + "'/>"
- ).parent();
-
- if (!options.fullWidthWrap) {
- wrap.width(width);
- }
- }
-
- if (options.single && !options.width) {
- this.attr("class", `${this.attr("class")} fullwidth-input`);
- } else if (options.width) {
- this.css("width", options.width);
- }
-
- this.attr(
- "name",
- options.updateData ? this.attr("name") : this.attr("name") + "-renamed"
- );
-
- let vals = this.val().split(",");
- vals.forEach((x) => {
- if (x !== "") {
- if (options.reverseTransform) {
- x = options.reverseTransform(x);
- }
- if (options.single) {
- me.hide();
- }
- addInputSelectedItem(x, false);
- }
- });
-
- if (options.items) {
- options.items.forEach((item) => {
- if (options.single) {
- me.hide();
- }
- addInputSelectedItem(item, true);
- });
- }
-
- this.val("");
- completeStart = 0;
- wrap.click(function () {
- this.focus();
- return true;
- });
- }
-
- function markSelected() {
- getLinks().removeClass("selected");
- return $(getSelectedOptionElement()).addClass("selected");
- }
-
- function getSelectedOptionElement() {
- return getLinks()[selectedOption];
- }
-
- function getLinks() {
- return div.find("li a");
- }
-
- // a sane spot below cursor
- const BELOW = -32;
-
- function renderAutocomplete() {
- if (div) {
- div.hide().remove();
- }
- if (autocompleteOptions.length === 0) {
- return;
- }
-
- div = $(options.template({ options: autocompleteOptions }));
-
- let ul = div.find("ul");
- if (options.autoSelectFirstSuggestion) {
- selectedOption = 0;
- markSelected();
- } else {
- selectedOption = -1;
- }
- ul.find("li").click(async function ({ originalEvent }) {
- // this is required to prevent the default behaviour when clicking on a <a> tag
- originalEvent.preventDefault();
- originalEvent.stopPropagation();
-
- selectedOption = ul.find("li").index(this);
- // hack for Gboard, see meta.discourse.org/t/-/187009/24
- if (autocompleteOptions == null) {
- const opts = { ...options, _gboard_hack_force_lookup: true };
- const data = await dataSource(prevTerm, opts);
- if (data) {
- updateAutoComplete(data);
- await completeTerm(
- autocompleteOptions[selectedOption],
- originalEvent
- );
- if (!options.single) {
- me.focus();
- }
- }
- } else {
- await completeTerm(autocompleteOptions[selectedOption], originalEvent);
- if (!options.single) {
- me.focus();
- }
- }
- });
-
- if (options.appendSelector) {
- me.parents(options.appendSelector).append(div);
- } else {
- me.parent().append(div);
- }
-
- if (options.scrollElementSelector) {
- scrollElement = div.find(options.scrollElementSelector);
- }
-
- if (options.onRender) {
- options.onRender(autocompleteOptions);
- }
-
- if (isInput || options.treatAsTextarea) {
- _autoCompletePopper && _autoCompletePopper.destroy();
- _autoCompletePopper = createPopper(me[0], div[0], {
- placement: `${Site.currentProp("mobileView") ? "top" : "bottom"}-start`,
- modifiers: [
- {
- name: "offset",
- options: {
- offset: [0, 2],
- },
- },
- ],
- });
- return _autoCompletePopper;
- }
-
- let vOffset = 0;
- let pos = options.textHandler.getCaretCoords(completeStart);
-
- if (options.treatAsTextarea) {
- vOffset = -32;
- }
-
- if (!isInput && !options.treatAsTextarea) {
- vOffset = div.height();
-
- const spaceOutside =
- window.innerHeight -
- me.outerHeight() -
- $("header.d-header").innerHeight();
-
- if (spaceOutside < vOffset && vOffset > pos.top) {
- vOffset = BELOW;
- }
-
- if (Site.currentProp("mobileView") && me.height() / 2 >= pos.top) {
- vOffset = BELOW;
- }
- }
-
- const mePos = me.position();
-
- let left;
- if (isDocumentRTL()) {
- left = mePos.left + pos.left - div.width();
- } else {
- let hOffset = 10;
- if (Site.currentProp("mobileView")) {
- if (me.width() / 2 <= pos.left) {
- hOffset = -div.width();
- }
- }
- left = mePos.left + pos.left + hOffset;
- }
- if (left < 0) {
- left = 0;
- }
-
- const offsetTop = me.offset().top;
- const borderTop = parseInt(me.css("border-top-width"), 10) || 0;
- if (mePos.top + pos.top + borderTop - vOffset + offsetTop < 30) {
- vOffset = BELOW;
- }
-
- div.css({
- position: "absolute",
- top: `${mePos.top + pos.top - vOffset + borderTop}px`,
- left: `${left}px`,
- });
- }
-
- function dataSource(term, opts) {
- const force = opts._gboard_hack_force_lookup;
- if (force) {
- delete opts._gboard_hack_force_lookup;
- }
- if (prevTerm === term && !force) {
- return SKIP;
- }
-
- prevTerm = term;
- if (
- (term.length !== 0 && term.trim().length === 0) ||
- // close unless the caret is at the end of a word, like #line|<-
- options.textHandler
- .getValue()
- [options.textHandler.getCaretPosition()]?.trim()
- ) {
- closeAutocomplete();
- return null;
- } else {
- return opts.dataSource(term);
- }
- }
-
- function updateAutoComplete(r) {
- if (completeStart === null || r === SKIP) {
- return;
- }
-
- if (r && r.then && typeof r.then === "function") {
- if (div) {
- div.hide().remove();
- }
- r.then(updateAutoComplete);
- return;
- }
-
- // Allow an update method to cancel. This allows us to debounce
- // promises without leaking
- if (r === CANCELLED_STATUS) {
- return;
- }
-
- autocompleteOptions = r;
- if (!r || r.length === 0) {
- closeAutocomplete();
- } else {
- renderAutocomplete();
- }
- }
-
- // chain to allow multiples
- const oldClose = me.data("closeAutocomplete");
- me.data("closeAutocomplete", function () {
- if (oldClose) {
- oldClose();
- }
- closeAutocomplete();
- });
-
- async function checkTriggerRule(_opts) {
- const opts = {
- ..._opts,
- inCodeBlock: () => options.textHandler.inCodeBlock(),
- };
- const shouldTrigger = await options.triggerRule?.(me[0], opts);
- return shouldTrigger ?? true;
- }
-
- async function handleKeyUp(e) {
- if (options.debounced) {
- discourseDebounce(this, performAutocomplete, e, INPUT_DELAY);
- } else {
- await performAutocomplete(e);
- }
- }
-
- async function performAutocomplete(e) {
- if ([keys.esc, keys.enter].includes(e.which)) {
- return true;
- }
-
- let cp = options.textHandler.getCaretPosition();
- const key = options.textHandler.getValue()[cp - 1];
-
- if (options.key) {
- if (options.onKeyUp && key !== options.key) {
- let match = options.onKeyUp(options.textHandler.getValue(), cp);
-
- if (match && (await checkTriggerRule())) {
- completeStart = cp - match[0].length;
- let term = match[0].substring(1, match[0].length);
- updateAutoComplete(dataSource(term, options));
- }
- }
- }
-
- if (completeStart === null && cp > 0) {
- if (key === options.key) {
- let prevChar = options.textHandler.getValue().charAt(cp - 2);
- if (
- (!prevChar || ALLOWED_LETTERS_REGEXP.test(prevChar)) &&
- (await checkTriggerRule())
- ) {
- completeStart = cp - 1;
- updateAutoComplete(dataSource("", options));
- }
- }
- } else if (completeStart !== null) {
- let term = options.textHandler
- .getValue()
- .substring(completeStart + (options.key ? 1 : 0), cp);
- if (
- !options.key ||
- options.textHandler.getValue()[completeStart] === options.key
- ) {
- updateAutoComplete(dataSource(term, options));
- } else {
- closeAutocomplete();
- }
- }
- }
-
- async function guessCompletePosition(opts) {
- let prev, stopFound, term;
- let prevIsGood = true;
- let backSpace = opts?.backSpace;
- let completeTermOption = opts?.completeTerm;
- let caretPos = options.textHandler.getCaretPosition();
-
- if (backSpace) {
- caretPos -= 1;
- }
-
- let start = null;
- let end = null;
-
- let initialCaretPos = caretPos;
-
- while (prevIsGood && caretPos >= 0) {
- caretPos -= 1;
- prev = options.textHandler.getValue()[caretPos];
-
- stopFound = prev === options.key;
-
- if (stopFound) {
- prev = options.textHandler.getValue()[caretPos - 1];
- const shouldTrigger = await checkTriggerRule({ backSpace });
-
- if (
- shouldTrigger &&
- (prev === undefined || ALLOWED_LETTERS_REGEXP.test(prev))
- ) {
- start = caretPos;
- term = options.textHandler
- .getValue()
- .substring(caretPos + 1, initialCaretPos);
- end = caretPos + term.length;
- break;
- }
- }
- prevIsGood = !/\s/.test(prev);
- if (completeTermOption) {
- prevIsGood ||= prev === " ";
- }
- }
-
- return { completeStart: start, completeEnd: end, term };
- }
-
- async function handleKeyDown(e) {
- let i, term, total, userToComplete;
- let cp;
-
- if (e.ctrlKey || e.altKey || e.metaKey) {
- return true;
- }
-
- if (options.allowAny) {
- // saves us wiring up a change event as well
-
- cancel(_inputTimeout);
- _inputTimeout = discourseLater(() => {
- if (inputSelectedItems.length === 0) {
- inputSelectedItems.push("");
- }
-
- const value = options.textHandler.getValue();
- if (typeof inputSelectedItems[0] === "string" && value.length > 0) {
- inputSelectedItems.pop();
- inputSelectedItems.push(value);
- if (options.onChangeItems) {
- options.onChangeItems(inputSelectedItems);
- }
- }
- }, 50);
- }
-
- if (!options.key) {
- completeStart = 0;
- }
-
- if (e.which === keys.shift) {
- return;
- }
-
- if (completeStart === null && e.which === keys.backSpace && options.key) {
- let position = await guessCompletePosition({ backSpace: true });
- completeStart = position.completeStart;
-
- if (position.completeEnd) {
- updateAutoComplete(dataSource(position.term, options));
- return true;
- }
- }
-
- // ESC
- if (e.which === keys.esc) {
- if (div !== null) {
- closeAutocomplete();
- e.preventDefault();
- e.stopImmediatePropagation();
- return false;
- }
- return true;
- }
-
- if (completeStart !== null) {
- cp = options.textHandler.getCaretPosition();
-
- // allow people to right arrow out of completion
- if (
- e.which === keys.rightArrow &&
- options.textHandler.getValue()[cp] === " "
- ) {
- closeAutocomplete();
- return true;
- }
-
- // If we've backspaced past the beginning, cancel unless no key
- if (cp <= completeStart && options.key) {
- closeAutocomplete();
- return true;
- }
-
- // Keyboard codes! So 80's.
- switch (e.which) {
- case keys.tab:
- case keys.enter:
- if (!autocompleteOptions) {
- closeAutocomplete();
- return true;
- }
- if (
- selectedOption >= 0 &&
- (userToComplete = autocompleteOptions[selectedOption])
- ) {
- await completeTerm(userToComplete, e);
- } else {
- // We're cancelling it, really.
- return true;
- }
-
- e.stopImmediatePropagation();
- e.preventDefault();
- return false;
- case keys.upArrow:
- selectedOption = selectedOption - 1;
- if (selectedOption < 0) {
- selectedOption = 0;
- }
- markSelected();
- scrollAutocomplete();
- e.preventDefault();
- return false;
- case keys.downArrow:
- if (!autocompleteOptions) {
- closeAutocomplete();
- return true;
- }
-
- total = autocompleteOptions.length;
- selectedOption = selectedOption + 1;
- if (selectedOption >= total) {
- selectedOption = total - 1;
- }
- if (selectedOption < 0) {
- selectedOption = 0;
- }
- markSelected();
- scrollAutocomplete();
- e.preventDefault();
- return false;
- case keys.backSpace:
- autocompleteOptions = null;
- cp--;
-
- if (cp < 0) {
- closeAutocomplete();
-
- if (isInput) {
- i = wrap.find("a:last");
- if (i) {
- i.click();
- }
- }
- return true;
- }
-
- term = options.textHandler
- .getValue()
- .substring(completeStart + (options.key ? 1 : 0), cp);
-
- if (completeStart === cp && term === options.key) {
- closeAutocomplete();
- }
-
- updateAutoComplete(dataSource(term, options));
- return true;
- default:
- autocompleteOptions = null;
- return true;
- }
- }
- }
-
- window.addEventListener("click", closeAutocomplete);
- this[0].addEventListener("click", closeAutocomplete);
- this[0].addEventListener("paste", handlePaste);
- this[0].addEventListener("keyup", handleKeyUp);
- this[0].addEventListener("keydown", handleKeyDown);
-
- return this;
-}
diff --git a/frontend/discourse/app/services/deprecation-warning-handler.js b/frontend/discourse/app/services/deprecation-warning-handler.js
index c68e0dcd174..b6f119a9554 100644
--- a/frontend/discourse/app/services/deprecation-warning-handler.js
+++ b/frontend/discourse/app/services/deprecation-warning-handler.js
@@ -35,7 +35,6 @@ export const CRITICAL_DEPRECATIONS = [
"discourse.script-tag-discourse-plugin",
"discourse.post-stream-widget-overrides",
"discourse.widgets-end-of-life",
- "discourse.jquery-autocomplete",
];
const REPLACEMENT_URLS = {};
diff --git a/frontend/discourse/tests/unit/lib/autocomplete-test.js b/frontend/discourse/tests/unit/lib/autocomplete-test.js
deleted file mode 100644
index b38a39b6aba..00000000000
--- a/frontend/discourse/tests/unit/lib/autocomplete-test.js
+++ /dev/null
@@ -1,247 +0,0 @@
-import { triggerKeyEvent } from "@ember/test-helpers";
-import { setupTest } from "ember-qunit";
-import $ from "jquery";
-import { module, test } from "qunit";
-import {
- disableDeprecationWarningInTests,
- enableDeprecationWarningInTests,
-} from "discourse/lib/autocomplete";
-import { escapeExpression, setCaretPosition } from "discourse/lib/utilities";
-import {
- simulateKey,
- simulateKeys,
-} from "discourse/tests/helpers/qunit-helpers";
-
-module("Unit | Utility | autocomplete", function (hooks) {
- setupTest(hooks);
-
- let _element;
-
- const template = (context) => `
- <div id='ac-testing' class='autocomplete ac-test'>
- <ul>
- ${context.options.map((option) => `<li><a href>${escapeExpression(option)}</a></li>`).join("")}
- </ul>
- </div>
- `;
-
- function textArea() {
- _element = document.createElement("TEXTAREA");
- document.getElementById("ember-testing").appendChild(_element);
- return _element;
- }
-
- hooks.beforeEach(() => {
- disableDeprecationWarningInTests();
- });
-
- hooks.afterEach(() => {
- if (!_element) {
- return;
- }
- const $e = $(_element);
- $e.autocomplete({ cancel: true });
- $e.autocomplete("destroy");
- _element.remove();
-
- enableDeprecationWarningInTests();
- });
-
- test("Autocomplete can complete really short terms correctly", async function (assert) {
- const element = textArea();
-
- $(element).autocomplete({
- key: ":",
- template,
- transformComplete: (e) => e.slice(1),
- dataSource: () => [":sad:"],
- });
-
- await simulateKeys(element, "a :)\r");
-
- assert.dom(element).hasValue("a :sad: ");
- assert.strictEqual(element.selectionStart, 8);
- assert.strictEqual(element.selectionEnd, 8);
- });
-
- test("Autocomplete can account for cursor drift correctly", async function (assert) {
- const element = textArea();
- const db = ["test1", "test2"];
-
- $(element).autocomplete({
- key: "@",
- template,
- dataSource: (term) => db.filter((word) => word.includes(term)),
- });
-
- await simulateKeys(element, "@\r");
-
- assert.dom(element).hasValue("@test1 ");
- assert.strictEqual(element.selectionStart, 7);
- assert.strictEqual(element.selectionEnd, 7);
-
- await simulateKeys(element, "@2\r");
-
- assert.dom(element).hasValue("@test1 @test2 ");
- assert.strictEqual(element.selectionStart, 14);
- assert.strictEqual(element.selectionEnd, 14);
-
- await setCaretPosition(element, 6);
- await simulateKeys(element, "\b\b");
-
- assert.dom(element).hasValue("@tes @test2 ");
-
- await simulateKey(element, "\r");
-
- assert.dom(element).hasValue("@test1 @test2 ");
- assert.strictEqual(element.selectionStart, 7);
- assert.strictEqual(element.selectionEnd, 7);
-
- // ensures that deleting last space triggers autocomplete
- await setCaretPosition(element, element.value.length);
- await simulateKey(element, "\b");
-
- assert.dom("#ac-testing ul li").exists({ count: 1 });
-
- await simulateKey(element, "\b");
-
- assert.dom("#ac-testing ul li").exists({ count: 2 });
-
- // close autocomplete
- await simulateKey(element, "\r");
-
- // does not trigger by mistake at the start
- element.value = "test";
-
- await setCaretPosition(element, element.value.length);
- await simulateKey(element, "\b");
-
- assert.dom("#ac-testing ul li").exists({ count: 0 });
- });
-
- test("Autocomplete can handle spaces", async function (assert) {
- const element = textArea();
- const db = [
- { username: "jd", name: "jane dale" },
- { username: "jb", name: "jack black" },
- ];
-
- $(element).autocomplete({
- key: "@",
- template,
- dataSource: (term) =>
- db
- .filter(
- (user) => user.username.includes(term) || user.name.includes(term)
- )
- .map((user) => user.username),
- });
-
- await simulateKeys(element, "@jane d\r");
-
- assert.dom(element).hasValue("@jd ");
- });
-
- test("Autocomplete can render on @", async function (assert) {
- const element = textArea();
-
- $(element).autocomplete({
- key: "@",
- template,
- dataSource: () => ["test1", "test2"],
- });
-
- await simulateKey(element, "@");
-
- assert.dom("#ac-testing ul li").exists({ count: 2 });
- assert.dom("#ac-testing li a.selected").exists({ count: 1 });
- assert.dom("#ac-testing li a.selected").hasText("test1");
- });
-
- test("Autocomplete doesn't reset undo history", async function (assert) {
- const element = textArea();
-
- $(element).autocomplete({
- key: "@",
- template,
- dataSource: () => ["test1", "test2"],
- });
-
- await simulateKeys(element, "@t\r");
-
- assert.strictEqual(element.value, "@test1 ");
-
- document.execCommand("undo");
-
- assert.strictEqual(element.value, "@t");
- });
-
- test("Autocomplete does not trigger with right-left arrow keys", async function (assert) {
- const element = textArea();
-
- $(element).autocomplete({
- key: ":",
- template,
- transformComplete: (e) => e.slice(1),
- dataSource: () => [":smile:"],
- });
-
- await simulateKeys(element, ":smi\t");
-
- assert.dom(element).hasValue(":smile: ");
-
- async function triggerArrowKey(key) {
- await triggerKeyEvent(element, "keydown", key, { code: key });
- await triggerKeyEvent(element, "keyup", key, { code: key });
-
- const pos = element.selectionStart;
- const direction = key === "ArrowLeft" ? -1 : 1;
- element.setSelectionRange(pos + 1 * direction, pos + 1 * direction);
- }
-
- await triggerArrowKey("ArrowLeft");
- await triggerArrowKey("ArrowLeft");
- await triggerArrowKey("ArrowLeft");
- await triggerArrowKey("ArrowRight");
-
- assert.strictEqual(element.selectionStart, 6);
-
- // This is passing, but it's a false positive
- // triggerArrowKey isn't triggering the event the autocomplete listens to
- assert.dom("#ac-testing").doesNotExist();
-
- await triggerArrowKey("ArrowRight");
- await simulateKey(element, "\b");
-
- assert.dom(element).hasValue(":smile ");
- assert.dom("#ac-testing").exists();
- });
-
- test("Autocomplete respects triggerRule on continued typing", async function (assert) {
- const element = textArea();
-
- $(element).autocomplete({
- key: ":",
- template,
- transformComplete: (e) => e.slice(1),
- dataSource: () => [":smile:"],
- triggerRule: async (_, { inCodeBlock }) => !(await inCodeBlock()),
- });
-
- await simulateKeys(element, "```\n:");
-
- assert.dom("#ac-testing").doesNotExist();
-
- await simulateKey(element, "smil");
-
- assert.dom("#ac-testing").doesNotExist();
-
- await simulateKey(element, "\n```\n:");
-
- assert.dom("#ac-testing").exists();
-
- await simulateKey(element, "smil");
-
- assert.dom("#ac-testing").exists();
- });
-});