Skip to content

Build your personal knowledge base with Trilium Notes

fix(attributes): keep filtering while the typed text spells a choice

Elian Doran3f559fb25034
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx
index 093807832a..afc49a8d02 100644
--- a/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx
@@ -217,6 +217,42 @@ describe("LabelValueInput", () => {
expect(onCommit).toHaveBeenCalledWith("Blocked");
});
+ it("filters by typed text even when it retypes the stored value, bolding the match", async () => {
+ const onCommit = vi.fn();
+ // "Blo" is a stale value: stored once, but no longer among the options.
+ await mount({
+ labelType: "select", value: "Blo", selectOptions: [ "Alpha", "Beta" ],
+ onCommit, onCreateOption: vi.fn()
+ });
+
+ const input = container.querySelector("input");
+ await act(async () => input?.focus());
+ // Opened without typing: every choice is offered, the stored text notwithstanding.
+ expect((await settleDropdown()).map((item) => item.textContent)).toEqual([ "Alpha", "Beta" ]);
+
+ // Typing the very text the box already held must still filter (and offer creating it):
+ // the list follows the typing, not how the text compares to the value. Typed in two
+ // keystrokes, as a user would: a lone input event carrying the unchanged text is
+ // indistinguishable from no edit at all.
+ await typeInto(input, "B");
+ await typeInto(input, "Blo");
+ const items = await settleDropdown();
+ expect(items).toHaveLength(1);
+ expect(items[0]?.querySelector(".label-select-create-option")).not.toBeNull();
+
+ // The part an entry matched is set in bold.
+ await typeInto(input, "et");
+ const [ beta ] = await settleDropdown();
+ expect(beta?.innerHTML).toContain("B<b>et</b>a");
+
+ // Even text spelling an option exactly keeps filtering and bolding: it is not yet a
+ // pick, so nothing commits and the list must not snap back to everything.
+ await typeInto(input, "Beta");
+ const [ exact ] = await settleDropdown();
+ expect(exact?.innerHTML).toContain("<b>Beta</b>");
+ expect(onCommit).not.toHaveBeenCalled();
+ });
+
it("reverts unpicked text on blur, while an emptied box commits the unset value", async () => {
const onCommit = vi.fn();
await mount({
@@ -232,11 +268,18 @@ describe("LabelValueInput", () => {
expect(onCommit).not.toHaveBeenCalled();
expect(input?.value).toBe("Todo");
+ // Leaving after typing an option's full name commits it like a pick, in its own casing.
+ await typeInto(input, "done");
+ await act(async () => {
+ input?.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
+ });
+ expect(onCommit).toHaveBeenLastCalledWith("Done");
+
await typeInto(input, "");
await act(async () => {
input?.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
});
- expect(onCommit).toHaveBeenCalledWith("");
+ expect(onCommit).toHaveBeenLastCalledWith("");
});
});
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
index 9249d357d9..f8e6e59afa 100644
--- a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
@@ -240,25 +240,32 @@ function SelectComboBox({ options, value, onCommit, onCreateOption, inputProps }
const [ draft, setDraft ] = useState(value);
// What the note holds is what the box shows, however the value came to change.
useEffect(() => setDraft(value), [ value ]);
+ // Whether the text is something typed this visit, rather than the value the box opened with.
+ // Only typed text filters the list and offers creating: comparing the text against the value
+ // instead would stop filtering whenever typing happens to pass through it (retyping what was
+ // erased, or reproducing a stale value), which is exactly when the list must keep up.
+ const typedSinceFocus = useRef(false);
// Narrowed because Preact types the attribute as possibly signal-backed, while the text box
// underneath takes the plain string.
const { id, ...restInputProps } = inputProps ?? {};
+ // What the list is narrowed by: the typed text, or nothing while the box still shows the value
+ // it opened with — reopening a filled field offers every choice, not the one already made.
+ const filter = typedSinceFocus.current ? draft.trim() : "";
+
const source = useCallback(async (query: string) => {
const trimmed = query.trim();
- // The stored value in the box means the list was only just opened, so the whole of it is
- // offered rather than the near-empty tail that filtering by the value would leave.
- const items = !trimmed || trimmed === value
- ? [ ...options ]
- : options.filter((option) => option.toLowerCase().includes(trimmed.toLowerCase()));
+ const typed = typedSinceFocus.current ? trimmed : "";
+ const items = typed
+ ? options.filter((option) => option.toLowerCase().includes(typed.toLowerCase()))
+ : [ ...options ];
- if (trimmed && trimmed !== value
- && !options.some((option) => option.toLowerCase() === trimmed.toLowerCase())) {
+ if (typed && !options.some((option) => option.toLowerCase() === typed.toLowerCase())) {
items.push(CREATE_OPTION_SENTINEL + trimmed);
}
return items;
- }, [ options, value ]);
+ }, [ options ]);
return (
<FormAutocomplete
@@ -273,27 +280,45 @@ function SelectComboBox({ options, value, onCommit, onCreateOption, inputProps }
<span className="bx bx-plus" />{" "}
{t("promoted_attributes.create_option", { option: item.substring(CREATE_OPTION_SENTINEL.length) })}
</span>
- : item}
+ : highlightMatch(item, filter)}
onChange={(newValue) => {
- if (newValue.startsWith(CREATE_OPTION_SENTINEL)) {
- const option = newValue.substring(CREATE_OPTION_SENTINEL.length);
+ // Typing only — a made choice arrives through onPick — so the text is never a
+ // commit, only the filter. Even text spelling an option exactly keeps filtering:
+ // "bar" typed on the way to "barr" is not yet a decision for either.
+ typedSinceFocus.current = true;
+ setDraft(newValue);
+ }}
+ onPick={(item) => {
+ // A made choice resets the box to its opened-with state: the text is the value
+ // again, so the list is back to offering everything.
+ typedSinceFocus.current = false;
+ if (item.startsWith(CREATE_OPTION_SENTINEL)) {
+ const option = item.substring(CREATE_OPTION_SENTINEL.length);
void onCreateOption(option);
setDraft(option);
onCommit(option);
- } else if (options.includes(newValue)) {
- setDraft(newValue);
- onCommit(newValue);
} else {
- // Not a pick yet — the text is a filter, held until an entry is chosen.
- setDraft(newValue);
+ setDraft(item);
+ onCommit(item);
}
}}
onBlur={(leftBehind) => {
- if (!leftBehind.trim()) {
+ typedSinceFocus.current = false;
+ const trimmed = leftBehind.trim();
+ if (!trimmed) {
setDraft("");
if (value) {
onCommit("");
}
+ return;
+ }
+
+ // Text spelling an option's full name is as good as picking it — leaving the field
+ // after typing it out must not throw the choice away. The option's own casing wins.
+ const match = options.find((option) => option.toLowerCase() === trimmed.toLowerCase());
+ if (match && match !== value) {
+ setDraft(match);
+ onCommit(match);
} else if (leftBehind !== value) {
setDraft(value);
}
@@ -302,6 +327,23 @@ function SelectComboBox({ options, value, onCommit, onCreateOption, inputProps }
);
}
+/**
+ * An option with the part the typed text matched set in bold, so a filtered list shows why each of
+ * its entries is still there. Case-insensitive like the filtering, first occurrence only — the same
+ * match the filter found. Without a filter (or, defensively, without a match) the text is plain.
+ */
+function highlightMatch(text: string, filter: string) {
+ const index = filter ? text.toLowerCase().indexOf(filter.toLowerCase()) : -1;
+ if (index < 0) {
+ return text;
+ }
+ return <>
+ {text.substring(0, index)}
+ <b>{text.substring(index, index + filter.length)}</b>
+ {text.substring(index + filter.length)}
+ </>;
+}
+
/**
* The choices a select offers: the unset entry first — a promoted field can always be left blank, and
* it wears the host's placeholder so "not set" reads the same as in a text field — then the defined
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index 452859bcac..0bea35cdd7 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -27,6 +27,13 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
source(query: string): Promise<string[]>;
/** Opens the dropdown as soon as the field receives focus, not just on typing. */
openOnFocus?: boolean;
+ /**
+ * Receives a suggestion picked from the dropdown (click or Enter) instead of `onChange`, for a
+ * host that treats a made choice differently from typing — both otherwise arrive as the same
+ * string. Left out, picking reports through `onChange`, exactly like typing. (Not `onSelect`,
+ * which is the DOM's own text-selection event and reaches the input as such.)
+ */
+ onPick?(item: string): void;
/**
* Renders one suggestion, for lists where the bare text does not tell the whole story. Only the
* appearance of the row is affected: what a suggestion means and what selecting it commits stay
@@ -41,7 +48,7 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
* The dropdown is portalled to the body and positioned over everything else, so it is not clipped
* by scrolling ancestors. Selecting a suggestion reports it through `onChange`, exactly like typing.
*/
-export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, renderItem, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {
+export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, onPick, renderItem, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {
const ownInputRef = useRef<HTMLInputElement>(null);
const inputEl = inputRef ?? ownInputRef;
const dropdownRef = useRef<HTMLUListElement>(null);
@@ -106,7 +113,7 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
}, [ isOpen, items.length, inputEl ]);
function selectItem(item: string) {
- onChange(item);
+ (onPick ?? onChange)(item);
close();
inputEl.current?.focus();
}