Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): remove the jQuery autocomplete

Elian Doranfc06d1af7a61
diff --git a/apps/client/package.json b/apps/client/package.json
index 9c7d858995..3f2eadcbc9 100644
--- a/apps/client/package.json
+++ b/apps/client/package.json
@@ -37,7 +37,6 @@
"@univerjs/preset-sheets-note": "1.0.2",
"@univerjs/preset-sheets-sort": "1.0.2",
"@univerjs/presets": "1.0.2",
- "autocomplete.js": "0.38.1",
"bootstrap": "5.3.8",
"boxicons": "2.1.4",
"clsx": "2.1.1",
diff --git a/apps/client/src/components/entrypoints.ts b/apps/client/src/components/entrypoints.ts
index 4aa6a9bb2e..366a40c71a 100644
--- a/apps/client/src/components/entrypoints.ts
+++ b/apps/client/src/components/entrypoints.ts
@@ -213,20 +213,6 @@ export default class Entrypoints extends Component {
toastService.showMessage(t("entrypoints.note-executed"));
}
- hideAllPopups() {
- if (utils.isDesktop()) {
- $(".aa-input").autocomplete("close");
- }
- }
-
- noteSwitchedEvent() {
- this.hideAllPopups();
- }
-
- activeContextChangedEvent() {
- this.hideAllPopups();
- }
-
async forceSaveRevisionCommand() {
const noteId = appContext.tabManager.getActiveContextNoteId();
diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.ts
index 93b7d21c75..c06838626e 100644
--- a/apps/client/src/components/tab_manager.ts
+++ b/apps/client/src/components/tab_manager.ts
@@ -539,12 +539,6 @@ export default class TabManager extends Component {
}
}
- // close dangling autocompletes after closing the tab
- const $autocompleteEl = $(".aa-input");
- if ("autocomplete" in $autocompleteEl) {
- $autocompleteEl.autocomplete("close");
- }
-
// close dangling tooltips
$("body > div.tooltip").remove();
diff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.ts
index 082be7539b..27015b7120 100644
--- a/apps/client/src/desktop.ts
+++ b/apps/client/src/desktop.ts
@@ -1,5 +1,3 @@
-import "autocomplete.js/index_jquery.js";
-
import type { ElectronWindowApi } from "@triliumnext/commons";
import appContext, { type CommandNames } from "./components/app_context.js";
@@ -10,7 +8,6 @@ import { setupClipboardImageEmbed } from "./services/clipboard_image_embed.js";
import glob from "./services/glob.js";
import { t } from "./services/i18n.js";
import { syncNativeWindowWithTheme } from "./services/native_window.js";
-import noteAutocompleteService from "./services/note_autocomplete.js";
import noteTooltipService from "./services/note_tooltip.js";
import { onEffectiveThemeStyleChange, setBackgroundEffectsSuspended } from "./services/theme.js";
import toastService from "./services/toast.js";
@@ -54,8 +51,6 @@ if (utils.isElectron()) {
noteTooltipService.setupGlobalTooltip();
-noteAutocompleteService.init();
-
setupClipboardImageEmbed();
if (utils.isElectron()) {
diff --git a/apps/client/src/index.ts b/apps/client/src/index.ts
index 02461000e5..f405f55223 100644
--- a/apps/client/src/index.ts
+++ b/apps/client/src/index.ts
@@ -47,7 +47,7 @@ async function initJQuery() {
window.$ = $;
window.jQuery = $;
- // Polyfill removed jQuery methods for autocomplete.js compatibility
+ // Polyfills the jQuery methods jQuery 4 removed, which Fancytree still calls.
($ as any).isArray = Array.isArray;
($ as any).isFunction = function(obj: any) { return typeof obj === 'function'; };
($ as any).isPlainObject = function(obj: any) {
diff --git a/apps/client/src/mobile.ts b/apps/client/src/mobile.ts
index 45b8c8f519..2ef5bfd9e6 100644
--- a/apps/client/src/mobile.ts
+++ b/apps/client/src/mobile.ts
@@ -1,17 +1,12 @@
-import "autocomplete.js/index_jquery.js";
-
import appContext from "./components/app_context.js";
import { setupClipboardImageEmbed } from "./services/clipboard_image_embed.js";
import glob from "./services/glob.js";
-import noteAutocompleteService from "./services/note_autocomplete.js";
import { preloadCommonNoteTypes } from "./widgets/note_types.js";
glob.setupGlobs();
await appContext.earlyInit();
-noteAutocompleteService.init();
-
setupClipboardImageEmbed();
// A dynamic import is required for layouts since they initialize components which require translations.
diff --git a/apps/client/src/runtime.ts b/apps/client/src/runtime.ts
index cab174a76d..7dad033aca 100644
--- a/apps/client/src/runtime.ts
+++ b/apps/client/src/runtime.ts
@@ -8,7 +8,7 @@ async function loadBootstrap() {
}
}
-// Polyfill removed jQuery methods for autocomplete.js compatibility
+// Polyfills the jQuery methods jQuery 4 removed, which Fancytree still calls.
($ as any).isArray = Array.isArray;
($ as any).isFunction = function(obj: any) { return typeof obj === 'function'; };
($ as any).isPlainObject = function(obj: any) {
diff --git a/apps/client/src/services/attribute_autocomplete.spec.ts b/apps/client/src/services/attribute_autocomplete.spec.ts
deleted file mode 100644
index 39ff928844..0000000000
--- a/apps/client/src/services/attribute_autocomplete.spec.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import $ from "jquery";
-
-import server from "./server.js";
-import attributeAutocomplete from "./attribute_autocomplete.js";
-
-type Dataset = {
- displayKey: string;
- cache: boolean;
- source: (term: string, cb: (rows: object[]) => void) => void | Promise<void>;
-};
-
-// Captures the most recent `$el.autocomplete(config, datasets)` init call so tests
-// can invoke the registered `source` callback directly and exercise its body.
-let lastDatasets: Dataset[] | undefined;
-let autocompleteSpy: ReturnType<typeof vi.fn>;
-
-function registerAutocompleteStub() {
- lastDatasets = undefined;
- autocompleteSpy = vi.fn(function (this: JQuery, config: object | string, datasets?: Dataset[]) {
- if (typeof config === "object" && Array.isArray(datasets)) {
- lastDatasets = datasets;
- }
- return this;
- });
- ($.fn as any).autocomplete = autocompleteSpy;
-}
-
-function makeEl(extraClass = "") {
- return $(`<input class="${extraClass}" />`);
-}
-
-describe("attribute_autocomplete", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- registerAutocompleteStub();
- });
-
- describe("initAttributeNameAutocomplete", () => {
- it("initializes autocomplete, wires the name source and the readonly opened handler", async () => {
- const $el = makeEl();
- server.get = vi.fn(async () => ["foo", "bar"]) as typeof server.get;
-
- attributeAutocomplete.initAttributeNameAutocomplete({
- $el,
- attributeType: "label",
- open: true
- });
-
- // init form (config + datasets) followed by the "open" command.
- expect(autocompleteSpy).toHaveBeenCalledWith(
- expect.objectContaining({ openOnFocus: true, minLength: 0 }),
- expect.any(Array)
- );
- expect(autocompleteSpy).toHaveBeenCalledWith("open");
- expect(lastDatasets?.[0].displayKey).toBe("name");
- expect(lastDatasets?.[0].cache).toBe(false);
-
- // Exercise the source callback with a static attributeType.
- const cb = vi.fn();
- await lastDatasets![0].source("co lor", cb);
- expect(server.get).toHaveBeenCalledWith("attribute-names/?type=label&query=co%20lor");
- expect(cb).toHaveBeenCalledWith([{ name: "foo" }, { name: "bar" }]);
-
- // readonly element -> opened handler closes the autocomplete.
- $el.attr("readonly", "readonly");
- $el.trigger("autocomplete:opened");
- expect(autocompleteSpy).toHaveBeenCalledWith("close");
- });
-
- it("resolves a function attributeType and does not close when not readonly; skips open when open=false", async () => {
- const $el = makeEl();
- server.get = vi.fn(async () => ["x"]) as typeof server.get;
-
- attributeAutocomplete.initAttributeNameAutocomplete({
- $el,
- attributeType: () => "relation",
- open: false
- });
-
- // open=false -> the "open" command is never issued.
- expect(autocompleteSpy).not.toHaveBeenCalledWith("open");
-
- const cb = vi.fn();
- await lastDatasets![0].source("q", cb);
- expect(server.get).toHaveBeenCalledWith("attribute-names/?type=relation&query=q");
-
- // not readonly -> opened handler does NOT close.
- $el.trigger("autocomplete:opened");
- expect(autocompleteSpy).not.toHaveBeenCalledWith("close");
- });
-
- it("skips re-initialization when the element already has the aa-input class", () => {
- const $el = makeEl("aa-input");
-
- attributeAutocomplete.initAttributeNameAutocomplete({
- $el,
- attributeType: "label",
- open: false
- });
-
- // Already initialized -> no init call (config+datasets) was made.
- expect(lastDatasets).toBeUndefined();
- expect(autocompleteSpy).not.toHaveBeenCalled();
- });
- });
-
- describe("initLabelValueAutocomplete", () => {
- it("returns early without a nameCallback (empty attribute name)", async () => {
- const $el = makeEl();
- server.get = vi.fn(async () => ["v"]) as typeof server.get;
-
- await attributeAutocomplete.initLabelValueAutocomplete({ $el, open: true });
-
- expect(server.get).not.toHaveBeenCalled();
- expect(autocompleteSpy).not.toHaveBeenCalled();
- });
-
- it("returns early when the nameCallback yields a blank name", async () => {
- const $el = makeEl();
- server.get = vi.fn(async () => ["v"]) as typeof server.get;
-
- await attributeAutocomplete.initLabelValueAutocomplete({
- $el,
- open: true,
- nameCallback: () => " "
- });
-
- expect(server.get).not.toHaveBeenCalled();
- });
-
- it("returns early when no attribute values are returned", async () => {
- const $el = makeEl();
- server.get = vi.fn(async () => []) as typeof server.get;
-
- await attributeAutocomplete.initLabelValueAutocomplete({
- $el,
- open: true,
- nameCallback: () => "color"
- });
-
- expect(server.get).toHaveBeenCalledWith("attribute-values/color");
- expect(autocompleteSpy).not.toHaveBeenCalledWith(expect.any(Object), expect.any(Array));
- });
-
- it("destroys an existing instance, inits the value source, filters case-insensitively and closes on readonly", async () => {
- const $el = makeEl("aa-input");
- server.get = vi.fn(async () => ["Apple", "Banana", "Cherry"]) as typeof server.get;
-
- await attributeAutocomplete.initLabelValueAutocomplete({
- $el,
- open: true,
- nameCallback: () => "my color"
- });
-
- // aa-input present -> destroy was called before re-init.
- expect(autocompleteSpy).toHaveBeenCalledWith("destroy");
- expect(server.get).toHaveBeenCalledWith("attribute-values/my%20color");
- expect(autocompleteSpy).toHaveBeenCalledWith(
- expect.objectContaining({ openOnFocus: false }),
- expect.any(Array)
- );
- expect(autocompleteSpy).toHaveBeenCalledWith("open");
- expect(lastDatasets?.[0].displayKey).toBe("value");
-
- // source filters by lower-cased substring ("AN" -> "an" matches only "Banana").
- const cb = vi.fn();
- await lastDatasets![0].source("AN", cb);
- expect(cb).toHaveBeenCalledWith([{ value: "Banana" }]);
-
- // readonly -> opened handler closes.
- $el.attr("readonly", "readonly");
- $el.trigger("autocomplete:opened");
- expect(autocompleteSpy).toHaveBeenCalledWith("close");
- });
-
- it("does not destroy when not aa-input, does not open when open=false, and keeps the dropdown open when not readonly", async () => {
- const $el = makeEl();
- server.get = vi.fn(async () => ["a"]) as typeof server.get;
-
- await attributeAutocomplete.initLabelValueAutocomplete({
- $el,
- open: false,
- nameCallback: () => "tag"
- });
-
- expect(autocompleteSpy).not.toHaveBeenCalledWith("destroy");
- expect(autocompleteSpy).not.toHaveBeenCalledWith("open");
-
- // not readonly -> opened handler does not close.
- $el.trigger("autocomplete:opened");
- expect(autocompleteSpy).not.toHaveBeenCalledWith("close");
- });
- });
-});
diff --git a/apps/client/src/services/attribute_autocomplete.ts b/apps/client/src/services/attribute_autocomplete.ts
deleted file mode 100644
index 22d99d49b8..0000000000
--- a/apps/client/src/services/attribute_autocomplete.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import type { AttributeType } from "../entities/fattribute.js";
-import server from "./server.js";
-
-interface InitOptions {
- $el: JQuery<HTMLElement>;
- attributeType?: AttributeType | (() => AttributeType);
- open: boolean;
- nameCallback?: () => string;
-}
-
-/**
- * @param $el - element on which to init autocomplete
- * @param attributeType - "relation" or "label" or callback providing one of those values as a type of autocompleted attributes
- * @param open - should the autocomplete be opened after init?
- */
-function initAttributeNameAutocomplete({ $el, attributeType, open }: InitOptions) {
- if (!$el.hasClass("aa-input")) {
- $el.autocomplete(
- {
- appendTo: document.querySelector("body"),
- hint: false,
- openOnFocus: true,
- minLength: 0,
- tabAutocomplete: false
- },
- [
- {
- displayKey: "name",
- // disabling cache is important here because otherwise cache can stay intact when switching between attribute type which will lead to autocomplete displaying attribute names for incorrect attribute type
- cache: false,
- source: async (term, cb) => {
- const type = typeof attributeType === "function" ? attributeType() : attributeType;
-
- const names = await server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(term)}`);
- const result = names.map((name) => ({ name }));
-
- cb(result);
- }
- }
- ]
- );
-
- $el.on("autocomplete:opened", () => {
- if ($el.attr("readonly")) {
- $el.autocomplete("close");
- }
- });
- }
-
- if (open) {
- $el.autocomplete("open");
- }
-}
-
-async function initLabelValueAutocomplete({ $el, open, nameCallback }: InitOptions) {
- if ($el.hasClass("aa-input")) {
- // we reinit every time because autocomplete seems to have a bug where it retains state from last
- // open even though the value was reset
- $el.autocomplete("destroy");
- }
-
- let attributeName = "";
- if (nameCallback) {
- attributeName = nameCallback();
- }
-
- if (attributeName.trim() === "") {
- return;
- }
-
- const attributeValues = (await server.get<string[]>(`attribute-values/${encodeURIComponent(attributeName)}`)).map((attribute) => ({ value: attribute }));
-
- if (attributeValues.length === 0) {
- return;
- }
-
- $el.autocomplete(
- {
- appendTo: document.querySelector("body"),
- hint: false,
- openOnFocus: false, // handled manually
- minLength: 0,
- tabAutocomplete: false
- },
- [
- {
- displayKey: "value",
- cache: false,
- source: async function (term, cb) {
- term = term.toLowerCase();
-
- const filtered = attributeValues.filter((attr) => attr.value.toLowerCase().includes(term));
-
- cb(filtered);
- }
- }
- ]
- );
-
- $el.on("autocomplete:opened", () => {
- if ($el.attr("readonly")) {
- $el.autocomplete("close");
- }
- });
-
- if (open) {
- $el.autocomplete("open");
- }
-}
-
-export default {
- initAttributeNameAutocomplete,
- initLabelValueAutocomplete
-};
diff --git a/apps/client/src/services/dialog.spec.ts b/apps/client/src/services/dialog.spec.ts
index 5f89439e3e..123b533928 100644
--- a/apps/client/src/services/dialog.spec.ts
+++ b/apps/client/src/services/dialog.spec.ts
@@ -177,34 +177,6 @@ describe("dialog service", () => {
expect(document.activeElement).toBe(input);
});
-
- it("closes the autocomplete dropdown on hide", async () => {
- const $dialog = makeDialog();
- await openDialog($dialog, false);
-
- // `"autocomplete" in $autocompleteEl` is true for a jQuery object only if the
- // autocomplete plugin is registered. Register a stub on the jQuery prototype so
- // the branch is taken and the plugin is invoked.
- const autocomplete = vi.fn();
- ($.fn as any).autocomplete = autocomplete;
-
- $dialog.trigger("hidden.bs.modal");
-
- expect(autocomplete).toHaveBeenCalledWith("close");
-
- delete ($.fn as any).autocomplete;
- });
-
- it("skips closing autocomplete when the plugin is not registered", async () => {
- const $dialog = makeDialog();
- await openDialog($dialog, false);
-
- // Ensure no autocomplete plugin is present so the `in` check is false.
- delete ($.fn as any).autocomplete;
-
- // Should not throw.
- expect(() => $dialog.trigger("hidden.bs.modal")).not.toThrow();
- });
});
describe("lifting a dialog above what is already open", () => {
diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.ts
index d91bbf2d54..725b39831d 100644
--- a/apps/client/src/services/dialog.ts
+++ b/apps/client/src/services/dialog.ts
@@ -52,11 +52,6 @@ export async function openDialog($dialog: JQuery<HTMLElement>, closeActDialog =
$dialog.on("hidden.bs.modal", () => {
sendDialogHome($dialog[0]);
- const $autocompleteEl = $(".aa-input");
- if ("autocomplete" in $autocompleteEl) {
- $autocompleteEl.autocomplete("close");
- }
-
if (!glob.activeDialog || glob.activeDialog === $dialog) {
focusSavedElement();
}
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index 377147e714..9657e452b3 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -29,7 +29,6 @@ export interface Suggestion extends Partial<AutocompleteResult> {
}
export interface Options {
- container?: HTMLElement | null;
fastSearch?: boolean;
allowCreatingNotes?: boolean;
allowJumpToSearchNotes?: boolean;
@@ -267,28 +266,6 @@ function buildCreateNoteTitle(term: string, target: InboxTargetResponse | null)
return t("note_autocomplete.create-note-into", { term: escapeHtml(term), parentTitle: escapeHtml(target.title) });
}
-// #region Stubs
-// TODO: Stubs that keep the existing callers compiling and running while the implementation is
-// rebuilt. None of them searches for or suggests anything.
-
-function initNoteAutocomplete($el: JQuery<HTMLElement>, _options?: Options) {
- return $el;
-}
-
-/** Installs the `$.fn` helpers `NoteAutocomplete` and the dialogs call, as no-ops. */
-function init() {
- $.fn.getSelectedNotePath = () => "";
- $.fn.getSelectedNoteId = () => null;
- $.fn.setSelectedNotePath = () => {};
- $.fn.getSelectedExternalLink = () => "";
- $.fn.setSelectedExternalLink = () => {};
- $.fn.setNote = async () => {};
-}
-
-// #endregion
-
export default {
- autocompleteSourceForCKEditor,
- initNoteAutocomplete,
- init
+ autocompleteSourceForCKEditor
};
diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.ts
deleted file mode 100644
index 801ed2b956..0000000000
--- a/apps/client/src/services/note_autocomplete_bak.spec.ts
+++ /dev/null
@@ -1,286 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import $ from "jquery";
-
-// --- Mocks (hoisted above imports) ---
-
-const {
- triggerCommand, getActiveContextNoteId, getActiveContext, chooseNoteType, createNote,
- getInboxNotePath, getInboxTarget, translate, logError
-} = vi.hoisted(() => ({
- triggerCommand: vi.fn(),
- getActiveContextNoteId: vi.fn<() => string | null>(() => "activeNote"),
- getActiveContext: vi.fn<() => any>(() => ({ hoistedNoteId: "hoisted" })),
- chooseNoteType: vi.fn(),
- createNote: vi.fn(),
- getInboxNotePath: vi.fn<() => Promise<string | undefined>>(async () => "root/inbox"),
- getInboxTarget: vi.fn<() => Promise<unknown>>(
- async () => ({ kind: "inbox", noteId: "inb", title: "Inbox" })
- ),
- // i18next is never initialised here, so the real `t` returns undefined. Echoing the key
- // keeps the label assertions about which string is chosen rather than about its English.
- translate: vi.fn((key: string, _opts?: Record<string, unknown>) => key),
- logError: vi.fn()
-}));
-
-vi.mock("../components/app_context.js", () => ({
- default: {
- triggerCommand,
- tabManager: {
- getActiveContextNoteId,
- getActiveContext
- }
- }
-}));
-
-vi.mock("./note_create.js", () => ({
- default: { chooseNoteType, createNote }
-}));
-
-vi.mock("./date_notes.js", () => ({
- default: { getInboxNotePath, getInboxTarget }
-}));
-
-vi.mock("./i18n.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("./i18n.js")>()),
- t: translate
-}));
-
-// Narrows the blanket ws mock from test/setup.ts to a spy, so what the module reports can be asserted.
-vi.mock("./ws.js", () => ({
- default: {
- subscribeToMessages() {},
- async waitForMaxKnownEntityChangeId() {}
- },
- subscribeToMessages() {},
- unsubscribeToMessage() {},
- async waitForMaxKnownEntityChangeId() {},
- logError
-}));
-
-// Imports AFTER vi.mock calls.
-import server from "./server.js";
-import froca from "./froca.js";
-import { buildNote } from "../test/easy-froca.js";
-import noteAutocomplete from "./note_autocomplete_bak.js";
-
-type Dataset = {
- displayKey: string;
- cache: boolean;
- source: (term: string, cb: (rows: any[]) => void) => void;
- templates: { suggestion: (s: any) => string };
-};
-
-// Captures the last `$el.autocomplete(config, datasets)` init call and records
-// every command invocation so tests can drive the registered callbacks.
-let lastConfig: AutoCompleteConfig | undefined;
-let lastDatasets: Dataset[] | undefined;
-let autocompleteCalls: any[][];
-const stored = new Map<HTMLElement, string>();
-
-function registerAutocompleteStub() {
- lastConfig = undefined;
- lastDatasets = undefined;
- autocompleteCalls = [];
- ($.fn as any).autocomplete = vi.fn(function (this: JQuery, config: any, datasets?: Dataset[]) {
- autocompleteCalls.push([config, datasets]);
- if (typeof config === "object" && Array.isArray(datasets)) {
- lastConfig = config;
- lastDatasets = datasets;
- }
- // emulate the "val" getter/setter so fullTextSearch can read it back
- if (config === "val") {
- const el = this[0];
- if (datasets === undefined) {
- return stored.get(el) as any;
- }
- stored.set(el, datasets as unknown as string);
- }
- return this;
- });
-}
-
-function makeEl(extraClass = "") {
- return $(`<input class="${extraClass}" />`);
-}
-
-function lastCommandWith(arg: any) {
- return autocompleteCalls.some((c) => c[0] === arg && c[1] === undefined);
-}
-
-describe("$.fn jQuery extensions (init)", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- registerAutocompleteStub();
- server.get = vi.fn(async () => []) as typeof server.get;
- noteAutocomplete.init();
- });
-
- it("getSelectedNotePath returns empty when input value is blank", () => {
- const $el = makeEl();
- $el.val("");
- $el.attr("data-note-path", "root/x");
- expect($el.getSelectedNotePath()).toBe("");
- });
-
- it("getSelectedNotePath returns the stored path when there is a value", () => {
- const $el = makeEl();
- $el.val("Some title");
- $el.attr("data-note-path", "root/x");
- expect($el.getSelectedNotePath()).toBe("root/x");
- });
-
- it("getSelectedNoteId returns null when no path, last segment otherwise", () => {
- const $el = makeEl();
- $el.val("");
- expect($el.getSelectedNoteId()).toBeNull();
-
- $el.val("title");
- $el.attr("data-note-path", "root/parent/child");
- expect($el.getSelectedNoteId()).toBe("child");
- });
-
- it("setSelectedNotePath toggles the go-to button and sets href", () => {
- const $group = $(`<div class="input-group"><input class="note-autocomplete-input" /><a class="go-to-selected-note-button"></a></div>`);
- const $el = $group.find("input");
- $el.setSelectedNotePath("root/abc");
- const $btn = $group.find(".go-to-selected-note-button");
- expect($btn.hasClass("disabled")).toBe(false);
- expect($btn.attr("href")).toBe("#root/abc");
-
- $el.setSelectedNotePath("");
- expect($group.find(".go-to-selected-note-button").hasClass("disabled")).toBe(true);
- });
-
- it("getSelectedExternalLink mirrors getSelectedNotePath blank/value behaviour", () => {
- const $el = makeEl();
- $el.val("");
- $el.attr("data-external-link", "https://x");
- expect($el.getSelectedExternalLink()).toBe("");
-
- $el.val("title");
- expect($el.getSelectedExternalLink()).toBe("https://x");
- });
-
- it("setSelectedExternalLink stores the link and disables the go-to button", () => {
- const $group = $(`<div class="input-group"><input /><a class="go-to-selected-note-button"></a></div>`);
- const $el = $group.find("input");
- $el.setSelectedExternalLink("https://example.com");
- expect($el.attr("data-external-link")).toBe("https://example.com");
- expect($group.find(".go-to-selected-note-button").hasClass("disabled")).toBe(true);
- });
-
- it("setNote loads the note title from froca and sets the value + path", async () => {
- const note = buildNote({ title: "Loaded note" });
- const $el = makeEl();
- await $el.setNote(note.noteId);
- expect($el.val()).toBe("Loaded note");
- expect($el.attr("data-note-path")).toBe(note.noteId);
- });
-
- it("setNote clears the value when noteId is falsy", async () => {
- const $el = makeEl();
- $el.val("previous");
- await $el.setNote(null as any);
- expect($el.val()).toBe("");
- expect($el.attr("data-note-path")).toBe("");
- });
-});
-
-describe("initNoteAutocomplete wiring", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- registerAutocompleteStub();
- server.get = vi.fn(async () => []) as typeof server.get;
- noteAutocomplete.init();
- });
-
- it("returns early and detaches the noteselected listener if already initialized", () => {
- const $el = makeEl("note-autocomplete-input");
- const result = noteAutocomplete.initNoteAutocomplete($el);
- // no autocomplete init call was made (config + datasets form)
- expect(lastDatasets).toBeUndefined();
- expect(result).toBe($el);
- });
-
- // Issue #5669: autocomplete.js empties its suggestion list only a tick after closing
- // it, and its Enter handler selects from the closed-but-not-yet-emptied dropdown, so
- // a fast second Enter right after a selection would consume a stale suggestion row.
- // Plain Enter must never reach the library while the dropdown is closed (the library
- // keeps aria-expanded in sync with its open/close state).
- it("does not deliver a plain Enter to autocomplete while the dropdown is closed", () => {
- const $el = makeEl();
- noteAutocomplete.initNoteAutocomplete($el);
- // simulates the library's own keydown handler, which is bound after init
- const autocompleteKeydown = vi.fn((event: JQuery.KeyDownEvent) => event.preventDefault());
- $el.on("keydown.aa", autocompleteKeydown);
-
- // aria-expanded not yet set (before the first open), then explicitly closed
- for (const expanded of [undefined, "false"]) {
- if (expanded) {
- $el.attr("aria-expanded", expanded);
- }
- const event = $.Event("keydown", { key: "Enter" });
- $el.trigger(event);
- // the default action (form submission) must stay intact
- expect(event.isDefaultPrevented()).toBe(false);
- }
- expect(autocompleteKeydown).not.toHaveBeenCalled();
- });
-
- it("delivers a plain Enter to autocomplete while the dropdown is open", () => {
- const $el = makeEl();
- noteAutocomplete.initNoteAutocomplete($el);
- const autocompleteKeydown = vi.fn();
- $el.on("keydown.aa", autocompleteKeydown);
-
- $el.attr("aria-expanded", "true");
- $el.trigger($.Event("keydown", { key: "Enter" }));
-
- expect(autocompleteKeydown).toHaveBeenCalledOnce();
- });
-
- it("leaves modified Enter presses alone even when the dropdown is closed", () => {
- const $el = makeEl();
- noteAutocomplete.initNoteAutocomplete($el);
- const autocompleteKeydown = vi.fn();
- $el.on("keydown.aa", autocompleteKeydown);
-
- $el.attr("aria-expanded", "false");
- $el.trigger($.Event("keydown", { key: "Enter", ctrlKey: true }));
-
- expect(autocompleteKeydown).toHaveBeenCalledOnce();
- });
-
-});
-
-describe("autocomplete:selected handler", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getActiveContext.mockReturnValue({ hoistedNoteId: "hoisted" });
- registerAutocompleteStub();
- server.get = vi.fn(async () => []) as typeof server.get;
- noteAutocomplete.init();
- });
-
- function initWithSelected() {
- const $el = makeEl();
- const handlers: Record<string, any> = {};
- noteAutocomplete.initNoteAutocomplete($el);
- ["autocomplete:externallinkselected", "autocomplete:noteselected"].forEach((evt) => {
- $el.on(evt, (_e: any, s: any) => (handlers[evt] = s));
- });
- return { $el, handlers };
- }
-
- function fireSelected($el: JQuery, suggestion: any) {
- ($el as any).trigger("autocomplete:selected", suggestion);
- return new Promise((r) => setTimeout(r, 0));
- }
-
- it("handles a plain note selection", async () => {
- const { $el, handlers } = initWithSelected();
- await fireSelected($el, { action: undefined, notePath: "root/n", noteTitle: "N" });
- expect($el.attr("data-note-path")).toBe("root/n");
- expect(handlers["autocomplete:noteselected"]).toBeDefined();
- });
-});
diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.ts
deleted file mode 100644
index f98f625351..0000000000
--- a/apps/client/src/services/note_autocomplete_bak.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import froca from "./froca.js";
-import { createSearchScheduler, getNoteSuggestions, type Options, type Suggestion } from "./note_autocomplete.js";
-
-// this key needs to have this value, so it's hit by the tooltip
-const SELECTED_NOTE_PATH_KEY = "data-note-path";
-
-const SELECTED_EXTERNAL_LINK_KEY = "data-external-link";
-
-async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void, options: Options = {}) {
- cb(await getNoteSuggestions(term, { allowCreatingNotes: options.allowCreatingNotes }));
-}
-
-function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
- if ($el.hasClass("note-autocomplete-input")) {
- // clear any event listener added in previous invocation of this function
- $el.off("autocomplete:noteselected");
-
- return $el;
- }
-
- options = options || {};
-
- const scheduleSearch = createSearchScheduler();
-
- $el.addClass("note-autocomplete-input");
-
- $el.on("keydown", (event) => {
- const isPlainEnter = event.key === "Enter"
- && !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey;
- // autocomplete.js empties its suggestion list only a tick after closing it, and its
- // Enter handler selects from the closed-but-not-yet-emptied dropdown — so a fast second
- // Enter after a selection consumes a stale row (#5669). Enter must never select from a
- // dropdown the user cannot see; the library keeps aria-expanded in sync with open/close.
- if (isPlainEnter && $el.attr("aria-expanded") !== "true") {
- // Stop autocomplete from seeing the keypress, but leave form submission intact.
- event.stopImmediatePropagation();
- }
- });
-
- $el.autocomplete(
- {
- appendTo: document.querySelector("body"),
- hint: false,
- autoselect: true,
- // openOnFocus has to be false, otherwise re-focus (after return from note type chooser dialog) forces
- // re-querying of the autocomplete source which then changes the currently selected suggestion
- openOnFocus: false,
- minLength: 0,
- tabAutocomplete: false
- },
- [
- {
- source: (term, cb) => {
- scheduleSearch(() => {
- // Returned so the scheduler holds the next search until this one settles.
- return autocompleteSource(term, cb, options);
- });
- },
- displayKey: "notePathTitle",
- // we can't cache identical searches because notes can be created / renamed, new recent notes can be added
- cache: false
- }
- ]
- );
-
- //@ts-expect-error The `autocomplete:selected` handler takes an extra `suggestion` argument that jQuery's `.on()` typings don't model.
- $el.on("autocomplete:selected", async (event: Event, suggestion: Suggestion) => {
- $el.setSelectedNotePath(suggestion.notePath);
- $el.setSelectedExternalLink(null);
-
- $el.autocomplete("val", suggestion.noteTitle);
-
- $el.autocomplete("close");
-
- $el.trigger("autocomplete:noteselected", [suggestion]);
- });
-
- // clear any event listener added in previous invocation of this function
- $el.off("autocomplete:noteselected");
-
- return $el;
-}
-
-function init() {
- $.fn.getSelectedNotePath = function () {
- if (!String($(this).val())?.trim()) {
- return "";
- }
- return $(this).attr(SELECTED_NOTE_PATH_KEY);
-
- };
-
- $.fn.getSelectedNoteId = function () {
- const $el = $(this as unknown as HTMLElement);
- const notePath = $el.getSelectedNotePath();
- if (!notePath) {
- return null;
- }
-
- const chunks = notePath.split("/");
-
- /* v8 ignore next -- String.split always yields at least one element, so the `: null` branch is unreachable */
- return chunks.length >= 1 ? chunks[chunks.length - 1] : null;
- };
-
- $.fn.setSelectedNotePath = function (notePath) {
- notePath = notePath || "";
- $(this).attr(SELECTED_NOTE_PATH_KEY, notePath);
- $(this).closest(".input-group").find(".go-to-selected-note-button").toggleClass("disabled", !notePath.trim()).attr("href", `#${notePath}`); // we also set href here so tooltip can be displayed
- };
-
- $.fn.getSelectedExternalLink = function () {
- if (!String($(this).val())?.trim()) {
- return "";
- }
- return $(this).attr(SELECTED_EXTERNAL_LINK_KEY);
-
- };
-
- $.fn.setSelectedExternalLink = function (externalLink: string | null) {
- $(this).attr(SELECTED_EXTERNAL_LINK_KEY, externalLink);
- $(this).closest(".input-group").find(".go-to-selected-note-button").toggleClass("disabled", true);
- };
-
- $.fn.setNote = async function (noteId) {
- const note = noteId ? await froca.getNote(noteId, true) : null;
-
- $(this)
- .val(note ? note.title : "")
- .setSelectedNotePath(noteId);
- };
-}
-
-export default {
- initNoteAutocomplete,
- init
-};
diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.ts
index e3df790d09..2a8a8a5184 100644
--- a/apps/client/src/types.d.ts
+++ b/apps/client/src/types.d.ts
@@ -7,7 +7,6 @@ import type { PrintReport } from "./print";
import type { lint } from "./services/eslint";
import type { Froca } from "./services/froca-interface";
import { Library } from "./services/library_loader";
-import { Suggestion } from "./services/note_autocomplete";
import server from "./services/server";
import utils from "./services/utils";
@@ -87,42 +86,6 @@ declare global {
"note-load-progress": CustomEvent<{ progress: number }>;
}
- interface AutoCompleteConfig {
- appendTo?: HTMLElement | null;
- hint?: boolean;
- openOnFocus?: boolean;
- minLength?: number;
- tabAutocomplete?: boolean;
- autoselect?: boolean;
- dropdownMenuContainer?: HTMLElement;
- debug?: boolean;
- }
-
- type AutoCompleteCallback = (values: AutoCompleteArg[]) => void;
-
- interface AutoCompleteArg {
- name?: string;
- value?: string;
- notePathTitle?: string;
- displayKey?: "name" | "value" | "notePathTitle";
- cache?: boolean;
- source?: (term: string, cb: AutoCompleteCallback) => void,
- templates?: {
- suggestion: (suggestion: Suggestion) => string | undefined
- }
- }
-
- interface JQuery {
- autocomplete: (action?: "close" | "open" | "destroy" | "val" | AutoCompleteConfig, args?: AutoCompleteArg[] | string) => JQuery<HTMLElement>;
-
- getSelectedNotePath(): string | undefined;
- getSelectedNoteId(): string | null;
- setSelectedNotePath(notePath: string | null | undefined);
- getSelectedExternalLink(): string | undefined;
- setSelectedExternalLink(externalLink: string | null | undefined);
- setNote(noteId: string);
- }
-
var logError: (message: string, e?: unknown) => void;
var logInfo: (message: string) => void;
var glob: CustomGlobals;
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx
index 82bb3cb224..305a6460de 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx
@@ -387,6 +387,46 @@ describe("the rows the form carries", () => {
});
});
+describe("dismissing the attribute detail popup", () => {
+ afterEach(() => {
+ document.body.replaceChildren();
+ });
+
+ it("stays open for a press in the note list of its target field, and closes for one elsewhere", async () => {
+ const { AttributeDetail } = await import("./attribute_detail");
+ const onDismiss = vi.fn();
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <AttributeDetail
+ opts={opts({ attribute: { type: "relation", name: "author", value: "" } })}
+ onDismiss={onDismiss}
+ onCancel={() => {}}
+ />
+ </ParentComponent.Provider>,
+ host
+ );
+ });
+
+ // `NoteAutocomplete` portals its list to the body, outside the popup.
+ const noteList = document.createElement("div");
+ noteList.className = "dropdown-menu note-autocomplete-menu";
+ const row = document.createElement("div");
+ noteList.appendChild(row);
+ document.body.appendChild(noteList);
+
+ row.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+ expect(onDismiss).not.toHaveBeenCalled();
+
+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+ expect(onDismiss).toHaveBeenCalledOnce();
+
+ render(null, host);
+ });
+});
+
const NO_OFFSET = { top: 0, left: 0 };
function opts(overrides: Partial<AttributeDetailOpts>): AttributeDetailOpts {
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
index 9f1a9080a0..74b5a9da0a 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
@@ -257,7 +257,7 @@ export function AttributeDetail({ opts, currentNoteId, onDismiss, onCancel, ...f
// the popup down before the created note could be filled in. The type menu belongs
// to it too: it is portaled to the body, as every dropdown is, so a
// press on one of its items lands outside the popup element.
- || e.target.closest(`${AUTOCOMPLETE_DROPDOWN_SELECTOR}, .algolia-autocomplete, #context-menu-container, .modal, .modal-backdrop, .attr-input-label-type`)) {
+ || e.target.closest(`${AUTOCOMPLETE_DROPDOWN_SELECTOR}, .note-autocomplete-menu, #context-menu-container, .modal, .modal-backdrop, .attr-input-label-type`)) {
return;
}
onDismiss();
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
index 2914f03cbc..117cf9a3c1 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx
@@ -1,4 +1,3 @@
-import $ from "jquery";
import { render } from "preact";
import { useState } from "preact/hooks";
import { act } from "preact/test-utils";
@@ -71,10 +70,7 @@ vi.mock("../../../services/clipboard_ext", async (importOriginal) => ({
copyTextWithToast: (...args: unknown[]) => copied(...args)
}));
-// A promoted text field suggests what other notes hold under its name, asked for through the Algolia
-// jQuery plugin and answered by the server. Neither is loaded here.
-type PluggedIn = { autocomplete(...args: unknown[]): PluggedIn };
-($.fn as unknown as PluggedIn).autocomplete = function (this: PluggedIn) { return this; };
+// A promoted text field asks the server for the values other notes hold under its name.
server.get = (async () => []) as unknown as typeof server.get;
/** What a marker click hands the handler, and what the pane reads the note out of. */
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index 7ecfc9dd87..a9fa2d7a86 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -263,6 +263,10 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
// Discards responses of queries that were superseded while in flight.
const latestQuery = useRef(0);
+ // The Enter handler reads the list as last rendered, so a pick holds Enter off that list until the
+ // next render: a second Enter in the same task then reaches the host's form (issue #5669).
+ const pickedSinceRender = useRef(false);
+ pickedSinceRender.current = false;
// Names the entries so the field can point at the highlighted one: focus stays in the box, so
// that pointer is all a screen reader has to go on.
const itemIdPrefix = useUniqueName("autocomplete-item");
@@ -325,6 +329,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
return;
}
+ pickedSinceRender.current = true;
onPick(item);
if (keepOpenOnPick) {
// Nothing is highlighted until the refreshed entries arrive, so Enter cannot take twice
@@ -353,7 +358,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
break;
case "Enter":
- if (isShown && activeIndex >= 0) {
+ if (isShown && activeIndex >= 0 && !pickedSinceRender.current) {
// Consume the key so it does not also reach the surrounding form or dialog.
e.preventDefault();
e.stopPropagation();
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.css b/apps/client/src/widgets/react/NoteAutocomplete.css
index 524692ab5d..283b4e2223 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.css
+++ b/apps/client/src/widgets/react/NoteAutocomplete.css
@@ -54,8 +54,7 @@
}
/*
- * The lists in a host's container, such as the empty tab's and Jump to Note's, in the markup of
- * `autocomplete.js`. It set the `display` inline.
+ * The lists in a host's container, such as the empty tab's and Jump to Note's.
*/
span.aa-dropdown-menu,
span.aa-dropdown-menu .aa-suggestions {
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 552af60ac4..c10a0b1970 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -42,11 +42,11 @@ function buttonClasses(container: HTMLElement) {
}
describe("NoteAutocomplete", () => {
- it("renders the input with the classes and attributes of the jQuery plugin", async () => {
+ it("renders the input with its classes and attributes", async () => {
const { container, input } = await render({ id: "picker", placeholder: "Find" });
expect(container.firstElementChild?.className).toBe("input-group");
- expect(input.className).toBe("note-autocomplete form-control note-autocomplete-input aa-input");
+ expect(input.className).toBe("note-autocomplete form-control note-autocomplete-input");
expect(input.id).toBe("picker");
expect(input.placeholder).toBe("Find");
expect(input.getAttribute("autocomplete")).toBe("off");
@@ -237,6 +237,23 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(rows()).toHaveLength(0);
});
+ // Issue #5669: a second Enter that arrives before the list re-renders submits the host's form
+ // rather than picking a row of the list the first Enter closed.
+ it("leaves a second Enter in the same task to the host", async () => {
+ const onChange = vi.fn();
+ const input = await mount({ onChange });
+ await type(input, "b");
+ await press(input, "ArrowDown");
+
+ const prevented: boolean[] = [];
+ await act(async () => {
+ for (let i = 0; i < 2; i++) {
+ const e = new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });
+ input.dispatchEvent(e);
+ prevented.push(e.defaultPrevented);
+ }
+ });
+
it("searches on the first keystroke, and paces the rest of a burst", async () => {
const input = await mount();
@@ -316,7 +333,7 @@ describe("NoteAutocomplete's suggestion list", () => {
const menu = host.querySelector<HTMLElement>(":scope > span.aa-dropdown-menu");
expect(menu?.querySelectorAll(".aa-suggestion")).toHaveLength(2);
- // In the host's flow, as `autocomplete.js` left it: its contained menu had only `display: block`.
+ // In the host's flow, with no position of its own.
expect(menu?.hasAttribute("style")).toBe(false);
expect(document.querySelector(".note-autocomplete-menu")).toBeNull();
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 45e3279775..741766acc2 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -26,7 +26,7 @@ export interface NoteAutocompleteProps {
placeholder?: string;
container?: RefObject<HTMLElement | null | undefined>;
containerStyle?: CSSProperties;
- opts?: Omit<Options, "container">;
+ opts?: Options;
onChange?: (suggestion: Suggestion | null) => void;
onTextChange?: (text: string) => void;
onKeyDown?: (e: KeyboardEvent) => void;
@@ -213,9 +213,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
<input
id={id}
ref={inputRef}
- // `note-autocomplete-input` and `aa-input` are the classes the jQuery plugin used to
- // add, which the stylesheets and the global `$(".aa-input")` closers still select.
- className="note-autocomplete form-control note-autocomplete-input aa-input"
+ className="note-autocomplete form-control note-autocomplete-input"
value={value}
readOnly={readOnly}
tabIndex={tabIndex}
@@ -241,14 +239,14 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
const isEnter = e.key === "Enter" && !e.isComposing;
if (isEnter && e.ctrlKey && allowJumpToSearchNotes) {
// Kept from the host's other listeners, such as a Ctrl+Enter shortcut of its
- // own, as the jQuery plugin did.
+ // own.
e.preventDefault();
e.stopImmediatePropagation();
void appContext.triggerCommand("searchNotes", { searchString: value });
return;
}
if (isEnter && e.shiftKey) {
- // Kept from the host and the list, as the jQuery plugin did.
+ // Kept from the host and the list.
e.preventDefault();
e.stopPropagation();
fullTextSearch();
@@ -328,8 +326,9 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}
/**
- * The list of suggestions, in the markup of `autocomplete.js`. With `searchingFor`, the query of a
- * search in progress, it shows a row saying so in place of the suggestions.
+ * The list of suggestions, in the `aa-*` markup that the Empty tab and Jump to Note style. With
+ * `searchingFor`, the query of a search in progress, it shows a row saying so in place of the
+ * suggestions.
*/
function NoteSuggestionList({ autocomplete, searchingFor }: {
autocomplete: ReturnType<typeof useAutocomplete<Suggestion>>;
@@ -426,7 +425,7 @@ function NoteSuggestionMenuItem({ suggestion }: { suggestion: Suggestion }) {
);
}
-/** One row of the list, in the markup of the jQuery plugin's suggestion template. */
+/** One row of the list. */
function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
if (suggestion.action === "command") {
return (
diff --git a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
deleted file mode 100644
index 02d9a16477..0000000000
--- a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { useEffect } from "preact/hooks";
-import note_autocomplete from "../../services/note_autocomplete";
-import { useSyncedRef } from "./hooks";
-import type { NoteAutocompleteProps } from "./NoteAutocomplete";
-
-export default function NoteAutocomplete({ inputRef: externalInputRef, onChange, opts, noteIdChanged }: NoteAutocompleteProps) {
- const ref = useSyncedRef<HTMLInputElement>(externalInputRef);
-
- useEffect(() => {
- if (!ref.current) return;
- const $autoComplete = $(ref.current);
-
- // clear any event listener added in previous invocation of this function
- $autoComplete
- .off("autocomplete:noteselected");
-
- note_autocomplete.initNoteAutocomplete($autoComplete, opts);
- }, [opts]);
-
- // On change event handlers.
- useEffect(() => {
- if (!ref.current) return;
- const $autoComplete = $(ref.current);
-
- if (onChange || noteIdChanged) {
- const autoCompleteListener = (_e, suggestion) => {
- onChange?.(suggestion);
-
- if (noteIdChanged) {
- const noteId = suggestion?.notePath?.split("/")?.at(-1);
- noteIdChanged(noteId);
- }
- };
- $autoComplete
- .on("autocomplete:externallinkselected", autoCompleteListener);
- return () => {
- $autoComplete
- .off("autocomplete:externallinkselected", autoCompleteListener);
- };
- }
- }, [opts, onChange, noteIdChanged])
-
- return null;
-}
diff --git a/apps/client/src/widgets/react/floating_layers.spec.ts b/apps/client/src/widgets/react/floating_layers.spec.ts
index 6671a83cdc..5e802f3cd5 100644
--- a/apps/client/src/widgets/react/floating_layers.spec.ts
+++ b/apps/client/src/widgets/react/floating_layers.spec.ts
@@ -20,7 +20,7 @@ describe("isWithinFloatingLayer", () => {
// One of each family named in the selector: a menu, a modal, an editor balloon, a picker,
// the context menu (matched by id rather than class), and an autocomplete.
for (const className of [ "dropdown-menu", "modal", "modal-backdrop", "popover", "tooltip", "gutter",
- "ck-balloon-panel", "ck-body", "flatpickr-calendar", "attr-detail", "form-autocomplete-dropdown", "aa-dropdown-menu" ]) {
+ "ck-balloon-panel", "ck-body", "flatpickr-calendar", "attr-detail", "form-autocomplete-dropdown" ]) {
expect(isWithinFloatingLayer(elementIn(className)), className).toBe(true);
}
});
diff --git a/apps/client/src/widgets/react/floating_layers.ts b/apps/client/src/widgets/react/floating_layers.ts
index ae64a44cd1..809b97966a 100644
--- a/apps/client/src/widgets/react/floating_layers.ts
+++ b/apps/client/src/widgets/react/floating_layers.ts
@@ -2,7 +2,7 @@
* The app's floating layers: popup roots that render into `document.body` rather than inside
* whatever raised them — resize gutters, Bootstrap dropdowns, tooltips, modals and their backdrop,
* popovers, CKEditor balloons, Flatpickr calendars, the attribute detail popup, the context menu,
- * and both autocomplete dropdowns (Preact `FormAutocomplete` and the jQuery note autocomplete).
+ * and the `FormAutocomplete` dropdown.
*
* A surface that closes on an outside press — the peeked right pane, an anchored popover — cannot
* tell "outside" by DOM containment alone. A dropdown opened from within it lives in the body, so
@@ -16,7 +16,7 @@
*/
export const FLOATING_LAYER_SELECTOR = ".gutter, .dropdown-menu, .tooltip, .modal, .modal-backdrop, .popover, "
+ ".ck-balloon-panel, .ck-body, .flatpickr-calendar, .attr-detail, #context-menu-container, "
- + ".form-autocomplete-dropdown, .aa-dropdown-menu";
+ + ".form-autocomplete-dropdown";
/** Whether a press landed in one of the app's floating layers. See {@link FLOATING_LAYER_SELECTOR}. */
export function isWithinFloatingLayer(target: EventTarget | null): boolean {
diff --git a/apps/client/src/widgets/react/peek_pane.spec.tsx b/apps/client/src/widgets/react/peek_pane.spec.tsx
index ffd179e250..31098b71d2 100644
--- a/apps/client/src/widgets/react/peek_pane.spec.tsx
+++ b/apps/client/src/widgets/react/peek_pane.spec.tsx
@@ -170,7 +170,6 @@ describe("usePeekDismiss", () => {
<ul class="dropdown-menu"></ul>
<div class="attr-detail"><input class="attr-input" /></div>
<div class="form-autocomplete-dropdown"><li class="suggestion"></li></div>
- <div class="aa-dropdown-menu"><div class="aa-suggestion"></div></div>
<div id="context-menu-container"><li class="menu-item"></li></div>
<div id="center-pane"></div>
`;
@@ -182,10 +181,9 @@ describe("usePeekDismiss", () => {
// ...as does a default popup root (not in keepOpenSelector, but in the built-in allowlist).
document.querySelector(".dropdown-menu")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
// Body-portalled popups spawned from within the pane keep it open too: the attribute
- // detail popup and its fields, both autocomplete dropdowns, and the context menu.
+ // detail popup and its fields, the autocomplete dropdown, and the context menu.
document.querySelector(".attr-input")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
document.querySelector(".suggestion")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
- document.querySelector(".aa-suggestion")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
document.querySelector(".menu-item")?.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
expect(onDismiss).not.toHaveBeenCalled();
diff --git a/apps/client/src/widgets/sidebar/AttributeEditorOverlay.tsx b/apps/client/src/widgets/sidebar/AttributeEditorOverlay.tsx
index ee5bfa600a..87e3c20fc1 100644
--- a/apps/client/src/widgets/sidebar/AttributeEditorOverlay.tsx
+++ b/apps/client/src/widgets/sidebar/AttributeEditorOverlay.tsx
@@ -49,7 +49,7 @@ export default function AttributeEditorOverlay({ overlayRef, className, children
// is appended to the body, and creating a note from it opens the note type chooser — the
// same company the detail popup keeps itself open over.
if (e.relatedTarget instanceof Element
- && e.relatedTarget.closest(`${AUTOCOMPLETE_DROPDOWN_SELECTOR}, .algolia-autocomplete, .modal, .modal-backdrop`)) {
+ && e.relatedTarget.closest(`${AUTOCOMPLETE_DROPDOWN_SELECTOR}, .note-autocomplete-menu, .modal, .modal-backdrop`)) {
return;
}
diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.ts b/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.ts
deleted file mode 100644
index 4cffe19ff9..0000000000
--- a/apps/client/src/widgets/type_widgets/relation_map/RelationMap.spec.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import $ from "jquery";
-import { beforeEach,describe, expect, it, vi } from "vitest";
-
-import dialog from "../../../services/dialog";
-
-vi.mock("../../../services/utils", async (importOriginal) => {
- const actual = await importOriginal() as any;
- return {
- ...actual,
- default: {
- ...actual.default,
- filterAttributeName: vi.fn((val: string) => val.replace(/[^\p{L}\p{N}_:]/gu, ""))
- }
- };
-});
-
-vi.mock("../../../services/dialog", () => ({
- default: {
- prompt: vi.fn()
- }
-}));
-
-vi.mock("../../../services/attribute_autocomplete", () => ({
- default: {
- initAttributeNameAutocomplete: vi.fn()
- }
-}));
-
-vi.mock("../../../services/i18n", () => ({
- t: (key: string) => key
-}));
-
-// Call promptForRelationName and extract the $answer input element from the dialog's shown callback
-async function getAnswerFromPrompt(): Promise<JQuery<HTMLInputElement>> {
- const { promptForRelationName } = await import("./utils");
-
- let $answer!: JQuery<HTMLInputElement>;
-
- vi.mocked(dialog.prompt).mockImplementation(({ shown }) => {
- document.body.innerHTML = '<div><form><label /><input type="text" /></form></div>';
- const input = document.querySelector("input") as HTMLInputElement;
- $answer = $(input) as JQuery<HTMLInputElement>;
- shown?.({
- $dialog: $(document.querySelector("div")!) as JQuery<HTMLDivElement>,
- $question: $(document.querySelector("label")!) as JQuery<HTMLLabelElement>,
- $answer,
- $form: $(document.querySelector("form")!) as JQuery<HTMLFormElement>
- });
- return Promise.resolve(null);
- });
-
- promptForRelationName();
- return $answer;
-}
-
-describe("IME composition handling - Chinese input (promptForRelationName)", () => {
- let input: HTMLInputElement;
- let $answer: JQuery<HTMLInputElement>;
-
- beforeEach(async () => {
- vi.clearAllMocks();
- $answer = await getAnswerFromPrompt();
- input = $answer[0] as HTMLInputElement;
- });
-
- it("does not filter intermediate Chinese characters during composition", () => {
- // user starts typing in Chinese IME
- input.dispatchEvent(new Event("compositionstart"));
-
- // intermediate IME states — these are pinyin keystrokes shown before final char
- input.value = "n";
- input.dispatchEvent(new Event("input"));
- input.value = "ni";
- input.dispatchEvent(new Event("input"));
- input.value = "nin";
- input.dispatchEvent(new Event("input"));
- input.value = "ning";
- input.dispatchEvent(new Event("input"));
-
- expect(input.value).toBe("ning");
- });
-
- it("preserves valid Unicode characters after IME composition ends", () => {
- input.dispatchEvent(new Event("compositionstart"));
-
- // intermediate pinyin
- input.value = "n";
- input.dispatchEvent(new Event("input"));
- input.value = "ni";
- input.dispatchEvent(new Event("input"));
-
- // user selects the Chinese character 你 from the IME picker
- input.value = "你";
- input.dispatchEvent(new Event("compositionend"));
-
- expect(input.value).toBe("你");
- });
-
- it("allows normal latin input after Chinese composition ends", () => {
- // first do a Chinese composition
- input.dispatchEvent(new Event("compositionstart"));
- input.value = "你";
- input.dispatchEvent(new Event("compositionend"));
-
- // then type normally in latin
- input.value = "hello";
- input.dispatchEvent(new Event("input"));
-
- expect(input.value).toBe("hello");
- });
-
- it("handles multiple Chinese characters in sequence", () => {
- // first character
- input.dispatchEvent(new Event("compositionstart"));
- input.value = "你";
- input.dispatchEvent(new Event("compositionend"));
-
- // second character
- input.dispatchEvent(new Event("compositionstart"));
- input.value = "好";
- input.dispatchEvent(new Event("compositionend"));
-
- expect(input.value).toBe("好");
- });
-});
diff --git a/apps/client/src/widgets/type_widgets/relation_map/utils.ts b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
index 65d7e173ca..e131a7b8e1 100644
--- a/apps/client/src/widgets/type_widgets/relation_map/utils.ts
+++ b/apps/client/src/widgets/type_widgets/relation_map/utils.ts
@@ -1,7 +1,5 @@
-import attribute_autocomplete from "../../../services/attribute_autocomplete";
-import dialog from "../../../services/dialog";
import { t } from "../../../services/i18n";
-import utils from "../../../services/utils";
+
export function noteIdToId(noteId: string) {
return `rel-map-note-${noteId}`;
@@ -35,47 +33,3 @@ export function getMousePosition(evt: MouseEvent, container: HTMLDivElement, zoo
y: ((evt.clientY ?? 0) - rect.top) / zoom
};
}
-
-export function promptForRelationName(defaultValue?: string): Promise<string | null> {
- return dialog.prompt({
- message: t("relation_map.specify_new_relation_name"),
- defaultValue,
- shown: ({ $answer }) => {
- if (!$answer) {
- return;
- }
-
- let isComposing = false;
-
- $answer.on("compositionstart", () => {
- isComposing = true;
- });
- $answer.on("compositionend", () => {
- isComposing = false;
- const attrName = utils.filterAttributeName($answer.val() as string);
- $answer.val(attrName);
- });
- $answer.on("input", () => {
- if (isComposing) return;
- const attrName = utils.filterAttributeName($answer.val() as string);
- $answer.val(attrName);
- });
-
- $answer.on("keydown", (e) => {
- if (e.key === "Enter") {
- $answer[0].dispatchEvent(new Event("input", { bubbles: true }));
- }
- });
-
- $answer.on("blur", () => {
- $answer[0].dispatchEvent(new Event("input", { bubbles: true }));
- });
-
- attribute_autocomplete.initAttributeNameAutocomplete({
- $el: $answer,
- attributeType: "relation",
- open: true
- });
- }
- });
-}
diff --git a/apps/server/e2e/add_link_double_enter.spec.ts b/apps/server/e2e/add_link_double_enter.spec.ts
index e397546cc7..fabe3f04a8 100644
--- a/apps/server/e2e/add_link_double_enter.spec.ts
+++ b/apps/server/e2e/add_link_double_enter.spec.ts
@@ -4,19 +4,14 @@ import App from "../../../packages/trilium-e2e/src/support/app";
// Repro for https://github.com/TriliumNext/Trilium/issues/5669
//
-// Mechanism: after Enter selects a note, autocomplete.js closes the dropdown but
-// only *defers* emptying it (setTimeout 0). Until that timer fires, the stale
-// suggestion rows are still in the DOM, and _onEnterKeyed happily selects
-// getDatumForCursor()/getDatumForTopSuggestion() even though the dropdown is
-// closed. A second Enter landing inside that window is therefore consumed by
-// autocomplete (re-selecting a stale row — or, when the create-note row is on
-// top, opening the "Choose note type" dialog) instead of submitting the form.
+// Mechanism: the note autocomplete's Enter handler reads the list as it was last
+// rendered. A second Enter dispatched before the list re-renders, after the first
+// one picked a row and closed it, would pick from that stale list again (or, when
+// the create-note row is on top, open the "Choose note type" dialog) instead of
+// submitting the form.
//
// Dispatching both Enter keydowns in a single synchronous task makes the race
-// deterministic: the deferred empty() can never run between them. (Humans hit
-// the same window when the second keypress is dispatched ahead of the pending
-// 0 ms timer — input events are prioritized over timers, especially with a
-// busy main thread right after the dialog re-renders.)
+// deterministic: no render can run between them.
test("fast double-Enter in add-link dialog is not consumed by a stale suggestion", async ({ page, context }) => {
const app = new App(page, context);
await app.goto();
@@ -34,8 +29,8 @@ test("fast double-Enter in add-link dialog is not consumed by a stale suggestion
const input = dialog.locator("input.note-autocomplete");
await input.pressSequentially("Highlights");
- // Row 0 is the prepended "Create note 'Highlights'" row; wait for a real note row too.
- await expect(page.locator(".aa-dropdown-menu:visible .aa-suggestion").nth(1)).toBeVisible();
+ // Rows 0 and 1 are the creation rows; wait for a real note row too.
+ await expect(page.locator(".note-autocomplete-menu .dropdown-item").nth(2)).toBeVisible();
// Move the cursor onto a real note row, as in the issue's repro steps, and
// let the re-query the arrows can trigger settle.
@@ -49,10 +44,6 @@ test("fast double-Enter in add-link dialog is not consumed by a stale suggestion
const el = document.querySelector<HTMLInputElement>(".add-link-dialog input.note-autocomplete");
if (!el) throw new Error("autocomplete input not found");
- const selections: string[] = [];
- const jq = (window as unknown as { $: (el: HTMLElement) => { on: (ev: string, cb: (e: unknown, s?: { action?: string; noteTitle?: string }) => void) => void } }).$;
- jq(el).on("autocomplete:selected", (_e, s) => selections.push(`${s?.action ?? "note"}:${s?.noteTitle}`));
-
const fire = () => {
const e = new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });
Object.defineProperty(e, "keyCode", { value: 13 });
@@ -62,15 +53,14 @@ test("fast double-Enter in add-link dialog is not consumed by a stale suggestion
};
const firstPrevented = fire();
const secondPrevented = fire();
- return { selections, firstPrevented, secondPrevented };
+ return { firstPrevented, secondPrevented };
});
- // The first Enter must select the note under the cursor…
- expect(result.selections.length).toBe(1);
+ // The first Enter must pick the note under the cursor…
expect(result.firstPrevented).toBe(true);
- // …and the second Enter must NOT be consumed by autocomplete: no second
- // selection, no "Choose note type" dialog, and the default action (form
+ // …and the second Enter must NOT be consumed by the autocomplete: no second
+ // pick, no "Choose note type" dialog, and the default action (form
// submission = adding the link) left intact.
expect(result.secondPrevented).toBe(false);
await expect(page.locator(".note-type-chooser-dialog")).not.toBeVisible({ timeout: 2000 });
diff --git a/apps/standalone/package.json b/apps/standalone/package.json
index 6e82793041..0b661f6d1b 100644
--- a/apps/standalone/package.json
+++ b/apps/standalone/package.json
@@ -27,7 +27,6 @@
"@triliumnext/highlightjs": "workspace:*",
"@triliumnext/share-theme": "workspace:*",
"@triliumnext/split.js": "workspace:*",
- "autocomplete.js": "0.38.1",
"bootstrap": "5.3.8",
"buffer": "6.0.3",
"boxicons": "2.1.4",
diff --git a/packages/trilium-e2e/src/support/app.ts b/packages/trilium-e2e/src/support/app.ts
index 72ee9a8eef..2cb001649b 100644
--- a/packages/trilium-e2e/src/support/app.ts
+++ b/packages/trilium-e2e/src/support/app.ts
@@ -116,9 +116,7 @@ export default class App {
async goToNoteInNewTab(noteTitle: string) {
const autocomplete = this.currentNoteSplit.locator(".note-autocomplete");
await expect(autocomplete).toBeVisible();
- // The algolia autocomplete listens to keyboard events. `fill()` only
- // dispatches `input`, which doesn't reliably open the dropdown — clear
- // and type with real key events instead.
+ // Typed with real key events, as a person types, rather than `fill()`.
await autocomplete.click();
await autocomplete.clear();
await autocomplete.pressSequentially(noteTitle);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3f61276173..a2b8167c85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -264,9 +264,6 @@ importers:
'@univerjs/presets':
specifier: 1.0.2
- autocomplete.js:
- specifier: 0.38.1
- version: 0.38.1
bootstrap:
specifier: 5.3.8
version: 5.3.8(@popperjs/[email protected])
@@ -896,9 +893,6 @@ importers:
aes-js:
specifier: 3.1.2
version: 3.1.2
- autocomplete.js:
- specifier: 0.38.1
- version: 0.38.1
bootstrap:
specifier: 5.3.8
version: 5.3.8(@popperjs/[email protected])
@@ -5858,9 +5852,6 @@ packages:
resolution: {integrity: sha512-KbWgR8wOYRAPekEmMXrYYdc7BRyhn2Ftk7KWfMUnQ43hFdojWEFRxhhRUm3/OFEdPa1r0KAvTTg9YQK57xTe0g==}
engines: {node: '>=0.8'}
- resolution: {integrity: sha512-6pSJzuRMY3pqpozt+SXThl2DmJfma8Bi3SVFbZHS0PW/N72bOUv+Db0jAh2cWOhTsA4X+GNmKvIl8wExJTnN9w==}
-
resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==}
engines: {node: '>= 0.4'}
@@ -8042,9 +8033,6 @@ packages:
resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==}
- resolution: {integrity: sha512-HR7EVodfFUdQCTIeySw+WDRFJlPcLOJbXfwwZ7Oom6tjsvZ3bOkCDJHehQC3nxJrv7+f9XecwazynjU8e4Vw3Q==}
-
resolution: {integrity: sha512-m8nVez3rwrgmWxtLMt1ZYXB2Lv7OKYn/disyxAlSDYAlKSlFoPPfIAmAM/M5xqL4m4C/wAPw7S2/CNaUii1Hxg==}
@@ -17419,10 +17407,6 @@ snapshots:
- dependencies:
- immediate: 3.3.0
-
dependencies:
possible-typed-array-names: 1.1.0
@@ -20097,8 +20081,6 @@ snapshots:
-