Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Fold letters like Postgres unaccent in the client-side search matching

François Zaninotto7f1bf6a27320
diff --git a/src/components/atomic-crm/search/searchHighlight.test.ts b/src/components/atomic-crm/search/searchHighlight.test.ts
index a527d739..f4bb8af1 100644
--- a/src/components/atomic-crm/search/searchHighlight.test.ts
+++ b/src/components/atomic-crm/search/searchHighlight.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vitest";
-import { getSearchTerms, getSnippet, highlight } from "./searchHighlight";
+import {
+ getSearchTerms,
+ getSnippet,
+ highlight,
+ matchesAllTerms,
+} from "./searchHighlight";
const matchedText = (text: string, query: string) =>
highlight(text, getSearchTerms(query))
@@ -19,6 +24,14 @@ describe("highlight", () => {
]);
});
+ it("folds letters that have no accent to strip, like the database does", () => {
+ expect(matchedText("Łódź, Straße, Œuvre", "lodz strasse oeu")).toEqual([
+ "Łódź",
+ "Straße",
+ "Œu",
+ ]);
+ });
+
it("does not mark a term found in the middle of a word", () => {
expect(matchedText("Thomas", "homas")).toEqual([]);
});
@@ -32,6 +45,17 @@ describe("highlight", () => {
});
});
+describe("matchesAllTerms", () => {
+ it("requires every term to start a word, folding letters like the database", () => {
+ expect(
+ matchesAllTerms("Søren Kierkegaard", getSearchTerms("soren kier")),
+ ).toBe(true);
+ expect(
+ matchesAllTerms("Søren Kierkegaard", getSearchTerms("soren ren")),
+ ).toBe(false);
+ });
+});
+
describe("getSnippet", () => {
const description =
"A family bakery founded in 1952, known across the region for its sourdough bread and its weekly farmers market stall near the station, run by the third generation of the Martin family since the late nineties.";
diff --git a/src/components/atomic-crm/search/searchHighlight.ts b/src/components/atomic-crm/search/searchHighlight.ts
index 24183783..2d0ecb41 100644
--- a/src/components/atomic-crm/search/searchHighlight.ts
+++ b/src/components/atomic-crm/search/searchHighlight.ts
@@ -14,8 +14,36 @@ const SNIPPET_RADIUS = 60;
// term past this point does not count as shown by the title.
const VISIBLE_TITLE_LENGTH = 30;
+// Letters Postgres unaccent() folds but Unicode does not decompose
+const FOLDED_LETTERS: Record<string, string> = {
+ æ: "ae",
+ ð: "d",
+ ø: "o",
+ þ: "th",
+ ß: "ss",
+ đ: "d",
+ ħ: "h",
+ ı: "i",
+ ij: "ij",
+ ĸ: "q",
+ ŀ: "l",
+ ł: "l",
+ ŋ: "n",
+ œ: "oe",
+ ŧ: "t",
+ ſ: "s",
+};
+const FOLDABLE_LETTER = new RegExp(
+ `[${Object.keys(FOLDED_LETTERS).join("")}]`,
+ "g",
+);
+
const normalize = (value: string): string =>
- value.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
+ value
+ .normalize("NFD")
+ .replace(/\p{M}/gu, "")
+ .toLowerCase()
+ .replace(FOLDABLE_LETTER, (letter) => FOLDED_LETTERS[letter]);
export const getSearchTerms = (query: string): string[] => [
...new Set(normalize(query).match(WORD) ?? []),