Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Notes: a search marks what it found, in the results and in the note

Yashwanth Kamireddi1545a0672587
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 246a0a5..58e9ba2 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -465,7 +465,13 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
const words = String(args.query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
return !notesFixture ? [] : noteList
.filter((n) => n.folderGuid !== "f2" && words.every((w) => `${n.title} ${n.body ?? ""}`.toLowerCase().includes(w)))
- .map((n) => ({ ...n }));
+ // The preview is the line where a word is, past the title, as the library gives it
+ // (search.rs note_line); the stored one when the words are only in the title.
+ .map((n) => {
+ const rest = (n.body ?? "").split("\n").slice(1);
+ const line = rest.find((l) => words.some((w) => l.toLowerCase().includes(w)));
+ return { ...n, snippet: line ?? n.snippet };
+ });
}
// Adding files: off unless a test turns it on (`__attachOn`), as the backend's switch is.
case "note_attach_enabled": return Boolean(window.__attachOn);
diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rs
index a357372..e8d3881 100644
--- a/crates/quince-core/src/notes.rs
+++ b/crates/quince-core/src/notes.rs
@@ -436,10 +436,11 @@ impl Library {
let Some(question) = crate::search::match_all(query) else {
return Ok(Vec::new());
};
+ let words = crate::search::folded_words(query);
let mut stmt = self.conn.prepare_cached(
"SELECT guid, folder_guid, title,
coalesce(snippet, substr(body, 1, 200)), locked, pinned,
- created_at, modified_at, editable, etag
+ created_at, modified_at, editable, etag, body
FROM notes
WHERE guid IN (SELECT d.key FROM search_text
JOIN search_docs d ON d.id = search_text.rowid
@@ -447,13 +448,27 @@ impl Library {
ORDER BY pinned DESC, modified_at DESC, title",
)?;
let rows = stmt.query_map(params![question], |row| {
+ let title: String = row.get(2)?;
+ let snippet: Option<String> = row.get(3)?;
+ let locked = row.get::<_, i64>(4)? != 0;
+ // Each result's preview is where its words are, as in Notes: a note found by a
+ // word far down its text shows that part of it, not its first line. Never for a
+ // locked note, whose text is not shown.
+ let snippet = if locked {
+ snippet
+ } else {
+ let body: Option<String> = row.get(10)?;
+ crate::search::note_line(&title, body, snippet.clone(), &words)
+ .0
+ .or(snippet)
+ };
Ok(Note {
guid: row.get(0)?,
folder_guid: row.get(1)?,
- title: row.get(2)?,
- snippet: row.get(3)?,
+ title,
+ snippet,
body: None,
- locked: row.get::<_, i64>(4)? != 0,
+ locked,
pinned: row.get::<_, i64>(5)? != 0,
created_at: row.get(6)?,
modified_at: row.get(7)?,
@@ -555,6 +570,31 @@ mod search_tests {
.collect()
}
+ /// A note found by a word deep in its text shows that part of it under its title.
+ #[test]
+ fn a_result_previews_where_its_words_are() {
+ let mut lib = library();
+ lib.put_notes(&[note(
+ "E",
+ "F",
+ "Trip",
+ "Trip\nPack the bags\nBook the train\nWater the ferns before leaving",
+ )])
+ .unwrap();
+ let hit = lib.search_notes("ferns").unwrap();
+ assert_eq!(
+ hit[0].snippet.as_deref(),
+ Some("Water the ferns before leaving")
+ );
+ // Found by its title alone, the preview is its text from the top.
+ let hit = lib.search_notes("trip").unwrap();
+ assert!(hit[0]
+ .snippet
+ .as_deref()
+ .unwrap()
+ .starts_with("Pack the bags"));
+ }
+
#[test]
fn a_word_in_the_body_finds_the_note() {
assert_eq!(found(&library(), "mirrors"), vec!["A"]);
diff --git a/crates/quince-core/src/search.rs b/crates/quince-core/src/search.rs
index 37d7508..35b9605 100644
--- a/crates/quince-core/src/search.rs
+++ b/crates/quince-core/src/search.rs
@@ -183,7 +183,7 @@ fn words_of(text: &str) -> impl Iterator<Item = (usize, &str)> {
}
/// The typed words, folded and split as the index splits them.
-fn folded_words(query: &str) -> Vec<String> {
+pub(crate) fn folded_words(query: &str) -> Vec<String> {
let mut out: Vec<String> = query_words(query)
.into_iter()
.flat_map(|w| {
@@ -271,6 +271,33 @@ fn excerpt(text: &str, words: &[String]) -> Option<String> {
(!line.is_empty()).then_some(line)
}
+/// The line a found note shows under its title, and where the typed words fall in it: from
+/// the note's text past its title line, around the first word found there, as Notes shows a
+/// search's results; its own preview when the words are only in the title.
+pub(crate) fn note_line(
+ title: &str,
+ body: Option<String>,
+ snippet: Option<String>,
+ words: &[String],
+) -> (Option<String>, Vec<[u32; 2]>) {
+ let line = |text: Option<String>| -> (Option<String>, Vec<[u32; 2]>) {
+ let line = text.as_deref().and_then(|t| excerpt(t, words));
+ let m = line.as_deref().map(|l| marks(l, words)).unwrap_or_default();
+ (line, m)
+ };
+ // The first line of a note is its title: the line shown is from the rest.
+ let rest = body.map(|b| match b.split_once('\n') {
+ Some((first, rest)) if first.trim() == title.trim() => rest.to_string(),
+ _ => b,
+ });
+ let (d, m) = line(rest.filter(|r| !r.trim().is_empty()));
+ if d.is_some() {
+ (d, m)
+ } else {
+ line(snippet)
+ }
+}
+
/// The ranking query: what `ranked` asks, written once.
fn ranking_sql() -> &'static str {
static SQL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
@@ -410,17 +437,7 @@ impl Library {
let (detail, detail_marks) = if locked {
(None, Vec::new())
} else {
- // The first line of a note is its title: the line shown is from the rest.
- let rest = body.map(|b| match b.split_once('\n') {
- Some((first, rest)) if first.trim() == title.trim() => rest.to_string(),
- _ => b,
- });
- let (d, m) = line(rest.filter(|r| !r.trim().is_empty()));
- if d.is_some() {
- (d, m)
- } else {
- line(snippet)
- }
+ note_line(&title, body, snippet, words)
};
Hit {
id: key.into(),
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 13f55fe..d2761b4 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -31,6 +31,7 @@ import { Picker } from "../components/Picker";
import { holdTyping } from "../lib/updates";
import { keepSame } from "../lib/same";
import { useArrivals } from "../lib/arrival";
+import { foundRanges, queryWords } from "./notes/found";
const ALL = "__all__";
@@ -104,11 +105,14 @@ const NoteRows = memo(function NoteRows({
openGuid,
rowsRef,
onPick,
+ found,
}: {
sections: Section[];
openGuid: string | null;
rowsRef: React.MutableRefObject<HTMLDivElement | null>;
onPick: (note: Note, e: React.MouseEvent) => void;
+ /** The words being searched for, marked where they fall in each row. */
+ found: string[];
}) {
return (
<div className="note-rows" ref={rowsRef} role="listbox" aria-label="Notes" data-rows="">
@@ -131,12 +135,12 @@ const NoteRows = memo(function NoteRows({
{note.locked && (
<LockKeyhole className="note-row-lock" size={12} strokeWidth={2.4} aria-label="Locked" />
)}
- <span className="note-row-name">{wordsOnly(note.title) || "New Note"}</span>
+ <span className="note-row-name"><Found text={wordsOnly(note.title) || "New Note"} words={found} /></span>
</span>
<span className="note-row-meta">
<span className="note-row-when">{listDate(note.modifiedAt)}</span>
<span className="note-row-snippet">
- {note.locked ? "Locked" : wordsOnly(note.snippet ?? "").slice(0, 80) || "No additional text"}
+ {note.locked ? "Locked" : <Found text={wordsOnly(note.snippet ?? "").slice(0, 120) || "No additional text"} words={found} />}
</span>
</span>
</button>
@@ -148,6 +152,21 @@ const NoteRows = memo(function NoteRows({
);
});
+/** `text` with the searched-for words marked, as Notes marks them in its results. */
+function Found({ text, words }: { text: string; words: string[] }) {
+ const ranges = words.length ? foundRanges(text, words) : [];
+ if (!ranges.length) return <>{text}</>;
+ const out: React.ReactNode[] = [];
+ let from = 0;
+ ranges.forEach(([a, b], i) => {
+ if (a > from) out.push(text.slice(from, a));
+ out.push(<mark key={i} className="note-found">{text.slice(a, b)}</mark>);
+ from = b;
+ });
+ if (from < text.length) out.push(text.slice(from));
+ return <>{out}</>;
+}
+
export function NotesView() {
// The folders' column: as wide as it was left, or — the first time — as wide as the longest
// folder name needs, within reason.
@@ -1188,6 +1207,8 @@ export function NotesView() {
useEffect(() => setDetail(false), [folder]);
const sections = useMemo(() => groupNotes(notes, new Date(), listOrder), [notes, listOrder]);
+ /** What a search is looking for, marked in the results and in the note opened from them. */
+ const foundWords = useMemo(() => (searching ? queryWords(query) : []), [searching, query]);
/** The folders as nested, worked out when they change rather than on every key typed. */
const nested = useMemo(() => nestFolders(folders), [folders]);
@@ -1477,7 +1498,7 @@ export function NotesView() {
{/* One list box of notes, a group per heading: the open note is its selected option.
The heading is drawn for the eye; the group's name says it to a screen reader. */}
- <NoteRows sections={sections} openGuid={openGuid} rowsRef={rowsRef} onPick={pickRow} />
+ <NoteRows sections={sections} openGuid={openGuid} rowsRef={rowsRef} onPick={pickRow} found={foundWords} />
{loaded && notes.length === 0 && !error && !(arriving && !searching) && (
searching ? (
@@ -1692,6 +1713,7 @@ export function NotesView() {
onChange={apply}
onStatus={setStatus}
onBlur={leave}
+ found={composing ? undefined : foundWords}
/>
</div>
{attaching && (
diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsx
index c258550..1e48b9d 100644
--- a/src/screens/notes/NoteEditor.tsx
+++ b/src/screens/notes/NoteEditor.tsx
@@ -9,6 +9,7 @@ import { Fragment, Slice, type Node as PMNode } from "prosemirror-model";
import type { Run } from "./Formatted";
import { checklistMove, fromDoc, listNumbers, LIST_STYLES, schema, STYLE, tableCells, toDoc } from "./rich";
import { MOVE_CHECKED_KEY } from "./model";
+import { foundRanges } from "./found";
function moveCheckedOn(): boolean {
try {
@@ -484,6 +485,8 @@ type Props = {
onChange: (text: string, runs: Run[]) => void;
onStatus?: (status: EditorStatus) => void;
onBlur?: () => void;
+ /** The words of the search the note was opened from, marked where they fall (found.ts). */
+ found?: string[];
};
/** Every paragraph the selection touches, with where it starts. */
@@ -607,6 +610,35 @@ const numbered: Plugin<DecorationSet> = new Plugin<DecorationSet>({
props: { decorations: (state): DecorationSet | undefined => numbered.getState(state) },
});
+/**
+ * The words of a search marked in the note, as Notes marks them in a note opened from its
+ * results. Only drawn — never part of the note — and worked out again only when the words or
+ * the text change; with no search, nothing is walked at all.
+ */
+type FoundState = { words: string[]; marks: DecorationSet };
+function foundMarks(doc: PMNode, words: string[]): DecorationSet {
+ if (!words.length) return DecorationSet.empty;
+ const marks: Decoration[] = [];
+ doc.descendants((node, pos) => {
+ if (!node.isText || !node.text) return true;
+ for (const [a, b] of foundRanges(node.text, words)) marks.push(Decoration.inline(pos + a, pos + b, { class: "note-found" }));
+ return false;
+ });
+ return DecorationSet.create(doc, marks);
+}
+const found: Plugin<FoundState> = new Plugin<FoundState>({
+ state: {
+ init: () => ({ words: [], marks: DecorationSet.empty }),
+ apply: (tr, was) => {
+ const words = tr.getMeta(found) as string[] | undefined;
+ if (words) return { words, marks: foundMarks(tr.doc, words) };
+ if (!tr.docChanged || !was.words.length) return was;
+ return { words: was.words, marks: foundMarks(tr.doc, was.words) };
+ },
+ },
+ props: { decorations: (state): DecorationSet | undefined => found.getState(state)?.marks },
+});
+
const parentOf = (state: EditorState) => state.selection.$from.parent;
const inList = (state: EditorState) => LIST_STYLES.includes(parentOf(state).attrs.style);
@@ -705,7 +737,7 @@ function statusOf(state: EditorState): EditorStatus {
* back as Apple's text and runs on every change.
*/
export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
- { text, runs, editable, label, placeholder, autoFocus, onChange, onStatus, onBlur },
+ { text, runs, editable, label, placeholder, autoFocus, onChange, onStatus, onBlur, found: words },
ref,
) {
const host = useRef<HTMLDivElement | null>(null);
@@ -756,6 +788,7 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
letTabOut,
autolink,
numbered,
+ found,
history(),
keymap({
"Mod-z": undo,
@@ -941,6 +974,29 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
view.current?.setProps({ editable: () => editable });
}, [editable]);
+ // The search's words, marked; a new search marks its own, and leaving it clears them.
+ const wordsKey = (words ?? []).join("\u0000");
+ useEffect(() => {
+ const v = view.current;
+ if (!v) return;
+ const now = words ?? [];
+ const was = found.getState(v.state)?.words ?? [];
+ if (was.join("\u0000") === now.join("\u0000")) return;
+ v.dispatch(v.state.tr.setMeta(found, now).setMeta("addToHistory", false));
+ // The first place it is found is brought into view, as Notes opens a result there — not
+ // while someone is writing in the note, whose place is their own.
+ if (now.length && !v.hasFocus()) {
+ const first = v.dom.querySelector<HTMLElement>(".note-found");
+ const scroller = v.dom.closest<HTMLElement>(".note-editor");
+ if (first && scroller) {
+ const box = scroller.getBoundingClientRect();
+ const at = first.getBoundingClientRect();
+ if (at.top < box.top || at.bottom > box.bottom) first.scrollIntoView({ block: "center" });
+ }
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [wordsKey]);
+
useImperativeHandle(ref, () => ({
setStyle: (style) => {
const v = view.current;
diff --git a/src/screens/notes/found.ts b/src/screens/notes/found.ts
new file mode 100644
index 0000000..3789c4f
--- /dev/null
+++ b/src/screens/notes/found.ts
@@ -0,0 +1,41 @@
+/**
+ * Where the words of a search fall in a piece of text, as Notes marks them in its list and in
+ * the note opened from it: each word typed matches the start of a word, case and accents aside
+ * — the way the library's index found the note (search.rs), so what is marked is what found it.
+ */
+
+/** A character as the search compares it: lower case, its accents off. */
+const foldChar = (c: string) => c.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
+
+/** The words of a query, folded, longest first — so "spring" marks all of "Springfield". */
+export function queryWords(query: string): string[] {
+ return [...new Set(query.split(/\s+/).map((w) => [...w].map(foldChar).join("").replace(/[^\p{L}\p{N}]/gu, "")).filter(Boolean))]
+ .sort((a, b) => b.length - a.length);
+}
+
+const WORD = /[\p{L}\p{N}\p{M}]+/gu;
+
+/** Each place in `text` a word begins with one of `words`, as [from, to) in UTF-16 units. */
+export function foundRanges(text: string, words: string[]): [number, number][] {
+ if (!words.length || !text) return [];
+ const out: [number, number][] = [];
+ for (const m of text.matchAll(WORD)) {
+ const word = m[0];
+ const at = m.index ?? 0;
+ for (const w of words) {
+ // Folded a character at a time, so the end of the match is known in the text itself.
+ let folded = "";
+ let end = 0;
+ for (const c of word) {
+ if (folded.length >= w.length) break;
+ folded += foldChar(c);
+ end += c.length;
+ }
+ if (folded.startsWith(w)) {
+ out.push([at, at + end]);
+ break;
+ }
+ }
+ }
+ return out;
+}
diff --git a/src/styles/notes.css b/src/styles/notes.css
index 9b03288..d63d50f 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -102,6 +102,10 @@
.note-row-when { flex: none; color: var(--text); font-variant-numeric: tabular-nums; }
.note-row-snippet { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-3); }
+/* What a search found, marked in yellow as Notes marks it: in the results and in the note. */
+.note-found { border-radius: 2px; background: color-mix(in srgb, var(--sys-yellow, #ffcc00) 45%, transparent); color: inherit; }
+.note-rows:focus-within .note-row[aria-selected="true"] .note-found { background: color-mix(in srgb, var(--sys-yellow, #ffcc00) 35%, transparent); }
+
/* ---- the note ------------------------------------------------------------------- */
.note-body { display: flex; flex-direction: column; min-width: 0; min-height: 0; padding: 0 0 0 28px; }