Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
feat(web): highlight search matches in memo content (#6335)
ABird14d3c689dd29
diff --git a/web/src/components/MemoContent/index.tsx b/web/src/components/MemoContent/index.tsxindex 740c55434..d914b496d 100644--- a/web/src/components/MemoContent/index.tsx+++ b/web/src/components/MemoContent/index.tsx@@ -1,8 +1,10 @@-import { memo } from "react";+import { memo, useRef } from "react";+import { useContentSearchTerms } from "@/contexts/MemoFilterContext";import { cn } from "@/lib/utils";import { MemoMarkdownRenderer } from "./MemoMarkdownRenderer";import { useResolvedMentionUsernames } from "./MentionResolutionContext";import type { MemoContentProps } from "./types";+import { useSearchMatchHighlight } from "./useSearchMatchHighlight";// Stateless markdown renderer. Truncation is not this component's concern — compact cards// are bounded by ClampedSection around the whole memo body; `compact` here only informs@@ -11,10 +13,14 @@ import type { MemoContentProps } from "./types";const MemoContent = (props: MemoContentProps) => {const { className, contentClassName, content, attachments, onClick, onDoubleClick } = props;const resolvedMentionUsernames = useResolvedMentionUsernames(content);+ // Whatever the page's search matched is painted here, without altering the rendered tree.+ const contentRef = useRef<HTMLDivElement>(null);+ useSearchMatchHighlight(contentRef, useContentSearchTerms());return (<div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}><div+ ref={contentRef}data-memo-contentdata-memo-name={props.memoName}className={cn(diff --git a/web/src/components/MemoContent/useSearchMatchHighlight.ts b/web/src/components/MemoContent/useSearchMatchHighlight.tsnew file mode 100644index 000000000..e152ff5eaBinary files /dev/null and b/web/src/components/MemoContent/useSearchMatchHighlight.ts differdiff --git a/web/src/contexts/MemoFilterContext.tsx b/web/src/contexts/MemoFilterContext.tsxindex 7e2711b10..d3e1b6b29 100644--- a/web/src/contexts/MemoFilterContext.tsx+++ b/web/src/contexts/MemoFilterContext.tsx@@ -191,3 +191,17 @@ export function useMemoFilterContext() {// Alias for backwards compatibility during migrationexport const useMemoFilter = useMemoFilterContext;++const NO_TERMS: string[] = [];++/**+ * The words of the active plain-text search, in the order the user typed them. Safe outside a+ * provider (share previews, tests), where there is no search and therefore nothing to match.+ */+export function useContentSearchTerms(): string[] {+ const filters = useContext(MemoFilterContext)?.filters;+ return useMemo(() => {+ const terms = (filters ?? []).filter((filter) => filter.factor === "contentSearch").map((filter) => filter.value);+ return terms.length > 0 ? terms : NO_TERMS;+ }, [filters]);+}diff --git a/web/src/index.css b/web/src/index.cssindex ae4689f23..bcc176416 100644--- a/web/src/index.css+++ b/web/src/index.css@@ -30,6 +30,12 @@body {@apply bg-background text-foreground;}++ /* Search hits in memo bodies (CSS Custom Highlight API, registered by useSearchMatchHighlight).+ A translucent wash of the theme's amber keeps the text's own color legible on every theme. */+ ::highlight(memo-search-match) {+ background-color: color-mix(in oklch, var(--warning) 40%, transparent);+ }}@layer components {diff --git a/web/src/utils/search-match.ts b/web/src/utils/search-match.tsnew file mode 100644index 000000000..4431436f9--- /dev/null+++ b/web/src/utils/search-match.ts@@ -0,0 +1,88 @@+/**+ * Locates search terms inside rendered text the same way the server's `content.contains`+ * filter does: as case-folded substrings. The server folds with Unicode case folding+ * (`cases.Fold`), which JavaScript has no direct equivalent for; upper-casing then+ * lower-casing each code point is the standard approximation and agrees with folding+ * on the cases that matter in practice (`ß` → `ss`, final sigma → `σ`, `İ` → `i̇`).+ *+ * Folding can change a string's length, so matching runs on the folded text and every+ * folded code unit remembers which original offset it came from. The ranges returned+ * are therefore always valid offsets into the original text.+ */++export interface TextRange {+ /** Inclusive start offset in the original text (UTF-16 code units). */+ start: number;+ /** Exclusive end offset in the original text. */+ end: number;+}++interface FoldedText {+ folded: string;+ /** `offsets[i]` is the original offset of folded code unit `i`; `offsets[folded.length]` is the original length. */+ offsets: number[];+}++const foldCodePoint = (codePoint: string): string => codePoint.toUpperCase().toLowerCase();++const foldText = (text: string): FoldedText => {+ let folded = "";+ const offsets: number[] = [];+ let originalOffset = 0;+ for (const codePoint of text) {+ const foldedCodePoint = foldCodePoint(codePoint);+ for (let i = 0; i < foldedCodePoint.length; i++) {+ offsets.push(originalOffset);+ }+ folded += foldedCodePoint;+ originalOffset += codePoint.length;+ }+ offsets.push(originalOffset);+ return { folded, offsets };+};++/** Folds and de-duplicates search terms once so they can be matched against many text nodes. */+export const prepareSearchTerms = (terms: readonly string[]): string[] => {+ const prepared = new Set<string>();+ for (const term of terms) {+ const folded = foldText(term.trim()).folded;+ if (folded) prepared.add(folded);+ }+ return Array.from(prepared);+};++/**+ * Every occurrence of any prepared term in `text`, as sorted, non-overlapping ranges.+ * Adjacent or overlapping hits (two terms sharing characters, or a term appearing+ * back-to-back) merge into one range so a highlight never paints the same character twice.+ */+export const findSearchMatches = (text: string, preparedTerms: readonly string[]): TextRange[] => {+ if (!text || preparedTerms.length === 0) return [];++ const { folded, offsets } = foldText(text);+ const hits: TextRange[] = [];+ for (const term of preparedTerms) {+ let from = folded.indexOf(term);+ while (from !== -1) {+ // A hit may end partway through a code point that folded to several units (`ß` → `ss`);+ // widen it to that code point's end so the range never splits an original character.+ let endIndex = from + term.length;+ while (endIndex < folded.length && offsets[endIndex] === offsets[endIndex - 1]) endIndex++;+ hits.push({ start: offsets[from], end: offsets[endIndex] });+ from = folded.indexOf(term, from + 1);+ }+ }+ if (hits.length === 0) return [];++ hits.sort((a, b) => a.start - b.start || a.end - b.end);+ const merged: TextRange[] = [];+ for (const hit of hits) {+ const last = merged[merged.length - 1];+ if (last && hit.start <= last.end) {+ last.end = Math.max(last.end, hit.end);+ } else {+ merged.push({ ...hit });+ }+ }+ return merged;+};diff --git a/web/tests/search-match-highlight.test.tsx b/web/tests/search-match-highlight.test.tsxnew file mode 100644index 000000000..aeea40887--- /dev/null+++ b/web/tests/search-match-highlight.test.tsx@@ -0,0 +1,89 @@+import { render, waitFor } from "@testing-library/react";+import { useRef } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SEARCH_MATCH_HIGHLIGHT_NAME, useSearchMatchHighlight } from "@/components/MemoContent/useSearchMatchHighlight";++// jsdom has no CSS Custom Highlight API; a Set-backed Highlight and a Map registry are+// exactly the surface the hook uses (add/delete on the highlight, get/set on the registry).+class HighlightStub extends Set<Range> {}++const registry = new Map<string, HighlightStub>();++const paintedRanges = (): string[] => {+ const highlight = registry.get(SEARCH_MATCH_HIGHLIGHT_NAME);+ return highlight ? Array.from(highlight, (range) => range.toString()) : [];+};++const Body = ({ terms, html }: { terms: string[]; html: string }) => {+ const ref = useRef<HTMLDivElement>(null);+ useSearchMatchHighlight(ref, terms);+ return <div ref={ref} dangerouslySetInnerHTML={{ __html: html }} />;+};++describe("useSearchMatchHighlight", () => {+ beforeEach(() => {+ registry.clear();+ vi.stubGlobal("Highlight", HighlightStub);+ vi.stubGlobal("CSS", { highlights: registry });+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("registers one shared highlight and paints every case-folded hit as a range", () => {+ render(<Body terms={["memo"]} html="<p>A <em>Memo</em> about memos.</p>" />);++ expect(registry.has(SEARCH_MATCH_HIGHLIGHT_NAME)).toBe(true);+ expect(paintedRanges()).toEqual(["Memo", "memo"]);+ });++ it("leaves math and SVG subtrees alone", () => {+ render(<Body terms={["x"]} html='<p>x<span class="katex">x</span><svg><text>x</text></svg></p>' />);++ expect(paintedRanges()).toEqual(["x"]);+ });++ it("does nothing without terms", () => {+ render(<Body terms={[]} html="<p>memo</p>" />);++ expect(registry.has(SEARCH_MATCH_HIGHLIGHT_NAME)).toBe(false);+ });++ it("rebuilds the ranges after the subtree changes", async () => {+ const { container } = render(<Body terms={["memo"]} html="<p>loading</p>" />);+ expect(paintedRanges()).toEqual([]);++ // Simulates an async renderer (code highlighting, a lazy link card) replacing content later.+ container.querySelector("p")!.textContent = "memo, then memo";++ await waitFor(() => expect(paintedRanges()).toEqual(["memo", "memo"]));+ });++ it("follows the search as the terms change and removes its ranges on unmount", async () => {+ const { rerender, unmount } = render(<Body terms={["alpha"]} html="<p>alpha bravo</p>" />);+ expect(paintedRanges()).toEqual(["alpha"]);++ rerender(<Body terms={["bravo"]} html="<p>alpha bravo</p>" />);+ expect(paintedRanges()).toEqual(["bravo"]);++ unmount();+ expect(paintedRanges()).toEqual([]);+ });++ it("only removes its own ranges when several bodies share the highlight", () => {+ const first = render(<Body terms={["memo"]} html="<p>first memo</p>" />);+ render(<Body terms={["memo"]} html="<p>second memo</p>" />);+ expect(paintedRanges()).toHaveLength(2);++ first.unmount();+ expect(paintedRanges()).toHaveLength(1);+ });++ it("is a no-op where the browser lacks the API", () => {+ vi.stubGlobal("CSS", {});++ expect(() => render(<Body terms={["memo"]} html="<p>memo</p>" />)).not.toThrow();+ expect(registry.size).toBe(0);+ });+});diff --git a/web/tests/search-match.test.ts b/web/tests/search-match.test.tsnew file mode 100644index 000000000..344a67a5f--- /dev/null+++ b/web/tests/search-match.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vitest";+import { findSearchMatches, prepareSearchTerms } from "@/utils/search-match";++const matches = (text: string, ...terms: string[]) => findSearchMatches(text, prepareSearchTerms(terms));++describe("prepareSearchTerms", () => {+ it("folds case, trims, drops empties and duplicates", () => {+ expect(prepareSearchTerms([" Memo ", "", "memo", "MEMO", " "])).toEqual(["memo"]);+ });+});++describe("findSearchMatches", () => {+ it("finds every occurrence of a term, ignoring case", () => {+ expect(matches("Memo memo MEMO", "memo")).toEqual([+ { start: 0, end: 4 },+ { start: 5, end: 9 },+ { start: 10, end: 14 },+ ]);+ });++ it("returns nothing without text or terms", () => {+ expect(matches("", "memo")).toEqual([]);+ expect(matches("memo")).toEqual([]);+ expect(matches("memo", " ")).toEqual([]);+ });++ it("matches several terms and sorts the hits", () => {+ expect(matches("bravo alpha charlie", "charlie", "alpha")).toEqual([+ { start: 6, end: 11 },+ { start: 12, end: 19 },+ ]);+ });++ it("merges overlapping and adjacent hits into one range", () => {+ // "aba" at 0 and 2 overlap; "ab" is adjacent to the second "aba".+ expect(matches("ababa" + "ab", "aba", "ab")).toEqual([{ start: 0, end: 7 }]);+ });++ it("keeps original offsets across astral code points", () => {+ // The emoji is two UTF-16 units; offsets must count them.+ expect(matches("🙂 note", "note")).toEqual([{ start: 3, end: 7 }]);+ });++ it("case-folds like the server: ß matches ss without splitting the character", () => {+ expect(matches("Straße", "strasse")).toEqual([{ start: 0, end: 6 }]);+ // A hit ending inside the folded "ss" widens to cover the whole ß.+ expect(matches("aß", "as")).toEqual([{ start: 0, end: 2 }]);+ });++ it("case-folds Greek final sigma", () => {+ expect(matches("ΟΔΥΣΣΕΥΣ", "οδυσσευς")).toEqual([{ start: 0, end: 8 }]);+ });+});