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): complete operators and the note object in the search string
Elian Doran1a8eb38d4e3d
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 2bb525dd1d..a18681f7f3 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4300,5 +4300,20 @@"pan_right": "Right","pan_fast": "Faster panning"}+ },+ "search_completion": {+ "note": "Note title, properties and related notes",+ "operator_equal": "Equals the whole value",+ "operator_not_equal": "Does not equal the whole value",+ "operator_contains": "Contains",+ "operator_starts_with": "Starts with",+ "operator_ends_with": "Ends with",+ "operator_greater_than": "Greater than",+ "operator_greater_or_equal": "Greater than or equal to",+ "operator_less_than": "Less than",+ "operator_less_or_equal": "Less than or equal to",+ "operator_regex": "Matches a regular expression",+ "operator_fuzzy_equal": "Equals, tolerating typos",+ "operator_fuzzy_contains": "Contains, tolerating typos"}}diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsxindex 03ce7971e9..06ce06fb0e 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx@@ -4,6 +4,8 @@ import type { SingleLineEditor } from "@triliumnext/codemirror/src/single_line";import clsx from "clsx";import { useEffect, useRef } from "preact/hooks";+import { searchCompletionSource } from "./search_completions";+interface SearchStringEditorProps {currentValue: string;placeholder?: string;@@ -45,6 +47,7 @@ export default function SearchStringEditor({ currentValue, placeholder, classNamdoc: propsRef.current.currentValue,placeholder,extensions: [ triliumSearchHighlighter ],+ completionSource: searchCompletionSource,onChange: (value) => propsRef.current.onChange(value),onEnter: () => propsRef.current.onEnter()});diff --git a/apps/client/src/widgets/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.tsnew file mode 100644index 0000000000..b0a21b8050--- /dev/null+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts@@ -0,0 +1,52 @@+import type { CompletionContext } from "@triliumnext/codemirror/src/single_line";+import { describe, expect, it, vi } from "vitest";++import { 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 }));++describe("searchCompletionSource", () => {+ it("offers the note object while a word is being typed, anchored at its start", () => {+ const result = searchCompletionSource(contextAt("#book AND no"));++ expect(result?.from).toBe(10);+ expect(result?.options.map((option) => option.label)).toEqual([ "note" ]);+ // A bare `note` is never a complete clause, so the dot comes with it.+ expect(result?.options[0].apply).toBe("note.");+ expect(result?.options[0].detail).toBe("search_completion.note");+ });++ it("offers every operator once one of their characters is typed", () => {+ const result = searchCompletionSource(contextAt("#year >"));++ expect(result?.from).toBe(6);+ expect(result?.options.map((option) => option.label)).toEqual([+ "=", "!=", "*=*", "=*", "*=", ">", ">=", "<", "<=", "%=", "~=", "~*"+ ]);+ expect(result?.options.every((option) => option.detail)).toBe(true);+ });++ it("stays quiet on empty space, and offers everything when asked explicitly", () => {+ expect(searchCompletionSource(contextAt("#book "))).toBeNull();++ const explicit = searchCompletionSource(contextAt("#book ", { explicit: true }));++ expect(explicit?.from).toBe(6);+ expect(explicit?.options).toHaveLength(13);+ });+});++/** Stands in for the editor's context, whose `matchBefore` anchors the pattern at the cursor. */+function contextAt(text: string, { explicit = false } = {}): CompletionContext {+ const pos = text.length;++ return {+ pos,+ explicit,+ matchBefore(expr: RegExp) {+ const match = new RegExp(`(?:${expr.source})$`).exec(text);+ return match ? { from: pos - match[0].length, to: pos, text: match[0] } : null;+ }+ } as unknown as CompletionContext;+}diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.tsnew file mode 100644index 0000000000..a8cc042681--- /dev/null+++ b/apps/client/src/widgets/ribbon/search_completions.ts@@ -0,0 +1,60 @@+import type { Completion, CompletionContext, CompletionResult } from "@triliumnext/codemirror/src/single_line";++import { t } from "../../services/i18n";++/**+ * Offers the top level of Trilium's search syntax: the `note` object a property path hangs off,+ * and the comparison operators, whose spellings (`*=*`, `=*`, `~=`) are the part of the syntax+ * hardest to recall.+ *+ * Attribute names, property names and values are not offered yet — reading those needs the note+ * being searched, which a source built from static text cannot see.+ */+export function searchCompletionSource(context: CompletionContext): CompletionResult | null {+ const operator = context.matchBefore(OPERATOR_PREFIX);+ if (operator) {+ return { from: operator.from, options: operatorOptions(), validFor: OPERATOR_PREFIX };+ }++ const word = context.matchBefore(WORD_PREFIX);+ if (word) {+ return { from: word.from, options: objectOptions(), validFor: WORD_PREFIX };+ }++ // Ctrl-Space on empty space asks for everything on offer.+ if (context.explicit) {+ return { from: context.pos, options: [ ...objectOptions(), ...operatorOptions() ] };+ }++ return null;+}++/** The characters an operator is spelled with, so typing any of them starts offering them. */+const OPERATOR_PREFIX = /[=!*<>%~]+/;+const WORD_PREFIX = /[a-zA-Z]+/;++/**+ * The options are built per request rather than once, so they read the catalogue after i18n has+ * loaded and follow a language switched while the app is running.+ */+function objectOptions(): Completion[] {+ // `note.` completes with the dot, since a bare `note` is never a complete clause.+ return [ { label: "note", apply: "note.", type: "namespace", detail: t("search_completion.note") } ];+}++function operatorOptions(): Completion[] {+ return [+ { label: "=", detail: t("search_completion.operator_equal") },+ { label: "!=", detail: t("search_completion.operator_not_equal") },+ { label: "*=*", detail: t("search_completion.operator_contains") },+ { label: "=*", detail: t("search_completion.operator_starts_with") },+ { label: "*=", detail: t("search_completion.operator_ends_with") },+ { label: ">", detail: t("search_completion.operator_greater_than") },+ { label: ">=", detail: t("search_completion.operator_greater_or_equal") },+ { label: "<", detail: t("search_completion.operator_less_than") },+ { label: "<=", detail: t("search_completion.operator_less_or_equal") },+ { label: "%=", detail: t("search_completion.operator_regex") },+ { label: "~=", detail: t("search_completion.operator_fuzzy_equal") },+ { label: "~*", detail: t("search_completion.operator_fuzzy_contains") }+ ].map((option) => ({ ...option, type: "keyword" }));+}diff --git a/packages/codemirror/src/single_line.ts b/packages/codemirror/src/single_line.tsindex a2a5e6fc36..b16286dc01 100644--- a/packages/codemirror/src/single_line.ts+++ b/packages/codemirror/src/single_line.ts@@ -1,7 +1,14 @@+import { autocompletion, type CompletionSource } from "@codemirror/autocomplete";import { history, historyKeymap, standardKeymap } from "@codemirror/commands";import { EditorState, type Extension } from "@codemirror/state";import { EditorView, keymap, placeholder } from "@codemirror/view";+/**+ * The types a consumer needs to write a {@link SingleLineEditorConfig.completionSource}, re-exported+ * so it does not have to depend on `@codemirror/autocomplete` itself.+ */+export type { Completion, CompletionContext, CompletionResult, CompletionSource } from "@codemirror/autocomplete";+export interface SingleLineEditorConfig {parent: HTMLElement;/** Text the editor starts with. */@@ -9,6 +16,8 @@ export interface SingleLineEditorConfig {placeholder?: string;/** Extra extensions, such as a highlighter for whatever syntax the value holds. */extensions?: Extension[];+ /** Completions to offer as the value is typed. Without one, the editor has no autocompletion. */+ completionSource?: CompletionSource;/** 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. */@@ -20,7 +29,8 @@ export type SingleLineEditor = EditorView;/*** Builds a CodeMirror editor for a one-line value: text editing, undo history and wrapped- * display, and nothing else — no gutter, no language, no autocompletion.+ * display, and nothing else — no gutter and no language. Highlighting and completion are the+ * consumer's to supply, through `extensions` and `completionSource`.** It sits apart from the editor in `index.ts` so a consumer that wants a plain input does not* load the language, theme and completion machinery a code note needs.@@ -54,6 +64,12 @@ export function createSingleLineEditor(config: SingleLineEditorConfig): SingleLiextensions.push(placeholder(config.placeholder));}+ if (config.completionSource) {+ // The completion keymap is registered at the highest precedence, so Enter picks the+ // selected option while the popup is open and reaches `onEnter` the rest of the time.+ extensions.push(autocompletion({ override: [ config.completionSource ], activateOnTyping: true }));+ }+return new EditorView({parent: config.parent,doc: config.doc ?? "",