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
feat(autocomplete): set the typed text in bold in client-filtered lists
Elian Doran46c1bdb2501e
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex 51a271d947..ecffa2bb1e 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -29,7 +29,7 @@ import FormTextBox, { FormTextBoxWithUnit } from "../react/FormTextBox.jsx";import HelpTooltipButton from "../react/HelpTooltipButton.jsx";import Icon from "../react/Icon.jsx";import { suspendModalFocusTraps } from "../react/modal_focustrap.js";-import NoteAutocomplete from "../react/NoteAutocomplete.jsx";+import NoteAutocomplete, { HighlightedText } from "../react/NoteAutocomplete.jsx";import NoteLink, { NewNoteLink } from "../react/NoteLink.jsx";import { disposeReactWidget, ParentComponent, renderReactWidgetAtElement } from "../react/react_utils.jsx";import OptionsRow, { OptionsRowWithToggle } from "../type_widgets/options/components/OptionsRow.jsx";@@ -388,11 +388,11 @@ export function AttributeForm({ opts, attrType: initialAttrType, currentNoteId,? fetchDefinitionNames(nameType, query): fetchAttributeNames(nameType, query), [ nameType, isDefinitionType ]);const renderNameSuggestion = useCallback(- (suggestion: string) => <AttributeNameSuggestion type={nameType} name={suggestion} />, [ nameType ]);+ (suggestion: string, query: string) => <AttributeNameSuggestion type={nameType} name={suggestion} query={query} />, [ nameType ]);// Whatever a relation is the inverse of is itself a relation.const suggestRelationNames = useCallback((query: string) => fetchAttributeNames("relation", query), []);const renderRelationSuggestion = useCallback(- (suggestion: string) => <AttributeNameSuggestion type="relation" name={suggestion} />, []);+ (suggestion: string, query: string) => <AttributeNameSuggestion type="relation" name={suggestion} query={query} />, []);const [ name, setName ] = useState(() => stripDefinitionPrefix(attribute.name, attrType));const [ value, setValue ] = useState(attribute.value ?? "");const [ isInheritable, setIsInheritable ] = useState(!!attribute.isInheritable);@@ -788,7 +788,12 @@ function AttributeNameField({ help, ...autocompleteProps }: { help?: AttrHelpEnt* Exported, with {@link fetchAttributeNames}, for whatever else completes an attribute name — the* attribute panel's in-row creation — so every name box offers the same list the same way.*/-export function AttributeNameSuggestion({ type, name }: { type: "label" | "relation"; name: string }) {+export function AttributeNameSuggestion({ type, name, query = "" }: {+ type: "label" | "relation";+ name: string;+ /** The text typed, set in bold where the name holds it. */+ query?: string;+}) {const isSystem = isBuiltinAttribute(type, name);return (@@ -799,7 +804,7 @@ export function AttributeNameSuggestion({ type, name }: { type: "label" | "relat><Icon icon={attributeKindIcon(type, name, "")} /></span>- <span class="attr-name-suggestion-name">{name}</span>+ <span class="attr-name-suggestion-name"><HighlightedText text={name} query={query} /></span></span>);}diff --git a/apps/client/src/widgets/attribute_widgets/attribute_kind.css b/apps/client/src/widgets/attribute_widgets/attribute_kind.cssindex 02bfd79c5b..8a5540a9c7 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_kind.css+++ b/apps/client/src/widgets/attribute_widgets/attribute_kind.css@@ -65,3 +65,11 @@.form-autocomplete-dropdown .form-autocomplete-item.active .attr-name-suggestion .attribute-kind {--attribute-kind-cutout: var(--suggestion-active-background-color);}++/* The text typed, as `.note-autocomplete-menu` shows the search's matches in NoteAutocomplete.css. */+.attr-name-suggestion .attr-name-suggestion-name b {+ background: var(--note-list-view-search-result-highlight-background, transparent);+ color: var(--note-list-view-search-result-highlight-color, var(--admonition-warning-accent-color));+ font-weight: inherit;+ text-decoration: underline;+}diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsxindex f487b3aee7..a30f8386a3 100644--- a/apps/client/src/widgets/react/FormAutocomplete.tsx+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx@@ -55,9 +55,10 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {/*** 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- * the string the source returned. Defaults to showing that string.+ * the string the source returned. Defaults to showing that string. `query` is the text typed,+ * for setting what matches it in bold.*/- renderItem?(item: string): ComponentChildren;+ renderItem?(item: string, query: string): ComponentChildren;/*** Rendered inside the field, ahead of the box being typed into — the chips of a field holding* several values, which belong within its frame rather than above it.@@ -166,6 +167,7 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO<AutocompleteDropdownautocomplete={autocomplete}+ query={currentValue}// The wrapper where there is one, so a field carrying chips is spanned whole.anchor={fieldRef.current ?? inputEl.current}minWidth={dropdownMinWidth}@@ -194,7 +196,7 @@ export function AutocompleteList({ query, source, anchor, renderItem, onPick, haquery: string;source(query: string): Promise<string[]>;anchor: DropdownAnchor;- renderItem?(item: string): ComponentChildren;+ renderItem?(item: string, query: string): ComponentChildren;onPick(item: string): void;handleRef: MutableRef<AutocompleteListHandle | null>;elementRef?: PopupProps["elementRef"];@@ -210,6 +212,7 @@ export function AutocompleteList({ query, source, anchor, renderItem, onPick, hareturn (<AutocompleteDropdownautocomplete={autocomplete}+ query={query}anchor={anchor}minWidth={CARET_LIST_MIN_WIDTH}renderItem={renderItem}@@ -243,11 +246,13 @@ export function useForwardedKeys<T>(autocomplete: ReturnType<typeof useAutocompl* The list of a {@link useAutocomplete}, in a {@link Popup} under `anchor`, which places it again as* the list or the anchor changes size or moves.*/-function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem, isHeading, elementRef }: {+function AutocompleteDropdown({ autocomplete, query, anchor, minWidth = 0, renderItem, isHeading, elementRef }: {autocomplete: ReturnType<typeof useAutocomplete<string>>;+ /** The text typed, which `renderItem` is given. */+ query: string;anchor: DropdownAnchor | null;minWidth?: number;- renderItem?(item: string): ComponentChildren;+ renderItem?(item: string, query: string): ComponentChildren;isHeading?(item: string): boolean;elementRef?: PopupProps["elementRef"];}) {@@ -275,7 +280,7 @@ function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem,{items.map((item, index) => (isHeading?.(item)? <li key={item} className="form-autocomplete-heading" role="presentation">- {renderItem ? renderItem(item) : item}+ {renderItem ? renderItem(item, query) : item}</li>: <likey={item}@@ -286,7 +291,7 @@ function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem,onMouseMove={(e) => autocomplete.hover(index, e)}onClick={() => pick(item)}>- {renderItem ? renderItem(item) : item}+ {renderItem ? renderItem(item, query) : item}</li>))}</ul>diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxindex 58aea65bb3..2b79ad4511 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -22,7 +22,7 @@ import { collectShortcutHints } from "../../services/shortcut_hints";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";import type { AutocompleteListHandle } from "./FormAutocomplete";-import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList } from "./NoteAutocomplete";+import NoteAutocomplete, { HighlightedText, type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList } from "./NoteAutocomplete";import { ParentComponent } from "./react_utils";async function render(props: NoteAutocompleteProps = {}) {@@ -1280,3 +1280,19 @@ describe("NoteMentionList", () => {await unmount();});});++describe("HighlightedText", () => {+ it("sets the first occurrence of the query in bold, whatever its case, and nothing where there is none", () => {+ const html = (text: string, query: string) => {+ const host = document.createElement("div");+ preactRender(<HighlightedText text={text} query={query} />, host);+ return host.innerHTML;+ };++ expect(html("ownedLabelCount", "label")).toBe("owned<b>Label</b>Count");+ expect(html("labelCount", "la")).toBe("<b>la</b>belCount");+ expect(html("a<b>&", "<b")).toBe("a<b><b</b>>&");+ expect(html("title", "xyz")).toBe("title");+ expect(html("title", "")).toBe("title");+ });+});diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex 67ca1da408..140acb9ffa 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -540,7 +540,7 @@ export function CommandMentionList<T extends CommandEntry>({ query, source, anch<span><SuggestionRowContenticon={<CommandIcon entry={entry} />}- header={<span className="search-result-title">{entry.title}</span>}+ header={<span className="search-result-title"><HighlightedText text={entry.title} query={query} /></span>}details={entry.description && <span className="note-suggestion-description">{entry.description}</span>}/></span>@@ -592,6 +592,20 @@ export function createHostedList<S extends { caretRect(): DOMRect; editable: HTM};}+/**+ * `text` with the first occurrence of `query` in it, whatever its case, set in bold as the search+ * sets its matches in a note's title. For a list filtered on the client, which matches the same way.+ */+export function HighlightedText({ text, query }: { text: string; query: string }) {+ const at = query ? text.toLowerCase().indexOf(query.toLowerCase()) : -1;+ if (at < 0) {+ return <>{text}</>;+ }++ const end = at + query.length;+ return <>{text.slice(0, at)}<b>{text.slice(at, end)}</b>{text.slice(end)}</>;+}+function CommandIcon({ entry }: { entry: CommandEntry }) {if (entry.iconSvg) {return <RawHtml className="tn-icon note-suggestion-svg-icon" html={entry.iconSvg} />;diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsxindex 7be1a173f2..921edd7e7f 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx@@ -423,7 +423,7 @@ function attributeNameMention(marker: "#" | "~", type: "label" | "relation"): MeminimumCharacters: 0,list: () => createAutocompleteMentionList({source: (query) => fetchAttributeNames(type, query),- renderItem: (name) => <AttributeNameSuggestion type={type} name={name} />,+ renderItem: (name, query) => <AttributeNameSuggestion type={type} name={name} query={query} />,toMention: (name) => ({ id: `${marker}${name}` })})};diff --git a/apps/client/src/widgets/search_field_editor.spec.tsx b/apps/client/src/widgets/search_field_editor.spec.tsxindex 51e36b707d..2928848e50 100644--- a/apps/client/src/widgets/search_field_editor.spec.tsx+++ b/apps/client/src/widgets/search_field_editor.spec.tsx@@ -60,6 +60,7 @@ describe("createSearchFieldEditor", () => {type("#bo");const rows = () => menuRows(".form-autocomplete-dropdown");await vi.waitFor(() => expect(rows()).toEqual([ "book", "bookmark" ]));+ expect(matches(".form-autocomplete-dropdown")).toEqual([ "bo", "bo" ]);await press("Enter");expect(onEnter).toHaveBeenCalledOnce();@@ -80,6 +81,7 @@ describe("createSearchFieldEditor", () => {// Asked for, the list opens on the best match, so Enter takes it.type("no");await vi.waitFor(() => expect(rows()[0]).toBe("note"));+ expect(matches(".note-autocomplete-menu")[0]).toBe("no");await press("Enter");await vi.waitFor(() => expect(text()).toBe("#book note."));@@ -113,3 +115,8 @@ describe("createSearchFieldEditor", () => {function menuRows(menu: string) {return [ ...document.querySelectorAll(`${menu} [role=option]`) ].map((row) => row.textContent ?? "");}++/** What each row of `menu` sets in bold as matching the query. */+function matches(menu: string) {+ return [ ...document.querySelectorAll(`${menu} [role=option]`) ].map((row) => row.querySelector("b")?.textContent);+}diff --git a/apps/client/src/widgets/search_field_editor.tsx b/apps/client/src/widgets/search_field_editor.tsxindex 3907ae9ffd..d30416db47 100644--- a/apps/client/src/widgets/search_field_editor.tsx+++ b/apps/client/src/widgets/search_field_editor.tsx@@ -80,7 +80,7 @@ function createSearchCompletionList() {{...props}query={match.query}source={(query) => fetchAttributeNames(match.type, query)}- renderItem={(name) => <AttributeNameSuggestion type={match.type} name={name} />}+ renderItem={(name, query) => <AttributeNameSuggestion type={match.type} name={name} query={query} />}onPick={state.commit}/>);diff --git a/apps/client/src/widgets/sidebar/AttributeCreationEditor.tsx b/apps/client/src/widgets/sidebar/AttributeCreationEditor.tsxindex 3d6839ed2e..30c166399c 100644--- a/apps/client/src/widgets/sidebar/AttributeCreationEditor.tsx+++ b/apps/client/src/widgets/sidebar/AttributeCreationEditor.tsx@@ -59,7 +59,7 @@ export default function AttributeCreationEditor({ note, attribute, onCommit, onRconst suggestNames = useCallback((query: string) => fetchAttributeNames(kind, query), [ kind ]);const renderNameSuggestion = useCallback(- (suggestion: string) => <AttributeNameSuggestion type={kind} name={suggestion} />, [ kind ]);+ (suggestion: string, query: string) => <AttributeNameSuggestion type={kind} name={suggestion} query={query} />, [ kind ]);// What the name as it stands would be typed as, so a name with a definition behind it gets its// field the moment the name settles — type `due`, and the value side becomes its date picker.diff --git a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsxindex 17c341fe83..d3316b874e 100644--- a/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx+++ b/apps/client/src/widgets/type_widgets/relation_map/RelationNamePopover.tsx@@ -37,7 +37,7 @@ export default function RelationNamePopover({ connection, defaultValue, onAnswerconst suggestRelationNames = useCallback((query: string) => fetchAttributeNames("relation", query), []);const renderRelationSuggestion = useCallback(- (suggestion: string) => <AttributeNameSuggestion type="relation" name={suggestion} />, []);+ (suggestion: string, query: string) => <AttributeNameSuggestion type="relation" name={suggestion} query={query} />, []);const cancel = useCallback(() => onAnswer(null), [ onAnswer ]);// `FormAutocomplete` stops the propagation of an Escape that closes its list, so only andiff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsxindex a2829564de..3ee7228bc9 100644--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx@@ -44,7 +44,7 @@ export function createNoteMentionList({ allowCreatingNotes, preselect, getParent*/export function createAutocompleteMentionList({ source, renderItem, toMention }: {source(query: string): Promise<string[]>;- renderItem?(item: string): ComponentChildren;+ renderItem?(item: string, query: string): ComponentChildren;toMention(item: string): MentionFeedObjectItem;}): MentionHostedList {return createHostedList<MentionHostedListState>((state, list) => (