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: Block Quote, and a folder column that shows whole names

Yashwanth Kamireddie26204142682
diff --git a/.uiverify/notes-folder-width.mjs b/.uiverify/notes-folder-width.mjs
new file mode 100644
index 0000000..d664882
--- /dev/null
+++ b/.uiverify/notes-folder-width.mjs
@@ -0,0 +1,46 @@
+// The folders' column shows whole names, as on the Mac: the first time it is as wide as the
+// longest name needs (within reason); its edge drags it wider or narrower and is kept; a
+// double-click on the edge fits the names; a name cut short shows whole on hover.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1400, height: 800 } });
+await ctx.addInitScript(() => {
+ window.__noteFolders = [
+ { guid: "f1", title: "Notes", sortOrder: 0 },
+ { guid: "f3", title: "Notes Features Testing", sortOrder: 1 },
+ { guid: "f2", title: "Recently Deleted", sortOrder: 2 },
+ ];
+});
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const name = page.locator(".notes-folder-name", { hasText: "Notes Features Testing" });
+const whole = () => name.evaluate((e) => e.scrollWidth <= e.clientWidth);
+const width = () => page.locator(".notes-folders").evaluate((e) => e.getBoundingClientRect().width);
+ok(await whole(), `the longest name shows whole the first time (${await width()} px)`);
+ok((await name.getAttribute("title")) === "Notes Features Testing", "and its whole name on hover");
+// Dragged narrower: cut short, with an ellipsis, and kept.
+const edge = page.getByRole("separator", { name: "Folder column width" });
+const e = await edge.boundingBox();
+await page.mouse.move(e.x + e.width / 2, e.y + 200);
+await page.mouse.down();
+await page.mouse.move(e.x - 60, e.y + 200, { steps: 6 });
+await page.mouse.up();
+await page.waitForTimeout(100);
+const narrow = await width();
+ok(narrow < e.x - 20 && !(await whole()), `dragged narrower (${narrow} px), the name is cut short`);
+await page.reload({ waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.waitForTimeout(400);
+ok(Math.abs((await width()) - narrow) < 2, "the width is kept");
+await page.getByRole("separator", { name: "Folder column width" }).dblclick();
+await page.waitForTimeout(100);
+ok(await whole(), `a double-click on the edge fits the names (${await width()} px)`);
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/notes-quote.mjs b/.uiverify/notes-quote.mjs
new file mode 100644
index 0000000..83b68f0
--- /dev/null
+++ b/.uiverify/notes-quote.mjs
@@ -0,0 +1,66 @@
+// Block Quote, as Notes has it: a quoted line shows the bar down its left; Command-' and the
+// Aa panel's Block Quote put lines in a quote and take them out; Return on an empty quoted
+// line ends the quote; and the save carries it to Apple on the lines that hold it.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+for (const scheme of ["light", "dark"]) {
+ const ctx = await b.newContext({ viewport: { width: 1200, height: 800 }, colorScheme: scheme });
+ await ctx.addInitScript(() => { window.__linkNote = true; });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+ await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+ await openScreen(page, "Notes");
+ await page.locator(".note-row", { hasText: "Links" }).first().click();
+ await page.waitForTimeout(500);
+ const line = (t) => page.locator(".note-rich .nf-p", { hasText: t }).first();
+ // A line's own start, on its first row: its first words, never the line above nor a link in it.
+ const atStart = async (t) => {
+ const box = await line(t).boundingBox();
+ const pad = await line(t).evaluate((e) => parseFloat(getComputedStyle(e).paddingInlineStart) || 0);
+ await page.mouse.click(box.x + pad + 2, box.y + Math.min(10, box.height / 2));
+ };
+ const bar = (t) => line(t).evaluate((e) => parseFloat(getComputedStyle(e).borderInlineStartWidth));
+ ok((await bar("Read")) === 3 && (await bar("Yashps")) === 0, `${scheme}: a quoted line shows its bar, others none`);
+ const lastSave = async () => { await page.waitForTimeout(1200); return page.evaluate(() => window.__noteSaves?.at(-1)); };
+ const runAt = (save, text) => {
+ const at = save.body.indexOf(text);
+ let n = 0;
+ for (const r of save.runs ?? []) { if (at < n + r.length) return r; n += r.length; }
+ return null;
+ };
+ // Command-' on the address line quotes it; the save says so on that line.
+ await atStart("Yashps");
+ await page.waitForTimeout(80);
+ await page.keyboard.press("Control+'");
+ ok((await bar("Yashps")) === 3, `${scheme}: Command-' quotes the line`);
+ let save = await lastSave();
+ ok(save && runAt(save, "Yashps")?.quote === true && runAt(save, "Links")?.quote !== true, `${scheme}: saved quoted on that line only`);
+ // The Aa panel shows it ticked, and takes it off.
+ await page.getByRole("button", { name: /^(Aa|Format)/ }).first().click().catch(() => page.locator(".notes-aa").click());
+ await page.waitForTimeout(150);
+ const item = page.getByRole("menuitemcheckbox", { name: "Block Quote" });
+ ok((await item.getAttribute("aria-checked")) === "true", `${scheme}: Aa shows Block Quote ticked on a quoted line`);
+ await item.click();
+ await page.waitForTimeout(150);
+ ok((await bar("Yashps")) === 0, `${scheme}: and takes it off`);
+ // Return on an empty quoted line ends the quote.
+ // At the line's start: its middle is a link, and a click there opens it.
+ await atStart("Read");
+ await page.waitForTimeout(80);
+ await page.keyboard.press("End");
+ // The editor learns where the cursor went from the selection's own event: a key pressed in
+ // the same instant would act on where it was (Chromium), which no hand can do.
+ await page.waitForTimeout(80);
+ await page.keyboard.press("Enter");
+ ok(await page.evaluate(() => [...document.querySelectorAll(".note-rich .nf-p")].at(-1).dataset.quote === "true"), `${scheme}: a new line in a quote is quoted`);
+ await page.keyboard.press("Enter");
+ ok(await page.evaluate(() => [...document.querySelectorAll(".note-rich .nf-p")].at(-1).dataset.quote !== "true"), `${scheme}: Return on an empty quoted line ends the quote`);
+ await page.screenshot({ path: `${process.env.TMPDIR ?? "/tmp"}/notes-quote-${scheme}-${process.env.ENGINE}.png` });
+ await ctx.close();
+}
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index b46e350..ae6afe4 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -247,6 +247,13 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });
return [plain(5), { ...plain(1), attachment: "M1" }, plain(1), { ...plain(1), attachment: "M2" }, plain(4)];
}
+ if (args.guid === "nL") {
+ // "Links", then the address line, then the last line quoted (Block Quote, field 8).
+ const body = (noteList.find((n) => n.guid === "nL") ?? {}).body ?? "";
+ const lines = body.split("\n");
+ return lines.map((l, i) => ({ length: l.length + (i < lines.length - 1 ? 1 : 0), style: i === 0 ? 0 : null, indent: 0,
+ checked: null, bold: false, italic: false, underline: false, strike: false, link: null, ...(i === 2 ? { quote: true } : {}) }));
+ }
if (args.guid === "nT") {
// "Groceries", a table on its own line, then a last line: the table's run names it.
const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index de0d831..30db939 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -521,4 +521,10 @@ pub const MIGRATIONS: &[&str] = &[
ALTER TABLE photos ADD COLUMN live_size INTEGER;
UPDATE sync_state SET token = NULL WHERE service = 'photos';
"#,
+ // Notes read once more from the start, so every stored note knows its block quotes
+ // (paragraph field 8): a note stored before would hand back its quoted lines unquoted on
+ // its next edit, and the quotes would be lost at Apple.
+ r#"
+ UPDATE sync_state SET token = NULL, last_full_at = NULL WHERE service = 'notes';
+ "#,
];
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index ba3afe2..a460db8 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -1021,6 +1021,12 @@ pub fn set_runs(original: &[u8], runs: &[Run]) -> Option<Vec<u8>> {
} else {
without_field(&p, 4)?
};
+ // A block quote line, or not.
+ p = if para.quote {
+ set_varint_field(&p, 8, 1)?
+ } else {
+ without_field(&p, 8)?
+ };
// Where a numbered list starts, on its line only, as Notes keeps it.
p = match para.start {
Some(n) if para.style == Some(102) && n != 1 => set_varint_field(&p, 7, n)?,
@@ -1782,6 +1788,10 @@ pub struct Run {
/// 5 blue. Measured on a note coloured on a phone.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub emphasis: Option<u64>,
+ /// A block quote line, paragraph field 8 (Format › Block Quote; measured on a note quoted
+ /// on a phone: 1 on every quoted line).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub quote: bool,
}
/// Every run of a note document, in order. Empty for anything that is not one.
@@ -1842,6 +1852,7 @@ fn parse_paragraph(bytes: &[u8], run: &mut Run) -> Option<()> {
(1, WIRE_VARINT) => run.style = Some(reader.varint()?),
(4, WIRE_VARINT) => run.indent = reader.varint()?,
(7, WIRE_VARINT) => run.start = Some(reader.varint()?).filter(|&n| n != 1),
+ (8, WIRE_VARINT) => run.quote = reader.varint()? != 0,
(5, WIRE_LEN) => {
let n = usize::try_from(reader.varint()?).ok()?;
let mut item = Reader::new(reader.take(n)?);
diff --git a/probe/examples/note_unread_fields.rs b/probe/examples/note_unread_fields.rs
new file mode 100644
index 0000000..c732796
--- /dev/null
+++ b/probe/examples/note_unread_fields.rs
@@ -0,0 +1,136 @@
+//! Read-only: the values of the formatting fields Quince does not read yet (run field 13,
+//! paragraph fields 2, 3, 8, 9), with the live notes (not deleted) that hold each — to know
+//! which change how a note looks. Prints titles (first 30 chars) and values only.
+use anyhow::{anyhow, Result};
+use std::collections::BTreeMap;
+
+fn varint(b: &[u8], mut at: usize) -> Option<(u64, usize)> {
+ let mut v = 0u64;
+ let mut s = 0;
+ loop {
+ let x = *b.get(at)?;
+ at += 1;
+ v |= u64::from(x & 0x7f) << s;
+ s += 7;
+ if x < 0x80 {
+ return Some((v, at));
+ }
+ }
+}
+
+/// Each field's number, its bytes when length-delimited, and its value when a varint.
+fn fields(b: &[u8]) -> Vec<(u64, Option<&[u8]>, u64)> {
+ let mut out = Vec::new();
+ let mut at = 0;
+ while at < b.len() {
+ let Some((key, n)) = varint(b, at) else { break };
+ at = n;
+ match key & 7 {
+ 0 => {
+ let Some((v, n)) = varint(b, at) else { break };
+ at = n;
+ out.push((key >> 3, None, v));
+ }
+ 2 => {
+ let Some((len, n)) = varint(b, at) else { break };
+ let end = n + len as usize;
+ if end > b.len() {
+ break;
+ }
+ out.push((key >> 3, Some(&b[n..end]), 0));
+ at = end;
+ }
+ 5 => {
+ at += 4;
+ out.push((key >> 3, None, 0));
+ }
+ 1 => {
+ at += 8;
+ out.push((key >> 3, None, 0));
+ }
+ _ => break,
+ }
+ }
+ out
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());
+ let walk = zc.all_records("Notes", None).await?;
+ let mut samples: BTreeMap<String, BTreeMap<String, u32>> = BTreeMap::new();
+ use base64::Engine;
+ for r in walk.records.iter().filter(|r| r["recordType"] == "Note") {
+ let gone = r["fields"]["Deleted"]["value"].as_i64() == Some(1)
+ || r["fields"]["MarkedForDeletion"]["value"].as_i64() == Some(1);
+ if gone {
+ continue;
+ }
+ let Some(v) = r["fields"]["TextDataEncrypted"]["value"].as_str() else {
+ continue;
+ };
+ let Ok(raw) = base64::engine::general_purpose::STANDARD.decode(v) else {
+ continue;
+ };
+ let title: String = quince_icloud::ckdocument::text_from_base64(v)
+ .unwrap_or_default()
+ .lines()
+ .next()
+ .unwrap_or("")
+ .chars()
+ .take(30)
+ .collect();
+ let mut note = |key: String, value: String| {
+ *samples
+ .entry(key)
+ .or_default()
+ .entry(format!("{value} in {title:?}"))
+ .or_insert(0) += 1;
+ };
+ for run in quince_icloud::ckdocument::debug_attribute_runs(&raw) {
+ for (f, body, value) in fields(&run) {
+ if f == 13 {
+ let shape = body.map_or(format!("varint {value}"), |b| {
+ format!(
+ "{} bytes, inner fields {:?}",
+ b.len(),
+ fields(b).iter().map(|x| x.0).collect::<Vec<_>>()
+ )
+ });
+ note("run.13".into(), shape);
+ }
+ if f == 2 {
+ for (pf, pbody, pvalue) in fields(body.unwrap_or_default()) {
+ if matches!(pf, 2 | 3 | 8 | 9) {
+ let shape = pbody.map_or(format!("varint {pvalue}"), |b| {
+ format!(
+ "{} bytes, inner fields {:?}",
+ b.len(),
+ fields(b).iter().map(|x| x.0).collect::<Vec<_>>()
+ )
+ });
+ note(format!("para.{pf}"), shape);
+ }
+ }
+ }
+ }
+ }
+ }
+ for (k, vals) in samples {
+ println!("{k}:");
+ for (v, n) in vals.iter().take(12) {
+ println!(" {n:>4} × {v}");
+ }
+ }
+ Ok(())
+}
diff --git a/probe/examples/notes_quote_live.rs b/probe/examples/notes_quote_live.rs
new file mode 100644
index 0000000..a11b53c
--- /dev/null
+++ b/probe/examples/notes_quote_live.rs
@@ -0,0 +1,131 @@
+//! Live, throwaway note only: Block Quote as the editor saves it — two quoted lines between
+//! plain ones — read back from Apple as Apple stores a quote (paragraph field 8), then taken
+//! off one line, then the note moved to Recently Deleted. Prints the record name to delete.
+use anyhow::{anyhow, Result};
+use quince_icloud::ckdocument::{runs_from_base64, Run};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());
+ let first = "Quince mount test quote\nplain";
+ let guid =
+ quince_icloud::notes::create_cloudkit(&http, &root, p.clone(), None, first, None).await?;
+ let mut note = quince_core::notes::Note {
+ guid: guid.clone(),
+ folder_guid: None,
+ title: "Quince mount test quote".into(),
+ snippet: None,
+ body: None,
+ locked: false,
+ pinned: false,
+ created_at: None,
+ modified_at: None,
+ editable: true,
+ etag: None,
+ runs: None,
+ };
+ let plain = |n: u64| Run {
+ length: n,
+ ..Run::default()
+ };
+ let quoted = |n: u64| Run {
+ length: n,
+ quote: true,
+ ..Run::default()
+ };
+ // "Quince mount test quote\n" (24) "Said once\n" (10, quoted) "and again\n" (10, quoted) "after" (5)
+ let text = "Quince mount test quote\nSaid once\nand again\nafter";
+ let runs = vec![
+ Run {
+ style: Some(0),
+ ..plain(24)
+ },
+ quoted(10),
+ quoted(10),
+ plain(5),
+ ];
+ let quotes = |r: &serde_json::Value| -> Vec<(u64, bool)> {
+ runs_from_base64(
+ r["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or(""),
+ )
+ .iter()
+ .map(|x| (x.length, x.quote))
+ .collect()
+ };
+ let saved = quince_icloud::notes::edit_rich_cloudkit_from(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ Some(first),
+ text,
+ Some(&runs),
+ None,
+ )
+ .await?;
+ let back = zc
+ .lookup_record("Notes", &guid)
+ .await?
+ .ok_or_else(|| anyhow!("gone"))?;
+ let got = quotes(&back);
+ let quoted_len: u64 = got.iter().filter(|(_, q)| *q).map(|(n, _)| n).sum();
+ println!(
+ "{} saved: quoted {} of the 20 quoted units, runs {got:?}",
+ if saved == text && quoted_len == 20 {
+ "PASS"
+ } else {
+ "FAIL"
+ },
+ quoted_len
+ );
+ // Off the second line, as Command-' on it would.
+ note.etag = back["recordChangeTag"].as_str().map(String::from);
+ let runs = vec![
+ Run {
+ style: Some(0),
+ ..plain(24)
+ },
+ quoted(10),
+ plain(10),
+ plain(5),
+ ];
+ quince_icloud::notes::edit_rich_cloudkit_from(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ Some(text),
+ text,
+ Some(&runs),
+ None,
+ )
+ .await?;
+ let back = zc
+ .lookup_record("Notes", &guid)
+ .await?
+ .ok_or_else(|| anyhow!("gone"))?;
+ let quoted_len: u64 = quotes(&back)
+ .iter()
+ .filter(|(_, q)| *q)
+ .map(|(n, _)| n)
+ .sum();
+ println!(
+ "{} taken off one line: quoted {quoted_len} (want 10)",
+ if quoted_len == 10 { "PASS" } else { "FAIL" }
+ );
+ note.etag = back["recordChangeTag"].as_str().map(String::from);
+ quince_icloud::notes::delete_cloudkit(&http, &root, p, &note).await?;
+ println!("RECORD {guid}");
+ Ok(())
+}
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 0a9c262..677a709 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -1,4 +1,4 @@
-import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { usePending } from "../lib/pending";
import { Notice } from "../components/Notice";
import { ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, Pin, PinOff, SquarePen, Trash2 } from "lucide-react";
@@ -42,8 +42,54 @@ const DEFAULT_FOLDER = "DefaultFolder-CloudKit";
* what was stored before it did. */
const wordsOnly = (text: string) => text.replace(/[\uFFFC\u2028]/g, " ").replace(/\s+/g, " ").trim();
+const FOLDERS_KEY = "quince.notes.foldersWidth";
+const clampFolders = (w: number) => Math.round(Math.max(160, Math.min(420, w)));
+function keptFoldersWidth(): number | null {
+ try {
+ const n = Number(window.localStorage.getItem(FOLDERS_KEY));
+ return n > 0 ? clampFolders(n) : null;
+ } catch {
+ return null;
+ }
+}
+function keepFoldersWidth(w: number) {
+ try {
+ window.localStorage.setItem(FOLDERS_KEY, String(w));
+ } catch {
+ /* a width not kept is only a width not kept */
+ }
+}
+/** The width that shows every folder's whole name: the widest row's name as it would run
+ * untruncated, with the row's icon, count and padding around it. */
+function fitFolders(aside: HTMLElement | null): number | null {
+ if (!aside) return null;
+ let widest = 0;
+ aside.querySelectorAll<HTMLElement>(".notes-folder").forEach((row) => {
+ const name = row.querySelector<HTMLElement>(".notes-folder-name");
+ if (!name) return;
+ const others = row.scrollWidth - name.clientWidth;
+ widest = Math.max(widest, others + name.scrollWidth);
+ });
+ if (!widest) return null;
+ const pad = parseFloat(getComputedStyle(aside).paddingLeft) + parseFloat(getComputedStyle(aside).paddingRight);
+ return clampFolders(widest + pad + 2);
+}
+
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.
+ const notesRef = useRef<HTMLDivElement | null>(null);
+ const foldersRef = useRef<HTMLElement | null>(null);
+ const [foldersWidth, setFoldersWidth] = useState<number | null>(keptFoldersWidth);
+
const [folders, setFolders] = useState<NoteFolder[]>([]);
+ const kept = useRef(foldersWidth !== null);
+ useLayoutEffect(() => {
+ if (kept.current) return;
+ const fit = fitFolders(foldersRef.current);
+ // Never narrower than the column was made, and never more than a third of a wide window.
+ if (fit) setFoldersWidth(Math.max(208, Math.min(fit, 320)));
+ }, [folders]);
const [folderMenu, setFolderMenu] = useState<{ folder: NoteFolder; x: number; y: number; alignRight: boolean } | null>(null);
const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
const [folder, setFolder] = useState<string>(ALL);
@@ -625,9 +671,45 @@ export function NotesView() {
const saveFailed = error !== null;
return (
- <div className={`notes${detail ? " is-detail" : ""}`}>
+ <div
+ className={`notes${detail ? " is-detail" : ""}`}
+ ref={notesRef}
+ style={foldersWidth ? ({ "--folders-w": `${foldersWidth}px` } as React.CSSProperties) : undefined}
+ >
<NotePicture />
- <aside className="notes-folders" aria-label="Note folders">
+ <div
+ className="notes-folders-edge"
+ role="separator"
+ aria-orientation="vertical"
+ aria-label="Folder column width"
+ title="Drag to resize. Double-click to fit the names."
+ onPointerDown={(e) => {
+ const box = notesRef.current?.getBoundingClientRect();
+ if (!box) return;
+ e.currentTarget.setPointerCapture(e.pointerId);
+ const move = (m: PointerEvent) => setFoldersWidth(clampFolders(m.clientX - box.left));
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ kept.current = true;
+ setFoldersWidth((w) => {
+ if (w) keepFoldersWidth(w);
+ return w;
+ });
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ }}
+ onDoubleClick={() => {
+ const w = fitFolders(foldersRef.current);
+ if (w) {
+ kept.current = true;
+ setFoldersWidth(w);
+ keepFoldersWidth(w);
+ }
+ }}
+ />
+ <aside className="notes-folders" aria-label="Note folders" ref={foldersRef}>
<p className="notes-side-heading">iCloud</p>
<button className="notes-folder" aria-current={folder === ALL} onClick={() => setFolder(ALL)}>
<FolderOpen className="notes-folder-glyph" size={16} strokeWidth={2} aria-hidden="true" />
@@ -675,7 +757,7 @@ export function NotesView() {
style={depth > 0 ? { paddingLeft: `${8 + depth * 16}px` } : undefined}
>
<Folder className="notes-folder-glyph" size={16} strokeWidth={2} aria-hidden="true" />
- <span className="notes-folder-name">{f.title}</span>
+ <span className="notes-folder-name" title={f.title}>{f.title}</span>
<span className="notes-folder-count">{counts.per.get(f.guid) || ""}</span>
</button>
{own && (
@@ -857,6 +939,7 @@ export function NotesView() {
onClose={() => setFormatAt(null)}
onStyle={(style) => editorRef.current?.setStyle(style)}
onMark={(mark) => editorRef.current?.toggleMark(mark)}
+ onQuote={() => editorRef.current?.toggleQuote()}
/>
)}
</>
diff --git a/src/screens/notes/FormatPanel.tsx b/src/screens/notes/FormatPanel.tsx
index 630d099..3230002 100644
--- a/src/screens/notes/FormatPanel.tsx
+++ b/src/screens/notes/FormatPanel.tsx
@@ -35,12 +35,14 @@ export function FormatPanel({
onClose,
onStyle,
onMark,
+ onQuote,
}: {
at: { x: number; y: number };
status: EditorStatus | null;
onClose: () => void;
onStyle: (style: number | null) => void;
onMark: (mark: "bold" | "italic" | "underline" | "strike") => void;
+ onQuote: () => void;
}) {
const box = useRef<HTMLDivElement | null>(null);
const [pos, setPos] = useState({ left: at.x, top: at.y });
@@ -118,6 +120,24 @@ export function FormatPanel({
</button>
))}
</div>
+ {/* Not a style but a setting on top of one, as Notes keeps it: a quoted heading or
+ list stays a heading or a list. */}
+ <div className="fp-styles fp-extra" role="group" aria-label="Block quote">
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={Boolean(status?.quote)}
+ className="fp-style fp-quote"
+ onClick={() => {
+ onQuote();
+ onClose();
+ }}
+ >
+ <span className="fp-check" aria-hidden="true">{status?.quote && <Check size={15} strokeWidth={2} />}</span>
+ <span className="fp-quote-bar" aria-hidden="true" />
+ <span>Block Quote</span>
+ </button>
+ </div>
</div>
</Portal>
);
diff --git a/src/screens/notes/Formatted.tsx b/src/screens/notes/Formatted.tsx
index 58b1ebd..ff454da 100644
--- a/src/screens/notes/Formatted.tsx
+++ b/src/screens/notes/Formatted.tsx
@@ -25,6 +25,8 @@ export type Run = {
emphasis?: number | null;
/** The attachment this run's character stands for — a table, a picture — by id. */
attachment?: string | null;
+ /** A block quote line (Format › Block Quote). */
+ quote?: boolean;
};
/** Apple's paragraph styles. */
@@ -164,7 +166,7 @@ export function FormattedBody({
const style = p.run?.style ?? STYLE.body;
number = style === STYLE.numbered ? (p.run?.start ?? number + 1) : 0;
const indent = { paddingInlineStart: `${(p.run?.indent ?? 0) * 1.5}em` };
- const at = { "data-start": p.start } as Record<string, number>;
+ const at = { "data-start": p.start, ...(p.run?.quote ? { "data-quote": "true" } : {}) } as Record<string, number | string>;
const content = p.spans.length ? p.spans.map((s, j) => <Inline key={j} span={s} />) : <br />;
if (style === STYLE.title) return <h2 key={i} className="nf-title" style={indent} {...at}>{content}</h2>;
if (style === STYLE.heading) return <h3 key={i} className="nf-heading" style={indent} {...at}>{content}</h3>;
diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsx
index 74562ba..6f8ddd9 100644
--- a/src/screens/notes/NoteEditor.tsx
+++ b/src/screens/notes/NoteEditor.tsx
@@ -277,9 +277,12 @@ export type EditorStatus = {
underline: boolean;
strike: boolean;
checklist: boolean;
+ quote: boolean;
};
export type EditorHandle = {
+ /** Block Quote on the lines the selection touches, or off. */
+ toggleQuote: () => void;
/** Set every line the selection touches to one of Notes' styles. */
setStyle: (style: number | null) => void;
/** Lines to checklist items, or — when they all are — back to plain lines. */
@@ -333,6 +336,17 @@ function restyle(style: number | null, tick?: (was: PMNode) => boolean | null):
};
}
+/** Block Quote on every line the selection touches, or — when they all are — off, as
+ * Format › Block Quote (Command-') does in Notes. */
+const toggleQuote: Command = (state, dispatch) => {
+ const lines = linesIn(state);
+ const on = !lines.every(({ node }) => node.attrs.quote);
+ const tr = state.tr;
+ for (const { node, pos } of lines) tr.setNodeMarkup(pos, undefined, { ...node.attrs, quote: on });
+ dispatch?.(tr.scrollIntoView());
+ return true;
+};
+
/** Indent or outdent the lines in a list, as Tab and Command-] do. */
function shift(by: 1 | -1, onlyLists: boolean): Command {
return (state, dispatch) => {
@@ -360,6 +374,10 @@ const enter: Command = (state, dispatch) => {
if (inList(state) && p.content.size === 0 && state.selection.empty) {
return restyle(null)(state, dispatch);
}
+ // Return on an empty quoted line ends the quote, as it ends a list.
+ if (p.attrs.quote && p.content.size === 0 && state.selection.empty) {
+ return toggleQuote(state, dispatch);
+ }
return splitBlockAs((node, atEnd) => {
const style = node.attrs.style as number | null;
if (LIST_STYLES.includes(style as number)) {
@@ -406,6 +424,7 @@ function statusOf(state: EditorState): EditorStatus {
underline: has("underline"),
strike: has("strike"),
checklist: p.attrs.style === STYLE.checklist,
+ quote: Boolean(p.attrs.quote),
};
}
@@ -461,6 +480,7 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
"Mod-b": toggleMark(schema.marks.bold),
"Mod-i": toggleMark(schema.marks.italic),
"Mod-u": toggleMark(schema.marks.underline),
+ "Mod-'": toggleQuote,
"Mod-]": shift(1, false),
"Mod-[": shift(-1, false),
Tab: tab,
@@ -596,6 +616,12 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(
toggleChecklistCmd(v.state, v.dispatch);
v.focus();
},
+ toggleQuote: () => {
+ const v = view.current;
+ if (!v) return;
+ toggleQuote(v.state, v.dispatch);
+ v.focus();
+ },
toggleMark: (mark) => {
const v = view.current;
if (!v) return;
diff --git a/src/screens/notes/rich.ts b/src/screens/notes/rich.ts
index 1c36974..5059e04 100644
--- a/src/screens/notes/rich.ts
+++ b/src/screens/notes/rich.ts
@@ -45,6 +45,8 @@ export const schema = new Schema({
checked: { default: null as boolean | null },
/** A numbered list's first number, when not 1. */
start: { default: null as number | null },
+ /** A block quote line. */
+ quote: { default: false },
},
parseDOM: [{ tag: "p" }],
toDOM: (node) => [
@@ -53,6 +55,7 @@ export const schema = new Schema({
class: "nf-p",
"data-style": node.attrs.style === null ? "none" : String(node.attrs.style),
...(node.attrs.checked ? { "data-checked": "true" } : {}),
+ ...(node.attrs.quote ? { "data-quote": "true" } : {}),
style: [
node.attrs.indent ? `--indent: ${node.attrs.indent}` : "",
// CSS sets a counter after counting the line, so this line shows the start.
@@ -176,6 +179,7 @@ export function toDoc(text: string, runs: Run[] | null): PMNode {
indent: own?.indent ?? 0,
checked: own?.style === STYLE.checklist ? Boolean(own.checked) : null,
start: own?.style === STYLE.numbered ? (own.start ?? null) : null,
+ quote: Boolean(own?.quote),
},
inline,
),
@@ -190,7 +194,7 @@ const same = (a: Run, b: Run) =>
a.style === b.style && a.indent === b.indent && a.checked === b.checked && a.bold === b.bold &&
a.italic === b.italic && a.underline === b.underline && a.strike === b.strike && a.link === b.link &&
(a.attachment ?? null) === (b.attachment ?? null) && (a.emphasis ?? null) === (b.emphasis ?? null) &&
- (a.start ?? null) === (b.start ?? null);
+ (a.start ?? null) === (b.start ?? null) && Boolean(a.quote) === Boolean(b.quote);
/** A document as Apple's text and runs. */
export function fromDoc(doc: PMNode): { text: string; runs: Run[] } {
@@ -209,6 +213,7 @@ export function fromDoc(doc: PMNode): { text: string; runs: Run[] } {
indent: para.attrs.indent as number,
checked: para.attrs.style === STYLE.checklist ? Boolean(para.attrs.checked) : null,
...(para.attrs.style === STYLE.numbered && para.attrs.start ? { start: para.attrs.start as number } : {}),
+ ...(para.attrs.quote ? { quote: true } : {}),
};
const base: Run = { ...plain(0), ...p };
para.forEach((child) => {
diff --git a/src/styles/notes.css b/src/styles/notes.css
index d7265c6..a9e58e5 100644
--- a/src/styles/notes.css
+++ b/src/styles/notes.css
@@ -6,7 +6,14 @@
flex: 1;
min-height: 0;
display: grid;
- grid-template-columns: 208px minmax(250px, 320px) minmax(0, 1fr);
+ grid-template-columns: var(--folders-w, 208px) minmax(250px, 320px) minmax(0, 1fr);
+ position: relative;
+}
+/* The folders' edge, dragged to make them wider or narrower, as on the Mac; a double-click
+ fits the longest name. Over the hairline, wider than it, so it is easy to catch. */
+.notes-folders-edge {
+ position: absolute; top: 0; bottom: 0; left: calc(var(--folders-w, 208px) - 4px); width: 8px;
+ cursor: col-resize; z-index: 2; touch-action: none;
}
/* ---- folders -------------------------------------------------------------------- */
@@ -455,3 +462,16 @@ textarea.note-title::placeholder { color: var(--text-3); }
.nf-picture-close { display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; border: 0;
background: color-mix(in srgb, var(--text) 9%, transparent); color: var(--text); cursor: pointer; flex: none; }
.nf-picture-close:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+/* A block quote, as Notes draws one: a grey bar down the left of every quoted line, one
+ unbroken bar down a run of them; a quoted list keeps its marks, inside the bar. */
+.note-rich .nf-p[data-quote="true"], .note-formatted [data-quote="true"] {
+ border-inline-start: 3px solid color-mix(in srgb, var(--text) 26%, transparent);
+}
+.note-rich .nf-p[data-quote="true"]:not([data-style="100"], [data-style="101"], [data-style="102"], [data-style="103"]),
+.note-formatted .nf-body[data-quote="true"] {
+ padding-inline-start: calc(11px + var(--indent, 0) * 1.5em);
+}
+.fp-extra { border-top: 1px solid var(--separator); margin-top: 6px; padding-top: 6px; }
+.fp-quote-bar { width: 3px; height: 16px; border-radius: 2px; margin: 0 6px 0 4px;
+ background: color-mix(in srgb, var(--text) 30%, transparent); }