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.

Calendar: search, as Calendar's toolbar field

Yashwanth Kamireddiec1acdc97d56
diff --git a/.uiverify/occasions.mjs b/.uiverify/occasions.mjs
index 28a563f..14f737a 100644
--- a/.uiverify/occasions.mjs
+++ b/.uiverify/occasions.mjs
@@ -45,5 +45,24 @@ await page.waitForTimeout(300);
ok(!(await shown("Zoya Ahuja’s Birthday")) && (await shown("Diwali")), "switching Birthdays off hides them, and only them",
"switching Birthdays off did not hide them, or hid the holidays too");
+// Search, as Calendar's toolbar field: Ctrl+F to it, type, and a result opens its day.
+await page.keyboard.press("Control+f");
+const focused = await page.evaluate(() => document.activeElement?.getAttribute("aria-label"));
+ok(focused === "Search events", "Ctrl+F goes to the search field", `focus went to ${focused}`);
+await page.keyboard.type("diwali");
+await page.waitForTimeout(400);
+const rows = await page.locator(".cx-found-row").allInnerTexts();
+ok(rows.length === 1 && rows[0].includes("Diwali"), "searching finds the event", `found: ${JSON.stringify(rows)}`);
+if (rows.length) {
+ await page.locator(".cx-found-row").first().click();
+ await page.waitForTimeout(400);
+ const after = await page.evaluate(() => ({
+ day: document.querySelector('.segment[aria-pressed="true"]')?.textContent,
+ shows: document.body.innerText.includes("Diwali"),
+ open: Boolean(document.querySelector(".cx-found")),
+ }));
+ ok(after.day === "Day" && after.shows && !after.open, "and opening it shows its day", `after: ${JSON.stringify(after)}`);
+}
+
await b.close();
process.exitCode = failures === 0 ? 0 : 1;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index cb13777..b543d63 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -134,6 +134,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "auth_submit_code": return null;
case "account_services": return services;
case "calendar_events": return events;
+ case "calendar_search": {
+ const words = String(args?.query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
+ return events.filter((e) => words.every((w) => `${e.title} ${e.location ?? ""}`.toLowerCase().includes(w)))
+ .sort((a, b) => a.startsAt - b.startsAt);
+ }
case "calendar_list": return calendars;
case "event_save": return "E-new";
case "event_delete": return null;
diff --git a/crates/quince-core/src/calendar.rs b/crates/quince-core/src/calendar.rs
index a8253a0..dd75f80 100644
--- a/crates/quince-core/src/calendar.rs
+++ b/crates/quince-core/src/calendar.rs
@@ -200,6 +200,38 @@ impl Library {
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
+ /// Events whose title, place or notes hold every word of `query`, accent- and
+ /// case-insensitively, soonest first — what Calendar's search field finds.
+ pub fn search_events(&self, query: &str) -> Result<Vec<Event>> {
+ let words = crate::fold::words(query);
+ if words.is_empty() {
+ return Ok(Vec::new());
+ }
+ let mut stmt = self.conn.prepare("SELECT guid FROM events")?;
+ let guids: Vec<String> = stmt
+ .query_map([], |row| row.get(0))?
+ .collect::<rusqlite::Result<_>>()?;
+ let mut found: Vec<Event> = guids
+ .iter()
+ .filter_map(|g| self.event(g).ok().flatten())
+ .filter(|e| {
+ let text = [
+ Some(e.title.as_str()),
+ e.location.as_deref(),
+ e.notes.as_deref(),
+ ]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>()
+ .join(" ");
+ crate::fold::holds_all(&crate::fold::fold(&text), &words)
+ })
+ .collect();
+ found.sort_by_key(|e| e.starts_at);
+ found.truncate(200);
+ Ok(found)
+ }
+
/// One event by its guid, if the library still holds it.
pub fn event(&self, guid: &str) -> Result<Option<Event>> {
let mut stmt = self.conn.prepare(
@@ -398,3 +430,50 @@ mod tests {
assert!(lib.last_synced("calendar").unwrap().is_some());
}
}
+
+#[cfg(test)]
+mod search_tests {
+ use super::*;
+
+ #[test]
+ fn search_finds_every_word_in_title_place_or_notes_ignoring_accents() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_calendars(&[Calendar {
+ guid: "c".into(),
+ title: "Work".into(),
+ enabled: true,
+ writable: true,
+ ..Default::default()
+ }])
+ .unwrap();
+ let ev = |g: &str, t: &str, place: Option<&str>, at: i64| Event {
+ guid: g.into(),
+ calendar_guid: "c".into(),
+ title: t.into(),
+ location: place.map(Into::into),
+ starts_at: at,
+ ends_at: at + 60,
+ ..Default::default()
+ };
+ lib.put_events(&[
+ ev("a", "Dentist", Some("Café Road"), 200),
+ ev("b", "Design review", None, 100),
+ ev("c", "Dentist", None, 50),
+ ])
+ .unwrap();
+ let titles = |q: &str| {
+ lib.search_events(q)
+ .unwrap()
+ .into_iter()
+ .map(|e| e.guid)
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(titles("dentist"), ["c", "a"], "soonest first");
+ assert_eq!(
+ titles("dentist cafe"),
+ ["a"],
+ "every word, accents folded, place included"
+ );
+ assert!(titles(" ").is_empty());
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index f47eb6e..008c66d 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -475,6 +475,38 @@ async fn calendar_events(
Ok(events)
}
+/// Events holding every word of `query`, soonest first — and birthdays and holidays in the
+/// year either side of now, which are found the same way.
+#[tauri::command]
+async fn calendar_search(
+ query: String,
+ data: State<'_, Data>,
+ occasions: State<'_, Occasions>,
+) -> UiResult<Vec<Event>> {
+ let words = quince_core::fold::words(&query);
+ let (mut found, people) = {
+ let library = data.0.lock().await;
+ (
+ library.search_events(&query).map_err(|e| e.to_string())?,
+ library.contacts(None).map_err(|e| e.to_string())?,
+ )
+ };
+ if !words.is_empty() {
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0));
+ let (from, to) = (now - 366 * 86_400, now + 366 * 86_400);
+ let feed = occasions.feed.lock().await;
+ let extra = quince_icloud::occasions::birthdays(&people, from, to)
+ .into_iter()
+ .chain(quince_icloud::occasions::holidays(&feed.1, from, to))
+ .filter(|e| quince_core::fold::holds_all(&quince_core::fold::fold(&e.title), &words));
+ found.extend(extra);
+ found.sort_by_key(|e| e.starts_at);
+ }
+ Ok(found)
+}
+
/// The holiday feed for this machine's region, and its name, kept beside the library.
struct Occasions {
feed: Mutex<(Option<String>, Vec<quince_icloud::occasions::Holiday>)>,
@@ -1944,6 +1976,7 @@ fn main() {
event_save,
event_delete,
calendar_list,
+ calendar_search,
reminder_lists,
reminder_groups,
reminder_sections,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 256c320..67c6e1d 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -77,6 +77,8 @@ export const api = {
eventDelete: (guid: string) => invoke<void>("event_delete", { guid }),
calendarSync: (from: string, to: string, timezone: string) =>
invoke<SyncSummary>("calendar_sync", { from, to, timezone }),
+ /** Events holding every word of the query, soonest first. */
+ calendarSearch: (query: string) => invoke<CalendarEvent[]>("calendar_search", { query }),
calendarEvents: (from: number, to: number) =>
invoke<CalendarEvent[]>("calendar_events", { from, to }),
calendarList: () => invoke<Calendar[]>("calendar_list"),
diff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsx
index 71dbe08..b572042 100644
--- a/src/screens/calendar/CalendarView.tsx
+++ b/src/screens/calendar/CalendarView.tsx
@@ -1,4 +1,5 @@
import { Notice } from "../../components/Notice";
+import { Search } from "lucide-react";
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import {
api,
@@ -123,8 +124,31 @@ export function CalendarView() {
// Remembering the view is a convenience.
}
};
+ /** A found event: its day, in Day view, and the search put away. */
+ const openFound = (e: CalendarEvent) => {
+ setSelected(midnight(dateOf(e.startsAt)));
+ setView("day");
+ setQuery("");
+ };
+
/** The day everything is anchored on: the one selected, and what the views are built around. */
const [selected, setSelected] = useState<Date>(() => midnight(today));
+ // Search, as Calendar's toolbar field: every word, any calendar, soonest first.
+ const [query, setQuery] = useState("");
+ const [found, setFound] = useState<CalendarEvent[]>([]);
+ const searchField = useRef<HTMLInputElement | null>(null);
+ useEffect(() => {
+ const q = query.trim();
+ if (!q) return setFound([]);
+ let cancelled = false;
+ const timer = window.setTimeout(() => {
+ api.calendarSearch(q).then((r) => !cancelled && setFound(r)).catch(() => !cancelled && setFound([]));
+ }, 120);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ };
+ }, [query]);
const [events, setEvents] = useState<CalendarEvent[]>([]);
const [due, setDue] = useState<Reminder[]>([]);
const [calendars, setCalendars] = useState<Calendar[]>([]);
@@ -347,6 +371,12 @@ export function CalendarView() {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const typing = (e.target as HTMLElement | null)?.closest("input, textarea, select, [contenteditable]");
+ // Find, as everywhere on a Mac: ⌘F (Ctrl+F here) goes to the search field.
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {
+ e.preventDefault();
+ searchField.current?.focus();
+ return;
+ }
if (typing || draft) return;
if ((e.metaKey || e.ctrlKey) && e.key === "ArrowLeft") shift(-1);
else if ((e.metaKey || e.ctrlKey) && e.key === "ArrowRight") shift(1);
@@ -477,9 +507,50 @@ export function CalendarView() {
›
</button>
</span>
+ <label className="cx-search">
+ <Search size={13} strokeWidth={2.25} aria-hidden="true" />
+ <input
+ ref={searchField}
+ type="search"
+ placeholder="Search"
+ aria-label="Search events"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") setQuery("");
+ if (e.key === "Enter" && found[0]) openFound(found[0]);
+ }}
+ />
+ </label>
</div>
</header>
+ {query.trim() && (
+ <div className="cx-found" role="listbox" aria-label="Events found">
+ {found.length === 0 ? (
+ <p className="cx-found-none">No events match “{query.trim()}”.</p>
+ ) : (
+ found.map((e) => (
+ <button
+ key={e.guid}
+ className="cx-found-row"
+ role="option"
+ aria-selected={false}
+ style={{ "--cal": tint(byGuid.get(e.calendarGuid)) } as React.CSSProperties}
+ onClick={() => openFound(e)}
+ >
+ <span className="cx-dot" aria-hidden="true" />
+ <span className="cx-found-title">{e.title}</span>
+ <span className="cx-found-when">
+ {dateOf(e.startsAt).toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short", year: "numeric" })}
+ {e.allDay ? "" : ` · ${clock(e.startsAt)}`}
+ </span>
+ </button>
+ ))
+ )}
+ </div>
+ )}
+
{error && (
<Notice message={error} onDismiss={() => setError(null)} />
)}
diff --git a/src/styles/calendar.css b/src/styles/calendar.css
index 8f48c75..54d16cc 100644
--- a/src/styles/calendar.css
+++ b/src/styles/calendar.css
@@ -151,6 +151,59 @@
.cx-title strong { font-weight: 700; }
.cx-title-brief { display: none; }
.cx-bar > .segmented { flex: none; }
+/* Search, at the toolbar's end as in Calendar. */
+.cx-search {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ width: 168px;
+ height: 26px;
+ padding: 0 8px;
+ border-radius: var(--r-field);
+ background: color-mix(in srgb, var(--text) 7%, transparent);
+ color: var(--text-3);
+}
+.cx-search:focus-within { box-shadow: 0 0 0 3px var(--gold-ring); }
+.cx-search input { flex: 1; min-width: 0; border: 0; background: none; color: var(--text); font: inherit; font-size: var(--t-13); outline: none; }
+.cx-search input::placeholder { color: var(--text-3); }
+@container cx-page (max-width: 860px) { .cx-search { width: 120px; } }
+@container cx-page (max-width: 560px) { .cx-search { width: 34px; padding: 0 9px; } .cx-search:focus-within { width: 150px; } }
+
+/* What search found, laid over the view below, soonest first. */
+.cx-found {
+ position: relative;
+ z-index: 30;
+ max-height: min(60vh, 420px);
+ margin: 0 18px 10px;
+ padding: 4px;
+ overflow-y: auto;
+ border-radius: 12px;
+ background: var(--glass);
+ -webkit-backdrop-filter: var(--glass-blur);
+ backdrop-filter: var(--glass-blur);
+ box-shadow: var(--glass-specular), 0 0 0 0.5px var(--glass-edge), var(--shadow-sheet);
+}
+.cx-found-row {
+ display: grid;
+ grid-template-columns: 8px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 7px 10px;
+ border: 0;
+ border-radius: 8px;
+ background: none;
+ color: var(--text);
+ font: inherit;
+ font-size: var(--t-13);
+ text-align: left;
+ cursor: default;
+}
+.cx-found-row:hover, .cx-found-row:focus-visible { background: color-mix(in srgb, var(--text) 8%, transparent); outline: none; }
+.cx-found-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.cx-found-when { color: var(--text-3); font-size: var(--t-11); font-variant-numeric: tabular-nums; white-space: nowrap; }
+.cx-found-none { margin: 0; padding: 10px; color: var(--text-3); font-size: var(--t-13); }
+
.cx-tools { flex: none; display: flex; justify-content: flex-end; align-items: center; gap: 10px; }
.cx-step { display: inline-flex; align-items: center; gap: 2px; }