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(search): offer the # and ~ markers, and reopen the popup on what follows
Elian Doran2c1e350c6075
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a884af7783..f2eb1da277 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4348,6 +4348,8 @@"date_now_offset": "Any number of seconds before now","date_today_offset": "Any number of days before today","date_month_offset": "Any number of months before this one",- "date_year_offset": "Any number of years before this one"+ "date_year_offset": "Any number of years before this one",+ "label_marker": "Refers to a label. Press Enter to see the list of labels",+ "relation_marker": "Refers to a relation. Press Enter to see the list of relations"}}diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsxindex aa8646c838..bfe8d26bc1 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx@@ -8,7 +8,8 @@ import SearchStringEditor from "./SearchStringEditor";// The completions fetch attribute names and values through the server; nothing here opens the popup.vi.mock("./search_completions", () => ({searchCompletionSource: () => null,- searchCompletionIcon: () => undefined+ searchCompletionIcon: () => undefined,+ searchCompletionReactivates: () => false}));describe("SearchStringEditor", () => {diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsxindex 0c043223ff..7813c67e3e 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx@@ -6,7 +6,7 @@ import clsx from "clsx";import { useEffect, useRef } from "preact/hooks";import { t } from "../../services/i18n";-import { searchCompletionIcon, searchCompletionSource } from "./search_completions";+import { searchCompletionIcon, searchCompletionReactivates, searchCompletionSource } from "./search_completions";interface SearchStringEditorProps {currentValue: string;@@ -57,6 +57,7 @@ export default function SearchStringEditor({ currentValue, noteId, placeholder,extensions: [ triliumSearchHighlighter, triliumSearchLinter(searchLintMessages()) ],completionSource: searchCompletionSource,completionIcon: searchCompletionIcon,+ activateOnCompletion: searchCompletionReactivates,onChange: (value) => {if (!isAdopting.current) {propsRef.current.onChange(value);diff --git a/apps/client/src/widgets/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.tsindex 75f094f431..48a3b9310d 100644--- a/apps/client/src/widgets/ribbon/search_completions.spec.ts+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import server from "../../services/server";import { fetchAttributeNames } from "../attribute_widgets/attribute_detail";-import { searchCompletionIcon, searchCompletionSource } from "./search_completions";+import { searchCompletionIcon, searchCompletionReactivates, searchCompletionSource } from "./search_completions";// The descriptions are catalogue lookups, which specs don't initialize; the keys identify them.vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));@@ -25,7 +25,7 @@ describe("searchCompletionSource", () => {const result = await complete("#book AND no");expect(result?.from).toBe(10);- expect(labelsOf(result)).toEqual([ "note", "and", "or", "not", "orderBy", "limit" ]);+ expect(labelsOf(result)).toEqual([ "#", "~", "note", "and", "or", "not", "orderBy", "limit" ]);// Both complete with what has to follow them.expect(optionFor(result, "note")?.apply).toBe("note.");expect(optionFor(result, "not")?.apply).toBe("not(");@@ -43,8 +43,8 @@ describe("searchCompletionSource", () => {it("narrows an orderBy to what can follow the key being written", async () => {// A key is a property path or an attribute name, which the branches above answer for.- expect(labelsOf(await complete("#book orderBy n"))).toEqual([ "note" ]);- expect(labelsOf(await complete("#book orderBy ", { explicit: true }))).toEqual([ "note" ]);+ expect(labelsOf(await complete("#book orderBy n"))).toEqual([ "#", "~", "note" ]);+ expect(labelsOf(await complete("#book orderBy ", { explicit: true }))).toEqual([ "#", "~", "note" ]);// Once a key stands there it can be sorted, followed by another, or cut short.expect(labelsOf(await complete("#book orderBy note.title d")))@@ -53,14 +53,14 @@ describe("searchCompletionSource", () => {.toEqual([ "asc", "desc", "limit" ]);// A comma opens the next key, which has no direction of its own yet.- expect(labelsOf(await complete("#book orderBy note.title, n"))).toEqual([ "note" ]);+ expect(labelsOf(await complete("#book orderBy note.title, n"))).toEqual([ "#", "~", "note" ]);// An ordering names a key and sorts on it; nothing in it is compared.expect(await complete("#book orderBy note.title =")).toBeNull();// Outside an ordering the keywords are untouched.expect(labelsOf(await complete("#book n")))- .toEqual([ "note", "and", "or", "not", "orderBy", "limit" ]);+ .toEqual([ "#", "~", "note", "and", "or", "not", "orderBy", "limit" ]);});it("offers every operator once one of their characters is typed", async () => {@@ -89,7 +89,7 @@ describe("searchCompletionSource", () => {expect(await complete("note.relations.author >")).toBeNull();// An explicit request past one is left with the keywords alone.expect(labelsOf(await complete("~author ", { explicit: true })))- .toEqual([ "note", "and", "or", "not", "orderBy", "limit" ]);+ .toEqual([ "#", "~", "note", "and", "or", "not", "orderBy", "limit" ]);// The last segment decides, and a name the user chose after `labels.` restricts nothing.expect(labelsOf(await complete("note.parents.title >"))).toContain(">");@@ -127,8 +127,16 @@ describe("searchCompletionSource", () => {const explicit = await complete("#book ", { explicit: true });expect(explicit?.from).toBe(6);- // The six words, then every operator.- expect(explicit?.options).toHaveLength(18);+ // The words and the two attribute markers, then every operator.+ expect(explicit?.options).toHaveLength(20);+ // CodeMirror sorts by score and ignores the order offered, so the markers are boosted+ // to the top rather than merely listed first.+ expect(optionFor(explicit, "#")?.boost).toBe(99);+ expect(optionFor(explicit, "~")?.boost).toBe(98);++ // Everything that leaves a clause unfinished reopens the popup on what follows it.+ const reopening = explicit?.options.filter(searchCompletionReactivates).map((o) => o.label);+ expect(reopening).toEqual([ "#", "~", "note", "not" ]);});describe("attribute names", () => {@@ -270,7 +278,7 @@ describe("searchCompletionSource", () => {// A property whose values nothing can enumerate falls through to the keywords, and a// label that happens to share a property's name is still a label.expect(labelsOf(await complete("note.title = so")))- .toEqual([ "note", "and", "or", "not", "orderBy", "limit" ]);+ .toEqual([ "#", "~", "note", "and", "or", "not", "orderBy", "limit" ]);expect(labelsOf(await complete("note.labels.type = fic"))).toEqual([ "fiction", "science fiction" ]);});@@ -315,6 +323,9 @@ describe("searchCompletionIcon", () => {expect(iconFor(await complete("no"), "note")).toBeUndefined();expect(iconFor(await complete("or"), "orderBy")).toBeUndefined();expect(iconFor(await complete("note."), "title")).toBeUndefined();+ // The marker is the icon; drawing one beside it reads as noise.+ expect(iconFor(await complete("no"), "#")).toBeUndefined();+ expect(iconFor(await complete("no"), "~")).toBeUndefined();expect(iconFor(await complete("#year >"), ">=")).toBeUndefined();});});diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.tsindex b073125a90..1e01315826 100644--- a/apps/client/src/widgets/ribbon/search_completions.ts+++ b/apps/client/src/widgets/ribbon/search_completions.ts@@ -153,6 +153,14 @@ const SYSTEM_ATTRIBUTE = "system-attribute";*/const BUILTIN_BOOST = -99;+/**+ * The furthest an option can be moved up, the other end of {@link BUILTIN_BOOST}. CodeMirror never+ * reads the order options are offered in — it sorts by match score, and a pattern of a character or+ * two scores everything alike, leaving the tie to be broken by label. That puts `~` last of all, so+ * the markers carry the boost instead.+ */+const MARKER_BOOST = 99;+const COMPLETION_ICONS: Record<string, string> = {[SYSTEM_ATTRIBUTE]: "bx bx-cog",label: "bx bx-hash",@@ -363,9 +371,16 @@ function wordOptions(ordering: OrderingPosition): Completion[] {// parenthesised sub-expression, is never a clause on its own.const noteObject: Completion = { label: "note", apply: "note.", type: "namespace", detail: t("search_completion.note") };const limit: Completion = { label: "limit", type: "keyword", detail: t("search_completion.keyword_limit") };+ // The characters the whole syntax turns on, and the only part of it a reader cannot arrive at+ // by typing a word, so they lead. `ValueExtractor` rewrites either into a path, so a sort key+ // takes them too. Drawn as keywords: the marker is already the icon.+ const attributeMarkers: Completion[] = [+ { label: "#", apply: "#", type: "keyword", boost: MARKER_BOOST, detail: t("search_completion.label_marker") },+ { label: "~", apply: "~", type: "keyword", boost: MARKER_BOOST - 1, detail: t("search_completion.relation_marker") }+ ];if (ordering === "key") {- return [ noteObject ];+ return [ ...attributeMarkers, noteObject ];}if (ordering === "sorted") {@@ -377,6 +392,7 @@ function wordOptions(ordering: OrderingPosition): Completion[] {}return [+ ...attributeMarkers,noteObject,{ label: "and", type: "keyword", detail: t("search_completion.keyword_and") },{ label: "or", type: "keyword", detail: t("search_completion.keyword_or") },@@ -386,6 +402,18 @@ function wordOptions(ordering: OrderingPosition): Completion[] {];}+/**+ * Whether picking `completion` reopens the popup. Every option that inserts one of these leaves a+ * clause unfinished: `note.` and `#` are waiting for a name, `not(` for a sub-expression.+ */+export function searchCompletionReactivates(completion: Completion): boolean {+ const applied = completion.apply;++ return typeof applied === "string" && OPENERS.includes(applied.slice(-1));+}++const OPENERS = [ ".", "(", "#", "~" ];+/*** Where the cursor stands in an `orderBy`, which decides what can follow it.* `parseOrderByAndLimit()` reads a property path, then an optional `asc` or `desc`, then either adiff --git a/packages/codemirror/src/single_line.ts b/packages/codemirror/src/single_line.tsindex 3cf1438bb7..7277f3ad5b 100644--- a/packages/codemirror/src/single_line.ts+++ b/packages/codemirror/src/single_line.ts@@ -23,6 +23,11 @@ export interface SingleLineEditorConfig {* nothing for are drawn without one; supplying it at all replaces CodeMirror's own icons.*/completionIcon?(completion: Completion): string | undefined;+ /**+ * Whether picking a completion reopens the popup on what follows it, for one that inserts an+ * opening rather than a finished value.+ */+ activateOnCompletion?(completion: Completion): boolean;/** Runs after every document change, with the whole text. */onChange?(value: string): void;/** Runs when Enter is pressed; the key never inserts a line break. */@@ -77,6 +82,7 @@ export function createSingleLineEditor(config: SingleLineEditorConfig): SingleLiextensions.push(autocompletion({override: [ config.completionSource ],activateOnTyping: true,+ activateOnCompletion: config.activateOnCompletion,icons: !icon,addToOptions: icon ? [ { position: ICON_POSITION, render: (completion) => renderIcon(icon(completion)) } ] : []}));