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 note's first picture shows small at the end of its row

Yashwanth Kamireddi3f70fd9d5a2c
diff --git a/.uiverify/notes-list-pictures.mjs b/.uiverify/notes-list-pictures.mjs
new file mode 100644
index 0000000..6fc8315
--- /dev/null
+++ b/.uiverify/notes-list-pictures.mjs
@@ -0,0 +1,89 @@
+// A note with a picture shows it small at the end of its row in the list, as Notes on the Mac
+// does — only a picture this computer already holds (the backend answers which, nothing is
+// fetched for the list), appearing once the note has drawn it, with the row keeping its height.
+// A note without one keeps its whole width; a picture that cannot be had is never a broken one.
+import zlib from "node:zlib";
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+// Ink on white, as Apple's fallback image of a drawing is.
+const png = (() => {
+ const { deflateSync, crc32 } = zlib;
+ const w = 120, h = 96;
+ const raw = Buffer.alloc((w * 3 + 1) * h, 255);
+ for (let y = 0; y < h; y++) {
+ raw[y * (w * 3 + 1)] = 0;
+ if (y > 40 && y < 56) raw.fill(0, y * (w * 3 + 1) + 1, (y + 1) * (w * 3 + 1));
+ }
+ const chunk = (type, data) => {
+ const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
+ const td = Buffer.concat([Buffer.from(type), data]);
+ const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(td));
+ return Buffer.concat([len, td, crc]);
+ };
+ const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
+})();
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(() => { window.__drawNote = true; window.__mediaNote = true; window.__picBase = "http://pics.test"; });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+const asked = [];
+await ctx.route("http://pics.test/**", (r) => {
+ const url = decodeURIComponent(r.request().url());
+ asked.push(url);
+ // A picture this computer no longer holds: the route has nothing for it.
+ if (url.includes("note/GONE/")) return r.fulfill({ status: 404, body: "" });
+ return r.fulfill({ status: 200, contentType: "image/png", body: png });
+});
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.locator(".note-row", { hasText: "Sketch" }).first().waitFor();
+await page.waitForFunction(() => (window.__pictureAsks ?? 0) > 0);
+
+const sketch = page.locator(".note-row", { hasText: "Sketch" }).first();
+const trip = page.locator(".note-row", { hasText: "Trip" }).first();
+const box = (l) => l.evaluate((el) => { const r = el.getBoundingClientRect(); return { top: r.top, height: r.height, right: r.right }; });
+ok((await page.locator(".note-row-thumb").count()) === 0, "with no picture kept, no row shows one");
+ok(!asked.some((u) => u.includes("/thumb")), "and none is asked for");
+const before = await box(sketch);
+
+// The note is opened and draws its drawing — which the backend then holds, and says so.
+await page.evaluate(() => { window.__notePictures = { nD: "D1" }; });
+await sketch.click();
+await page.locator(".ProseMirror img.nf-drawing").first().waitFor();
+const thumb = sketch.locator(".note-row-thumb");
+await thumb.waitFor({ state: "visible", timeout: 3000 }).catch(() => {});
+ok(await thumb.isVisible(), "once the note has drawn its picture, the row shows it, unasked");
+ok((await thumb.getAttribute("src") ?? "").includes("note%2FD1%2Fthumb"), "from the kept-pictures route, never one that fetches");
+const after = await box(sketch);
+ok(Math.abs(after.height - before.height) < 0.5 && Math.abs(after.top - before.top) < 0.5,
+ `the row keeps its height and place ${before.height.toFixed(1)} → ${after.height.toFixed(1)}`);
+const t = await box(thumb);
+ok(t.height <= after.height && Math.abs(after.right - t.right) <= 14, `the picture sits at the row's end, inside its height ${JSON.stringify({ row: after, thumb: t })}`);
+// The row is still one element: the picture is inside it, not a box around it.
+ok(await thumb.evaluate((img) => img.parentElement.classList.contains("note-row")), "the picture is part of the row itself");
+// A row without a picture keeps its whole width for its words.
+const words = await trip.evaluate((row) => {
+ const snip = row.querySelector(".note-row-meta").getBoundingClientRect();
+ return Math.round(row.getBoundingClientRect().right - snip.right);
+});
+ok(words <= 14 && (await trip.locator(".note-row-thumb").count()) === 0, `a note without a picture keeps its whole width ${words}`);
+
+// A picture the computer no longer holds: nothing drawn, no broken frame, the row unchanged.
+const tripBefore = await box(trip);
+await page.evaluate(() => {
+ window.__notePictures = { nD: "D1", nM: "GONE" };
+ window.dispatchEvent(new Event("quince:note-picture-kept"));
+});
+await page.waitForFunction(() => document.querySelectorAll(".note-row-thumb").length !== 1 || window.__pictureAsks > 2, null, { timeout: 2000 }).catch(() => {});
+await page.waitForFunction(() => [...document.querySelectorAll('.note-row')].every((r) => !r.textContent.includes("Trip") || !r.querySelector(".note-row-thumb[hidden]")), null, { timeout: 2000 }).catch(() => {});
+const shownInTrip = await trip.locator(".note-row-thumb").evaluateAll((els) => els.filter((e) => !e.hidden).length);
+const tripAfter = await box(trip);
+ok(shownInTrip === 0 && Math.abs(tripAfter.height - tripBefore.height) < 0.5, "a picture that cannot be had is not shown, and the row stays as it was");
+await page.screenshot({ path: `${process.env.TMPDIR ?? "/tmp"}/notes-list-pictures-${process.env.ENGINE ?? "chromium"}.png` });
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 1c16098..5258770 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -637,6 +637,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
? { id: "M1", uti: "public.jpeg", kind: "image", filename: "beach.jpeg", title: null, width: 1200, height: 800, size: 271872, hasPreview: true }
: { id: "M2", uti: "org.openxmlformats.spreadsheetml.sheet", kind: "file", filename: "Budget.xlsx", title: null, width: null, height: null, size: 9100, hasPreview: false };
case "note_attachment_open": (window.__opened ??= []).push(args.id); return null;
+ // Each note's first picture kept on this computer (`__notePictures`, by note); none by default.
+ case "note_pictures": window.__pictureAsks = (window.__pictureAsks ?? 0) + 1; return { ...(window.__notePictures ?? {}) };
case "note_table": if (/^[MDU]/.test(String(args.id)) || /^A[1-79]$/.test(String(args.id))) return null; return (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]).map((r) => r.slice());
case "photos_list": case "photos_counts": {
const P = (id, takenAt, extra = {}) => ({ id, master: `m${id}`, takenAt, addedAt: takenAt, kind: "image",
diff --git a/crates/quince-core/src/notes.rs b/crates/quince-core/src/notes.rs
index e8d3881..b42a75b 100644
--- a/crates/quince-core/src/notes.rs
+++ b/crates/quince-core/src/notes.rs
@@ -172,6 +172,37 @@ impl Library {
.flatten())
}
+ /// Each note's first picture — a photo, a drawing, or a scan or PDF Apple keeps a
+ /// rendering of — as `(note, attachment)`, for the small picture the list shows beside a
+ /// note, as Notes on the Mac does. Read from what this computer already knows: the note's
+ /// stored formatting says where its attachments sit, and an attachment's kind is known
+ /// once it has been drawn (`notes.attachment.<id>`, kept by `note_attachment_info`). One
+ /// whose kind is not known yet is passed over, never asked of Apple from here. Locked
+ /// notes show none: their pictures are not shown either.
+ pub fn note_first_pictures(&self) -> Result<Vec<(String, String)>> {
+ let mut stmt = self.conn.prepare_cached(
+ "SELECT n.guid, j.value ->> '$.attachment'
+ FROM notes n, json_each(n.runs) j
+ JOIN app_state s ON s.key = 'notes.attachment.' || (j.value ->> '$.attachment')
+ WHERE n.locked = 0
+ AND n.runs LIKE '%\"attachment\"%'
+ AND json_valid(n.runs)
+ AND json_valid(s.value)
+ AND (s.value ->> '$.kind' IN ('image', 'drawing')
+ OR (s.value ->> '$.kind' = 'document' AND s.value ->> '$.hasPreview'))
+ ORDER BY n.guid, j.key",
+ )?;
+ let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
+ let mut out: Vec<(String, String)> = Vec::new();
+ for row in rows {
+ let (note, attachment) = row?;
+ if out.last().is_none_or(|(n, _)| *n != note) {
+ out.push((note, attachment));
+ }
+ }
+ Ok(out)
+ }
+
pub fn put_notes(&mut self, notes: &[Note]) -> Result<()> {
let tx = self.conn.savepoint()?;
{
@@ -984,4 +1015,58 @@ mod count_tests {
assert_eq!(of("Folder/work"), Some(1));
assert_eq!(of(TRASH_FOLDER), Some(1));
}
+
+ /// The list's picture for a note is its first picture whose kind is known here — a file
+ /// before it, or one not drawn yet, is passed over — and none for a note without one, a
+ /// film, or a locked note.
+ #[test]
+ fn a_notes_first_known_picture_is_its_picture() {
+ let mut lib = Library::in_memory().unwrap();
+ let with = |guid: &str, ids: &[&str], locked: bool| {
+ let mut runs = vec![r#"{"length":5}"#.to_string()];
+ runs.extend(
+ ids.iter()
+ .map(|id| format!(r#"{{"length":1,"attachment":"{id}"}}"#)),
+ );
+ Note {
+ guid: guid.into(),
+ folder_guid: None,
+ title: guid.into(),
+ snippet: None,
+ body: Some("x".into()),
+ locked,
+ pinned: false,
+ created_at: None,
+ modified_at: Some(1),
+ editable: true,
+ etag: None,
+ runs: Some(format!("[{}]", runs.join(","))),
+ }
+ };
+ lib.put_notes(&[
+ with("trip", &["FILE", "UNKNOWN", "PIC2", "PIC3"], false),
+ with("plain", &[], false),
+ with("bank", &["PIC3"], true),
+ with("scan", &["DOC"], false),
+ with("film", &["FILM"], false),
+ ])
+ .unwrap();
+ for (id, json) in [
+ ("FILE", r#"{"kind":"file","hasPreview":false}"#),
+ ("PIC2", r#"{"kind":"drawing","hasPreview":true}"#),
+ ("PIC3", r#"{"kind":"image","hasPreview":true}"#),
+ ("DOC", r#"{"kind":"document","hasPreview":true}"#),
+ ("FILM", r#"{"kind":"video","hasPreview":true}"#),
+ ] {
+ lib.set_state(&format!("notes.attachment.{id}"), json)
+ .unwrap();
+ }
+ assert_eq!(
+ lib.note_first_pictures().unwrap(),
+ vec![
+ ("scan".to_string(), "DOC".to_string()),
+ ("trip".to_string(), "PIC2".to_string()),
+ ]
+ );
+ }
}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 3fda7f9..f21625c 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -539,6 +539,74 @@ async fn note_media_inline(app: &tauri::AppHandle, id: &str) -> Result<Vec<u8>,
Ok(small)
}
+/// The edge of the small square picture the notes list shows beside a note: three times its
+/// 34 points, sharp on a high-density screen.
+const NOTE_THUMB: u32 = 102;
+
+/// Where a note's picture already sits on this computer, to make the list's small one from:
+/// the picture as the note draws it, a drawing as Apple renders it, or a document's rendering
+/// — each kept the first time the note drew it. Never fetched for the list.
+fn note_thumb_source(dir: &std::path::Path, id: &str) -> Option<std::path::PathBuf> {
+ let safe = media_file_id(id);
+ ["inline", "drawing", "preview"]
+ .iter()
+ .map(|part| dir.join(format!("{safe}-{part}")))
+ .find(|p| p.is_file())
+}
+
+/// The note attachment whose small list picture a `quince://` request asks for:
+/// `note/<attachment id>/thumb`.
+fn note_thumb_part(path: &str) -> Option<String> {
+ let path = percent_decode(path.trim_start_matches('/'));
+ let id = path.strip_prefix("note/")?.strip_suffix("/thumb")?;
+ (!id.is_empty() && !id.contains('/')).then(|| id.to_string())
+}
+
+/// A note's small list picture: made once from the picture already kept on this computer
+/// (`note_thumb_source`), cut to a square as Notes shows it, and kept. Nothing is asked of
+/// Apple — a picture not kept yet is no picture, and the list shows none.
+async fn note_media_thumb(app: &tauri::AppHandle, id: &str) -> Result<Vec<u8>, String> {
+ let dir = state_dir(app).join("note-media");
+ let made = dir.join(format!("{}-thumb", media_file_id(id)));
+ if let Ok(bytes) = tokio::fs::read(&made).await {
+ return Ok(bytes);
+ }
+ let source = note_thumb_source(&dir, id).ok_or("not kept on this computer")?;
+ let bytes = tokio::fs::read(&source).await.map_err(|e| e.to_string())?;
+ let small = crate::cpu::run(move || quince_media::avatar(&bytes, None, NOTE_THUMB))
+ .await?
+ .map_err(|e| e.to_string())?;
+ let part = made.with_extension("part");
+ if tokio::fs::write(&part, &small).await.is_ok() {
+ let _ = tokio::fs::rename(&part, &made).await;
+ }
+ Ok(small)
+}
+
+/// Each note's first picture that this computer already holds, by note, for the small picture
+/// the list shows beside it (`note/<id>/thumb`). Read from the library and the files already
+/// kept: nothing is fetched for it, so a note whose pictures were never drawn here shows none
+/// until they are.
+#[tauri::command]
+async fn note_pictures(
+ app: tauri::AppHandle,
+ data: State<'_, Data>,
+) -> UiResult<std::collections::HashMap<String, String>> {
+ let first = data
+ .0
+ .read(quince_core::Library::note_first_pictures)
+ .await
+ .map_err(|e| e.to_string())?;
+ let dir = state_dir(&app).join("note-media");
+ crate::cpu::run(move || {
+ first
+ .into_iter()
+ .filter(|(_, id)| note_thumb_source(&dir, id).is_some())
+ .collect()
+ })
+ .await
+}
+
/// Show a file the app saved in its folder, in the file manager, chosen: a "Saved to
/// Downloads" toast's Show in Folder. Only a file in Downloads — what the app itself saves
/// there — never any other path the page might name.
@@ -6288,6 +6356,7 @@ fn main() {
let uri = request.uri();
let wanted = photo_guid(uri.host(), uri.path());
let attachment = note_part(uri.path());
+ let note_thumb = note_thumb_part(uri.path());
let reminder_image = reminder_image_part(uri.path());
let drive_thumb = drive_thumb_part(uri.path());
// A drawing's ink for a dark page, rather than a light one.
@@ -6372,6 +6441,21 @@ fn main() {
responder.respond(response.unwrap_or_default());
return;
}
+ // A note's small picture in the list: from what is kept, or none.
+ if let Some(id) = note_thumb {
+ let response = match note_media_thumb(&app, &id).await {
+ Ok(bytes) => tauri::http::Response::builder()
+ .status(200)
+ .header("Content-Type", image_type(&bytes))
+ .header("Cache-Control", "private, max-age=86400")
+ .body(bytes),
+ Err(_) => tauri::http::Response::builder()
+ .status(404)
+ .body(Vec::new()),
+ };
+ responder.respond(response.unwrap_or_default());
+ return;
+ }
// A note's picture, or the rendering of a document or film in it.
if let Some((id, part)) = attachment {
let shown = if inline {
@@ -6744,6 +6828,7 @@ fn main() {
note_table_add_row,
note_table_remove,
note_attachment_info,
+ note_pictures,
note_attachment_open,
diagnostics_save,
download_reveal,
@@ -7245,6 +7330,26 @@ mod tests {
Some((_, quince_icloud::note_media::Part::File))
));
assert!(note_part("/note%2FABC-1%2Fother").is_none());
+ // The list's small picture is its own route, never one that could fetch.
+ assert!(note_part("/note%2FABC-1%2Fthumb").is_none());
+ assert_eq!(
+ super::note_thumb_part("/note%2FABC-1%2Fthumb").as_deref(),
+ Some("ABC-1")
+ );
+ assert_eq!(super::note_thumb_part("/note%2FABC-1%2Finline"), None);
+ assert_eq!(super::note_thumb_part("/note%2Fa%2Fb%2Fthumb"), None);
+ // Made only from a picture already kept: the one the note draws first, and nothing
+ // when none is.
+ let dir = std::env::temp_dir().join(format!("skykeep-thumb-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ assert_eq!(super::note_thumb_source(&dir, "P-1"), None);
+ std::fs::write(dir.join("P-1-preview"), b"x").unwrap();
+ std::fs::write(dir.join("P-1-inline"), b"x").unwrap();
+ assert_eq!(
+ super::note_thumb_source(&dir, "P-1"),
+ Some(dir.join("P-1-inline"))
+ );
+ std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(percent_decode("plain-uuid"), "plain-uuid");
assert_eq!(percent_decode("%zz"), "%zz", "malformed stays as it was");
}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 9d5871e..d2849de 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -315,6 +315,9 @@ export const api = {
noteAttachmentInfo: (id: string) => invoke<NoteAttachment>("note_attachment_info", { id }),
/** Open a note's attachment in the app this computer uses for it. */
noteAttachmentOpen: (id: string) => invoke<void>("note_attachment_open", { id }),
+ /** Each note's first picture this computer already holds, by note: the attachment whose
+ * small picture the list shows beside it (`noteMediaSrc(id, "thumb")`). Nothing fetched. */
+ notePictures: () => invoke<Record<string, string>>("note_pictures"),
noteTableSetCell: (id: string, row: number, column: number, text: string) =>
invoke<string[][]>("note_table_set_cell", { id, row, column, text }),
/** An empty row added at `at` (0 the top); answers the table as Apple now holds it. */
@@ -755,7 +758,7 @@ export type NoteAttachment = {
};
/** A note attachment's picture — the file itself, or Apple's rendering of it. */
-export function noteMediaSrc(id: string, part: "file" | "inline" | "preview" | "drawing" | "drawing-dark"): string {
+export function noteMediaSrc(id: string, part: "file" | "inline" | "preview" | "drawing" | "drawing-dark" | "thumb"): string {
return convertFileSrc(`note/${id}/${part}`, "quince");
}
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index b14a195..1df1233 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -11,7 +11,7 @@ import { ArrowDownUp, ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, L
import { pickOpen, pickSave } from "../lib/pick";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { DEFAULT_ORDER, editorDate, groupNotes, listDate, mergeEdits, splitTitle, type NoteOrder, type Section } from "./notes/model";
-import { api, messageOf, nestFolders, notesLockApi, type Note, type NoteFolder, type UnlockedNote } from "../lib/ipc";
+import { api, messageOf, nestFolders, noteMediaSrc, notesLockApi, type Note, type NoteFolder, type UnlockedNote } from "../lib/ipc";
import { LockScreen } from "./notes/LockedNote";
import { fileName, useAttachEnabled } from "./notes/attach";
import { toast } from "../components/Toast";
@@ -20,7 +20,7 @@ import { RowMenu } from "../components/RowMenu";
import { Spinner } from "../components/Spinner";
import { FormattedBody, type Run } from "./notes/Formatted";
import { carryRuns, runsFit, sameFormatting } from "./notes/rich";
-import { NoteEditor, refreshTables, type EditorHandle, type EditorStatus } from "./notes/NoteEditor";
+import { NoteEditor, PICTURE_KEPT_EVENT, refreshTables, type EditorHandle, type EditorStatus } from "./notes/NoteEditor";
import { FormatPanel } from "./notes/FormatPanel";
import { NotePicture } from "./notes/NotePicture";
import { OPEN_NOTE_EVENT } from "./notes/links";
@@ -29,7 +29,7 @@ import { Arriving } from "../components/EmptyState";
import { useArriving, useRevision, useShownRevision } from "../lib/sync";
import { Picker } from "../components/Picker";
import { holdTyping } from "../lib/updates";
-import { keepSame } from "../lib/same";
+import { keepSame, same } from "../lib/same";
import { useArrivals } from "../lib/arrival";
import { foundRanges, queryWords } from "./notes/found";
@@ -106,6 +106,7 @@ const NoteRows = memo(function NoteRows({
rowsRef,
onPick,
found,
+ pictures,
}: {
sections: Section[];
openGuid: string | null;
@@ -113,6 +114,8 @@ const NoteRows = memo(function NoteRows({
onPick: (note: Note, e: React.MouseEvent) => void;
/** The words being searched for, marked where they fall in each row. */
found: string[];
+ /** Each note's first picture kept on this computer, by note (`api.notePictures`). */
+ pictures: Record<string, string>;
}) {
return (
<div className="note-rows" ref={rowsRef} role="listbox" aria-label="Notes" data-rows="">
@@ -120,30 +123,15 @@ const NoteRows = memo(function NoteRows({
<Fragment key={section.key}>
<div className="notes-section" aria-hidden="true">{section.heading}</div>
<div role="group" aria-label={section.heading}>
- {/* Each note is one element, the row itself: wrapped in a box of its own, every row
- was two boxes deep, and the separator had to reach across from one to the next. */}
{section.notes.map((note) => (
- <button
+ <NoteRow
key={note.guid}
- className="note-row"
- role="option"
- data-guid={note.guid}
- aria-selected={openGuid === note.guid}
- onClick={(e) => onPick(note, e)}
- >
- <span className="note-row-title">
- {note.locked && (
- <LockKeyhole className="note-row-lock" size={12} strokeWidth={2.4} aria-label="Locked" />
- )}
- <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" : <Found text={wordsOnly(note.snippet ?? "").slice(0, 120) || "No additional text"} words={found} />}
- </span>
- </span>
- </button>
+ note={note}
+ selected={openGuid === note.guid}
+ picture={pictures[note.guid] ?? null}
+ onPick={onPick}
+ found={found}
+ />
))}
</div>
</Fragment>
@@ -152,6 +140,77 @@ const NoteRows = memo(function NoteRows({
);
});
+/**
+ * One note in the list, drawn again only when something it shows changes: its note, whether
+ * it is the one open, its picture. Moving the selection with the arrow keys draws the two rows
+ * it moved between, not every row in the folder.
+ *
+ * Each note is one element, the row itself: wrapped in a box of its own, every row was two
+ * boxes deep, and the separator had to reach across from one to the next.
+ */
+const NoteRow = memo(function NoteRow({
+ note,
+ selected,
+ picture,
+ onPick,
+ found,
+}: {
+ note: Note;
+ selected: boolean;
+ picture: string | null;
+ onPick: (note: Note, e: React.MouseEvent) => void;
+ found: string[];
+}) {
+ return (
+ <button
+ className="note-row"
+ role="option"
+ data-guid={note.guid}
+ aria-selected={selected}
+ onClick={(e) => onPick(note, e)}
+ >
+ <span className="note-row-title">
+ {note.locked && (
+ <LockKeyhole className="note-row-lock" size={12} strokeWidth={2.4} aria-label="Locked" />
+ )}
+ <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" : <Found text={wordsOnly(note.snippet ?? "").slice(0, 120) || "No additional text"} words={found} />}
+ </span>
+ </span>
+ {/* The note's first picture, small, at the row's end, as Notes on the Mac shows it —
+ only one already kept on this computer, so a row never waits on Apple for it. */}
+ {picture && <NoteThumb key={picture} id={picture} />}
+ </button>
+ );
+});
+
+/**
+ * A note's small picture in the list. It takes the row's end only once it is decoded — never
+ * a blank square first, and never a broken one: a picture this computer no longer holds is
+ * not shown. It sits inside the row's own height, so a row that gains one never grows; the
+ * title and snippet just end sooner, as in Notes.
+ */
+function NoteThumb({ id }: { id: string }) {
+ const [state, setState] = useState<"loading" | "shown" | "gone">("loading");
+ if (state === "gone") return null;
+ return (
+ <img
+ className="note-row-thumb"
+ src={noteMediaSrc(id, "thumb")}
+ alt=""
+ draggable={false}
+ decoding="async"
+ hidden={state !== "shown"}
+ onLoad={() => setState("shown")}
+ onError={() => setState("gone")}
+ />
+ );
+}
+
/** `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) : [];
@@ -309,6 +368,37 @@ export function NotesView() {
// `outbox.tick`: an edit sent, or turned down, changes what the library holds.
}, [read, revision, outbox.tick]);
+ /**
+ * Each note's first picture this computer already holds, for the small picture at the end of
+ * its row. Asked again when the library moves and when a note draws a picture (and so keeps
+ * it) — a burst of pictures in one note is one ask — and kept as it was when nothing changed,
+ * so no row is drawn again for it.
+ */
+ const [pictures, setPictures] = useState<Record<string, string>>({});
+ useEffect(() => {
+ let live = true;
+ let timer: number | undefined;
+ const ask = () => {
+ api.notePictures().then(
+ (found) => live && found && setPictures((was) => (same(was, found) ? was : found)),
+ () => {
+ // Only the small pictures are missing; the list itself is unaffected.
+ },
+ );
+ };
+ const kept = () => {
+ window.clearTimeout(timer);
+ timer = window.setTimeout(ask, 120);
+ };
+ ask();
+ window.addEventListener(PICTURE_KEPT_EVENT, kept);
+ return () => {
+ live = false;
+ window.clearTimeout(timer);
+ window.removeEventListener(PICTURE_KEPT_EVENT, kept);
+ };
+ }, [revision, outbox.tick]);
+
/**
* Every write goes to Apple first and the library is re-read after, so nothing on screen
* is a guess about what was stored.
@@ -1505,7 +1595,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} found={foundWords} />
+ <NoteRows sections={sections} openGuid={openGuid} rowsRef={rowsRef} onPick={pickRow} found={foundWords} pictures={pictures} />
{loaded && notes.length === 0 && !error && !(arriving && !searching) && (
searching ? (
diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsx
index f9d212a..78ca378 100644
--- a/src/screens/notes/NoteEditor.tsx
+++ b/src/screens/notes/NoteEditor.tsx
@@ -105,6 +105,9 @@ function size(bytes: number | null): string {
/** A note's picture asked to be shown large: the viewer (NotePicture) listens for it. */
export const PICTURE_EVENT = "quince:note-picture";
export type PictureShown = { id: string; name: string; src: string; srcDark?: string; drawing?: boolean; whole?: string };
+/** A note's picture drawn, so now kept on this computer: the list may show it beside the note
+ * (NotesView asks which notes have one). */
+export const PICTURE_KEPT_EVENT = "quince:note-picture-kept";
export function drawMedia(dom: HTMLElement, info: NoteAttachment) {
const name = info.filename ?? info.title ?? (info.kind === "audio" ? "Recording" : "Attachment");
@@ -179,6 +182,7 @@ export function drawMedia(dom: HTMLElement, info: NoteAttachment) {
}
img.loading = "lazy";
img.src = noteMediaSrc(info.id, part);
+ img.addEventListener("load", () => window.dispatchEvent(new Event(PICTURE_KEPT_EVENT)), { once: true });
// The backend says whether the picture can be shown: a 404 (a HEIC with no decoder on
// this computer, a fetch that failed) and it is the file's chip, drawn as one.
img.addEventListener("error", () => {
diff --git a/src/styles/notes.css b/src/styles/notes.css
index d63d50f..be14b86 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -58,10 +58,14 @@
}
.notes-section:first-child { margin-top: 0; }
+/* Two lines — title, then date and snippet — and, for a note with a picture, that picture
+ small at the end, across both (`.note-row-thumb`). A grid so the picture takes a column of
+ its own without a box around the two lines. */
.note-row {
- display: flex;
- flex-direction: column;
- gap: 2px;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ row-gap: 2px;
+ align-items: center;
width: 100%;
padding: 8px 10px 9px;
border: 0;
@@ -101,6 +105,21 @@
.note-row-meta { display: flex; gap: 8px; min-width: 0; font-size: var(--t-11); }
.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); }
+.note-row-title, .note-row-meta { grid-column: 1; }
+/* A note's first picture, as Notes shows it at the end of the row: a small rounded square,
+ no taller than the two lines beside it, so a row that gains one keeps its height. */
+.note-row-thumb {
+ grid-column: 2;
+ grid-row: 1 / span 2;
+ margin-left: 10px;
+ display: block;
+ width: 34px;
+ height: 34px;
+ border-radius: 5px;
+ object-fit: cover;
+ box-shadow: 0 0 0 var(--hairline) var(--separator);
+}
+.note-row-thumb[hidden] { display: none; }
/* 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; }