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(collections): filter a board with the search string field
Elian Doran877db11eddd1
diff --git a/apps/client/src/widgets/collections/collection_filter.css b/apps/client/src/widgets/collections/collection_filter.cssindex 5b379e9793..0bb738deb9 100644--- a/apps/client/src/widgets/collections/collection_filter.css+++ b/apps/client/src/widgets/collections/collection_filter.css@@ -58,7 +58,7 @@border-color: var(--collection-filter-active-border-color);}- > input.form-control {+ > .collection-filter-input {width: 100%;box-shadow: none;border: 0;@@ -69,12 +69,17 @@color: inherit;font-size: inherit;- &::placeholder {+ .cm-placeholder {color: var(--collection-filter-color);}++ /* One line, laid out like the input it replaced: a long query scrolls sideways. */+ .cm-line {+ white-space: pre;+ }}- &:has(.collection-filter-clear) > input.form-control {+ &:has(.collection-filter-clear) > .collection-filter-input {padding-inline-end: calc(2 * var(--collection-filter-button-size) + 2 * var(--collection-filter-button-inset)+ var(--collection-filter-button-gap));diff --git a/apps/client/src/widgets/collections/collection_filter.spec.tsx b/apps/client/src/widgets/collections/collection_filter.spec.tsxindex 04ddc9811c..e96ad0d948 100644--- a/apps/client/src/widgets/collections/collection_filter.spec.tsx+++ b/apps/client/src/widgets/collections/collection_filter.spec.tsx@@ -1,3 +1,4 @@+import { EditorView } from "@codemirror/view";import { deferred } from "@triliumnext/commons";import { render } from "preact";import { act } from "preact/test-utils";@@ -413,9 +414,11 @@ describe("CollectionFilterInput", () => {<CollectionFilterInput filter={filter} /></ParentComponent.Provider>,container));- const input = container.querySelector("input");- expect(input).not.toBeNull();- return { filter, input: input as HTMLInputElement };+ const content = container.querySelector<HTMLElement>(".cm-content");+ expect(content).not.toBeNull();+ const view = content && EditorView.findFromDOM(content);+ expect(view).not.toBeNull();+ return { filter, view: view as EditorView };}/**@@ -423,46 +426,46 @@ describe("CollectionFilterInput", () => {* through and does not open on one at all. Narrowing the collection is the search it has.*/it("takes the note's own search, on the pane it is drawn in", async () => {- const { input } = mountInput({ query: "#done" });- input.value = "#done";+ const { view } = mountInput({ query: "#done" });await act(async () => { await parent.handleEvent("findInText", {}); });- expect(document.activeElement).toBe(input);+ expect(document.activeElement).toBe(view.contentDOM);// Selected, so what is typed next replaces the query rather than running on from it.- expect(input.selectionStart).toBe(0);- expect(input.selectionEnd).toBe("#done".length);+ expect(view.state.selection.main.from).toBe(0);+ expect(view.state.selection.main.to).toBe("#done".length);// A search aimed at another pane leaves this one alone.- input.blur();+ view.contentDOM.blur();await act(async () => { await parent.handleEvent("findInText", { ntxId: "ntx2" }); });- expect(document.activeElement).not.toBe(input);+ expect(document.activeElement).not.toBe(view.contentDOM);await act(async () => { await parent.handleEvent("findInText", { ntxId: "ntx1" }); });- expect(document.activeElement).toBe(input);+ expect(document.activeElement).toBe(view.contentDOM);});- function type(input: HTMLInputElement, value: string) {- input.value = value;- input.dispatchEvent(new Event("input", { bubbles: true }));+ function type(view: EditorView, value: string) {+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });+ }++ function press(view: EditorView, key: string) {+ view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));}it("submits what is typed on Enter", async () => {- const { filter, input } = mountInput();+ const { filter, view } = mountInput();// Typed first and submitted in a pass of its own, so the keydown runs against the// re-rendered handler that has seen the typing.- await act(async () => type(input, "#done"));- await act(async () => {- input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));- });+ await act(async () => type(view, "#done"));+ await act(async () => press(view, "Enter"));expect(filter.setQuery).toHaveBeenCalledWith("#done");});it("submits what is typed through the search button", async () => {- const { filter, input } = mountInput();+ const { filter, view } = mountInput();- await act(async () => type(input, "#done"));+ await act(async () => type(view, "#done"));const submit = container.querySelector<HTMLElement>(".collection-filter-submit");expect(submit).not.toBeNull();await act(async () => submit?.click());@@ -481,24 +484,26 @@ describe("CollectionFilterInput", () => {expect(submit).toBe(clear + 1);});- it("clears the filter through the button and refocuses the box", async () => {- const { filter } = mountInput({ query: "#done" });+ it("clears the filter through the button, emptying the box and refocusing it", async () => {+ const { filter, view } = mountInput({ query: "#done" });const clear = container.querySelector<HTMLElement>(".collection-filter-clear");expect(clear).not.toBeNull();await act(async () => clear?.click());expect(filter.setQuery).toHaveBeenCalledWith("");+ expect(view.state.doc.toString()).toBe("");+ expect(document.activeElement).toBe(view.contentDOM);});it("offers no clear button until a filter is in force, whatever is typed", async () => {- const { input } = mountInput();+ const { view } = mountInput();const box = () => container.querySelector(".collection-filter");expect(box()?.classList.contains("active")).toBe(false);expect(container.querySelector(".collection-filter-clear")).toBeNull();// Typing is not yet a filter, so there is nothing for the button to take away.- await act(async () => type(input, "#done"));+ await act(async () => type(view, "#done"));expect(container.querySelector(".collection-filter-clear")).toBeNull();mountInput({ query: "#done" });@@ -508,8 +513,8 @@ describe("CollectionFilterInput", () => {// The box carries no tooltip, and a placeholder is gone as soon as something is typed.it("names the box for assistive technology", () => {- const { input } = mountInput();- expect(input.getAttribute("aria-label")).toBe("collection_filter.placeholder");+ const { view } = mountInput();+ expect(view.contentDOM.getAttribute("aria-label")).toBe("collection_filter.placeholder");});it("shows the query error under the box", () => {@@ -518,14 +523,12 @@ describe("CollectionFilterInput", () => {});it("gives up unsubmitted typing on Escape without touching the filter", async () => {- const { filter, input } = mountInput({ query: "#kept" });+ const { filter, view } = mountInput({ query: "#kept" });- await act(async () => type(input, "#typed"));- await act(async () => {- input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));- });+ await act(async () => type(view, "#typed"));+ await act(async () => press(view, "Escape"));- expect(input.value).toBe("#kept");+ expect(view.state.doc.toString()).toBe("#kept");expect(filter.setQuery).not.toHaveBeenCalled();});});diff --git a/apps/client/src/widgets/collections/collection_filter.tsx b/apps/client/src/widgets/collections/collection_filter.tsxindex b6c826e86c..fa91fa59ba 100644--- a/apps/client/src/widgets/collections/collection_filter.tsx+++ b/apps/client/src/widgets/collections/collection_filter.tsx@@ -1,5 +1,6 @@import "./collection_filter.css";+import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";import type { HighlightedTokenInfo } from "@triliumnext/commons";import clsx from "clsx";import { useEffect, useMemo, useRef, useState } from "preact/hooks";@@ -9,8 +10,8 @@ import { t } from "../../services/i18n";import type LoadResults from "../../services/load_results";import searchService from "../../services/search";import ActionButton from "../react/ActionButton";-import FormTextBox from "../react/FormTextBox";import { useNoteContext, useTriliumEvent } from "../react/hooks";+import SearchStringEditor from "../ribbon/SearchStringEditor";/** How long to wait after a change before re-running the active filter. */const RERUN_DEBOUNCE_MS = 300;@@ -193,7 +194,7 @@ export function CollectionFilterInput({ filter, placeholder }: {placeholder?: string;}) {const [ typed, setTyped ] = useState(filter.query);- const inputRef = useRef<HTMLInputElement>(null);+ const editorRef = useRef<FieldEditor>();const { noteContext } = useNoteContext();// Adopt a query submitted elsewhere, or the stored one arriving on mount.@@ -206,31 +207,43 @@ export function CollectionFilterInput({ filter, placeholder }: {return;}- inputRef.current?.focus();- inputRef.current?.select();+ const editor = editorRef.current;+ editor?.focus();+ editor?.dispatch({ selection: { anchor: 0, head: editor.state.doc.length } });});const isActive = !!filter.query;+ const label = placeholder ?? t("collection_filter.placeholder");++ /** Puts a query in the box, which a focused editor does not otherwise adopt. */+ function show(query: string) {+ const editor = editorRef.current;++ setTyped(query);+ editor?.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: query } });+ }return (<div className={clsx("collection-filter", { active: isActive })}>- <FormTextBox- inputRef={inputRef}+ <SearchStringEditor+ className="collection-filter-input"+ noteId={noteContext?.note?.noteId ?? ""}currentValue={typed}- placeholder={placeholder ?? t("collection_filter.placeholder")}- // A placeholder names the box only until something is typed into it.- aria-label={placeholder ?? t("collection_filter.placeholder")}+ placeholder={label}+ ariaLabel={label}+ singleLine+ editorRef={editorRef}onChange={setTyped}- onKeyDown={(e: KeyboardEvent) => {- if (e.key === "Enter") {- e.preventDefault();- filter.setQuery(typed);- } else if (e.key === "Escape" && typed !== filter.query) {- // Drops what was typed and keeps the submitted query. A second Escape- // reaches the view, which handles it as usual.- e.stopPropagation();- setTyped(filter.query);+ onEnter={() => filter.setQuery(typed)}+ onEscape={() => {+ // Drops what was typed and keeps the submitted query. With nothing to drop the+ // key goes on to the view, which handles it as usual.+ if (typed === filter.query) {+ return false;}++ show(filter.query);+ return true;}}/><div className="collection-filter-buttons">@@ -241,9 +254,9 @@ export function CollectionFilterInput({ filter, placeholder }: {icon="bx bx-x"text={t("collection_filter.clear")}onClick={() => {- setTyped("");+ show("");filter.setQuery("");- inputRef.current?.focus();+ editorRef.current?.focus();}}/>)}diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsxindex 10391f61bd..ff1c1ee78f 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx@@ -1,5 +1,6 @@import type { FieldEditor } from "@triliumnext/codemirror/src/field_editor";import clsx from "clsx";+import type { MutableRef } from "preact/hooks";import { useEffect, useRef } from "preact/hooks";import { t } from "../../services/i18n";@@ -12,11 +13,22 @@ interface SearchStringEditorProps {/** The note `currentValue` belongs to. A change to it replaces the document. */noteId: string;placeholder?: string;+ /** Names the field where the placeholder is a hint rather than a name for it. */+ ariaLabel?: string;className?: string;autoFocus?: boolean;+ /** Whether the query is held to one line, for a field laid out as an input. */+ singleLine?: boolean;+ /** Handed the editor once built, for a caller that has to focus or select what it holds. */+ editorRef?: MutableRef<FieldEditor | undefined>;onChange(newValue: string): void;/** Runs when Enter is pressed, which the editor treats as "run this search". */onEnter(): void;+ /**+ * Runs on Escape, once the completion popup has passed the key on. Returns whether the field+ * took it; `false` leaves it to whatever the field sits in.+ */+ onEscape?(): boolean;}// The keys the field answers, for the contextual shortcut pane (Alt+F1). CodeMirror binds@@ -32,22 +44,36 @@ const SEARCH_STRING_HINTS: ShortcutHintDefinition = [}];+/** The same, less the line break a one-line field does not take. */+const SINGLE_LINE_HINTS: ShortcutHintDefinition = [+ {+ titleKey: "search_string.hints.title",+ hints: [+ { keys: ["Ctrl+Space"], labelKey: "search_string.hints.completions" },+ { keys: ["Enter"], labelKey: "search_string.hints.run_search" }+ ]+ }+];+/**- * Edits the `#searchString` of a saved search in a CodeMirror editor. Enter runs the search and- * Shift-Enter starts a new line, so a long query can be laid out over several of them.+ * A search query in a CodeMirror editor, with the highlighting, linting and completions the syntax+ * carries. Enter runs the search; Shift-Enter starts a new line, so a long query can be laid out+ * over several of them, unless `singleLine` holds the field to one.+ *+ * Written to edit the `#searchString` of a saved search, and used for a collection filter too.*/-export default function SearchStringEditor({ currentValue, noteId, placeholder, className, autoFocus, onChange, onEnter }: SearchStringEditorProps) {+export default function SearchStringEditor({ currentValue, noteId, placeholder, ariaLabel, className, autoFocus, singleLine, editorRef: exposedRef, onChange, onEnter, onEscape }: SearchStringEditorProps) {const parentRef = useRef<HTMLDivElement>(null);const editorRef = useRef<FieldEditor>();// 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 };+ const propsRef = useRef({ currentValue, onChange, onEnter, onEscape });+ propsRef.current = { currentValue, onChange, onEnter, onEscape };// Set while the effect below writes `currentValue` into the document, so `onChange` does not// report it as an edit the user made.const isAdopting = useRef(false);- useContextualShortcutHints(SEARCH_STRING_HINTS);+ useContextualShortcutHints(singleLine ? SINGLE_LINE_HINTS : SEARCH_STRING_HINTS);useEffect(() => {if (!parentRef.current) {@@ -58,14 +84,20 @@ export default function SearchStringEditor({ currentValue, noteId, placeholder,parent: parentRef.current,doc: propsRef.current.currentValue,placeholder,+ ariaLabel,+ singleLine,onChange: (value) => {if (!isAdopting.current) {propsRef.current.onChange(value);}},- onEnter: () => propsRef.current.onEnter()+ onEnter: () => propsRef.current.onEnter(),+ onEscape: () => propsRef.current.onEscape?.() ?? false});editorRef.current = editor;+ if (exposedRef) {+ exposedRef.current = editor;+ }if (autoFocus) {editor.focus();@@ -74,6 +106,9 @@ export default function SearchStringEditor({ currentValue, noteId, placeholder,return () => {editor.destroy();editorRef.current = undefined;+ if (exposedRef) {+ exposedRef.current = undefined;+ }};// Builds the editor once; `placeholder` and `autoFocus` are read at that point.// eslint-disable-next-line react-hooks/exhaustive-depsdiff --git a/packages/codemirror/src/field_editor.ts b/packages/codemirror/src/field_editor.tsindex 1f1b800837..9f432cc429 100644--- a/packages/codemirror/src/field_editor.ts+++ b/packages/codemirror/src/field_editor.ts@@ -14,6 +14,8 @@ export interface FieldEditorConfig {/** Text the editor starts with. */doc?: string;placeholder?: string;+ /** Names the field for assistive technology, where a placeholder is a hint rather than a name. */+ ariaLabel?: 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. */@@ -103,6 +105,10 @@ export function createFieldEditor(config: FieldEditorConfig): FieldEditor {extensions.push(placeholder(config.placeholder));}+ if (config.ariaLabel) {+ extensions.push(EditorView.contentAttributes.of({ "aria-label": config.ariaLabel }));+ }+if (config.completionSource) {const icon = config.completionIcon;