Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): leave an input method's composition alone

Elian Doran79a4982ec62e
diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.ts
index ea96c06fe2..d24c18abd2 100644
--- a/apps/client/src/services/note_autocomplete_bak.spec.ts
+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts
@@ -167,41 +167,6 @@ describe("autocompleteSource (via dataset)", () => {
});
});
-describe("source debounce", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.useFakeTimers();
- getActiveContextNoteId.mockReturnValue("activeNote");
- registerAutocompleteStub();
- server.get = vi.fn(async () => []) as typeof server.get;
- noteAutocomplete.init();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("debounces and skips the search while composing input", async () => {
- const { $el, dataset } = initAndGetSource();
- // simulate IME composition active
- $el.trigger("compositionstart");
- const cb = vi.fn();
- dataset.source("hi", cb);
- await vi.runAllTimersAsync();
- // isComposingInput is true -> autocompleteSource not invoked
- expect(server.get).not.toHaveBeenCalled();
- expect(cb).not.toHaveBeenCalled();
- });
-
- it("runs the search after the debounce when not composing", async () => {
- const { dataset } = initAndGetSource();
- const cb = vi.fn();
- dataset.source("hi", cb);
- await vi.runAllTimersAsync();
- expect(server.get).toHaveBeenCalled();
- });
-});
-
describe("$.fn jQuery extensions (init)", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -373,16 +338,6 @@ describe("initNoteAutocomplete wiring", () => {
expect(autocompleteKeydown).toHaveBeenCalledOnce();
});
- it("composition end re-sets the autocomplete value", () => {
- const $el = makeEl();
- noteAutocomplete.initNoteAutocomplete($el);
- $el.autocomplete("val", "composed");
- $el.trigger("compositionstart");
- $el.trigger("compositionend");
- // value was read then re-applied -> still "composed"
- expect($el.autocomplete("val")).toBe("composed");
- });
-
});
describe("autocomplete:selected handler", () => {
diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.ts
index 384e5c915d..2fab0d4ee4 100644
--- a/apps/client/src/services/note_autocomplete_bak.ts
+++ b/apps/client/src/services/note_autocomplete_bak.ts
@@ -51,18 +51,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, 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");
if (options.allowJumpToSearchNotes) {
@@ -103,9 +91,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
{
source: (term, cb) => {
scheduleSearch(() => {
- if (isComposingInput) {
- return;
- }
// Returned so the scheduler holds the next search until this one settles.
return autocompleteSource(term, cb, options);
});
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index 65bcac6917..08bafbdd85 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -255,6 +255,9 @@ interface UseAutocompleteOptions<T> {
*/
export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled, openOnFocus, openOnEnter, keepOpenOnPick, autoActivate, isHeading, textOf = String, schedule }: UseAutocompleteOptions<T>) {
const [ isOpen, setIsOpen ] = useState(false);
+ // What an input method is composing is not yet what the user means, so nothing is looked up for
+ // it until the composition ends.
+ const [ isComposing, setIsComposing ] = useState(false);
const [ items, setItems ] = useState<T[]>([]);
const [ activeIndex, setActiveIndex ] = useState(-1);
@@ -281,7 +284,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
// Fetch suggestions for the current query, debounced. The previous items stay visible while
// the request is in flight, so refining a query does not make the dropdown flicker.
useEffect(() => {
- if (!isOpen) {
+ if (!isOpen || isComposing) {
return;
}
@@ -306,7 +309,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
const timeout = setTimeout(lookUp, DEBOUNCE_MS);
return () => clearTimeout(timeout);
- }, [ isOpen, query, source, autoActivate, isHeading, textOf, schedule ]);
+ }, [ isOpen, isComposing, query, source, autoActivate, isHeading, textOf, schedule ]);
// Keep the highlighted entry in sight: it can be picked out on opening, or arrowed past the
// bottom of a list taller than the room the dropdown was given.
@@ -334,6 +337,9 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
}
function handleKeyDown(e: KeyboardEvent) {
+ // The keys belong to the input method, such as the Enter that commits a candidate.
+ if (e.isComposing) return;
+
switch (e.key) {
case "ArrowDown":
case "ArrowUp":
@@ -387,6 +393,12 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
if (openOnFocus) open();
},
handleBlur: close,
+ handleCompositionStart() {
+ setIsComposing(true);
+ },
+ handleCompositionEnd() {
+ setIsComposing(false);
+ },
handleKeyDown,
/** The field's combobox attributes. */
comboboxProps: {
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 7057728190..038a376ae2 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -492,6 +492,32 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(onKeyDown).not.toHaveBeenCalledWith(shiftEnter);
});
+ it("searches for what an input method commits, not what it is composing", async () => {
+ const onChange = vi.fn();
+ const input = await mount({ onChange });
+ await type(input, "n");
+ getNoteSuggestions.mockClear();
+
+ await act(async () => { input.dispatchEvent(new Event("compositionstart", { bubbles: true })); });
+ await type(input, "ni");
+ await type(input, "nih");
+ expect(getNoteSuggestions).not.toHaveBeenCalled();
+
+ // The Enter that commits a candidate, and a Shift+Enter, belong to the input method.
+ for (const shiftKey of [ false, true ]) {
+ const key = new KeyboardEvent("keydown", { key: "Enter", shiftKey, isComposing: true, bubbles: true, cancelable: true });
+ await act(async () => { input.dispatchEvent(key); });
+ expect(key.defaultPrevented).toBe(false);
+ }
+ await settle();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(getNoteSuggestions).not.toHaveBeenCalled();
+
+ await act(async () => { input.dispatchEvent(new Event("compositionend", { bubbles: true })); });
+ await settle();
+ expect(getNoteSuggestions.mock.calls).toEqual([ [ "nih" ] ]);
+ });
+
it("spans the whole field, the buttons included", async () => {
const input = await mount();
const group = input.closest(".input-group");
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index dfc30120cd..2865b25cbc 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -200,7 +200,9 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
if (!e.currentTarget.value) clearSelection();
}}
onKeyDown={(e) => {
- if (e.key === "Enter" && e.shiftKey) {
+ // An Enter while composing commits the input method's candidate instead.
+ const isEnter = e.key === "Enter" && !e.isComposing;
+ if (isEnter && e.shiftKey) {
// Kept from the host and the list, as the jQuery plugin did.
e.preventDefault();
e.stopPropagation();
@@ -209,7 +211,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}
// The rows of the fast search stay behind the row saying it is searching, so Enter
// waits for the full-text results instead of taking one of them.
- if (e.key === "Enter" && isSearchingFullText) {
+ if (isEnter && isSearchingFullText) {
e.preventDefault();
return;
}
@@ -220,6 +222,8 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}
onKeyDown?.(e);
}}
+ onCompositionStart={autocomplete.handleCompositionStart}
+ onCompositionEnd={autocomplete.handleCompositionEnd}
onBlur={() => {
// A list in the host's container stays open until a pick.
if (!container) autocomplete.handleBlur();