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): lead a note's row with its title, the path to it after
Elian Doran3153846bbcd8
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.css b/apps/client/src/widgets/react/NoteAutocomplete.cssindex 69ad60c037..ccfb3d90c3 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.css+++ b/apps/client/src/widgets/react/NoteAutocomplete.css@@ -48,9 +48,37 @@/* Lets a badge too long for the row shrink to its width and end in an ellipsis. */.note-suggestion-text {+ flex: 1 1 auto;min-width: 0;}+ /*+ * The title, then the path to the note at the end of the line, as the search results' cards set+ * them. A path with no room beside the title moves under it rather than squeezing it.+ */+ .note-suggestion-header {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0 12px;+ }++ .search-result-title {+ flex: 0 1 auto;+ min-width: 0;+ }++ .note-suggestion-path {+ flex: 0 1 auto;+ min-width: 0;+ margin-inline-start: auto;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 0.85em;+ color: var(--muted-text-color);+ }+.note-suggestion-description {display: block;font-size: small;@@ -69,7 +97,7 @@}/* The search's matches, in the colors quick_search.css gives them, at the row's own weight. */- :is(.search-result-title, .note-suggestion-attributes) b {+ :is(.search-result-title, .note-suggestion-path, .note-suggestion-attributes) 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));diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxindex c38433078e..d71897a29f 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -220,6 +220,38 @@ describe("NoteAutocomplete's suggestion list", () => {expect(document.querySelector(".note-autocomplete-menu .dropdown-header")).toBeNull();});+ it("reports the highlighted suggestion as the keys move, and none once the list closes", async () => {+ const onHighlight = vi.fn();+ const input = await mount({ onHighlight });+ await type(input, "al");+ expect(onHighlight).toHaveBeenLastCalledWith(notes[0]);++ await press(input, "ArrowDown");+ expect(onHighlight).toHaveBeenLastCalledWith(notes[1]);++ await press(input, "Escape");+ expect(onHighlight).toHaveBeenLastCalledWith(undefined);+ });++ it("shows a note's title first and the path to it after, while other rows keep their one title", async () => {+ getNoteSuggestions.mockResolvedValue([+ { ...notes[1], highlightedNoteTitle: "<b>Be</b>ta", highlightedParentPathTitle: "X" },+ { ...notes[0], highlightedNoteTitle: "Alpha", highlightedParentPathTitle: "" },+ { action: "create-note", noteTitle: "be", highlightedNotePathTitle: "Create be" }+ ]);+ const input = await mount();+ await type(input, "be");++ const [ beta, alpha ] = rows();+ expect(beta.querySelector(".search-result-title")?.innerHTML).toBe("<b>Be</b>ta");+ expect(beta.querySelector(".note-suggestion-path")?.innerHTML).toBe("X");+ // A top-level note has no path to show.+ expect(alpha.querySelector(".note-suggestion-path")).toBeNull();+ const create = allRows().find((row) => row.querySelector(".bx-plus"));+ expect(create?.querySelector(".search-result-title")?.textContent).toBe("Create be");+ expect(create?.querySelector(".note-suggestion-path")).toBeNull();+ });+it("lists the notes as the rows of a menu, the first one highlighted", async () => {const input = await mount();await type(input, "al");diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex a55cbc1abd..bfa5633a24 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -58,6 +58,8 @@ export interface NoteAutocompleteProps {* Note does.*/searchFooter?: boolean;+ /** Called with the suggestion the list highlights, or `undefined` while it highlights none. */+ onHighlight?: (suggestion: Suggestion | undefined) => void;}/** Drives a note autocomplete from outside it, for a caller that decides when. */@@ -75,7 +77,7 @@ export interface NoteAutocompleteHandle {clear(): void;}-export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, container, containerStyle, opts, onChange, onTextChange, onKeyDown, onBlur, noteIdChanged, noteId, readOnly, tabIndex, handleRef, anchorRef, searchFooter }: NoteAutocompleteProps) {+export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, container, containerStyle, opts, onChange, onTextChange, onKeyDown, onBlur, noteIdChanged, noteId, readOnly, tabIndex, handleRef, anchorRef, searchFooter, onHighlight }: NoteAutocompleteProps) {const inputRef = useSyncedRef<HTMLInputElement>(externalInputRef);const groupRef = useRef<HTMLDivElement>(null);const [ value, setValue ] = useState("");@@ -172,6 +174,11 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,schedule});+ const highlighted = autocomplete.isShown ? autocomplete.items[autocomplete.activeIndex] : undefined;+ const onHighlightRef = useRef(onHighlight);+ onHighlightRef.current = onHighlight;+ useEffect(() => onHighlightRef.current?.(highlighted), [ highlighted ]);+/** Drops the selected note, and reports that to the host. */function clearSelection() {setNotePath("");@@ -511,12 +518,21 @@ function NoteSuggestionMenuItem({ suggestion }: { suggestion: Suggestion }) {function NoteSuggestionMenuItemContent({ suggestion }: { suggestion: Suggestion }) {const isCommand = suggestion.action === "command";const icon = isCommand ? (suggestion.icon || "bx bx-terminal") : suggestionIcon(suggestion);+ // A note leads with its own title, the path to it after, as the search results do; the rows the+ // client builds itself have only the one title.+ const title = suggestion.highlightedNoteTitle ?? suggestion.highlightedNotePathTitle ?? "";+ const parentPath = suggestion.highlightedNoteTitle !== undefined+ ? suggestion.highlightedParentPathTitle+ : undefined;return <><Icon icon={icon} /><span className="tn-menu-gap" /><div className="note-suggestion-text">- <RawHtml className="search-result-title" html={suggestion.highlightedNotePathTitle ?? ""} />+ <div className="note-suggestion-header">+ <RawHtml className="search-result-title" html={title} />+ {parentPath && <RawHtml className="note-suggestion-path" html={parentPath} />}+ </div>{isCommand? suggestion.commandDescription && (<span className="note-suggestion-description">{suggestion.commandDescription}</span>diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 7f13069882..c135dfca7f 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -382,6 +382,10 @@ export interface SearchResultDetails {noteTitle: string;notePathTitle: string;highlightedNotePathTitle?: string;+ /** The note's own title as the path shows it, highlighted. */+ highlightedNoteTitle?: string;+ /** The path to the note, without its own title, highlighted; empty for a top-level note. */+ highlightedParentPathTitle?: string;contentSnippet?: string;highlightedContentSnippet?: string;attributeSnippet?: string;@@ -395,7 +399,8 @@ export interface SearchResultDetails {* time of the visit.*/export type AutocompleteResult = Pick<SearchResultDetails, "notePath" | "noteTitle" | "notePathTitle"- | "highlightedNotePathTitle" | "attributeSnippet" | "highlightedAttributeSnippet" | "icon"> & {+ | "highlightedNotePathTitle" | "highlightedNoteTitle" | "highlightedParentPathTitle"+ | "attributeSnippet" | "highlightedAttributeSnippet" | "icon"> & {/** When the note was last visited, as `recent_notes.utcDateCreated` holds it. */utcDateVisited?: string;};diff --git a/packages/trilium-core/src/routes/api/autocomplete.spec.ts b/packages/trilium-core/src/routes/api/autocomplete.spec.tsindex 90a2b7b361..4000b9b096 100644--- a/packages/trilium-core/src/routes/api/autocomplete.spec.ts+++ b/packages/trilium-core/src/routes/api/autocomplete.spec.ts@@ -17,6 +17,8 @@ interface AutocompleteResult {highlightedNotePathTitle: string;icon: string;utcDateVisited?: string;+ highlightedNoteTitle?: string;+ highlightedParentPathTitle?: string;}describe("Autocomplete API (core)", () => {@@ -46,6 +48,31 @@ describe("Autocomplete API (core)", () => {expect(match?.icon).toBeTruthy();});+ it("splits a result's path into the note's title and the path to it, both highlighted", async () => {+ const stamp = Date.now();+ const { noteId: shelfId } = await createTextNote(api, { title: `Shelf ${stamp}` });+ const { noteId } = await createTextNote(api, { parentNoteId: shelfId, title: `Ledger <${stamp}>` });++ const found = await api.get<AutocompleteResult[]>("/api/autocomplete", {+ query: { query: `ledger ${stamp}` }+ });+ const match = found.body.find((r) => r.notePath.endsWith(noteId));+ expect(match?.highlightedNoteTitle).toBe(`<b>Ledger</b> <<b>${stamp}</b>>`);+ expect(match?.highlightedParentPathTitle).toBe(`Shelf <b>${stamp}</b>`);+ // A note at the top level has no path to it.+ const shelf = await api.get<AutocompleteResult[]>("/api/autocomplete", {+ query: { query: `shelf ${stamp}` }+ });+ expect(shelf.body.find((r) => r.notePath.endsWith(shelfId))?.highlightedParentPathTitle).toBe("");++ // The recent notes come split too, escaped as there is nothing to highlight.+ await api.post("/api/recent-notes", { body: { noteId, notePath: `root/${shelfId}/${noteId}` } });+ const recent = await api.get<AutocompleteResult[]>("/api/autocomplete", { query: { query: "" } });+ const visited = recent.body.find((r) => r.notePath.endsWith(noteId));+ expect(visited?.highlightedNoteTitle).toBe(`Ledger <${stamp}>`);+ expect(visited?.highlightedParentPathTitle).toBe(`Shelf ${stamp}`);+ });+it("returns recent notes for an empty query, with when each was visited", async () => {const { noteId } = await createTextNote(api, { title: "Recently visited" });await api.post("/api/recent-notes", { body: { noteId, notePath: `root/${noteId}` } });diff --git a/packages/trilium-core/src/routes/api/autocomplete.ts b/packages/trilium-core/src/routes/api/autocomplete.tsindex 6bf1614f99..0a65cccbfc 100644--- a/packages/trilium-core/src/routes/api/autocomplete.ts+++ b/packages/trilium-core/src/routes/api/autocomplete.ts@@ -69,13 +69,16 @@ function getRecentNotes(activeNoteId: string): AutocompleteResult[] {const notePathArray = rn.notePath.split("/");const { title, icon } = becca_service.getNoteTitleAndIcon(notePathArray[notePathArray.length - 1]);- const notePathTitle = becca_service.getNoteTitleForPath(notePathArray);+ const pathTitles = becca_service.getNoteTitleArrayForPath(notePathArray);+ const notePathTitle = pathTitles.join(" › ");return {notePath: rn.notePath,noteTitle: title,notePathTitle,highlightedNotePathTitle: escapeHtml(notePathTitle || title),+ highlightedNoteTitle: escapeHtml(pathTitles.at(-1) ?? title),+ highlightedParentPathTitle: escapeHtml(pathTitles.slice(0, -1).join(" › ")),icon: icon ?? "bx bx-note",utcDateVisited: rn.utcDateCreated};diff --git a/packages/trilium-core/src/services/search/search_result.ts b/packages/trilium-core/src/services/search/search_result.tsindex 2382d48c07..3ed5afa190 100644--- a/packages/trilium-core/src/services/search/search_result.ts+++ b/packages/trilium-core/src/services/search/search_result.ts@@ -76,6 +76,8 @@ class SearchResult {private __pathTitleSegments?: string[];private __notePathTitle?: string;highlightedNotePathTitle?: string;+ highlightedNoteTitle?: string;+ highlightedParentPathTitle?: string;contentSnippet?: string;highlightedContentSnippet?: string;attributeSnippet?: string;@@ -109,6 +111,16 @@ class SearchResult {return this.__notePathTitle;}+ /** The note's own segment of {@link notePathTitle}. */+ get noteTitleSegment(): string {+ return this.pathTitleSegments.at(-1) ?? "";+ }++ /** The segments of {@link notePathTitle} before the note's own, empty for a top-level note. */+ get parentPathTitle(): string {+ return this.pathTitleSegments.slice(0, -1).join(" › ");+ }+get notePath() {return this.notePathArray.join("/");}diff --git a/packages/trilium-core/src/services/search/services/search.spec.ts b/packages/trilium-core/src/services/search/services/search.spec.tsindex f3aa51027f..22082e4a66 100644--- a/packages/trilium-core/src/services/search/services/search.spec.ts+++ b/packages/trilium-core/src/services/search/services/search.spec.ts@@ -1100,7 +1100,10 @@ describe("Search", () => {// ...which the quick-search route (extractContentSnippet -> highlightSearchResults)// turns into <br> tags in the HTML the dropdown renders.- const result: any = { notePathTitle: "Collapsible note", contentSnippet: snippet, attributeSnippet: "" };+ const result: any = {+ notePathTitle: "Collapsible note", noteTitleSegment: "Collapsible note", parentPathTitle: "",+ contentSnippet: snippet, attributeSnippet: ""+ };searchService.highlightSearchResults([ result ], [ "body" ]);expect(result.highlightedContentSnippet).toBe("Summary Title<br><b>Body</b> text here<br>After the block");});@@ -1109,13 +1112,21 @@ describe("Search", () => {// The title is interpolated into the autocomplete dropdown as raw HTML, so a title// containing markup-like text must come back escaped. Stripping only "<" would render// "Issues caused by <div>" as "Issues caused by div>".- const result: any = { notePathTitle: "Issues caused by <div>", contentSnippet: "", attributeSnippet: "" };+ const result: any = {+ notePathTitle: "Bugs › Issues caused by <div>", noteTitleSegment: "Issues caused by <div>",+ parentPathTitle: "Bugs", contentSnippet: "", attributeSnippet: ""+ };searchService.highlightSearchResults([ result ], [ "caused" ]);- expect(result.highlightedNotePathTitle).toBe("Issues <b>caused</b> by <div>");+ expect(result.highlightedNotePathTitle).toBe("Bugs › Issues <b>caused</b> by <div>");+ expect(result.highlightedNoteTitle).toBe("Issues <b>caused</b> by <div>");+ expect(result.highlightedParentPathTitle).toBe("Bugs");// Escaping happens after highlighting, so a token that looks like part of an entity// ("lt" in "<") cannot cut the entity in half and produce "&<b>lt</b>;".- const entityResult: any = { notePathTitle: "a < b", contentSnippet: "x < y", attributeSnippet: "#lt=1 < 2" };+ const entityResult: any = {+ notePathTitle: "a < b", noteTitleSegment: "a < b", parentPathTitle: "",+ contentSnippet: "x < y", attributeSnippet: "#lt=1 < 2"+ };searchService.highlightSearchResults([ entityResult ], [ "lt" ]);expect(entityResult.highlightedNotePathTitle).toBe("a < b");expect(entityResult.highlightedContentSnippet).toBe("x < y");diff --git a/packages/trilium-core/src/services/search/services/search.ts b/packages/trilium-core/src/services/search/services/search.tsindex 64c3f4ff6b..1c77a1399b 100644--- a/packages/trilium-core/src/services/search/services/search.ts+++ b/packages/trilium-core/src/services/search/services/search.ts@@ -871,6 +871,8 @@ function buildSearchResultDetails(results: SearchResult[], searchContext: SearchnoteTitle: title,notePathTitle: result.notePathTitle,highlightedNotePathTitle: result.highlightedNotePathTitle,+ highlightedNoteTitle: result.highlightedNoteTitle,+ highlightedParentPathTitle: result.highlightedParentPathTitle,contentSnippet: result.contentSnippet,highlightedContentSnippet: result.highlightedContentSnippet,attributeSnippet: result.attributeSnippet,@@ -895,6 +897,8 @@ function highlightSearchResults(searchResults: SearchResult[], tokens: Highlight// The only characters that have to go are the { } markers themselves.for (const result of searchResults) {result.highlightedNotePathTitle = result.notePathTitle.replace(MARKER_CHARS, "");+ result.highlightedNoteTitle = result.noteTitleSegment.replace(MARKER_CHARS, "");+ result.highlightedParentPathTitle = result.parentPathTitle.replace(MARKER_CHARS, "");// Initialize highlighted content snippet, preserving newlines for later conversion to <br>if (result.contentSnippet) {@@ -910,6 +914,8 @@ function highlightSearchResults(searchResults: SearchResult[], tokens: Highlightfor (const tokenInfo of tokenInfos) {for (const result of searchResults) {result.highlightedNotePathTitle = highlightField(result.highlightedNotePathTitle, tokenInfo);+ result.highlightedNoteTitle = highlightField(result.highlightedNoteTitle, tokenInfo);+ result.highlightedParentPathTitle = highlightField(result.highlightedParentPathTitle, tokenInfo);result.highlightedContentSnippet = highlightField(result.highlightedContentSnippet, tokenInfo);result.highlightedAttributeSnippet = highlightField(result.highlightedAttributeSnippet, tokenInfo);}@@ -920,6 +926,14 @@ function highlightSearchResults(searchResults: SearchResult[], tokens: Highlightresult.highlightedNotePathTitle = renderHighlights(result.highlightedNotePathTitle);}+ if (result.highlightedNoteTitle) {+ result.highlightedNoteTitle = renderHighlights(result.highlightedNoteTitle);+ }++ if (result.highlightedParentPathTitle) {+ result.highlightedParentPathTitle = renderHighlights(result.highlightedParentPathTitle);+ }+if (result.highlightedContentSnippet) {result.highlightedContentSnippet = renderHighlights(result.highlightedContentSnippet)// Convert newlines to <br> tags for HTML display