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): highlight the search syntax in the search string
Elian Doranef0e95b0ca84
diff --git a/apps/client/src/stylesheets/theme-next-dark.css b/apps/client/src/stylesheets/theme-next-dark.cssindex fb2f0c504f..659d5719a4 100644--- a/apps/client/src/stylesheets/theme-next-dark.css+++ b/apps/client/src/stylesheets/theme-next-dark.css@@ -290,6 +290,16 @@--log-error-line-background-color: #d44b4b1f;--log-info-color: inherit; /* Placeholder: give it a colour to make info lines stand out. */+ /* Search query syntax (the search string of a saved search) */+ --search-label-color: #79b8ff;+ --search-relation-color: #c2a8ff;+ --search-property-color: #5bc4b1;+ --search-keyword-color: #ff7eb6;+ --search-operator-color: #9aa4b0;+ --search-string-color: #8fd48f;+ --search-literal-color: #e0a85c;+ --search-bracket-color: #8a94a0;+--card-background-color: #ffffff12;--card-background-hover-color: #ffffff20;--card-border-color: transparent;diff --git a/apps/client/src/stylesheets/theme-next-light.css b/apps/client/src/stylesheets/theme-next-light.cssindex 0b5db7ad9e..3dea58dd7b 100644--- a/apps/client/src/stylesheets/theme-next-light.css+++ b/apps/client/src/stylesheets/theme-next-light.css@@ -288,6 +288,16 @@--log-error-line-background-color: #ff000017;--log-info-color: inherit; /* Placeholder: give it a colour to make info lines stand out. */+ /* Search query syntax (the search string of a saved search) */+ --search-label-color: #1a6fc4;+ --search-relation-color: #7d4bbd;+ --search-property-color: #0f7b6c;+ --search-keyword-color: #b02a5b;+ --search-operator-color: #596573;+ --search-string-color: #2e7d32;+ --search-literal-color: #a35c00;+ --search-bracket-color: #7b8794;+--card-background-color: #0000000d;--card-background-hover-color: #0000001c;--card-border-color: transparent;diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsxindex 2c8934dfc9..03ce7971e9 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx@@ -32,7 +32,10 @@ export default function SearchStringEditor({ currentValue, placeholder, classNamlet editor: SingleLineEditor | undefined;let cancelled = false;- void import("@triliumnext/codemirror/src/single_line").then(({ createSingleLineEditor }) => {+ void Promise.all([+ import("@triliumnext/codemirror/src/single_line"),+ import("@triliumnext/codemirror/src/extensions/trilium_search_highlighter")+ ]).then(([ { createSingleLineEditor }, { triliumSearchHighlighter } ]) => {if (cancelled || !parentRef.current) {return;}@@ -41,6 +44,7 @@ export default function SearchStringEditor({ currentValue, placeholder, classNamparent: parentRef.current,doc: propsRef.current.currentValue,placeholder,+ extensions: [ triliumSearchHighlighter ],onChange: (value) => propsRef.current.onChange(value),onEnter: () => propsRef.current.onEnter()});diff --git a/packages/codemirror/src/extensions/trilium_search_highlighter.spec.ts b/packages/codemirror/src/extensions/trilium_search_highlighter.spec.tsnew file mode 100644index 0000000000..bfbe074428--- /dev/null+++ b/packages/codemirror/src/extensions/trilium_search_highlighter.spec.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from "vitest";++import { createSingleLineEditor } from "../single_line.js";+import { tokenizeSearchQuery, triliumSearchHighlighter } from "./trilium_search_highlighter.js";++describe("tokenizeSearchQuery", () => {+ it("colours labels, keywords and a property path in an orderBy query", () => {+ expect(tokenize("#author=Tolkien orderBy #publicationDate desc, note.title limit 10")).toEqual([+ "label:#author",+ "operator:=",+ "keyword:orderBy",+ "label:#publicationDate",+ "keyword:desc",+ "property:note",+ "property:.title",+ "keyword:limit",+ "literal:10"+ ]);+ });++ it("follows a property path through a relation", () => {+ expect(tokenize("~author.relations.son.title = 'Christopher Tolkien'")).toEqual([+ "relation:~author",+ "property:.relations",+ "property:.son",+ "property:.title",+ "operator:=",+ "string:'Christopher Tolkien'"+ ]);+ });++ it("handles grouping, negation and the logical keywords", () => {+ expect(tokenize("#book AND not(#!fiction or ~author.title *=* tolkien)")).toEqual([+ "label:#book",+ "keyword:AND",+ "keyword:not",+ "bracket:(",+ "label:#!fiction",+ "keyword:or",+ "relation:~author",+ "property:.title",+ "operator:*=*",+ "bracket:)"+ ]);+ });++ it("reads ~= and ~* as fuzzy operators rather than a relation", () => {+ expect(tokenize("note.title ~= boks")).toEqual([+ "property:note",+ "property:.title",+ "operator:~=",+ // `boks` is the compared value, which carries no colour of its own.+ ]);+ expect(tokenize("note.content ~* progr")).toEqual([+ "property:note",+ "property:.content",+ "operator:~*"+ ]);+ });++ it("splits a smart date value from its offset", () => {+ expect(tokenize("note.dateCreated >= today-30")).toEqual([+ "property:note",+ "property:.dateCreated",+ "operator:>=",+ "literal:today",+ "operator:-",+ "literal:30"+ ]);+ });++ it("leaves full text alone, including an escaped # and a half-typed path", () => {+ expect(tokenize("towers rings")).toEqual([]);+ // The backslash escape is how a literal "#" is searched for as text.+ expect(tokenize("\\#tolkien")).toEqual([]);+ expect(tokenize("note.")).toEqual([ "property:note", "property:." ]);+ });++ it("runs an unclosed quote to the end of the query", () => {+ expect(tokenize("#title = \"unfinished")).toEqual([+ "label:#title",+ "operator:=",+ "string:\"unfinished"+ ]);+ });+});++describe("triliumSearchHighlighter", () => {+ it("marks the tokens in the rendered editor", () => {+ const parent = document.createElement("div");+ document.body.appendChild(parent);+ const editor = createSingleLineEditor({+ parent,+ doc: "#book or ~author.title = 'Tolkien'",+ extensions: [ triliumSearchHighlighter ]+ });++ try {+ expect(textOf(parent, ".cm-search-label")).toEqual([ "#book" ]);+ expect(textOf(parent, ".cm-search-keyword")).toEqual([ "or" ]);+ expect(textOf(parent, ".cm-search-relation")).toEqual([ "~author" ]);+ expect(textOf(parent, ".cm-search-property")).toEqual([ ".title" ]);+ expect(textOf(parent, ".cm-search-string")).toEqual([ "'Tolkien'" ]);+ } finally {+ editor.destroy();+ }+ });+});++/** Renders the tokens as `kind:text` pairs, which reads far better in an expectation than offsets. */+function tokenize(query: string): string[] {+ return tokenizeSearchQuery(query).map(({ kind, from, to }) => `${kind}:${query.slice(from, to)}`);+}++function textOf(parent: HTMLElement, selector: string): string[] {+ return Array.from(parent.querySelectorAll(selector)).map((element) => element.textContent ?? "");+}diff --git a/packages/codemirror/src/extensions/trilium_search_highlighter.ts b/packages/codemirror/src/extensions/trilium_search_highlighter.tsnew file mode 100644index 0000000000..87393ef38d--- /dev/null+++ b/packages/codemirror/src/extensions/trilium_search_highlighter.ts@@ -0,0 +1,201 @@+import { type EditorState, type Extension, RangeSetBuilder, StateField } from "@codemirror/state";+import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";++/**+ * Highlighter for Trilium's search syntax, as entered in the `#searchString` of a saved search.+ *+ * It scans the query the way `lex()` does — left to right, one token at a time — but classifies+ * rather than parses: nothing here decides whether a query is valid, so a half-typed clause still+ * colours the part that is already there. Operators, quoting and the rule that `+`/`-` bind only+ * to digits follow the lexer, which is what keeps `today-30` three tokens rather than one word.+ *+ * Recognised tokens:+ * - `#label` and `~relation`, either optionally negated with `!`+ * - `note` and the dotted path after it or after a relation (`~author.relations.son.title`)+ * - the comparison operators, including the fuzzy `~=` and `~*` that look like a relation prefix+ * - `and`, `or`, `not`, `orderBy`, `limit`, `asc`, `desc`+ * - quoted operands, numbers, and the smart date values `now`, `today`, `month` and `year`+ *+ * Words outside all of that are the full-text part of the query and stay unstyled.+ */++export type SearchTokenKind =+ | "label"+ | "relation"+ | "property"+ | "keyword"+ | "operator"+ | "string"+ | "literal"+ | "bracket";++export interface SearchToken {+ from: number;+ to: number;+ kind: SearchTokenKind;+}++const KEYWORDS = new Set([ "and", "or", "not", "orderby", "limit", "asc", "desc" ]);+/** Values `resolveConstantOperand()` turns into a date, optionally followed by `+`/`-` and a count. */+const DATE_VALUES = new Set([ "now", "today", "month", "year" ]);++/**+ * Characters that end an attribute name or a property-path segment. They are the structural ones+ * plus `+`/`-`, which `isSymbolAnOperator()` counts as operators and so splits a word on.+ */+const NAME = "[^\\s#~().,=<>*!%+\\-'\"`]";++const SPACE = /\s+/y;+// Runs to the matching quote, or to the end of the query while the closing quote is still missing.+const STRING = /(['"`])(?:\\[^]|(?!\1)[^])*(?:\1|$)/y;+const ESCAPE = /\\[^]/y;+const ATTRIBUTE = new RegExp(`([#~])!?${NAME}+`, "y");+// The segment is allowed to be empty so a trailing `note.` colours while it is being typed.+const PATH_SEGMENT = new RegExp(`\\.${NAME}*`, "y");+const NOTE_PREFIX = /note(?=\.)/iy;+const OPERATOR = /\*=\*|~=|~\*|!=|>=|<=|%=|\*=|=\*|[=><]|[+\-](?=\d)/y;+const BRACKET = /[()]/y;+const NUMBER = /\d+(?:\.\d+)?/y;+const WORD = /[^\s#~().,=<>*!%+\-'"`]+/y;++/** Splits a search query into the tokens worth colouring, skipping over everything else. */+export function tokenizeSearchQuery(text: string): SearchToken[] {+ const tokens: SearchToken[] = [];+ let pos = 0;+ // Set by `note` and by a relation, both of which a dotted property path can follow.+ let inPath = false;++ const match = (pattern: RegExp) => {+ pattern.lastIndex = pos;+ return pattern.exec(text);+ };+ const take = (kind: SearchTokenKind, pattern: RegExp) => {+ tokens.push({ from: pos, to: pattern.lastIndex, kind });+ pos = pattern.lastIndex;+ };++ while (pos < text.length) {+ if (match(SPACE)) {+ pos = SPACE.lastIndex;+ continue;+ }++ if (inPath) {+ if (match(PATH_SEGMENT)) {+ take("property", PATH_SEGMENT);+ continue;+ }+ inPath = false;+ }++ if (match(STRING)) {+ take("string", STRING);+ continue;+ }++ if (match(ESCAPE)) {+ // An escaped `#`, `~` or `note.` is full text, so it carries no colour of its own.+ pos = ESCAPE.lastIndex;+ continue;+ }++ const attribute = match(ATTRIBUTE);+ if (attribute) {+ const isLabel = attribute[1] === "#";+ take(isLabel ? "label" : "relation", ATTRIBUTE);+ inPath = !isLabel;+ continue;+ }++ if (match(NOTE_PREFIX)) {+ take("property", NOTE_PREFIX);+ inPath = true;+ continue;+ }++ if (match(OPERATOR)) {+ take("operator", OPERATOR);+ continue;+ }++ if (match(BRACKET)) {+ take("bracket", BRACKET);+ continue;+ }++ if (match(NUMBER)) {+ take("literal", NUMBER);+ continue;+ }++ const word = match(WORD);+ if (word) {+ const lowerCased = word[0].toLowerCase();+ if (KEYWORDS.has(lowerCased)) {+ take("keyword", WORD);+ } else if (DATE_VALUES.has(lowerCased)) {+ take("literal", WORD);+ } else {+ pos = WORD.lastIndex;+ }+ continue;+ }++ // A structural character carrying no meaning where it stands, such as a stray `.` or `,`.+ pos++;+ }++ return tokens;+}++const MARKS: Record<SearchTokenKind, Decoration> = {+ label: Decoration.mark({ class: "cm-search-label" }),+ relation: Decoration.mark({ class: "cm-search-relation" }),+ property: Decoration.mark({ class: "cm-search-property" }),+ keyword: Decoration.mark({ class: "cm-search-keyword" }),+ operator: Decoration.mark({ class: "cm-search-operator" }),+ string: Decoration.mark({ class: "cm-search-string" }),+ literal: Decoration.mark({ class: "cm-search-literal" }),+ bracket: Decoration.mark({ class: "cm-search-bracket" })+};++/**+ * The Next themes own the palette (`--search-*` in theme-next-light.css / theme-next-dark.css).+ * The fallbacks below are what the legacy themes — which don't define those variables — render+ * with, so they are mid-tones that hold up on a light and a dark background alike.+ */+const searchHighlightTheme = EditorView.baseTheme({+ ".cm-search-label": { color: "var(--search-label-color, #539bf5)" },+ ".cm-search-relation": { color: "var(--search-relation-color, #8957e5)" },+ ".cm-search-property": { color: "var(--search-property-color, #268a8a)" },+ ".cm-search-keyword": { color: "var(--search-keyword-color, #bf3989)", fontWeight: "bold" },+ ".cm-search-operator": { color: "var(--search-operator-color, var(--muted-text-color))" },+ ".cm-search-string": { color: "var(--search-string-color, #2ea043)" },+ ".cm-search-literal": { color: "var(--search-literal-color, #d29922)" },+ ".cm-search-bracket": { color: "var(--search-bracket-color, var(--muted-text-color))" }+});++const searchHighlightField = StateField.define<DecorationSet>({+ create: (state) => buildSearchDecorations(state),+ update: (decorations, tr) => (tr.docChanged ? buildSearchDecorations(tr.state) : decorations),+ provide: (field) => EditorView.decorations.from(field)+});++/**+ * The extension to register on an editor holding a search query.+ *+ * The decorations live in a {@link StateField} rather than a view plugin so they paint the moment+ * the extension enters the configuration instead of only after the next edit — the same reason+ * `triliumLogHighlighter` uses one. A query is one short line, so every change rescans all of it.+ */+export const triliumSearchHighlighter: Extension = [ searchHighlightField, searchHighlightTheme ];++function buildSearchDecorations(state: EditorState): DecorationSet {+ const builder = new RangeSetBuilder<Decoration>();++ for (const token of tokenizeSearchQuery(state.doc.toString())) {+ builder.add(token.from, token.to, MARKS[token.kind]);+ }++ return builder.finish();+}diff --git a/packages/codemirror/src/single_line.ts b/packages/codemirror/src/single_line.tsindex f674644b84..a2a5e6fc36 100644--- a/packages/codemirror/src/single_line.ts+++ b/packages/codemirror/src/single_line.ts@@ -7,6 +7,8 @@ export interface SingleLineEditorConfig {/** Text the editor starts with. */doc?: string;placeholder?: string;+ /** Extra extensions, such as a highlighter for whatever syntax the value holds. */+ extensions?: Extension[];/** 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. */@@ -44,7 +46,8 @@ export function createSingleLineEditor(config: SingleLineEditorConfig): SingleLiif (update.docChanged) {config.onChange?.(update.state.doc.toString());}- })+ }),+ ...(config.extensions ?? [])];if (config.placeholder) {