Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(autocomplete): stub out the note autocomplete for a rewrite
Elian Doran71fd0c3bd535
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex 3766f158d1..5bab519bb4 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -1,120 +1,4 @@import type { MentionFeedObjectItem } from "@triliumnext/ckeditor5";-import type { InboxTargetResponse } from "@triliumnext/commons";--import appContext from "../components/app_context.js";-import commandRegistry from "./command_registry.js";-import dateNoteService from "./date_notes.js";-import froca from "./froca.js";-import { t } from "./i18n.js";-import noteCreateService from "./note_create.js";-import server from "./server.js";-import { escapeHtml } from "./utils.js";-import { logError } from "./ws.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";--// Short on purpose: a search costs tens of milliseconds, so this exists to merge keystrokes that-// arrive faster than a person reads a result, not to wait out a slow server. Anything longer is-// felt on every keystroke typed at a normal pace.-const SEARCH_DEBOUNCE_MS = 50;--/**- * Paces one input's searches: the first keystroke after a pause queries immediately, a burst typed- * faster than {@link SEARCH_DEBOUNCE_MS} collapses into one search that runs once it stops, and at- * most one search is ever outstanding.- *- * The single-flight part is what keeps a slow search from compounding. The server answers- * autocomplete requests one at a time, so firing a second while the first is still running makes- * every later keystroke wait out the whole queue ahead of it. Holding the newest term back until- * the outstanding search settles paces requests at whatever the server can actually serve, without- * the client having to know how slow that is.- *- * Each input holds its own timer and its own in-flight search, so a keystroke in one cannot cancel- * or delay what another is waiting on.- */-function createSearchScheduler() {- type Search = () => void | Promise<void>;-- let timeoutId: ReturnType<typeof setTimeout> | undefined;- let lastCallAt = 0;- let running = false;- let queued: Search | undefined;-- function start(runSearch: Search) {- // Only the newest term is worth searching for, so a search waiting here replaces the one- // before it instead of queueing behind it.- if (running) {- queued = runSearch;- return;- }-- running = true;- void Promise.resolve(runSearch())- .catch((e) => logError(`Autocomplete search failed: ${e}`))- .finally(() => {- running = false;- const next = queued;- queued = undefined;- if (next) {- start(next);- }- });- }-- return (runSearch: Search) => {- // A newer keystroke supersedes whatever the previous one left waiting, be that a pending- // timer or a search held back by the one in flight.- clearTimeout(timeoutId);- queued = undefined;-- // Measured from the previous keystroke rather than the previous search. Measuring from the- // search paces requests at a fixed rate instead of ending the window when typing pauses.- const now = Date.now();- const startsBurst = now - lastCallAt >= SEARCH_DEBOUNCE_MS;- lastCallAt = now;-- if (startsBurst) {- start(runSearch);- } else {- timeoutId = setTimeout(() => start(runSearch), SEARCH_DEBOUNCE_MS);- }- };-}--async function getInboxTarget() {- try {- return await dateNoteService.getInboxTarget();- } catch (e) {- // The entry falls back to a label with no destination rather than failing the dropdown.- logError(`Unable to resolve the inbox target: ${e}`);- return null;- }-}--/** Labels the creation entry with the note the capture would land in. */-function buildCreateNoteTitle(term: string, target: InboxTargetResponse | null) {- if (!target) {- return t("note_autocomplete.create-note", { term: escapeHtml(term) });- }-- if (target.kind === "dayNote") {- return t("note_autocomplete.create-note-into-day-note", { term: escapeHtml(term) });- }-- // The root note's own title names nothing the user recognises in the tree.- if (target.kind === "root") {- return t("note_autocomplete.create-note-into-root", { term: escapeHtml(term) });- }-- if (!target.title) {- return t("note_autocomplete.create-note", { term: escapeHtml(term) });- }-- return t("note_autocomplete.create-note-into", { term: escapeHtml(term), parentTitle: escapeHtml(target.title) });-}// TODO: Deduplicate with server.export interface Suggestion {@@ -147,489 +31,37 @@ export interface Options {isCommandPalette?: boolean;}-/**- * Feeds a CKEditor mention. Creation entries are offered only where the editor's host component- * implements `createNoteForReferenceLink`, which is what `MentionCustomization` calls to act on- * them.- */-async function autocompleteSourceForCKEditor(queryText: string, allowCreatingNotes = true) {- return await new Promise<MentionFeedObjectItem[]>((res, rej) => {- autocompleteSource(- queryText,- (rows) => {- res(- rows.map((row) => {- return {- action: row.action,- noteTitle: row.noteTitle,- id: `@${row.notePathTitle}`,- name: row.notePathTitle || "",- link: `#${row.notePath}`,- notePath: row.notePath,- highlightedNotePathTitle: row.highlightedNotePathTitle,- icon: row.icon- };- })- );- },- {- allowCreatingNotes- }- );- });-}--async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void, options: Options = {}) {- // Check if we're in command mode- if (options.isCommandPalette && term.startsWith(">")) {- const commandQuery = term.substring(1).trim();-- // Get commands (all if no query, filtered if query provided)- const commands = commandQuery.length === 0- ? commandRegistry.getAllCommands()- : commandRegistry.searchCommands(commandQuery);-- // Convert commands to suggestions- const commandSuggestions: Suggestion[] = commands.map(cmd => ({- action: "command",- commandId: cmd.id,- noteTitle: cmd.name,- notePathTitle: `>${cmd.name}`,- highlightedNotePathTitle: cmd.name,- commandDescription: cmd.description,- commandShortcut: cmd.shortcut,- icon: cmd.icon- }));+// #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.- cb(commandSuggestions);- return;- }-- const fastSearch = options.fastSearch !== false;- if (fastSearch === false) {- if (term.trim().length === 0) {- return;- }- cb([- {- noteTitle: term,- highlightedNotePathTitle: t("quick-search.searching")- }- ]);- }-- const activeNoteId = appContext.tabManager.getActiveContextNoteId();- const length = term.trim().length;-- // Runs concurrently with the search, so naming the destination costs a request but no wait.- const pendingInboxTarget = length >= 1 && options.allowCreatingNotes ? getInboxTarget() : null;-- let results = await server.get<Suggestion[]>(`autocomplete?query=${encodeURIComponent(term)}&activeNoteId=${activeNoteId}&fastSearch=${fastSearch}`);-- options.fastSearch = true;-- // Both rows stay above the results: the CKEditor mention feed renders only the first- // `mention.dropdownLimit` items, and the jQuery dropdown scrolls past as many as 200.- if (pendingInboxTarget) {- results = [- {- action: "create-note",- noteTitle: term,- highlightedNotePathTitle: buildCreateNoteTitle(term, await pendingInboxTarget)- } as Suggestion,- {- action: "create-child-note",- noteTitle: term,- parentNoteId: activeNoteId || "root",- highlightedNotePathTitle: t("note_autocomplete.create-child-note", { term: escapeHtml(term) })- } as Suggestion- ].concat(results);- }-- if (length >= 1 && options.allowJumpToSearchNotes) {- results = results.concat([- {- action: "search-notes",- noteTitle: term,- highlightedNotePathTitle: `${t("note_autocomplete.search-for", { term: escapeHtml(term) })} <kbd style='color: var(--muted-text-color); background-color: transparent; float: right;'>Ctrl+Enter</kbd>`- }- ]);- }-- if (term.match(/^[a-z]+:\/\/.+/i) && options.allowExternalLinks) {- results = [- {- action: "external-link",- externalLink: term,- highlightedNotePathTitle: t("note_autocomplete.insert-external-link", { term: escapeHtml(term) })- } as Suggestion- ].concat(results);- }-- cb(results);-}--// `autocomplete("val", ...)` does not dispatch a native "input" event, so each function below-// fires one to keep consumers bound to it, such as NoteAutocomplete's onTextChange, in sync.--function clearText($el: JQuery<HTMLElement>) {- $el.setSelectedNotePath("");- $el.autocomplete("val", "").trigger("change");- $el.trigger("input");+async function autocompleteSourceForCKEditor(_queryText: string, _allowCreatingNotes = true): Promise<MentionFeedObjectItem[]> {+ return [];}-function setText($el: JQuery<HTMLElement>, text: string) {- $el.setSelectedNotePath("");- $el.autocomplete("val", text.trim());- $el.trigger("input");- $el.autocomplete("open");-}--function showRecentNotes($el: JQuery<HTMLElement>) {- $el.setSelectedNotePath("");- $el.autocomplete("val", "");- $el.trigger("input");- $el.autocomplete("open");- $el.trigger("focus");-}--function showAllCommands($el: JQuery<HTMLElement>) {- $el.setSelectedNotePath("");- $el.autocomplete("val", ">");- $el.trigger("input");- $el.autocomplete("open");-}--function fullTextSearch($el: JQuery<HTMLElement>, options: Options) {- const searchString = $el.autocomplete("val") as unknown as string;- if (options.fastSearch === false || searchString?.trim().length === 0) {- return;- }- $el.trigger("focus");- options.fastSearch = false;- $el.autocomplete("val", "");- $el.setSelectedNotePath("");- $el.autocomplete("val", searchString);-}--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();-- // Used to track whether the user is performing character composition with an input method (such as Chinese Pinyin, Japanese, Korean, etc.) and to avoid triggering a search during the composition process.- let isComposingInput = false;- $el.on("compositionstart", () => {- isComposingInput = true;- });- $el.on("compositionend", () => {- isComposingInput = false;- const searchString = $el.autocomplete("val") as unknown as string;- $el.autocomplete("val", "");- $el.autocomplete("val", searchString);- });-- $el.addClass("note-autocomplete-input");-- const $clearTextButton = $("<a>").addClass("input-group-text input-clearer-button bx bxs-tag-x").prop("title", t("note_autocomplete.clear-text-field"));-- const $showRecentNotesButton = $("<a>").addClass("input-group-text show-recent-notes-button bx bx-time").prop("title", t("note_autocomplete.show-recent-notes"));-- const $fullTextSearchButton = $("<a>")- .addClass("input-group-text full-text-search-button bx bx-search")- .prop("title", `${t("note_autocomplete.full-text-search")} (Shift+Enter)`);-- const $goToSelectedNoteButton = $("<a>").addClass("input-group-text go-to-selected-note-button bx bx-arrow-to-right");-- if (!options.hideAllButtons) {- $el.after($clearTextButton).after($showRecentNotesButton).after($fullTextSearchButton);- }-- if (!options.hideGoToSelectedNoteButton && !options.hideAllButtons) {- $el.after($goToSelectedNoteButton);- }-- $clearTextButton.on("click", () => clearText($el));-- $showRecentNotesButton.on("click", (e) => {- showRecentNotes($el);-- // this will cause the click not give focus to the "show recent notes" button- // this is important because otherwise input will lose focus immediately and not show the results- return false;- });-- $fullTextSearchButton.on("click", (e) => {- fullTextSearch($el, options);- return false;- });-- const autocompleteOptions: AutoCompleteConfig = {};- if (options.container) {- autocompleteOptions.dropdownMenuContainer = options.container;- autocompleteOptions.debug = true; // don't close on blur- }-- if (options.allowJumpToSearchNotes) {- $el.on("keydown", (event) => {- if (event.ctrlKey && event.key === "Enter") {- // Prevent Ctrl + Enter from triggering autoComplete.- event.stopImmediatePropagation();- event.preventDefault();- $el.trigger("autocomplete:selected", { action: "search-notes", noteTitle: $el.autocomplete("val") });- }- });- }- $el.on("keydown", async (event) => {- if (event.shiftKey && event.key === "Enter") {- // Prevent Enter from triggering autoComplete.- event.stopImmediatePropagation();- event.preventDefault();- fullTextSearch($el, options);- }- });- $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(- {- ...autocompleteOptions,- 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(() => {- if (isComposingInput) {- return;- }- // Returned so the scheduler holds the next search until this one settles.- return autocompleteSource(term, cb, options);- });- },- displayKey: "notePathTitle",- templates: {- suggestion: (suggestion) => {- if (suggestion.action === "command") {- let html = `<div class="command-suggestion">`;- html += `<span class="command-icon ${escapeHtml(suggestion.icon || "bx bx-terminal")}"></span>`;- html += `<div class="command-content">`;- html += `<div class="command-name">${suggestion.highlightedNotePathTitle}</div>`;- if (suggestion.commandDescription) {- html += `<div class="command-description">${suggestion.commandDescription}</div>`;- }- html += `</div>`;- if (suggestion.commandShortcut) {- html += `<kbd class="command-shortcut">${suggestion.commandShortcut}</kbd>`;- }- html += '</div>';- return html;- }- // Add special class for search-notes action- const actionClass = suggestion.action === "search-notes" ? "search-notes-action" : "";-- // Choose appropriate icon based on action- let iconClass = suggestion.icon ?? "bx bx-note";- if (suggestion.action === "search-notes") {- iconClass = "bx bx-search";- } else if (suggestion.action === "create-note") {- iconClass = "bx bx-plus";- } else if (suggestion.action === "create-child-note") {- iconClass = "bx bx-subdirectory-right";- } else if (suggestion.action === "external-link") {- iconClass = "bx bx-link-external";- }-- // Simplified HTML structure without nested divs- let html = `<div class="note-suggestion ${actionClass}">`;- html += `<span class="icon ${escapeHtml(iconClass)}"></span>`;- html += `<span class="text">`;- html += `<span class="search-result-title">${suggestion.highlightedNotePathTitle}</span>`;-- // Add attribute snippet inline if available- if (suggestion.highlightedAttributeSnippet) {- html += `<span class="search-result-attributes">${suggestion.highlightedAttributeSnippet}</span>`;- }-- html += `</span>`;- html += `</div>`;- return html;- }- },- // 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) => {- if (suggestion.action === "command") {- $el.autocomplete("close");- $el.trigger("autocomplete:commandselected", [suggestion]);- return;- }-- if (suggestion.action === "external-link") {- $el.setSelectedNotePath(null);- $el.setSelectedExternalLink(suggestion.externalLink);-- $el.autocomplete("val", suggestion.externalLink);-- $el.autocomplete("close");-- $el.trigger("autocomplete:externallinkselected", [suggestion]);-- return;- }-- if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {- const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();- if (!success) {- return;- }-- const parentNotePath = notePath ?? (suggestion.action === "create-note"- ? await dateNoteService.getInboxNotePath()- : suggestion.parentNoteId);- if (!parentNotePath) {- return;- }-- const { note } = await noteCreateService.createNote(parentNotePath, {- title: suggestion.noteTitle,- activate: false,- type: noteType,- templateNoteId,- cloneToNoteIds- });-- const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;- suggestion.notePath = note?.getBestNotePathString(hoistedNoteId);- }-- if (suggestion.action === "search-notes") {- const searchString = suggestion.noteTitle;- appContext.triggerCommand("searchNotes", { searchString });- return;- }-- $el.setSelectedNotePath(suggestion.notePath);- $el.setSelectedExternalLink(null);-- $el.autocomplete("val", suggestion.noteTitle);-- $el.autocomplete("close");-- $el.trigger("autocomplete:noteselected", [suggestion]);- });-- $el.on("autocomplete:closed", () => {- if (!String($el.val())?.trim()) {- clearText($el);- }- });-- $el.on("autocomplete:opened", () => {- if ($el.attr("readonly")) {- $el.autocomplete("close");- }- });-- // clear any event listener added in previous invocation of this function- $el.off("autocomplete:noteselected");-+function initNoteAutocomplete($el: JQuery<HTMLElement>, _options?: Options) {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("/");+function showRecentNotes(_$el: JQuery<HTMLElement>) {}- /* 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;- };+function showAllCommands(_$el: JQuery<HTMLElement>) {}- $.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- };+function setText(_$el: JQuery<HTMLElement>, _text: string) {}- $.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);- };+/** 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 () => {};}-/**- * Convenience function which triggers the display of recent notes in the autocomplete input and focuses it.- *- * @param inputElement - The input element to trigger recent notes on.- */-export function triggerRecentNotes(inputElement: HTMLInputElement | null | undefined) {- if (!inputElement) {- return;- }+export function triggerRecentNotes(_inputElement: HTMLInputElement | null | undefined) {}- const $el = $(inputElement);- showRecentNotes($el);- $el.trigger("focus").trigger("select");-}+// #endregionexport default {autocompleteSourceForCKEditor,diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.tssimilarity index 99%rename from apps/client/src/services/note_autocomplete.spec.tsrename to apps/client/src/services/note_autocomplete_bak.spec.tsindex 6f05eb55d4..f8b3e51b18 100644--- a/apps/client/src/services/note_autocomplete.spec.ts+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts@@ -67,7 +67,7 @@ vi.mock("./ws.js", () => ({import server from "./server.js";import froca from "./froca.js";import { buildNote } from "../test/easy-froca.js";-import noteAutocomplete, { triggerRecentNotes } from "./note_autocomplete.js";+import noteAutocomplete, { triggerRecentNotes } from "./note_autocomplete_bak.js";type Dataset = {displayKey: string;diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.tsnew file mode 100644index 0000000000..3766f158d1--- /dev/null+++ b/apps/client/src/services/note_autocomplete_bak.ts@@ -0,0 +1,641 @@+import type { MentionFeedObjectItem } from "@triliumnext/ckeditor5";+import type { InboxTargetResponse } from "@triliumnext/commons";++import appContext from "../components/app_context.js";+import commandRegistry from "./command_registry.js";+import dateNoteService from "./date_notes.js";+import froca from "./froca.js";+import { t } from "./i18n.js";+import noteCreateService from "./note_create.js";+import server from "./server.js";+import { escapeHtml } from "./utils.js";+import { logError } from "./ws.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";++// Short on purpose: a search costs tens of milliseconds, so this exists to merge keystrokes that+// arrive faster than a person reads a result, not to wait out a slow server. Anything longer is+// felt on every keystroke typed at a normal pace.+const SEARCH_DEBOUNCE_MS = 50;++/**+ * Paces one input's searches: the first keystroke after a pause queries immediately, a burst typed+ * faster than {@link SEARCH_DEBOUNCE_MS} collapses into one search that runs once it stops, and at+ * most one search is ever outstanding.+ *+ * The single-flight part is what keeps a slow search from compounding. The server answers+ * autocomplete requests one at a time, so firing a second while the first is still running makes+ * every later keystroke wait out the whole queue ahead of it. Holding the newest term back until+ * the outstanding search settles paces requests at whatever the server can actually serve, without+ * the client having to know how slow that is.+ *+ * Each input holds its own timer and its own in-flight search, so a keystroke in one cannot cancel+ * or delay what another is waiting on.+ */+function createSearchScheduler() {+ type Search = () => void | Promise<void>;++ let timeoutId: ReturnType<typeof setTimeout> | undefined;+ let lastCallAt = 0;+ let running = false;+ let queued: Search | undefined;++ function start(runSearch: Search) {+ // Only the newest term is worth searching for, so a search waiting here replaces the one+ // before it instead of queueing behind it.+ if (running) {+ queued = runSearch;+ return;+ }++ running = true;+ void Promise.resolve(runSearch())+ .catch((e) => logError(`Autocomplete search failed: ${e}`))+ .finally(() => {+ running = false;+ const next = queued;+ queued = undefined;+ if (next) {+ start(next);+ }+ });+ }++ return (runSearch: Search) => {+ // A newer keystroke supersedes whatever the previous one left waiting, be that a pending+ // timer or a search held back by the one in flight.+ clearTimeout(timeoutId);+ queued = undefined;++ // Measured from the previous keystroke rather than the previous search. Measuring from the+ // search paces requests at a fixed rate instead of ending the window when typing pauses.+ const now = Date.now();+ const startsBurst = now - lastCallAt >= SEARCH_DEBOUNCE_MS;+ lastCallAt = now;++ if (startsBurst) {+ start(runSearch);+ } else {+ timeoutId = setTimeout(() => start(runSearch), SEARCH_DEBOUNCE_MS);+ }+ };+}++async function getInboxTarget() {+ try {+ return await dateNoteService.getInboxTarget();+ } catch (e) {+ // The entry falls back to a label with no destination rather than failing the dropdown.+ logError(`Unable to resolve the inbox target: ${e}`);+ return null;+ }+}++/** Labels the creation entry with the note the capture would land in. */+function buildCreateNoteTitle(term: string, target: InboxTargetResponse | null) {+ if (!target) {+ return t("note_autocomplete.create-note", { term: escapeHtml(term) });+ }++ if (target.kind === "dayNote") {+ return t("note_autocomplete.create-note-into-day-note", { term: escapeHtml(term) });+ }++ // The root note's own title names nothing the user recognises in the tree.+ if (target.kind === "root") {+ return t("note_autocomplete.create-note-into-root", { term: escapeHtml(term) });+ }++ if (!target.title) {+ return t("note_autocomplete.create-note", { term: escapeHtml(term) });+ }++ return t("note_autocomplete.create-note-into", { term: escapeHtml(term), parentTitle: escapeHtml(target.title) });+}++// TODO: Deduplicate with server.+export interface Suggestion {+ noteTitle?: string;+ externalLink?: string;+ notePathTitle?: string;+ notePath?: string;+ highlightedNotePathTitle?: string;+ action?: string | "create-note" | "create-child-note" | "search-notes" | "external-link" | "command";+ parentNoteId?: string;+ icon?: string;+ commandId?: string;+ commandDescription?: string;+ commandShortcut?: string;+ attributeSnippet?: string;+ highlightedAttributeSnippet?: string;+}++export interface Options {+ container?: HTMLElement | null;+ fastSearch?: boolean;+ allowCreatingNotes?: boolean;+ allowJumpToSearchNotes?: boolean;+ allowExternalLinks?: boolean;+ /** If set, hides the right-side button corresponding to go to selected note. */+ hideGoToSelectedNoteButton?: boolean;+ /** If set, hides all right-side buttons in the autocomplete dropdown */+ hideAllButtons?: boolean;+ /** If set, enables command palette mode */+ isCommandPalette?: boolean;+}++/**+ * Feeds a CKEditor mention. Creation entries are offered only where the editor's host component+ * implements `createNoteForReferenceLink`, which is what `MentionCustomization` calls to act on+ * them.+ */+async function autocompleteSourceForCKEditor(queryText: string, allowCreatingNotes = true) {+ return await new Promise<MentionFeedObjectItem[]>((res, rej) => {+ autocompleteSource(+ queryText,+ (rows) => {+ res(+ rows.map((row) => {+ return {+ action: row.action,+ noteTitle: row.noteTitle,+ id: `@${row.notePathTitle}`,+ name: row.notePathTitle || "",+ link: `#${row.notePath}`,+ notePath: row.notePath,+ highlightedNotePathTitle: row.highlightedNotePathTitle,+ icon: row.icon+ };+ })+ );+ },+ {+ allowCreatingNotes+ }+ );+ });+}++async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void, options: Options = {}) {+ // Check if we're in command mode+ if (options.isCommandPalette && term.startsWith(">")) {+ const commandQuery = term.substring(1).trim();++ // Get commands (all if no query, filtered if query provided)+ const commands = commandQuery.length === 0+ ? commandRegistry.getAllCommands()+ : commandRegistry.searchCommands(commandQuery);++ // Convert commands to suggestions+ const commandSuggestions: Suggestion[] = commands.map(cmd => ({+ action: "command",+ commandId: cmd.id,+ noteTitle: cmd.name,+ notePathTitle: `>${cmd.name}`,+ highlightedNotePathTitle: cmd.name,+ commandDescription: cmd.description,+ commandShortcut: cmd.shortcut,+ icon: cmd.icon+ }));++ cb(commandSuggestions);+ return;+ }++ const fastSearch = options.fastSearch !== false;+ if (fastSearch === false) {+ if (term.trim().length === 0) {+ return;+ }+ cb([+ {+ noteTitle: term,+ highlightedNotePathTitle: t("quick-search.searching")+ }+ ]);+ }++ const activeNoteId = appContext.tabManager.getActiveContextNoteId();+ const length = term.trim().length;++ // Runs concurrently with the search, so naming the destination costs a request but no wait.+ const pendingInboxTarget = length >= 1 && options.allowCreatingNotes ? getInboxTarget() : null;++ let results = await server.get<Suggestion[]>(`autocomplete?query=${encodeURIComponent(term)}&activeNoteId=${activeNoteId}&fastSearch=${fastSearch}`);++ options.fastSearch = true;++ // Both rows stay above the results: the CKEditor mention feed renders only the first+ // `mention.dropdownLimit` items, and the jQuery dropdown scrolls past as many as 200.+ if (pendingInboxTarget) {+ results = [+ {+ action: "create-note",+ noteTitle: term,+ highlightedNotePathTitle: buildCreateNoteTitle(term, await pendingInboxTarget)+ } as Suggestion,+ {+ action: "create-child-note",+ noteTitle: term,+ parentNoteId: activeNoteId || "root",+ highlightedNotePathTitle: t("note_autocomplete.create-child-note", { term: escapeHtml(term) })+ } as Suggestion+ ].concat(results);+ }++ if (length >= 1 && options.allowJumpToSearchNotes) {+ results = results.concat([+ {+ action: "search-notes",+ noteTitle: term,+ highlightedNotePathTitle: `${t("note_autocomplete.search-for", { term: escapeHtml(term) })} <kbd style='color: var(--muted-text-color); background-color: transparent; float: right;'>Ctrl+Enter</kbd>`+ }+ ]);+ }++ if (term.match(/^[a-z]+:\/\/.+/i) && options.allowExternalLinks) {+ results = [+ {+ action: "external-link",+ externalLink: term,+ highlightedNotePathTitle: t("note_autocomplete.insert-external-link", { term: escapeHtml(term) })+ } as Suggestion+ ].concat(results);+ }++ cb(results);+}++// `autocomplete("val", ...)` does not dispatch a native "input" event, so each function below+// fires one to keep consumers bound to it, such as NoteAutocomplete's onTextChange, in sync.++function clearText($el: JQuery<HTMLElement>) {+ $el.setSelectedNotePath("");+ $el.autocomplete("val", "").trigger("change");+ $el.trigger("input");+}++function setText($el: JQuery<HTMLElement>, text: string) {+ $el.setSelectedNotePath("");+ $el.autocomplete("val", text.trim());+ $el.trigger("input");+ $el.autocomplete("open");+}++function showRecentNotes($el: JQuery<HTMLElement>) {+ $el.setSelectedNotePath("");+ $el.autocomplete("val", "");+ $el.trigger("input");+ $el.autocomplete("open");+ $el.trigger("focus");+}++function showAllCommands($el: JQuery<HTMLElement>) {+ $el.setSelectedNotePath("");+ $el.autocomplete("val", ">");+ $el.trigger("input");+ $el.autocomplete("open");+}++function fullTextSearch($el: JQuery<HTMLElement>, options: Options) {+ const searchString = $el.autocomplete("val") as unknown as string;+ if (options.fastSearch === false || searchString?.trim().length === 0) {+ return;+ }+ $el.trigger("focus");+ options.fastSearch = false;+ $el.autocomplete("val", "");+ $el.setSelectedNotePath("");+ $el.autocomplete("val", searchString);+}++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();++ // Used to track whether the user is performing character composition with an input method (such as Chinese Pinyin, Japanese, Korean, etc.) and to avoid triggering a search during the composition process.+ let isComposingInput = false;+ $el.on("compositionstart", () => {+ isComposingInput = true;+ });+ $el.on("compositionend", () => {+ isComposingInput = false;+ const searchString = $el.autocomplete("val") as unknown as string;+ $el.autocomplete("val", "");+ $el.autocomplete("val", searchString);+ });++ $el.addClass("note-autocomplete-input");++ const $clearTextButton = $("<a>").addClass("input-group-text input-clearer-button bx bxs-tag-x").prop("title", t("note_autocomplete.clear-text-field"));++ const $showRecentNotesButton = $("<a>").addClass("input-group-text show-recent-notes-button bx bx-time").prop("title", t("note_autocomplete.show-recent-notes"));++ const $fullTextSearchButton = $("<a>")+ .addClass("input-group-text full-text-search-button bx bx-search")+ .prop("title", `${t("note_autocomplete.full-text-search")} (Shift+Enter)`);++ const $goToSelectedNoteButton = $("<a>").addClass("input-group-text go-to-selected-note-button bx bx-arrow-to-right");++ if (!options.hideAllButtons) {+ $el.after($clearTextButton).after($showRecentNotesButton).after($fullTextSearchButton);+ }++ if (!options.hideGoToSelectedNoteButton && !options.hideAllButtons) {+ $el.after($goToSelectedNoteButton);+ }++ $clearTextButton.on("click", () => clearText($el));++ $showRecentNotesButton.on("click", (e) => {+ showRecentNotes($el);++ // this will cause the click not give focus to the "show recent notes" button+ // this is important because otherwise input will lose focus immediately and not show the results+ return false;+ });++ $fullTextSearchButton.on("click", (e) => {+ fullTextSearch($el, options);+ return false;+ });++ const autocompleteOptions: AutoCompleteConfig = {};+ if (options.container) {+ autocompleteOptions.dropdownMenuContainer = options.container;+ autocompleteOptions.debug = true; // don't close on blur+ }++ if (options.allowJumpToSearchNotes) {+ $el.on("keydown", (event) => {+ if (event.ctrlKey && event.key === "Enter") {+ // Prevent Ctrl + Enter from triggering autoComplete.+ event.stopImmediatePropagation();+ event.preventDefault();+ $el.trigger("autocomplete:selected", { action: "search-notes", noteTitle: $el.autocomplete("val") });+ }+ });+ }+ $el.on("keydown", async (event) => {+ if (event.shiftKey && event.key === "Enter") {+ // Prevent Enter from triggering autoComplete.+ event.stopImmediatePropagation();+ event.preventDefault();+ fullTextSearch($el, options);+ }+ });+ $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(+ {+ ...autocompleteOptions,+ 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(() => {+ if (isComposingInput) {+ return;+ }+ // Returned so the scheduler holds the next search until this one settles.+ return autocompleteSource(term, cb, options);+ });+ },+ displayKey: "notePathTitle",+ templates: {+ suggestion: (suggestion) => {+ if (suggestion.action === "command") {+ let html = `<div class="command-suggestion">`;+ html += `<span class="command-icon ${escapeHtml(suggestion.icon || "bx bx-terminal")}"></span>`;+ html += `<div class="command-content">`;+ html += `<div class="command-name">${suggestion.highlightedNotePathTitle}</div>`;+ if (suggestion.commandDescription) {+ html += `<div class="command-description">${suggestion.commandDescription}</div>`;+ }+ html += `</div>`;+ if (suggestion.commandShortcut) {+ html += `<kbd class="command-shortcut">${suggestion.commandShortcut}</kbd>`;+ }+ html += '</div>';+ return html;+ }+ // Add special class for search-notes action+ const actionClass = suggestion.action === "search-notes" ? "search-notes-action" : "";++ // Choose appropriate icon based on action+ let iconClass = suggestion.icon ?? "bx bx-note";+ if (suggestion.action === "search-notes") {+ iconClass = "bx bx-search";+ } else if (suggestion.action === "create-note") {+ iconClass = "bx bx-plus";+ } else if (suggestion.action === "create-child-note") {+ iconClass = "bx bx-subdirectory-right";+ } else if (suggestion.action === "external-link") {+ iconClass = "bx bx-link-external";+ }++ // Simplified HTML structure without nested divs+ let html = `<div class="note-suggestion ${actionClass}">`;+ html += `<span class="icon ${escapeHtml(iconClass)}"></span>`;+ html += `<span class="text">`;+ html += `<span class="search-result-title">${suggestion.highlightedNotePathTitle}</span>`;++ // Add attribute snippet inline if available+ if (suggestion.highlightedAttributeSnippet) {+ html += `<span class="search-result-attributes">${suggestion.highlightedAttributeSnippet}</span>`;+ }++ html += `</span>`;+ html += `</div>`;+ return html;+ }+ },+ // 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) => {+ if (suggestion.action === "command") {+ $el.autocomplete("close");+ $el.trigger("autocomplete:commandselected", [suggestion]);+ return;+ }++ if (suggestion.action === "external-link") {+ $el.setSelectedNotePath(null);+ $el.setSelectedExternalLink(suggestion.externalLink);++ $el.autocomplete("val", suggestion.externalLink);++ $el.autocomplete("close");++ $el.trigger("autocomplete:externallinkselected", [suggestion]);++ return;+ }++ if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {+ const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();+ if (!success) {+ return;+ }++ const parentNotePath = notePath ?? (suggestion.action === "create-note"+ ? await dateNoteService.getInboxNotePath()+ : suggestion.parentNoteId);+ if (!parentNotePath) {+ return;+ }++ const { note } = await noteCreateService.createNote(parentNotePath, {+ title: suggestion.noteTitle,+ activate: false,+ type: noteType,+ templateNoteId,+ cloneToNoteIds+ });++ const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;+ suggestion.notePath = note?.getBestNotePathString(hoistedNoteId);+ }++ if (suggestion.action === "search-notes") {+ const searchString = suggestion.noteTitle;+ appContext.triggerCommand("searchNotes", { searchString });+ return;+ }++ $el.setSelectedNotePath(suggestion.notePath);+ $el.setSelectedExternalLink(null);++ $el.autocomplete("val", suggestion.noteTitle);++ $el.autocomplete("close");++ $el.trigger("autocomplete:noteselected", [suggestion]);+ });++ $el.on("autocomplete:closed", () => {+ if (!String($el.val())?.trim()) {+ clearText($el);+ }+ });++ $el.on("autocomplete:opened", () => {+ if ($el.attr("readonly")) {+ $el.autocomplete("close");+ }+ });++ // 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);+ };+}++/**+ * Convenience function which triggers the display of recent notes in the autocomplete input and focuses it.+ *+ * @param inputElement - The input element to trigger recent notes on.+ */+export function triggerRecentNotes(inputElement: HTMLInputElement | null | undefined) {+ if (!inputElement) {+ return;+ }++ const $el = $(inputElement);+ showRecentNotes($el);+ $el.trigger("focus").trigger("select");+}++export default {+ autocompleteSourceForCKEditor,+ initNoteAutocomplete,+ showRecentNotes,+ showAllCommands,+ setText,+ init+};diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex d1afe15462..6864ece661 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -1,9 +1,7 @@-import { t } from "../../services/i18n";-import { useEffect } from "preact/hooks";-import note_autocomplete, { Options, type Suggestion } from "../../services/note_autocomplete";import type { RefObject } from "preact";import type { CSSProperties } from "preact/compat";-import { useSyncedRef } from "./hooks";++import type { Options, Suggestion } from "../../services/note_autocomplete";interface NoteAutocompleteProps {id?: string;@@ -25,91 +23,6 @@ interface NoteAutocompleteProps {tabIndex?: number;}-export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, onChange, onTextChange, container, containerStyle, opts, noteId, noteIdChanged, onKeyDown, onBlur, readOnly, tabIndex }: 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")- .off("autocomplete:commandselected")-- note_autocomplete.initNoteAutocomplete($autoComplete, {- ...opts,- container: container?.current- });- if (onTextChange) {- $autoComplete.on("input", () => onTextChange($autoComplete[0].value));- }- if (onKeyDown) {- $autoComplete.on("keydown", (e) => e.originalEvent && onKeyDown(e.originalEvent));- }- if (onBlur) {- $autoComplete.on("blur", () => onBlur($autoComplete.getSelectedNoteId() ?? ""));- }- }, [opts, container?.current]);-- // 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);- }- };- const changeListener = (e) => {- if (!ref.current?.value) {- autoCompleteListener(e, null);- }- };- $autoComplete- .on("autocomplete:noteselected", autoCompleteListener)- .on("autocomplete:externallinkselected", autoCompleteListener)- .on("autocomplete:commandselected", autoCompleteListener)- .on("change", changeListener);- return () => {- $autoComplete- .off("autocomplete:noteselected", autoCompleteListener)- .off("autocomplete:externallinkselected", autoCompleteListener)- .off("autocomplete:commandselected", autoCompleteListener)- .off("change", changeListener);- };- }- }, [opts, container?.current, onChange, noteIdChanged])-- useEffect(() => {- if (!ref.current) return;- const $autoComplete = $(ref.current);-- if (noteId) {- $autoComplete.setNote(noteId);- } else if (text) {- note_autocomplete.setText($autoComplete, text);- } else {- $autoComplete.setSelectedNotePath("");- $autoComplete.autocomplete("val", "");- ref.current.value = "";- }- }, [text, noteId]);-- return (- <div className="input-group" style={containerStyle}>- <input- id={id}- ref={ref}- className="note-autocomplete form-control"- readOnly={readOnly}- tabIndex={tabIndex}- placeholder={placeholder ?? t("add_link.search_note")} />- </div>- );+export default function NoteAutocomplete(_props: NoteAutocompleteProps) {+ return <div>Hello world</div>;}diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.spec.tsxsimilarity index 96%rename from apps/client/src/widgets/react/NoteAutocomplete.spec.tsxrename to apps/client/src/widgets/react/NoteAutocomplete_bak.spec.tsxindex e4b302f310..191eb43864 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete_bak.spec.tsx@@ -8,7 +8,7 @@ vi.mock("../../services/note_autocomplete", () => ({import $ from "jquery";import { renderInto } from "../../test/render";-import NoteAutocomplete from "./NoteAutocomplete";+import NoteAutocomplete from "./NoteAutocomplete_bak";// The autocomplete plugin is not loaded here, so the calls that clear an empty input are stubbed.type PluggedIn = {diff --git a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsxnew file mode 100644index 0000000000..d1afe15462--- /dev/null+++ b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx@@ -0,0 +1,115 @@+import { t } from "../../services/i18n";+import { useEffect } from "preact/hooks";+import note_autocomplete, { Options, type Suggestion } from "../../services/note_autocomplete";+import type { RefObject } from "preact";+import type { CSSProperties } from "preact/compat";+import { useSyncedRef } from "./hooks";++interface NoteAutocompleteProps {+ id?: string;+ inputRef?: RefObject<HTMLInputElement>;+ text?: string;+ placeholder?: string;+ container?: RefObject<HTMLElement | null | undefined>;+ containerStyle?: CSSProperties;+ opts?: Omit<Options, "container">;+ onChange?: (suggestion: Suggestion | null) => void;+ onTextChange?: (text: string) => void;+ onKeyDown?: (e: KeyboardEvent) => void;+ onBlur?: (newValue: string) => void;+ noteIdChanged?: (noteId: string) => void;+ noteId?: string;+ /** Shows the selected note without allowing a different one to be picked. */+ readOnly?: boolean;+ /** Places the input in the tab order of a host that orders its fields with `tabIndex`. */+ tabIndex?: number;+}++export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, onChange, onTextChange, container, containerStyle, opts, noteId, noteIdChanged, onKeyDown, onBlur, readOnly, tabIndex }: 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")+ .off("autocomplete:commandselected")++ note_autocomplete.initNoteAutocomplete($autoComplete, {+ ...opts,+ container: container?.current+ });+ if (onTextChange) {+ $autoComplete.on("input", () => onTextChange($autoComplete[0].value));+ }+ if (onKeyDown) {+ $autoComplete.on("keydown", (e) => e.originalEvent && onKeyDown(e.originalEvent));+ }+ if (onBlur) {+ $autoComplete.on("blur", () => onBlur($autoComplete.getSelectedNoteId() ?? ""));+ }+ }, [opts, container?.current]);++ // 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);+ }+ };+ const changeListener = (e) => {+ if (!ref.current?.value) {+ autoCompleteListener(e, null);+ }+ };+ $autoComplete+ .on("autocomplete:noteselected", autoCompleteListener)+ .on("autocomplete:externallinkselected", autoCompleteListener)+ .on("autocomplete:commandselected", autoCompleteListener)+ .on("change", changeListener);+ return () => {+ $autoComplete+ .off("autocomplete:noteselected", autoCompleteListener)+ .off("autocomplete:externallinkselected", autoCompleteListener)+ .off("autocomplete:commandselected", autoCompleteListener)+ .off("change", changeListener);+ };+ }+ }, [opts, container?.current, onChange, noteIdChanged])++ useEffect(() => {+ if (!ref.current) return;+ const $autoComplete = $(ref.current);++ if (noteId) {+ $autoComplete.setNote(noteId);+ } else if (text) {+ note_autocomplete.setText($autoComplete, text);+ } else {+ $autoComplete.setSelectedNotePath("");+ $autoComplete.autocomplete("val", "");+ ref.current.value = "";+ }+ }, [text, noteId]);++ return (+ <div className="input-group" style={containerStyle}>+ <input+ id={id}+ ref={ref}+ className="note-autocomplete form-control"+ readOnly={readOnly}+ tabIndex={tabIndex}+ placeholder={placeholder ?? t("add_link.search_note")} />+ </div>+ );+}