Skip to content

Build your personal knowledge base with Trilium Notes

feat(search): edit the search string in a CodeMirror editor

Elian Dorane2fc2a6a1098
diff --git a/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsx b/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsx
index bf25947f8d..72c5f65423 100644
--- a/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsx
+++ b/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsx
@@ -1,7 +1,7 @@
import { AttributeType } from "@triliumnext/commons";
import clsx from "clsx";
import { ComponentChildren, VNode } from "preact";
-import { useEffect, useMemo, useRef } from "preact/hooks";
+import { useMemo, useRef } from "preact/hooks";
import appContext from "../../components/app_context";
import FNote from "../../entities/fnote";
@@ -11,12 +11,12 @@ import server from "../../services/server";
import { openInAppHelpFromUrl } from "../../services/utils";
import Admonition from "../react/Admonition";
import FormSelect from "../react/FormSelect";
-import FormTextArea from "../react/FormTextArea";
import FormTextBox from "../react/FormTextBox";
import HelpRemoveButtons from "../react/HelpRemoveButtons";
import { useNoteLabel, useNoteRelation, useSpacedUpdate, useTooltip } from "../react/hooks";
import Icon from "../react/Icon";
import NoteAutocomplete from "../react/NoteAutocomplete";
+import SearchStringEditor from "./SearchStringEditor";
export interface SearchOption {
attributeName: string;
@@ -144,7 +144,6 @@ function SearchOption({ note, className, title, titleIcon, children, help, attri
function SearchStringOption({ note, refreshResults, error, ...restProps }: SearchOptionProps) {
const [ searchString, setSearchString ] = useNoteLabel(note, "searchString");
- const inputRef = useRef<HTMLTextAreaElement>(null);
const currentValue = useRef(searchString ?? "");
const spacedUpdate = useSpacedUpdate(async () => {
const searchString = currentValue.current;
@@ -158,9 +157,6 @@ function SearchStringOption({ note, refreshResults, error, ...restProps }: Searc
}
}, 1000);
- // Auto-focus.
- useEffect(() => inputRef.current?.focus(), []);
-
return <>
<SearchOption
title={t("search_string.title_column")}
@@ -182,25 +178,18 @@ function SearchStringOption({ note, refreshResults, error, ...restProps }: Searc
</>}
note={note} {...restProps}
>
- <FormTextArea
- inputRef={inputRef}
+ <SearchStringEditor
className="search-string"
+ autoFocus
placeholder={t("search_string.placeholder")}
currentValue={searchString ?? ""}
onChange={text => {
currentValue.current = text;
spacedUpdate.scheduleUpdate();
}}
- onKeyDown={async (e) => {
- if (e.key === "Enter") {
- e.preventDefault();
-
- // this also in effect disallows new lines in query string.
- // on one hand, this makes sense since search string is a label
- // on the other hand, it could be nice for structuring long search string. It's probably a niche case though.
- await spacedUpdate.updateNowIfNecessary();
- refreshResults();
- }
+ onEnter={async () => {
+ await spacedUpdate.updateNowIfNecessary();
+ refreshResults();
}}
/>
</SearchOption>
diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.css b/apps/client/src/widgets/ribbon/SearchStringEditor.css
new file mode 100644
index 0000000000..0a0a17e7ef
--- /dev/null
+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.css
@@ -0,0 +1,34 @@
+/* The wrapper carries the `.form-control` chrome, so the editor inside draws none of its own. */
+.search-string-editor {
+ .cm-editor {
+ background: transparent;
+ }
+
+ .cm-editor.cm-focused {
+ outline: none;
+ }
+
+ .cm-scroller {
+ font-family: inherit;
+ font-size: inherit;
+ line-height: inherit;
+ }
+
+ .cm-content {
+ padding: 0;
+ caret-color: var(--input-text-color);
+ }
+
+ .cm-line {
+ padding: 0;
+ /* `.search-setting-table div` sets nowrap on every descendant, which would stop wrapping. */
+ white-space: pre-wrap;
+ }
+
+ .cm-placeholder {
+ /* CodeMirror draws the placeholder as an inline-block, which leaves the empty line with no
+ text-sized inline box for the caret to take its height from. */
+ display: inline;
+ color: var(--input-placeholder-color, var(--muted-text-color));
+ }
+}
diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
new file mode 100644
index 0000000000..2c8934dfc9
--- /dev/null
+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
@@ -0,0 +1,78 @@
+import "./SearchStringEditor.css";
+
+import type { SingleLineEditor } from "@triliumnext/codemirror/src/single_line";
+import clsx from "clsx";
+import { useEffect, useRef } from "preact/hooks";
+
+interface SearchStringEditorProps {
+ currentValue: string;
+ placeholder?: string;
+ className?: string;
+ autoFocus?: boolean;
+ onChange(newValue: string): void;
+ /** Runs when Enter is pressed, which the editor treats as "run this search". */
+ onEnter(): void;
+}
+
+/**
+ * Edits the `#searchString` of a saved search in a one-line CodeMirror editor.
+ *
+ * CodeMirror loads on demand: `RibbonDefinition` imports the tab holding this component
+ * statically, so a static import here would put the editor in the initial bundle.
+ */
+export default function SearchStringEditor({ currentValue, placeholder, className, autoFocus, onChange, onEnter }: SearchStringEditorProps) {
+ const parentRef = useRef<HTMLDivElement>(null);
+ const editorRef = useRef<SingleLineEditor>();
+ // The editor is built once, so it reaches the current props through a ref rather than
+ // through the closure of the render that created it.
+ const propsRef = useRef({ currentValue, onChange, onEnter });
+ propsRef.current = { currentValue, onChange, onEnter };
+
+ useEffect(() => {
+ let editor: SingleLineEditor | undefined;
+ let cancelled = false;
+
+ void import("@triliumnext/codemirror/src/single_line").then(({ createSingleLineEditor }) => {
+ if (cancelled || !parentRef.current) {
+ return;
+ }
+
+ editor = createSingleLineEditor({
+ parent: parentRef.current,
+ doc: propsRef.current.currentValue,
+ placeholder,
+ onChange: (value) => propsRef.current.onChange(value),
+ onEnter: () => propsRef.current.onEnter()
+ });
+ editorRef.current = editor;
+
+ if (autoFocus) {
+ editor.focus();
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ editor?.destroy();
+ editorRef.current = undefined;
+ };
+ // Builds the editor once; `placeholder` and `autoFocus` are read at that point.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Follows a value that changed outside the editor, such as the ribbon switching to another
+ // search note. A focused editor is left alone: the debounced save echoes the typed text back
+ // as `currentValue`, and replacing the document would drop the caret to the end.
+ useEffect(() => {
+ const editor = editorRef.current;
+ if (!editor || editor.hasFocus || editor.state.doc.toString() === currentValue) {
+ return;
+ }
+
+ editor.dispatch({
+ changes: { from: 0, to: editor.state.doc.length, insert: currentValue }
+ });
+ }, [ currentValue ]);
+
+ return <div ref={parentRef} className={clsx("search-string-editor form-control tn-input-field", className)} />;
+}
diff --git a/packages/codemirror/src/single_line.spec.ts b/packages/codemirror/src/single_line.spec.ts
new file mode 100644
index 0000000000..f3ebe14b1f
--- /dev/null
+++ b/packages/codemirror/src/single_line.spec.ts
@@ -0,0 +1,64 @@
+import { EditorSelection } from "@codemirror/state";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createSingleLineEditor, type SingleLineEditor, type SingleLineEditorConfig } from "./single_line.js";
+
+let editor: SingleLineEditor | undefined;
+
+afterEach(() => {
+ editor?.destroy();
+ editor = undefined;
+});
+
+describe("createSingleLineEditor", () => {
+ it("mounts with the given document and reports every change", () => {
+ const onChange = vi.fn();
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ editor = createSingleLineEditor({ parent, doc: "#book", onChange });
+
+ expect(parent.contains(editor.dom)).toBe(true);
+ expect(editor.state.doc.toString()).toBe("#book");
+ // The initial document is not a change.
+ expect(onChange).not.toHaveBeenCalled();
+
+ editor.dispatch({ changes: { from: 5, insert: " #year = 1954" } });
+
+ expect(onChange).toHaveBeenCalledWith("#book #year = 1954");
+ });
+
+ it("treats Enter as a command rather than a line break", () => {
+ const onEnter = vi.fn();
+ editor = build({ doc: "#book", onEnter });
+ editor.dispatch({ selection: EditorSelection.cursor(5) });
+
+ const handled = !editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true
+ }));
+
+ expect(handled).toBe(true);
+ expect(onEnter).toHaveBeenCalledOnce();
+ expect(editor.state.doc.toString()).toBe("#book");
+ });
+
+ it("collapses line breaks in inserted text, keeping the document on one line", () => {
+ const onChange = vi.fn();
+ editor = build({ onChange });
+
+ editor.dispatch({ changes: { from: 0, insert: "#book\r\n #year = 1954\nnote.title *=* a" } });
+
+ expect(editor.state.doc.lines).toBe(1);
+ expect(editor.state.doc.toString()).toBe("#book #year = 1954 note.title *=* a");
+ expect(onChange).toHaveBeenLastCalledWith("#book #year = 1954 note.title *=* a");
+ // The caret stays within the shortened document.
+ expect(editor.state.selection.main.head).toBeLessThanOrEqual(editor.state.doc.length);
+ });
+});
+
+function build(config: Partial<SingleLineEditorConfig> = {}): SingleLineEditor {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ return createSingleLineEditor({ parent, ...config });
+}
diff --git a/packages/codemirror/src/single_line.ts b/packages/codemirror/src/single_line.ts
new file mode 100644
index 0000000000..f674644b84
--- /dev/null
+++ b/packages/codemirror/src/single_line.ts
@@ -0,0 +1,77 @@
+import { history, historyKeymap, standardKeymap } from "@codemirror/commands";
+import { EditorState, type Extension } from "@codemirror/state";
+import { EditorView, keymap, placeholder } from "@codemirror/view";
+
+export interface SingleLineEditorConfig {
+ parent: HTMLElement;
+ /** Text the editor starts with. */
+ doc?: string;
+ placeholder?: string;
+ /** 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. */
+ onEnter?(): void;
+}
+
+/** The editor {@link createSingleLineEditor} returns. */
+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.
+ *
+ * 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.
+ */
+export function createSingleLineEditor(config: SingleLineEditorConfig): SingleLineEditor {
+ const extensions: Extension[] = [
+ EditorView.lineWrapping,
+ collapseLineBreaks,
+ history(),
+ keymap.of([
+ {
+ key: "Enter",
+ run: () => {
+ config.onEnter?.();
+ return true;
+ },
+ preventDefault: true
+ },
+ ...standardKeymap,
+ ...historyKeymap
+ ]),
+ EditorView.updateListener.of((update) => {
+ if (update.docChanged) {
+ config.onChange?.(update.state.doc.toString());
+ }
+ })
+ ];
+
+ if (config.placeholder) {
+ extensions.push(placeholder(config.placeholder));
+ }
+
+ return new EditorView({
+ parent: config.parent,
+ doc: config.doc ?? "",
+ extensions
+ });
+}
+
+/**
+ * Keeps the document on one line. Typing a line break is already impossible because Enter is
+ * bound, so this covers text arriving by paste or drop: every run of whitespace holding a line
+ * break collapses to a single space.
+ */
+const collapseLineBreaks = EditorState.transactionFilter.of((tr) => {
+ if (!tr.docChanged || tr.newDoc.lines === 1) {
+ return tr;
+ }
+
+ const flattened = tr.newDoc.toString().replace(/\s*\n\s*/g, " ");
+
+ return {
+ changes: { from: 0, to: tr.startState.doc.length, insert: flattened },
+ selection: { anchor: Math.min(tr.newSelection.main.head, flattened.length) }
+ };
+});