Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

core: improve prefix/suffix generation for matches

Abdullah Attaff723e5c78a8
diff --git a/packages/core/src/api/lookup.ts b/packages/core/src/api/lookup.ts
index e43bd96d7..c3b4f58cf 100644
--- a/packages/core/src/api/lookup.ts
+++ b/packages/core/src/api/lookup.ts
@@ -533,7 +533,7 @@ function arrayToVirtualizedGrouping<T extends { id: string }>(
);
}
-function splitHighlightedMatch(text: string): Match[][] {
+export function splitHighlightedMatch(text: string): Match[][] {
const parts = text.split(MATCH_TAG_REGEX);
const allMatches: Match[][] = [];
let matches: Match[] = [];
@@ -554,17 +554,20 @@ function splitHighlightedMatch(text: string): Match[][] {
if (suffix) {
suffix = suffix.replace(/\s{2,}/gm, " ");
- suffix = suffix.slice(0, Math.max(suffix.length / 2, 60));
+ const [_suffix, remaining] = splitToNearestWord(
+ suffix,
+ Math.max(suffix.length / 2, 60)
+ );
+ parts[i + 2] = remaining;
+ suffix = _suffix;
}
matches.push({
match,
- prefix: prefix.replace(/\s{2,}/gm, " "),
+ prefix: prefix.replace(/\s{2,}/gm, " ").trimStart(),
suffix: suffix || ""
});
- if (suffix) parts[i + 2] = suffix.slice(suffix.length);
-
totalLength += matchLength;
}
@@ -599,6 +602,23 @@ function splitHighlightedMatch(text: string): Match[][] {
return allMatches;
}
+function splitToNearestWord(text: string, maxLength: number): [string, string] {
+ if (text.length <= maxLength) return [text, ""];
+
+ // Find the last space before maxLength
+ let splitIndex = text.lastIndexOf(" ", maxLength);
+
+ // If no space found, force split at maxLength
+ if (splitIndex === -1) {
+ splitIndex = maxLength;
+ }
+
+ const firstPart = text.substring(0, splitIndex);
+ const remainingText = text.substring(splitIndex);
+
+ return [firstPart, remainingText];
+}
+
interface CenterOptions {
maxLength?: number; // Maximum total length of output
minContext?: number; // Minimum context on each side