Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): suggest promoted label values through FormAutocomplete

Elian Doranc655e023d0ac
diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsx
index bce14961f2..93a4b19ad3 100644
--- a/apps/client/src/widgets/PromotedAttributes.spec.tsx
+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx
@@ -4,8 +4,8 @@ import { useState } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-// A relation's target is picked in an Algolia autocomplete bound to jQuery, which is not loaded
-// here; a plain input in its place keeps the cell around it assertable.
+// `NoteAutocomplete` has a spec of its own and reaches the server for its suggestions; a plain
+// input in its place keeps the cell around it assertable.
vi.mock("./react/NoteAutocomplete", () => ({
default: ({ id, noteId, tabIndex }: { id?: string; noteId?: string; tabIndex?: number }) =>
<input id={id} tabIndex={tabIndex} className="note-autocomplete-stub" value={noteId} />
@@ -54,8 +54,6 @@ vi.mock("../services/ws", async (importOriginal) => {
};
});
-import $ from "jquery";
-
import type Component from "../components/component";
import FAttribute from "../entities/fattribute";
import type FNote from "../entities/fnote";
@@ -69,12 +67,6 @@ import { renderInto } from "../test/render";
import { ParentComponent } from "./react/react_utils";
import PromotedAttributes, { buildPromotedCells, PromotedAttributesContent, usePromotedAttributeData } from "./PromotedAttributes";
-// A text field offers the values other notes hold under its name through the Algolia plugin, which
-// is not loaded here; a stub that chains like jQuery does keeps the field's setup on its feet.
-type PluggedIn = { autocomplete(...args: unknown[]): PluggedIn };
-const autocompleteMock = vi.fn(function (this: PluggedIn) { return this; });
-($.fn as unknown as PluggedIn).autocomplete = autocompleteMock;
-
// The fields reach the server through these three; every suite stands them down, and the ones
// asserting on what was written reach for these same handles.
const serverGetMock = vi.fn(async () => [] as string[]);
@@ -573,27 +565,44 @@ describe("PromotedAttributesContent rendering", () => {
);
});
- it("fetches suggestion values only for text attributes", async () => {
- await renderCells(note, [ buildCell(note, { name: "tags", definition: { labelType: "text" } }) ]);
+ it("offers the values a text label's name holds, committing a pick once the field is left", async () => {
+ serverGetMock.mockResolvedValue([ "alpha", "beta" ]);
+ const container = await renderCells(note, [
+ buildCell(note, { name: "tags", definition: { labelType: "text" } })
+ ]);
+
+ const input = container.querySelector<HTMLInputElement>("input.promoted-attribute-input");
+ expect(input).not.toBeNull();
+ await act(async () => input?.focus());
+ const items = await settleDropdown();
expect(serverGetMock).toHaveBeenCalledWith("attribute-values/tags");
+ expect(items.map((item) => item.textContent)).toEqual([ "alpha", "beta" ]);
- serverGetMock.mockClear();
- await renderCells(note, [ buildCell(note, { definition: { labelType: "number" }, uniqueId: "num" }) ]);
- expect(serverGetMock).not.toHaveBeenCalled();
- });
+ await act(async () => (items[1] as HTMLElement | undefined)?.click());
+ expect(input?.value).toBe("beta");
+ expect(serverPutMock).not.toHaveBeenCalled();
- it("binds the suggestion list only where there is something to suggest", async () => {
- serverGetMock.mockResolvedValueOnce([ "one", "two" ]);
- await renderCells(note, [ buildCell(note, { name: "tags", definition: { labelType: "text" } }) ]);
- expect(autocompleteMock).toHaveBeenCalled();
+ await act(async () => {
+ input?.dispatchEvent(new Event("focusout", { bubbles: true }));
+ });
+ expect(serverPutMock).toHaveBeenCalledWith(
+ `notes/${note.noteId}/attribute`,
+ expect.objectContaining({ name: "tags", value: "beta" }),
+ "test-component"
+ );
+ });
- autocompleteMock.mockClear();
- await renderCells(note, [ buildCell(note, { name: "flag", definition: { labelType: "boolean" }, uniqueId: "flag" }) ]);
- expect(autocompleteMock).not.toHaveBeenCalled();
+ it("offers no values in a field of another type", async () => {
+ serverGetMock.mockResolvedValue([ "1", "2" ]);
+ const container = await renderCells(note, [
+ buildCell(note, { name: "size", definition: { labelType: "number" } })
+ ]);
- // A text field whose name nothing else holds a value under is bound no more than a flag is.
- await renderCells(note, [ buildCell(note, { name: "fresh", definition: { labelType: "text" }, uniqueId: "fresh" }) ]);
- expect(autocompleteMock).not.toHaveBeenCalled();
+ const input = container.querySelector<HTMLInputElement>("input.promoted-attribute-input");
+ expect(input).not.toBeNull();
+ await act(async () => input?.focus());
+ expect(await settleDropdown()).toEqual([]);
+ expect(serverGetMock).not.toHaveBeenCalled();
});
it("hands a multi text field the values the name holds, and the other kinds none", async () => {
@@ -766,6 +775,14 @@ async function renderCells(note: FNote, cells: CellLike[], setCells = vi.fn()) {
return container;
}
+/** Lets the debounced lookup run, then returns the rows of the list portaled to the body. */
+async function settleDropdown() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ });
+ return [ ...document.querySelectorAll(".form-autocomplete-dropdown li") ];
+}
+
/** Runs the hook against a real note and returns the cells it derived. */
async function collectCells(note: FNote | null | undefined, context: unknown = { viewScope: { viewMode: "default" } }) {
let cells: CellLike[] | undefined;
diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsx
index 4cfc999f68..3b31f187aa 100644
--- a/apps/client/src/widgets/PromotedAttributes.tsx
+++ b/apps/client/src/widgets/PromotedAttributes.tsx
@@ -2,7 +2,7 @@ import "./PromotedAttributes.css";
import { DefinitionObject, extractAttributeDefinitionTypeAndName, UpdateAttributeResponse } from "@triliumnext/commons";
import clsx from "clsx";
-import { ComponentChild, TargetedEvent } from "preact";
+import { ComponentChild } from "preact";
import { Dispatch, StateUpdater, useCallback, useEffect, useState } from "preact/hooks";
import NoteContext from "../components/note_context";
@@ -18,6 +18,7 @@ import LabelValueInput, { useLabelValueSuggestions } from "./attribute_widgets/l
import MultiValueInput from "./attribute_widgets/multi_value_input";
import RelationValuesInput from "./attribute_widgets/relation_values_input";
import ColorPicker from "./react/ColorPicker";
+import FormAutocomplete from "./react/FormAutocomplete";
import { useNoteContext, useNoteLabel, useTriliumEvent, useUniqueName } from "./react/hooks";
import NoteAutocomplete from "./react/NoteAutocomplete";
@@ -44,9 +45,6 @@ interface CellProps {
setCells: Dispatch<StateUpdater<Cell[] | undefined>>;
}
-type OnChangeEventData = TargetedEvent<HTMLInputElement | HTMLTextAreaElement, Event> | InputEvent | JQuery.TriggeredEvent<HTMLInputElement, undefined, HTMLInputElement, HTMLInputElement>;
-type OnChangeListener = (e: OnChangeEventData) => void | Promise<void>;
-
export default function PromotedAttributes({ omit }: {
/**
* Names of definitions to leave out, for a host that shows what they hold better than a field
@@ -227,39 +225,44 @@ function LabelInput(props: CellProps & { inputId: string }) {
[ cell, componentId, note, setCells ]);
const createOption = useCreateSelectOption(definitionAttr, componentId, setCells);
-
- useTextLabelAutocomplete(inputId, valueAttr, definition, (e) => {
- if (e.currentTarget instanceof HTMLInputElement) {
- setDraft(e.currentTarget.value);
- }
- });
+ const suggestValues = useLabelValueSuggestions(valueName);
// React to model changes.
useEffect(() => {
setDraft(valueAttr.value);
}, [ valueAttr.value ]);
- const input = (
- <LabelValueInput
+ const inputProps = {
+ className: "form-control promoted-attribute-input",
+ tabIndex: 200 + definitionAttr.position,
+ id: inputId,
+ placeholder: t("promoted_attributes.unset-field-placeholder"),
+ "data-attribute-id": valueAttr.attributeId,
+ "data-attribute-type": valueAttr.type,
+ "data-attribute-name": valueAttr.name
+ };
+
+ // A text value commits on blur like the other types, so a picked suggestion only fills in the
+ // draft.
+ const input = labelType === "text"
+ ? <FormAutocomplete
+ {...inputProps}
+ currentValue={valueDraft ?? ""}
+ source={suggestValues}
+ openOnFocus
+ onChange={setDraft}
+ onBlur={commit}
+ />
+ : <LabelValueInput
labelType={labelType}
- // The draft is what the field shows: the autocomplete writes into it as the user picks.
- value={(labelType === "boolean" ? valueAttr.value : valueDraft) ?? ""}
+ value={valueAttr.value ?? ""}
onCommit={commit}
commitOn="blur"
numberPrecision={definition.numberPrecision}
selectOptions={definition.selectOptions}
onCreateOption={labelType === "select" ? createOption : undefined}
- inputProps={{
- className: "form-control promoted-attribute-input",
- tabIndex: 200 + definitionAttr.position,
- id: inputId,
- placeholder: t("promoted_attributes.unset-field-placeholder"),
- "data-attribute-id": valueAttr.attributeId,
- "data-attribute-type": valueAttr.type,
- "data-attribute-name": valueAttr.name
- }}
- />
- );
+ inputProps={inputProps}
+ />;
if (labelType === "boolean") {
return <>
@@ -309,8 +312,7 @@ function MultiLabelInput({ inputId, note, cell, componentId, setCells }: CellPro
<MultiValueInput
labelType={labelType}
values={values ?? []}
- // Matches the single-value field, which useTextLabelAutocomplete limits to
- // `text`.
+ // Matches the single-value field, which offers suggestions for `text` alone.
source={labelType === "text" ? suggestValues : undefined}
options={definition.selectOptions}
onCreateOption={labelType === "select" ? createOption : undefined}
@@ -383,59 +385,6 @@ function MultiRelationInput({ inputId, note, cell, componentId, setCells }: Cell
);
}
-function useTextLabelAutocomplete(inputId: string, valueAttr: Attribute, definition: DefinitionObject, onChangeListener: OnChangeListener) {
- const [ attributeValues, setAttributeValues ] = useState<{ value: string }[] | null>(null);
-
- // Obtain data.
- useEffect(() => {
- // A nameless attribute has no values to suggest, and would request `attribute-values/`, which
- // matches no route.
- if (definition.labelType !== "text" || !valueAttr.name) {
- return;
- }
-
- server.get<string[]>(`attribute-values/${encodeURIComponent(valueAttr.name)}`).then((_attributesValues) => {
- setAttributeValues(_attributesValues.map((attribute) => ({ value: attribute })));
- });
- }, [ definition.labelType, valueAttr.name ]);
-
- // Initialize autocomplete.
- useEffect(() => {
- if (!attributeValues?.length) return;
- const el = document.getElementById(inputId) as HTMLInputElement | null;
- if (!el) return;
-
- const $input = $(el);
- $input.autocomplete(
- {
- appendTo: document.querySelector("body"),
- hint: false,
- autoselect: false,
- openOnFocus: true,
- minLength: 0,
- tabAutocomplete: false
- },
- [
- {
- displayKey: "value",
- source (term, cb) {
- term = term.toLowerCase();
-
- const filtered = (attributeValues ?? []).filter((attr) => attr.value.toLowerCase().includes(term));
-
- cb(filtered);
- }
- }
- ]
- );
-
- $input.off("autocomplete:selected");
- $input.on("autocomplete:selected", onChangeListener);
-
- return () => $input.autocomplete("destroy");
- }, [ inputId, attributeValues, onChangeListener ]);
-}
-
async function updateAttribute(note: FNote, cell: Cell, componentId: string, value: string | undefined, setCells: Dispatch<StateUpdater<Cell[] | undefined>>) {
if (value === cell.valueAttr.value) return;
const { attributeId } = await server.put<UpdateAttributeResponse>(