Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Skykeep: new name and icon, per-app passes, desktop search, export, README
Yashwanth Kamireddic304b1897729
diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..1183dce--- /dev/null+++ b/.github/CODE_OF_CONDUCT.md@@ -0,0 +1,84 @@++# Contributor Covenant Code of Conduct++## Our Pledge++We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.++We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.++## Our Standards++Examples of behavior that contributes to a positive environment for our community include:++* Demonstrating empathy and kindness toward other people+* Being respectful of differing opinions, viewpoints, and experiences+* Giving and gracefully accepting constructive feedback+* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience+* Focusing on what is best not just for us as individuals, but for the overall community++Examples of unacceptable behavior include:++* The use of sexualized language or imagery, and sexual attention or advances of any kind+* Trolling, insulting or derogatory comments, and personal or political attacks+* Public or private harassment+* Publishing others' private information, such as a physical or email address, without their explicit permission+* Other conduct which could reasonably be considered inappropriate in a professional setting++## Enforcement Responsibilities++Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.++Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.++## Scope++This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.++## Enforcement++Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement by contacting the project maintainer, [@YashwanthKamireddi](https://github.com/YashwanthKamireddi), privately: through the contact details on his GitHub profile, or with GitHub's "Report content" option on the comment, issue or discussion concerned. All complaints will be reviewed and investigated promptly and fairly.++All community leaders are obligated to respect the privacy and security of the reporter of any incident.++## Enforcement Guidelines++Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:++### 1. Correction++**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.++**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.++### 2. Warning++**Community Impact**: A violation through a single incident or series of actions.++**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.++### 3. Temporary Ban++**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.++**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.++### 4. Permanent Ban++**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.++**Consequence**: A permanent ban from any sort of public interaction within the community.++## Attribution++This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].++Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].++For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].++[homepage]: https://www.contributor-covenant.org+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html+[Mozilla CoC]: https://github.com/mozilla/diversity+[FAQ]: https://www.contributor-covenant.org/faq+[translations]: https://www.contributor-covenant.org/translationsdiff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdnew file mode 100644index 0000000..7f7cbed--- /dev/null+++ b/.github/CONTRIBUTING.md@@ -0,0 +1,172 @@+# Contributing to Skykeep++Thank you for helping make Skykeep better. Whether it's a typo, a bug fix, a packaging recipe, a design idea or a new feature, it's welcome here.++By taking part, you agree to the [Code of Conduct](CODE_OF_CONDUCT.md). Contributions are licensed under the project's license, [GPL-3.0-only](../LICENSE).++**Contents:** [Ways to help](#ways-to-help) · [Set up](#set-up) · [Run it](#run-it) · [The checks](#the-checks) · [Code map](#code-map) · [Testing with iCloud](#testing-with-icloud) · [Ground rules](#ground-rules) · [UI and design](#ui-and-design) · [Commit style](#commit-style) · [Pull requests](#pull-requests)++## Ways to help++- **Good first issues:** [labelled here](https://github.com/YashwanthKamireddi/Skykeep/labels/good%20first%20issue), each sized for an afternoon.+- **Bugs:** reproduce an open issue, or confirm a fix on your distribution or desktop.+- **Packaging:** Nix, Fedora COPR, Debian, Snap, winget. Each one brings Skykeep to more people.+- **Desktop integration:** GNOME, KDE and Windows shell integration.+- **Design:** see [UI and design](#ui-and-design).+- **Docs:** clearer install steps, FAQ answers, screenshots made with test data.++For anything bigger than a small fix, please open an issue or a [Discussion](https://github.com/YashwanthKamireddi/Skykeep/discussions) first so we can agree on the approach before you invest the time.++## Set up++You need **Rust 1.85+** ([rustup](https://rustup.rs)), **Node.js 22** and the system libraries Tauri uses.++```sh+# Debian / Ubuntu+sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \+ librsvg2-dev libsecret-1-dev libheif-dev libfuse3-dev pkg-config++# Arch+sudo pacman -S --needed webkit2gtk-4.1 gtk3 libsecret libheif libayatana-appindicator \+ gstreamer gst-plugins-base-libs fuse3 rust nodejs npm pkgconf++# Fedora+sudo dnf install webkit2gtk4.1-devel gtk3-devel libayatana-appindicator-gtk3-devel \+ librsvg2-devel libsecret-devel libheif-devel fuse3-devel pkgconf-pkg-config+```++Then:++```sh+git clone https://github.com/YashwanthKamireddi/Skykeep.git+cd Skykeep+npm ci+npx playwright install chromium webkit # for the interface suites+```++On Windows, follow the [Tauri prerequisites](https://tauri.app/start/prerequisites/) and install libheif through vcpkg, exactly as [`.github/workflows/windows.yml`](workflows/windows.yml) does.++## Run it++```sh+./run.sh+```++builds the interface and the app and opens Skykeep. There's no dev server: the app always serves its own built bundle, the same way a release does.++## The checks++One command runs everything a change has to pass:++```sh+./check.sh+```++It runs, in order:++| Step | Command |+|---|---|+| Rust formatting | `cargo fmt --all -- --check` |+| Rust lints | `cargo clippy --workspace --all-targets -- -D warnings` |+| Rust tests | `cargo test --workspace` |+| TypeScript | `npx tsc --noEmit` |+| Model tests | `node --test .uiverify/*.test.mjs` |+| Frontend build | `npm run build` |+| Interface suites | `node .uiverify/<suite>.mjs`, against `npx vite preview --port 4173` |++The interface suites in [`.uiverify/`](../.uiverify) are Playwright scripts that drive the real built interface: screenshots, keyboard paths, accessibility (axe), narrow windows, other locales and time zones, and frame-by-frame motion checks (a list that flickers fails). Each runs in Chromium by default; Skykeep draws in WebKit on Linux, so many also run with `ENGINE=webkit`:++```sh+npx vite preview --port 4173 --strictPort &+node .uiverify/notes-compose.mjs+ENGINE=webkit node .uiverify/notes-table.mjs # WebKit (run .uiverify/webkit-libs.sh once on non-Ubuntu distros)+ENGINE=msedge node .uiverify/menus.mjs # Edge, on Windows (WebView2's engine)+```++When you change a screen, run its suites in both engines. When you add behaviour, add or extend a suite.++**A test must fail without its fix.** Before you call a bug fixed, check that the new test fails on the old code.++The Windows pipeline (the full test suite, every interface suite in Edge, the installers and an install-and-launch smoke test) runs from Actions → Windows build, and on every release.++## Code map++```text+crates/quince-auth/ Sign-in (Apple's SRP + two-factor), session, keyring, apple_only() allow-list+crates/quince-icloud/ Each iCloud service: CloudKit, Notes (topotext CRDT, tables), Reminders,+ Calendar, Contacts, Drive, Photos, push channel+crates/quince-core/ Local library (SQLite), sync, outbox, search, export+crates/quince-vfs/ iCloud Drive and Photos as folders (FUSE, Linux)+crates/quince-media/ Picture decoding and thumbnails (HEIC included)+src-tauri/src/ The app: windows, Tauri commands, alerts, tray, search provider, import+src/screens/ One screen per app, plus sign-in and Settings+src/components/ The shared design system+src/lib/ IPC, sync state, optimistic writes (outbox, pending), theming+probe/examples/ Live checks against a real iCloud account; never part of CI+packaging/ Arch, AUR, Flatpak, desktop entries, AppStream metadata+```++The crates keep the `quince-` prefix from the project's working name.++**Adding a field Apple sends**, roughly:+1. Parse it in the service module in `crates/quince-icloud`, with a unit test from a trimmed, anonymised sample.+2. Store it in `crates/quince-core` (add a migration in `schema.rs` if it needs a column).+3. Expose it through a command in `src-tauri/src` and its type in `src/lib/ipc.ts`.+4. Show it in the screen, and cover it in a `.uiverify` suite.+5. If it can be edited, write it through the outbox so it's instant, works offline, and rolls back with a reason if Apple refuses it.++## Testing with iCloud++- **Use a test Apple Account**, never your personal data, for anything that writes. Name test items clearly (for example "Skykeep test …") and clean them up afterwards.+- Live checks live in `probe/examples` and are run on purpose, for example:+ ```sh+ cargo run -p quince-probe --example notes_audit+ ```+ They ask whether the account and the local copy agree, right now, about real data.+- Features whose writes aren't proven on a real iPhone yet sit behind a constant that is `false` (for example `TABLE_CELL_WRITES`, `NOTE_ATTACH_WRITES`, `REMINDER_DETAIL_WRITES`). Don't turn one on in a pull request without evidence that the change appears correctly on an iPhone and a second device.++## Ground rules++- **Privacy is the product.** Never add a network host, telemetry, analytics, crash reporting or an update check. Every client is built by `apple_only()` (or `listed_only()` for calendar subscriptions), and `crates/quince-auth/tests/apple_only.rs` must keep passing.+- **No personal data** in code, tests, fixtures, logs or screenshots: no real names, emails, phone numbers, note contents, account IDs or tokens. A pre-commit secret scan is a good idea; CI-safe test vectors use `example.invalid`.+- **Instant everywhere.** Every write shows immediately and rolls back with a reason on failure. Never block a redraw on the network.+- **Never lose data.** Merges keep both sides; deletes go to Recently Deleted where Apple has one.+- **Copy is short, positive and true.** No "…" on labels, no rows that add nothing, and never imply Apple affiliation.+- **Localisation:** formats (week start, 12/24-hour time, dates) follow the system. Translations aren't planned yet, so please don't open pull requests adding them.++## UI and design++Designers are very welcome. Skykeep aims to feel like Apple's own apps: calm, familiar and quietly premium.++- **Start with a Discussion** in the Ideas category: a sketch, mockup or screenshot and the problem it solves. Agreeing on the direction first saves everyone time.+- **Use the design system** in `src/components` (Toast, Confirm, EmptyState, PaneTitle, RowMenu and the rest) rather than one-off styles. Styles live in `src/styles`.+- **Light and dark, always.** Honour Reduce Transparency and Increase Contrast.+- **Motion:** no animation on large layers (whole panes, viewers, sheets). WebKitGTK on some Wayland compositors flickers, so these open and close instantly. Small, local motion is fine if it passes the frame-sampling suites in WebKit.+- **Glass on chrome only.** Sidebars, toolbars, menus and sheets may be translucent; your content never is.+- **Keyboard first.** Follow the keys of Apple's matching app, with Ctrl for ⌘.+- **No fruit imagery** in icons or artwork.+- Include **before and after screenshots, light and dark**, in the pull request.++## Commit style++Short, plain-English subjects that start with the area changed, followed by what's now true:++```text+Notes: tables keep their rows after an empty version+Calendar: an event's time zone, set as Calendar sets one+Windows build: the launch check runs for a quick build too+```++- Area first (`Notes`, `Reminders`, `Calendar`, `Contacts`, `Drive`, `Photos`, `Sync`, `Interface`, `Windows build`, `Packaging`, `Docs`, …), then a colon.+- Describe the result, not the activity ("tables keep their rows", not "fix table bug").+- Use the body for the *why*, and for what you verified and how.+- One logical change per commit.++## Pull requests++1. Fork, branch from `main`, and keep the change focused.+2. Run `./check.sh` until it's green.+3. Fill in the pull request template: what, why, how it was tested, and screenshots for UI.+4. Expect a review within a few days. Small, well-tested pull requests are merged fastest.++Thank you for making Skykeep better.diff --git a/.github/FUNDING.yml b/.github/FUNDING.ymlnew file mode 100644index 0000000..e2c3124--- /dev/null+++ b/.github/FUNDING.yml@@ -0,0 +1,16 @@+# The "Sponsor" button on the repository page.+#+# To turn it on:+# 1. Get approved for GitHub Sponsors (github.com/sponsors → Get sponsored; see+# docs/github-setup.md for what it needs).+# 2. Remove the "#" in front of the "github:" line below.+# 3. Repository → Settings → General → Features → tick "Sponsorships".+#+# github: [YashwanthKamireddi]++# Other platforms, if ever wanted (uncomment and fill in one or more):+# ko_fi: your-ko-fi-name+# buy_me_a_coffee: your-bmc-name+# open_collective: skykeep+# liberapay: your-liberapay-name+# custom: ["https://example.com/donate"]diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 0000000..562f604--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,149 @@+name: Bug report+description: Something in Skykeep isn't working as it should.+labels: ["bug", "triage"]+body:+ - type: markdown+ attributes:+ value: |+ Thanks for taking the time to report this. A clear report gets fixed fastest.++ **Security problem?** Please don't file it here. Use [private vulnerability reporting](https://github.com/YashwanthKamireddi/Skykeep/security/advisories/new) instead.++ **Privacy first:** before attaching logs or screenshots, remove anything personal (names, email addresses, phone numbers, note contents). Never paste a password, a two-factor code, or the contents of `cookies.json`.++ - type: textarea+ id: what-happened+ attributes:+ label: What happened?+ description: What you did, what you expected, and what happened instead.+ placeholder: |+ 1. Open Reminders+ 2. Tick a repeating reminder+ 3. Expected the next one to appear; instead…+ validations:+ required: true++ - type: dropdown+ id: app+ attributes:+ label: Which app?+ multiple: true+ options:+ - Notes+ - Reminders+ - Calendar+ - Contacts+ - iCloud Drive+ - iCloud Drive folder (file manager)+ - Photos+ - Sign-in / account+ - Settings / export+ - Tray, notifications or quick capture+ - Installation / packaging+ - Other+ validations:+ required: true++ - type: dropdown+ id: sync+ attributes:+ label: Is your data affected?+ description: Helps us prioritise. Anything that loses or duplicates data is fixed first.+ options:+ - "No, it's a display or behaviour problem"+ - "A change didn't reach my iPhone (or didn't arrive from it)"+ - "Something was lost, duplicated or changed unexpectedly"+ validations:+ required: true++ - type: input+ id: version+ attributes:+ label: Skykeep version+ description: Shown in Settings → About. For a source build, also the commit (`git rev-parse --short HEAD`).+ placeholder: "0.1.0"+ validations:+ required: true++ - type: dropdown+ id: platform+ attributes:+ label: Platform+ options:+ - Linux+ - Windows (beta)+ validations:+ required: true++ - type: dropdown+ id: install+ attributes:+ label: How did you install it?+ options:+ - AUR+ - Flatpak+ - .deb+ - .rpm+ - AppImage+ - Windows .exe installer+ - Windows .msi+ - Built from source+ validations:+ required: true++ - type: input+ id: distro+ attributes:+ label: Distribution or Windows version+ placeholder: "Fedora 43, Ubuntu 26.04, Arch, Windows 11 24H2…"+ validations:+ required: true++ - type: input+ id: desktop+ attributes:+ label: Desktop and session (Linux)+ description: Your desktop environment or compositor, and Wayland or X11.+ placeholder: "GNOME 49 on Wayland, KDE Plasma 6.5 on X11, Hyprland…"++ - type: dropdown+ id: adp+ attributes:+ label: Advanced Data Protection+ description: On your iPhone, Settings → your name → iCloud → Advanced Data Protection.+ options:+ - "Off"+ - "On, with Access iCloud Data on the Web turned on"+ - "On, with Access iCloud Data on the Web turned off"+ - "Not sure"++ - type: textarea+ id: logs+ attributes:+ label: Logs+ description: |+ **Linux:** quit Skykeep from the tray, run it from a terminal so its messages are printed, reproduce the problem, then paste what's relevant:+ `skykeep 2>&1 | tee skykeep.log`+ (Flatpak: `flatpak run io.github.yashwanthkamireddi.Skykeep 2>&1 | tee skykeep.log`;+ AppImage: `./Skykeep_*.AppImage 2>&1 | tee skykeep.log`).++ **Windows:** release builds don't print to a console. Copy the exact text of any error Skykeep shows, or attach a screenshot of it below.++ Please look through the log and remove anything personal first.+ render: text++ - type: textarea+ id: screenshots+ attributes:+ label: Screenshots or a recording+ description: Optional, often very helpful. Use test data or blur anything personal.++ - type: checkboxes+ id: checks+ attributes:+ label: Before you submit+ options:+ - label: I searched the existing issues and this hasn't been reported.+ required: true+ - label: I removed personal information from the logs and screenshots.+ required: truediff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 0000000..5f6e0c7--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,11 @@+blank_issues_enabled: false+contact_links:+ - name: Questions and help+ url: https://github.com/YashwanthKamireddi/Skykeep/discussions/categories/q-a+ about: Ask how something works or get help with setup.+ - name: Ideas+ url: https://github.com/YashwanthKamireddi/Skykeep/discussions/categories/ideas+ about: Share and discuss ideas before they become feature requests.+ - name: Report a security vulnerability+ url: https://github.com/YashwanthKamireddi/Skykeep/security/advisories/new+ about: Please report security problems privately, never in a public issue.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 0000000..422250d--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,54 @@+name: Feature request+description: Suggest something Skykeep could do better or do next.+labels: ["enhancement"]+body:+ - type: markdown+ attributes:+ value: |+ Thanks for the idea. For open-ended brainstorming, [Discussions → Ideas](https://github.com/YashwanthKamireddi/Skykeep/discussions/categories/ideas) is a great place to start. Use this form when you have a concrete request.++ - type: dropdown+ id: app+ attributes:+ label: Which app?+ multiple: true+ options:+ - Notes+ - Reminders+ - Calendar+ - Contacts+ - iCloud Drive+ - Photos+ - Desktop integration (tray, notifications, search, files)+ - Packaging / a new platform+ - Everywhere+ validations:+ required: true++ - type: textarea+ id: problem+ attributes:+ label: What would you like to do?+ description: The task or moment where Skykeep falls short today. A real situation helps a lot.+ placeholder: "When I'm planning my week, I'd like to…"+ validations:+ required: true++ - type: textarea+ id: solution+ attributes:+ label: How could it work?+ description: Your idea for it. If Apple's own app on iPhone or Mac does this, describe how it behaves there.++ - type: textarea+ id: alternatives+ attributes:+ label: What do you do today instead?+ description: A workaround, another app, or icloud.com.++ - type: checkboxes+ id: contribute+ attributes:+ label: Contributing+ options:+ - label: I'd be interested in helping build this.diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdnew file mode 100644index 0000000..bbaf5b4--- /dev/null+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -0,0 +1,29 @@+<!-- Thanks for contributing to Skykeep. A few lines here make review quick. -->++## What this changes++<!-- One or two sentences. Link the issue it closes: "Closes #123". -->++## Why++<!-- The problem it solves, or the behaviour it brings closer to Apple's own app. -->++## How it was tested++<!-- What you ran and what you saw. For anything that touches iCloud, say whether it was checked+ against a real (test) account and an iPhone, and how. -->++- [ ] `./check.sh` passes (or: `cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`, `npx tsc --noEmit`, and the relevant `.uiverify` suites)+- [ ] New or changed behaviour has a test that fails without this change+- [ ] Interface changes: checked in light and dark, and in WebKit (`ENGINE=webkit`)++## Screenshots++<!-- For interface changes: before and after, light and dark. Use test data only. -->++## Checklist++- [ ] No personal data (real names, emails, notes, account IDs) in code, tests, fixtures or screenshots+- [ ] No new network host: everything still goes through `apple_only()` (or `listed_only()` for subscriptions)+- [ ] User-facing text is short, positive and true, and never implies Apple affiliation+- [ ] Commit messages follow the style in [CONTRIBUTING.md](CONTRIBUTING.md#commit-style)diff --git a/.github/SUPPORT.md b/.github/SUPPORT.mdnew file mode 100644index 0000000..86d63cd--- /dev/null+++ b/.github/SUPPORT.md@@ -0,0 +1,31 @@+# Getting help with Skykeep++Thanks for using Skykeep. Here's the quickest way to an answer.++## Start here++- **Read the [FAQ](../README.md#faq).** It covers sign-in, Advanced Data Protection, offline use, sync timing, and what's included.+- **Advanced Data Protection on?** Turn on **Access iCloud Data on the Web** on your iPhone: Settings → your name → iCloud → Access iCloud Data on the Web. Without it, Apple lets no app outside your devices read your iCloud data.+- **Can't stay signed in on Linux?** Make sure a Secret Service keyring is running (GNOME Keyring or KWallet) and `libsecret` is installed.++## Ask a question++Use **[Discussions → Q&A](https://github.com/YashwanthKamireddi/Skykeep/discussions/categories/q-a)** for how-to questions, setup help, and anything you're unsure about. Answers there help the next person too.++## Report a bug++Open a **[bug report](https://github.com/YashwanthKamireddi/Skykeep/issues/new?template=bug_report.yml)**. Include your version, platform, how you installed Skykeep, and logs (the form shows how to get them). Please remove anything personal first.++## Suggest a feature++Share it in **[Discussions → Ideas](https://github.com/YashwanthKamireddi/Skykeep/discussions/categories/ideas)**, or open a **[feature request](https://github.com/YashwanthKamireddi/Skykeep/issues/new?template=feature_request.yml)** if it's concrete.++## Security++Never post security problems publicly. Use **[private vulnerability reporting](https://github.com/YashwanthKamireddi/Skykeep/security/advisories/new)**; see [SECURITY.md](../SECURITY.md).++## A note on Apple support++Skykeep is an independent project and isn't affiliated with Apple, so Apple Support can't help with Skykeep itself. For problems with your Apple Account or iCloud in general, Apple Support is the right place.++Skykeep is maintained by one person in their own time. Every report is read, and a clear, kind report is the fastest way to a fix.diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 8d734ea..e90360f 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -35,7 +35,7 @@ jobs:- name: Build the packages# The build machine's paths are never written into the program.env:- RUSTFLAGS: --remap-path-prefix=${{ github.workspace }}=pomander+ RUSTFLAGS: --remap-path-prefix=${{ github.workspace }}=skykeeprun: npx tauri build- name: The .deb installs and its program startsrun: |@@ -51,7 +51,7 @@ jobs:cat SHA256SUMS-linux.txt- uses: actions/upload-artifact@v4with:- name: pomander-linux+ name: skykeep-linuxpath: |target/release/bundle/deb/*.debtarget/release/bundle/rpm/*.rpm@@ -79,4 +79,4 @@ jobs:run: |find dist -type f \( -name '*.deb' -o -name '*.rpm' -o -name '*.AppImage' -o -name '*.msi' -o -name '*-setup.exe' -o -name 'SHA256SUMS*' \) -print0 \| xargs -0 gh release create "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" \- --draft --verify-tag --title "Pomander ${GITHUB_REF_NAME#v}" --generate-notes+ --draft --verify-tag --title "Skykeep ${GITHUB_REF_NAME#v}" --generate-notesdiff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex d3a7c61..6f048d1 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -1,8 +1,8 @@-# Pomander for Windows, proven on Windows before anyone downloads it:+# Skykeep for Windows, proven on Windows before anyone downloads it:# 1. test — the whole test suite on a Windows machine, the real Credential Manager included;# ui — every interface suite in Edge (WebView2's engine), each screen photographed;# 2. build — the .msi and the per-user .exe installer, only if every test passed;-# 3. smoke — the .exe installed silently, Pomander launched, its window seen on screen, and a+# 3. smoke — the .exe installed silently, Skykeep launched, its window seen on screen, and a# screenshot kept, so an installer that cannot even start is never handed over.# Run by hand (Actions → Windows build → Run workflow) or by a release (release.yml); never on# every push.@@ -53,7 +53,9 @@ jobs:# The window's files must exist for the app crate to compile.- run: npm run build- name: Tests, on Windows- run: cargo test --workspace --no-fail-fast+ # The real tests: libraries, the app and test files. The probe examples are live tools for+ # Linux (one mounts a FUSE folder), not tests, and are not built here.+ run: cargo test --workspace --lib --bins --tests --no-fail-fast# Every interface suite in Microsoft Edge — the engine WebView2 is — with Windows' own fonts,# and every screen photographed light and dark, to be looked at.@@ -101,7 +103,7 @@ jobs:- uses: actions/upload-artifact@v4if: always()with:- name: pomander-ui-in-edge+ name: skykeep-ui-in-edgepath: shotsif-no-files-found: ignore@@ -136,7 +138,7 @@ jobs:- name: Build the installers# The build machine's paths are never written into the program.env:- RUSTFLAGS: --remap-path-prefix=${{ github.workspace }}=pomander+ RUSTFLAGS: --remap-path-prefix=${{ github.workspace }}=skykeeprun: npx tauri build- name: Checksumsshell: pwsh@@ -146,7 +148,7 @@ jobs:Set-Content target/release/bundle/SHA256SUMS-windows.txt- uses: actions/upload-artifact@v4with:- name: pomander-windows+ name: skykeep-windowspath: |target/release/bundle/msi/*.msitarget/release/bundle/nsis/*.exe@@ -162,42 +164,42 @@ jobs:steps:- uses: actions/download-artifact@v4with:- name: pomander-windows+ name: skykeep-windowspath: dist- name: Install, launch, and see the windowshell: pwshrun: |$setup = Get-ChildItem dist -Recurse -Filter *-setup.exe | Select-Object -First 1Start-Process $setup.FullName -ArgumentList "/S" -Wait- $exe = Get-ChildItem "$env:LOCALAPPDATA\Programs" -Recurse -Filter pomander.exe | Select-Object -First 1- if (-not $exe) { $exe = Get-ChildItem "$env:LOCALAPPDATA" -Recurse -Filter pomander.exe -ErrorAction SilentlyContinue | Select-Object -First 1 }- if (-not $exe) { throw "Pomander was not installed" }+ $exe = Get-ChildItem "$env:LOCALAPPDATA\Programs" -Recurse -Filter skykeep.exe | Select-Object -First 1+ if (-not $exe) { $exe = Get-ChildItem "$env:LOCALAPPDATA" -Recurse -Filter skykeep.exe -ErrorAction SilentlyContinue | Select-Object -First 1 }+ if (-not $exe) { throw "Skykeep was not installed" }"installed at $($exe.FullName)"# Alerts are sent as the app the Start menu knows; without that ID on its entry they# came from "Windows PowerShell".- $entry = Get-StartApps | Where-Object { $_.Name -eq "Pomander" } | Select-Object -First 1- if (-not $entry -or $entry.AppID -ne "io.github.yashwanthkamireddi.Pomander") { throw "Start menu entry has app ID '$($entry.AppID)', not io.github.yashwanthkamireddi.Pomander" }+ $entry = Get-StartApps | Where-Object { $_.Name -eq "Skykeep" } | Select-Object -First 1+ if (-not $entry -or $entry.AppID -ne "io.github.yashwanthkamireddi.Skykeep") { throw "Start menu entry has app ID '$($entry.AppID)', not io.github.yashwanthkamireddi.Skykeep" }"start menu app ID: $($entry.AppID)"$p = Start-Process $exe.FullName -PassThru$title = ""for ($i = 0; $i -lt 30 -and -not $title; $i++) {Start-Sleep -Seconds 2- if ($p.HasExited) { throw "Pomander exited on start (code $($p.ExitCode))" }+ if ($p.HasExited) { throw "Skykeep exited on start (code $($p.ExitCode))" }$p.Refresh(); $title = $p.MainWindowTitle}- if ($title -ne "Pomander") { throw "no Pomander window after 60 s (title: '$title')" }+ if ($title -ne "Skykeep") { throw "no Skykeep window after 60 s (title: '$title')" }"window up: $title"Start-Sleep -Seconds 6Add-Type -AssemblyName System.Windows.Forms, System.Drawing$b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds$bmp = New-Object System.Drawing.Bitmap $b.Width, $b.Height[System.Drawing.Graphics]::FromImage($bmp).CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size)- $bmp.Save("$PWD\pomander-on-windows.png")- if ($p.HasExited) { throw "Pomander closed by itself" }+ $bmp.Save("$PWD\skykeep-on-windows.png")+ if ($p.HasExited) { throw "Skykeep closed by itself" }Stop-Process -Id $p.Id- uses: actions/upload-artifact@v4if: always()with:- name: pomander-on-windows- path: pomander-on-windows.png+ name: skykeep-on-windows+ path: skykeep-on-windows.pngif-no-files-found: ignorediff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjsindex 6714e86..804ba43 100644--- a/.uiverify/a11y.mjs+++ b/.uiverify/a11y.mjs@@ -97,7 +97,7 @@ const screens = [kind: "FOLDER", size: null, childCount: 3, createdAt: 1785000000,modifiedAt: 1788000000, etag: null },], act: async (p) => {- await p.click('.nav-item:has-text("iCloud Drive")');+ await p.click('.nav-item:has-text("Drive")');await p.waitForSelector(".drive-row-hit");await p.hover(".drive-row.is-folder");await p.click('.drive-row.is-folder .drive-action[aria-label^="Actions for"]');diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjsindex 650879e..7ab7fe5 100644--- a/.uiverify/assert.mjs+++ b/.uiverify/assert.mjs@@ -98,7 +98,7 @@ console.log("nav items :", JSON.stringify(names));console.log("page errors :", errs.length ? errs : "none");const collapsed =JSON.stringify(names) ===- JSON.stringify(["Reminders", "Notes", "iCloud Drive", "Photos", "Calendar", "Contacts"]);+ JSON.stringify(["Reminders", "Notes", "Drive", "Photos", "Calendar", "Contacts"]);const selectsBuilt = selected === "Reminders";console.log(collapsed ? "PASS the sidebar holds only what works, most used first" : `FAIL the sidebar holds ${JSON.stringify(names)}`);console.log(selectsBuilt ? "PASS opens on the first screen" : `FAIL opened on ${selected}`);@@ -340,7 +340,7 @@ let failures = 0;{const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });- await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+ await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForSelector(".drive-rows");await page.getByRole("button", { name: "New Folder" }).click();await page.keyboard.type("downloads");@@ -365,7 +365,7 @@ let failures = 0;{const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });- await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+ await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForSelector(".drive-row-hit");const folderRow = page.locator(".drive-row.is-folder .drive-row-hit").first();@@ -786,7 +786,7 @@ let failures = 0;["Calendar", ".cal-grid, .cal-month, .empty-state"],["Notes", ".empty-state, .notes-empty"],["Contacts", ".empty-state, .contact-empty"],- ["iCloud Drive", ".drive-rows"],+ ["Drive", ".drive-rows"],]) {await page.getByRole("button", { name: screen, exact: true }).click();await page.waitForTimeout(350);diff --git a/.uiverify/calendar-collections.mjs b/.uiverify/calendar-collections.mjsindex 9867a02..b5c5a93 100644--- a/.uiverify/calendar-collections.mjs+++ b/.uiverify/calendar-collections.mjs@@ -15,13 +15,15 @@ let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };const names = () => page.locator(".cx-cal-name").allInnerTexts();-await page.getByRole("button", { name: "New Calendar" }).click();+await page.getByRole("button", { name: "Add Calendar" }).click();+await page.getByRole("menuitem", { name: "New Calendar" }).click();await page.getByLabel("New calendar name").fill("Trips");await page.keyboard.press("Enter");await page.waitForTimeout(400);ok((await names()).includes("Trips"), "+ makes a calendar, named as typed");-await page.getByRole("button", { name: "New Calendar" }).click();+await page.getByRole("button", { name: "Add Calendar" }).click();+await page.getByRole("menuitem", { name: "New Calendar" }).click();await page.getByLabel("New calendar name").fill("Work");await page.keyboard.press("Enter");await page.waitForTimeout(400);@@ -38,7 +40,7 @@ ok((await names()).includes("Office") && !(await names()).includes("Work"), "Renawait page.locator(".cx-cal", { hasText: "Office" }).click({ button: "right" });await page.getByRole("menuitem", { name: "Colour" }).hover();-await page.getByRole("menuitem", { name: "Brown" }).click();+await page.getByRole("menuitemcheckbox", { name: "Brown" }).click();await page.waitForTimeout(300);const writes = await page.evaluate(() => window.__calWrites);ok(writes.some((w) => w.update?.colour === "#a2845e"), `Colour sets Apple's brown ${JSON.stringify(writes.at(-1))}`);diff --git a/.uiverify/calendar-edits.mjs b/.uiverify/calendar-edits.mjsnew file mode 100644index 0000000..cd8dc41--- /dev/null+++ b/.uiverify/calendar-edits.mjs@@ -0,0 +1,120 @@+// Working with events as in Calendar: the picked event opens on Return, deletes on Delete+// (asked first), duplicates on Ctrl+D, copies and pastes onto another day, moves calendar from+// its menu, drags to another day in Month, stretches from its top edge, and opens its place in+// Maps. A calendar's default alert goes on each new event made in it.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });+const page = await ctx.newPage();+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.keyboard.press("Control+2");+await page.waitForTimeout(300);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const saves = () => page.evaluate(() => window.__eventSaves ?? []);+const local = (n, h, m = 0) => page.evaluate(([n, h, m]) => { const d = new Date(); d.setHours(h, m, 0, 0); d.setDate(d.getDate() + n); return d.getTime() / 1000; }, [n, h, m]);+const fullDate = (n) => page.evaluate((n) => { const d = new Date(); d.setDate(d.getDate() + n); return new Intl.DateTimeFormat(undefined, { dateStyle: "full" }).format(d); }, n);+const ten = await local(0, 10);++// Picked, then Return opens it again.+const review = page.locator(".cx-block", { hasText: "Design review" });+await review.click();+await page.waitForTimeout(200);+const pop = page.getByRole("dialog", { name: "Design review" });+ok(await pop.isVisible(), "a click opens the event");+ok((await pop.getByRole("link", { name: "Open in Maps" }).getAttribute("href")) === "geo:0,0?q=Studio", "its place has Open in Maps");+await page.keyboard.press("Escape");+ok(await pop.count() === 0 && await review.evaluate((el) => el.classList.contains("is-picked")), "Escape closes it, and it stays picked");+await page.keyboard.press("Enter");+await page.waitForTimeout(200);+ok(await pop.isVisible(), "Return opens the picked event");+await page.keyboard.press("Escape");++// Ctrl+D: a copy at the same time, in the same calendar.+await page.keyboard.press("Control+d");+await page.waitForTimeout(300);+let s = await saves();+ok(s.length === 1 && s[0].guid === null && s[0].title === "Design review" && s[0].startsAt === ten && s[0].calendarGuid === "work",+ `Ctrl+D duplicates it ${JSON.stringify(s[0])}`);++// Ctrl+C, then Ctrl+V on another day: the copy at its own time of day.+await page.keyboard.press("Control+c");+await page.keyboard.press("Control+3");+await page.waitForTimeout(300);+await page.getByRole("gridcell").filter({ has: page.getByRole("button", { name: new RegExp(`^${await fullDate(2)}`) }) }).locator(".cx-day-hit").click();+await page.keyboard.press("Control+v");+await page.waitForTimeout(300);+s = await saves();+const two = await local(2, 10);+ok(s.length === 2 && s[1].guid === null && s[1].startsAt === two && s[1].endsAt === two + 3600, `Ctrl+V pastes it on the selected day ${JSON.stringify(s[1])}`);++// Month: dragged from tomorrow to three days on, the clock time kept.+const sprint = page.locator(".cx-item", { hasText: "Sprint planning" });+const target = page.getByRole("gridcell").filter({ has: page.getByRole("button", { name: new RegExp(`^${await fullDate(3)}`) }) });+const from = await sprint.boundingBox();+const to = await target.boundingBox();+await page.mouse.move(from.x + 20, from.y + from.height / 2);+await page.mouse.down();+await page.mouse.move(from.x + 40, from.y + from.height / 2 + 4, { steps: 3 });+await page.mouse.move(to.x + to.width / 2, to.y + to.height - 12, { steps: 8 });+ok(await target.evaluate((el) => el.classList.contains("is-drop")), "the day under the pointer is marked");+await page.mouse.up();+await page.waitForTimeout(300);+s = await saves();+const sprintAt = await local(1, 11);+ok(s.length === 3 && s[2].guid === "e3" && s[2].startsAt === sprintAt + 2 * 86400 && s[2].endsAt === sprintAt + 2 * 86400 + 3600,+ `dragged two days on ${JSON.stringify(s[2] && { g: s[2].guid, d: (s[2].startsAt - sprintAt) / 3600 })}`);+ok(await page.getByRole("dialog").count() === 0, "a drag does not open the event");++// Its menu moves it to another calendar.+await page.locator(".cx-item", { hasText: "Design review" }).click({ button: "right" });+await page.getByRole("menuitem", { name: "Calendar" }).hover();+await page.getByRole("menuitemcheckbox", { name: "Personal" }).click();+await page.waitForTimeout(300);+s = await saves();+ok(s.at(-1)?.guid === "e1" && s.at(-1)?.calendarGuid === "personal", "Calendar ▸ Personal moves it");++// Delete, from the keyboard, asks first.+await page.locator(".cx-item", { hasText: "Dentist" }).click();+await page.waitForTimeout(200);+await page.keyboard.press("Escape");+await page.keyboard.press("Delete");+const ask = page.getByRole("alertdialog");+ok(/Delete .Dentist/.test(await ask.innerText()), "Delete asks first");+await ask.getByRole("button", { name: "Cancel" }).click();+ok((await page.evaluate(() => window.__eventDeletes ?? [])).length === 0, "Cancel keeps it");+await page.keyboard.press("Delete");+await page.getByRole("alertdialog").getByRole("button", { name: "Delete" }).click();+await page.waitForTimeout(300);+ok((await page.evaluate(() => window.__eventDeletes ?? [])).some((d) => d.guid === "e2"), "confirmed, it is deleted");++// Week: the top edge moves the start and leaves the end.+await page.keyboard.press("Control+2");+await page.waitForTimeout(300);+await review.evaluate((el) => el.scrollIntoView({ block: "center" }));+const block = await review.boundingBox();+await page.mouse.move(block.x + block.width / 2, block.y + 2);+await page.mouse.down();+await page.mouse.move(block.x + block.width / 2, block.y + 2 - 48, { steps: 6 });+await page.mouse.up();+await page.waitForTimeout(300);+s = await saves();+ok(s.at(-1)?.guid === "e1" && s.at(-1)?.startsAt === ten - 3600 && s.at(-1)?.endsAt === ten + 3600,+ `the top edge starts it an hour earlier ${JSON.stringify(s.at(-1) && [(s.at(-1).startsAt - ten) / 60, (s.at(-1).endsAt - ten) / 60])}`);++// A default alert for Home goes on each new event made there.+await page.getByRole("complementary", { name: "Calendars" }).getByText("Home").click({ button: "right" });+await page.getByRole("menuitem", { name: "Default Alert", exact: true }).hover();+await page.getByRole("menuitemcheckbox", { name: "15 minutes before" }).click();+await page.getByRole("button", { name: "New event" }).click();+await page.keyboard.type("Call the bank tomorrow 3pm");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+s = await saves();+ok(JSON.stringify(s.at(-1)?.alerts) === "[15]", `a new event takes Home's default alert ${JSON.stringify(s.at(-1)?.alerts)}`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/calendar-goto.mjs b/.uiverify/calendar-goto.mjsindex 152f773..2ff1e4d 100644--- a/.uiverify/calendar-goto.mjs+++ b/.uiverify/calendar-goto.mjs@@ -1,4 +1,4 @@-// Go to Date…, as in Calendar's View menu: Shift-Ctrl-T opens a date field, Return goes there,+// Go to Date, as in Calendar's View menu: Shift-Ctrl-T opens a date field, Return goes there,// Escape closes it without moving.import { engine } from "./engine.mjs";import { SERVICES, installStub, openScreen } from "./stub.mjs";diff --git a/.uiverify/calendar-instant.mjs b/.uiverify/calendar-instant.mjsindex 5748cd1..6744052 100644--- a/.uiverify/calendar-instant.mjs+++ b/.uiverify/calendar-instant.mjs@@ -61,7 +61,8 @@ const linked = await page.evaluate(() => window.__saves.at(-1)?.draft?.url);ok(linked === "https://example.com/new", `a URL typed into the event is saved [${linked}]`);// A new event is on the calendar the moment it is saved, before Apple has named it.-await page.getByRole("button", { name: "New event" }).click();+await page.evaluate(() => document.activeElement?.blur());+await page.keyboard.press("Control+n");await page.waitForTimeout(250);await page.locator('input[placeholder="New Event"]').first().fill("Coffee with Ana");await page.locator('input[placeholder="New Event"]').first().press("Enter");@@ -75,6 +76,7 @@ await page.locator(".cx-block", { hasText: "Design review" }).first().click();await page.waitForTimeout(250);await page.evaluate(() => document.activeElement?.blur());await page.keyboard.press("Delete");+await page.getByRole("alertdialog").getByRole("button", { name: "Delete" }).click();await page.waitForTimeout(150);ok(await page.locator(".cx-block", { hasText: "Design review" }).count() === 0, "a deleted event leaves at once");// A reminder on the calendar ticks there, at once, as in Calendar.diff --git a/.uiverify/calendar-model.test.mjs b/.uiverify/calendar-model.test.mjsindex 0670245..634084c 100644--- a/.uiverify/calendar-model.test.mjs+++ b/.uiverify/calendar-model.test.mjs@@ -141,3 +141,15 @@ test("a week starts where the region starts it, and a 24-hour clock keeps its :0assert.notEqual(hourLabel(12, false), "Noon");assert.equal(hourLabel(12, true), "Noon");});++test("week numbers: ISO where weeks start on Monday, the week of 1 January elsewhere", async () => {+ const { weekNumber } = await import("../src/screens/calendar/model.ts");+ // ISO: 29 Dec 2025 (Mon) is week 1 of 2026; 28 Dec 2026 is week 53; 19 Oct 2026 is 43.+ assert.equal(weekNumber(new Date(2025, 11, 29), 1), 1);+ assert.equal(weekNumber(new Date(2026, 9, 19), 1), 43);+ assert.equal(weekNumber(new Date(2026, 11, 28), 1), 53);+ // US: the week of Sun 28 Dec 2025 holds 1 Jan, so is week 1; 18 Oct 2026 is week 43.+ assert.equal(weekNumber(new Date(2025, 11, 28), 0), 1);+ assert.equal(weekNumber(new Date(2026, 9, 18), 0), 43);+ assert.equal(weekNumber(new Date(2026, 11, 27), 0), 1);+});diff --git a/.uiverify/calendar-quick.mjs b/.uiverify/calendar-quick.mjsnew file mode 100644index 0000000..89f14c4--- /dev/null+++ b/.uiverify/calendar-quick.mjs@@ -0,0 +1,65 @@+// Quick Event under the +: a line read as it is typed, shown as the event it will make, and+// made on Return — or opened in full with Details.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });+const page = await ctx.newPage();+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.waitForTimeout(300);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const saves = () => page.evaluate(() => window.__eventSaves ?? []);+const local = (dayOffset, h, m = 0) => page.evaluate(([n, h, m]) => {+ const d = new Date(); d.setHours(h, m, 0, 0); d.setDate(d.getDate() + n); return d.getTime() / 1000;+}, [dayOffset, h, m]);++await page.getByRole("button", { name: "New event" }).click();+const dialog = page.getByRole("dialog", { name: "Quick Event" });+ok(await dialog.isVisible(), "the + opens Quick Event");+ok(await dialog.getByRole("button", { name: "Add" }).isDisabled(), "Add waits for something to add");+await page.keyboard.type("Lunch with Asha tomorrow 1pm at Olive");+const preview = dialog.locator(".cx-quick-preview");+const text = (await preview.innerText()).replace(/\s+/g, " ");+ok(/Lunch with Asha/.test(text) && /1 ?PM.*2 ?PM|13:00.*14:00/i.test(text) && /Olive/.test(text) && /Home/.test(text),+ `the preview shows the title, time, place and calendar [${text}]`);+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+let sent = await saves();+const tomorrow1 = await local(1, 13);+ok(sent.length === 1 && sent[0].guid === null && sent[0].title === "Lunch with Asha" && sent[0].startsAt === tomorrow1 &&+ sent[0].endsAt === tomorrow1 + 3600 && sent[0].location === "Olive" && sent[0].calendarGuid === "home" && !sent[0].allDay,+ `Return saves it as read ${JSON.stringify(sent[0])}`);+ok(await dialog.count() === 0, "and the field is put away");++// A repeat: Gym every Monday.+await page.getByRole("button", { name: "New event" }).click();+await page.keyboard.type("Gym every Monday 7am");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+sent = await saves();+const gym = sent[1];+const gymDay = gym && new Date(gym.startsAt * 1000);+ok(gym && gym.title === "Gym" && gymDay.getDay() === 1 && gymDay.getHours() === 7 && gym.repeatChanged === true &&+ gym.repeat?.freq === "weekly", `a weekly repeat is saved with it ${JSON.stringify(gym)}`);++// Details opens the whole event, filled in, nothing saved yet.+await page.getByRole("button", { name: "New event" }).click();+await page.keyboard.type("Flight Fri 6:30am–9");+await dialog.getByRole("button", { name: /Details/ }).click();+await page.waitForTimeout(300);+const pop = page.getByRole("dialog", { name: "New event" });+ok(await pop.isVisible() && (await pop.getByLabel("Title").inputValue()) === "Flight", "Details opens the event, its title filled in");+ok((await saves()).length === 2, "nothing is saved until it is added");+await page.keyboard.press("Escape");++// Escape closes Quick Event without adding.+await page.getByRole("button", { name: "New event" }).click();+await page.keyboard.type("Something");+await page.keyboard.press("Escape");+ok(await dialog.count() === 0 && (await saves()).length === 2, "Escape closes it, nothing added");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/calendar-quick.test.mjs b/.uiverify/calendar-quick.test.mjsnew file mode 100644index 0000000..66e4bf4--- /dev/null+++ b/.uiverify/calendar-quick.test.mjs@@ -0,0 +1,82 @@+// Quick Event: a line read into a title, a day, a time, a length, a repeat and a place.+import { test } from "node:test";+import assert from "node:assert/strict";+import { parseQuick } from "../src/screens/calendar/quick.ts";++// Wednesday 21 October 2026, 10:15 in the morning.+const now = new Date(2026, 9, 21, 10, 15);+const at = (y, m, d, h = 0, min = 0) => Math.floor(new Date(y, m, d, h, min).getTime() / 1000);+const q = (s, dmy = true) => parseQuick(s, now, dmy);++test("lunch with someone tomorrow at one", () => {+ const r = q("Lunch with Asha tomorrow 1pm");+ assert.equal(r.title, "Lunch with Asha");+ assert.equal(r.startsAt, at(2026, 9, 22, 13));+ assert.equal(r.endsAt, at(2026, 9, 22, 14));+ assert.equal(r.allDay, false);+ assert.equal(r.repeat, null);+});++test("a weekly repeat on a named day", () => {+ const r = q("Gym every Monday 7am");+ assert.equal(r.title, "Gym");+ assert.equal(r.startsAt, at(2026, 9, 26, 7));+ assert.deepEqual(r.repeat, { freq: "weekly", interval: 1, count: null });+});++test("a range with no am or pm", () => {+ const r = q("Flight Fri 6:30–9");+ assert.equal(r.title, "Flight");+ assert.equal(r.startsAt, at(2026, 9, 23, 18, 30));+ assert.equal(r.endsAt, at(2026, 9, 23, 21));+ const morning = q("Flight Fri 6:30am-9");+ assert.equal(morning.startsAt, at(2026, 9, 23, 6, 30));+ assert.equal(morning.endsAt, at(2026, 9, 23, 9));+ const span = q("Workshop 1-2pm");+ assert.equal(span.startsAt, at(2026, 9, 21, 13));+ assert.equal(span.endsAt, at(2026, 9, 21, 14));+ const noon = q("Talk 11am to 1");+ assert.equal(noon.endsAt - noon.startsAt, 2 * 3600);+});++test("a day alone is all day; nothing said is the next hour", () => {+ const r = q("Mum's birthday on 3 Nov");+ assert.equal(r.title, "Mum's birthday");+ assert.equal(r.allDay, true);+ assert.equal(r.startsAt, at(2026, 10, 3));+ assert.equal(r.endsAt, at(2026, 10, 4));+ const bare = q("Call the bank");+ assert.equal(bare.title, "Call the bank");+ assert.equal(bare.startsAt, at(2026, 9, 21, 11));+ assert.equal(bare.dated || bare.timed, false);+});++test("places, lengths, dates and months", () => {+ const r = q("Coffee with Ravi at Third Wave tomorrow at 4 for 30 min");+ assert.equal(r.title, "Coffee with Ravi");+ assert.equal(r.location, "Third Wave");+ assert.equal(r.startsAt, at(2026, 9, 22, 16));+ assert.equal(r.endsAt - r.startsAt, 1800);+ assert.equal(q("Review Oct 30 at 2:30pm").startsAt, at(2026, 9, 30, 14, 30));+ assert.equal(q("Exam 2027-01-12 9am").startsAt, at(2027, 0, 12, 9));+ assert.equal(q("Dentist 12/11 10am", true).startsAt, at(2026, 10, 12, 10));+ assert.equal(q("Dentist 12/11 10am", false).startsAt, at(2026, 11, 11, 10));+ // A month gone this year is next year's.+ assert.equal(q("Trip March 3").startsAt, at(2027, 2, 3));+ assert.deepEqual(q("Rent every month").repeat, { freq: "monthly", interval: 1, count: null });+ assert.deepEqual(q("Payroll every 2 weeks").repeat, { freq: "weekly", interval: 2, count: null });+ assert.equal(q("Standup daily 9:30").repeat.freq, "daily");+});++test("a time already gone today is tomorrow's; tonight is the evening", () => {+ assert.equal(q("Stretch 8am").startsAt, at(2026, 9, 22, 8));+ assert.equal(q("Dinner tonight").startsAt, at(2026, 9, 21, 19));+ assert.equal(q("Dinner tonight at 8:30").startsAt, at(2026, 9, 21, 20, 30));+ assert.equal(q("Movie at noon").startsAt, at(2026, 9, 21, 12));+});++test("numbers that are not times stay in the title", () => {+ assert.equal(q("Read chapter 4 tomorrow").title, "Read chapter 4");+ assert.equal(q("Room 101 meeting Thursday 3pm").title, "Room 101 meeting");+ assert.equal(q("Room 101 meeting Thursday 3pm").startsAt, at(2026, 9, 22, 15));+});diff --git a/.uiverify/calendar-sidebar-search.mjs b/.uiverify/calendar-sidebar-search.mjsnew file mode 100644index 0000000..6128909--- /dev/null+++ b/.uiverify/calendar-sidebar-search.mjs@@ -0,0 +1,76 @@+// Week numbers on request (More ▸ Show Week Numbers, remembered), sidebar groups that fold+// and show or hide together, and search: coming up first, arrows to choose, Return to go to+// the day with the event open.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });+const page = await ctx.newPage();+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.keyboard.press("Control+3");+await page.waitForTimeout(300);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++ok(await page.locator(".cx-weeknum").count() === 0, "no week numbers by default");+await page.getByRole("button", { name: "More" }).click();+await page.getByRole("menuitemcheckbox", { name: "Show Week Numbers" }).click();+await page.waitForTimeout(200);+const nums = await page.locator(".cx-weeknum").allInnerTexts();+const expected = await page.evaluate(() => {+ // The week holding today, counted as the view counts it.+ const cell = [...document.querySelectorAll(".cx-day")].find((c) => c.querySelector(".cx-daynum.is-today"));+ return cell?.parentElement?.querySelector(".cx-weeknum")?.textContent;+});+ok(nums.length === 6 && nums.every((n) => /^\d{1,2}$/.test(n)) && Number(nums[1]) === (Number(nums[0]) % 53) + 1 || Number(nums[1]) === 1,+ `each week of the month is numbered [${nums.join(" ")}]`);+ok(Boolean(expected) && await page.locator(".cx-minimonth-wk").count() >= 6, "the mini month numbers its weeks too");+await page.keyboard.press("Control+2");+await page.waitForTimeout(200);+ok(/^W\d+$/.test(await page.locator(".cx-head-week").innerText()), "Week shows its number");+await page.reload({ waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.waitForTimeout(300);+ok(await page.locator(".cx-head-week").innerText() !== "", "remembered after a restart");++// Groups fold, and show or hide all their calendars.+const side = page.getByRole("complementary", { name: "Calendars" });+const other = side.getByRole("button", { name: "Other" });+await other.click();+ok(await other.getAttribute("aria-expanded") === "false" && await side.getByText("Birthdays").count() === 0, "a group folds away");+await other.click();+ok(await side.getByText("Birthdays").isVisible(), "and opens again");+await side.getByRole("button", { name: "iCloud" }).click({ button: "right" });+await page.getByRole("menuitem", { name: "Hide All" }).click();+await page.waitForTimeout(200);+ok(await page.locator(".cx-block").count() === 0, "Hide All hides the group's calendars");+const ticks = await side.locator("input[type=checkbox]").evaluateAll((els) => els.slice(0, 3).map((e) => e.checked));+ok(ticks.every((t) => !t), "their ticks say so");+await side.getByRole("button", { name: "iCloud" }).click({ button: "right" });+await page.getByRole("menuitem", { name: "Show All" }).click();+await page.waitForTimeout(200);+ok(await page.locator(".cx-block").count() > 0, "Show All brings them back");++// Search: the arrows choose, Return goes there and opens it.+await page.keyboard.press("Control+f");+await page.keyboard.type("planning");+await page.waitForTimeout(400);+const rows = page.getByRole("option");+ok(await rows.count() === 1 && /Sprint planning/.test(await rows.first().innerText()), "the event is found");+ok(await page.locator(".cx-mark").first().innerText() === "planning", "the words found are marked");+await page.keyboard.press("Control+a");+await page.keyboard.type("e");+await page.waitForTimeout(400);+const n = await rows.count();+await page.keyboard.press("ArrowDown");+ok(n > 1 && await rows.nth(1).getAttribute("aria-selected") === "true", "Down lights the next");+const chosen = (await rows.nth(1).locator(".cx-found-title").innerText()).trim();+await page.keyboard.press("Enter");+await page.waitForTimeout(500);+ok(await page.getByRole("button", { name: "Day", exact: true }).getAttribute("aria-pressed") === "true", "Return goes to its day");+ok(await page.getByRole("dialog", { name: chosen }).isVisible(), `and opens it [${chosen}]`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/calendar-subscriptions.mjs b/.uiverify/calendar-subscriptions.mjsnew file mode 100644index 0000000..661d0ec--- /dev/null+++ b/.uiverify/calendar-subscriptions.mjs@@ -0,0 +1,81 @@+// Calendars subscribed to by address: added from the sidebar's +, listed under Subscriptions,+// their events drawn read-only, refreshed as often as chosen, and let go with Unsubscribe.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1300, height: 850 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, calendarFixture: true });+const page = await ctx.newPage();+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Calendar");+await page.keyboard.press("Control+2");+await page.waitForTimeout(300);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const writes = () => page.evaluate(() => window.__subWrites ?? []);+const side = page.getByRole("complementary", { name: "Calendars" });++ok(await side.getByRole("button", { name: "Subscriptions" }).count() === 0, "no Subscriptions group before there is one");++// A wrong address is said in the panel, and nothing is kept.+await page.evaluate(() => { window.__feedFails = "There’s no calendar at that address any more."; });+await side.getByRole("button", { name: "Add Calendar" }).click();+await page.getByRole("menuitem", { name: /New Subscription/ }).click();+const form = page.getByRole("form", { name: "New Calendar Subscription" });+ok(await form.isVisible(), "New Subscription opens the address field");+await form.getByRole("textbox").fill("webcal://fixtures.example/missing.ics");+await form.getByRole("button", { name: "Subscribe" }).click();+await page.waitForTimeout(200);+ok(/no calendar at that address/.test(await form.getByRole("alert").innerText().catch(() => "")), "a refusal is said where the address was typed");++await page.evaluate(() => { window.__feedFails = null; });+await form.getByRole("textbox").fill("webcal://fixtures.example/pl.ics");+await page.keyboard.press("Enter");+await page.waitForTimeout(500);+ok(await form.count() === 0, "subscribed, the panel closes");+ok(await side.getByRole("button", { name: "Subscriptions" }).isVisible() && await side.getByText("Premier League").isVisible(),+ "it is listed under Subscriptions");+ok((await writes()).some((w) => w.subscribe === "webcal://fixtures.example/pl.ics"), "the address is sent as typed (the engine reads webcal as https)");+const match = page.locator(".cx-block", { hasText: "Arsenal v Chelsea" });+ok(await match.count() === 1, "its events are drawn");+await match.click();+await page.waitForTimeout(200);+const info = page.getByRole("dialog", { name: "Arsenal v Chelsea" });+ok(await info.isVisible() && await info.getByRole("button", { name: "Save" }).count() === 0, "read-only: shown, not edited");+ok((await info.getByRole("link", { name: /Open in Maps/ }).getAttribute("href"))?.startsWith("geo:0,0?q=Emirates"), "its place opens in Maps");+await page.keyboard.press("Escape");++// Hidden with its tick, as any calendar.+await side.getByText("Premier League").click();+await page.waitForTimeout(150);+ok(await match.count() === 0, "its tick hides it");+await side.getByText("Premier League").click();++// Refreshed every hour, on choice.+await side.getByText("Premier League").click({ button: "right" });+await page.getByRole("menuitem", { name: "Refresh", exact: true }).hover();+await page.getByRole("menuitemcheckbox", { name: "Every Hour" }).click();+await page.waitForTimeout(200);+ok((await writes()).some((w) => w.update?.refreshMinutes === 60), "Refresh ▸ Every Hour is kept");++// Renamed from its menu.+await side.getByText("Premier League").click({ button: "right" });+await page.getByRole("menuitem", { name: "Rename" }).click();+await page.keyboard.press("Control+a");+await page.keyboard.type("Football");+await page.keyboard.press("Enter");+await page.waitForTimeout(200);+ok(await side.getByText("Football").isVisible() && (await writes()).some((w) => w.update?.title === "Football"), "renamed");++// Unsubscribe asks first.+await side.getByText("Football").click({ button: "right" });+await page.getByRole("menuitem", { name: "Unsubscribe" }).click();+const ask = page.getByRole("alertdialog");+ok(/Unsubscribe from/.test(await ask.innerText()), "Unsubscribe asks first");+await ask.getByRole("button", { name: "Unsubscribe" }).click();+await page.waitForTimeout(400);+ok(await side.getByText("Football").count() === 0 && await page.locator(".cx-block", { hasText: "Arsenal" }).count() === 0+ && (await writes()).some((w) => w.unsubscribe === "s1"), "unsubscribed, it and its events are gone");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/calendar.mjs b/.uiverify/calendar.mjsindex 86d05c3..31f0829 100644--- a/.uiverify/calendar.mjs+++ b/.uiverify/calendar.mjs@@ -168,13 +168,15 @@ ok(/Sep/.test(title) && /Oct/.test(title), `a week across two months is named fo`a lost release left ${JSON.stringify(left)}`);}-// The whole of making an event from the + button: it opens, takes a title, and is saved with-// what was typed — the thing that has to work for Calendar to be usable at all.+// The whole of making an event with New Event (Ctrl+N; the + opens Quick Event, its own+// suite): it opens, takes a title, and is saved with what was typed — the thing that has to+// work for Calendar to be usable at all.{- await page.locator('button[aria-label="New event"]').click();+ await page.evaluate(() => document.activeElement?.blur());+ await page.keyboard.press("Control+n");await page.waitForTimeout(250);const open = await page.locator(".cx-popover").count();- ok(open === 1, "the + button opens a new event", "the + button opened nothing");+ ok(open === 1, "New Event opens a new event", "New Event opened nothing");await page.keyboard.type("Dinner with Asha");await page.getByRole("button", { name: "Add", exact: true }).click();await page.waitForTimeout(400);@@ -261,13 +263,14 @@ ok(/Sep/.test(title) && /Oct/.test(title), `a week across two months is named fo});ok(notice?.text === "iCloud didn't accept that change, so nothing was saved." && notice.dismiss,"a refused delete says so in a sentence, with Dismiss", `the notice: ${JSON.stringify(notice)}`);- // Delete, pressed with an event open and no field in use, deletes it — as in Calendar.+ // Delete, pressed with an event open and no field in use, deletes it once confirmed.if (notice?.dismiss) {await p.getByRole("button", { name: "Dismiss" }).click();await p.locator(".cx-block", { hasText: "New Event" }).first().click();await p.waitForTimeout(250);await p.evaluate(() => document.activeElement?.blur());await p.keyboard.press("Delete");+ await p.getByRole("alertdialog").getByRole("button", { name: "Delete" }).click();await p.waitForTimeout(300);ok((await p.locator('[role="alert"]').count()) === 1, "Delete deletes an open event, as in Calendar","Delete did nothing to the open event");@@ -323,11 +326,12 @@ ok(/Sep/.test(title) && /Oct/.test(title), `a week across two months is named fo`${narrow.starved} cell(s) show only "N more"`);}- // "+" at six: the new event, 7 to 8, crosses the 7:30 Dentist — it takes a column beside it,+ // New Event at six: the new event, 7 to 8, crosses the 7:30 Dentist — it takes a column beside it,// and its popover opens by it, never over the toolbar.await small.getByRole("button", { name: "Week", exact: true }).click();await small.waitForTimeout(300);- await small.getByRole("button", { name: "New event" }).click();+ await small.evaluate(() => document.activeElement?.blur());+ await small.keyboard.press("Control+n");await small.waitForTimeout(300);const placed = await small.evaluate(() => {const hit = (a, b) => a.left < b.right - 1 && a.right > b.left + 1 && a.top < b.bottom - 1 && a.bottom > b.top + 1;diff --git a/.uiverify/contacts-address.mjs b/.uiverify/contacts-address.mjsnew file mode 100644index 0000000..de9f3ac--- /dev/null+++ b/.uiverify/contacts-address.mjs@@ -0,0 +1,139 @@+// A card's postal addresses, part by part: shown in the order the country writes them, with+// a way to the map; edited as Contacts on the Mac lays an address out; written at once, and+// put back with a toast when Apple turns the change down.+//+// URL=http://localhost:4204 SHOTS=/some/dir ENGINE=webkit node .uiverify/contacts-address.mjs+import { engine, engineName } from "./engine.mjs";+import { SERVICES, installStub } from "./stub.mjs";++const URL = process.env.URL ?? "http://localhost:4173";+const SHOTS = process.env.SHOTS ?? null;+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: 1280, height: 860 }, colorScheme: scheme });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,+ calendarFixture: false, notesFixture: false, contactsFixture: true, driveFixture: false, remindersFixture: false });+ const page = await ctx.newPage();+ await page.goto(URL, { waitUntil: "networkidle" });+ await page.locator(".nav-item", { hasText: "Contacts" }).click();+ await page.locator(".contact-row", { hasText: "Zoya" }).click();+ const card = page.locator(".contact-detail");+ await card.locator(".contact-postal").first().waitFor();+ const shot = async (name) => SHOTS && card.screenshot({ path: `${SHOTS}/${engineName}-${scheme}-${name}.png` });++ if (scheme === "dark") {+ // The look, in the dark: the card and the editor.+ await shot("card");+ await page.getByRole("button", { name: "Edit", exact: true }).click();+ await page.getByLabel("Street, address 1").waitFor();+ await shot("edit");+ await ctx.close();+ continue;+ }++ // ── Shown in the country's own order ──+ const texts = await card.locator(".contact-postal .contact-address").allInnerTexts();+ ok(texts[0] === "Hauptstraße 5\nHinterhaus\n10115 Berlin\nGermany", `a German address puts the postcode before the town ${JSON.stringify(texts[0])}`);+ ok(texts[1] === "12 MG Road\nBengaluru 560001\nKarnataka\nIndia", `an Indian one puts the state under the town ${JSON.stringify(texts[1])}`);+ const labels = await card.locator(".contact-postal dt").allInnerTexts();+ ok(/home/.test(labels[0]) && /work/.test(labels[1]), `labels read as Apple's own ${JSON.stringify(labels)}`);+ const maps = await card.locator(".contact-postal .contact-maps").first().getAttribute("href");+ ok(maps?.startsWith("geo:0,0?q=") && decodeURIComponent(maps).includes("10115 Berlin"), `Show in Maps searches the address ${maps}`);+ await shot("card");++ // ── Edit one part; Return saves, at once ──+ await page.getByRole("button", { name: "Edit", exact: true }).click();+ const street = page.getByLabel("Street, address 1");+ await street.waitFor();+ ok((await street.inputValue()) === "Hauptstraße 5\nHinterhaus", "the street is one multi-line field");+ // Tab walks the parts in the order they are laid out.+ await street.focus();+ const order = [];+ for (let i = 0; i < 4; i++) {+ await page.keyboard.press("Tab");+ order.push(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")));+ }+ ok(JSON.stringify(order) === JSON.stringify(["City, address 1", "State, address 1", "Postcode, address 1", "Country, address 1"]), `Tab goes street, city, state, postcode, country ${JSON.stringify(order)}`);+ const [sTop, cTop, stTop, pTop, coTop] = await Promise.all(["Street", "City", "State", "Postcode", "Country"].map(async (n) => (await page.getByLabel(`${n}, address 1`).boundingBox()).y));+ ok(cTop === stTop && stTop === pTop && sTop < cTop && cTop < coTop, "city, state and postcode share a line, between street and country");+ await shot("edit");+ const city = page.getByLabel("City, address 1");+ await city.fill("Potsdam");+ await page.getByLabel("Postcode, address 1").fill("14467");+ await page.keyboard.press("Enter");+ await page.locator(".contact-form").waitFor({ state: "detached" });+ // Drawn before Apple answers (the stub takes 400 ms).+ const drawn = await card.locator(".contact-postal .contact-address").first().innerText();+ const sentYet = await page.evaluate(() => (window.__addressEdits ?? []).length);+ ok(drawn.includes("14467 Potsdam"), `the change shows at once ${JSON.stringify(drawn)}`);+ await page.waitForFunction(() => (window.__addressEdits ?? []).length === 1);+ const first = await page.evaluate(() => window.__addressEdits[0]);+ ok(JSON.stringify(first.edits) === JSON.stringify([+ { op: "setField", index: 0, field: "city", value: "Potsdam" },+ { op: "setField", index: 0, field: "postalCode", value: "14467" },+ ]) && first.guid === "c1" && first.base?.length === 2, `only the parts changed are sent, against the list the form opened ${JSON.stringify(first.edits)} (queued ${sentYet})`);+ const saves = await page.evaluate(() => (window.__contactSaves ?? []).length);+ ok(saves === 0, "a change to an address alone does not rewrite the rest of the card");++ // ── Esc leaves an edit unsaved ──+ await page.getByRole("button", { name: "Edit", exact: true }).click();+ await page.getByLabel("City, address 1").fill("Hamburg");+ await page.keyboard.press("Escape");+ await page.waitForTimeout(500);+ ok((await page.evaluate(() => (window.__addressEdits ?? []).length)) === 1 && !(await card.innerText()).includes("Hamburg"), "Escape leaves the address as it was");++ // ── Add one, with its label ──+ await page.getByRole("button", { name: "Edit", exact: true }).click();+ await page.getByRole("button", { name: "Add address" }).click();+ const newStreet = page.getByLabel("Street, address 3");+ ok(await newStreet.evaluate((el) => el === document.activeElement), "a new address starts in its street");+ await newStreet.fill("1 Main St");+ await page.getByLabel("City, address 3").fill("Springfield");+ await page.getByLabel("State, address 3").fill("IL");+ await page.getByLabel("Postcode, address 3").fill("62701");+ await page.getByLabel("Country, address 3").fill("United States");+ await page.getByLabel("Label for address 3").click();+ await page.getByRole("option", { name: "Custom" }).click();+ await page.getByLabel("Custom label for address 3").fill("cabin");+ await page.getByRole("button", { name: "Save" }).click();+ await page.waitForFunction(() => (window.__addressEdits ?? []).length === 2);+ const add = await page.evaluate(() => window.__addressEdits[1].edits);+ ok(add.length === 1 && add[0].op === "add" && add[0].address.label === "cabin" && add[0].address.countryCode === "us", `added with its label and country code ${JSON.stringify(add)}`);+ await page.waitForTimeout(500);+ const third = await card.locator(".contact-postal").nth(2).innerText();+ ok(third.includes("Springfield, IL 62701") && third.includes("cabin"), `an American address is written the American way ${JSON.stringify(third)}`);++ // ── Remove one ──+ await page.getByRole("button", { name: "Edit", exact: true }).click();+ await page.getByRole("button", { name: "Remove address 2" }).click();+ await page.getByRole("button", { name: "Save" }).click();+ ok((await card.locator(".contact-postal").count()) === 2 && !(await card.innerText()).includes("Bengaluru"), "a removed address leaves the card at once");+ await page.waitForFunction(() => (window.__addressEdits ?? []).length === 3);+ ok(JSON.stringify(await page.evaluate(() => window.__addressEdits[2].edits)) === JSON.stringify([{ op: "remove", index: 1 }]), "sent as one removal");+ await page.waitForTimeout(500);++ // ── Turned down: put back, with a toast ──+ await page.evaluate(() => { window.__addressFail = true; window.__addressDelay = 600; });+ await page.getByRole("button", { name: "Edit", exact: true }).click();+ await page.getByLabel("Label for address 1").click();+ await page.getByRole("option", { name: "work", exact: true }).click();+ await page.getByLabel("Street, address 1").fill("Unter den Linden 1");+ await page.getByLabel("Street, address 1").press("Enter");+ const during = await card.locator(".contact-postal").first().innerText();+ ok(during.includes("Unter den Linden 1") && /work/.test(during), "shown at once while Apple decides");+ const toast = page.locator(".toast", { hasText: "Address not saved" });+ await toast.waitFor({ timeout: 4000 });+ const after = await card.locator(".contact-postal").first().innerText();+ ok(after.includes("Hauptstraße 5") && !after.includes("Unter den Linden") && /home/.test(after), `turned down, the address goes back ${JSON.stringify(after)}`);+ ok(await toast.getByRole("button", { name: "Try Again" }).isVisible(), "the toast offers to try again");+ await toast.getByRole("button", { name: "Try Again" }).click();+ await page.waitForFunction(() => (window.__addressEdits ?? []).length === 5);+ await page.waitForTimeout(700);+ ok((await card.locator(".contact-postal").first().innerText()).includes("Unter den Linden 1"), "trying again writes it");+ await ctx.close();+}+await b.close();+process.exitCode = failures === 0 ? 0 : 1;diff --git a/.uiverify/contacts-keys.mjs b/.uiverify/contacts-keys.mjsindex 1d50d94..5053f6e 100644--- a/.uiverify/contacts-keys.mjs+++ b/.uiverify/contacts-keys.mjs@@ -61,8 +61,8 @@ await page.locator(".contacts-search").fill("");await page.locator(".contact-row", { hasText: "Northfield" }).click();const link = await page.locator(".contact-methods a", { hasText: "northfield.example" }).getAttribute("href").catch(() => null);ok(link === "https://northfield.example", `a link without its scheme opens on the web ${link}`);-const tel = await page.locator(".contact-methods a", { hasText: "+91 891" }).getAttribute("href");-ok(tel === "tel:+15555550100", `a number dials without its spaces ${tel}`);+const tel = await page.locator(".contact-methods a", { hasText: "+1 555" }).getAttribute("href");+ok(tel === "tel:+15550100199", `a number dials without its spaces ${tel}`);await page.locator(".contact-row", { hasText: "Zoya Ahuja" }).click();await ctx.grantPermissions(["clipboard-read", "clipboard-write"]).catch(() => {});diff --git a/.uiverify/csp.mjs b/.uiverify/csp.mjsindex ef3bf1b..286debf 100644--- a/.uiverify/csp.mjs+++ b/.uiverify/csp.mjs@@ -26,7 +26,7 @@ await page.goto("http://localhost:4173/", { waitUntil: "networkidle" });let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };ok(await page.evaluate(() => !!document.querySelector('meta[http-equiv="Content-Security-Policy"]')), "the policy is in force");-for (const s of ["Reminders", "Notes", "iCloud Drive", "Photos", "Calendar", "Contacts"]) {+for (const s of ["Reminders", "Notes", "Drive", "Photos", "Calendar", "Contacts"]) {await openScreen(page, s);await page.waitForTimeout(500);}diff --git a/.uiverify/drive-delete.mjs b/.uiverify/drive-delete.mjsindex 6af7834..1d87897 100644--- a/.uiverify/drive-delete.mjs+++ b/.uiverify/drive-delete.mjs@@ -28,7 +28,7 @@ for (const refuse of [false, true]) {let asked = false;page.on("dialog", (d) => { asked = true; d.accept(); });await page.goto("http://localhost:4173", { waitUntil: "networkidle" });- await openScreen(page, "iCloud Drive");+ await openScreen(page, "Drive");await page.waitForTimeout(300);await page.getByRole("button", { name: "Actions for Semester Plan.pdf" }).click();await page.getByRole("menuitem", { name: "Delete" }).click();diff --git a/.uiverify/drive-drag.mjs b/.uiverify/drive-drag.mjsindex ca6ff74..3c37282 100644--- a/.uiverify/drive-drag.mjs+++ b/.uiverify/drive-drag.mjs@@ -7,7 +7,7 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(400);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };diff --git a/.uiverify/drive-gone.mjs b/.uiverify/drive-gone.mjsindex 0f4265d..8d9e443 100644--- a/.uiverify/drive-gone.mjs+++ b/.uiverify/drive-gone.mjs@@ -7,7 +7,7 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(400);let failures = 0;const ok = (pass, what) => { console.log(`${pass ? "PASS" : "FAIL"} ${what}`); if (!pass) failures++; };diff --git a/.uiverify/drive-info.mjs b/.uiverify/drive-info.mjsindex c9f59ea..2cd76ff 100644--- a/.uiverify/drive-info.mjs+++ b/.uiverify/drive-info.mjs@@ -6,7 +6,7 @@ const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(300);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };@@ -15,7 +15,7 @@ await page.getByRole("button", { name: "Actions for Semester Plan.pdf" }).click(await page.getByRole("menuitem", { name: "Get Info" }).click();await page.waitForTimeout(200);const facts = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll(".info-rows > div")].map((d) => [d.querySelector("dt").textContent, d.querySelector("dd").textContent])));-ok(facts.Kind === "PDF document" && facts.Size === "2.3 MB" && facts.Where === "iCloud Drive", `File Info ${JSON.stringify(facts)}`);+ok(facts.Kind === "PDF document" && facts.Size === "2.3 MB" && facts.Where === "Drive", `File Info ${JSON.stringify(facts)}`);await page.keyboard.press("Escape");await page.waitForTimeout(150);ok((await page.locator(".info-sheet").count()) === 0, "Escape closes it");diff --git a/.uiverify/drive-keep.mjs b/.uiverify/drive-keep.mjsindex 0429ac2..52406fe 100644--- a/.uiverify/drive-keep.mjs+++ b/.uiverify/drive-keep.mjs@@ -13,7 +13,7 @@ for (const on of [false, 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 page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+ await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(500);const row = page.locator(".drive-row-hit").filter({ hasNot: page.locator("[data-kind='FOLDER']") }).last();const name = (await row.innerText()).split("\n")[0];diff --git a/.uiverify/drive-keys.mjs b/.uiverify/drive-keys.mjsindex dce84b8..2590d75 100644--- a/.uiverify/drive-keys.mjs+++ b/.uiverify/drive-keys.mjs@@ -7,7 +7,7 @@ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(400);let failures = 0;const ok = (pass, what) => { console.log(`${pass ? "PASS" : "FAIL"} ${what}`); if (!pass) failures++; };diff --git a/.uiverify/drive-nav.mjs b/.uiverify/drive-nav.mjsindex 2fce446..51c997a 100644--- a/.uiverify/drive-nav.mjs+++ b/.uiverify/drive-nav.mjs@@ -30,7 +30,7 @@ await ctx.addInitScript(() => {});const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(400);let failures = 0;diff --git a/.uiverify/drive-recents.mjs b/.uiverify/drive-recents.mjsindex e71e899..2ddff5b 100644--- a/.uiverify/drive-recents.mjs+++ b/.uiverify/drive-recents.mjs@@ -20,7 +20,7 @@ await ctx.addInitScript(() => {});const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(300);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };@@ -33,7 +33,7 @@ await page.waitForTimeout(200);const sent = await page.evaluate(() => window.__downloads?.at(-1));ok(sent?.drivewsid === "FILE::r1" && sent?.item?.name === "Invoice-0001", "a double-click saves it, with the file's details sent along");ok(/Saved to Downloads/.test(await page.locator(".toast").innerText()) && (await page.locator(".toast").getByRole("button", { name: "Show in Folder" }).count()) === 1, "and says where, with a way to see it");-await page.locator(".crumb", { hasText: "iCloud Drive" }).click();+await page.locator(".crumb", { hasText: "Drive" }).click();ok((await page.locator(".drive-group").count()) === 0, "the breadcrumb goes back to iCloud Drive");await b.close();process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/drive-select.mjs b/.uiverify/drive-select.mjsindex aee1a17..9ffe31f 100644--- a/.uiverify/drive-select.mjs+++ b/.uiverify/drive-select.mjs@@ -22,7 +22,7 @@ await ctx.addInitScript(() => {});const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(400);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };@@ -57,7 +57,7 @@ await page.waitForTimeout(300);const deleted = await page.evaluate(() => window.__driveDeletes ?? []);ok(deleted.length === 2 && deleted.includes("FOLDER::a") && deleted.includes("FILE::d"), `Delete sends all of the selection ${JSON.stringify(deleted)}`);await page.reload({ waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(400);// F2: rename in place, the name without its extension selected.@@ -97,7 +97,7 @@ ok((await page.locator(".drive-head .drive-col.is-on").innerText()).includes("await page.locator(".drive-head").getByRole("button", { name: /^Name/ }).click();ok(JSON.stringify(await names()) === JSON.stringify(before), "a third click puts it back");await page.reload({ waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(300);ok(JSON.stringify(await names()) === JSON.stringify(before), "remembered the right way round");await ctx.close();@@ -123,7 +123,7 @@ await big.addInitScript(() => {});const p2 = await big.newPage();await p2.goto("http://localhost:4173", { waitUntil: "networkidle" });-await openScreen(p2, "iCloud Drive");+await openScreen(p2, "Drive");await p2.waitForTimeout(800);await p2.locator("button.drive-row-hit").first().click();const t0 = await p2.evaluate(() => performance.now());diff --git a/.uiverify/drive-sort.mjs b/.uiverify/drive-sort.mjsindex 1199d08..a8470a0 100644--- a/.uiverify/drive-sort.mjs+++ b/.uiverify/drive-sort.mjs@@ -25,7 +25,7 @@ await ctx.addInitScript(() => {});const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(400);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };@@ -52,7 +52,7 @@ await pick("Date");const byDate = await files();ok(JSON.stringify(byDate) === JSON.stringify(["File 10.txt", "Semester Plan.pdf", "File 2.txt"]), `by Date, newest first ${JSON.stringify(byDate)}`);await page.reload({ waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(400);ok(JSON.stringify(await files()) === JSON.stringify(byDate), "the order chosen is remembered");// View as Grid: tiles side by side, remembered.@@ -75,7 +75,7 @@ const mid = sheet ? Math.abs(sheet.x + sheet.width / 2 - 600) : 999;ok(mid < 30, `Get Info opens in the middle of the window [${Math.round(mid)}px off]`);await page.keyboard.press("Escape");await page.reload({ waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(400);ok(new Set((await tops()).slice(0, 3)).size === 1, "and Grid is remembered");await b.close();diff --git a/.uiverify/drive-trash.mjs b/.uiverify/drive-trash.mjsindex 44eee6d..9c29eea 100644--- a/.uiverify/drive-trash.mjs+++ b/.uiverify/drive-trash.mjs@@ -8,7 +8,7 @@ const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await openScreen(page, "iCloud Drive");+await openScreen(page, "Drive");await page.waitForTimeout(300);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };diff --git a/.uiverify/drive-upload-cancel.mjs b/.uiverify/drive-upload-cancel.mjsindex 65881a8..39e175c 100644--- a/.uiverify/drive-upload-cancel.mjs+++ b/.uiverify/drive-upload-cancel.mjs@@ -66,7 +66,7 @@ await ctx.addInitScript(() => {const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForSelector(".drive-rows", { state: "attached" });await page.waitForTimeout(300);let failures = 0;diff --git a/.uiverify/drive-upload.mjs b/.uiverify/drive-upload.mjsindex f74fc19..3d2e8ce 100644--- a/.uiverify/drive-upload.mjs+++ b/.uiverify/drive-upload.mjs@@ -53,7 +53,7 @@ await ctx.addInitScript(() => {const page = await ctx.newPage();await page.goto("http://localhost:4173", { waitUntil: "networkidle" });-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForSelector(".drive-rows", { state: "attached" });await page.waitForTimeout(300);diff --git a/.uiverify/drive-watch.mjs b/.uiverify/drive-watch.mjsindex b8ed244..659bb67 100644--- a/.uiverify/drive-watch.mjs+++ b/.uiverify/drive-watch.mjs@@ -25,7 +25,7 @@ await ctx.addInitScript(() => {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 page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(600);let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };diff --git a/.uiverify/drive-widths.mjs b/.uiverify/drive-widths.mjsindex aca87fa..5c6ad4b 100644--- a/.uiverify/drive-widths.mjs+++ b/.uiverify/drive-widths.mjs@@ -15,7 +15,7 @@ for (const [w, h] of [[1920, 1040], [960, 1040], [700, 900], [480, 800]]) {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, "iCloud Drive").catch(() => openScreen(page, "Drive"));+ await openScreen(page, "Drive").catch(() => openScreen(page, "Drive"));await page.waitForTimeout(150);const box = () => page.evaluate(() => {const bar = document.querySelector(".drive > .drive-bar"), up = [...bar.querySelectorAll("button")].find((x) => /Upload/.test(x.textContent));diff --git a/.uiverify/elsewhere.mjs b/.uiverify/elsewhere.mjsindex 07e031f..1221d26 100644--- a/.uiverify/elsewhere.mjs+++ b/.uiverify/elsewhere.mjs@@ -78,7 +78,7 @@ for (const place of PLACES) {page.on("pageerror", (e) => blew.push(String(e)));await page.goto("http://localhost:4173", { waitUntil: "networkidle" });- for (const screen of ["Reminders", "Calendar", "Notes", "Contacts", "iCloud Drive"]) {+ for (const screen of ["Reminders", "Calendar", "Notes", "Contacts", "Drive"]) {await page.getByRole("button", { name: screen, exact: true }).click();await page.waitForTimeout(300);}diff --git a/.uiverify/footer-refresh.mjs b/.uiverify/footer-refresh.mjsindex 95ec3d7..3f4a103 100644--- a/.uiverify/footer-refresh.mjs+++ b/.uiverify/footer-refresh.mjs@@ -56,9 +56,9 @@ ok(JSON.stringify(await page.evaluate(() => window.__some)) === '[["reminders"]]await page.waitForTimeout(700);ok((await said()) === "Reminders updated just now", `and settles [${await said()}]`);-await page.locator(".nav-item", { hasText: "iCloud Drive" }).click();+await page.locator(".nav-item", { hasText: "Drive" }).click();await page.waitForTimeout(150);-ok((await page.evaluate(() => window.__titles.at(-1))) === "iCloud Drive", "the title follows to iCloud Drive");+ok((await page.evaluate(() => window.__titles.at(-1))) === "Drive", "the title follows to iCloud Drive");await page.keyboard.press("Control+r");await page.waitForTimeout(100);ok(JSON.stringify(await page.evaluate(() => window.__some.at(-1))) === '["drive"]', "Ctrl+R updates Drive's own service (drive, not drivews)");diff --git a/.uiverify/intake.mjs b/.uiverify/intake.mjsindex 22c5e96..ad187b3 100644--- a/.uiverify/intake.mjs+++ b/.uiverify/intake.mjs@@ -1,4 +1,4 @@-// A calendar or contacts file opened with Pomander shows what it holds and adds it only on+// A calendar or contacts file opened with Skykeep shows what it holds and adds it only on// confirm, through the same commands the apps use (event_save, contacts_import). The quick// capture window is one field: Enter makes the reminder or note and the window closes.import { engine } from "./engine.mjs";@@ -27,7 +27,7 @@ const ARRIVALS = {{ title: "Dentist", location: null, startsAt: base + 2 * DAY, endsAt: base + 2 * DAY + 1800, allDay: false,timezone: "Asia/Kolkata", notes: null, url: null, alerts: null, repeat: null, duplicate: true },],- refused: [{ title: "Classes", reason: "It repeats on several days of the week, which Pomander can’t set up yet." }],+ refused: [{ title: "Classes", reason: "It repeats on several days of the week, which Skykeep can’t set up yet." }],},contacts: {kind: "contacts", file: "people.vcf", path: "/home/test/Downloads/people.vcf",@@ -197,7 +197,7 @@ async function page(url, arrivals, stub = {}) {await ctx.close();}-// ── Quick capture before Pomander is signed in. ──+// ── Quick capture before Skykeep is signed in. ──{const ctx = await b.newContext({ viewport: { width: 460, height: 132 } });await ctx.addInitScript(installStub, { screen: "signin", services: SERVICES, twoFactor: null, remindersFixture: true });@@ -209,10 +209,10 @@ async function page(url, arrivals, stub = {}) {await field.fill("Pay rent");await field.press("Enter");await p.waitForTimeout(300);- ok(await p.getByText("Sign in to Pomander first.").isVisible() && (await p.evaluate(() => (window.__creates ?? []).length)) === 0,+ ok(await p.getByText("Sign in to Skykeep first.").isVisible() && (await p.evaluate(() => (window.__creates ?? []).length)) === 0,"signed out, it says so and writes nothing");- await p.getByRole("button", { name: "Open Pomander" }).click();- ok(await p.evaluate(() => (window.__calls ?? []).some(([c]) => c === "intake_open_main")), "and Open Pomander brings up the sign-in");+ await p.getByRole("button", { name: "Open Skykeep" }).click();+ ok(await p.evaluate(() => (window.__calls ?? []).some(([c]) => c === "intake_open_main")), "and Open Skykeep brings up the sign-in");await ctx.close();}diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjsindex f0e4c7b..28989eb 100644--- a/.uiverify/keyboard.mjs+++ b/.uiverify/keyboard.mjs@@ -291,7 +291,7 @@ const focused = (page) =>// --- Drive's Move dialog: Escape closes it, focus starts inside it ---{const { ctx, page } = await open("library");- await page.click('.nav-item:has-text("iCloud Drive")');+ await page.click('.nav-item:has-text("Drive")');await page.waitForSelector(".drive-row-hit");await page.hover(".drive-row.is-folder");await page.click('.drive-row.is-folder .drive-action[aria-label^="Actions for"]');diff --git a/.uiverify/look-all.mjs b/.uiverify/look-all.mjsindex 9e71e5c..19160f0 100644--- a/.uiverify/look-all.mjs+++ b/.uiverify/look-all.mjs@@ -8,7 +8,7 @@ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twcalendarFixture: true, notesFixture: true, contactsFixture: true, driveFixture: true, remindersFixture: true });const p = await ctx.newPage();await p.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });-for (const s of ["Reminders", "Notes", "iCloud Drive", "Calendar", "Contacts", "Photos", "Settings"]) {+for (const s of ["Reminders", "Notes", "Drive", "Calendar", "Contacts", "Photos", "Settings"]) {if (s === "Settings") await p.locator(".sidebar-account").click();else await openScreen(p, s);await p.waitForTimeout(500);diff --git a/.uiverify/notes-drawing-link.mjs b/.uiverify/notes-drawing-link.mjsindex 89cd8cc..2afb788 100644--- a/.uiverify/notes-drawing-link.mjs+++ b/.uiverify/notes-drawing-link.mjs@@ -60,7 +60,7 @@ for (const scheme of ["light", "dark"]) {ok((await link.count()) === 1, `${scheme}: the link to a note shows as a link`);await link.click();await page.waitForTimeout(600);- ok(page.url().startsWith("http://localhost:4173"), `${scheme}: following it stays in Pomander`);+ ok(page.url().startsWith("http://localhost:4173"), `${scheme}: following it stays in Skykeep`);const opened = (await page.locator(".note-rich .nf-p").first().innerText()).trim();ok(opened === "The plan" && /Step one/.test(await page.locator(".note-rich").first().innerText()),`${scheme}: and opens the note it links to (the note open is "${opened}")`);diff --git a/.uiverify/notes-keys.mjs b/.uiverify/notes-keys.mjsnew file mode 100644index 0000000..97eb84e--- /dev/null+++ b/.uiverify/notes-keys.mjs@@ -0,0 +1,147 @@+// Notes' keys, as on a Mac (Ctrl here): ↑/↓ through the list, Ctrl+N a new note, Ctrl+F this+// folder's search and Ctrl+Shift+F every folder's, Esc out of search, Ctrl+Backspace delete+// (asked first), and the editor's Ctrl+B/I/U and Ctrl+Shift+L. Adding a file stays hidden while+// the backend's switch is off.+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/notes-keys.mjs+import { engine } from "./engine.mjs";+import { SERVICES, installStub } from "./stub.mjs";++const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (pass, yes, no) => { console.log(pass ? `PASS ${yes}` : `FAIL ${no}`); if (!pass) failures++; };++async function open(setup = () => {}) {+ const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,+ calendarFixture: false, notesFixture: true, contactsFixture: false, driveFixture: false, remindersFixture: false });+ await ctx.addInitScript(setup);+ const page = await ctx.newPage();+ page.on("pageerror", (e) => ok(false, "", `page error: ${e.message}`));+ await page.goto(BASE, { waitUntil: "networkidle" });+ await page.locator(".nav-item", { hasText: "Notes" }).click();+ await page.waitForTimeout(500);+ return { ctx, page };+}+const current = (page) => page.evaluate(() => document.querySelector('.note-row[aria-current="true"] .note-row-name')?.textContent ?? null);+const focusIn = (page, sel) => page.evaluate((s) => Boolean(document.activeElement?.closest(s)), sel);++{+ const { ctx, page } = await open();+ // The list as shown: the pinned note, then Curtains, then the last.+ await page.locator(".note-row", { hasText: "Curtains" }).click();+ await page.waitForTimeout(200);+ await page.keyboard.press("ArrowDown");+ await page.waitForTimeout(250);+ const down = await current(page);+ ok(down?.startsWith("These sources"), "↓ moves to the next note", `↓ landed on ${down}`);+ ok(await focusIn(page, ".note-rows"), "and the list keeps the focus", "focus left the list");+ await page.keyboard.press("ArrowUp");+ await page.keyboard.press("ArrowUp");+ await page.waitForTimeout(250);+ const up = await current(page);+ ok(up?.includes("UNIT 1"), "↑ moves back up, pinned notes first", `↑↑ landed on ${up}`);+ await page.keyboard.press("ArrowUp");+ await page.waitForTimeout(150);+ ok((await current(page))?.includes("UNIT 1"), "and stops at the top", "↑ ran past the top");++ // Ctrl+F in a folder: that folder's search; Esc back to the list.+ await page.locator(".notes-folder", { hasText: /^Notes/ }).click();+ await page.waitForTimeout(300);+ await page.locator(".note-row", { hasText: "Curtains" }).click();+ await page.waitForTimeout(200);+ await page.keyboard.press("Control+f");+ ok(await focusIn(page, ".notes-search"), "Ctrl+F goes to the search field", "Ctrl+F went nowhere");+ ok(await page.getByLabel("Search notes").getAttribute("placeholder") === "Search Notes", "and searches this folder",+ `placeholder ${await page.getByLabel("Search notes").getAttribute("placeholder")}`);+ await page.keyboard.type("curt");+ await page.waitForTimeout(400);+ ok(await page.locator('.notes-scope .segment[aria-pressed="true"]').textContent() === "Notes",+ "the scope shows the folder", "scope not shown");+ ok(await page.locator(".note-row").count() === 1, "results are the folder's matches", `${await page.locator(".note-row").count()} rows`);+ await page.keyboard.press("Escape");+ await page.waitForTimeout(300);+ ok(await page.getByLabel("Search notes").inputValue() === "" && await focusIn(page, ".note-rows"),+ "Esc clears the search and returns to the list", "Esc left the search as it was");+ await page.keyboard.press("Control+Shift+F");+ await page.keyboard.type("curt");+ await page.waitForTimeout(400);+ ok(await page.locator('.notes-scope .segment[aria-pressed="true"]').textContent() === "All iCloud",+ "Ctrl+Shift+F searches every folder", "Ctrl+Shift+F kept the folder scope");+ await page.keyboard.press("Escape");+ await page.waitForTimeout(200);++ // Ctrl+Backspace asks first; No keeps the note.+ await page.locator(".note-row", { hasText: "Curtains" }).click();+ await page.waitForTimeout(200);+ await page.keyboard.press("Control+Backspace");+ await page.waitForTimeout(300);+ const asked = await page.locator(".confirm h2").textContent().catch(() => null);+ ok(asked === "Delete “Curtains”?", "Ctrl+Backspace asks before deleting", `asked ${asked}`);+ await page.keyboard.press("Escape");+ await page.waitForTimeout(300);+ ok(await page.evaluate(() => (window.__noteDeletes ?? []).length) === 0 && await page.locator(".note-row", { hasText: "Curtains" }).count() === 1,+ "and keeping it keeps it", "the note went anyway");+ await page.locator(".note-row", { hasText: "Curtains" }).click();+ await page.keyboard.press("Control+Backspace");+ await page.waitForTimeout(300);+ await page.locator(".confirm .confirm-answer").click();+ await page.waitForTimeout(400);+ ok(JSON.stringify(await page.evaluate(() => window.__noteDeletes)) === '["n1"]', "Delete deletes it", "nothing was deleted");++ // No paperclip while the backend's switch is off.+ ok(await page.getByRole("button", { name: "Add a picture or file" }).count() === 0, "adding a file stays hidden while it is off",+ "the paperclip shows while the backend is off");+ await ctx.close();+}++{+ const { ctx, page } = await open();+ // Ctrl+N from anywhere: a new note, cursor in it.+ await page.locator(".note-row", { hasText: "Curtains" }).click();+ await page.keyboard.press("Control+n");+ await page.waitForTimeout(400);+ ok(await focusIn(page, ".note-rich"), "Ctrl+N starts a new note with the cursor in it", "Ctrl+N did nothing");+ await page.keyboard.type("Plan\nbuy milk");+ await page.keyboard.press("Control+Shift+L");+ await page.waitForTimeout(100);+ ok(await page.locator('.note-rich .nf-p[data-style="103"]', { hasText: "buy milk" }).count() === 1,+ "Ctrl+Shift+L makes the line a checklist item", "no checklist");+ await page.keyboard.press("Shift+Home");+ await page.keyboard.press("Control+b");+ await page.keyboard.press("Control+i");+ await page.keyboard.press("Control+u");+ await page.waitForTimeout(100);+ const marks = await page.evaluate(() => {+ const p = [...document.querySelectorAll(".note-rich .nf-p")].find((x) => x.textContent === "buy milk");+ return ["strong", "em", "u"].filter((t) => p?.querySelector(t)?.textContent === "buy milk");+ });+ ok(marks.length === 3, "Ctrl+B, Ctrl+I and Ctrl+U set bold, italic and underline", `marks ${marks}`);+ // In the editor Ctrl+Backspace is the editor's (a word back), never a delete.+ await page.keyboard.press("End");+ await page.keyboard.press("Control+Backspace");+ await page.waitForTimeout(250);+ ok(await page.locator(".confirm").count() === 0, "Ctrl+Backspace while typing stays the editor's", "it asked to delete the note");+ await ctx.close();+}++{+ // The backend's switch on: the paperclip appears, and adds at the cursor.+ const { ctx, page } = await open(() => { window.__attachOn = true; window.__pick = "/home/test/Pictures/beach.jpg"; });+ await page.locator(".note-row", { hasText: "Curtains" }).click();+ await page.waitForTimeout(400);+ const clip = page.getByRole("button", { name: "Add a picture or file" });+ ok(await clip.count() === 1, "with the switch on, the paperclip shows", "no paperclip with the switch on");+ await page.locator(".note-rich .nf-p", { hasText: "Fan" }).click();+ await page.keyboard.press("End");+ await clip.click();+ await page.waitForTimeout(600);+ const sent = await page.evaluate(() => window.__attaches ?? []);+ const base = sent[0]?.base ?? "";+ ok(sent.length === 1 && sent[0].guid === "n1" && sent[0].path === "/home/test/Pictures/beach.jpg"+ && base.slice(0, sent[0].atOffset).endsWith("Fan"), "it adds the file where the cursor is", `sent ${JSON.stringify(sent)}`);+ await ctx.close();+}++await b.close();+process.exitCode = failures === 0 ? 0 : 1;diff --git a/.uiverify/notes-locked.mjs b/.uiverify/notes-locked.mjsnew file mode 100644index 0000000..618474a--- /dev/null+++ b/.uiverify/notes-locked.mjs@@ -0,0 +1,100 @@+// A locked note, as Notes shows one: a calm lock screen, the hint on request, a wrong password+// said plainly, then the note read-only with Lock Now — and the password kept nowhere.+// BASE=http://localhost:4173 ENGINE=webkit node .uiverify/notes-locked.mjs+import { engine } from "./engine.mjs";+import { SERVICES, installStub } from "./stub.mjs";++const BASE = process.env.BASE ?? "http://localhost:4173";+const PASSWORD = "marigold-7";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 820 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null,+ calendarFixture: false, notesFixture: true, contactsFixture: false, driveFixture: false, remindersFixture: false });+await ctx.addInitScript(() => { window.__lockedNote = true; });+const page = await ctx.newPage();+const errors = [];+page.on("pageerror", (e) => errors.push(e.message));+await page.goto(BASE, { waitUntil: "networkidle" });+await page.locator(".nav-item", { hasText: "Notes" }).click();+await page.waitForTimeout(500);++let failures = 0;+const ok = (pass, yes, no) => { console.log(pass ? `PASS ${yes}` : `FAIL ${no}`); if (!pass) failures++; };++const row = page.locator(".note-row", { hasText: "Bank" });+ok(await row.locator(".note-row-lock").count() === 1 && (await row.textContent()).includes("Locked"),+ "a locked note shows its lock in the list", `the row reads ${await row.textContent()}`);++// From another note, so the lock screen is drawn by the click.+await page.locator(".note-row", { hasText: "Curtains" }).click();+await page.waitForTimeout(300);+await row.click();+await page.waitForTimeout(300);+const lock = page.locator(".note-lock");+ok(await lock.isVisible() && (await lock.textContent()).includes("This note is locked"),+ "it opens on the lock screen", "no lock screen");+const field = page.getByLabel("Note password");+ok(await field.evaluate((el) => el === document.activeElement), "the password field takes the cursor after a click",+ "focus is elsewhere");+ok(await page.getByRole("button", { name: "Unlock" }).isDisabled(), "Unlock waits for a password", "Unlock is live with nothing typed");+ok(await page.locator(".note-rich, [contenteditable='true']").count() === 0, "nothing on it is editable", "an editor is open");++await page.getByRole("button", { name: "Show Hint" }).click();+await page.waitForTimeout(200);+ok((await lock.textContent()).includes("Hint: The fruit"), "the hint shows when asked for", `lock reads ${await lock.textContent()}`);++await field.fill("wrong one");+await field.press("Enter");+await page.waitForTimeout(300);+const problem = (await page.locator(".note-lock-problem").textContent()) ?? "";+ok(/didn’t match/.test(problem) && !/error|invalid/i.test(problem), "a wrong password is said plainly",+ `said ${JSON.stringify(problem)}`);+ok(await field.inputValue() === "" && await field.evaluate((el) => el === document.activeElement),+ "the field is cleared and ready for another try", "the wrong password stayed, or focus left");++await field.fill(PASSWORD);+await page.getByRole("button", { name: "Unlock" }).click();+await page.waitForTimeout(400);+const shown = page.locator(".note-editor.is-unlocked");+ok(await shown.isVisible() && (await shown.textContent()).includes("PIN for the locker 4821"),+ "the right password opens the note", "the note did not open");+ok(await shown.locator("h1").textContent() === "Bank", "with its title set as a title", "title missing");+ok(await shown.locator(".nf-check").count() === 1, "and its checklist drawn", "checklist missing");+ok(await page.locator("[contenteditable='true']").count() === 0 && await shown.locator(".nf-circle:not([disabled])").count() === 0,+ "read-only: no editor, no live checkboxes", "something in it can be changed");+ok(await page.getByRole("button", { name: "Lock Now" }).isVisible(), "Lock Now is in the toolbar", "no Lock Now");++// The password is nowhere the page keeps things.+const kept = await page.evaluate((pw) => {+ const all = [];+ for (const s of [localStorage, sessionStorage]) for (let i = 0; i < s.length; i++) all.push(s.key(i), s.getItem(s.key(i)));+ return all.join("\n").includes(pw) || document.documentElement.outerHTML.includes(pw)+ || [...document.querySelectorAll("input")].some((i) => i.value.includes(pw));+}, PASSWORD);+ok(!kept, "the password is not kept in storage or the page", "the password is still in the page");++// Away and back: still open, without asking again.+await page.locator(".note-row", { hasText: "Curtains" }).click();+await page.waitForTimeout(300);+await row.click();+await page.waitForTimeout(300);+const asks = await page.evaluate(() => (window.__unlockAsks ?? []).length);+ok(await shown.isVisible() && asks === 2, "coming back, it is still open", `asked ${asks} times, open ${await shown.isVisible()}`);++await page.getByRole("button", { name: "Lock Now" }).click();+await page.waitForTimeout(300);+ok(await lock.isVisible() && await page.evaluate(() => window.__lockForgets) === 1,+ "Lock Now locks it again, and the backend lets the password go", "it stayed open");+ok(await page.getByRole("button", { name: "Lock Now" }).count() === 0, "and Lock Now goes with it", "Lock Now still there");++// Arrowing onto a locked note keeps the cursor in the list.+await page.locator(".note-row", { hasText: "Curtains" }).click();+await page.waitForTimeout(300);+await page.keyboard.press("ArrowUp");+await page.waitForTimeout(300);+ok(await lock.isVisible() && await page.evaluate(() => Boolean(document.activeElement?.closest(".note-rows"))),+ "moving onto it with the arrows leaves focus in the list", "focus jumped into the password field");++ok(errors.length === 0, "no errors on the page", errors.join("; "));+await b.close();+process.exitCode = failures === 0 ? 0 : 1;diff --git a/.uiverify/photos-compact.mjs b/.uiverify/photos-compact.mjsnew file mode 100644index 0000000..f9f1a66--- /dev/null+++ b/.uiverify/photos-compact.mjs@@ -0,0 +1,68 @@+// A narrow window: Photos' sidebar folds into one pop-up above the library, so the photos have+// the window's width (beside 480px of window the sidebar took half of it). Every place the+// sidebar goes is in the pop-up, and it stays there on the Albums and Shared Albums pages, so+// there is always a way back. A wide window keeps the sidebar and no pop-up.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++for (const [w, h] of [[480, 760], [700, 760]]) {+ const ctx = await b.newContext({ viewport: { width: w, height: h } });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+ const page = await ctx.newPage();+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); failures++; });+ await page.goto(BASE, { waitUntil: "networkidle" });+ await openScreen(page, "Photos");+ await page.locator(".px-tile").first().waitFor();+ await page.waitForTimeout(300);+ const r = await page.evaluate(() => {+ const side = document.querySelector(".px-side").getBoundingClientRect();+ const scroll = document.querySelector(".px-scroll").getBoundingClientRect();+ const pick = document.querySelector(".px-compact .picker-button")?.getBoundingClientRect();+ const bar = document.querySelector(".px-bar").getBoundingClientRect();+ return { side: side.width, grid: scroll.width, pick: pick ? { w: pick.width, b: pick.bottom } : null, barTop: bar.top };+ });+ ok(r.side === 0 && r.grid >= w - 40, `${w}px: the sidebar folds away and the photos have the width (sidebar ${r.side}px, photos ${Math.round(r.grid)}px)`);+ ok(r.pick && r.pick.w > 40 && r.pick.b <= r.barTop + 1, `${w}px: a pop-up stands for it, above the title ${JSON.stringify(r.pick)}`);++ const pick = page.locator(".px-compact .picker-button");+ const go = async (label) => {+ await pick.click();+ await page.getByRole("option", { name: label, exact: true }).click();+ await page.waitForTimeout(300);+ };+ await go("Favorites");+ ok((await page.locator(".px-bar h1").innerText()) === "Favorites" && (await pick.innerText()).includes("Favorites"), `${w}px: choosing Favorites shows Favorites`);+ await go("Albums");+ ok((await page.locator(".px-albums-page").isVisible()) && (await pick.isVisible()), `${w}px: the Albums page, with the pop-up still there to leave it`);+ await go("Shared Albums");+ ok((await page.locator(".px-main").getAttribute("aria-label")) === "Shared Albums" && (await pick.isVisible()), `${w}px: Shared Albums too`);+ await go("Library");+ ok((await page.locator(".px-bar h1").innerText()) === "Library" && (await page.locator(".px-tile").count()) > 0, `${w}px: and back to the Library`);++ // Keyboard: the pop-up is reached and worked by keys alone.+ await pick.focus();+ await page.keyboard.press("Enter");+ await page.waitForTimeout(150);+ // The first arrow lights the current choice, as a Mac pop-up's; the next moves.+ await page.keyboard.press("ArrowDown");+ await page.keyboard.press("ArrowDown");+ await page.keyboard.press("Enter");+ await page.waitForTimeout(300);+ ok((await page.locator(".px-bar h1").innerText()) === "Favorites", `${w}px: and with the keys alone`);+ await ctx.close();+}++const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+const page = await ctx.newPage();+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Photos");+await page.waitForTimeout(300);+ok((await page.locator(".px-side").isVisible()) && !(await page.locator(".px-compact").isVisible()), "1280px: the sidebar, and no pop-up");+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/photos-narrow.mjs b/.uiverify/photos-narrow.mjsindex 3607287..8f4b3a8 100644--- a/.uiverify/photos-narrow.mjs+++ b/.uiverify/photos-narrow.mjs@@ -15,7 +15,12 @@ for (const [w, h] of [[1280, 800], [900, 700], [760, 700], [560, 700]]) {await openScreen(page, "Photos");await page.waitForTimeout(500);for (const view of ["Library", "Favorites"]) {- await page.locator(".px-source", { hasText: view }).first().click();+ // From 720px down the sidebar is a pop-up above the library (photos-compact).+ if (await page.locator(".px-side").isVisible()) await page.locator(".px-source", { hasText: view }).first().click();+ else {+ await page.locator(".px-compact .picker-button").click();+ await page.getByRole("option", { name: view, exact: true }).click();+ }await page.waitForTimeout(300);const r = await page.evaluate(() => {const t = document.querySelector(".px-bar h1"), span = document.querySelector(".px-bar .px-span");diff --git a/.uiverify/photos-scale.mjs b/.uiverify/photos-scale.mjsindex c05c68b..3c1a8ac 100644--- a/.uiverify/photos-scale.mjs+++ b/.uiverify/photos-scale.mjs@@ -51,14 +51,21 @@ ok(fitted.built && Math.abs(fitted.before - fitted.after) < 1,await page.getByRole("button", { name: "Show Square Photos" }).click();await page.waitForTimeout(200);await page.locator(".px-scroll").evaluate((e) => (e.scrollTop = 0));-await page.waitForTimeout(300);+// Past the moment every tile re-asked for its picture at the new size (and, here, where no+// picture comes, for its thumbnail after 1.5 s): the click is measured, not that.+await page.waitForTimeout(1800);+// The middle of five clicks: one click alone measured whatever else the machine was doing then.const ms = await page.evaluate(async () => {- const t = performance.now();- document.querySelectorAll(".px-tile")[3].click();- await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));- return performance.now() - t;+ const runs = [];+ for (let i = 0; i < 5; i++) {+ const t = performance.now();+ document.querySelectorAll(".px-tile")[3 + i].click();+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));+ runs.push(performance.now() - t);+ }+ return runs.sort((a, b) => a - b)[2];});-ok(ms < 150, `a click that selects stays quick (${Math.round(ms)}ms, two frames included)`);+ok(ms < 150, `a click that selects stays quick (${Math.round(ms)}ms, the middle of five, two frames included)`);// Down, row after row, past the months that were built when it began — after a real click,// with the app list holding the focus first, as it does once Photos is chosen from it.diff --git a/.uiverify/photos-scroll.mjs b/.uiverify/photos-scroll.mjsnew file mode 100644index 0000000..ac97323--- /dev/null+++ b/.uiverify/photos-scroll.mjs@@ -0,0 +1,97 @@+// Scrolling a library of 2,000 photos, with real pictures to decode, at a steady fling's speed:+// the time between frames, as the engine gives them. Every month is built as it comes near and+// kept, so the scroll is the work a user's own scroll does. Prints the numbers, and fails on a+// freeze: one frame held past the bound below. Headless WebKit paints in software, every frame+// on the CPU, so its bound is looser; what it guards against there is the old way of building a+// month whole, all at once, which held single frames for 1.6–4.3 s in a fling.+//+// ENGINE=webkit node .uiverify/photos-scroll.mjs+import http from "node:http";+import { engine, engineName } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++// Twelve photo-like pictures, made once by the engine's own canvas and served from here — a+// page.route per picture is a round trip through the driver, and that was what got measured.+const maker = await b.newPage();+const pics = await maker.evaluate(() => Array.from({ length: 12 }, (_, i) => {+ const c = document.createElement("canvas"); c.width = 384; c.height = 288;+ const g = c.getContext("2d");+ const grad = g.createLinearGradient(0, 0, 384, 288);+ grad.addColorStop(0, `hsl(${i * 30} 70% 60%)`); grad.addColorStop(1, `hsl(${i * 30 + 120} 60% 35%)`);+ g.fillStyle = grad; g.fillRect(0, 0, 384, 288);+ for (let k = 0; k < 60; k++) { g.fillStyle = `hsla(${(i * 30 + k * 13) % 360} 80% 60% / 0.35)`; g.beginPath(); g.arc((k * 97) % 384, (k * 53) % 288, 10 + (k % 7) * 6, 0, 7); g.fill(); }+ return c.toDataURL("image/jpeg", 0.8).split(",")[1];+}));+await maker.close();+const bufs = pics.map((p) => Buffer.from(p, "base64"));+const server = http.createServer((q, r) => {+ const n = Number(decodeURIComponent(q.url).match(/q(\d+)/)?.[1] ?? 0);+ r.writeHead(200, { "content-type": "image/jpeg", "cache-control": "max-age=3600", "access-control-allow-origin": "*" });+ r.end(bufs[n % bufs.length]);+}).listen(0);+const picBase = `http://127.0.0.1:${server.address().port}`;++const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+await ctx.addInitScript((base) => {+ window.__picBase = base;+ const P = (i, t) => ({ id: `q${i}`, master: `mq${i}`, takenAt: t, addedAt: t, kind: i % 17 === 4 ? "video" : "image", width: 4032, height: 3024,+ duration: i % 17 === 4 ? 21 : null, filename: `IMG_${i}.JPG`, size: 2400000, uti: "public.jpeg", favorite: i % 9 === 0, hidden: false,+ deleted: false, deletedAt: null, subtype: 0, changeTag: null });+ window.__photos = Array.from({ length: 2000 }, (_, i) => P(i, 1792600000 - i * 20000));+}, picBase);+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); failures++; });+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Photos");+await page.locator(".px-tile").first().waitFor();+await page.waitForTimeout(800);++/** Scroll the library at `speed` px/s for `ms`, one step a frame; the gaps between frames. */+const run = (speed, ms) => page.evaluate(([speed, ms]) => new Promise((done) => {+ const el = document.querySelector(".px-scroll");+ const gaps = [];+ let last = performance.now();+ const start = last;+ const step = (now) => {+ gaps.push(now - last);+ el.scrollTop += (speed * (now - last)) / 1000;+ last = now;+ if (now - start < ms && el.scrollTop + el.clientHeight < el.scrollHeight - 2) requestAnimationFrame(step);+ else done({ gaps: gaps.slice(2), reached: Math.round(el.scrollTop) });+ };+ requestAnimationFrame(step);+}), [speed, ms]);+const stats = (gaps) => {+ const s = [...gaps].sort((x, y) => x - y);+ const q = (p) => s[Math.min(s.length - 1, Math.floor(p * s.length))];+ return { frames: s.length, p50: q(0.5), p95: q(0.95), max: s[s.length - 1], late: gaps.filter((g) => g > 25).length };+};+const BOUND = engineName === "chromium" ? 120 : 900;+const fmt = (r) => `${r.frames} frames, p50 ${r.p50.toFixed(1)} ms, p95 ${r.p95.toFixed(1)} ms, max ${r.max.toFixed(1)} ms, ${r.late} late (>25 ms)`;++for (const [what, speed] of [["a steady scroll (3,000 px/s)", 3000], ["a fling (9,000 px/s)", 9000]]) {+ await page.evaluate(() => { document.querySelector(".px-scroll").scrollTop = 0; });+ await page.waitForTimeout(400);+ const r = await run(speed, 4000);+ const st = stats(r.gaps);+ console.log(` ${what}: ${fmt(st)} (to ${r.reached}px)`);+ ok(st.max < BOUND, `${what} never freezes (longest frame ${Math.round(st.max)} ms, bound ${BOUND})`);+}++// Zoomed in to days, the same.+await page.evaluate(() => { document.querySelector(".px-scroll").scrollTop = 0; });+await page.keyboard.press("Control+=");+await page.waitForTimeout(600);+const r = stats((await run(3000, 3000)).gaps);+console.log(` by day, 5 across: ${fmt(r)}`);+ok(r.max < BOUND, `grouped by day, never either (longest frame ${Math.round(r.max)} ms)`);++await b.close();+server.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/photos-shortcuts.mjs b/.uiverify/photos-shortcuts.mjsnew file mode 100644index 0000000..73644f7--- /dev/null+++ b/.uiverify/photos-shortcuts.mjs@@ -0,0 +1,173 @@+// The viewer's and the library's keys, as Photos on a Mac takes them: ← and → go through the+// photos, F favorites, I shows Info (which moves the photo aside rather than covering it), Space+// plays a Live Photo's moving part and takes a still back to the library, Ctrl+Backspace deletes+// after asking, Escape closes — and closing leaves the photo last shown chosen and in view.+// In the library: Ctrl + and − zoom, keeping the photo looked at in place, grouped by day from+// five across; and a rectangle swept from the space around the photos selects what it touches.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+await ctx.addInitScript(() => {+ // A moving part that never arrives: the Live Photo stays playing for as long as it is looked at.+ window.__videoBase = "http://video.test/hang";+ const P = (i, t, x = {}) => ({ id: `k${i}`, master: `mk${i}`, takenAt: t, addedAt: t, kind: "image", width: 4032, height: 3024, duration: null,+ filename: `IMG_${i}.JPG`, size: 2400000, uti: "public.jpeg", favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null, ...x });+ // Three photos a day, back over four months.+ window.__photos = Array.from({ length: 360 }, (_, i) => P(i, 1792600000 - Math.floor(i / 3) * 86400 - (i % 3) * 3600, i === 1 ? { kind: "live" } : {}));+});+await ctx.route("http://video.test/**", () => {}); // never answered+const page = await ctx.newPage();+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+// Every question answered yes, and remembered.+await page.addInitScript(() => addEventListener("DOMContentLoaded", () =>+ new MutationObserver(() => {+ const q = document.querySelector(".confirm:not([data-answered])");+ if (!q) return;+ q.setAttribute("data-answered", "");+ (window.__asked ??= []).push(q.querySelector("h2")?.textContent ?? "");+ q.querySelector(".confirm-answer")?.click();+ }).observe(document.body, { childList: true, subtree: true })));+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Photos");+await page.locator(".px-tile").first().waitFor();+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const shown = () => page.evaluate(() => document.querySelector(".px-viewer")?.getAttribute("aria-label") ?? null);+const box = (s) => page.locator(s).first().evaluate((e) => { const r = e.getBoundingClientRect(); return { x: r.x, y: r.y, w: r.width, h: r.height, r: r.right, b: r.bottom }; });++// ---- the viewer ----+await page.locator('.px-tile[data-index="0"]').dblclick();+await page.waitForTimeout(400);+ok((await shown()) === "IMG_0.JPG", "a double-click opens the photo");+ok((await page.evaluate(() => document.getAnimations().filter((a) => a.playState === "running").length)) === 0,+ "and it is open at once — nothing animates");+await page.keyboard.press("ArrowRight");+ok((await shown()) === "IMG_1.JPG", "→ goes to the next photo");++// Space on a Live Photo plays its moving part.+await page.keyboard.press(" ");+await page.waitForTimeout(100);+ok((await page.locator(".px-live").count()) === 1 && (await shown()) === "IMG_1.JPG", "Space plays a Live Photo's moving part");+await page.keyboard.press(" ");+await page.waitForTimeout(100);+ok((await page.locator(".px-live").count()) === 0, "and Space again stops it");++await page.keyboard.press("ArrowRight");+await page.keyboard.press("ArrowLeft");+await page.keyboard.press("ArrowRight");+ok((await shown()) === "IMG_2.JPG", "← and → step either way");++await page.keyboard.press("f");+await page.waitForTimeout(150);+ok((await page.evaluate(() => window.__flags?.at(-1))).flag === "favorite" &&+ (await page.locator('.px-viewer-bar [aria-label="Unfavorite"]').count()) === 1, "F favorites it, and the heart fills at once");++// I: Info beside the photo, never over it, and never over the next arrow.+await page.keyboard.press("i");+await page.waitForTimeout(200);+ok((await page.locator(".px-info").count()) === 1, "I shows Info");+const info = await box(".px-info"), pic = await box(".px-shown"), next = await box(".px-nav.is-next");+ok(pic.r <= info.x && next.r <= info.x, `the photo and its next arrow make room for Info (photo ends ${Math.round(pic.r)}, arrow ${Math.round(next.r)}, Info starts ${Math.round(info.x)})`);+await page.keyboard.press("i");+await page.waitForTimeout(100);+ok((await page.locator(".px-info").count()) === 0, "and I again hides it");++// Ctrl+Backspace: asked first, then gone, and the viewer goes on to the next photo.+await page.keyboard.press("Control+Backspace");+await page.waitForTimeout(300);+ok((await page.evaluate(() => window.__asked?.at(-1))) === "Delete this photo?" &&+ (await page.evaluate(() => window.__flags?.at(-1))).flag === "deleted", "Ctrl+Backspace deletes it, asked first");+ok((await shown()) === "IMG_3.JPG", "and the viewer goes on to the next");++// Through to a photo further on, then Escape: that photo is the one chosen, in view, focused.+for (let i = 0; i < 40; i++) await page.keyboard.press("ArrowRight");+await page.waitForTimeout(200);+const far = await shown();+await page.keyboard.press("Escape");+await page.waitForTimeout(400);+ok((await page.locator(".px-viewer").count()) === 0, "Escape closes it");+const back = await page.evaluate((name) => {+ const t = document.querySelector('.px-tile[aria-selected="true"]');+ const s = document.querySelector(".px-scroll").getBoundingClientRect();+ const r = t?.getBoundingClientRect();+ return { name: t?.getAttribute("aria-label")?.startsWith(name + ","), focused: document.activeElement === t, inView: !!r && r.top >= s.top && r.bottom <= s.bottom };+}, far);+ok(back.name && back.focused && back.inView, `the photo last shown (${far}) is chosen, focused and in view ${JSON.stringify(back)}`);++// Space on a still takes it back to the library, as Photos.+await page.keyboard.press(" ");+await page.waitForTimeout(300);+ok((await shown()) === far, "Space opens the chosen photo");+await page.keyboard.press(" ");+await page.waitForTimeout(300);+ok((await page.locator(".px-viewer").count()) === 0, "and Space on a still closes it again");++// ---- the library ----+const across = () => page.locator(".px-grid").first().evaluate((g) => getComputedStyle(g).gridTemplateColumns.split(" ").length);+const where = () => page.evaluate(() => {+ const t = document.querySelector('.px-tile[aria-selected="true"]');+ return Math.round(t.getBoundingClientRect().top - document.querySelector(".px-scroll").getBoundingClientRect().top);+});+const was = await where(), n0 = await across();+await page.keyboard.press("Control+=");+await page.waitForTimeout(400);+const n1 = await across(), now = await where();+ok(n1 < n0, `Ctrl + makes the photos bigger (${n0} → ${n1} across)`);+ok(Math.abs(now - was) < 40, `and the chosen photo stays where it was on the screen (${was} → ${now}px)`);+const titles = await page.locator(".px-month-title").allInnerTexts();+ok(titles.length > 0 && titles.every((t) => !/^\w+ \d{4}$/.test(t)) && /day/.test(titles[0]), `five across, the library is grouped by day (${titles.slice(0, 2).join(" | ")})`);+await page.keyboard.press("Control+-");+await page.waitForTimeout(400);+ok((await across()) === n0 && /^\w+ \d{4}$/.test((await page.locator(".px-month-title").first().innerText())), "Ctrl − back, by month again");++// The month picker still lists months, once each, by day as well as by month.+await page.keyboard.press("Control+=");+await page.waitForTimeout(300);+await page.getByRole("button", { name: "Go to a Month" }).click();+await page.waitForTimeout(300);+const listed = await page.locator(".px-jump-month span").allInnerTexts();+ok(listed.length >= 3 && new Set(listed).size === listed.length, `by day, the month picker lists each month once (${listed.join(", ")})`);+await page.keyboard.press("Escape");+await page.keyboard.press("Control+-");+await page.waitForTimeout(300);++// A sweep from the space beside the first month's heading down over two rows.+await page.locator(".px-scroll").evaluate((e) => (e.scrollTop = 0));+await page.waitForTimeout(300);+const title = await box(".px-month-title");+const t9 = await box('.px-tile[data-index="9"]');+await page.mouse.move(title.r - 8, title.y + 6);+await page.mouse.down();+await page.mouse.move(t9.x + t9.w / 2, t9.y + t9.h / 2, { steps: 6 });+await page.waitForTimeout(150);+const during = await page.locator(".px-sweep").evaluate((e) => !e.hidden);+await page.mouse.up();+await page.waitForTimeout(150);+const picked = await page.locator('.px-tile[aria-selected="true"]').evaluateAll((ts) => ts.map((t) => +t.dataset.index).sort((a, b) => a - b));+// From the last column down to the middle of photo 9 (second row): those columns of both rows.+const n = await across();+const col9 = 9 % n;+const want = [0, 1].flatMap((r) => Array.from({ length: n - col9 }, (_, c) => r * n + col9 + c));+ok(during, "sweeping draws the rectangle");+ok(picked.join() === want.join(), `a sweep selects exactly the photos it touches (${picked.join(",")}; want ${want.join(",")})`);+ok((await page.locator(".px-sweep").evaluate((e) => e.hidden)), "and the rectangle goes when the button is let go");+const kept = picked.length;+await page.waitForTimeout(100);+ok((await page.locator('.px-tile[aria-selected="true"]').count()) === kept, "the click that ends a sweep does not let the selection go");++// Shift + click extends; Ctrl + click adds and takes away.+await page.locator('.px-tile[data-index="20"]').click();+await page.locator('.px-tile[data-index="24"]').click({ modifiers: ["Shift"] });+ok((await page.locator('.px-tile[aria-selected="true"]').count()) === 5, "Shift-click selects the run between");+await page.locator('.px-tile[data-index="30"]').click({ modifiers: ["Control"] });+await page.locator('.px-tile[data-index="22"]').click({ modifiers: ["Control"] });+ok((await page.locator('.px-tile[aria-selected="true"]').count()) === 5, "Ctrl-click adds one and takes one away");+ok((await page.locator(".px-bar .px-span").innerText()) === "5 Photos Selected", "the header counts them");++await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/reminders-detail-writes.mjs b/.uiverify/reminders-detail-writes.mjsnew file mode 100644index 0000000..5749f2b--- /dev/null+++ b/.uiverify/reminders-detail-writes.mjs@@ -0,0 +1,77 @@+// The controls for tags, links, early alerts and sections, once REMINDER_DETAIL_WRITES is on+// (RemindersView.tsx, mirroring reminders_details.rs). While it is off this says so and stops:+// reminders-tags and reminders-sections check that none of these controls show.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1200, height: 900 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });+await ctx.addInitScript(() => {+ window.__filterLists = true;+ window.__sections = [{ guid: "s1", listGuid: "l1", title: "Errands", createdAt: 1 }];+});+const page = await ctx.newPage();+const errors = [];+page.on("pageerror", (e) => errors.push(String(e)));+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Reminders");+await page.locator(".rx-list", { hasText: "Daily" }).click();+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const writes = () => page.evaluate(() => window.__detailWrites ?? []);++await page.getByRole("button", { name: "Details for Pick up the parcel" }).click();+await page.waitForTimeout(300);+if (await page.locator(".rx-detail .rx-tag-input").count() === 0) {+ console.log("SKIP detail writes are off (REMINDER_DETAIL_WRITES = false)");+ await b.close();+ process.exit(0);+}+// Tags: typed, then shown at once and sent.+await page.locator(".rx-detail .rx-tag-input").fill("#urgent");+await page.keyboard.press("Enter");+await page.waitForTimeout(60);+ok((await page.locator(".rx-detail .rx-tag-name").allInnerTexts()).includes("#urgent"), "a typed tag shows at once");+await page.waitForTimeout(300);+ok((await writes()).some((w) => w.cmd === "reminder_tag_add" && w.name === "urgent" && w.guid === "r2"), "and is sent without its #");+ok((await page.locator(".rx-tags .rx-tag-chip").allInnerTexts()).includes("#urgent"), "and joins the sidebar's tags");+await page.getByRole("button", { name: "Remove tag home" }).click();+await page.waitForTimeout(300);+ok(!(await page.locator(".rx-detail .rx-tag-name").allInnerTexts()).includes("#home"), "a tag is taken off");+ok((await writes()).some((w) => w.cmd === "reminder_tag_remove" && w.name === "home"), "and that is sent");+// Link.+const url = page.getByLabel("URL for Pick up the parcel");+await url.fill("https://example.com/parcel");+await url.press("Enter");+await page.waitForTimeout(200);+ok((await writes()).some((w) => w.cmd === "reminder_url_set" && w.url === "https://example.com/parcel"), "a link is saved");+// Early alert.+await page.getByRole("button", { name: /Early alert for Pick up the parcel/ }).click();+await page.locator(".picker-menu li", { hasText: "15 minutes early" }).click();+await page.waitForTimeout(200);+ok((await writes()).some((w) => w.cmd === "reminder_early_alert_set" && w.count === 15 && w.unit === 0), "an early alert is set");+// Sections: move, make, rename.+await page.getByRole("button", { name: /Section for Pick up the parcel/ }).click();+await page.locator(".picker-menu li", { hasText: "Errands" }).click();+await page.waitForTimeout(300);+ok((await writes()).some((w) => w.cmd === "reminder_section_move" && w.section === "s1" && w.guid === "r2"), "a reminder moves into a section");+const order = await page.evaluate(() => [...document.querySelectorAll(".rx-main .rx-section, .rx-main .rx-row .rx-title")].map((el) => el.classList.contains("rx-section") ? `## ${el.textContent}` : el.value));+ok(order.indexOf("Pick up the parcel") > order.indexOf("## Errands"), `and is shown under it ${JSON.stringify(order)}`);+await page.getByRole("button", { name: "Add Section" }).click();+await page.keyboard.type("Weekend");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok(await page.locator(".rx-section", { hasText: "Weekend" }).count() === 1, "a new section appears");+ok((await writes()).some((w) => w.cmd === "reminder_section_create" && w.title === "Weekend" && w.listGuid === "l1"), "and is made at Apple");+await page.locator(".rx-section", { hasText: "Errands" }).dblclick();+await page.keyboard.press("Control+a");+await page.keyboard.type("Out and about");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok(await page.locator(".rx-section", { hasText: "Out and about" }).count() === 1, "a section is renamed in place");+ok((await writes()).some((w) => w.cmd === "reminder_section_rename" && w.guid === "s1"), "and that is sent");+ok(errors.length === 0, `no page errors ${errors.join(" | ")}`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-sections.mjs b/.uiverify/reminders-sections.mjsnew file mode 100644index 0000000..f838257--- /dev/null+++ b/.uiverify/reminders-sections.mjs@@ -0,0 +1,67 @@+// A list's sections, as Apple shows them: the reminders outside any section first with no+// heading, then each section under its own heading in the order it was made — and a reminder+// placed in a section since deleted stays in view with the loose ones.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });+await ctx.addInitScript(() => {+ window.__filterLists = true;+ window.__sections = [+ { guid: "s1", listGuid: "l1", title: "Errands", createdAt: 1 },+ { guid: "s2", listGuid: "l1", title: "At home", createdAt: 2 },+ { guid: "s3", listGuid: "l2", title: "Elsewhere", createdAt: 3 },+ ];+ const r = (guid, title, sectionGuid) => ({ guid, listGuid: "l1", title, notes: null, dueAt: null, completedAt: null,+ priority: 0, flagged: false, parentGuid: null, sectionGuid, recurFrequency: null, recurInterval: null, etag: null });+ window.__extraReminders = [+ r("x1", "Return the library books", "s1"),+ r("x2", "Buy oat milk", "s1"),+ r("x3", "Fix the balcony light", "s2"),+ r("x4", "Call the plumber", "gone-section"),+ ];+});+const page = await ctx.newPage();+const errors = [];+page.on("pageerror", (e) => errors.push(String(e)));+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Reminders");+await page.locator(".rx-list", { hasText: "Daily" }).click();+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++// What the pane reads top to bottom: headings and titles, in order.+const order = await page.evaluate(() =>+ [...document.querySelectorAll(".rx-main .rx-section, .rx-main .rx-row .rx-title")].map((el) =>+ el.classList.contains("rx-section") ? `## ${el.textContent}` : el.value));+const at = (x) => order.indexOf(x);+ok(at("## Errands") > -1 && at("## At home") > at("## Errands"), `sections in the order they were made ${JSON.stringify(order)}`);+ok(!order.includes("## Elsewhere"), "another list's sections are not shown");+ok(at("Plan tomorrow") < at("## Errands") && at("Call the plumber") < at("## Errands"), "loose reminders first, with no heading — a lost section's too");+ok(at("Return the library books") > at("## Errands") && at("Buy oat milk") < at("## At home"), "each reminder under its own section");+ok(at("Fix the balcony light") > at("## At home"), "the last section holds its own");+ok(await page.locator(".rx-section.is-list-section").count() === 2, "two section headings");++// The info panel names the section, read only while section writes are off.+await page.getByRole("button", { name: "Details for Buy oat milk" }).click();+await page.waitForTimeout(300);+const field = await page.locator(".rx-detail .rx-field", { hasText: "Section" }).innerText();+ok(field.includes("Errands"), `the info names its section ${JSON.stringify(field)}`);+ok(await page.getByRole("button", { name: "Add Section" }).count() === 0, "no Add Section while section writes are off");+// The row menu offers no section move while off.+await page.locator(".rx-row", { has: page.getByLabel("Rename Buy oat milk") }).click({ button: "right", position: { x: 300, y: 10 } });+await page.waitForTimeout(200);+const menu = await page.locator('[role="menu"] [role="menuitem"]').allInnerTexts();+ok(!menu.some((m) => m.includes("Move to Section")), `no Move to Section while off ${JSON.stringify(menu)}`);+await page.keyboard.press("Escape");++// Smart views gather from every list and do not use a list's sections.+await page.locator(".rx-tile", { hasText: "All" }).click();+await page.waitForTimeout(300);+ok(await page.locator(".rx-section.is-list-section").count() === 0, "a smart view is grouped by list, not section");+ok(errors.length === 0, `no page errors ${errors.join(" | ")}`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-shortcuts.mjs b/.uiverify/reminders-shortcuts.mjsnew file mode 100644index 0000000..4a64cd2--- /dev/null+++ b/.uiverify/reminders-shortcuts.mjs@@ -0,0 +1,142 @@+// Reminders' keys, as on the Mac with Ctrl for Command: Ctrl+N a new reminder, Ctrl+Shift+N a+// new list, Ctrl+F the search, Ctrl+I the selected reminder's info; on a row Up/Down move,+// Space ticks, Return edits, Delete asks first and then deletes.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });+await ctx.addInitScript(() => {+ const real = window.__TAURI_INTERNALS__;+ // Deletes are recorded, as Apple would be asked.+ const watch = () => {+ const inv = window.__TAURI_INTERNALS__?.invoke;+ if (!inv || inv.__wrapped) return;+ const wrapped = async (cmd, args) => {+ if (cmd === "reminder_delete") {+ (window.__deletes ??= []).push(args.guid);+ // Apple takes a moment, so what shows first is the app's own answer.+ await new Promise((r) => setTimeout(r, 1500));+ }+ return inv(cmd, args);+ };+ wrapped.__wrapped = true;+ window.__TAURI_INTERNALS__.invoke = wrapped;+ };+ document.addEventListener("DOMContentLoaded", watch);+ void real;+});+const page = await ctx.newPage();+const errors = [];+page.on("pageerror", (e) => errors.push(String(e)));+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Reminders");+await page.locator(".rx-list", { hasText: "Daily" }).click();+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const active = () => page.evaluate(() => {+ const a = document.activeElement;+ return { cls: a?.className ?? "", label: a?.getAttribute("aria-label") ?? "", row: a?.classList.contains("rx-row") ? a.querySelector(".rx-title")?.value : null };+});+const clickEmpty = () => page.mouse.click(900, 760);++// Ctrl+N: the new reminder field, from anywhere.+await clickEmpty();+await page.keyboard.press("Control+n");+await page.waitForTimeout(150);+ok((await page.evaluate(() => !!document.activeElement?.closest(".rx-add"))), "Ctrl+N goes to a new reminder");+await page.keyboard.type("Book the dentist");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok(await page.locator(".rx-row .rx-title").evaluateAll((els) => els.some((e) => e.value === "Book the dentist")), "and Return adds it");+// From a tag, which has nowhere to add, Ctrl+N opens a list to add to.+await page.locator(".rx-tag-chip", { hasText: "#home" }).click();+await page.waitForTimeout(300);+await clickEmpty();+await page.keyboard.press("Control+n");+await page.waitForTimeout(500);+ok(await page.evaluate(() => !!document.activeElement?.closest(".rx-add")), "Ctrl+N from a tag still lands in a new reminder");+await page.keyboard.press("Escape");++// Ctrl+Shift+N: a new list.+await clickEmpty();+await page.keyboard.press("Control+Shift+N");+await page.waitForTimeout(200);+ok((await active()).label === "New list name", `Ctrl+Shift+N names a new list ${JSON.stringify(await active())}`);+await page.keyboard.press("Escape");+await page.locator(".rx-list", { hasText: "Daily" }).click();+await page.waitForTimeout(300);++// Ctrl+F: the search.+await clickEmpty();+await page.keyboard.press("Control+f");+ok((await active()).label === "Search reminders", "Ctrl+F goes to the search");+await page.keyboard.press("Escape");++// Down from nowhere picks the first reminder; Up and Down move.+await clickEmpty();+await page.keyboard.press("ArrowDown");+const first = (await active()).row;+ok(first === "Plan tomorrow", `Down starts at the first reminder ${first}`);+await page.keyboard.press("ArrowDown");+ok((await active()).row === "Pick up the parcel", "Down moves to the next");+await page.keyboard.press("ArrowUp");+ok((await active()).row === "Plan tomorrow", "Up comes back");++// Ctrl+I: the selected reminder's info, and again to close it.+await page.keyboard.press("ArrowDown");+await page.keyboard.press("Control+i");+await page.waitForTimeout(250);+ok(await page.locator(".rx-row.is-open", { has: page.getByLabel("Rename Pick up the parcel") }).count() === 1, "Ctrl+I opens its info");+await page.keyboard.press("Control+i");+await page.waitForTimeout(250);+ok(await page.locator(".rx-detail").count() === 0, "Ctrl+I again closes it");+ok((await active()).row === "Pick up the parcel", "and the row keeps the keys");++// Space ticks; Return edits.+// Apple is slow here, so what shows is the tick itself, before any answer.+await page.evaluate(() => { window.__doneDelay = 800; });+await page.keyboard.press(" ");+await page.waitForTimeout(60);+ok(await page.locator(".rx-row", { has: page.getByLabel("Rename Pick up the parcel") }).locator('.rx-tick[aria-checked="true"]').count() === 1, "Space ticks the selected reminder, at once");+await page.waitForTimeout(900);+await page.evaluate(() => { window.__doneDelay = 0; });+const done = await page.evaluate(() => window.__done?.at(-1));+ok(done?.guid === "r2" && done.done === true, `and asks Apple for that one ${JSON.stringify(done)}`);+// The ticked row goes, and the keys carry on from the one that took its place.+const heir = (await active()).row;+ok(heir && heir !== "Pick up the parcel", `a ticked row hands the keys to the next ${heir}`);+await page.keyboard.press("Enter");+ok((await active()).cls.includes("rx-title"), "Return edits its title");+await page.keyboard.press("Escape");+ok((await active()).row === heir, "Escape goes back to the row");++// Delete asks first; Cancel keeps it; Delete deletes and moves on.+await page.keyboard.press("Delete");+await page.waitForTimeout(200);+const sheet = page.locator('[role="alertdialog"]');+ok(await sheet.count() === 1, "Delete asks first");+ok((await sheet.innerText()).includes(heir), "naming the reminder");+await page.keyboard.press("Escape");+await page.waitForTimeout(200);+ok(await page.locator(".rx-row .rx-title").evaluateAll((els, h) => els.some((e) => e.value === h), heir), "Cancel keeps it");+ok(!(await page.evaluate(() => window.__deletes?.length)), "and nothing is sent");+const heirGuid = await page.locator(".rx-row", { has: page.getByLabel(`Rename ${heir}`) }).getAttribute("data-guid");+await page.locator(".rx-row", { has: page.getByLabel(`Rename ${heir}`) }).focus();+await page.keyboard.press("Delete");+await page.waitForTimeout(200);+await page.locator('[role="alertdialog"] .confirm-answer').click();+await page.waitForTimeout(300);+ok(!(await page.locator(".rx-row .rx-title").evaluateAll((els, h) => els.some((e) => e.value === h), heir)), "Delete, confirmed, removes it at once");+ok(JSON.stringify(await page.evaluate(() => window.__deletes)) === JSON.stringify([heirGuid]), `and asks Apple ${JSON.stringify(await page.evaluate(() => window.__deletes))}`);+ok((await active()).row !== null, `the focus moves on to a neighbouring row ${JSON.stringify(await active())}`);+// Backspace in a title still deletes text, not the reminder.+await page.getByLabel("Rename Plan tomorrow").click();+await page.keyboard.press("End");+await page.keyboard.press("Backspace");+ok(await page.locator('[role="alertdialog"]').count() === 0, "Backspace in a title edits the text");+ok(errors.length === 0, `no page errors ${errors.join(" | ")}`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-tags.mjs b/.uiverify/reminders-tags.mjsnew file mode 100644index 0000000..7770ebe--- /dev/null+++ b/.uiverify/reminders-tags.mjs@@ -0,0 +1,82 @@+// Reminders' tags, custom smart lists, and what the info panel reads beside a reminder:+// #chips on rows, a Tags section in the sidebar that filters, smart lists with their counts,+// the early alert and the link — and no write control while Apple's side is off.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const BASE = process.env.BASE ?? "http://localhost:4173";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });+const page = await ctx.newPage();+const errors = [];+page.on("pageerror", (e) => errors.push(String(e)));+await page.goto(BASE, { waitUntil: "networkidle" });+await openScreen(page, "Reminders");+await page.locator(".rx-list", { hasText: "Daily" }).click();+await page.waitForTimeout(400);+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+const row = (title) => page.locator(".rx-row", { has: page.getByLabel(`Rename ${title}`) });++// Chips on rows.+const chips = await row("Pick up the parcel").locator(".rx-meta .rx-tag").allInnerTexts();+ok(JSON.stringify(chips) === JSON.stringify(["#errands", "#home"]), `a row shows its tags as #chips ${JSON.stringify(chips)}`);+ok((await row("Water the plants").locator(".rx-tag").count()) === 0, "a reminder without tags shows none");++// The sidebar's Tags.+const side = await page.locator(".rx-tags .rx-tag-chip").allInnerTexts();+ok(JSON.stringify(side) === JSON.stringify(["#errands", "#fitness", "#home"]), `the sidebar lists every tag ${JSON.stringify(side)}`);+await page.locator(".rx-tag-chip", { hasText: "#home" }).click();+await page.waitForTimeout(300);+const heading = await page.locator(".rx-head h1").innerText();+const shown = await page.locator(".rx-row .rx-title").evaluateAll((els) => els.map((e) => e.value).sort());+ok(heading === "#home", `tapping a tag opens it ${heading}`);+ok(JSON.stringify(shown) === JSON.stringify(["Pick up the parcel", "Plan tomorrow"]), `and shows only what carries it ${JSON.stringify(shown)}`);+ok(await page.locator('.rx-tag-chip[aria-current="true"]', { hasText: "#home" }).count() === 1, "the open tag is marked in the sidebar");+ok(await page.locator(".rx-add").count() === 0, "a tag view has no add field while tag writes are off");+// A chip on a row opens its tag too.+await row("Pick up the parcel").locator(".rx-meta .rx-tag", { hasText: "#errands" }).click();+await page.waitForTimeout(300);+ok((await page.locator(".rx-head h1").innerText()) === "#errands", "a chip on a row opens its tag");++// Custom smart lists under My Lists, with their counts.+const smart = page.locator(".rx-smart-row", { hasText: "Important" });+ok(await smart.count() === 1, "a custom smart list sits under My Lists");+ok((await page.locator(".rx-smart-row").count()) === 1, "built-in smart lists are not listed twice");+ok((await smart.locator(".count").innerText()) === "1", `with how many it holds ${await smart.locator(".count").innerText()}`);+await smart.click();+await page.waitForTimeout(300);+ok((await page.locator(".rx-head h1").innerText()) === "Important", "opening it shows its name");+const inSmart = await page.locator(".rx-row .rx-title").evaluateAll((els) => els.map((e) => e.value));+ok(JSON.stringify(inSmart) === JSON.stringify(["Pick up the parcel"]), `and what it holds ${JSON.stringify(inSmart)}`);+ok(await page.locator(".rx-capped").count() === 0, "no note when every rule is read");++// The info panel: early alert and link, read only.+await page.locator(".rx-list", { hasText: "Daily" }).click();+await page.waitForTimeout(300);+await page.getByRole("button", { name: "Details for Pick up the parcel" }).click();+await page.waitForTimeout(300);+const panel = page.locator(".rx-detail");+const early = await panel.locator(".rx-field", { hasText: "Early alert" }).innerText().catch(() => "");+ok(early.includes("30 minutes early"), `the info shows the early alert ${JSON.stringify(early)}`);+const link = panel.locator("a.rx-url");+ok((await link.getAttribute("href")) === "https://www.apple.com/shop/order", "and the link, ready to open");+ok((await link.innerText()) === "www.apple.com/shop/order", `shown without its scheme ${await link.innerText()}`);+const tagsField = await panel.locator(".rx-tag-field .rx-tag-name").allInnerTexts();+ok(JSON.stringify(tagsField) === JSON.stringify(["#errands", "#home"]), `and its tags ${JSON.stringify(tagsField)}`);+ok(await panel.locator(".rx-tag-remove, .rx-tag-input, input[type=url]").count() === 0, "no tag or link controls while those writes are off");+// A reminder with none of these shows no empty rows for them.+await page.getByRole("button", { name: "Details for Plan tomorrow" }).click();+await page.waitForTimeout(300);+ok(await page.locator(".rx-detail .rx-field", { hasText: "Early alert" }).count() === 0, "no Early alert row where there is none");+ok(await page.locator(".rx-detail a.rx-url").count() === 0, "no URL row where there is none");+ok(await page.locator(".rx-detail").count() === 1, "one info panel open at a time");++// Rules not read here are said, once.+await page.evaluate(() => { window.__smartUnknown = ["location"]; });+await smart.click();+await page.waitForTimeout(300);+ok(await page.locator(".rx-capped").count() === 1, "a smart list with rules not read here says so");+ok(errors.length === 0, `no page errors ${errors.join(" | ")}`);+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/reminders-tick.mjs b/.uiverify/reminders-tick.mjsindex 3b9e753..d652b20 100644--- a/.uiverify/reminders-tick.mjs+++ b/.uiverify/reminders-tick.mjs@@ -16,14 +16,16 @@ const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failuawait page.evaluate(() => { window.__doneDelay = 4000; });const row = (t) => page.locator(".rx-row", { has: page.getByLabel(`Rename ${t}`) });-// Heights of the row frame by frame from the tick: it must fold (shrink over frames), not vanish.+// The row frame by frame from the tick: it fades out (opacity over several frames), and only+// opacity — its height never animates, which flickered under WebKitGTK on Hyprland.await page.evaluate(() => {const r = [...document.querySelectorAll(".rx-row")].find((x) => x.querySelector('[aria-label="Rename Pick up the parcel"]'));window.__fold = [];const t0 = performance.now();const tick = () => {const h = r.isConnected ? Math.round(r.getBoundingClientRect().height) : -1;- window.__fold.push([Math.round(performance.now() - t0), h]);+ const o = r.isConnected ? Number(getComputedStyle(r).opacity) : -1;+ window.__fold.push([Math.round(performance.now() - t0), h, o]);if (h !== -1 && performance.now() - t0 < 2000) requestAnimationFrame(tick);};requestAnimationFrame(tick);@@ -36,8 +38,9 @@ await page.waitForTimeout(900);ok((await row("Pick up the parcel").count()) === 0, "the row is gone within a moment, before Apple has answered");const fold = await page.evaluate(() => window.__fold);const full = fold[0][1];-const between = fold.filter(([, h]) => h > 0 && h < full - 2);-ok(between.length >= 3, `it folds away over several frames, not all at once ${JSON.stringify(fold.filter(([, h]) => h !== full))}`);+const fading = fold.filter(([, h, o]) => h !== -1 && o > 0.02 && o < 0.98);+ok(fading.length >= 3, `it fades away over several frames, not all at once ${JSON.stringify(fading)}`);+ok(fold.every(([, h]) => h === -1 || h === full), `by opacity alone: its height never animates ${JSON.stringify(fold.filter(([, h]) => h !== full))}`);await row("Plan tomorrow").locator(".rx-tick").click();await page.waitForTimeout(300);diff --git a/.uiverify/screens-return.mjs b/.uiverify/screens-return.mjsindex b8aa92c..a11fe6e 100644--- a/.uiverify/screens-return.mjs+++ b/.uiverify/screens-return.mjs@@ -50,19 +50,33 @@ await page.waitForTimeout(300);await openScreen(page, "Contacts");ok((await playing(".face-photo")) === 0, "back to Contacts: no face fades in again");-// Reminders: a tick springs in on the press, and only then.+// Reminders: a tick's fill fades in on the press, and only then (drawn by the page, frame by+// frame — lib/fade — so it is measured as the fill's opacity rising, not as an animation).await openScreen(page, "Reminders");await page.locator(".rx-list", { hasText: "Daily" }).click();await page.waitForTimeout(400);await page.evaluate(() => { window.__doneDelay = 4000; });const tick = page.locator(".rx-row", { has: page.getByLabel("Rename Pick up the parcel") }).locator(".rx-tick");+const rising = page.evaluate(() => new Promise((done) => {+ const seen = [];+ const sample = () => {+ const fill = document.querySelector(".rx-row.is-settling .rx-tick-fill, .rx-tick[aria-checked='true'] .rx-tick-fill");+ if (fill) seen.push(Number(getComputedStyle(fill).opacity));+ if (seen.length < 12) requestAnimationFrame(sample); else done(seen);+ };+ requestAnimationFrame(sample);+}));await tick.click();-ok((await playing(".rx-tick.is-pressed")) > 0, "a tick pressed springs in");+const seen = await rising;+// Faded in: from faint to (nearly) whole over a few frames, never whole at once.+const low = seen.findIndex((o) => o < 0.5);+ok(low >= 0 && seen.slice(low).some((o) => o >= 0.9), `a tick pressed fades in [${seen.map((o) => o.toFixed(2)).join(" ")}]`);await page.waitForTimeout(400);await openScreen(page, "Notes");await page.waitForTimeout(200);await openScreen(page, "Reminders");-ok((await playing(".rx-tick")) === 0, "back to Reminders: no tick springs again");+const after = await page.evaluate(() => [...document.querySelectorAll(".rx-tick-fill")].map((f) => Number(getComputedStyle(f).opacity)));+ok((await playing(".rx-tick")) === 0 && after.every((o) => o === 0 || o === 1), "back to Reminders: no tick fades in again");// Photos: the square/whole toggle wears no fill until it is hovered.await openScreen(page, "Photos");diff --git a/.uiverify/search-everything.mjs b/.uiverify/search-everything.mjsindex 465eb3c..940d499 100644--- a/.uiverify/search-everything.mjs+++ b/.uiverify/search-everything.mjs@@ -33,7 +33,7 @@ for (const scheme of ["light", "dark"]) {(await page.locator('.nav-item[aria-current="true"]').innerText()).includes("Contacts"), `${scheme}: in Contacts, on that person`);await field.fill("downloads");await page.waitForTimeout(300);- ok((await panel.getByRole("region", { name: "iCloud Drive" }).count()) === 1, `${scheme}: files found by name`);+ ok((await panel.getByRole("region", { name: "Drive" }).count()) === 1, `${scheme}: files found by name`);await page.keyboard.press("Escape");ok(!(await panel.isVisible()), `${scheme}: Escape puts the results away`);await page.keyboard.press("Escape");diff --git a/.uiverify/settings-drive-folder.mjs b/.uiverify/settings-drive-folder.mjsindex d29dc04..8198f1c 100644--- a/.uiverify/settings-drive-folder.mjs+++ b/.uiverify/settings-drive-folder.mjs@@ -13,7 +13,7 @@ let failures = 0;const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };await page.locator(".sidebar-account").click();await page.waitForTimeout(400);-const sw = page.getByRole("switch", { name: "iCloud Drive folder" });+const sw = page.getByRole("switch", { name: "Drive folder" });ok((await sw.getAttribute("aria-checked")) === "false", "off until turned on");await sw.click();await page.waitForTimeout(200);@@ -40,7 +40,7 @@ await page.waitForTimeout(300);const row = await page.locator(".settings-row", { has: sw }).innerText();ok((await sw.getAttribute("aria-checked")) === "false" && /already has files in it/.test(row), `one that cannot come up is left off, and says why "${row.replace(/\n/g, " ")}"`);// The Photos folder: its own switch, beside Drive's, independent of it.-const ph = page.getByRole("switch", { name: "iCloud Photos folder" });+const ph = page.getByRole("switch", { name: "Photos folder" });ok((await ph.getAttribute("aria-checked")) === "false" && (await sw.getAttribute("aria-checked")) === "false", "the Photos folder has its own switch, off");await ph.click();await page.waitForTimeout(200);diff --git a/.uiverify/settings-export.mjs b/.uiverify/settings-export.mjsnew file mode 100644index 0000000..cb51e40--- /dev/null+++ b/.uiverify/settings-export.mjs@@ -0,0 +1,94 @@+// Settings › Storage on This Computer › Export Everything: a folder is chosen, the bar moves+// service by service, it can be cancelled, it ends with Show in Folder; Photos are off unless+// switched on, and a refusal is said.+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++; };+const open = async (init) => {+ const ctx = await b.newContext({ viewport: { width: 1180, height: 820 } });+ if (init) await ctx.addInitScript(init);+ // The event plugin's own half, which the shared stub leaves out (as crash.mjs does).+ await ctx.addInitScript(() => { window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+ const page = await ctx.newPage();+ page.on("pageerror", (e) => ok(false, `page error: ${e.message}`));+ await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });+ await page.locator(".sidebar-account").click();+ await page.waitForSelector(".settings");+ await page.waitForTimeout(300);+ return { ctx, page, row: page.getByRole("group", { name: "Export Everything" }) };+};++{+ const { ctx, page, row } = await open(() => { window.__pick = "/home/test/Backups"; window.__exportStepMs = 60; });+ const section = page.locator(".settings-group", { has: page.getByText("Cached pictures") });+ ok(await section.getByRole("group", { name: "Export Everything" }).isVisible(), "the row sits in Storage on This Computer");+ const photos = row.getByRole("switch", { name: "Include Photos" });+ ok((await photos.getAttribute("aria-checked")) === "false", "photos are off by default");+ await row.getByRole("button", { name: "Export" }).click();+ await page.waitForTimeout(250);+ const bar = row.getByRole("progressbar", { name: "Export progress" });+ ok(await bar.isVisible(), "a bar shows while it runs");+ const mid = await row.innerText();+ ok(/(Notes|Reminders) · \d+ of 10/.test(mid), `each service is said with its count [${mid.split("\n")[1]}]`);+ const now = Number(await bar.getAttribute("aria-valuenow"));+ ok(now > 0 && now < 100, `the bar is part way [${now}%]`);+ ok(await row.getByRole("button", { name: "Cancel" }).isVisible(), "Cancel is offered while it runs");+ await page.waitForFunction(() => document.body.innerText.includes("Exported to"), null, { timeout: 5000 });+ const args = await page.evaluate(() => window.__exportArgs);+ ok(args.dest === "/home/test/Backups" && args.photos === false, "the chosen folder is sent, photos left out");+ ok((await row.innerText()).includes("Exported to Skykeep Export 2026-10-21 10.30"), "the row says where it went");+ ok(await page.locator(".toast", { hasText: "Exported to" }).getByRole("button", { name: "Show in Folder" }).isVisible(), "a toast says so, with Show in Folder");+ await row.getByRole("button", { name: "Show in Folder" }).click();+ await page.waitForTimeout(100);+ ok((await page.evaluate(() => window.__exportRevealed)) === 1, "Show in Folder asks the backend to show it");++ // Photos switched on, and the export kept across leaving Settings and coming back.+ await photos.click();+ ok((await photos.getAttribute("aria-checked")) === "true", "Include Photos switches on");+ await page.evaluate(() => { window.__exportStepMs = 120; });+ await row.getByRole("button", { name: "Export" }).click();+ await page.waitForTimeout(200);+ await openScreen(page, "Reminders");+ await page.waitForTimeout(200);+ await page.locator(".sidebar-account").click();+ await page.waitForSelector(".settings");+ const back = page.getByRole("group", { name: "Export Everything" });+ ok(await back.getByRole("progressbar").isVisible(), "an export under way is still shown on coming back");+ await page.waitForFunction(() => document.body.innerText.includes("photo wasn't on this computer"), null, { timeout: 8000 });+ ok((await page.evaluate(() => window.__exportArgs.photos)) === true, "photos are asked for when switched on");+ await ctx.close();+}+{+ const { ctx, page, row } = await open(() => { window.__pick = "/home/test/Backups"; window.__exportStepMs = 200; });+ await row.getByRole("button", { name: "Export" }).click();+ await page.waitForTimeout(300);+ await row.getByRole("button", { name: "Cancel" }).click();+ await page.waitForTimeout(500);+ ok(await page.locator(".toast", { hasText: "Export cancelled. Nothing was left behind." }).isVisible(), "a cancel says nothing was left");+ ok(!(await page.locator(".toast.is-error").isVisible()), "and is not shown as a failure");+ ok(await row.getByRole("button", { name: "Export" }).isVisible() && !(await row.getByRole("progressbar").isVisible()), "the row is ready again");+ await ctx.close();+}+{+ const { ctx, page, row } = await open(() => {+ window.__pick = "/etc";+ window.__exportStepMs = 1;+ window.__exportFail = "That’s a system folder. Choose one in your home folder or on a drive.";+ });+ await row.getByRole("button", { name: "Export" }).click();+ await page.waitForTimeout(400);+ ok((await page.locator(".toast.is-error").innerText()).includes("system folder"), "a refused folder says why");+ await ctx.close();+}+{+ const { ctx, page, row } = await open(() => { window.__pick = null; });+ await row.getByRole("button", { name: "Export" }).click();+ await page.waitForTimeout(200);+ ok((await page.evaluate(() => window.__exportArgs)) === undefined, "closing the folder picker starts nothing");+ await ctx.close();+}+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/settings-scroll.mjs b/.uiverify/settings-scroll.mjsindex 8f8c2ba..20afb03 100644--- a/.uiverify/settings-scroll.mjs+++ b/.uiverify/settings-scroll.mjs@@ -26,7 +26,7 @@ const scrolls = async () => {await settings();await page.waitForTimeout(300);ok(await scrolls(), "Settings scrolls");-for (const s of ["Notes", "Photos", "Calendar", "iCloud Drive", "Reminders", "Contacts"]) {+for (const s of ["Notes", "Photos", "Calendar", "Drive", "Reminders", "Contacts"]) {await openScreen(page, s);await page.waitForTimeout(300);await settings();diff --git a/.uiverify/settings-storage.mjs b/.uiverify/settings-storage.mjsindex e2524ff..4df7d99 100644--- a/.uiverify/settings-storage.mjs+++ b/.uiverify/settings-storage.mjs@@ -44,7 +44,7 @@ const open = async (init) => {});await page.getByRole("button", { name: "Open", exact: true }).click();await page.waitForTimeout(150);- const row = page.locator(".settings-row", { hasText: "iCloud Drive folder" });+ const row = page.locator(".settings-row", { hasText: "Drive folder" });ok((await row.innerText()).includes("That folder is off.") && !(await page.locator(".toast.is-error").isVisible()), "a folder that cannot be opened says why on its own row");ok(await page.getByText("Alerts can't appear: this desktop has no notification service running.").isVisible(), "a desktop with no notification service is said under the switches");await page.getByRole("button", { name: "Clear", exact: true }).click();diff --git a/.uiverify/sizes.mjs b/.uiverify/sizes.mjsindex 0c832a5..49fe313 100644--- a/.uiverify/sizes.mjs+++ b/.uiverify/sizes.mjs@@ -18,7 +18,7 @@ const SIZES = [{ width: 1920, height: 1040 },{ width: 2560, height: 1440 },];-const SCREENS = ["Reminders", "Notes", "iCloud Drive", "Calendar", "Contacts"];+const SCREENS = ["Reminders", "Notes", "Drive", "Calendar", "Contacts"];const CALENDAR_VIEWS = ["Day", "Week", "Month", "Year"];/** What is broken on the page as it stands, described so a failure says where to look. */diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 6091974..04e21ed 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -80,7 +80,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notemethods: [{ kind: "phone", label: null, value: "+91 98765 43210" }] },{ guid: "c3", firstName: null, lastName: null, company: "Northfield University",isCompany: true, birthday: null, notes: null, etag: null,- methods: [{ kind: "phone", label: "work", value: "+91 891 284 0000" },+ methods: [{ kind: "phone", label: "work", value: "+1 555 010 0199" },{ kind: "url", label: null, value: "northfield.example" }] },{ guid: "c4", firstName: null, lastName: null, company: null, isCompany: false,birthday: null, notes: null, etag: null,@@ -149,7 +149,14 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note// A heavy account, for measuring: `window.__manyEvents = n` adds n events spread over// the year around today, several a day.const n = window.__manyEvents ?? 0;- if (!n) return events;+ // A subscription's fixtures: two matches this week, read-only.+ const subbed = (window.__subs ?? []).flatMap((x) => [+ { guid: `quince:sub:${x.id}:m1:1`, calendarGuid: `quince:sub:${x.id}`, title: "Arsenal v Chelsea", location: "Emirates Stadium",+ startsAt: base + DAY + 8 * HOUR, endsAt: base + DAY + 10 * HOUR, allDay: false, timezone: "Europe/London", url: null, notes: null, etag: null },+ { guid: `quince:sub:${x.id}:m2:1`, calendarGuid: `quince:sub:${x.id}`, title: "Liverpool v Spurs", location: null,+ startsAt: base + 2 * DAY + 8 * HOUR, endsAt: base + 2 * DAY + 10 * HOUR, allDay: false, timezone: "Europe/London", url: null, notes: null, etag: null },+ ]);+ if (!n) return [...events, ...subbed];const extra = (window.__extra ??= Array.from({ length: n }, (_, i) => ({guid: `many${i}`, calendarGuid: i % 2 ? "work" : "home", title: `Event ${i}`, location: null,startsAt: base + Math.floor((i - n / 2) / 8) * DAY + (8 + (i % 8)) * HOUR, endsAt: base + Math.floor((i - n / 2) / 8) * DAY + (9 + (i % 8)) * HOUR,@@ -161,7 +168,38 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notereturn events.filter((e) => words.every((w) => `${e.title} ${e.location ?? ""}`.toLowerCase().includes(w))).sort((a, b) => a.startsAt - b.startsAt);}- case "calendar_list": return (window.__cals ??= calendars.map((c) => ({ ...c }))).map((c) => ({ ...c }));+ case "calendar_list": {+ const subCals = (window.__subs ?? []).map((x, i) => ({ guid: `quince:sub:${x.id}`, title: x.title, colour: x.colour, ctag: null, sortOrder: 800 + i, enabled: true, writable: false, isDefault: false }));+ return [...(window.__cals ??= calendars.map((c) => ({ ...c }))).map((c) => ({ ...c })), ...subCals];+ }+ // Calendars subscribed to by address (calendar tests). `window.__feedFails` makes the+ // next subscribe refuse, as a wrong address is refused.+ case "calendar_subscriptions": return (window.__subs ?? []).map((x) => ({ ...x }));+ case "calendar_subscribe": {+ (window.__subWrites ??= []).push({ subscribe: args.url });+ if (window.__feedFails) throw window.__feedFails;+ const sub = { id: `s${(window.__subs ?? []).length + 1}`, url: String(args.url).replace(/^webcal:/i, "https:"),+ title: "Premier League", colour: "#ff9500", refreshMinutes: 1440, fetchedAt: Math.floor(Date.now() / 1000), problem: null };+ (window.__subs ??= []).push(sub);+ return { ...sub };+ }+ case "calendar_subscription_update": {+ (window.__subWrites ??= []).push({ update: args });+ const x = (window.__subs ?? []).find((y) => y.id === args.id);+ if (x && args.title) x.title = args.title;+ if (x && args.colour) x.colour = args.colour;+ if (x && args.refreshMinutes !== null && args.refreshMinutes !== undefined) x.refreshMinutes = args.refreshMinutes;+ return null;+ }+ case "calendar_unsubscribe": {+ (window.__subWrites ??= []).push({ unsubscribe: args.id });+ window.__subs = (window.__subs ?? []).filter((y) => y.id !== args.id);+ return null;+ }+ case "calendar_subscription_refresh": {+ const x = (window.__subs ?? []).find((y) => y.id === args.id);+ return { ...x, fetchedAt: Math.floor(Date.now() / 1000) };+ }case "calendar_create": {const cals = (window.__cals ??= calendars.map((c) => ({ ...c })));if (cals.some((c) => c.title === args.title)) throw `A calendar with the name \u201c${args.title}\u201d already exists.`;@@ -240,6 +278,44 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "reminder_list_create": case "reminder_list_rename": case "reminder_list_delete":return null;case "reminders_smart": return !remindersFixture || remindersFixture === "lists" ? [] : reminderItems.filter(r => !r.completedAt);+ // Reminders' details (reminders_cmds.rs): tags, a link, early alerts, custom smart lists+ // and sections. A test sets __tagMap / __details / __smartLists / __sections to change them.+ case "reminder_sections": return (window.__sections ?? []).filter((s) => s.listGuid === args.listGuid);+ case "reminder_tags": case "reminders_tagged": case "reminder_detail": {+ const tagMap = (window.__tagMap ??= !remindersFixture || remindersFixture === "lists" ? {} : { r1: ["home"], r2: ["errands", "home"], r3: ["fitness"] });+ const every = [...reminderItems, ...(window.__extraReminders ?? [])];+ if (cmd === "reminder_detail") {+ const extra = (window.__details ?? (remindersFixture ? { r2: { url: "https://www.apple.com/shop/order", earlyAlerts: [{ id: "a1", count: 30, unit: 0 }] } } : {}))[args.guid] ?? {};+ return { guid: args.guid, tags: tagMap[args.guid] ?? [], url: null, earlyAlerts: [], otherAttachments: 0, ...extra };+ }+ const open = (name) => every.filter((r) => !r.completedAt && (tagMap[r.guid] ?? []).some((t) => t.toLowerCase() === name.toLowerCase()));+ if (cmd === "reminders_tagged") return open(args.name);+ const names = [...new Set(Object.values(tagMap).flat())].sort((a, b) => a.localeCompare(b));+ return names.map((name) => ({ name, open: open(name).length }));+ }+ case "reminder_smart_lists": return window.__smartLists ?? (!remindersFixture || remindersFixture === "lists" ? [] : [+ { guid: "SL-today", kind: "today", title: null, colour: null, emblem: null, pinned: true, sorting: null, filter: null },+ { guid: "SL-1", kind: "custom", title: "Important", colour: "#FF9500", emblem: null, pinned: false, sorting: null, filter: '{"priorities":["medium"]}' },+ ]);+ case "reminders_in_smart_list":+ return { reminders: [...reminderItems, ...(window.__extraReminders ?? [])].filter((r) => !r.completedAt && r.flagged), unknown: window.__smartUnknown ?? [] };+ case "reminder_tag_add": case "reminder_tag_remove": case "reminder_url_set": case "reminder_early_alert_set":+ case "reminder_section_create": case "reminder_section_rename": case "reminder_section_move": {+ (window.__detailWrites ??= []).push({ cmd, ...args });+ if (cmd === "reminder_section_create") {+ const made = { guid: `sec-${Date.now()}`, listGuid: args.listGuid, title: args.title, createdAt: null };+ (window.__sections ??= []).push(made);+ return made;+ }+ if (cmd === "reminder_section_rename") { const s = (window.__sections ?? []).find((x) => x.guid === args.guid); if (s) s.title = args.title; }+ if (cmd === "reminder_section_move") { const r = [...reminderItems, ...(window.__extraReminders ?? [])].find((x) => x.guid === args.guid); if (r) r.sectionGuid = args.section; }+ if (cmd === "reminder_tag_add" || cmd === "reminder_tag_remove") {+ const tagMap = (window.__tagMap ??= {});+ const now = tagMap[args.guid] ?? [];+ tagMap[args.guid] = cmd === "reminder_tag_add" ? [...new Set([...now, args.name])] : now.filter((t) => t !== args.name);+ }+ return null;+ }case "note_paragraph": (window.__paragraphs ??= []).push(args); return null;case "note_runs": {if (window.__savedRuns?.[args.guid]) return window.__savedRuns[args.guid];@@ -275,6 +351,35 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notebold: false, italic: false, underline: false, strike: false, link: null }));return runs;}+ // Locked notes (notes_cmds.rs). The password is "marigold-7"; `__unlockAsks` keeps what was+ // sent, `__lockForgets` counts Lock Now. `__lockHint` overrides the hint (null for none).+ case "note_unlock": {+ (window.__unlockAsks ??= []).push(args);+ if (window.__slowUnlock) await new Promise((r) => setTimeout(r, window.__slowUnlock));+ if (args.password !== "marigold-7") throw "That password didn’t open this note.";+ const text = "Bank\nPIN for the locker 4821\nCall before Friday";+ const line = (length, extra = {}) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null, ...extra });+ return { body: text, runs: [line(5, { style: 0 }), line(24), line(18, { style: 103, checked: false })] };+ }+ case "note_lock_hint": return window.__lockHint !== undefined ? window.__lockHint : "The fruit";+ case "note_lock_forget": window.__lockForgets = (window.__lockForgets ?? 0) + 1; return null;+ // Search across every folder but Recently Deleted, by every word typed.+ case "notes_search": {+ 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 }));+ }+ // Adding files: off unless a test turns it on (`__attachOn`), as the backend's switch is.+ case "note_attach_enabled": return Boolean(window.__attachOn);+ case "note_attach_file": {+ (window.__attaches ??= []).push(args);+ const n = noteList.find((x) => x.guid === args.guid);+ const base = args.base ?? n?.body ?? "";+ const body = base.slice(0, args.atOffset) + "\uFFFC" + base.slice(args.atOffset);+ if (n) n.body = body;+ return { attachment: "A-new", media: "M-new", uti: "public.jpeg", offset: args.atOffset, body };+ }case "note_folders": return !notesFixture ? [] : (window.__noteFolders ??= noteFolders.slice()).slice();case "note_folder_create": {const guid = `f-${(window.__noteFolders ??= noteFolders.slice()).length + 1}`;@@ -333,6 +438,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteif (window.__tableNote && !noteList.some((n) => n.guid === "nT"))noteList.unshift({ guid: "nT", folderGuid: "f1", title: "Groceries", snippet: "", body: "Groceries\n\uFFFC\nend",locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789000000, etag: null });+ // Opt-in: a note locked with a password, as a phone locks one.+ if (window.__lockedNote && !noteList.some((n) => n.guid === "nK"))+ noteList.unshift({ guid: "nK", folderGuid: "f1", title: "Bank", snippet: null, body: null,+ locked: true, editable: false, pinned: false, createdAt: null, modifiedAt: 1789400000, etag: null });return !notesFixture ? [] : noteList.map((n) => ({ ...n }));case "note_attachment_info":if (args.id === "D1") return { id: "D1", uti: "com.apple.paper", kind: "drawing", filename: null, title: null, width: 768, height: 621, size: null, hasPreview: true };@@ -592,7 +701,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notereturn (window.__local = { ...l, photos: l.photos - (l.clearable - l.notes - 3_000), notes: 0, drive: l.drive - 3_000, total: l.total - l.clearable, clearable: 0 });}case "alerts_shown": return window.__alertsShown ?? true;- case "diagnostics_save": (window.__diagnostics = (window.__diagnostics ?? 0) + 1); return "/home/user/Downloads/Pomander diagnostics 2026-10-18 20.00.txt";+ case "diagnostics_save": (window.__diagnostics = (window.__diagnostics ?? 0) + 1); return "/home/user/Downloads/Skykeep diagnostics 2026-10-18 20.00.txt";case "account_info": return { name: "Asha Rao", email: "[email protected]", photoContact: window.__mePhoto ?? null, webAccessAllowed: window.__webAccess ?? true, dataProtection: false };case "settings_get": return { reminderAlerts: true, eventAlerts: true, ...(window.__settings ?? {}) };case "settings_set":@@ -659,7 +768,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note}case "drive_kept": return window.__driveFolder?.on ? [...(window.__kept ??= [])] : null;case "drive_keep":- if (!window.__driveFolder?.on) throw "Turn on the iCloud Drive folder in Settings to keep files on this computer.";+ if (!window.__driveFolder?.on) throw "Turn on the Drive folder in Settings to keep files on this computer.";window.__kept = (window.__kept ??= []).filter((k) => k !== args.drivewsid).concat(args.on ? [args.drivewsid] : []);return [...window.__kept];case "login_item_status": return { on: false, command: "\"/usr/bin/quince-app\" --background", honoured: true, ...(window.__login ?? {}) };@@ -699,6 +808,52 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note}case "plugin:event|unlisten":return null;+ // Contacts: a card's postal addresses, part by part (contacts_cmds.rs). Zoya (c1) has a+ // home in Germany and a work address in India; __addressFail turns the next write down.+ case "contact_addresses": {+ const book = (window.__addresses ??= !contactsFixture ? {} : { c1: [+ { label: "HOME", street: "Hauptstraße 5\nHinterhaus", subLocality: null, city: "Berlin", subAdministrativeArea: null,+ state: null, postalCode: "10115", country: "Germany", countryCode: "de" },+ { label: "WORK", street: "12 MG Road", subLocality: null, city: "Bengaluru", subAdministrativeArea: null,+ state: "Karnataka", postalCode: "560001", country: "India", countryCode: "in" },+ ] });+ return (book[args.guid] ?? []).map((a) => ({ ...a }));+ }+ case "contact_address_edit": {+ (window.__addressEdits ??= []).push(args);+ await new Promise((r) => setTimeout(r, window.__addressDelay ?? 400));+ if (window.__addressFail) { window.__addressFail = false; throw "Apple turned that change down."; }+ const list = (args.base ?? window.__addresses?.[args.guid] ?? []).map((a) => ({ ...a }));+ for (const e of args.edits) {+ if (e.op === "setField") list[e.index][e.field] = e.value;+ else if (e.op === "setLabel") list[e.index].label = e.label;+ else if (e.op === "add") list.push({ ...e.address });+ else if (e.op === "remove") list.splice(e.index, 1);+ }+ const kept = list.filter((a) => Object.entries(a).some(([k, v]) => k !== "label" && v));+ (window.__addresses ??= {})[args.guid] = kept;+ return kept.map((a) => ({ ...a }));+ }+ // Export Everything (src-tauri/src/export.rs): each service told along the way, as the+ // backend tells it; __exportStepMs slows it to catch it mid-way, __exportFail fails it.+ case "library_export_start": {+ window.__exportArgs = args;+ window.__exportCancel = false;+ const services = ["notes", "reminders", "contacts", "calendar", "drive", ...(args.photos ? ["photos"] : [])];+ const wait = (ms) => new Promise((r) => setTimeout(r, ms));+ for (const [i, service] of services.entries()) {+ for (const done of [0, 5, 10]) {+ window.__emit?.("quince://export", { service, step: i + 1, steps: services.length, done, total: 10 });+ await wait(window.__exportStepMs ?? 20);+ if (window.__exportCancel) throw "Export cancelled.";+ }+ }+ if (window.__exportFail) throw window.__exportFail;+ return { path: `${args.dest}/Skykeep Export 2026-10-21 10.30`, notes: 3, reminders: 2, contacts: 1, events: 2,+ driveFiles: 1, photos: args.photos ? 2 : 0, photosMissing: args.photos ? 1 : 0 };+ }+ case "library_export_cancel": window.__exportCancel = true; return null;+ case "library_export_reveal": window.__exportRevealed = (window.__exportRevealed ?? 0) + 1; return null;default: throw new Error(`unstubbed command: ${cmd}`);}},@@ -717,7 +872,7 @@ export async function openScreen(page, name) {}await page.locator(".nav-item", { hasText: name }).click();// Each app's code arrives on its own; the screen is open once it is drawn.- const root = { Calendar: ".cx", Notes: ".notes", Reminders: ".rx", Contacts: ".contacts", "iCloud Drive": ".drive" }[name];+ const root = { Calendar: ".cx", Notes: ".notes", Reminders: ".rx", Contacts: ".contacts", "Drive": ".drive" }[name];if (root) await page.locator(root).first().waitFor({ state: "attached", timeout: 10000 });}diff --git a/.uiverify/switch-frames.mjs b/.uiverify/switch-frames.mjsindex f29cae9..1c57ea4 100644--- a/.uiverify/switch-frames.mjs+++ b/.uiverify/switch-frames.mjs@@ -47,7 +47,7 @@ const switchTo = (name) => page.evaluate(async (name) => {return frames;}, name);-for (const name of ["Notes", "Calendar", "Contacts", "iCloud Drive", "Notes", "Reminders", "Calendar"]) {+for (const name of ["Notes", "Calendar", "Contacts", "Drive", "Notes", "Reminders", "Calendar"]) {const frames = await switchTo(name);// Frame 0 is the state in the click's own task, never painted; frames 1.. are each a paint.const painted = frames.slice(1);diff --git a/README.md b/README.mdindex 7b5ec9c..eaad3b3 100644--- a/README.md+++ b/README.md@@ -1,155 +1,625 @@-# Quince+<div align="center">++<picture>+ <!-- The mark sits on a transparent background and reads on light and dark alike.+ To use a dedicated dark variant later, point the first srcset at docs/media/logo-dark.png. -->+ <source media="(prefers-color-scheme: dark)" srcset="packaging/icons/skykeep-mark-1024.png">+ <source media="(prefers-color-scheme: light)" srcset="packaging/icons/skykeep-mark-1024.png">+ <img src="packaging/icons/skykeep-mark-1024.png" alt="Skykeep: a blue tower rising from a cloud" width="140">+</picture>++# Skykeep++**Native iCloud apps for Linux and Windows.**++Your Notes, Reminders, Calendar, Contacts, iCloud Drive and Photos as fast, native apps on your own computer.<br>+Instant. Offline. Private. Open source.++[](LICENSE)+[](https://github.com/YashwanthKamireddi/Skykeep/releases)+[](https://github.com/YashwanthKamireddi/Skykeep/actions/workflows/release.yml)+[](https://github.com/YashwanthKamireddi/Skykeep/actions/workflows/windows.yml)+<br>+[-4a5568)](#install)+[](https://www.rust-lang.org)+[](https://tauri.app)+[](https://github.com/YashwanthKamireddi/Skykeep/stargazers)+<!-- Enable once published:+[](https://aur.archlinux.org/packages/skykeep-git)+[](https://flathub.org/apps/io.github.yashwanthkamireddi.Skykeep)+-->++[**Install**](#install) · [**Features**](#features) · [**Privacy**](#privacy-by-design) · [**FAQ**](#faq) · [**Build from source**](#build-from-source) · [**Contributing**](#contributing) · [**Roadmap**](#roadmap)++</div>++<br>++<div align="center">+ <!-- Hero: an edit on an iPhone shows up in Skykeep about a second later. See docs/media/README.md. -->+ <img src="docs/media/hero-sync.gif" alt="A note typed on an iPhone appears in Skykeep Notes on a Linux desktop about a second later" width="900">+</div>++<br>++<table>+ <tr>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/notes-dark.png">+ <img src="docs/media/notes-light.png" alt="Skykeep Notes with a checklist, a table and a picture">+ </picture>+ <p align="center"><b>Notes</b></p>+ </td>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/reminders-dark.png">+ <img src="docs/media/reminders-light.png" alt="Skykeep Reminders showing Today with a subtask and a flag">+ </picture>+ <p align="center"><b>Reminders</b></p>+ </td>+ </tr>+ <tr>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/calendar-dark.png">+ <img src="docs/media/calendar-light.png" alt="Skykeep Calendar in week view with reminders on the schedule">+ </picture>+ <p align="center"><b>Calendar</b></p>+ </td>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="docs/media/drive-dark.png">+ <img src="docs/media/drive-light.png" alt="Skykeep Drive beside the iCloud Drive folder in the file manager">+ </picture>+ <p align="center"><b>iCloud Drive</b></p>+ </td>+ </tr>+</table>++<details>+<summary><b>More screenshots</b>: Contacts, Photos, Settings, sign-in</summary>+<br>++| | |+|---|---|+| <img src="docs/media/contacts-light.png" alt="Skykeep Contacts with a card and the lists sidebar"> | <img src="docs/media/photos-dark.png" alt="Skykeep Photos library by month (preview)"> |+| **Contacts** | **Photos** (preview) |+| <img src="docs/media/settings-light.png" alt="Skykeep Settings showing the account, storage and what the app talks to"> | <img src="docs/media/signin-light.png" alt="Signing in with an Apple Account and a two-factor code"> |+| **Settings**: your account, storage and sync | **Sign-in**: Apple's own sign-in and two-factor code |++</details>++---++## Why Skykeep++Your iPhone keeps your life in iCloud: the shopping list, the meeting notes, the birthdays, the files. Apple makes iCloud apps for its own devices, so on a Linux or Windows computer you've had a browser tab and a lot of waiting.++**Skykeep brings your iCloud home.** It keeps a copy of your iCloud on your own computer, so every screen opens instantly, works without a connection, and stays in sync with your iPhone in both directions. The engine is written in Rust; it talks only to Apple; and the code is open for anyone to read.++> *Sky* is the cloud, where your iCloud lives. A *keep* is the strongest tower of a castle, where precious things are kept. **Skykeep: your cloud, kept safe on your own computer.**++## Highlights++| | |+|---|---|+| **Six apps, one engine** | Notes, Reminders, Calendar, Contacts, Drive and Photos. Each opens as its own app; all share one sign-in and one sync. |+| **Instant** | Your library lives on your disk. Screens open immediately, with no loading from the internet. |+| **Works offline** | Read and edit without a connection. Changes are sent when you're back online. |+| **Two-way sync** | Notes and Reminders arrive over Apple's push channel in about a second. Calendar and Contacts check for changes every few seconds while a window is open. |+| **Private by design** | Your password never leaves your computer. No Skykeep account, no Skykeep server, no telemetry. The network layer can reach only Apple. |+| **At home on your desktop** | Light and dark mode, system notifications with action buttons, a tray icon, quick capture, results in GNOME and KDE search, and `.ics` / `.vcf` files opened straight into Calendar and Contacts. |+| **Your data, exportable** | Export Everything writes your whole library to Markdown, iCalendar, vCard, CSV and the original files, any time, offline. |++## Features++<details open>+<summary><b>Notes</b></summary>+<br>++- Rich text: titles, headings, monospaced text, bold, italic, underline, strikethrough, and colours set on your phone.+- Bulleted, dashed, numbered lists and checklists, typed as on the iPhone (`- `, `* `, `1. `, `[ ] `).+- Pictures, drawings, scans, PDFs, recordings and files shown in place and opened in your own apps.+- Tables shown as grids and kept up to date as they change on your phone.+- Folders (new, rename, nest, delete), pinned notes, Recently Deleted and Recover.+- Search within a folder or across every note.+- Edits made on your phone at the same moment are **merged, not overwritten**.+- Markdown export.++*Coming soon:* editing tables, adding attachments, and opening locked notes.+</details>++<details>+<summary><b>Reminders</b></summary>+<br>++- Lists with Apple's colours and glyphs, and groups of lists.+- Today, Scheduled, Flagged and All, plus your smart lists.+- Subtasks (Tab), due dates and all-day dates, repeating reminders, flags and priorities.+- Alerts that ring on this computer, with **Complete** and **Snooze** buttons.+- Drag to reorder; completing a repeating reminder works the way your phone does.+- Tags and sections are shown.++*Coming soon:* editing tags and sections.+</details>++<details>+<summary><b>Calendar</b></summary>+<br>++- Day, Week, Month and Year views.+- Drag or double-click to create; drag to move and resize; nudge with the keyboard.+- Repeating events, with This Event, All Future Events and All Events.+- Alerts, time zones, and your reminders on the schedule in their list's colour.+- Birthdays and holidays.+- Create, rename, recolour and delete calendars.+- Subscribe to any public calendar by its `webcal://` or `https://` address.+- Open `.ics` files straight into an import sheet.++*Later:* invitations and RSVP.+</details>++<details>+<summary><b>Contacts</b></summary>+<br>++- Every field: phones, emails, links, addresses, birthdays, notes, with Apple's own labels, and structured addresses.+- Lists in a sidebar; add people by menu or by dragging.+- Select several to add, remove, export or delete together.+- Import from vCard, or from a CSV exported by Google Contacts or Outlook. Export to vCard.+- My Card.+</details>++<details>+<summary><b>iCloud Drive</b></summary>+<br>++- Browse in a list or grid with Apple's thumbnails; sort; Recents.+- Upload files or whole folders by button or drag and drop, with per-file progress and cancel.+- Download, rename, duplicate, Get Info, move by dialog or by dragging onto a folder.+- Quick preview with Space; keep files on this computer for offline use.+- Recently Deleted with Recover and Delete Now; your storage at a glance.+- **On Linux, iCloud Drive as a real folder** in your file manager (`~/iCloud Drive`, via FUSE).+</details>++<details>+<summary><b>Photos</b> <sub>(preview)</sub></summary>+<br>++> [!NOTE]+> Photos is a **preview**: it is built and tested, and is waiting on testing against a large real-world library before it leaves preview.++- Your whole library, edge to edge and by month, with zoom.+- Favourites, Recents, Videos, Screenshots, Recently Deleted, your albums and shared albums.+- A viewer with arrow keys, details, Favourite, Live Photos and videos.+- Search, slideshow, upload, and download in original quality.+</details>++<details>+<summary><b>Across every app</b></summary>+<br>++- **Global search** across notes, reminders, events, contacts, files and photos.+- **Quick capture:** `skykeep --new note` or `skykeep --new reminder` opens a small capture window. Also in the launcher's right-click menu.+- **Desktop search:** results appear in GNOME Shell search and KRunner.+- **Tray icon** and system notifications with sounds and action buttons.+- **Settings:** your account, iCloud storage, when each app last synced (with Sync Now), Automatic / Light / Dark, and alert switches.+- **Accessibility:** Reduce Transparency and Increase Contrast are honoured, and every app is built to be driven from the keyboard.+</details>++## Privacy by design++Skykeep asks for your Apple Account password, so it was built to deserve that trust, and it shows its work.++- **Your password never leaves your computer.** Sign-in uses Apple's own SRP flow: Skykeep proves it knows your password without sending it. Your session lives in your system keyring (Secret Service on Linux, Credential Manager on Windows).+- **It talks only to Apple, enforced in code.** Every network client is built by [`apple_only()`](crates/quince-auth/src/lib.rs), whose resolver refuses any host outside `apple.com`, `icloud.com` and `icloud-content.com`. A [test](crates/quince-auth/tests/apple_only.rs) holds it to that. The only other hosts it ever contacts are calendars you subscribe to yourself.+- **No Skykeep servers.** No account, no telemetry, no analytics, no crash reporting, no update check.+- **The window can't reach the network at all.** Its content security policy lets it talk only to Skykeep's own Rust core.+- **Your data stays yours.** Everything lives in your private data folder, and Export Everything hands it to you in open formats.++Read exactly what Skykeep talks to, what it keeps and where, in **[SECURITY.md](SECURITY.md)**.++## How it works++```mermaid+flowchart LR+ subgraph Computer["Your computer"]+ direction TB+ UI["Six app windows<br/>(Tauri + React)"]+ Core["Rust engine<br/>sync · outbox · merge"]+ DB[("Local library<br/>SQLite + caches")]+ Keyring["System keyring"]+ UI <-->|"IPC only"| Core+ Core <--> DB+ Core <--> Keyring+ end+ Core <-->|"HTTPS, Apple hosts only"| Apple["iCloud<br/>(CloudKit, Contacts,<br/>Calendar, Drive, Photos)"]+ Apple <--> Phone["Your iPhone"]+```-Your iCloud, on your own computer.+1. **Sign in once.** Apple's own sign-in and two-factor code. The session goes into your keyring.+2. **Your library comes home.** Each service syncs into a local SQLite library, and each screen fills as its service lands.+3. **Edits show instantly.** A change appears the moment you make it and goes into an outbox. It is sent to Apple when you're online, and put back with the reason if Apple ever refuses it.+4. **Changes flow back.** Notes and Reminders arrive over Apple's push channel; Calendar and Contacts are checked every few seconds, the same way icloud.com does.-Quince signs into iCloud once and keeps a copy of your calendar, reminders, notes, contacts,-Drive and photos on your machine. Everything opens straight away and works with no connection, and-what you change here reaches your phone.+## Install-It is a native Linux application — Rust underneath, a real window, no browser wrapper.+> [!IMPORTANT]+> The first public release is on its way. Packages appear on the [Releases page](https://github.com/YashwanthKamireddi/Skykeep/releases) as they're published, each with SHA-256 checksums. Until then, [build from source](#build-from-source) in a few minutes.-<!-- A screenshot belongs here once there is a public repo to host it. -->+| Platform | How | Status |+|---|---|---|+| **Arch, CachyOS, EndeavourOS, Manjaro** | `paru -S skykeep-git` or `yay -S skykeep-git` | AUR: coming soon |+| **Any distribution** | Flatpak from Flathub | Coming soon |+| **Debian, Ubuntu, Mint, Pop!_OS** | `.deb` from Releases | With the first release |+| **Fedora, openSUSE, RHEL** | `.rpm` from Releases | With the first release |+| **Any distribution, no install** | `.AppImage` from Releases | With the first release |+| **Windows 10 and 11** | `.exe` or `.msi` from Releases | **Beta** |-## What works+<details>+<summary><b>Arch Linux and derivatives</b></summary>+<br>-Everything here is read from and written to your real iCloud account, shows the moment you-make it — before Apple has answered — and is put back with the reason if Apple refuses.+From the AUR (coming soon):-**Notes** — pictures, scans, PDFs, recordings, films and files shown where they sit and opened-in your own apps; tables shown as the grids they are, kept up to date as they change on your-phone; text coloured on the phone in its colour; edited formatted, as on a Mac: titles,-headings, monospaced text, bulleted, dashed and numbered lists (typed as on the phone: "- ",-"* ", "1. ", "[ ] "), checklists you tick, bold, italic, underline and strikethrough, from the-Aa panel, the checklist button or the Mac's keys. Delete opens the note below, as Notes does. Folders: new, rename, nest,-delete. Pin, move, Recently Deleted and Recover. An edit made on your phone at the same time-is merged in, not overwritten, and nothing either side typed is lost.+```sh+paru -S skykeep-git # or: yay -S skykeep-git+```-**Reminders** — lists with Apple's colours and glyphs, groups, subtasks (Tab, ⌘]), repeats,-due dates and all-day dates, flags, priorities, alerts that ring on this computer, drag to-reorder, Today / Scheduled / Flagged / All, and completing a repeating reminder the way your-phone does.+Today, build the same package from a checkout:-**Calendar** — Day, Week, Month and Year; make, rename, recolour and delete calendars; Go to-Date (⇧⌃T); make an event by dragging or double-clicking;-move and resize by dragging, or nudge with ⌃⌥ and the arrows; alerts; repeats, with Only-This Event, All Future Events and All Events for one day of a series; your reminders on the-schedule in their list's colour; birthdays and holidays; the Mac's keyboard throughout.+```sh+git clone https://github.com/YashwanthKamireddi/Skykeep.git+cd Skykeep/packaging/arch+makepkg -si+```-**Contacts** — cards with phones, emails, links, birthdays and notes; lists in a sidebar,-with people added by menu or by dragging; select several to add, remove, export or delete-together; labels from Apple's own list; import many contacts at once from vCard or from a CSV-exported by Google Contacts or Outlook, and export; My Card.+Optional: install `fuse3` for iCloud Drive and Photos as folders in your file manager.+</details>-**iCloud Drive** — browse in a list or grid with Apple's own thumbnails; sort; upload files-or whole folders by button or by dropping them on the window, each file's progress shown and-any of them cancellable while it is still on its way up; download, rename, duplicate, Get Info; move by-dialog or by dragging onto a folder; Recents; Recently Deleted with the time each item has-left, Recover and Delete Now; your storage.+<details>+<summary><b>Debian / Ubuntu (.deb)</b></summary>+<br>-**Photos** — your whole library, edge to edge and by month, with a zoom; Favorites, Recents,-Videos, Screenshots, Recently Deleted and your albums; a viewer with the arrow keys, details,-Favorite (.), Delete to Recently Deleted and Recover, and the original downloaded. Videos open-in your own player. Pictures are fetched once and kept, so the library scrolls from disk.+```sh+sudo apt install ./Skykeep_*_amd64.deb+```+</details>-**Instant, both ways.** A change made on your phone reaches Quince in about a second: Notes,-Reminders and Photos through Apple's own push channel, Calendar and Contacts through the same quick-"has anything changed" checks icloud.com makes, every few seconds while the window is open.-What you change shows the moment you make it and is put back, with the reason, only if Apple-refuses it — and a refresh landing mid-change never undoes what is still on its way.+<details>+<summary><b>Fedora / openSUSE (.rpm)</b></summary>+<br>-**Settings** — your account and its picture from your own card, iCloud storage, when each app-last synced with Sync Now, Automatic / Light / Dark, and switches for reminder and calendar-alerts that the alerts really obey.+```sh+sudo dnf install ./Skykeep-*.x86_64.rpm # Fedora+sudo zypper install ./Skykeep-*.x86_64.rpm # openSUSE+```+</details>-**Designed as macOS 27 is.** Liquid Glass on the chrome — the sidebar, toolbars, menus,-popovers and sheets — and never on your content; capsule controls; motion on Apple's own-springs; each app in its own Mac colour, Notes yellow, Calendar red, the rest blue; light and-dark, Reduce Transparency and Increase Contrast honoured.+<details>+<summary><b>AppImage</b></summary>+<br>-**Advanced Data Protection.** With it on and "Access iCloud Data on the Web" off, no app-outside your devices can read your iCloud. Quince says exactly that, once, and names Apple's-switch — on your iPhone, Settings, your name, iCloud, Access iCloud Data on the Web — rather-than failing screen by screen.+```sh+chmod +x Skykeep_*_amd64.AppImage+./Skykeep_*_amd64.AppImage+```-Not yet: Mail, Find My, calendar invitations, uploading photos. Notes tables are read-only for-now: edits made here were stored by Apple but did not show on an iPhone, so no table is changed-until one is seen there.+Needs WebKitGTK 4.1 and libsecret on the system, which most desktops already have.+</details>-## Installing+<details>+<summary><b>Flatpak</b> (coming soon)</summary>+<br>-**Arch, CachyOS, EndeavourOS, Manjaro**+The Flathub manifest is in [`packaging/flatpak`](packaging/flatpak). Once it's live:```sh-cd packaging/arch && makepkg -si+flatpak install flathub io.github.yashwanthkamireddi.Skykeep```-**Running it from the source**+In the Flatpak, iCloud Drive and Photos are available inside the app; the file-manager folders need the native packages.+</details>++<details>+<summary><b>Windows</b> (beta)</summary>+<br>++> [!NOTE]+> Windows builds are tested on every release in CI (the full test suite, every interface suite in Edge, and an install-and-launch smoke test), and they're labelled **beta** until they've been verified on more real Windows machines. Feedback is very welcome.-```sh-./run.sh-```+Download `Skykeep_*_x64-setup.exe` (per-user, no admin needed) or the `.msi` from [Releases](https://github.com/YashwanthKamireddi/Skykeep/releases) and run it. It registers `.ics` and `.vcf` files, and notifications come with Complete and Snooze buttons.++The iCloud Drive and Photos folders in Explorer are on the roadmap.+</details>++**Requirements on Linux:** `webkit2gtk-4.1` for the window and `libsecret` for the keyring (GNOME Keyring or KWallet). Packages pull them in for you.-builds the interface and the app and opens Quince.+## First run++1. **Open Skykeep** from your app menu. On Linux, each app (Notes, Reminders, Calendar, Contacts, Drive, Photos) also has its own launcher entry.+2. **Sign in** with your Apple Account, then enter the code shown on your iPhone. This is Apple's own two-factor flow.+3. **Watch your library arrive.** Each app fills as its data lands. After this first sync, everything opens instantly, even offline.+4. **Optional:** in Settings, turn on the iCloud Drive and iCloud Photos folders (Linux), choose your appearance, and set which alerts ring.-**Anything else**+> [!TIP]+> Using **Advanced Data Protection**? Turn on **Access iCloud Data on the Web** on your iPhone: Settings → your name → iCloud → Access iCloud Data on the Web. Skykeep tells you if it's needed.-```sh-npm ci && npx tauri build-```+## Keyboard shortcuts++Skykeep follows the keys of Apple's own apps, with **Ctrl** in place of **⌘**.++<details>+<summary><b>Show all shortcuts</b></summary>+<br>++| Where | Keys | Action |+|---|---|---|+| Everywhere | `Ctrl` `R` / `F5` | Sync the app in front |+| Notes | `Ctrl` `N` | New note |+| | `Ctrl` `F` / `Ctrl` `Shift` `F` | Search this folder / all notes |+| | `↑` `↓` | Previous / next note |+| | `Ctrl` `Delete` | Delete note |+| | `Ctrl` `S` | Finish editing |+| Reminders | `Ctrl` `N` / `Ctrl` `Shift` `N` | New reminder / new list |+| | `Tab` / `Shift` `Tab` (or `Ctrl` `]` / `Ctrl` `[`) | Make a subtask / move it back out |+| | `Space` · `Return` | Tick · edit |+| | `Ctrl` `I` | Show details |+| | `Ctrl` `F` | Search |+| Calendar | `Ctrl` `1` – `4` | Day, Week, Month, Year |+| | `T` | Today |+| | `Ctrl` `Shift` `T` | Go to Date |+| | `←` `→` | Previous / next |+| | `Ctrl` `N` | New event |+| | `Ctrl` `D` · `Ctrl` `C` · `Ctrl` `V` | Duplicate · copy · paste event |+| | `Ctrl` `Alt` `↑↓←→` | Nudge the selected event |+| Contacts | `Ctrl` `N` · `Ctrl` `F` · `Ctrl` `A` | New contact · search · select all |+| Drive | `Return` / `Ctrl` `↓` | Open |+| | `Ctrl` `↑` | Enclosing folder |+| | `Space` | Quick preview |+| | `F2` · `Delete` | Rename · move to Recently Deleted |+| Photos | `←` `→` | Previous / next |+| | `.` or `F` | Favourite |+| | `I` · `Z` | Info · zoom to fit / full size |+| | `Ctrl` `+` `-` `0` | Zoom in / out / reset |+| | `Space` | Play a video or Live Photo |+| | `Esc` | Close the viewer |++</details>++## FAQ++<details>+<summary><b>Is Skykeep made by Apple?</b></summary>+<br>++No. Skykeep is an independent, open-source project. It is **not affiliated with, endorsed by, or sponsored by Apple Inc.** iCloud, iPhone and Apple are trademarks of Apple Inc., used here only to describe what Skykeep works with.+</details>++<details>+<summary><b>Is it safe to give Skykeep my Apple Account password?</b></summary>+<br>++Your password is used only on your computer, through Apple's SRP sign-in, which proves you know it without sending it. It's stored in your system keyring so a lapsed session can sign itself back in. Skykeep has no server and no account of its own, and its network layer refuses every host but Apple's. Every claim is in [SECURITY.md](SECURITY.md), with the code and tests that back it up.+</details>++<details>+<summary><b>I use Advanced Data Protection. Will it work?</b></summary>+<br>++Yes, with **Access iCloud Data on the Web** turned on (iPhone: Settings → your name → iCloud → Access iCloud Data on the Web). With that switch off, Apple lets no app outside your own devices read your iCloud data, Skykeep included. Skykeep explains this once and names the switch; it never asks you to turn Advanced Data Protection off.+</details>++<details>+<summary><b>Does it work offline?</b></summary>+<br>++Yes. Everything you've synced is on your disk. Read and edit freely; your changes wait in an outbox and are sent when you're back online. A small indicator shows anything still waiting.+</details>++<details>+<summary><b>How fast does a change on my iPhone show up?</b></summary>+<br>++Notes and Reminders arrive over Apple's push channel, typically in about a second. Calendar and Contacts are checked every few seconds while a window is open. Your own edits in Skykeep show the instant you make them.+</details>++<details>+<summary><b>What if I edit the same note on my phone and here at the same time?</b></summary>+<br>-leaves a `.deb`, an `.rpm` and an AppImage under `target/release/bundle/`. The AppImage needs-no package manager.+Both edits are kept. Notes merges text the way Apple's apps do, so nothing either side typed is lost.+</details>-Quince needs `webkit2gtk-4.1` for its window and `libsecret` for the keyring. It will start-without the second and will not be able to stay signed in, which is most of the point of it.+<details>+<summary><b>Which parts of iCloud aren't included?</b></summary>+<br>-Flatpak is not done yet — see `packaging/README.md` for what it needs and why it has not been-guessed at.+Mail and Find My aren't part of Skykeep today. Health, Messages, Keychain, Home and Safari history are end-to-end encrypted by Apple and can't be read by any app outside your devices; Skykeep shows them as unavailable rather than leaving them out silently.+</details>++<details>+<summary><b>Which Linux desktops does it support?</b></summary>+<br>-## Building and checking+Skykeep is built for any desktop with WebKitGTK 4.1 and a Secret Service keyring (GNOME Keyring or KWallet), on Wayland or X11. It's used daily on Hyprland, and GNOME and KDE Plasma also get Skykeep results in their desktop search. If something looks off on your desktop, please [open an issue](https://github.com/YashwanthKamireddi/Skykeep/issues/new/choose).+</details>++<details>+<summary><b>Can I get my data out?</b></summary>+<br>++Any time. Settings → Export Everything writes your whole library to a folder: notes as Markdown, events as iCalendar, contacts as vCard and CSV, and your files as they are. It works offline.+</details>++<details>+<summary><b>What happens if Apple changes something?</b></summary>+<br>++Skykeep uses the same services icloud.com uses. If Apple changes one, the affected screen may pause until an update catches up. Your local copy stays on your computer the whole time.+</details>++<details>+<summary><b>How do I sign out or remove my data?</b></summary>+<br>++Settings → Sign Out asks whether to keep a copy on this computer. Choose to remove it, and the library, its caches and its file-manager thumbnails are deleted.+</details>++## Build from source++<details open>+<summary><b>Linux</b></summary>+<br>++Prerequisites: Rust 1.85+ ([rustup](https://rustup.rs)), Node.js 22, and the system libraries.```sh-./check.sh+# Debian / Ubuntu+sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \+ librsvg2-dev libsecret-1-dev libheif-dev libfuse3-dev pkg-config++# Arch+sudo pacman -S --needed webkit2gtk-4.1 gtk3 libsecret libheif libayatana-appindicator \+ gstreamer gst-plugins-base-libs fuse3 rust nodejs npm pkgconf++# Fedora+sudo dnf install webkit2gtk4.1-devel gtk3-devel libayatana-appindicator-gtk3-devel \+ librsvg2-devel libsecret-devel libheif-devel fuse3-devel pkgconf-pkg-config```-Formatting, lints, the Rust tests, TypeScript, the bundle, and then the built application-driven in a real browser: every screen screenshotted and measured, the keyboard path walked, motion sampled frame by-frame (a fold that jumps, a list that flickers, a menu that blinks fails the build),-accessibility audited, and every screen opened again as a German speaker in New York, a-Japanese speaker in Tokyo and a New Zealander on the Chathams — because this was written in-one place with a clock that never moves, and most people are somewhere else.+Then:-Nothing lands with that red.+```sh+git clone https://github.com/YashwanthKamireddi/Skykeep.git+cd Skykeep+npm ci+./run.sh # builds the interface and the app, then opens Skykeep+```-There are also checks that talk to a real iCloud account, which is why they are not in-`check.sh`. They live in `probe/examples` and are run deliberately:+Packages (`.deb`, `.rpm`, `.AppImage` under `target/release/bundle/`):```sh-cargo run -p quince-probe --example notes_audit+npx tauri build+```+</details>++<details>+<summary><b>Windows</b></summary>+<br>++Install Rust, Node.js 22 and the [Tauri prerequisites](https://tauri.app/start/prerequisites/). HEIC support uses libheif from vcpkg:++```powershell+vcpkg install libheif:x64-windows-static-md+$env:VCPKG_ROOT = "<path to vcpkg>"+$env:VCPKGRS_TRIPLET = "x64-windows-static-md"+npm ci+npx tauri build+```++The exact steps CI uses are in [`.github/workflows/windows.yml`](.github/workflows/windows.yml).+</details>++## Architecture++Skykeep is one Rust engine with six app windows on top. The Rust side does all the talking to Apple; the interface is a React app rendered by the system's web engine (WebKitGTK on Linux, WebView2 on Windows), with no network access of its own.++<details>+<summary><b>Project layout</b></summary>+<br>++```text+crates/+ quince-auth/ Apple sign-in (SRP, two-factor), the session, the keyring,+ and the apple_only() network allow-list+ quince-icloud/ iCloud services: CloudKit, Notes (topotext CRDT, tables),+ Reminders, Calendar, Contacts, Drive, Photos, push channel+ quince-core/ The local library (SQLite), sync, outbox, search, export+ quince-vfs/ iCloud Drive and Photos as folders (FUSE, Linux)+ quince-media/ Picture decoding and thumbnails (including HEIC)+src-tauri/ The desktop app: windows, commands, alerts, tray, desktop search,+ file import, migrations+src/ The interface (React + TypeScript)+ screens/ One folder or file per app, plus sign-in and Settings+ components/ The shared design system: Toast, Confirm, EmptyState, PaneTitle and more+ lib/ IPC, sync state, optimistic writes, theming+probe/ Live checks against a real iCloud account (run deliberately)+.uiverify/ Playwright interface suites, in Chromium and WebKit+packaging/ Arch, AUR, Flatpak, desktop entries, AppStream metadata, icons```-Each one asks the same question of a different service — not "did the write return 200" but-"do the account and the local copy agree, right now, about real data".+The crates keep their original `quince-` prefix from before the project was named Skykeep.+</details>++<details>+<summary><b>Design principles</b></summary>+<br>++- **Instant, always.** Every write shows the moment it's made and rolls back with a reason if Apple refuses it. No screen waits on the network to redraw.+- **Calm and familiar.** Each app looks and behaves like the Apple app you already know, with that app's colour: Notes yellow, Calendar red, the rest blue.+- **Your content, never decorated.** Glass and translucency on the chrome only; content stays crisp.+- **Motion that never flickers.** Large layers open instantly; nothing animates that the engine can't draw cleanly on every desktop.+- **Simple for a beginner, fast for an expert, open for a developer.**+</details>++## Contributing++Contributions are welcome, from a typo fix to a new feature. Start with **[CONTRIBUTING.md](.github/CONTRIBUTING.md)** for setup, the checks, and commit style.++- **New here?** Pick a [good first issue](https://github.com/YashwanthKamireddi/Skykeep/labels/good%20first%20issue).+- **Ideas and questions:** [Discussions](https://github.com/YashwanthKamireddi/Skykeep/discussions).+- **Found a bug?** [Open an issue](https://github.com/YashwanthKamireddi/Skykeep/issues/new/choose).+- **Packagers:** Nix, Fedora COPR, Debian, winget and Snap recipes are especially welcome.+- **Designers:** UI contributions are welcome. Open a Discussion with a mockup or screenshot first, and read the design principles above.++Before a pull request, run `./check.sh`: formatting, Clippy, Rust tests, TypeScript, and the interface suites in a real browser engine.++## Roadmap++| | |+|---|---|+| **Shipped** | Six apps on one engine · two-way sync · offline outbox · Export Everything · desktop search · quick capture · `.ics` / `.vcf` import · the Apple-only network allow-list |+| **Now** | First public release · AUR and Flathub · Windows out of beta · Photos out of preview |+| **Next** | Editing Notes tables · adding attachments to notes · locked notes · editing reminder tags and sections · offline edits for events · merging duplicate contacts · an accessibility pass |+| **Later** | Drive and Photos folders in Windows Explorer · calendar invitations · sharing |++Have an idea? Share it in [Discussions](https://github.com/YashwanthKamireddi/Skykeep/discussions/categories/ideas).++## Security++Please report vulnerabilities privately through [GitHub's private vulnerability reporting](https://github.com/YashwanthKamireddi/Skykeep/security/advisories/new), not in a public issue. See [SECURITY.md](SECURITY.md) for what Skykeep talks to, what it stores, and where.++## Support the project++Skykeep is free and open source, built by one person. If it saves you a browser tab every day, a star helps others find it.+<!-- Enable once GitHub Sponsors is approved:+You can also [sponsor its development](https://github.com/sponsors/YashwanthKamireddi).+-->++## License++Skykeep is free software, licensed under the [GNU General Public License v3.0](LICENSE).++**Not affiliated with Apple.** Skykeep is an independent project that works with iCloud. Apple, iCloud, iPhone and related marks are trademarks of Apple Inc.-## The honest part+## Acknowledgements-**Quince is not made by Apple, endorsed by Apple, or affiliated with Apple.** It reaches-iCloud through interfaces Apple has not published and does not support. Apple can change them-without notice, and when that happens something here will stop working until it is put right.+Skykeep stands on excellent open-source work, including [Tauri](https://tauri.app), [Rust](https://www.rust-lang.org) and its ecosystem ([Tokio](https://tokio.rs), [reqwest](https://github.com/seanmonstar/reqwest), [rusqlite](https://github.com/rusqlite/rusqlite), [fuser](https://github.com/cberner/fuser), [libheif](https://github.com/strukturag/libheif)), [React](https://react.dev), [ProseMirror](https://prosemirror.net), [Lucide](https://lucide.dev), [Vite](https://vite.dev) and [Playwright](https://playwright.dev). Thank you to everyone who maintains them.-**Your credentials never leave your computer.** Quince proves you know your password without-sending it, and keeps the result in your system keyring. There is no Quince account, no Quince-server, and nowhere else for any of this to go. A hosted version of this would be a bad idea-and will not be built.+<div align="center">+<br>-**Some things cannot be read by any client.** Health, Messages, Keychain, Home, Safari history-and Screen Time are encrypted end to end — Apple's own servers hold no key to them. Quince-shows them as unavailable rather than quietly leaving them out.+<a href="https://star-history.com/#YashwanthKamireddi/Skykeep&Date">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=YashwanthKamireddi/Skykeep&type=Date&theme=dark">+ <img alt="Star history of Skykeep" src="https://api.star-history.com/svg?repos=YashwanthKamireddi/Skykeep&type=Date" width="600">+ </picture>+</a>-**Advanced Data Protection.** With it switched on and web access off, iCloud's data is-encrypted the same way and Quince cannot read it either. It says so, and how web access is-turned on, rather than nudging anybody to turn the security feature itself off.+<br><br>-## Licence+Made with care by [Yashwanth Kamireddi](https://github.com/YashwanthKamireddi).-GPL-3.0-only. See [LICENSE](LICENSE).+</div>diff --git a/SECURITY.md b/SECURITY.mdindex 6612745..acbbe89 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -1,13 +1,13 @@# Security-Pomander asks for your Apple Account password. That is a lot of trust to ask of an app made by+Skykeep asks for your Apple Account password. That is a lot of trust to ask of an app made byone person, so this page says exactly what it does with it: what it talks to, what it keeps,and where. Every line here is true of the code in this repository; if one ever stops beingtrue, that is a bug, and a serious one.-## What Pomander talks to+## What Skykeep talks to-Apple, and nothing else:+Apple, and to calendars you subscribe to — nothing else:- `idmsa.apple.com` — signing in (Apple's own SRP sign-in and two-factor codes).- `setup.icloud.com`, `www.icloud.com` — opening the session and finding your services.@@ -15,8 +15,10 @@ Apple, and nothing else:iCloud Drive, Photos), `gateway.icloud.com` and `cvws.icloud-content.com` (downloads).- `calendars.icloud.com` — Apple's public holiday calendars.- The `.com.cn` equivalents of the above, for accounts in mainland China.+- The host of each calendar you subscribe to by address (Calendar ▸ + ▸ New Subscription…),+ and only once you have: a `webcal://` or `https://` address of a public calendar file.-This is enforced, not only promised: every network client Pomander makes is built by+This is enforced, not only promised: every network client Skykeep makes is built by`quince_auth::apple_only()`, whose resolver refuses to look up any host outside `apple.com`,`icloud.com` and `icloud-content.com` (and their `.com.cn` twins) — a request anywhere elsefails before a connection exists. A URL that names an address instead of a host@@ -24,8 +26,17 @@ fails before a connection exists. A URL that names an address instead of a hostincluded: anything that is not Apple's by name (or this computer, `127.0.0.1`) is refused thesame way. The test `crates/quince-auth/tests/apple_only.rs` holds it to that.-There are no Pomander servers. There is no telemetry, analytics, crash reporting or update-check. Nothing is sent anywhere but Apple, and only what is needed to show and change your+A subscribed calendar is fetched by a separate client, `quince_auth::listed_only()`, built for+each fetch with exactly the hosts of the addresses you subscribed to — the same two locks, a+resolver that looks up no other name and a check of every request's URL and redirect, so it+can reach those hosts and nothing else (`listed_tests` in `crates/quince-auth/src/lib.rs`).+Apple's client is not widened by it. A new install subscribes to nothing, so until you add a+subscription Skykeep contacts no host but Apple's. A subscription is read-only: nothing is+ever sent to it but the request for its file, and no Apple data goes with that request.++There are no Skykeep servers. There is no telemetry, analytics, crash reporting or update+check. Nothing is sent anywhere but Apple (and the requests for the calendars you subscribe+to), and only what is needed to show and change yourown data. The window itself cannot reach the network at all: its content security policy(`src-tauri/tauri.conf.json`) lets it talk only to the app's own Rust side, which does alltalking to Apple.@@ -33,9 +44,9 @@ talking to Apple.Links you click in a note or an event open in your own browser, mail or map app; a photo'splace opens in this computer's own map app (a `geo:` link), never a website.-## What Pomander keeps, and where+## What Skykeep keeps, and where-Everything is in your user's data folder (`~/.local/share/io.github.yashwanthkamireddi.Pomander` on Linux),+Everything is in your user's data folder (`~/.local/share/io.github.yashwanthkamireddi.Skykeep` on Linux),which is readable by you alone (mode 700):- **Your password, Apple Account and session tokens:** in the system keyring (GNOME@@ -45,10 +56,10 @@ which is readable by you alone (mode 700):- **Session cookies:** `cookies.json`, readable by you alone (mode 600).- **Your library:** `library.db` (SQLite) — notes, reminders, events, contacts, the Driveand Photos listings — and caches of pictures and files you opened. These are not encrypted- by Pomander; use full-disk encryption, as you would for the same data on a Mac.+ by Skykeep; use full-disk encryption, as you would for the same data on a Mac.Signing out asks whether to keep a copy on this computer. Removing it deletes the library,-its caches and Pomander's file-manager thumbnails. Another Apple Account signing in never sees+its caches and Skykeep's file-manager thumbnails. Another Apple Account signing in never seesthe last one's data: each account's library is set aside whole and brought back only forthat account.@@ -56,14 +67,14 @@ that account.- **Videos** are played from a server on `127.0.0.1` only (WebKitGTK's player reads onlyhttp). It answers only a request that carries a secret made fresh at every start and given- to Pomander's window alone, is addressed to `127.0.0.1:<its port>` (so a web page that+ to Skykeep's window alone, is addressed to `127.0.0.1:<its port>` (so a web page thatrebinds its own name to this computer is refused), and carries no web page's `Origin`. Itsends no CORS headers. Another program or user on this computer, or a page in your browser,cannot read your videos from it.-- **Pictures** reach the window through Pomander's own `quince://` scheme, which only- Pomander's windows can load. Every id in it is checked to be an id — letters, digits,- dashes — before it names a file, so no request reads anything outside Pomander's caches.-- **The window** loads only Pomander's own bundled page, never a website, and may ask+- **Pictures** reach the window through Skykeep's own `quince://` scheme, which only+ Skykeep's windows can load. Every id in it is checked to be an id — letters, digits,+ dashes — before it names a file, so no request reads anything outside Skykeep's caches.+- **The window** loads only Skykeep's own bundled page, never a website, and may askTauri for no more than it uses: events, its version, a window title, and the open and savedialogs.- **A note's attachment** you open is saved under a cleaned-up name (never a path, a hidden@@ -77,7 +88,7 @@ that account.## Advanced Data ProtectionWith Advanced Data Protection on and "Access iCloud Data on the Web" off, Apple does not-let any app outside your devices read your iCloud data, Pomander included. Pomander says so+let any app outside your devices read your iCloud data, Skykeep included. Skykeep says soplainly and shows the switch; it does not work around it.## Reporting a vulnerabilitydiff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rsindex 4bc791d..22a47e7 100644--- a/crates/quince-auth/src/lib.rs+++ b/crates/quince-auth/src/lib.rs@@ -107,7 +107,7 @@ pub enum Error {BadCode,#[error("Apple didn't return a trust token, so this session wouldn't survive a restart")]NoTrustToken,- #[error("this account signs in a way Pomander can't handle yet ({0})")]+ #[error("this account signs in a way Skykeep can't handle yet ({0})")]UnsupportedAccount(String),/// Said without the address, which carries account and client ids.#[error("couldn't reach Apple: {}", if .0.is_timeout() { "it took too long to answer" } else if .0.is_connect() { "check your connection" } else { "the connection dropped" })]@@ -1046,7 +1046,7 @@ impl Client {}/// Whether `host` is Apple's: its sign-in, iCloud's services and their files, push, and their-/// China-mainland twins — every host Pomander has any reason to reach. Loopback too, which is+/// China-mainland twins — every host Skykeep has any reason to reach. Loopback too, which is/// this computer.#[must_use]pub fn is_apple_host(host: &str) -> bool {@@ -1065,10 +1065,10 @@ pub fn is_apple_host(host: &str) -> bool {.any(|d| host == *d || host.ends_with(&format!(".{d}")))}-/// Every HTTP client Pomander makes starts here: Apple's servers, and nothing else, can be+/// Every HTTP client Skykeep makes starts here: Apple's servers, and nothing else, can be/// reached at all (see [`AppleOnly`]).pub fn apple_only() -> reqwest::ClientBuilder {- let mut builder = HttpClient::builder()+ let builder = HttpClient::builder().dns_resolver(Arc::new(AppleOnly))// The resolver alone is not enough: a URL with an address in it (`https://1.2.3.4/`)// is never looked up, and through a proxy the proxy looks the name up, not us. So@@ -1080,6 +1080,12 @@ pub fn apple_only() -> reqwest::ClientBuilder {}));// Setting a proxy turns off the system's own (`HTTPS_PROXY` and the rest), which Apple's// hosts still go through when one is set, as they did before.+ with_system_proxies(builder)+}++/// The system's own proxies (`HTTPS_PROXY` and the rest), put back after a refusing proxy has+/// turned them off.+fn with_system_proxies(mut builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {for (scheme, names) in [("https",@@ -1104,8 +1110,59 @@ pub fn apple_only() -> reqwest::ClientBuilder {builder}+/// The client for calendars the person subscribed to by address — and for nothing else. It+/// reaches exactly the hosts in `hosts` (the ones those addresses name), by the same two locks+/// as [`apple_only`]: a resolver that looks up no other name, and a check of every request's+/// own URL, a redirect's included, so an address or a proxy cannot carry it anywhere else.+/// Apple's own client is not widened by it; nothing else in Skykeep uses this one.+pub fn listed_only(hosts: &[String]) -> reqwest::ClientBuilder {+ let listed: Arc<Vec<String>> = Arc::new(hosts.iter().map(|h| normal_host(h)).collect());+ let check = Arc::clone(&listed);+ let builder = HttpClient::builder()+ .dns_resolver(Arc::new(ListedOnly(Arc::clone(&listed))))+ .redirect(reqwest::redirect::Policy::limited(5))+ .proxy(reqwest::Proxy::custom(move |url| {+ (!url_is_listed(url, &check)).then(|| REFUSED.to_string())+ }));+ with_system_proxies(builder)+}++fn normal_host(host: &str) -> String {+ host.trim_end_matches('.')+ .trim_start_matches('[')+ .trim_end_matches(']')+ .to_ascii_lowercase()+}++/// Whether a request's URL names one of the listed hosts exactly.+fn url_is_listed(url: &reqwest::Url, listed: &[String]) -> bool {+ url.host_str()+ .is_some_and(|h| listed.iter().any(|l| *l == normal_host(h)))+}++/// The subscribed-calendar client's resolver: a listed host is looked up as the system looks+/// up any name; any other is never looked up at all.+struct ListedOnly(Arc<Vec<String>>);++impl reqwest::dns::Resolve for ListedOnly {+ fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {+ let host = normal_host(name.as_str());+ let allowed = self.0.contains(&host);+ Box::pin(async move {+ if !allowed {+ let refused: Box<dyn std::error::Error + Send + Sync> =+ format!("{host} is not a calendar you subscribed to").into();+ return Err(refused);+ }+ let found = tokio::net::lookup_host((host.as_str(), 0)).await?;+ let addrs: reqwest::dns::Addrs = Box::new(found.collect::<Vec<_>>().into_iter());+ Ok(addrs)+ })+ }+}+/// Where a request that is not Apple's is pointed: a name the resolver refuses.-const REFUSED: &str = "http://refused.pomander.invalid";+const REFUSED: &str = "http://refused.skykeep.invalid";/// Whether a request's URL may be sent: an Apple host by name, or this computer.fn url_is_apples(url: &reqwest::Url) -> bool {@@ -1122,7 +1179,7 @@ fn url_is_apples(url: &reqwest::Url) -> bool {}}-/// The one way Pomander's client finds a server: a host that is not Apple's is never looked+/// The one way Skykeep's client finds a server: a host that is not Apple's is never looked/// up, so no request can reach one — "talks only to Apple" is how the code works, not a promise/// about it. Apple's are looked up as the system looks up any name.struct AppleOnly;@@ -1133,7 +1190,7 @@ impl reqwest::dns::Resolve for AppleOnly {Box::pin(async move {if !is_apple_host(&host) {let refused: Box<dyn std::error::Error + Send + Sync> =- format!("{host} is not Apple's, and Pomander talks only to Apple").into();+ format!("{host} is not Apple's, and Skykeep talks only to Apple").into();return Err(refused);}let found = tokio::net::lookup_host((host.as_str(), 0)).await?;@@ -1143,6 +1200,43 @@ impl reqwest::dns::Resolve for AppleOnly {}}+#[cfg(test)]+mod listed_tests {+ use super::*;++ /// A subscribed calendar's client reaches its own hosts and refuses every other — by+ /// name, by address, and Apple's too — before anything leaves the machine.+ #[tokio::test]+ async fn the_subscription_client_refuses_a_host_nobody_subscribed_to() {+ let http = listed_only(&["calendar.example.org".into()])+ .build()+ .unwrap();+ for url in [+ "https://elsewhere.example.net/feed.ics",+ "https://93.184.216.34/feed.ics",+ "https://www.icloud.com/",+ ] {+ let err = http.get(url).send().await.expect_err(url);+ let text = format!("{err:?}");+ assert!(+ text.contains("not a calendar you subscribed to"),+ "{url} was not refused by the list: {text}"+ );+ }+ }++ #[test]+ fn a_listed_host_is_matched_exactly_and_without_case() {+ let listed = vec![normal_host("Calendar.Example.org.")];+ let ok = |u: &str| url_is_listed(&reqwest::Url::parse(u).unwrap(), &listed);+ assert!(ok("https://calendar.example.org/a.ics"));+ assert!(ok("http://CALENDAR.example.org:8080/a.ics"));+ assert!(!ok("https://evil.calendar.example.org/a.ics"));+ assert!(!ok("https://example.org/a.ics"));+ assert!(!ok("https://calendar.example.org.evil.net/a.ics"));+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/quince-auth/src/session.rs b/crates/quince-auth/src/session.rsindex ab790a9..017fd17 100644--- a/crates/quince-auth/src/session.rs+++ b/crates/quince-auth/src/session.rs@@ -14,7 +14,8 @@ const KEYRING_ENTRY: &str = "session";/// session may still be under, and the folders `src-tauri/src/migrate.rs` moves. The current/// identifier is never written here — it is tauri.conf.json's. Renaming the app means adding/// the identifier being replaced to the front of this list.-pub const PREVIOUS_IDENTIFIERS: &[&str] = &["dev.quince.client"];+pub const PREVIOUS_IDENTIFIERS: &[&str] =+ &["io.github.yashwanthkamireddi.Pomander", "dev.quince.client"];/// The keyring services: the one the session is kept under (the app's identifier), and the/// ones it was kept under before — read when the current one holds nothing, moved acrossdiff --git a/crates/quince-auth/tests/apple_only.rs b/crates/quince-auth/tests/apple_only.rsindex 47b9d16..f7f5f19 100644--- a/crates/quince-auth/tests/apple_only.rs+++ b/crates/quince-auth/tests/apple_only.rs@@ -1,4 +1,4 @@-//! Pomander talks only to Apple, by construction: the client cannot resolve, so cannot reach,+//! Skykeep talks only to Apple, by construction: the client cannot resolve, so cannot reach,//! any host that is not Apple's.#[test]@@ -38,7 +38,7 @@ async fn a_client_refuses_anything_but_apple_before_connecting() {.expect_err("a request to a host that is not Apple's");let said = format!("{err:?}");assert!(- said.contains("Pomander talks only to Apple"),+ said.contains("Skykeep talks only to Apple"),"refused by the resolver, not the network: {said}");}@@ -57,7 +57,7 @@ async fn an_address_is_refused_as_a_name_is() {] {let err = client.get(url).send().await.expect_err(url);assert!(- format!("{err:?}").contains("Pomander talks only to Apple"),+ format!("{err:?}").contains("Skykeep talks only to Apple"),"{url}: {err:?}");}@@ -74,6 +74,7 @@ async fn an_address_is_refused_as_a_name_is() {let ok = client.get(format!("{}/ok", server.uri())).send().await;assert_eq!(ok.unwrap().status(), 200);let away = client.get(format!("{}/away", server.uri())).send().await;- assert!(format!("{:?}", away.expect_err("redirected away"))- .contains("Pomander talks only to Apple"));+ assert!(+ format!("{:?}", away.expect_err("redirected away")).contains("Skykeep talks only to Apple")+ );}diff --git a/crates/quince-core/src/calendar.rs b/crates/quince-core/src/calendar.rsindex 3c9df20..6f9e430 100644--- a/crates/quince-core/src/calendar.rs+++ b/crates/quince-core/src/calendar.rs@@ -203,32 +203,59 @@ impl Library {/// 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>> {+ self.search_events_near(query, now())+ }++ /// The same, read in one pass over the table — a lookup per event made a large account's+ /// search wait — and, when there are more than are kept, the ones nearest `now`: kept+ /// oldest first, an account with years behind it found nothing that is still to come.+ pub fn search_events_near(&self, query: &str, now: i64) -> Result<Vec<Event>> {+ const KEPT: usize = 300;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)+ let mut stmt = self.conn.prepare(+ "SELECT guid, calendar_guid, title, location, starts_at, ends_at, all_day,+ timezone, url, notes, etag+ FROM events",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(Event {+ guid: row.get(0)?,+ calendar_guid: row.get(1)?,+ title: row.get(2)?,+ location: row.get(3)?,+ starts_at: row.get(4)?,+ ends_at: row.get(5)?,+ all_day: row.get::<_, i64>(6)? != 0,+ timezone: row.get(7)?,+ url: row.get(8)?,+ notes: row.get(9)?,+ etag: row.get(10)?,})- .collect();+ })?;+ let mut found = Vec::new();+ for e in rows {+ let e = e?;+ let text = [+ Some(e.title.as_str()),+ e.location.as_deref(),+ e.notes.as_deref(),+ ]+ .into_iter()+ .flatten()+ .collect::<Vec<_>>()+ .join(" ");+ if crate::fold::holds_all(&crate::fold::fold(&text), &words) {+ found.push(e);+ }+ }+ if found.len() > KEPT {+ found.sort_by_key(|e| (e.ends_at.max(e.starts_at) - now).abs());+ found.truncate(KEPT);+ }found.sort_by_key(|e| e.starts_at);- found.truncate(200);Ok(found)}@@ -476,4 +503,42 @@ mod search_tests {);assert!(titles(" ").is_empty());}++ /// Years of a weekly meeting: what is kept is around now, not the oldest few hundred.+ #[test]+ fn a_long_history_keeps_the_matches_nearest_now() {+ 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 week = 7 * 86_400;+ let events: Vec<Event> = (0..1000)+ .map(|i| Event {+ guid: format!("s{i}"),+ calendar_guid: "c".into(),+ title: "Standup".into(),+ starts_at: i * week,+ ends_at: i * week + 900,+ ..Default::default()+ })+ .collect();+ lib.put_events(&events).unwrap();+ let now = 900 * week;+ let found = lib.search_events_near("standup", now).unwrap();+ assert_eq!(found.len(), 300);+ assert!(+ found.iter().any(|e| e.starts_at == now),+ "this week's is found"+ );+ assert!(+ found.iter().any(|e| e.starts_at == 999 * week),+ "the last one is found"+ );+ assert!(found.windows(2).all(|w| w[0].starts_at <= w[1].starts_at));+ }}diff --git a/crates/quince-core/src/export.rs b/crates/quince-core/src/export.rsnew file mode 100644index 0000000..c0805e0--- /dev/null+++ b/crates/quince-core/src/export.rs@@ -0,0 +1,179 @@+//! Whole-library reads for Export Everything: every row of a kind, unfiltered and unlimited.+//!+//! The screens' own reads are shaped for screens — a thousand at most, enabled calendars only,+//! no note bodies in a list. An export wants the opposite: everything the library holds, once.++use crate::calendar::Event;+use crate::drive::DriveItem;+use crate::notes::Note;+use crate::reminders::Reminder;+use crate::{Library, Result};++/// A photo as an export needs it: where its picture is kept, when it was taken, its name.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ExportPhoto {+ pub id: String,+ pub taken_at: i64,+ pub filename: Option<String>,+ /// `image`, `video` …, as the library stores it.+ pub kind: String,+}++impl Library {+ /// Every note, Recently Deleted too, with its whole body and its runs (JSON), oldest first.+ pub fn export_notes(&self) -> Result<Vec<Note>> {+ let mut stmt = self.conn.prepare(+ "SELECT guid, folder_guid, title, snippet, body, locked, pinned,+ created_at, modified_at, editable, etag, runs+ FROM notes ORDER BY created_at, guid",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(Note {+ guid: row.get(0)?,+ folder_guid: row.get(1)?,+ title: row.get(2)?,+ snippet: row.get(3)?,+ body: row.get(4)?,+ locked: row.get::<_, i64>(5)? != 0,+ pinned: row.get::<_, i64>(6)? != 0,+ created_at: row.get(7)?,+ modified_at: row.get(8)?,+ editable: row.get::<_, i64>(9)? != 0,+ etag: row.get(10)?,+ runs: row.get(11)?,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// Every reminder in every list, done ones too, without Apple's raw record.+ pub fn export_reminders(&self) -> Result<Vec<Reminder>> {+ let mut stmt = self.conn.prepare(+ "SELECT guid, list_guid, title, notes, due_at, completed_at, priority, flagged,+ parent_guid, recur_frequency, recur_interval, etag, timezone, section_guid,+ all_day+ FROM reminders ORDER BY list_guid, completed_at IS NOT NULL, due_at, title, guid",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(Reminder {+ guid: row.get(0)?,+ list_guid: row.get(1)?,+ title: row.get(2)?,+ notes: row.get(3)?,+ due_at: row.get(4)?,+ completed_at: row.get(5)?,+ priority: row.get(6)?,+ flagged: row.get::<_, i64>(7)? != 0,+ parent_guid: row.get(8)?,+ recur_frequency: row.get(9)?,+ recur_interval: row.get(10)?,+ etag: row.get(11)?,+ raw: None,+ timezone: row.get(12)?,+ section_guid: row.get(13)?,+ all_day: row.get::<_, i64>(14)? != 0,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// Every event the library holds, in every calendar, shown or hidden, by start.+ pub fn export_events(&self) -> Result<Vec<Event>> {+ let mut stmt = self.conn.prepare(+ "SELECT guid, calendar_guid, title, location, starts_at, ends_at, all_day,+ timezone, url, notes, etag+ FROM events ORDER BY calendar_guid, starts_at, guid",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(Event {+ guid: row.get(0)?,+ calendar_guid: row.get(1)?,+ title: row.get(2)?,+ location: row.get(3)?,+ starts_at: row.get(4)?,+ ends_at: row.get(5)?,+ all_day: row.get::<_, i64>(6)? != 0,+ timezone: row.get(7)?,+ url: row.get(8)?,+ notes: row.get(9)?,+ etag: row.get(10)?,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// Every Drive item the library has listed, in every folder it has read.+ pub fn export_drive_items(&self) -> Result<Vec<DriveItem>> {+ let mut stmt = self.conn.prepare(+ "SELECT drivewsid, parent_id, name, extension, kind, size, child_count,+ created_at, modified_at, etag+ FROM drive_items ORDER BY drivewsid",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(DriveItem {+ drivewsid: row.get(0)?,+ parent_id: row.get(1)?,+ name: row.get(2)?,+ extension: row.get(3)?,+ kind: row.get(4)?,+ size: row.get(5)?,+ child_count: row.get(6)?,+ created_at: row.get(7)?,+ modified_at: row.get(8)?,+ etag: row.get(9)?,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }++ /// Every photo and video not in Recently Deleted — hidden ones and every shot of a burst+ /// included — oldest first.+ pub fn export_photos(&self) -> Result<Vec<ExportPhoto>> {+ let mut stmt = self.conn.prepare(+ "SELECT id, taken_at, filename, kind FROM photos+ WHERE deleted = 0 ORDER BY taken_at, id",+ )?;+ let rows = stmt.query_map([], |row| {+ Ok(ExportPhoto {+ id: row.get(0)?,+ taken_at: row.get(1)?,+ filename: row.get(2)?,+ kind: row.get(3)?,+ })+ })?;+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::reminders::ReminderList;++ #[test]+ fn reads_everything_past_the_screens_limits() {+ let mut lib = Library::in_memory().unwrap();+ lib.put_reminder_lists(&[ReminderList {+ guid: "L".into(),+ title: "List".into(),+ enabled: true,+ ..Default::default()+ }])+ .unwrap();+ let many: Vec<Reminder> = (0..1_200)+ .map(|i| Reminder {+ guid: format!("R{i}"),+ list_guid: "L".into(),+ title: format!("r{i}"),+ completed_at: (i % 2 == 0).then_some(1),+ ..Default::default()+ })+ .collect();+ lib.put_reminders(&many).unwrap();+ assert_eq!(lib.export_reminders().unwrap().len(), 1_200);+ assert!(lib.export_notes().unwrap().is_empty());+ assert!(lib.export_events().unwrap().is_empty());+ assert!(lib.export_drive_items().unwrap().is_empty());+ assert!(lib.export_photos().unwrap().is_empty());+ }+}diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rsindex 5c19891..f4eca6b 100644--- a/crates/quince-core/src/lib.rs+++ b/crates/quince-core/src/lib.rs@@ -8,6 +8,7 @@ pub mod alarms;pub mod calendar;pub mod contacts;pub mod drive;+pub mod export;pub mod fold;pub mod health;pub mod notes;diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rsindex d0436f4..ebd26b6 100644--- a/crates/quince-icloud/src/calendar.rs+++ b/crates/quince-icloud/src/calendar.rs@@ -287,7 +287,7 @@ fn refusal(path: &str, status: reqwest::StatusCode, body: &str) -> Error {401 | 403 => Error::Refused("iCloud won't let this calendar be changed from here — it may be read-only.".into(),),- 429 => Error::Refused("iCloud asked Pomander to slow down. Try again in a minute.".into()),+ 429 => Error::Refused("iCloud asked Skykeep to slow down. Try again in a minute.".into()),500..=599 => Error::Refused("iCloud's calendar isn't answering right now. Nothing was changed — try again in a moment.".into(),diff --git a/crates/quince-icloud/src/calendar_feeds.rs b/crates/quince-icloud/src/calendar_feeds.rsnew file mode 100644index 0000000..e2b4c20--- /dev/null+++ b/crates/quince-icloud/src/calendar_feeds.rs@@ -0,0 +1,1209 @@+//! Calendars subscribed to by address — a school's timetable, a team's fixtures, a trip — as+//! Calendar's New Calendar Subscription reads them: an iCalendar file fetched from where it is+//! published, read-only, refreshed now and then, its repeating events laid out day by day.+//!+//! Nothing here is Apple's. The file is fetched with a client that can reach the hosts the+//! person subscribed to and nothing else (`quince_auth::listed_only`), and only once they have.++use crate::{Error, Result};+use jiff::civil::{Date, DateTime, Time, Weekday};+use jiff::tz::TimeZone;+use jiff::{Span, Timestamp, ToSpan};+use quince_core::calendar::{Calendar, Event};+use serde::{Deserialize, Serialize};++/// Where a subscription's calendar guid begins; the rest is the subscription's own id.+pub const PREFIX: &str = "quince:sub:";++/// The largest file a subscription is read from. A sports season is a few hundred kilobytes;+/// a server sending more than this is sending something else.+pub const MOST_BYTES: usize = 25 * 1024 * 1024;++/// One calendar subscribed to by address, as it is kept on this computer.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct Subscription {+ pub id: String,+ /// The address it is fetched from, `webcal://` already read as `https://`.+ pub url: String,+ pub title: String,+ pub colour: String,+ /// How often it is fetched again, in minutes; 0 for never on its own.+ pub refresh_minutes: u32,+ /// When it was last fetched whole, unix seconds.+ #[serde(default)]+ pub fetched_at: Option<i64>,+ /// Why the last fetch did not land, in words; cleared by the next that does.+ #[serde(default)]+ pub problem: Option<String>,+}++impl Subscription {+ /// The calendar its events are drawn in.+ #[must_use]+ pub fn calendar_guid(&self) -> String {+ format!("{PREFIX}{}", self.id)+ }++ /// As the sidebar lists it: read-only, after the account's own calendars.+ #[must_use]+ pub fn calendar(&self, order: i64) -> Calendar {+ Calendar {+ guid: self.calendar_guid(),+ title: self.title.clone(),+ colour: Some(self.colour.clone()),+ ctag: None,+ sort_order: 800 + order,+ enabled: true,+ writable: false,+ is_default: false,+ }+ }++ /// Whether it is due a fetch at `now`.+ #[must_use]+ pub fn due(&self, now: i64) -> bool {+ self.refresh_minutes > 0+ && self+ .fetched_at+ .is_none_or(|t| now - t >= i64::from(self.refresh_minutes) * 60)+ }+}++/// An address as typed, made one that can be fetched: `webcal://` is `https://`, as Calendar+/// reads it; a bare `example.com/a.ics` is `https://` too. Only web addresses are taken.+pub fn normalise_url(raw: &str) -> Result<reqwest::Url> {+ let raw = raw.trim();+ let lower = raw.to_ascii_lowercase();+ let fixed = if let Some(rest) = lower+ .strip_prefix("webcals://")+ .or_else(|| lower.strip_prefix("webcal://"))+ {+ format!("https://{}", &raw[raw.len() - rest.len()..])+ } else if lower.starts_with("http://") || lower.starts_with("https://") {+ raw.to_string()+ } else if raw.contains("://") {+ return Err(Error::Refused(+ "That address isn’t a web address. Use one that begins with webcal:// or https://."+ .into(),+ ));+ } else {+ format!("https://{raw}")+ };+ let url = reqwest::Url::parse(&fixed).map_err(|_| {+ Error::Refused("That address can’t be read. Check it and try again.".into())+ })?;+ if url.host_str().is_none_or(str::is_empty) {+ return Err(Error::Refused(+ "That address has no server in it. Check it and try again.".into(),+ ));+ }+ if !url.username().is_empty() || url.password().is_some() {+ return Err(Error::Refused(+ "Subscriptions are to public calendars; that address carries a password.".into(),+ ));+ }+ Ok(url)+}++/// The host an address names, as the subscription client lists it.+#[must_use]+pub fn host_of(url: &str) -> Option<String> {+ reqwest::Url::parse(url)+ .ok()?+ .host_str()+ .map(|h| h.trim_matches(['[', ']']).to_ascii_lowercase())+}++/// Fetch a subscription's file. The client is the one that reaches subscribed hosts alone.+pub async fn fetch(http: &reqwest::Client, url: &str) -> Result<String> {+ let mut response = http.get(url).send().await?;+ let status = response.status();+ if !status.is_success() {+ return Err(Error::Refused(match status.as_u16() {+ 401 | 403 => "That calendar is private. Subscriptions are to public calendars.".into(),+ 404 | 410 => "There’s no calendar at that address any more.".into(),+ _ => format!(+ "The server didn’t send the calendar (it answered {}).",+ status.as_u16()+ ),+ }));+ }+ let mut bytes: Vec<u8> = Vec::new();+ while let Some(chunk) = response.chunk().await? {+ if bytes.len() + chunk.len() > MOST_BYTES {+ return Err(Error::Refused(+ "That file is too large to be a calendar.".into(),+ ));+ }+ bytes.extend_from_slice(&chunk);+ }+ let text = if bytes.starts_with(&[0x1f, 0x8b]) {+ use std::io::Read;+ let mut out = String::new();+ flate2::read::GzDecoder::new(&bytes[..])+ .take(MOST_BYTES as u64)+ .read_to_string(&mut out)+ .map_err(|_| Error::Refused("That calendar file couldn’t be opened.".into()))?;+ out+ } else {+ String::from_utf8_lossy(&bytes).into_owned()+ };+ if !text.contains("BEGIN:VCALENDAR") {+ return Err(Error::Refused(+ "There’s no calendar at that address — it sent a web page or another file.".into(),+ ));+ }+ Ok(text)+}++/* ---- reading the file --------------------------------------------------------------- */++#[derive(Debug, Clone)]+struct Property {+ name: String,+ params: Vec<(String, String)>,+ value: String,+}++impl Property {+ fn param(&self, name: &str) -> Option<&str> {+ self.params+ .iter()+ .find(|(k, _)| k.eq_ignore_ascii_case(name))+ .map(|(_, v)| v.as_str())+ }+}++fn unfold(text: &str) -> Vec<String> {+ let mut lines: Vec<String> = Vec::new();+ for raw in text.split('\n') {+ let raw = raw.strip_suffix('\r').unwrap_or(raw);+ if let Some(rest) = raw.strip_prefix([' ', '\t']) {+ if let Some(last) = lines.last_mut() {+ last.push_str(rest);+ continue;+ }+ }+ if !raw.is_empty() {+ lines.push(raw.to_string());+ }+ }+ lines+}++/// `NAME;P=v;Q="a:b":value`, a colon inside a quoted parameter not ending the name.+fn property(line: &str) -> Option<Property> {+ let mut quoted = false;+ let mut split = None;+ for (i, c) in line.char_indices() {+ match c {+ '"' => quoted = !quoted,+ ':' if !quoted => {+ split = Some(i);+ break;+ }+ _ => {}+ }+ }+ let at = split?;+ let (head, value) = (&line[..at], &line[at + 1..]);+ let mut parts = head.split(';');+ let name = parts.next()?.trim().to_ascii_uppercase();+ let params = parts+ .filter_map(|p| p.split_once('='))+ .map(|(k, v)| {+ (+ k.trim().to_ascii_uppercase(),+ v.trim().trim_matches('"').to_string(),+ )+ })+ .collect();+ Some(Property {+ name,+ params,+ value: value.to_string(),+ })+}++fn unescape(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut chars = s.chars();+ while let Some(c) = chars.next() {+ if c != '\\' {+ out.push(c);+ continue;+ }+ match chars.next() {+ Some('n' | 'N') => out.push('\n'),+ Some(other) => out.push(other),+ None => {}+ }+ }+ out+}++/// When something happens, as the file writes it.+#[derive(Debug, Clone, PartialEq)]+enum When {+ /// A date: an all-day event.+ Day(Date),+ /// A clock time in a zone (UTC for a time written with `Z`).+ At(DateTime, TimeZone),+}++fn parse_date(s: &str) -> Option<Date> {+ let s = s.trim();+ if s.len() < 8 || !s.as_bytes()[..8].iter().all(u8::is_ascii_digit) {+ return None;+ }+ Date::new(+ s[0..4].parse().ok()?,+ s[4..6].parse().ok()?,+ s[6..8].parse().ok()?,+ )+ .ok()+}++fn parse_datetime(s: &str) -> Option<(DateTime, bool)> {+ let s = s.trim();+ let (d, t) = s.split_once(['T', 't'])?;+ let date = parse_date(d)?;+ let utc = t.ends_with(['Z', 'z']);+ let t = t.trim_end_matches(['Z', 'z']);+ if t.len() < 4 || !t.bytes().all(|b| b.is_ascii_digit()) {+ return None;+ }+ let second: i8 = t.get(4..6).map_or(Some(0), |x| x.parse().ok())?;+ let time = Time::new(+ t[0..2].parse().ok()?,+ t[2..4].parse().ok()?,+ second.min(59),+ 0,+ )+ .ok()?;+ Some((date.to_datetime(time), utc))+}++/// A `TZID` this computer knows: an IANA name, one inside a longer id+/// (`/mozilla.org/20050126_1/Europe/Berlin`), or one of the Windows names Outlook writes.+fn zone_named(tzid: &str) -> Option<TimeZone> {+ let tzid = tzid.trim().trim_matches('"').trim_start_matches('/');+ if let Ok(tz) = TimeZone::get(tzid) {+ return Some(tz);+ }+ let segments: Vec<&str> = tzid.split('/').collect();+ for start in 1..segments.len() {+ if let Ok(tz) = TimeZone::get(&segments[start..].join("/")) {+ return Some(tz);+ }+ }+ WINDOWS_ZONES+ .iter()+ .find(|(w, _)| w.eq_ignore_ascii_case(tzid))+ .and_then(|(_, iana)| TimeZone::get(iana).ok())+}++/// Windows' zone names, as Outlook and Exchange publish them (CLDR's windowsZones, "001").+const WINDOWS_ZONES: &[(&str, &str)] = &[+ ("UTC", "UTC"),+ ("GMT Standard Time", "Europe/London"),+ ("Greenwich Standard Time", "Atlantic/Reykjavik"),+ ("W. Europe Standard Time", "Europe/Berlin"),+ ("Romance Standard Time", "Europe/Paris"),+ ("Central Europe Standard Time", "Europe/Budapest"),+ ("Central European Standard Time", "Europe/Warsaw"),+ ("E. Europe Standard Time", "Europe/Chisinau"),+ ("FLE Standard Time", "Europe/Kiev"),+ ("GTB Standard Time", "Europe/Bucharest"),+ ("Russian Standard Time", "Europe/Moscow"),+ ("Turkey Standard Time", "Europe/Istanbul"),+ ("Israel Standard Time", "Asia/Jerusalem"),+ ("South Africa Standard Time", "Africa/Johannesburg"),+ ("Egypt Standard Time", "Africa/Cairo"),+ ("Arabian Standard Time", "Asia/Dubai"),+ ("Arab Standard Time", "Asia/Riyadh"),+ ("Pakistan Standard Time", "Asia/Karachi"),+ ("India Standard Time", "Asia/Kolkata"),+ ("Sri Lanka Standard Time", "Asia/Colombo"),+ ("Nepal Standard Time", "Asia/Kathmandu"),+ ("Bangladesh Standard Time", "Asia/Dhaka"),+ ("SE Asia Standard Time", "Asia/Bangkok"),+ ("Singapore Standard Time", "Asia/Singapore"),+ ("China Standard Time", "Asia/Shanghai"),+ ("Taipei Standard Time", "Asia/Taipei"),+ ("Tokyo Standard Time", "Asia/Tokyo"),+ ("Korea Standard Time", "Asia/Seoul"),+ ("AUS Eastern Standard Time", "Australia/Sydney"),+ ("E. Australia Standard Time", "Australia/Brisbane"),+ ("W. Australia Standard Time", "Australia/Perth"),+ ("New Zealand Standard Time", "Pacific/Auckland"),+ ("Hawaiian Standard Time", "Pacific/Honolulu"),+ ("Alaskan Standard Time", "America/Anchorage"),+ ("Pacific Standard Time", "America/Los_Angeles"),+ ("Mountain Standard Time", "America/Denver"),+ ("US Mountain Standard Time", "America/Phoenix"),+ ("Central Standard Time", "America/Chicago"),+ ("Eastern Standard Time", "America/New_York"),+ ("Atlantic Standard Time", "America/Halifax"),+ ("Newfoundland Standard Time", "America/St_Johns"),+ ("E. South America Standard Time", "America/Sao_Paulo"),+ ("Argentina Standard Time", "America/Buenos_Aires"),+ ("Mexico Standard Time", "America/Mexico_City"),+];++/// A date or date-time property, read in `here` when it floats (no zone given).+fn when_of(p: &Property, here: &TimeZone) -> Option<When> {+ when_value(&p.value, p, here)+}++fn when_value(value: &str, p: &Property, here: &TimeZone) -> Option<When> {+ let date_only = p+ .param("VALUE")+ .is_some_and(|v| v.eq_ignore_ascii_case("DATE"))+ || (value.trim().len() == 8 && !value.contains(['T', 't']));+ if date_only {+ return parse_date(value).map(When::Day);+ }+ let (dt, utc) = parse_datetime(value)?;+ let zone = if utc {+ TimeZone::UTC+ } else {+ p.param("TZID")+ .and_then(zone_named)+ .unwrap_or_else(|| here.clone())+ };+ Some(When::At(dt, zone))+}++/// An iCalendar duration in seconds: `PT1H30M`, `-P1D`, `P2W`.+fn duration(s: &str) -> Option<i64> {+ let s = s.trim();+ let (sign, s) = match s.as_bytes().first()? {+ b'-' => (-1, &s[1..]),+ b'+' => (1, &s[1..]),+ _ => (1, s),+ };+ let s = s.strip_prefix(['P', 'p'])?;+ let mut total = 0i64;+ let mut number = String::new();+ let mut in_time = false;+ let mut any = false;+ for c in s.chars() {+ match c.to_ascii_uppercase() {+ '0'..='9' => number.push(c),+ 'T' => in_time = true,+ unit => {+ let n: i64 = number.parse().ok()?;+ number.clear();+ any = true;+ total += n * match (unit, in_time) {+ ('W', _) => 7 * 86_400,+ ('D', _) => 86_400,+ ('H', true) => 3_600,+ ('M', true) => 60,+ ('S', true) => 1,+ _ => return None,+ };+ }+ }+ }+ (any && number.is_empty()).then_some(sign * total)+}++/// How an event repeats: the parts of an `RRULE` people publish.+#[derive(Debug, Clone, PartialEq)]+struct Rule {+ freq: Freq,+ interval: i64,+ count: Option<i64>,+ until: Option<When>,+ /// `BYDAY`: a weekday, and for a month or year which one of it (2nd, last = -1); 0 for every.+ by_day: Vec<(i8, Weekday)>,+ by_month_day: Vec<i8>,+ by_month: Vec<i8>,+ by_set_pos: Vec<i32>,+ week_start: Weekday,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Freq {+ Daily,+ Weekly,+ Monthly,+ Yearly,+}++fn weekday_of(code: &str) -> Option<Weekday> {+ Some(match code.to_ascii_uppercase().as_str() {+ "MO" => Weekday::Monday,+ "TU" => Weekday::Tuesday,+ "WE" => Weekday::Wednesday,+ "TH" => Weekday::Thursday,+ "FR" => Weekday::Friday,+ "SA" => Weekday::Saturday,+ "SU" => Weekday::Sunday,+ _ => return None,+ })+}++fn rule_of(p: &Property, here: &TimeZone) -> Option<Rule> {+ let mut rule = Rule {+ freq: Freq::Daily,+ interval: 1,+ count: None,+ until: None,+ by_day: Vec::new(),+ by_month_day: Vec::new(),+ by_month: Vec::new(),+ by_set_pos: Vec::new(),+ week_start: Weekday::Monday,+ };+ let mut freq = None;+ for part in p.value.split(';') {+ let Some((k, v)) = part.split_once('=') else {+ continue;+ };+ let list = || v.split(',').map(str::trim).filter(|s| !s.is_empty());+ match k.trim().to_ascii_uppercase().as_str() {+ "FREQ" => {+ freq = Some(match v.trim().to_ascii_uppercase().as_str() {+ "DAILY" => Freq::Daily,+ "WEEKLY" => Freq::Weekly,+ "MONTHLY" => Freq::Monthly,+ "YEARLY" => Freq::Yearly,+ // Hourly and finer: not a calendar's kind of repeat; shown once.+ _ => return None,+ });+ }+ "INTERVAL" => rule.interval = v.trim().parse().ok().filter(|n: &i64| *n > 0)?,+ "COUNT" => rule.count = v.trim().parse().ok(),+ "UNTIL" => {+ let bare = Property {+ name: "UNTIL".into(),+ params: Vec::new(),+ value: v.trim().into(),+ };+ rule.until = when_of(&bare, here);+ }+ "BYDAY" => {+ for d in list() {+ let split = d.len().saturating_sub(2);+ let (n, code) = d.split_at(split);+ let n: i8 = if n.is_empty() || n == "+" {+ 0+ } else {+ n.trim_start_matches('+').parse().ok()?+ };+ rule.by_day.push((n, weekday_of(code)?));+ }+ }+ "BYMONTHDAY" => rule.by_month_day = list().filter_map(|d| d.parse().ok()).collect(),+ "BYMONTH" => rule.by_month = list().filter_map(|d| d.parse().ok()).collect(),+ "BYSETPOS" => rule.by_set_pos = list().filter_map(|d| d.parse().ok()).collect(),+ "WKST" => rule.week_start = weekday_of(v.trim()).unwrap_or(Weekday::Monday),+ _ => {}+ }+ }+ rule.freq = freq?;+ Some(rule)+}++/// One event in a subscribed file, before its repeats are laid out.+#[derive(Debug, Clone)]+struct Item {+ uid: String,+ title: String,+ location: Option<String>,+ notes: Option<String>,+ url: Option<String>,+ start: When,+ /// Seconds for a timed event; whole days for an all-day one.+ length: i64,+ rule: Option<Rule>,+ extra: Vec<When>,+ except: Vec<When>,+ /// For a changed occurrence: the start of the one it replaces.+ replaces: Option<When>,+ cancelled: bool,+}++/// A subscribed calendar's file, read.+#[derive(Debug, Clone, Default)]+pub struct Feed {+ /// `X-WR-CALNAME`: what the publisher calls it.+ pub name: Option<String>,+ /// `X-APPLE-CALENDAR-COLOR`, when the publisher gave one.+ pub colour: Option<String>,+ /// How often the publisher asks to be fetched, in minutes (`REFRESH-INTERVAL`,+ /// `X-PUBLISHED-TTL`).+ pub refresh_minutes: Option<u32>,+ items: Vec<Item>,+}++impl Feed {+ /// How many events it holds, a repeating one counted once.+ #[must_use]+ pub fn len(&self) -> usize {+ self.items.iter().filter(|i| i.replaces.is_none()).count()+ }++ #[must_use]+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }+}++/// Read a subscribed calendar's file. Events that cannot be read are left out, not the file;+/// a file with no calendar in it is an error. Floating times are read on `here`'s clock.+pub fn parse(text: &str, here: &TimeZone) -> Result<Feed> {+ if !text.contains("BEGIN:VCALENDAR") {+ return Err(Error::Refused("That isn’t a calendar file.".into()));+ }+ let mut feed = Feed::default();+ // Nesting: VCALENDAR > VEVENT > VALARM. Only a VEVENT's own lines are its own.+ let mut stack: Vec<String> = Vec::new();+ let mut current: Vec<Property> = Vec::new();+ for line in unfold(text) {+ let Some(p) = property(&line) else { continue };+ match p.name.as_str() {+ "BEGIN" => {+ let what = p.value.trim().to_ascii_uppercase();+ if what == "VEVENT" {+ current.clear();+ }+ stack.push(what);+ }+ "END" => {+ let what = p.value.trim().to_ascii_uppercase();+ if what == "VEVENT" && stack.last().map(String::as_str) == Some("VEVENT") {+ if let Some(item) = item_of(¤t, here) {+ feed.items.push(item);+ }+ }+ stack.pop();+ }+ _ => match stack.last().map(String::as_str) {+ Some("VEVENT") => current.push(p),+ Some("VCALENDAR") => match p.name.as_str() {+ "X-WR-CALNAME" => {+ let name = unescape(p.value.trim());+ if !name.is_empty() {+ feed.name = Some(name);+ }+ }+ "X-APPLE-CALENDAR-COLOR" => {+ let c = p.value.trim();+ if c.starts_with('#') && (c.len() == 7 || c.len() == 9) {+ feed.colour = Some(c[..7].to_ascii_lowercase());+ }+ }+ "REFRESH-INTERVAL" | "X-PUBLISHED-TTL" => {+ feed.refresh_minutes = duration(&p.value)+ .filter(|s| *s > 0)+ .map(|s| u32::try_from(s / 60).unwrap_or(u32::MAX).max(15));+ }+ _ => {}+ },+ _ => {}+ },+ }+ }+ Ok(feed)+}++fn item_of(props: &[Property], here: &TimeZone) -> Option<Item> {+ let get = |name: &str| props.iter().find(|p| p.name == name);+ let text = |name: &str| {+ get(name)+ .map(|p| unescape(p.value.trim()))+ .filter(|s| !s.is_empty())+ };+ let start = when_of(get("DTSTART")?, here)?;+ let length = match (&start, get("DTEND").and_then(|p| when_of(p, here))) {+ (When::Day(a), Some(When::Day(b))) => (b - *a).get_days().max(1).into(),+ (When::Day(_), _) => get("DURATION")+ .and_then(|p| duration(&p.value))+ .map_or(1, |s| (s / 86_400).max(1)),+ (When::At(..), Some(end @ When::At(..))) => {+ (instant(&end)?.as_second() - instant(&start)?.as_second()).max(0)+ }+ (When::At(..), _) => get("DURATION")+ .and_then(|p| duration(&p.value))+ .unwrap_or(0)+ .max(0),+ };+ let many = |name: &str| -> Vec<When> {+ props+ .iter()+ .filter(|p| p.name == name)+ .flat_map(|p| {+ p.value+ .split(',')+ .filter_map(|v| when_value(v, p, here))+ .collect::<Vec<_>>()+ })+ .collect()+ };+ Some(Item {+ uid: text("UID").unwrap_or_else(|| format!("{:?}", start)),+ title: text("SUMMARY").unwrap_or_else(|| "Untitled".into()),+ location: text("LOCATION"),+ notes: text("DESCRIPTION"),+ url: text("URL"),+ rule: get("RRULE").and_then(|p| rule_of(p, here)),+ extra: many("RDATE"),+ except: many("EXDATE"),+ replaces: get("RECURRENCE-ID").and_then(|p| when_of(p, here)),+ cancelled: text("STATUS").is_some_and(|s| s.eq_ignore_ascii_case("CANCELLED")),+ start,+ length,+ })+}++fn instant(w: &When) -> Option<Timestamp> {+ match w {+ When::Day(d) => d.to_zoned(TimeZone::system()).ok().map(|z| z.timestamp()),+ When::At(dt, tz) => dt.to_zoned(tz.clone()).ok().map(|z| z.timestamp()),+ }+}++/// The same moment for matching an exception or a changed occurrence to the one it is for:+/// a date by its date, a time by its instant.+fn key_of(w: &When) -> Option<i64> {+ match w {+ When::Day(d) => {+ Some(i64::from(d.year()) * 10_000 + i64::from(d.month()) * 100 + i64::from(d.day()))+ }+ When::At(..) => instant(w).map(|t| t.as_second()),+ }+}++/* ---- laying out repeats ---------------------------------------------------------------- */++/// The most periods a rule is walked through: a daily rule from 1970 reaches today in under+/// 21,000, and a broken one never runs away.+const MOST_PERIODS: i64 = 40_000;++fn nth_weekday_in(dates: &[Date], n: i8, wd: Weekday) -> Vec<Date> {+ let all: Vec<Date> = dates+ .iter()+ .copied()+ .filter(|d| d.weekday() == wd)+ .collect();+ if n == 0 {+ return all;+ }+ let i = if n > 0 {+ usize::try_from(n - 1).ok()+ } else {+ all.len().checked_sub(usize::from(n.unsigned_abs()))+ };+ i.and_then(|i| all.get(i).copied()).into_iter().collect()+}++fn month_dates(year: i16, month: i8) -> Vec<Date> {+ let Ok(first) = Date::new(year, month, 1) else {+ return Vec::new();+ };+ (0..first.days_in_month())+ .filter_map(|i| first.checked_add(i64::from(i).days()).ok())+ .collect()+}++fn month_day(year: i16, month: i8, day: i8) -> Option<Date> {+ let first = Date::new(year, month, 1).ok()?;+ let n = first.days_in_month();+ let d = if day > 0 { day } else { n + 1 + day };+ (1..=n)+ .contains(&d)+ .then(|| Date::new(year, month, d).ok())+ .flatten()+}++/// The dates one period of a rule holds, in order.+fn period_dates(rule: &Rule, first: Date, k: i64) -> Vec<Date> {+ let step = k * rule.interval;+ let mut out: Vec<Date> = match rule.freq {+ Freq::Daily => first+ .checked_add(step.days())+ .ok()+ .into_iter()+ .filter(|d| {+ rule.by_day.is_empty() || rule.by_day.iter().any(|(_, w)| *w == d.weekday())+ })+ .collect(),+ Freq::Weekly => {+ let back = i64::from(+ (first.weekday().to_monday_zero_offset() - rule.week_start.to_monday_zero_offset())+ .rem_euclid(7),+ );+ let Ok(week) = first.checked_add((step * 7 - back).days()) else {+ return Vec::new();+ };+ if rule.by_day.is_empty() {+ week.checked_add(back.days()).ok().into_iter().collect()+ } else {+ (0..7)+ .filter_map(|i| week.checked_add(i.days()).ok())+ .filter(|d| rule.by_day.iter().any(|(_, w)| *w == d.weekday()))+ .collect()+ }+ }+ Freq::Monthly => {+ let Ok(m) = first.first_of_month().checked_add(step.months()) else {+ return Vec::new();+ };+ month_set(rule, m.year(), m.month(), first.day())+ }+ Freq::Yearly => {+ let Ok(y) = Date::new(first.year(), 1, 1).and_then(|d| d.checked_add(step.years()))+ else {+ return Vec::new();+ };+ let year = y.year();+ if rule.by_month.is_empty() && !rule.by_day.is_empty() && rule.by_month_day.is_empty() {+ // The nth weekday of the year.+ let days: Vec<Date> = (1..=12).flat_map(|m| month_dates(year, m)).collect();+ rule.by_day+ .iter()+ .flat_map(|(n, w)| nth_weekday_in(&days, *n, *w))+ .collect()+ } else {+ let months: Vec<i8> = if rule.by_month.is_empty() {+ vec![first.month()]+ } else {+ rule.by_month.clone()+ };+ months+ .into_iter()+ .flat_map(|m| month_set(rule, year, m, first.day()))+ .collect()+ }+ }+ };+ if !rule.by_month.is_empty() && rule.freq != Freq::Yearly {+ out.retain(|d| rule.by_month.contains(&d.month()));+ }+ out.sort();+ out.dedup();+ if !rule.by_set_pos.is_empty() {+ let len = i32::try_from(out.len()).unwrap_or(0);+ let picked = rule+ .by_set_pos+ .iter()+ .filter_map(|p| {+ let i = if *p > 0 { p - 1 } else { len + p };+ usize::try_from(i).ok().and_then(|i| out.get(i).copied())+ })+ .collect::<Vec<_>>();+ out = picked;+ out.sort();+ }+ out+}++/// A month's dates under a rule's BYDAY and BYMONTHDAY (both: the days that are both, as+/// Friday the 13th); neither, the first date's day of the month — skipped where there is none.+fn month_set(rule: &Rule, year: i16, month: i8, day: i8) -> Vec<Date> {+ let by_day = |dates: &[Date]| -> Vec<Date> {+ rule.by_day+ .iter()+ .flat_map(|(n, w)| nth_weekday_in(dates, *n, *w))+ .collect()+ };+ match (rule.by_day.is_empty(), rule.by_month_day.is_empty()) {+ (true, true) => month_day(year, month, day).into_iter().collect(),+ (true, false) => rule+ .by_month_day+ .iter()+ .filter_map(|d| month_day(year, month, *d))+ .collect(),+ (false, true) => by_day(&month_dates(year, month)),+ (false, false) => {+ let days: Vec<Date> = rule+ .by_month_day+ .iter()+ .filter_map(|d| month_day(year, month, *d))+ .collect();+ by_day(&month_dates(year, month))+ .into_iter()+ .filter(|d| days.contains(d))+ .collect()+ }+ }+}++/// The starts of an item's occurrences, as `When`s, up to `to` (unix seconds).+fn starts(item: &Item, to: i64) -> Vec<When> {+ let Some(rule) = &item.rule else {+ let mut all = vec![item.start.clone()];+ all.extend(item.extra.iter().cloned());+ return all;+ };+ let (first, at) = match &item.start {+ When::Day(d) => (*d, None),+ When::At(dt, tz) => (dt.date(), Some((dt.time(), tz.clone()))),+ };+ let make = |d: Date| match &at {+ None => When::Day(d),+ Some((t, tz)) => When::At(d.to_datetime(*t), tz.clone()),+ };+ let until = rule.until.as_ref().and_then(|u| match u {+ When::Day(d) => Some(Err(*d)),+ When::At(..) => instant(u).map(|t| Ok(t.as_second())),+ });+ let first_key = instant(&item.start).map_or(i64::MIN, |t| t.as_second());+ let mut out = Vec::new();+ let mut n = 0i64;+ 'walk: for k in 0..MOST_PERIODS {+ let dates = period_dates(rule, first, k);+ let mut beyond = false;+ for d in dates {+ if d < first {+ continue;+ }+ let w = make(d);+ let Some(t) = instant(&w).map(|t| t.as_second()) else {+ continue;+ };+ if t < first_key {+ continue;+ }+ let past_until = match until {+ Some(Err(day)) => d > day,+ Some(Ok(u)) => t > u,+ None => false,+ };+ if past_until {+ break 'walk;+ }+ n += 1;+ if rule.count.is_some_and(|c| n > c) {+ break 'walk;+ }+ if t >= to {+ beyond = true;+ break;+ }+ out.push(w);+ }+ // The first date counts even where a rule's days would not hold it, as RFC 5545 has it.+ if k == 0+ && out.first() != Some(&item.start)+ && instant(&item.start).is_some_and(|t| t.as_second() < to)+ {+ out.insert(0, item.start.clone());+ if rule.count.is_some() {+ n += 1;+ }+ }+ if beyond {+ break;+ }+ }+ out.extend(item.extra.iter().cloned());+ out+}++/// The feed's events overlapping `[from, to)`, as the calendar `calendar_guid` holds them —+/// each repeat laid out on its own day, exceptions left out and changed ones put in their place.+#[must_use]+pub fn events(feed: &Feed, calendar_guid: &str, from: i64, to: i64) -> Vec<Event> {+ use std::collections::{HashMap, HashSet};+ // Changed occurrences, by the series and the start they replace.+ let mut moved: HashMap<&str, HashSet<i64>> = HashMap::new();+ for i in feed.items.iter().filter(|i| i.replaces.is_some()) {+ if let Some(k) = i.replaces.as_ref().and_then(key_of) {+ moved.entry(i.uid.as_str()).or_default().insert(k);+ }+ }+ let mut out = Vec::new();+ for item in &feed.items {+ // A changed occurrence is one event of its own; a cancelled one is no event.+ let occurrences = if item.replaces.is_some() {+ vec![item.start.clone()]+ } else {+ starts(item, to)+ };+ let except: HashSet<i64> = item.except.iter().filter_map(key_of).collect();+ let replaced = moved.get(item.uid.as_str());+ for w in occurrences {+ let Some(key) = key_of(&w) else { continue };+ if item.replaces.is_none()+ && (except.contains(&key) || replaced.is_some_and(|r| r.contains(&key)))+ {+ continue;+ }+ if item.cancelled {+ continue;+ }+ let Some(event) = event_of(item, &w, calendar_guid, key) else {+ continue;+ };+ if event.starts_at < to && event.ends_at > from {+ out.push(event);+ }+ }+ }+ out.sort_by(|a, b| {+ a.starts_at+ .cmp(&b.starts_at)+ .then_with(|| a.title.cmp(&b.title))+ });+ out+}++fn event_of(item: &Item, w: &When, calendar_guid: &str, key: i64) -> Option<Event> {+ let (starts_at, ends_at, all_day, timezone) = match w {+ When::Day(d) => {+ let zone = TimeZone::system();+ let start = d.to_zoned(zone.clone()).ok()?;+ let end = d+ .checked_add(Span::new().days(item.length.max(1)))+ .ok()?+ .to_zoned(zone)+ .ok()?;+ (+ start.timestamp().as_second(),+ end.timestamp().as_second(),+ true,+ None,+ )+ }+ When::At(dt, tz) => {+ let start = dt.to_zoned(tz.clone()).ok()?.timestamp().as_second();+ (+ start,+ start + item.length,+ false,+ tz.iana_name().map(ToString::to_string),+ )+ }+ };+ Some(Event {+ guid: format!("{calendar_guid}:{}:{key}", item.uid),+ calendar_guid: calendar_guid.into(),+ title: item.title.clone(),+ location: item.location.clone(),+ starts_at,+ ends_at,+ all_day,+ timezone,+ url: item.url.clone(),+ notes: item.notes.clone(),+ etag: None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn kolkata() -> TimeZone {+ TimeZone::get("Asia/Kolkata").unwrap()+ }++ fn at(zone: &str, s: &str) -> i64 {+ let (dt, _) = parse_datetime(s).unwrap();+ dt.to_zoned(TimeZone::get(zone).unwrap())+ .unwrap()+ .timestamp()+ .as_second()+ }++ fn wrap(body: &str) -> String {+ format!(+ "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nX-WR-CALNAME:Fixtures\r\nX-APPLE-CALENDAR-COLOR:#FF9500FF\r\nREFRESH-INTERVAL;VALUE=DURATION:PT6H\r\n{body}END:VCALENDAR\r\n"+ )+ }++ fn year(y: i16) -> (i64, i64) {+ let z = TimeZone::get("UTC").unwrap();+ let s = |y| {+ Date::new(y, 1, 1)+ .unwrap()+ .to_zoned(z.clone())+ .unwrap()+ .timestamp()+ .as_second()+ };+ (s(y), s(y + 1))+ }++ #[test]+ fn webcal_reads_as_https_and_only_web_addresses_are_taken() {+ assert_eq!(+ normalise_url(" webcal://p01-calendars.example.com/a.ics")+ .unwrap()+ .as_str(),+ "https://p01-calendars.example.com/a.ics"+ );+ assert_eq!(+ normalise_url("WEBCALS://Example.com/x").unwrap().scheme(),+ "https"+ );+ assert_eq!(+ normalise_url("example.org/team.ics").unwrap().as_str(),+ "https://example.org/team.ics"+ );+ assert!(normalise_url("ftp://example.org/a.ics").is_err());+ assert!(normalise_url("file:///etc/passwd").is_err());+ assert!(normalise_url("https://me:[email protected]/a.ics").is_err());+ assert_eq!(+ host_of("https://Cal.Example.org:8443/a").as_deref(),+ Some("cal.example.org")+ );+ }++ #[test]+ fn the_name_colour_and_refresh_come_from_the_file() {+ let feed = parse(&wrap(""), &kolkata()).unwrap();+ assert_eq!(feed.name.as_deref(), Some("Fixtures"));+ assert_eq!(feed.colour.as_deref(), Some("#ff9500"));+ assert_eq!(feed.refresh_minutes, Some(360));+ assert!(parse("<html>", &kolkata()).is_err());+ }++ #[test]+ fn a_weekly_class_keeps_its_clock_time_across_a_clock_change() {+ let text = wrap("BEGIN:VEVENT\r\nUID:gym\r\nSUMMARY:Gym\r\nDTSTART;TZID=America/New_York:20261026T070000\r\nDTEND;TZID=America/New_York:20261026T080000\r\nRRULE:FREQ=WEEKLY;BYDAY=MO;COUNT=4\r\nEND:VEVENT\r\n");+ let feed = parse(&text, &kolkata()).unwrap();+ let (from, to) = year(2026);+ let got = events(&feed, "quince:sub:x", from, to);+ assert_eq!(got.len(), 4);+ // 26 Oct is daylight time, 2 Nov standard: 7:00 on the clock both days.+ assert_eq!(got[0].starts_at, at("America/New_York", "20261026T070000"));+ assert_eq!(got[1].starts_at, at("America/New_York", "20261102T070000"));+ assert_eq!(got[1].ends_at - got[1].starts_at, 3600);+ assert_eq!(got[3].timezone.as_deref(), Some("America/New_York"));+ assert!(got.iter().all(|e| e.calendar_guid == "quince:sub:x"));+ let guids: std::collections::HashSet<_> = got.iter().map(|e| &e.guid).collect();+ assert_eq!(guids.len(), 4, "every occurrence is its own event");+ }++ #[test]+ fn exceptions_are_left_out_and_a_moved_occurrence_takes_its_place() {+ let text = wrap(concat!(+ "BEGIN:VEVENT\r\nUID:s\r\nSUMMARY:Standup\r\nDTSTART:20260105T040000Z\r\nDURATION:PT15M\r\n",+ "RRULE:FREQ=DAILY;UNTIL=20260109T040000Z\r\nEXDATE:20260107T040000Z\r\nEND:VEVENT\r\n",+ "BEGIN:VEVENT\r\nUID:s\r\nRECURRENCE-ID:20260108T040000Z\r\nSUMMARY:Standup (late)\r\n",+ "DTSTART:20260108T060000Z\r\nDTEND:20260108T061500Z\r\nEND:VEVENT\r\n",+ ));+ let feed = parse(&text, &kolkata()).unwrap();+ let (from, to) = year(2026);+ let got = events(&feed, "c", from, to);+ let titles: Vec<_> = got+ .iter()+ .map(|e| (e.title.as_str(), e.starts_at))+ .collect();+ assert_eq!(titles.len(), 4, "{titles:?}");+ assert!(!got+ .iter()+ .any(|e| e.starts_at == at("UTC", "20260107T040000")));+ assert!(got+ .iter()+ .any(|e| e.title == "Standup (late)" && e.starts_at == at("UTC", "20260108T060000")));+ assert!(!got+ .iter()+ .any(|e| e.title == "Standup" && e.starts_at == at("UTC", "20260108T040000")));+ assert_eq!(feed.len(), 1);+ }++ #[test]+ fn monthly_by_weekday_and_by_last_day() {+ let text = wrap(concat!(+ "BEGIN:VEVENT\r\nUID:a\r\nSUMMARY:Board\r\nDTSTART;VALUE=DATE:20260112\r\n",+ "RRULE:FREQ=MONTHLY;BYDAY=2MO;COUNT=3\r\nEND:VEVENT\r\n",+ "BEGIN:VEVENT\r\nUID:b\r\nSUMMARY:Rent\r\nDTSTART;VALUE=DATE:20260131\r\n",+ "RRULE:FREQ=MONTHLY;BYMONTHDAY=-1;COUNT=3\r\nEND:VEVENT\r\n",+ "BEGIN:VEVENT\r\nUID:c\r\nSUMMARY:Payday\r\nDTSTART;VALUE=DATE:20260130\r\n",+ "RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1;COUNT=2\r\nEND:VEVENT\r\n",+ ));+ let feed = parse(&text, &kolkata()).unwrap();+ let (from, to) = year(2026);+ let days = |t: &str| -> Vec<String> {+ events(&feed, "c", from - 86_400, to)+ .into_iter()+ .filter(|e| e.title == t)+ .map(|e| {+ Timestamp::from_second(e.starts_at)+ .unwrap()+ .to_zoned(TimeZone::system())+ .date()+ .to_string()+ })+ .collect()+ };+ assert_eq!(days("Board"), ["2026-01-12", "2026-02-09", "2026-03-09"]);+ assert_eq!(days("Rent"), ["2026-01-31", "2026-02-28", "2026-03-31"]);+ assert_eq!(days("Payday"), ["2026-01-30", "2026-02-27"]);+ assert!(events(&feed, "c", from, to).iter().all(|e| e.all_day));+ }++ #[test]+ fn a_birthday_feed_repeats_yearly_and_feb_29_is_skipped_in_other_years() {+ let text = wrap(concat!(+ "BEGIN:VEVENT\r\nUID:leap\r\nSUMMARY:Leap\r\nDTSTART;VALUE=DATE:20240229\r\nDTEND;VALUE=DATE:20240301\r\n",+ "RRULE:FREQ=YEARLY\r\nEND:VEVENT\r\n",+ ));+ let feed = parse(&text, &kolkata()).unwrap();+ let (f26, t26) = year(2026);+ assert!(events(&feed, "c", f26, t26).is_empty());+ let (f28, t28) = year(2028);+ assert_eq!(events(&feed, "c", f28, t28).len(), 1);+ }++ #[test]+ fn only_the_window_is_laid_out_and_an_endless_rule_ends() {+ let text = wrap("BEGIN:VEVENT\r\nUID:d\r\nSUMMARY:Daily\r\nDTSTART:19900101T090000\r\nRRULE:FREQ=DAILY\r\nEND:VEVENT\r\n");+ let feed = parse(&text, &kolkata()).unwrap();+ let from = at("Asia/Kolkata", "20261001T000000");+ let to = at("Asia/Kolkata", "20261008T000000");+ let got = events(&feed, "c", from, to);+ assert_eq!(got.len(), 7);+ // Floating: read on this computer's clock (here, Kolkata's).+ assert_eq!(got[0].starts_at, at("Asia/Kolkata", "20261001T090000"));+ }++ #[test]+ fn folded_lines_escapes_outlook_zones_and_cancelled_events() {+ let text = wrap(concat!(+ "BEGIN:VEVENT\r\nUID:o\r\nSUMMARY:Parent\\, teacher\r\n meeting\r\nDESCRIPTION:Room 4\\nBring forms\r\n",+ "LOCATION:Main hall\r\nURL:https://school.example/meet\r\n",+ "DTSTART;TZID=\"India Standard Time\":20261015T160000\r\nDTEND;TZID=\"India Standard Time\":20261015T170000\r\n",+ "BEGIN:VALARM\r\nTRIGGER:-PT15M\r\nDESCRIPTION:Reminder\r\nEND:VALARM\r\nEND:VEVENT\r\n",+ "BEGIN:VEVENT\r\nUID:x\r\nSUMMARY:Called off\r\nSTATUS:CANCELLED\r\nDTSTART:20261016T040000Z\r\nEND:VEVENT\r\n",+ ));+ let feed = parse(&text, &TimeZone::UTC).unwrap();+ let (from, to) = year(2026);+ let got = events(&feed, "c", from, to);+ assert_eq!(got.len(), 1);+ assert_eq!(got[0].title, "Parent, teacher meeting");+ assert_eq!(got[0].notes.as_deref(), Some("Room 4\nBring forms"));+ assert_eq!(got[0].location.as_deref(), Some("Main hall"));+ assert_eq!(got[0].url.as_deref(), Some("https://school.example/meet"));+ assert_eq!(got[0].starts_at, at("Asia/Kolkata", "20261015T160000"));+ }++ #[test]+ fn a_subscription_is_due_by_its_own_interval() {+ let mut s = Subscription {+ id: "a".into(),+ url: "https://example.org/a.ics".into(),+ title: "A".into(),+ colour: "#ff9500".into(),+ refresh_minutes: 60,+ fetched_at: None,+ problem: None,+ };+ assert!(s.due(1_000));+ s.fetched_at = Some(1_000);+ assert!(!s.due(1_000 + 59 * 60));+ assert!(s.due(1_000 + 60 * 60));+ s.refresh_minutes = 0;+ assert!(!s.due(i64::MAX / 2));+ assert_eq!(s.calendar(0).guid, "quince:sub:a");+ assert!(!s.calendar(0).writable);+ }+}diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rsindex bb25e42..e0357fe 100644--- a/crates/quince-icloud/src/contacts.rs+++ b/crates/quince-icloud/src/contacts.rs@@ -1521,7 +1521,7 @@ async fn startup(// every card it missed would read as deleted.if have < wanted {return Err(Error::Protocol(- "The address book is larger than Pomander reads in one go, so it was not stored short."+ "The address book is larger than Skykeep reads in one go, so it was not stored short.".into(),));}diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rsindex 940bfa9..9d69da1 100644--- a/crates/quince-icloud/src/lib.rs+++ b/crates/quince-icloud/src/lib.rs@@ -15,6 +15,7 @@ macro_rules! quiet {}pub mod calendar;+pub mod calendar_feeds;pub mod ckdocument;pub mod cloudkit;pub mod contacts;diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex 91cff71..88808c9 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -130,7 +130,7 @@ fn note_from_record(record: &Value) -> Option<Note> {/// Said when a write would leave a note's attachments unsound (see/// [`crate::ckdocument::attachments_sound_in_base64`]): nothing is sent.const ATTACHMENTS_UNSOUND: &str =- "Pomander didn’t save this: it would have left a table or attachment in this note referenced twice, which Notes on iPhone can’t open. Nothing was changed.";+ "Skykeep didn’t save this: it would have left a table or attachment in this note referenced twice, which Notes on iPhone can’t open. Nothing was changed.";pub async fn sync_cloudkit(http: &reqwest::Client,@@ -203,7 +203,7 @@ const MOST_INLINE: usize = 700 * 1024;fn fits_inline(document: &str) -> Result<()> {if document.len() > MOST_INLINE {return Err(Error::Protocol(- "This note is longer than Pomander can save to iCloud yet. Nothing was changed.".into(),+ "This note is longer than Skykeep can save to iCloud yet. Nothing was changed.".into(),));}Ok(())@@ -587,7 +587,7 @@ pub async fn edit_rich_cloudkit_from(// — and the merge kept only what was typed here.let theirs = crate::ckdocument::stored_text_from_base64(encoded).ok_or_else(|| {Error::Refused(- "Pomander couldn't read this note's text as Apple holds it, so nothing was saved."+ "Skykeep couldn't read this note's text as Apple holds it, so nothing was saved.".into(),)})?;@@ -621,7 +621,7 @@ pub async fn edit_rich_cloudkit_from(}.ok_or_else(|| {Error::Refused(- "Pomander can’t safely save changes to this note yet, so nothing was changed. Editing it on an Apple device is safe."+ "Skykeep can’t safely save changes to this note yet, so nothing was changed. Editing it on an Apple device is safe.".into(),)})?;@@ -2654,7 +2654,7 @@ pub async fn add_table_line_cloudkit(.await?.ok_or_else(|| {Error::Refused(format!(- "A {} can’t be added to this table here: it holds something Pomander can’t rewrite exactly.",+ "A {} can’t be added to this table here: it holds something Skykeep can’t rewrite exactly.",if column { "column" } else { "row" }))})?;@@ -2694,7 +2694,7 @@ pub async fn remove_table_line_cloudkit(.await?.ok_or_else(|| {Error::Refused(format!(- "That {} can’t be deleted here: a table keeps at least one, or it holds something Pomander can’t rewrite exactly.",+ "That {} can’t be deleted here: a table keeps at least one, or it holds something Skykeep can’t rewrite exactly.",if column { "column" } else { "row" }))})?;@@ -2755,7 +2755,7 @@ pub async fn set_table_cell_cloudkit(}).await?.ok_or_else(|| {- Error::Refused("That cell can’t be changed here: this table holds something Pomander can’t rewrite exactly.".into())+ Error::Refused("That cell can’t be changed here: this table holds something Skykeep can’t rewrite exactly.".into())})?;// Apple's answer to the write does not carry the table back (measured), so what it now// holds is read from it.diff --git a/crates/quince-icloud/src/notes_attach.rs b/crates/quince-icloud/src/notes_attach.rsindex bd79967..810385b 100644--- a/crates/quince-icloud/src/notes_attach.rs+++ b/crates/quince-icloud/src/notes_attach.rs@@ -263,7 +263,7 @@ pub fn place_in_document()};let theirs = crate::ckdocument::stored_text_from_base64(current).ok_or_else(|| {- Error::Refused("Pomander couldn't read this note's text as Apple holds it.".into())+ Error::Refused("Skykeep couldn't read this note's text as Apple holds it.".into())})?;let place = match base {Some(base) if base != theirs => {@@ -291,7 +291,7 @@ pub fn place_in_document(let document = crate::ckdocument::insert_attachment_in_base64(current, place, id, uti, stamp).ok_or_else(|| {Error::Refused(- "Pomander can’t safely add a file to this note yet, so nothing was changed.".into(),+ "Skykeep can’t safely add a file to this note yet, so nothing was changed.".into(),)})?;super::fits_inline(&document)?;diff --git a/crates/quince-icloud/src/notes_locked.rs b/crates/quince-icloud/src/notes_locked.rsindex 1f23b17..62c4731 100644--- a/crates/quince-icloud/src/notes_locked.rs+++ b/crates/quince-icloud/src/notes_locked.rs@@ -85,14 +85,14 @@ pub fn is_sealed(record: &Value) -> bool {pub fn sealed(record: &Value) -> Result<Sealed> {let not_here = || {Error::Refused(- "This note is locked in a way Pomander can’t open — open it on an Apple device.".into(),+ "This note is locked in a way Skykeep can’t open — open it on an Apple device.".into(),)};if record.pointer(&format!("/fields/{BODY}")).is_none()&& record.pointer("/fields/TextDataAsset").is_some(){return Err(Error::Refused(- "This locked note is too long for Pomander to open yet.".into(),+ "This locked note is too long for Skykeep to open yet.".into(),));}let iterations = number_of(record, ITERATIONS)diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rsindex 8b5d3ef..b9e6513 100644--- a/crates/quince-icloud/src/reminders.rs+++ b/crates/quince-icloud/src/reminders.rs@@ -1625,7 +1625,7 @@ async fn edit_once(None => Ok(crate::ckdocument::text_to_base64(text)),Some(existing) => crate::ckdocument::replace_text_in_base64(existing, text).ok_or_else(|| {Error::Refused(- "Pomander can’t safely change this reminder’s text yet, so nothing was changed. Editing it on an Apple device is safe."+ "Skykeep can’t safely change this reminder’s text yet, so nothing was changed. Editing it on an Apple device is safe.".into(),)}),diff --git a/crates/quince-icloud/src/reminders_details.rs b/crates/quince-icloud/src/reminders_details.rsindex 8c52ebe..9524b67 100644--- a/crates/quince-icloud/src/reminders_details.rs+++ b/crates/quince-icloud/src/reminders_details.rs@@ -53,7 +53,7 @@ fn gate(enabled: bool) -> Result<()> {Ok(())} else {Err(Error::Refused(- "Pomander can't change this yet: writing it is still being checked against Apple's apps."+ "Skykeep can't change this yet: writing it is still being checked against Apple's apps.".into(),))}@@ -317,15 +317,14 @@ pub fn place_in_section(None => json!({ "minimumSupportedVersion": MINIMUM_SUPPORTED_VERSION, "memberships": [] }),Some(bytes) => serde_json::from_slice(bytes).map_err(|_| {Error::Refused(- "This list's sections are in a form Pomander doesn't read, so nothing was moved."+ "This list's sections are in a form Skykeep doesn't read, so nothing was moved.".into(),)})?,};if !doc.is_object() {return Err(Error::Refused(- "This list's sections are in a form Pomander doesn't read, so nothing was moved."- .into(),+ "This list's sections are in a form Skykeep doesn't read, so nothing was moved.".into(),));}if !doc.get("memberships").is_some_and(Value::is_array) {@@ -663,7 +662,7 @@ pub async fn set_early_alert_cloudkit(.or_else(|| account.map(ToString::to_string)).ok_or_else(|| {Error::Refused(- "Set one early reminder on an Apple device first; Pomander needs what it writes."+ "Set one early reminder on an Apple device first; Skykeep needs what it writes.".into(),)})?;diff --git a/crates/quince-media/src/lib.rs b/crates/quince-media/src/lib.rsindex af9b5db..fa820eb 100644--- a/crates/quince-media/src/lib.rs+++ b/crates/quince-media/src/lib.rs@@ -353,7 +353,7 @@ pub fn freedesktop_thumbnail(.add_text_chunk("Thumb::MTime".into(), mtime.to_string()).map_err(|e| e.to_string())?;encoder- .add_text_chunk("Software".into(), "Pomander".into())+ .add_text_chunk("Software".into(), "Skykeep".into()).map_err(|e| e.to_string())?;let mut writer = encoder.write_header().map_err(|e| e.to_string())?;writer.write_image_data(&rgba).map_err(|e| e.to_string())?;@@ -457,7 +457,7 @@ pub fn thumbnail_is_ours(png_bytes: &[u8]) -> bool {.uncompressed_latin1_text.iter()// Ours under either name: written as Quince before the app was renamed.- .any(|t| t.keyword == "Software" && (t.text == "Pomander" || t.text == "Quince"))+ .any(|t| t.keyword == "Software" && (t.text == "Skykeep" || t.text == "Quince"))}/// Whether bytes are a HEIF file (HEIC and its kin): an `ftyp` box naming a HEIF brand.diff --git a/docs/media/README.md b/docs/media/README.mdnew file mode 100644index 0000000..23b1785--- /dev/null+++ b/docs/media/README.md@@ -0,0 +1,79 @@+# Media for the README++Every image the top-level `README.md` shows lives in this folder. Until a file exists, its spot in the README shows a broken image, so capture these before the repository goes public.++> [!IMPORTANT]+> **Use a demo account only.** Every screenshot and clip uses synthetic data: invented notes, reminders, events, contacts and files. No real names, emails, phone numbers, account pictures, and nothing that identifies a person or a school, including in window titles, the tray, notifications and file paths. Check every frame of each GIF.++## General settings++- **Window size:** 1440 × 900 logical pixels (the app window, not the whole screen), captured at 2× scale, so files are **2880 × 1800**. Then export a copy scaled to **1440 × 900** and commit that one (keeps the repo small, still sharp on GitHub).+- **Capture the window only,** with its own rounded corners and shadow, on a plain background. No desktop wallpaper or other apps, except where noted.+- **Light and dark:** set the appearance in Settings → Appearance (Light / Dark), not by theme hacks.+- **Format:** PNG for screenshots, optimised (`oxipng -o 4` or `pngquant --quality 80-95`). Aim for under 600 KB each.+- **Cursor:** hidden in screenshots unless it explains something.+- **Time and date:** a plausible weekday morning (for example 9:41), with the calendar on a week that has events.++## Screenshots the README expects++| File | App | Mode | What to show |+|---|---|---|---|+| `notes-light.png` | Notes | Light | A note with a heading, a checklist (some ticked), a small table and a picture. Folders in the sidebar, a few pinned notes in the list. |+| `notes-dark.png` | Notes | Dark | Same scene. |+| `reminders-light.png` | Reminders | Light | **Today** with 5–7 reminders: one with a subtask, one flagged, one with a due time, one priority. Lists with colours in the sidebar. |+| `reminders-dark.png` | Reminders | Dark | Same scene. |+| `calendar-light.png` | Calendar | Light | **Week** view with 8–12 events in three or four calendar colours, a reminder on the schedule, and a birthday. |+| `calendar-dark.png` | Calendar | Dark | Same scene. |+| `drive-light.png` | Drive | Light | Skykeep Drive in grid view with thumbnails, **beside** a file manager window (Nautilus or Dolphin) open on `~/iCloud Drive` showing the same files. Capture both windows together on a plain background. |+| `drive-dark.png` | Drive | Dark | Same scene, file manager also in dark mode. |+| `contacts-light.png` | Contacts | Light | A card with a (stock, licence-free or generated) photo, several phones/emails, an address and a birthday; lists in the sidebar. |+| `photos-dark.png` | Photos | Dark | The library by month with a mix of photos, one video and one Live Photo badge. Use licence-free images. Labelled **preview** in the README. |+| `settings-light.png` | Settings | Light | Account (demo name and generated avatar), storage bar, per-app sync times with Sync Now, appearance. This is the trust screenshot. |+| `signin-light.png` | Sign-in | Light | The two-factor code step, showing the flow is Apple's own sign-in. Demo email only. |++Optional, for later:++| File | What |+|---|---|+| `logo-dark.png` | A dark-mode variant of the mark, if the transparent mark ever reads poorly on GitHub's dark theme. Swap it into the first `<source>` of the README hero. |+| `windows-light.png` | Skykeep on Windows 11, once Windows leaves beta. |+| `social-preview.png` | The 1280 × 640 social preview (see `docs/github-setup.md`). Kept here as the source; it's uploaded in GitHub's settings, not shown in the README. |++## GIFs++All GIFs: **under 8 seconds, looping, 1200 px wide (or less), under 5 MB**, 15–20 fps. Record as video first (OBS or `wf-recorder` at 60 fps), then convert:++```sh+ffmpeg -i in.mp4 -vf "fps=18,scale=1200:-1:flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=4" -loop 0 out.gif+gifsicle -O3 --lossy=60 out.gif -o out.gif+```++| File | Used where | What |+|---|---|---|+| `hero-sync.gif` | README hero (required) | The magic moment. Storyboard below. |+| `offline.gif` | Optional, release notes | Wi-Fi off, edit a reminder, Wi-Fi on, it syncs; the pending indicator shows the state. |+| `reminders.gif` | Optional, release notes | Tick a reminder, make a subtask with Tab, a desktop notification rings with Complete and Snooze. |+| `drive-folder.gif` | Optional, release notes | Drag a file into `~/iCloud Drive` in the file manager; it appears in Files on the iPhone. |+| `calendar-keys.gif` | Optional, release notes | Calendar driven by keys: Ctrl+Shift+T Go to Date, Ctrl+1–4 views, T for today. |++### Hero GIF storyboard (`hero-sync.gif`, about 7 s)++Real devices, no mockups: a real iPhone filmed on a tripod (or its screen mirrored), beside the desktop. Composite side by side: **iPhone on the left (about 30% of the width), Skykeep Notes on the right**, on a plain background, 1200 × 600.++| Time | Shot |+|---|---|+| 0.0–1.0 s | Both screens at rest. The same note ("Weekend plans") is open on the iPhone and in Skykeep, light mode. |+| 1.0–3.0 s | On the iPhone, type a new checklist line: "Book the train". |+| 3.0–4.0 s | About a second later, the line appears in Skykeep. No cut: one continuous take, so the timing is real. |+| 4.0–5.5 s | In Skykeep, tick "Book the train". |+| 5.5–6.5 s | The tick appears on the iPhone. |+| 6.5–7.0 s | Brief hold, then loop. |++Optional caption bar under the frame: *"Edit on your phone. See it here in a second."* Keep it out of the GIF if it makes the file too large; the README's alt text carries the message.++## After capturing++1. Put the files here with exactly the names above.+2. Run the privacy check on every image: zoom in on sidebars, title bars, avatars and notifications.+3. Strip metadata: `exiftool -all= -overwrite_original docs/media/*.png docs/media/*.gif`.+4. Commit only this folder's media and this README (`git add docs/media`). The rest of `docs/` holds internal notes that are not meant for the public repository.diff --git a/index.html b/index.htmlindex 3431353..29624b7 100644--- a/index.html+++ b/index.html@@ -3,7 +3,7 @@<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>Pomander</title>+ <title>Skykeep</title></head><body><div id="root"></div>diff --git a/packaging/README.md b/packaging/README.mdindex b39d2c1..b7f289e 100644--- a/packaging/README.md+++ b/packaging/README.md@@ -46,17 +46,17 @@ second and cannot stay signed in, which is most of the point of it.## Opening files and quick capture-Calendar (`.ics`) and contact (`.vcf`) files open in Pomander's import sheet+Calendar (`.ics`) and contact (`.vcf`) files open in Skykeep's import sheet(`src-tauri/src/intake.rs`): read on this computer, shown, and added only when confirmed.- **Linux:** the main entry declares `MimeType=text/calendar;text/vcard;text/x-vcard;` and takes`%U`; the metainfo files list the same types under `<provides>`. The per-app entries do not- claim them, so "Open With" offers one "Pomander", not a second "Calendar" beside GNOME's.+ claim them, so "Open With" offers one "Skykeep", not a second "Calendar" beside GNOME's.- **Windows:** `bundle.fileAssociations` in `tauri.conf.json` registers `.ics`/`.ical` and`.vcf`/`.vcard` in both the NSIS and MSI installers; Explorer passes the path on the command- line, and a second launch hands it to the running Pomander (single instance).+ line, and a second launch hands it to the running Skykeep (single instance).-`pomander --new reminder` and `pomander --new note` open the quick-capture window. They are+`skykeep --new reminder` and `skykeep --new note` open the quick-capture window. They are`Actions=` on the main entry and on the Reminders and Notes entries (right-click in a dock orlauncher).diff --git a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Calendar.desktop b/packaging/apps/io.github.yashwanthkamireddi.Pomander.Calendar.desktopdeleted file mode 100644index 76b6297..0000000--- a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Calendar.desktop+++ /dev/null@@ -1,15 +0,0 @@-# One of Pomander's six apps, on its own in the launcher. Its window says this file's name as-# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one-# Pomander: one sign-in, one library.-[Desktop Entry]-Type=Application-Name=Calendar-GenericName=Calendar for iCloud-Comment=Your iCloud calendars, on this computer-Exec=pomander --app calendar-Icon=io.github.yashwanthkamireddi.Pomander-Terminal=false-Categories=Office;-Keywords=Pomander;iCloud;events;schedule;-StartupNotify=true-StartupWMClass=io.github.yashwanthkamireddi.Pomander.Calendardiff --git a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Contacts.desktop b/packaging/apps/io.github.yashwanthkamireddi.Pomander.Contacts.desktopdeleted file mode 100644index 90728f4..0000000--- a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Contacts.desktop+++ /dev/null@@ -1,15 +0,0 @@-# One of Pomander's six apps, on its own in the launcher. Its window says this file's name as-# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one-# Pomander: one sign-in, one library.-[Desktop Entry]-Type=Application-Name=Contacts-GenericName=Contacts for iCloud-Comment=Your iCloud contacts, on this computer-Exec=pomander --app contacts-Icon=io.github.yashwanthkamireddi.Pomander-Terminal=false-Categories=Office;-Keywords=Pomander;iCloud;people;address;-StartupNotify=true-StartupWMClass=io.github.yashwanthkamireddi.Pomander.Contactsdiff --git a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Drive.desktop b/packaging/apps/io.github.yashwanthkamireddi.Pomander.Drive.desktopdeleted file mode 100644index 6739765..0000000--- a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Drive.desktop+++ /dev/null@@ -1,15 +0,0 @@-# One of Pomander's six apps, on its own in the launcher. Its window says this file's name as-# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one-# Pomander: one sign-in, one library.-[Desktop Entry]-Type=Application-Name=Drive-GenericName=Drive for iCloud-Comment=iCloud Drive, on this computer-Exec=pomander --app drive-Icon=io.github.yashwanthkamireddi.Pomander-Terminal=false-Categories=Office;-Keywords=Pomander;iCloud;files;folders;documents;-StartupNotify=true-StartupWMClass=io.github.yashwanthkamireddi.Pomander.Drivediff --git a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Photos.desktop b/packaging/apps/io.github.yashwanthkamireddi.Pomander.Photos.desktopdeleted file mode 100644index 765fa3f..0000000--- a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Photos.desktop+++ /dev/null@@ -1,15 +0,0 @@-# One of Pomander's six apps, on its own in the launcher. Its window says this file's name as-# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one-# Pomander: one sign-in, one library.-[Desktop Entry]-Type=Application-Name=Photos-GenericName=Photos for iCloud-Comment=iCloud Photos, on this computer-Exec=pomander --app photos-Icon=io.github.yashwanthkamireddi.Pomander-Terminal=false-Categories=Office;-Keywords=Pomander;iCloud;pictures;images;gallery;-StartupNotify=true-StartupWMClass=io.github.yashwanthkamireddi.Pomander.Photosdiff --git a/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Calendar.desktop b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Calendar.desktopnew file mode 100644index 0000000..a8e51e6--- /dev/null+++ b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Calendar.desktop@@ -0,0 +1,15 @@+# One of Skykeep's six apps, on its own in the launcher. Its window says this file's name as+# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one+# Skykeep: one sign-in, one library.+[Desktop Entry]+Type=Application+Name=Calendar+GenericName=Calendar for iCloud+Comment=Your iCloud calendars, on this computer+Exec=skykeep --app calendar+Icon=io.github.yashwanthkamireddi.Skykeep+Terminal=false+Categories=Office;+Keywords=Skykeep;iCloud;events;schedule;+StartupNotify=true+StartupWMClass=io.github.yashwanthkamireddi.Skykeep.Calendardiff --git a/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Contacts.desktop b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Contacts.desktopnew file mode 100644index 0000000..ab3f2a9--- /dev/null+++ b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Contacts.desktop@@ -0,0 +1,15 @@+# One of Skykeep's six apps, on its own in the launcher. Its window says this file's name as+# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one+# Skykeep: one sign-in, one library.+[Desktop Entry]+Type=Application+Name=Contacts+GenericName=Contacts for iCloud+Comment=Your iCloud contacts, on this computer+Exec=skykeep --app contacts+Icon=io.github.yashwanthkamireddi.Skykeep+Terminal=false+Categories=Office;+Keywords=Skykeep;iCloud;people;address;+StartupNotify=true+StartupWMClass=io.github.yashwanthkamireddi.Skykeep.Contactsdiff --git a/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Drive.desktop b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Drive.desktopnew file mode 100644index 0000000..7bbe563--- /dev/null+++ b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Drive.desktop@@ -0,0 +1,15 @@+# One of Skykeep's six apps, on its own in the launcher. Its window says this file's name as+# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one+# Skykeep: one sign-in, one library.+[Desktop Entry]+Type=Application+Name=Drive+GenericName=Drive for iCloud+Comment=iCloud Drive, on this computer+Exec=skykeep --app drive+Icon=io.github.yashwanthkamireddi.Skykeep+Terminal=false+Categories=Office;+Keywords=Skykeep;iCloud;files;folders;documents;+StartupNotify=true+StartupWMClass=io.github.yashwanthkamireddi.Skykeep.Drivediff --git a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Notes.desktop b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Notes.desktopsimilarity index 55%rename from packaging/apps/io.github.yashwanthkamireddi.Pomander.Notes.desktoprename to packaging/apps/io.github.yashwanthkamireddi.Skykeep.Notes.desktopindex 9c28891..c14d3e3 100644--- a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Notes.desktop+++ b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Notes.desktop@@ -1,21 +1,21 @@-# One of Pomander's six apps, on its own in the launcher. Its window says this file's name as+# One of Skykeep's six apps, on its own in the launcher. Its window says this file's name as# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one-# Pomander: one sign-in, one library.+# Skykeep: one sign-in, one library.[Desktop Entry]Type=ApplicationName=NotesGenericName=Notes for iCloudComment=Notes from iCloud, on this computer-Exec=pomander --app notes-Icon=io.github.yashwanthkamireddi.Pomander+Exec=skykeep --app notes+Icon=io.github.yashwanthkamireddi.SkykeepTerminal=falseCategories=Office;-Keywords=Pomander;iCloud;notes;memo;+Keywords=Skykeep;iCloud;notes;memo;StartupNotify=trueActions=new-note;-StartupWMClass=io.github.yashwanthkamireddi.Pomander.Notes+StartupWMClass=io.github.yashwanthkamireddi.Skykeep.Notes# A quick capture: one field, Enter, and it is in iCloud (src-tauri/src/intake.rs).[Desktop Action new-note]Name=New Note-Exec=pomander --new note+Exec=skykeep --new notediff --git a/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Photos.desktop b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Photos.desktopnew file mode 100644index 0000000..3268797--- /dev/null+++ b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Photos.desktop@@ -0,0 +1,15 @@+# One of Skykeep's six apps, on its own in the launcher. Its window says this file's name as+# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one+# Skykeep: one sign-in, one library.+[Desktop Entry]+Type=Application+Name=Photos+GenericName=Photos for iCloud+Comment=iCloud Photos, on this computer+Exec=skykeep --app photos+Icon=io.github.yashwanthkamireddi.Skykeep+Terminal=false+Categories=Office;+Keywords=Skykeep;iCloud;pictures;images;gallery;+StartupNotify=true+StartupWMClass=io.github.yashwanthkamireddi.Skykeep.Photosdiff --git a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Reminders.desktop b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Reminders.desktopsimilarity index 55%rename from packaging/apps/io.github.yashwanthkamireddi.Pomander.Reminders.desktoprename to packaging/apps/io.github.yashwanthkamireddi.Skykeep.Reminders.desktopindex f96ffb5..d12e647 100644--- a/packaging/apps/io.github.yashwanthkamireddi.Pomander.Reminders.desktop+++ b/packaging/apps/io.github.yashwanthkamireddi.Skykeep.Reminders.desktop@@ -1,21 +1,21 @@-# One of Pomander's six apps, on its own in the launcher. Its window says this file's name as+# One of Skykeep's six apps, on its own in the launcher. Its window says this file's name as# its app ID (src-tauri/src/apps.rs), so a dock shows it as this app. All six run in one-# Pomander: one sign-in, one library.+# Skykeep: one sign-in, one library.[Desktop Entry]Type=ApplicationName=RemindersGenericName=Reminders for iCloudComment=Reminders from iCloud, on this computer-Exec=pomander --app reminders-Icon=io.github.yashwanthkamireddi.Pomander+Exec=skykeep --app reminders+Icon=io.github.yashwanthkamireddi.SkykeepTerminal=falseCategories=Office;-Keywords=Pomander;iCloud;todo;tasks;lists;+Keywords=Skykeep;iCloud;todo;tasks;lists;StartupNotify=trueActions=new-reminder;-StartupWMClass=io.github.yashwanthkamireddi.Pomander.Reminders+StartupWMClass=io.github.yashwanthkamireddi.Skykeep.Reminders# A quick capture: one field, Enter, and it is in iCloud (src-tauri/src/intake.rs).[Desktop Action new-reminder]Name=New Reminder-Exec=pomander --new reminder+Exec=skykeep --new reminderdiff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILDindex 52c7e13..f116397 100644--- a/packaging/arch/PKGBUILD+++ b/packaging/arch/PKGBUILD@@ -1,16 +1,16 @@-# Builds Pomander from the checkout beside this file, so it can be installed the way any other+# Builds Skykeep from the checkout beside this file, so it can be installed the way any other# program on this machine is — `makepkg -si` from here — rather than run out of a build# directory. That is the difference between something Yash has and something anyone has.## For the AUR this becomes a `source=("git+https://github.com/…")` with a real `pkgver()`;# the build and package steps below are already what that version would use.-pkgname=pomander+pkgname=skykeeppkgver=0.1.0pkgrel=1pkgdesc="Your iCloud, on this computer — calendar, reminders, notes, contacts and Drive"arch=('x86_64')-url="https://github.com/YashwanthKamireddi/quince"+url="https://github.com/YashwanthKamireddi/Skykeep"license=('GPL-3.0-only')# WebKitGTK is what Tauri renders through on Linux, and libsecret is where the session is@@ -68,24 +68,32 @@ package() {cd "$_root"# Cargo names the binary after its crate; `tauri build` renames it and this does not go# through that, so the rename happens here.- install -Dm755 "$srcdir/target/release/quince-app" "$pkgdir/usr/bin/pomander"+ install -Dm755 "$srcdir/target/release/quince-app" "$pkgdir/usr/bin/skykeep"install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"- install -Dm644 packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xml \- "$pkgdir/usr/share/metainfo/io.github.yashwanthkamireddi.Pomander.metainfo.xml"+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xml \+ "$pkgdir/usr/share/metainfo/io.github.yashwanthkamireddi.Skykeep.metainfo.xml"# The same entry the .deb and .rpm get, with the names this package uses filled in.- sed -e 's/{{name}}/Pomander/' \+ sed -e 's/{{name}}/Skykeep/' \-e 's/{{comment}}/Your iCloud, on this computer/' \- -e 's/{{exec}}/pomander/g' \- -e 's/{{icon}}/io.github.yashwanthkamireddi.Pomander/' \+ -e 's/{{exec}}/skykeep/g' \+ -e 's/{{icon}}/io.github.yashwanthkamireddi.Skykeep/' \-e 's/{{categories}}/Office;Calendar;ContactManagement;/' \- packaging/io.github.yashwanthkamireddi.Pomander.desktop.in \- > "$srcdir/io.github.yashwanthkamireddi.Pomander.desktop"- install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Pomander.desktop" \- "$pkgdir/usr/share/applications/io.github.yashwanthkamireddi.Pomander.desktop"+ packaging/io.github.yashwanthkamireddi.Skykeep.desktop.in \+ > "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop"+ install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop" \+ "$pkgdir/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.desktop"install -Dm644 src-tauri/icons/icon.png \- "$pkgdir/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Pomander.png"- # The six apps, each its own launcher entry (pomander --app notes, …).+ "$pkgdir/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Skykeep.png"+ # The six apps, each its own launcher entry (skykeep --app notes, …).for entry in packaging/apps/*.desktop; doinstall -Dm644 "$entry" "$pkgdir/usr/share/applications/$(basename "$entry")"done+ # In the desktop's own search: GNOME Shell's provider, KRunner's D-Bus plugin, and the bus+ # entry that starts Skykeep hidden when either searches and it is not running.+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini \+ "$pkgdir/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini"+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service \+ "$pkgdir/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service"+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop \+ "$pkgdir/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop"}diff --git a/packaging/aur/.SRCINFO b/packaging/aur/.SRCINFOindex e61926c..f3a3a47 100644--- a/packaging/aur/.SRCINFO+++ b/packaging/aur/.SRCINFO@@ -2,7 +2,7 @@ pkgbase = quince-gitpkgdesc = Your iCloud, on this computer — calendar, reminders, notes, contacts and Drivepkgver = 0.1.0.r0.g0000000pkgrel = 1- url = https://github.com/YashwanthKamireddi/quince+ url = https://github.com/YashwanthKamireddi/Skykeeparch = x86_64license = GPL-3.0-onlymakedepends = rust@@ -17,7 +17,7 @@ pkgbase = quince-gitprovides = quinceconflicts = quinceoptions = !lto- source = quince::git+https://github.com/YashwanthKamireddi/quince.git+ source = quince::git+https://github.com/YashwanthKamireddi/Skykeep.gitsha256sums = SKIPpkgname = quince-gitdiff --git a/packaging/aur/PKGBUILD b/packaging/aur/PKGBUILDindex 86b99d3..07c3ce2 100644--- a/packaging/aur/PKGBUILD+++ b/packaging/aur/PKGBUILD@@ -1,13 +1,13 @@-# The AUR package: Pomander built from the latest source on GitHub, as `yay -S pomander-git` or+# The AUR package: Skykeep built from the latest source on GitHub, as `yay -S skykeep-git` or# `makepkg -si` installs it. The same build and package steps as packaging/arch, which builds# from a local checkout instead.-pkgname=pomander-git+pkgname=skykeep-gitpkgver=0.1.0.r0.g0000000pkgrel=1pkgdesc="Your iCloud, on this computer — calendar, reminders, notes, contacts and Drive"arch=('x86_64')-url="https://github.com/YashwanthKamireddi/quince"+url="https://github.com/YashwanthKamireddi/Skykeep"license=('GPL-3.0-only')# WebKitGTK is what Tauri renders through on Linux, and libsecret is where the session is@@ -31,10 +31,10 @@ makedepends=('rust' 'nodejs' 'npm' 'pkgconf')# here; this only declines to have it done twice, in two languages that disagree about how.options=('!lto')-provides=('pomander')-conflicts=('pomander')+provides=('skykeep')+conflicts=('skykeep')makedepends+=('git')-source=("quince::git+https://github.com/YashwanthKamireddi/quince.git")+source=("quince::git+https://github.com/YashwanthKamireddi/Skykeep.git")sha256sums=('SKIP')_root="$srcdir/quince"@@ -74,24 +74,32 @@ package() {cd "$_root"# Cargo names the binary after its crate; `tauri build` renames it and this does not go# through that, so the rename happens here.- install -Dm755 "$srcdir/target/release/quince-app" "$pkgdir/usr/bin/pomander"+ install -Dm755 "$srcdir/target/release/quince-app" "$pkgdir/usr/bin/skykeep"install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"- install -Dm644 packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xml \- "$pkgdir/usr/share/metainfo/io.github.yashwanthkamireddi.Pomander.metainfo.xml"+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xml \+ "$pkgdir/usr/share/metainfo/io.github.yashwanthkamireddi.Skykeep.metainfo.xml"# The same entry the .deb and .rpm get, with the names this package uses filled in.- sed -e 's/{{name}}/Pomander/' \+ sed -e 's/{{name}}/Skykeep/' \-e 's/{{comment}}/Your iCloud, on this computer/' \- -e 's/{{exec}}/pomander/g' \- -e 's/{{icon}}/io.github.yashwanthkamireddi.Pomander/' \+ -e 's/{{exec}}/skykeep/g' \+ -e 's/{{icon}}/io.github.yashwanthkamireddi.Skykeep/' \-e 's/{{categories}}/Office;Calendar;ContactManagement;/' \- packaging/io.github.yashwanthkamireddi.Pomander.desktop.in \- > "$srcdir/io.github.yashwanthkamireddi.Pomander.desktop"- install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Pomander.desktop" \- "$pkgdir/usr/share/applications/io.github.yashwanthkamireddi.Pomander.desktop"+ packaging/io.github.yashwanthkamireddi.Skykeep.desktop.in \+ > "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop"+ install -Dm644 "$srcdir/io.github.yashwanthkamireddi.Skykeep.desktop" \+ "$pkgdir/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.desktop"install -Dm644 src-tauri/icons/icon.png \- "$pkgdir/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Pomander.png"- # The six apps, each its own launcher entry (pomander --app notes, …).+ "$pkgdir/usr/share/icons/hicolor/512x512/apps/io.github.yashwanthkamireddi.Skykeep.png"+ # The six apps, each its own launcher entry (skykeep --app notes, …).for entry in packaging/apps/*.desktop; doinstall -Dm644 "$entry" "$pkgdir/usr/share/applications/$(basename "$entry")"done+ # In the desktop's own search: GNOME Shell's provider, KRunner's D-Bus plugin, and the bus+ # entry that starts Skykeep hidden when either searches and it is not running.+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini \+ "$pkgdir/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini"+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service \+ "$pkgdir/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service"+ install -Dm644 packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop \+ "$pkgdir/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop"}diff --git a/packaging/flatpak/README.md b/packaging/flatpak/README.mdindex d555636..99a4ea1 100644--- a/packaging/flatpak/README.md+++ b/packaging/flatpak/README.md@@ -2,11 +2,11 @@| File | What it is ||---|---|-| `io.github.yashwanthkamireddi.Pomander.yml` | The manifest. Builds offline from the vendored sources below. |+| `io.github.yashwanthkamireddi.Skykeep.yml` | The manifest. Builds offline from the vendored sources below. || `cargo-sources.json` | Every crate in `Cargo.lock`, generated by `flatpak-cargo-generator.py`. || `node-sources.json` | Every npm package in `package-lock.json`, generated by `flatpak-node-generator`. |-| `io.github.yashwanthkamireddi.Pomander.desktop` | The main launcher entry. |-| `io.github.yashwanthkamireddi.Pomander.metainfo.xml` | The AppStream metadata a software centre shows. |+| `io.github.yashwanthkamireddi.Skykeep.desktop` | The main launcher entry. |+| `io.github.yashwanthkamireddi.Skykeep.metainfo.xml` | The AppStream metadata a software centre shows. |**Status: never built.** The development machine has no `flatpak` or `flatpak-builder`. Checked so far:the manifest parses as YAML, both source files parse as JSON, `appstreamcli validate --pedantic`@@ -90,8 +90,8 @@ flatpak install --user flathub org.gnome.Platform//51 org.gnome.Sdk//51 \cd packaging/flatpakgit clone --depth 1 https://github.com/flathub/shared-modules.git-flatpak-builder --user --install --force-clean build-dir io.github.yashwanthkamireddi.Pomander.yml-flatpak run io.github.yashwanthkamireddi.Pomander+flatpak-builder --user --install --force-clean build-dir io.github.yashwanthkamireddi.Skykeep.yml+flatpak run io.github.yashwanthkamireddi.Skykeep````build-dir/`, `.flatpak-builder/` and `shared-modules/` are build output. Don't commit them.@@ -99,7 +99,7 @@ flatpak run io.github.yashwanthkamireddi.PomanderLint before submitting:```sh-flatpak run --command=flatpak-builder-lint org.flatpak.Builder manifest io.github.yashwanthkamireddi.Pomander.yml+flatpak run --command=flatpak-builder-lint org.flatpak.Builder manifest io.github.yashwanthkamireddi.Skykeep.ymlflatpak run --command=flatpak-builder-lint org.flatpak.Builder repo repo```diff --git a/packaging/flatpak/io.github.yashwanthkamireddi.Pomander.desktop b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.desktopsimilarity index 66%rename from packaging/flatpak/io.github.yashwanthkamireddi.Pomander.desktoprename to packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.desktopindex 78fd348..bcb5740 100644--- a/packaging/flatpak/io.github.yashwanthkamireddi.Pomander.desktop+++ b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.desktop@@ -1,46 +1,46 @@[Desktop Entry]Type=Application-Name=Pomander+Name=SkykeepGenericName=iCloud ClientComment=Your iCloud, on this computer-Exec=pomander %U-Icon=io.github.yashwanthkamireddi.Pomander+Exec=skykeep %U+Icon=io.github.yashwanthkamireddi.SkykeepTerminal=falseCategories=Office;Calendar;ContactManagement;Keywords=iCloud;calendar;reminders;notes;contacts;sync;MimeType=text/calendar;text/vcard;text/x-vcard;StartupNotify=true-StartupWMClass=io.github.yashwanthkamireddi.Pomander+StartupWMClass=io.github.yashwanthkamireddi.SkykeepActions=new-reminder;new-note;notes;reminders;calendar;contacts;drive;photos;[Desktop Action new-reminder]Name=New Reminder-Exec=pomander --new reminder+Exec=skykeep --new reminder[Desktop Action new-note]Name=New Note-Exec=pomander --new note+Exec=skykeep --new note[Desktop Action notes]Name=Notes-Exec=pomander --app notes+Exec=skykeep --app notes[Desktop Action reminders]Name=Reminders-Exec=pomander --app reminders+Exec=skykeep --app reminders[Desktop Action calendar]Name=Calendar-Exec=pomander --app calendar+Exec=skykeep --app calendar[Desktop Action contacts]Name=Contacts-Exec=pomander --app contacts+Exec=skykeep --app contacts[Desktop Action drive]Name=Drive-Exec=pomander --app drive+Exec=skykeep --app drive[Desktop Action photos]Name=Photos-Exec=pomander --app photos+Exec=skykeep --app photosdiff --git a/packaging/flatpak/io.github.yashwanthkamireddi.Pomander.metainfo.xml b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.metainfo.xmlsimilarity index 73%rename from packaging/flatpak/io.github.yashwanthkamireddi.Pomander.metainfo.xmlrename to packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.metainfo.xmlindex 663f9b2..a1698dc 100644--- a/packaging/flatpak/io.github.yashwanthkamireddi.Pomander.metainfo.xml+++ b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.metainfo.xml@@ -1,7 +1,7 @@<?xml version="1.0" encoding="UTF-8"?><!--- The Flatpak copy of packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xml (that one- names the .deb's launcher, Pomander.desktop). Keep the two in step. Flathub requires this+ The Flatpak copy of packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xml (that one+ names the .deb's launcher, Skykeep.desktop). Keep the two in step. Flathub requires thisfile; GNOME Software andKDE Discover read it to build the page someone decides from.@@ -10,26 +10,26 @@entitled to know that before they type their Apple ID.--><component type="desktop-application">- <id>io.github.yashwanthkamireddi.Pomander</id>+ <id>io.github.yashwanthkamireddi.Skykeep</id><metadata_license>CC0-1.0</metadata_license><project_license>GPL-3.0-only</project_license>- <name>Pomander</name>+ <name>Skykeep</name><summary>Your iCloud, on this computer</summary><description><p>- Pomander keeps your iCloud calendar, reminders, notes, contacts and Drive on your own+ Skykeep keeps your iCloud calendar, reminders, notes, contacts and Drive on your ownmachine. Everything opens straight away and works without a connection, and what youchange here reaches your other devices.</p><p>You sign in once with your Apple ID and stay signed in. Nothing is stored on anybody- else's server: there is no Pomander account and no Pomander service, and your credentials+ else's server: there is no Skykeep account and no Skykeep service, and your credentialsnever leave this computer.</p><p>- Pomander is an independent project. It is not made by, endorsed by, or affiliated with+ Skykeep is an independent project. It is not made by, endorsed by, or affiliated withApple, and it reaches iCloud through interfaces Apple has not published, which meansthey can change without warning. Services that Apple encrypts end to end — Health,Messages, Keychain and others — cannot be read by any client and are shown as@@ -37,7 +37,7 @@</p></description>- <launchable type="desktop-id">io.github.yashwanthkamireddi.Pomander.desktop</launchable>+ <launchable type="desktop-id">io.github.yashwanthkamireddi.Skykeep.desktop</launchable><categories><category>Utility</category>@@ -57,14 +57,14 @@<mediatype>text/calendar</mediatype><mediatype>text/vcard</mediatype><mediatype>text/x-vcard</mediatype>- <binary>pomander</binary>+ <binary>skykeep</binary></provides><content_rating type="oars-1.1"/>- <url type="homepage">https://github.com/YashwanthKamireddi/Pomander</url>- <url type="vcs-browser">https://github.com/YashwanthKamireddi/Pomander</url>- <url type="bugtracker">https://github.com/YashwanthKamireddi/Pomander/issues</url>+ <url type="homepage">https://github.com/YashwanthKamireddi/Skykeep</url>+ <url type="vcs-browser">https://github.com/YashwanthKamireddi/Skykeep</url>+ <url type="bugtracker">https://github.com/YashwanthKamireddi/Skykeep/issues</url><developer id="io.github.yashwanthkamireddi"><name>Yashwanth Kamireddi</name>diff --git a/packaging/flatpak/io.github.yashwanthkamireddi.Pomander.yml b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.ymlsimilarity index 78%rename from packaging/flatpak/io.github.yashwanthkamireddi.Pomander.ymlrename to packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.ymlindex 8b0b470..f79feff 100644--- a/packaging/flatpak/io.github.yashwanthkamireddi.Pomander.yml+++ b/packaging/flatpak/io.github.yashwanthkamireddi.Skykeep.yml@@ -1,4 +1,4 @@-# Pomander as a Flatpak, for Flathub.+# Skykeep as a Flatpak, for Flathub.## NOT YET BUILT: the development machine has no flatpak-builder, so this manifest has never run.# packaging/flatpak/README.md lists what was checked, what was not, and the open questions.@@ -22,7 +22,7 @@# FUSE: no fuse3 module either. fuser is built with default-features = false, its pure-Rust mount# path, which links no libfuse; it needs only /dev/fuse and a fusermount3 at run time, and the# FUSE folders are switched off in this package anyway (see finish-args).-app-id: io.github.yashwanthkamireddi.Pomander+app-id: io.github.yashwanthkamireddi.Skykeepruntime: org.gnome.Platformruntime-version: '51'sdk: org.gnome.Sdk@@ -30,7 +30,7 @@ sdk-extensions:# Both exist with a branch/26.08, the freedesktop-sdk under GNOME 51 (checked 2026-10-21).- org.freedesktop.Sdk.Extension.rust-stable- org.freedesktop.Sdk.Extension.node24-command: pomander+command: skykeepfinish-args:# iCloud.@@ -71,19 +71,19 @@ modules:# Flathub repository it is a git submodule at this path.- shared-modules/libayatana-appindicator/libayatana-appindicator-gtk3.json- - name: pomander+ - name: skykeepbuildsystem: simplebuild-options:append-path: /usr/lib/sdk/rust-stable/bin:/usr/lib/sdk/node24/binenv:# Offline: every crate and npm package comes from the generated sources below.- CARGO_HOME: /run/build/pomander/cargo+ CARGO_HOME: /run/build/skykeep/cargoCARGO_NET_OFFLINE: 'true'- XDG_CACHE_HOME: /run/build/pomander/flatpak-node/cache- npm_config_cache: /run/build/pomander/flatpak-node/npm-cache+ XDG_CACHE_HOME: /run/build/skykeep/flatpak-node/cache+ npm_config_cache: /run/build/skykeep/flatpak-node/npm-cachenpm_config_offline: 'true'# esbuild's binary, placed by node-sources.json for the build architecture.- ESBUILD_BINARY_PATH: /run/build/pomander/flatpak-node/cache/esbuild/bin/esbuild-current+ ESBUILD_BINARY_PATH: /run/build/skykeep/flatpak-node/cache/esbuild/bin/esbuild-currentbuild-commands:# The frontend into dist/, which tauri::generate_context! embeds at compile time.- npm ci --offline --no-audit --no-fund@@ -91,7 +91,7 @@ modules:# The app. tauri/custom-protocol is what `tauri build` turns on: without it the binary# is a dev build (cfg(dev)) — dev CSP and dev behaviour in a release package.- cargo --offline build --release --locked -p quince-app --features tauri/custom-protocol- - install -Dm755 target/release/quince-app ${FLATPAK_DEST}/bin/pomander+ - install -Dm755 target/release/quince-app ${FLATPAK_DEST}/bin/skykeep# The main launcher entry and the metainfo: written for this app ID, kept beside this# manifest (packaging/flatpak/), and added as file sources below.@@ -99,8 +99,8 @@ modules:- install -Dm644 ${FLATPAK_ID}.desktop ${FLATPAK_DEST}/share/applications/${FLATPAK_ID}.desktop# The six per-app entries, already named under this app ID (Flatpak exports only desktop- # files whose names start with it). Exec stays `pomander --app …`; flatpak rewrites it to- # `flatpak run --command=pomander io.github.yashwanthkamireddi.Pomander --app …` when it+ # files whose names start with it). Exec stays `skykeep --app …`; flatpak rewrites it to+ # `flatpak run --command=skykeep io.github.yashwanthkamireddi.Skykeep --app …` when it# exports the file.- |for entry in packaging/apps/${FLATPAK_ID}.*.desktop; do@@ -111,8 +111,18 @@ modules:- install -Dm644 ${FLATPAK_ID}.metainfo.xml ${FLATPAK_DEST}/share/metainfo/${FLATPAK_ID}.metainfo.xml+ # In the desktop's own search (src-tauri/src/search_provider.rs): GNOME Shell's provider,+ # KRunner's D-Bus plugin, and the bus entry that starts Skykeep hidden to answer. The+ # bus name is under the app ID, which the sandbox may own by default; Flatpak exports+ # all three and rewrites the service's Exec to `flatpak run`.+ - install -Dm644 packaging/${FLATPAK_ID}.search-provider.ini ${FLATPAK_DEST}/share/gnome-shell/search-providers/${FLATPAK_ID}.search-provider.ini+ - desktop-file-validate packaging/${FLATPAK_ID}.krunner.desktop+ - install -Dm644 packaging/${FLATPAK_ID}.krunner.desktop ${FLATPAK_DEST}/share/krunner/dbusplugins/${FLATPAK_ID}.krunner.desktop+ - sed 's|^Exec=/usr/bin/skykeep|Exec=${FLATPAK_DEST}/bin/skykeep|' packaging/${FLATPAK_ID}.SearchProvider.service > ${FLATPAK_ID}.SearchProvider.service+ - install -Dm644 ${FLATPAK_ID}.SearchProvider.service ${FLATPAK_DEST}/share/dbus-1/services/${FLATPAK_ID}.SearchProvider.service+# Icons: the vector original, and the rendered sizes.- - install -Dm644 src-tauri/icons/icon.svg ${FLATPAK_DEST}/share/icons/hicolor/scalable/apps/${FLATPAK_ID}.svg+ - install -Dm644 src-tauri/icons/icon.png ${FLATPAK_DEST}/share/icons/hicolor/512x512/apps/${FLATPAK_ID}.png- install -Dm644 src-tauri/icons/32x32.png ${FLATPAK_DEST}/share/icons/hicolor/32x32/apps/${FLATPAK_ID}.png- install -Dm644 src-tauri/icons/64x64.png ${FLATPAK_DEST}/share/icons/hicolor/64x64/apps/${FLATPAK_ID}.png- install -Dm644 src-tauri/icons/128x128.png ${FLATPAK_DEST}/share/icons/hicolor/128x128/apps/${FLATPAK_ID}.png@@ -127,16 +137,16 @@ modules:## FLATHUB: replace with the public repository at a release tag, e.g.# - type: git- # url: https://github.com/YashwanthKamireddi/Pomander.git+ # url: https://github.com/YashwanthKamireddi/Skykeep.git# tag: v0.1.0# commit: <full sha of that tag>- type: gitpath: ../..# Not part of the git checkout, so they work before packaging/flatpak/ is committed.- type: file- path: io.github.yashwanthkamireddi.Pomander.desktop+ path: io.github.yashwanthkamireddi.Skykeep.desktop- type: file- path: io.github.yashwanthkamireddi.Pomander.metainfo.xml+ path: io.github.yashwanthkamireddi.Skykeep.metainfo.xml# Regenerate both whenever Cargo.lock or package-lock.json changes (README).- cargo-sources.json- node-sources.jsondiff --git a/packaging/icons/skykeep-1024.png b/packaging/icons/skykeep-1024.pngnew file mode 100644index 0000000..cefb640Binary files /dev/null and b/packaging/icons/skykeep-1024.png differdiff --git a/packaging/icons/skykeep-mark-1024.png b/packaging/icons/skykeep-mark-1024.pngnew file mode 100644index 0000000..f1377aeBinary files /dev/null and b/packaging/icons/skykeep-mark-1024.png differdiff --git a/packaging/icons/skykeep-small-1024.png b/packaging/icons/skykeep-small-1024.pngnew file mode 100644index 0000000..05fd564Binary files /dev/null and b/packaging/icons/skykeep-small-1024.png differdiff --git a/packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service b/packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.servicenew file mode 100644index 0000000..5f6c08c--- /dev/null+++ b/packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service@@ -0,0 +1,6 @@+# Lets the session bus start Skykeep, hidden in the tray (--background), when GNOME Shell or+# KRunner searches and it is not already running. Installed to /usr/share/dbus-1/services/.+# The Flatpak manifest installs it with Exec pointing into /app instead.+[D-BUS Service]+Name=io.github.yashwanthkamireddi.Skykeep.SearchProvider+Exec=/usr/bin/skykeep --backgrounddiff --git a/packaging/io.github.yashwanthkamireddi.Pomander.desktop.in b/packaging/io.github.yashwanthkamireddi.Skykeep.desktop.insimilarity index 89%rename from packaging/io.github.yashwanthkamireddi.Pomander.desktop.inrename to packaging/io.github.yashwanthkamireddi.Skykeep.desktop.inindex e911441..d2471ca 100644--- a/packaging/io.github.yashwanthkamireddi.Pomander.desktop.in+++ b/packaging/io.github.yashwanthkamireddi.Skykeep.desktop.in@@ -1,7 +1,7 @@# The menu entry, with the names filled in by whatever is building the package — Tauri# substitutes these itself, and the Arch PKGBUILD fills them in with sed. One file, so the# entry cannot say one thing in a .deb and another in a .pkg.tar.zst.-# MimeType: calendar and contact files open in Pomander's import sheet (src-tauri/src/intake.rs);+# MimeType: calendar and contact files open in Skykeep's import sheet (src-tauri/src/intake.rs);# %U hands them over as file:// URIs, which intake reads.[Desktop Entry]Type=Application@@ -15,7 +15,7 @@ Categories={{categories}}Keywords=iCloud;calendar;reminders;notes;contacts;sync;MimeType=text/calendar;text/vcard;text/x-vcard;StartupNotify=true-StartupWMClass={{exec}}+StartupWMClass=io.github.yashwanthkamireddi.SkykeepActions=new-reminder;new-note;notes;reminders;calendar;contacts;drive;photos;[Desktop Action new-reminder]diff --git a/packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop b/packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktopnew file mode 100644index 0000000..fee70a5--- /dev/null+++ b/packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop@@ -0,0 +1,18 @@+# KRunner's plugin entry for Skykeep's D-Bus runner (src-tauri/src/search_provider.rs, the+# org.kde.krunner1 object). Installed to /usr/share/krunner/dbusplugins/; the bus starts+# Skykeep through the .SearchProvider.service when it is not running.+[Desktop Entry]+Type=Service+Name=Skykeep+Comment=Notes, reminders, events, contacts, files and photos from iCloud+Icon=io.github.yashwanthkamireddi.Skykeep+X-KDE-ServiceTypes=Plasma/Runner+X-KDE-PluginInfo-Name=io.github.yashwanthkamireddi.Skykeep+X-KDE-PluginInfo-Version=0.1.0+X-KDE-PluginInfo-License=GPL-3.0-only+X-KDE-PluginInfo-EnabledByDefault=true+X-Plasma-API=DBus+X-Plasma-DBusRunner-Service=io.github.yashwanthkamireddi.Skykeep.SearchProvider+X-Plasma-DBusRunner-Path=/io/github/yashwanthkamireddi/Skykeep/KRunner+X-Plasma-Request-Actions-Once=true+X-Plasma-Runner-Min-Letter-Count=2diff --git a/packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xml b/packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xmlsimilarity index 77%rename from packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xmlrename to packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xmlindex dcf3588..b518f4f 100644--- a/packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xml+++ b/packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xml@@ -1,6 +1,6 @@<?xml version="1.0" encoding="UTF-8"?><!--- What a software centre shows about Pomander. Flathub requires this file; GNOME Software and+ What a software centre shows about Skykeep. Flathub requires this file; GNOME Software andKDE Discover read it to build the page someone decides from.Every claim here has to be one the app can keep. The disclaimer is not boilerplate: this@@ -8,26 +8,26 @@entitled to know that before they type their Apple ID.--><component type="desktop-application">- <id>io.github.yashwanthkamireddi.Pomander</id>+ <id>io.github.yashwanthkamireddi.Skykeep</id><metadata_license>CC0-1.0</metadata_license><project_license>GPL-3.0-only</project_license>- <name>Pomander</name>+ <name>Skykeep</name><summary>Your iCloud, on this computer</summary><description><p>- Pomander keeps your iCloud calendar, reminders, notes, contacts and Drive on your own+ Skykeep keeps your iCloud calendar, reminders, notes, contacts and Drive on your ownmachine. Everything opens straight away and works without a connection, and what youchange here reaches your other devices.</p><p>You sign in once with your Apple ID and stay signed in. Nothing is stored on anybody- else's server: there is no Pomander account and no Pomander service, and your credentials+ else's server: there is no Skykeep account and no Skykeep service, and your credentialsnever leave this computer.</p><p>- Pomander is an independent project. It is not made by, endorsed by, or affiliated with+ Skykeep is an independent project. It is not made by, endorsed by, or affiliated withApple, and it reaches iCloud through interfaces Apple has not published, which meansthey can change without warning. Services that Apple encrypts end to end — Health,Messages, Keychain and others — cannot be read by any client and are shown as@@ -35,7 +35,7 @@</p></description>- <launchable type="desktop-id">Pomander.desktop</launchable>+ <launchable type="desktop-id">Skykeep.desktop</launchable><provides><mediatype>text/calendar</mediatype>@@ -59,8 +59,8 @@<content_rating type="oars-1.1"/>- <url type="homepage">https://github.com/YashwanthKamireddi/quince</url>- <url type="bugtracker">https://github.com/YashwanthKamireddi/quince/issues</url>+ <url type="homepage">https://github.com/YashwanthKamireddi/Skykeep</url>+ <url type="bugtracker">https://github.com/YashwanthKamireddi/Skykeep/issues</url><developer id="io.github.yashwanthkamireddi"><name>Yashwanth Kamireddi</name>diff --git a/packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini b/packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ininew file mode 100644index 0000000..0ce3db9--- /dev/null+++ b/packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini@@ -0,0 +1,8 @@+# GNOME Shell's search provider: what is typed in the Activities overview is asked of Skykeep+# too (src-tauri/src/search_provider.rs). Installed to /usr/share/gnome-shell/search-providers/.+# BusName starts Skykeep hidden if it is not running (the .SearchProvider.service beside this).+[Shell Search Provider]+DesktopId=io.github.yashwanthkamireddi.Skykeep.desktop+BusName=io.github.yashwanthkamireddi.Skykeep.SearchProvider+ObjectPath=/io/github/yashwanthkamireddi/Skykeep/SearchProvider+Version=2diff --git a/probe/examples/calendar_feed_fetch.rs b/probe/examples/calendar_feed_fetch.rsnew file mode 100644index 0000000..854d5f3--- /dev/null+++ b/probe/examples/calendar_feed_fetch.rs@@ -0,0 +1,36 @@+//! Read-only: a subscription fetched for real through `listed_only`, the way Calendar's New+//! Subscription does — Apple's own public holiday feed by its webcal:// address, so nothing but+//! Apple is contacted — then read and its 2026 events laid out. Also shows an unlisted host+//! refused. Prints counts and the first few titles only.+use anyhow::Result;+#[tokio::main]+async fn main() -> Result<()> {+ use quince_icloud::calendar_feeds as feeds;+ let url = feeds::normalise_url("webcal://calendars.icloud.com/holidays/in_en.ics")?;+ let host = feeds::host_of(url.as_str()).unwrap();+ let http = quince_auth::listed_only(std::slice::from_ref(&host)).build()?;+ let text = feeds::fetch(&http, url.as_str()).await?;+ let feed = feeds::parse(&text, &jiff::tz::TimeZone::system())?;+ let from = jiff::civil::date(2026, 1, 1)+ .to_zoned(jiff::tz::TimeZone::UTC)?+ .timestamp()+ .as_second();+ let to = jiff::civil::date(2027, 1, 1)+ .to_zoned(jiff::tz::TimeZone::UTC)?+ .timestamp()+ .as_second();+ let events = feeds::events(&feed, "quince:sub:probe", from, to);+ println!(+ "host={host} bytes={} name={:?} items={} events2026={}",+ text.len(),+ feed.name,+ feed.len(),+ events.len()+ );+ for e in events.iter().take(3) {+ println!(" {} all_day={} {}", e.title, e.all_day, e.starts_at);+ }+ let refused = http.get("https://www.apple.com/").send().await;+ println!("unlisted host refused: {}", refused.is_err());+ Ok(())+}diff --git a/probe/examples/calendar_subscriptions.rs b/probe/examples/calendar_subscriptions.rsnew file mode 100644index 0000000..3001b6e--- /dev/null+++ b/probe/examples/calendar_subscriptions.rs@@ -0,0 +1,75 @@+//! READ-ONLY probe: which collections the iCloud calendar service lists, by kind, and whether+//! any subscribed calendar's events come back with them. Prints kinds, flags and counts only,+//! never titles or URLs. Writes nothing.+use anyhow::{anyhow, Result};+use std::collections::BTreeMap;+#[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("calendar")+ .ok_or_else(|| anyhow!("no calendar"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let mut q = p.clone();+ for (k, v) in [+ ("clientVersion", "5.1"),+ ("requestID", "7"),+ ("lang", "en-us"),+ ("usertz", "Asia/Kolkata"),+ ("startDate", "2026-09-01"),+ ("endDate", "2026-09-30"),+ ("bday", "true"),+ ] {+ q.push((k.into(), v.into()));+ }+ let v = http+ .get(format!("{root}/ca/startup"))+ .query(&q)+ .send()+ .await?;+ let status = v.status();+ let text = v.text().await?;+ println!("status {status}, {} bytes", text.len());+ let v: serde_json::Value = serde_json::from_str(&text)?;+ let top: Vec<_> = v+ .as_object()+ .map(|o| o.keys().cloned().collect())+ .unwrap_or_default();+ println!("top-level keys: {top:?}");+ let mut per: BTreeMap<String, usize> = BTreeMap::new();+ for e in v["Event"].as_array().into_iter().flatten() {+ *per.entry(e["pGuid"].as_str().unwrap_or("?").to_string())+ .or_default() += 1;+ }+ for (i, c) in v["Collection"].as_array().into_iter().flatten().enumerate() {+ let keys: Vec<_> = c+ .as_object()+ .map(|o| o.keys().cloned().collect())+ .unwrap_or_default();+ let guid = c["guid"].as_str().unwrap_or("");+ println!(+ "#{i} objectType={} supportedType={} readOnly={} isFamily={} enabled={} events={} keys={keys:?}",+ c["objectType"], c["supportedType"], c["readOnly"], c["isFamily"], c["enabled"],+ per.get(guid).copied().unwrap_or(0)+ );+ }+ let bdays = v["Event"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|e| {+ e.get("birthdayIsYearlessBday").is_some()+ || e["pGuid"].as_str().is_some_and(|g| g.contains("irthday"))+ })+ .count();+ println!(+ "events total={} with birthday fields={bdays}",+ v["Event"].as_array().map_or(0, |a| a.len())+ );+ Ok(())+}diff --git a/probe/examples/keyring_pipe.rs b/probe/examples/keyring_pipe.rsindex 8b10b89..b29d517 100644--- a/probe/examples/keyring_pipe.rs+++ b/probe/examples/keyring_pipe.rs@@ -5,7 +5,7 @@ use anyhow::{anyhow, Result};use std::io::{Read, Write};fn main() -> Result<()> {- let entry = keyring::Entry::new("io.github.yashwanthkamireddi.Pomander", "session")?;+ let entry = keyring::Entry::new("io.github.yashwanthkamireddi.Skykeep", "session")?;match std::env::args().nth(1).as_deref() {Some("get") => std::io::stdout().write_all(entry.get_password()?.as_bytes())?,Some("set") => {diff --git a/probe/examples/notes_reach_live.rs b/probe/examples/notes_reach_live.rsindex 6bfb576..053e36d 100644--- a/probe/examples/notes_reach_live.rs+++ b/probe/examples/notes_reach_live.rs@@ -27,7 +27,7 @@ async fn main() -> Result<()> {let (http, p) = (client.http().clone(), client.service_params());let db = rusqlite::Connection::open_with_flags(std::path::PathBuf::from(std::env::var("HOME")?)- .join(".local/share/io.github.yashwanthkamireddi.Pomander/library.db"),+ .join(".local/share/io.github.yashwanthkamireddi.Skykeep/library.db"),rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,)?;let title = format!("Quince mount test {}", std::process::id());diff --git a/probe/examples/notes_vs_library.rs b/probe/examples/notes_vs_library.rsindex efec54c..2eeb5f5 100644--- a/probe/examples/notes_vs_library.rs+++ b/probe/examples/notes_vs_library.rs@@ -17,7 +17,7 @@ async fn main() -> Result<()> {let walk = zc.all_records("Notes", None).await?;let db = rusqlite::Connection::open_with_flags(std::path::PathBuf::from(std::env::var("HOME")?)- .join(".local/share/io.github.yashwanthkamireddi.Pomander/library.db"),+ .join(".local/share/io.github.yashwanthkamireddi.Skykeep/library.db"),rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,)?;let mut apple = std::collections::HashSet::new();diff --git a/run.sh b/run.shindex 25131d0..3cdb151 100755--- a/run.sh+++ b/run.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Build Quince and open it. Nothing else — no dev server, no watch mode.+# Build Skykeep and open it. Nothing else — no dev server, no watch mode.set -euo pipefailcd "$(dirname "$0")"@@ -25,6 +25,6 @@ pkill -f 'quince-ap[p]' 2>/dev/null || truesleep 1echo-echo "Opening Quince. Close the window, or press Ctrl-C here, to stop it."+echo "Opening Skykeep. Close the window, or press Ctrl-C here, to stop it."echoexec ./target/debug/quince-appdiff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex e57b889..ad9ea22 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -1,7 +1,7 @@{"$schema": "../gen/schemas/desktop-schema.json","identifier": "default",- "description": "What the window's own page may ask of Tauri itself, and no more: hearing the engine's events (and the webview's dropped files), the app's version for Settings, a window's title, and the system's open and save dialogs. Pomander's own commands are separate. These windows only ever load the app's bundled page (no remote URL is granted anything).",+ "description": "What the window's own page may ask of Tauri itself, and no more: hearing the engine's events (and the webview's dropped files), the app's version for Settings, a window's title, and the system's open and save dialogs. Skykeep's own commands are separate. These windows only ever load the app's bundled page (no remote URL is granted anything).","windows": ["main","app-*",diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.pngindex 39ca498..bf865b0 100644Binary files a/src-tauri/icons/128x128.png and b/src-tauri/icons/128x128.png differdiff --git a/src-tauri/icons/[email protected] b/src-tauri/icons/[email protected]index 80ef100..7004a18 100644Binary files a/src-tauri/icons/[email protected] and b/src-tauri/icons/[email protected] differdiff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.pngindex 957137c..3b5b509 100644Binary files a/src-tauri/icons/32x32.png and b/src-tauri/icons/32x32.png differdiff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.pngindex d1a5d1b..db59885 100644Binary files a/src-tauri/icons/64x64.png and b/src-tauri/icons/64x64.png differdiff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.icoindex 68c27a6..a018fa6 100644Binary files a/src-tauri/icons/icon.ico and b/src-tauri/icons/icon.ico differdiff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.pngindex c8beede..7aa7a58 100644Binary files a/src-tauri/icons/icon.png and b/src-tauri/icons/icon.png differdiff --git a/src-tauri/icons/icon.svg b/src-tauri/icons/icon.svgdeleted file mode 100644index a2e5ca1..0000000--- a/src-tauri/icons/icon.svg+++ /dev/null@@ -1,64 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">- <!--- Quince: a quince, ripe gold, against the evening sky its data lives in.- A quince, not an apple: it narrows to a neck at the stem like a pear, its body sits low- and a little lopsided, and it has one leaf and no bite. Laid on Apple's icon grid — an- 824px tile inset on the 1024 canvas — and drawn to read as one gold shape on blue at 16px.- -->- <defs>- <linearGradient id="sky" x1="0.15" y1="0" x2="0.85" y2="1">- <stop offset="0" stop-color="#4573B8"/>- <stop offset="0.55" stop-color="#284B85"/>- <stop offset="1" stop-color="#172C54"/>- </linearGradient>- <radialGradient id="glow" cx="0.3" cy="0.12" r="0.8">- <stop offset="0" stop-color="#8FB4E8" stop-opacity="0.5"/>- <stop offset="1" stop-color="#8FB4E8" stop-opacity="0"/>- </radialGradient>- <radialGradient id="skin" cx="0.38" cy="0.4" r="0.72">- <stop offset="0" stop-color="#F9D46E"/>- <stop offset="0.5" stop-color="#E4AE43"/>- <stop offset="0.82" stop-color="#C8912A"/>- <stop offset="1" stop-color="#93601A"/>- </radialGradient>- <radialGradient id="sheen" cx="0.5" cy="0.5" r="0.5">- <stop offset="0" stop-color="#FFF6D6" stop-opacity="0.55"/>- <stop offset="1" stop-color="#FFF6D6" stop-opacity="0"/>- </radialGradient>- <linearGradient id="leaf" x1="0" y1="1" x2="1" y2="0">- <stop offset="0" stop-color="#3D6B29"/>- <stop offset="1" stop-color="#83B552"/>- </linearGradient>- <filter id="shadow" x="-25%" y="-20%" width="150%" height="150%">- <feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#06122A" flood-opacity="0.5"/>- </filter>- </defs>-- <rect x="100" y="100" width="824" height="824" rx="186" fill="url(#sky)"/>- <rect x="100" y="100" width="824" height="824" rx="186" fill="url(#glow)"/>- <rect x="102" y="102" width="820" height="820" rx="184" fill="none"- stroke="#FFFFFF" stroke-opacity="0.18" stroke-width="4"/>-- <g filter="url(#shadow)">- <!-- Narrow at the neck, full and low in the body, the right side carrying more weight. -->- <path fill="url(#skin)" d="- M500 318- C540 312 574 330 594 364- C612 394 640 420 676 446- C736 490 766 560 760 634- C752 742 660 816 532 822- C404 828 288 768 268 652- C254 572 282 500 342 454- C380 424 408 398 420 366- C434 334 462 322 500 318Z"/>- <!-- Where the skin folds in round the stem. -->- <path d="M466 330C486 344 522 344 542 330" fill="none" stroke="#8A5815" stroke-opacity="0.6"- stroke-width="11" stroke-linecap="round"/>- <ellipse cx="420" cy="560" rx="70" ry="118" transform="rotate(-18 420 560)" fill="url(#sheen)"/>- <path d="M504 336C498 296 506 262 526 236" fill="none" stroke="#5E3C10" stroke-width="20"- stroke-linecap="round"/>- <path fill="url(#leaf)" d="M528 244C564 178 646 156 716 186C696 258 622 300 540 280C532 268 528 256 528 244Z"/>- <path d="M544 268C594 244 640 220 688 196" fill="none" stroke="#2C501D" stroke-opacity="0.55"- stroke-width="8" stroke-linecap="round"/>- </g>-</svg>diff --git a/src-tauri/src/alerts.rs b/src-tauri/src/alerts.rsindex c85c757..05619e0 100644--- a/src-tauri/src/alerts.rs+++ b/src-tauri/src/alerts.rs@@ -85,7 +85,7 @@ fn answer(app: &AppHandle, due: &DueAlarm, due_then: Option<Option<i64>>, action}}-/// A plain notice from the app itself — not a reminder or an event — sent as Pomander, and+/// A plain notice from the app itself — not a reminder or an event — sent as Skykeep, and/// opening the window when clicked where the desktop allows it.pub fn tell(app: &AppHandle, title: &str, body: &str) {let app = app.clone();@@ -95,7 +95,7 @@ pub fn tell(app: &AppHandle, title: &str, body: &str) {#[cfg(windows)]notice.app_id(&app.config().identifier);notice- .appname("Pomander")+ .appname("Skykeep").summary(&title).body(&body).icon(icon_path(&app).unwrap_or("quince"));@@ -137,7 +137,7 @@ fn chime(alert: &mut notify_rust::Notification) {}// Not waited on: an alert never stands behind its sound.std::process::Command::new("canberra-gtk-play")- .args(["--id", SOUND, "--description", "Pomander alert"])+ .args(["--id", SOUND, "--description", "Skykeep alert"]).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null())@@ -315,7 +315,7 @@ fn show(app: AppHandle, due: DueAlarm) {toast = toast.icon(std::path::Path::new(icon),tauri_winrt_notification::IconCrop::Square,- "Pomander",+ "Skykeep",);}toast.show().ok();@@ -325,7 +325,7 @@ fn show(app: AppHandle, due: DueAlarm) {let mut alert = notify_rust::Notification::new();chime(&mut alert);let shown = alert- .appname("Pomander")+ .appname("Skykeep").summary(&due.title).body(&body).icon(icon_path(&app).unwrap_or("quince"))@@ -472,7 +472,7 @@ fn show_event(app: AppHandle, event: quince_core::calendar::Event, minutes: i64)#[cfg(windows)]toast.sound_name("Reminder");toast- .appname("Pomander")+ .appname("Skykeep").summary(&event.title).body(&body).icon(icon_path(&app).unwrap_or("quince"))@@ -484,7 +484,7 @@ fn show_event(app: AppHandle, event: quince_core::calendar::Event, minutes: i64)let mut alert = notify_rust::Notification::new();chime(&mut alert);let shown = alert- .appname("Pomander")+ .appname("Skykeep").summary(&event.title).body(&body).icon(icon_path(&app).unwrap_or("quince"))diff --git a/src-tauri/src/apps.rs b/src-tauri/src/apps.rsindex 9685af1..945e8b3 100644--- a/src-tauri/src/apps.rs+++ b/src-tauri/src/apps.rs@@ -1,11 +1,11 @@-//! Pomander as six apps on one engine: Notes, Reminders, Calendar, Contacts, Drive and Photos,-//! each a window of its own, opened from its own launcher entry (`pomander --app notes`) — one+//! Skykeep as six apps on one engine: Notes, Reminders, Calendar, Contacts, Drive and Photos,+//! each a window of its own, opened from its own launcher entry (`skykeep --app notes`) — one//! process, one sign-in, one library and one sync behind all of them, as Microsoft 365 is one//! install with Word and Excel each in the Start menu.//!//! Each window is known to the desktop as its app: on Wayland it says its own app ID, so a//! dock shows Notes and Reminders as two apps with their own icons, each matched to its own-//! launcher entry — not six windows under one Pomander icon. (Measured: GTK 3.24's+//! launcher entry — not six windows under one Skykeep icon. (Measured: GTK 3.24's//! `gdk_wayland_window_set_application_id` sets it per window, within one process.)use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};@@ -55,7 +55,7 @@ pub fn new_asked(args: &[String]) -> Option<&'static str> {/// The calendar and contact files a command line hands over — opened from a file manager,/// as a path (`%F`, Windows) or a `file://` URI (`%U`) — made absolute against `cwd`, the-/// directory the launch came from. Only files of the kinds Pomander opens are taken; any+/// directory the launch came from. Only files of the kinds Skykeep opens are taken; any/// other argument is someone else's business.pub fn files_asked(args: &[String], cwd: &std::path::Path) -> Vec<std::path::PathBuf> {let mut skip_next = false;@@ -241,7 +241,7 @@ pub fn show(window: &tauri::WebviewWindow) {}}-/// On Wayland, the window says it is its app, not Pomander as a whole.+/// On Wayland, the window says it is its app, not Skykeep as a whole.#[cfg(target_os = "linux")]fn own_app_id(window: &tauri::WebviewWindow, id: &str) {use glib::translate::ToGlibPtr;@@ -287,30 +287,30 @@ mod tests {#[test]fn a_launcher_entry_names_its_app() {- assert_eq!(asked(&args(&["pomander", "--app", "notes"])), Some("notes"));+ assert_eq!(asked(&args(&["skykeep", "--app", "notes"])), Some("notes"));assert_eq!(- asked(&args(&["pomander", "--app=reminders"])),+ asked(&args(&["skykeep", "--app=reminders"])),Some("reminders"));assert_eq!(- asked(&args(&["pomander", "--app", "drive"])),+ asked(&args(&["skykeep", "--app", "drive"])),Some("drivews"));- assert_eq!(asked(&args(&["pomander", "--background"])), None);- assert_eq!(asked(&args(&["pomander", "--app", "mail"])), None);- assert_eq!(asked(&args(&["pomander", "--app"])), None);+ assert_eq!(asked(&args(&["skykeep", "--background"])), None);+ assert_eq!(asked(&args(&["skykeep", "--app", "mail"])), None);+ assert_eq!(asked(&args(&["skykeep", "--app"])), None);}#[test]fn a_launcher_action_asks_for_a_quick_capture() {assert_eq!(- new_asked(&args(&["pomander", "--new", "reminder"])),+ new_asked(&args(&["skykeep", "--new", "reminder"])),Some("reminder"));- assert_eq!(new_asked(&args(&["pomander", "--new=note"])), Some("note"));- assert_eq!(new_asked(&args(&["pomander", "--new", "event"])), None);- assert_eq!(new_asked(&args(&["pomander", "--new"])), None);- assert_eq!(new_asked(&args(&["pomander", "--app", "notes"])), None);+ assert_eq!(new_asked(&args(&["skykeep", "--new=note"])), Some("note"));+ assert_eq!(new_asked(&args(&["skykeep", "--new", "event"])), None);+ assert_eq!(new_asked(&args(&["skykeep", "--new"])), None);+ assert_eq!(new_asked(&args(&["skykeep", "--app", "notes"])), None);}#[test]@@ -318,7 +318,7 @@ mod tests {let cwd = std::path::Path::new("/home/a/Downloads");let got = files_asked(&args(&[- "pomander",+ "skykeep","--app","calendar","invite.ics",@@ -337,6 +337,6 @@ mod tests {std::path::PathBuf::from("/home/a/My Events.ics"),]);- assert!(files_asked(&args(&["pomander", "--app", "x.ics"]), cwd).is_empty());+ assert!(files_asked(&args(&["skykeep", "--app", "x.ics"]), cwd).is_empty());}}diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rsnew file mode 100644index 0000000..0f65398--- /dev/null+++ b/src-tauri/src/export.rs@@ -0,0 +1,2106 @@+//! Export Everything: the whole local copy of the person's iCloud, written into a folder they+//! choose in formats any other app opens — Markdown, iCalendar, vCard, CSV and the files+//! themselves. Their data, theirs to keep.+//!+//! Read only from the library and the caches beside it: nothing is asked of Apple, so an export+//! works offline and costs no request. What is not on this computer (a photo never opened, a+//! Drive file never downloaded) is listed rather than fetched.+//!+//! Crash-safe: everything is written into `dest/.partial-<time>` and renamed to its name only+//! once whole. A cancel, an error or a crash never leaves a folder that looks finished; a+//! partial one a crash left is cleared by the next export to the same place.++use crate::{Data, UiResult};+use jiff::tz::TimeZone;+use jiff::Timestamp;+use quince_core::calendar::{Calendar, Event};+use quince_core::contacts::{Contact, PostalAddress};+use quince_core::drive::DriveItem;+use quince_core::export::ExportPhoto;+use quince_core::notes::{Note, NoteFolder};+use quince_core::reminders::{Reminder, ReminderList};+use quince_core::Library;+use serde::Serialize;+use std::collections::{HashMap, HashSet};+use std::io::{Read, Write};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use tauri::{Emitter, State};++/// Told to the window as an export moves along: an [`ExportProgress`].+pub const EVENT: &str = "quince://export";++/// What a cancelled export answers, so the window can tell it from a failure.+pub const CANCELLED: &str = "Export cancelled.";++/// Left inside a partial export, so a later export knows the folder is one of its own leftovers+/// and may clear it — and nothing else.+const MARKER: &str = ".skykeep-export";++static RUNNING: AtomicBool = AtomicBool::new(false);+static CANCEL: AtomicBool = AtomicBool::new(false);+/// The last finished export, the one folder Show in Folder may show.+static LAST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);++/// Where an export is: which service (`step` of `steps`), and how far through it.+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct ExportProgress {+ pub service: &'static str,+ pub step: usize,+ pub steps: usize,+ pub done: u64,+ pub total: u64,+}++/// What a finished export holds.+#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct ExportSummary {+ pub path: String,+ pub notes: usize,+ pub reminders: usize,+ pub contacts: usize,+ pub events: usize,+ pub drive_files: usize,+ pub photos: usize,+ /// Photos left out because no copy is on this computer.+ pub photos_missing: usize,+}++/// Everything an export writes, read from the library at once and then let go of, so the+/// library is never held while files are written.+#[derive(Default)]+pub(crate) struct Snapshot {+ folders: Vec<NoteFolder>,+ notes: Vec<Note>,+ lists: Vec<ReminderList>,+ reminders: Vec<Reminder>,+ contacts: Vec<(Contact, Vec<PostalAddress>)>,+ calendars: Vec<Calendar>,+ events: Vec<Event>,+ drive: Vec<DriveItem>,+ /// `None`: photos were not asked for.+ photos: Option<Vec<ExportPhoto>>,+}++pub(crate) fn gather(lib: &Library, photos: bool) -> Result<Snapshot, String> {+ let e = |e: quince_core::Error| e.to_string();+ let contacts = lib+ .contacts(None)+ .map_err(e)?+ .into_iter()+ .map(|c| {+ let addresses = lib.contact_addresses(&c.guid).unwrap_or_default();+ (c, addresses)+ })+ .collect();+ Ok(Snapshot {+ folders: lib.note_folders().map_err(e)?,+ notes: lib.export_notes().map_err(e)?,+ lists: lib.reminder_lists().map_err(e)?,+ reminders: lib.export_reminders().map_err(e)?,+ contacts,+ calendars: lib.calendars().map_err(e)?,+ events: lib.export_events().map_err(e)?,+ drive: lib.export_drive_items().map_err(e)?,+ photos: if photos {+ Some(lib.export_photos().map_err(e)?)+ } else {+ None+ },+ })+}++/// The caches an export copies from, inside the app's data folder. Only ever read.+pub(crate) struct Sources {+ note_media: PathBuf,+ photos: PathBuf,+ drive_cache: PathBuf,+}++impl Sources {+ pub(crate) fn at(data_dir: &Path) -> Self {+ Self {+ note_media: data_dir.join("note-media"),+ photos: data_dir.join("photos"),+ drive_cache: data_dir.join("drive-cache"),+ }+ }+}++/// Why an export stopped short.+#[derive(Debug, PartialEq, Eq)]+pub(crate) enum Stop {+ Cancelled,+ Failed(String),+}++impl From<std::io::Error> for Stop {+ fn from(e: std::io::Error) -> Self {+ if e.kind() == std::io::ErrorKind::StorageFull {+ Stop::Failed("The disk is full. Free some room, or choose another drive.".into())+ } else {+ Stop::Failed(format!("The export couldn’t be written: {e}"))+ }+ }+}++type Done<T> = Result<T, Stop>;++// ── The folder chosen ──────────────────────────────────────────────────────────────────────++/// A folder no export goes into: the system's own. Writing there would need rights a person+/// should not hand an app, and anything put there is in the way of the system.+fn is_system(p: &Path) -> bool {+ #[cfg(windows)]+ {+ let s = p.to_string_lossy().to_ascii_lowercase();+ let s = s.trim_start_matches(r"\\?\");+ let rest = s.get(2..).unwrap_or("");+ return rest.is_empty()+ || rest == r"\"+ || [+ r"\windows",+ r"\program files",+ r"\program files (x86)",+ r"\programdata",+ ]+ .iter()+ .any(|d| rest == *d || rest.starts_with(&format!(r"{d}\")));+ }+ #[cfg(not(windows))]+ {+ // A person's own places that sit under a system folder: removable drives and the+ // home folders of the distributions that keep them under /var.+ const OURS: [&str; 4] = ["/run/media", "/var/home", "/var/mnt", "/Volumes"];+ if OURS.iter().any(|o| p.starts_with(o) && p != Path::new(o)) {+ return false;+ }+ const SYSTEM: [&str; 24] = [+ "/bin",+ "/boot",+ "/dev",+ "/etc",+ "/efi",+ "/lib",+ "/lib32",+ "/lib64",+ "/libx32",+ "/nix",+ "/opt",+ "/proc",+ "/root",+ "/run",+ "/sbin",+ "/snap",+ "/srv",+ "/sys",+ "/usr",+ "/var",+ "/System",+ "/Library",+ "/Applications",+ "/private",+ ];+ p == Path::new("/")+ || p == Path::new("/home")+ || p == Path::new("/Users")+ || SYSTEM.iter().any(|d| p.starts_with(d))+ }+}++/// The folder an export may go into, made absolute and real — or why not.+///+/// Never inside the app's own data (an export there would be copied into the next export, and+/// cleared with the caches), never in a folder that is iCloud itself (`synced`: the Drive and+/// Photos folders, where every file written goes up), and never in a system folder.+pub(crate) fn check_dest(+ dest: &Path,+ data_dir: &Path,+ synced: &[PathBuf],+) -> Result<PathBuf, String> {+ if dest.as_os_str().is_empty() || !dest.is_absolute() {+ return Err("Choose a folder to export into.".into());+ }+ let real =+ std::fs::canonicalize(dest).map_err(|_| "That folder isn’t there any more.".to_string())?;+ if !real.is_dir() {+ return Err("Choose a folder to export into.".into());+ }+ let data = std::fs::canonicalize(data_dir).unwrap_or_else(|_| data_dir.to_path_buf());+ if real.starts_with(&data) {+ return Err("That folder holds Skykeep’s own data. Choose another one.".into());+ }+ for s in synced {+ let s = std::fs::canonicalize(s).unwrap_or_else(|_| s.clone());+ if real.starts_with(&s) {+ return Err("That folder is in iCloud: everything put there would upload again. Choose one on this computer.".into());+ }+ }+ if is_system(&real) {+ return Err("That’s a system folder. Choose one in your home folder or on a drive.".into());+ }+ Ok(real)+}++// ── Names ──────────────────────────────────────────────────────────────────────────────────++/// A name made safe to be one file name on every system (see [`crate::attachment_name`]): no+/// path in it, nothing hidden, nothing reversed; `fallback` when nothing is left.+pub(crate) fn file_name(given: &str, fallback: &str) -> String {+ let cleaned = crate::attachment_name(Some(given), "");+ // `attachment_name` names an empty one after the id, and the id given was empty.+ if cleaned == "Attachment " {+ return fallback.to_string();+ }+ // Cut short at its length limit, it can end in a space, which Windows will not keep.+ cleaned.trim_end_matches(['.', ' ']).to_string()+}++/// Names taken so far, folder by folder, ignoring case — Windows and macOS do.+#[derive(Default)]+struct Names(HashSet<String>);++impl Names {+ /// `stem.ext` in `dir`, or `stem 2.ext`, `stem 3.ext` … when it is taken.+ fn unique(&mut self, dir: &Path, stem: &str, ext: &str) -> String {+ let dot = if ext.is_empty() { "" } else { "." };+ let mut n = 1;+ loop {+ let name = if n == 1 {+ format!("{stem}{dot}{ext}")+ } else {+ format!("{stem} {n}{dot}{ext}")+ };+ let key = dir.join(&name).to_string_lossy().to_lowercase();+ if self.0.insert(key) {+ return name;+ }+ n += 1;+ }+ }+}++/// A name split into its stem and extension (`""` for none).+fn split_ext(name: &str) -> (&str, &str) {+ match name.rsplit_once('.') {+ Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() && ext.len() <= 8 => (stem, ext),+ _ => (name, ""),+ }+}++/// What a file is, by its first bytes, as an extension; `None` when it can't be told.+fn sniff(path: &Path) -> Option<&'static str> {+ let mut head = [0u8; 16];+ let n = std::fs::File::open(path)+ .and_then(|mut f| f.read(&mut head))+ .ok()?;+ let h = &head[..n];+ Some(if h.starts_with(&[0xFF, 0xD8, 0xFF]) {+ "jpg"+ } else if h.starts_with(b"\x89PNG") {+ "png"+ } else if h.starts_with(b"GIF8") {+ "gif"+ } else if h.starts_with(b"%PDF") {+ "pdf"+ } else if h.len() >= 12 && &h[4..8] == b"ftyp" {+ match &h[8..12] {+ b"heic" | b"heix" | b"mif1" | b"msf1" | b"heim" | b"heis" => "heic",+ b"qt " => "mov",+ _ => "mp4",+ }+ } else if h.starts_with(b"PK\x03\x04") {+ "zip"+ } else {+ return None;+ })+}++// ── Writing ────────────────────────────────────────────────────────────────────────────────++/// One file's text, written whole.+fn write(path: &Path, text: &str) -> Done<()> {+ std::fs::write(path, text)?;+ Ok(())+}++/// A file copied a megabyte at a time, stopping between any two when asked to.+fn copy(from: &Path, to: &Path, cancel: &AtomicBool) -> Done<u64> {+ let mut src = std::fs::File::open(from)?;+ let mut dst = std::fs::File::create(to)?;+ let mut buf = vec![0u8; 1 << 20];+ let mut total = 0u64;+ loop {+ if cancel.load(Ordering::Relaxed) {+ return Err(Stop::Cancelled);+ }+ let n = src.read(&mut buf)?;+ if n == 0 {+ break;+ }+ dst.write_all(&buf[..n])?;+ total += n as u64;+ }+ dst.flush()?;+ Ok(total)+}++/// Dated as the thing it holds was last changed, so a file manager sorts it truly.+fn date(path: &Path, at: Option<i64>) {+ let Some(at) = at.and_then(|s| u64::try_from(s).ok()) else {+ return;+ };+ let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(at);+ if let Ok(f) = std::fs::File::options().write(true).open(path) {+ let _ = f.set_modified(when);+ }+}++/// Progress, told no more than every tenth of a second, and always at a service's start and+/// end.+struct Ticker<'a> {+ step: usize,+ steps: usize,+ last: std::time::Instant,+ tell: &'a mut dyn FnMut(ExportProgress),+ cancel: &'a AtomicBool,+}++impl Ticker<'_> {+ fn start(&mut self, service: &'static str, total: u64) -> Done<()> {+ self.step += 1;+ self.last = std::time::Instant::now();+ self.send(service, 0, total);+ self.check()+ }+ fn tick(&mut self, service: &'static str, done: u64, total: u64) -> Done<()> {+ if done >= total || self.last.elapsed() >= std::time::Duration::from_millis(100) {+ self.last = std::time::Instant::now();+ self.send(service, done, total);+ }+ self.check()+ }+ fn send(&mut self, service: &'static str, done: u64, total: u64) {+ (self.tell)(ExportProgress {+ service,+ step: self.step,+ steps: self.steps,+ done: done.min(total),+ total,+ });+ }+ fn check(&self) -> Done<()> {+ if self.cancel.load(Ordering::Relaxed) {+ Err(Stop::Cancelled)+ } else {+ Ok(())+ }+ }+}++// ── iCalendar and vCard ────────────────────────────────────────────────────────────────────++/// Text as a property value: backslash, semicolon, comma and line breaks escaped (RFC 5545+/// §3.3.11, RFC 6350 §3.4).+fn escape(v: &str) -> String {+ let mut out = String::with_capacity(v.len());+ let v = v.replace("\r\n", "\n").replace('\r', "\n");+ for c in v.chars() {+ match c {+ '\\' => out.push_str("\\\\"),+ ';' => out.push_str("\\;"),+ ',' => out.push_str("\\,"),+ '\n' => out.push_str("\\n"),+ c if c.is_control() && c != '\t' => {}+ c => out.push(c),+ }+ }+ out+}++/// One content line, folded at 75 octets — never inside a character — and ended with CRLF.+fn line(out: &mut String, text: &str) {+ let mut width = 0;+ for c in text.chars() {+ let len = c.len_utf8();+ if width + len > 75 {+ out.push_str("\r\n ");+ width = 1;+ }+ out.push(c);+ width += len;+ }+ out.push_str("\r\n");+}++fn utc(ts: i64) -> String {+ Timestamp::from_second(ts)+ .map(|t| t.strftime("%Y%m%dT%H%M%SZ").to_string())+ .unwrap_or_else(|_| "19700101T000000Z".into())+}++/// The zone a record names, or this computer's.+fn zone_of(name: Option<&str>, fallback: &TimeZone) -> TimeZone {+ name.and_then(|n| TimeZone::get(n).ok())+ .unwrap_or_else(|| fallback.clone())+}++fn day(ts: i64, tz: &TimeZone) -> String {+ Timestamp::from_second(ts)+ .map(|t| t.to_zoned(tz.clone()).strftime("%Y%m%d").to_string())+ .unwrap_or_else(|_| "19700101".into())+}++fn calendar_head(out: &mut String, name: &str) {+ line(out, "BEGIN:VCALENDAR");+ line(out, "VERSION:2.0");+ line(out, "PRODID:-//Skykeep//Export Everything//EN");+ line(out, "CALSCALE:GREGORIAN");+ line(out, &format!("X-WR-CALNAME:{}", escape(name)));+}++fn event_ics(out: &mut String, e: &Event, stamp: &str, tz: &TimeZone) {+ line(out, "BEGIN:VEVENT");+ line(out, &format!("UID:{}", escape(&e.guid)));+ line(out, &format!("DTSTAMP:{stamp}"));+ if e.all_day {+ let tz = zone_of(e.timezone.as_deref(), tz);+ line(+ out,+ &format!("DTSTART;VALUE=DATE:{}", day(e.starts_at, &tz)),+ );+ let end = if e.ends_at > e.starts_at {+ e.ends_at+ } else {+ e.starts_at + 86_400+ };+ line(out, &format!("DTEND;VALUE=DATE:{}", day(end, &tz)));+ } else {+ line(out, &format!("DTSTART:{}", utc(e.starts_at)));+ line(out, &format!("DTEND:{}", utc(e.ends_at.max(e.starts_at))));+ }+ line(out, &format!("SUMMARY:{}", escape(&e.title)));+ if let Some(l) = e.location.as_deref().filter(|s| !s.is_empty()) {+ line(out, &format!("LOCATION:{}", escape(l)));+ }+ if let Some(n) = e.notes.as_deref().filter(|s| !s.is_empty()) {+ line(out, &format!("DESCRIPTION:{}", escape(n)));+ }+ if let Some(u) = e.url.as_deref().filter(|s| !s.is_empty()) {+ line(out, &format!("URL:{}", escape(u)));+ }+ line(out, "END:VEVENT");+}++/// Apple's repeat frequency (0 daily … 3 yearly) as an RRULE.+fn rrule(r: &Reminder) -> Option<String> {+ let freq = match r.recur_frequency? {+ 0 => "DAILY",+ 1 => "WEEKLY",+ 2 => "MONTHLY",+ 3 => "YEARLY",+ _ => return None,+ };+ let interval = r.recur_interval.unwrap_or(1).max(1);+ Some(format!("RRULE:FREQ={freq};INTERVAL={interval}"))+}++fn todo_ics(out: &mut String, r: &Reminder, stamp: &str, tz: &TimeZone) {+ line(out, "BEGIN:VTODO");+ line(out, &format!("UID:{}", escape(&r.guid)));+ line(out, &format!("DTSTAMP:{stamp}"));+ line(out, &format!("SUMMARY:{}", escape(&r.title)));+ if let Some(n) = r.notes.as_deref().filter(|s| !s.is_empty()) {+ line(out, &format!("DESCRIPTION:{}", escape(n)));+ }+ if let Some(due) = r.due_at {+ if r.all_day {+ let tz = zone_of(r.timezone.as_deref(), tz);+ line(out, &format!("DUE;VALUE=DATE:{}", day(due, &tz)));+ } else {+ line(out, &format!("DUE:{}", utc(due)));+ }+ }+ match r.completed_at {+ Some(at) => {+ line(out, "STATUS:COMPLETED");+ line(out, &format!("COMPLETED:{}", utc(at)));+ }+ None => line(out, "STATUS:NEEDS-ACTION"),+ }+ // Apple's scale is iCalendar's: 1 high … 9 low, 0 none.+ if (1..=9).contains(&r.priority) {+ line(out, &format!("PRIORITY:{}", r.priority));+ }+ if r.flagged {+ line(out, "CATEGORIES:Flagged");+ line(out, "X-APPLE-FLAGGED:TRUE");+ }+ if let Some(p) = &r.parent_guid {+ line(out, &format!("RELATED-TO;RELTYPE=PARENT:{}", escape(p)));+ }+ if let Some(rule) = rrule(r) {+ line(out, &rule);+ }+ line(out, "END:VTODO");+}++/// A label as a `TYPE=` value: Apple's `_$!<Mobile>!$_` read as `Mobile`, quoted when it has+/// anything a parameter can't hold bare.+fn type_param(label: Option<&str>) -> String {+ let Some(label) = label else {+ return String::new();+ };+ let plain = label+ .trim_start_matches("_$!<")+ .trim_end_matches(">!$_")+ .replace(['"', '\r', '\n'], "");+ if plain.trim().is_empty() {+ return String::new();+ }+ if plain.contains([',', ';', ':']) {+ format!(";TYPE=\"{plain}\"")+ } else {+ format!(";TYPE={plain}")+ }+}++fn vcard(out: &mut String, c: &Contact, addresses: &[PostalAddress]) {+ let s = |v: &Option<String>| escape(v.as_deref().unwrap_or(""));+ line(out, "BEGIN:VCARD");+ line(out, "VERSION:3.0");+ line(out, &format!("UID:{}", escape(&c.guid)));+ line(+ out,+ &format!(+ "N:{};{};{};;",+ s(&c.last_name),+ s(&c.first_name),+ s(&c.middle_name)+ ),+ );+ line(out, &format!("FN:{}", escape(&c.display_name())));+ if let Some(o) = c.company.as_deref().filter(|s| !s.is_empty()) {+ line(out, &format!("ORG:{}", escape(o)));+ }+ if c.is_company {+ line(out, "X-ABShowAs:COMPANY");+ }+ if let Some(b) = c.birthday.as_deref().filter(|s| !s.is_empty()) {+ line(out, &format!("BDAY:{}", escape(b)));+ }+ for m in &c.methods {+ let t = type_param(m.label.as_deref());+ let v = escape(&m.value);+ match m.kind.as_str() {+ "phone" => line(out, &format!("TEL{t}:{v}")),+ "email" => line(out, &format!("EMAIL;TYPE=INTERNET{t}:{v}")),+ "url" => line(out, &format!("URL{t}:{v}")),+ // Written whole from its parts below; a card with none kept keeps its lines.+ "address" if !addresses.is_empty() => {}+ "address" => line(out, &format!("ADR{t}:;;{v};;;;")),+ other => {+ let name: String = other+ .chars()+ .filter(char::is_ascii_alphanumeric)+ .collect::<String>()+ .to_ascii_uppercase();+ let name = if name.is_empty() {+ "OTHER".into()+ } else {+ name+ };+ line(out, &format!("X-{name}{t}:{v}"));+ }+ }+ }+ for a in addresses {+ let t = type_param(a.label.as_deref());+ line(+ out,+ &format!(+ "ADR{t}:;;{};{};{};{};{}",+ s(&a.street),+ s(&a.city),+ s(&a.state),+ s(&a.postal_code),+ s(&a.country)+ ),+ );+ }+ if let Some(n) = c.notes.as_deref().filter(|s| !s.is_empty()) {+ line(out, &format!("NOTE:{}", escape(n)));+ }+ line(out, "END:VCARD");+}++fn csv_field(v: &str) -> String {+ if v.contains([',', '"', '\n', '\r']) {+ format!("\"{}\"", v.replace('"', "\"\""))+ } else {+ v.to_string()+ }+}++// ── The export ─────────────────────────────────────────────────────────────────────────────++/// Clear partial exports a crash left in `dest` — only folders this exporter marked as its own.+fn clear_leftovers(dest: &Path) {+ let Ok(entries) = std::fs::read_dir(dest) else {+ return;+ };+ for e in entries.flatten() {+ let name = e.file_name();+ if name.to_string_lossy().starts_with(".partial-") && e.path().join(MARKER).is_file() {+ let _ = std::fs::remove_dir_all(e.path());+ }+ }+}++/// Export everything in `snap` into a new folder in `dest`, which [`check_dest`] has passed.+/// Answers what was written; on a cancel or an error, nothing is left behind.+pub(crate) fn run(+ snap: &Snapshot,+ src: &Sources,+ dest: &Path,+ now: &jiff::Zoned,+ cancel: &AtomicBool,+ tell: &mut dyn FnMut(ExportProgress),+) -> Done<ExportSummary> {+ clear_leftovers(dest);+ let partial = dest.join(format!(".partial-{}", now.timestamp().as_millisecond()));+ std::fs::create_dir(&partial)?;+ std::fs::write(partial.join(MARKER), b"")?;+ let made = (|| {+ let mut summary = write_all(snap, src, &partial, now, cancel, tell)?;+ std::fs::remove_file(partial.join(MARKER))?;+ let stem = format!("Skykeep Export {}", now.strftime("%Y-%m-%d %H.%M"));+ let mut n = 1;+ let fin = loop {+ let name = if n == 1 {+ stem.clone()+ } else {+ format!("{stem} {n}")+ };+ let at = dest.join(name);+ if !at.exists() {+ break at;+ }+ n += 1;+ };+ if cancel.load(Ordering::Relaxed) {+ return Err(Stop::Cancelled);+ }+ std::fs::rename(&partial, &fin)?;+ summary.path = fin.to_string_lossy().into_owned();+ Ok(summary)+ })();+ if made.is_err() {+ let _ = std::fs::remove_dir_all(&partial);+ }+ made+}++fn write_all(+ snap: &Snapshot,+ src: &Sources,+ root: &Path,+ now: &jiff::Zoned,+ cancel: &AtomicBool,+ tell: &mut dyn FnMut(ExportProgress),+) -> Done<ExportSummary> {+ let tz = now.time_zone().clone();+ let stamp = utc(now.timestamp().as_second());+ let mut t = Ticker {+ step: 0,+ steps: 5 + usize::from(snap.photos.is_some()),+ last: std::time::Instant::now(),+ tell,+ cancel,+ };+ let mut names = Names::default();+ let mut summary = ExportSummary::default();+ let mut readme = Readme::default();++ notes(+ snap,+ src,+ root,+ &mut names,+ &mut t,+ &mut summary,+ &mut readme,+ )?;+ reminders(snap, root, &tz, &stamp, &mut names, &mut t, &mut summary)?;+ contacts(snap, root, &mut t, &mut summary)?;+ calendars(snap, root, &tz, &stamp, &mut names, &mut t, &mut summary)?;+ drive(+ snap,+ src,+ root,+ &mut names,+ &mut t,+ &mut summary,+ &mut readme,+ )?;+ if let Some(photos) = &snap.photos {+ self::photos(photos, src, root, &tz, &mut names, &mut t, &mut summary)?;+ }+ write(&root.join("README.txt"), &readme.text(&summary, snap, now))?;+ Ok(summary)+}++/// What the README says beyond the counts: what was left out, and why.+#[derive(Default)]+struct Readme {+ notes_locked: usize,+ notes_unread: usize,+ attachments_missing: usize,+ drive_missing: usize,+}++impl Readme {+ fn text(&self, s: &ExportSummary, snap: &Snapshot, now: &jiff::Zoned) -> String {+ let mut o = String::new();+ let mut l = |t: &str| {+ o.push_str(t);+ o.push('\n');+ };+ l("Skykeep Export");+ l("===============");+ l("");+ l(&format!(+ "Made {} from the copy of your iCloud kept on this computer.",+ now.strftime("%A %-d %B %Y at %H:%M %Z")+ ));+ l("Everything here is in an open format any app can read. Nothing was sent anywhere.");+ l("");+ let n =+ |k: usize, one: &str, many: &str| format!("{k} {}", if k == 1 { one } else { many });+ let be = |k: usize| if k == 1 { "is" } else { "are" };+ let was = |k: usize| if k == 1 { "wasn’t" } else { "weren’t" };+ l(&format!(+ "Notes/ {} as Markdown (.md), in folders as they are in Notes.",+ n(s.notes, "note", "notes")+ ));+ l(" A note's pictures and files sit beside it when they were on this computer.");+ l(&format!(+ "Reminders/ {}: each list as iCalendar (.ics, to-dos) and as a readable .md.",+ n(s.reminders, "reminder", "reminders")+ ));+ l(&format!(+ "Contacts/ {} in one vCard file (.vcf).",+ n(s.contacts, "contact", "contacts")+ ));+ l(&format!(+ "Calendar/ {}: each calendar as iCalendar (.ics).",+ n(s.events, "event", "events")+ ));+ l(&format!(+ "iCloud Drive/ Listing.csv lists every file and folder Skykeep has seen; Files/ holds the {} downloaded to this computer.",+ n(s.drive_files, "file", "files")+ ));+ if snap.photos.is_some() {+ l(&format!(+ "Photos/ {} by year and month (YYYY/MM).",+ n(s.photos, "photo or video", "photos and videos")+ ));+ } else {+ l("Photos Not included: photos were left out of this export.");+ }+ l("");+ l("Good to know");+ l("------------");+ l("- Repeating events are written as stored: each occurrence this computer holds is its own event, without the repeat rule. Occurrences outside the range Skykeep keeps are not in the file.");+ l("- In the .ics files times are in UTC, which every calendar app shows in your own time zone; all-day events and reminders are dates.");+ if self.notes_locked > 0 {+ l(&format!(+ "- {} {} not included: a locked note's text is encrypted with a password only you hold.",+ n(self.notes_locked, "locked note", "locked notes"),+ be(self.notes_locked)+ ));+ }+ if self.notes_unread > 0 {+ l(&format!(+ "- {} {} not included: the text hasn’t been downloaded to this computer yet.",+ n(self.notes_unread, "note", "notes"),+ be(self.notes_unread)+ ));+ }+ if self.attachments_missing > 0 {+ l(&format!(+ "- {} {} on this computer, so {} not included. Open those notes in Skykeep to download them.",+ n(self.attachments_missing, "note attachment", "note attachments"),+ was(self.attachments_missing),+ if self.attachments_missing == 1 { "it is" } else { "they are" }+ ));+ }+ if self.drive_missing > 0 {+ l(&format!(+ "- {} {} downloaded to this computer: listed in Listing.csv, not in Files/.",+ n(self.drive_missing, "Drive file", "Drive files"),+ was(self.drive_missing)+ ));+ }+ if s.photos_missing > 0 {+ l(&format!(+ "- {} {} on this computer; Photos/Not Included.txt lists them.",+ n(s.photos_missing, "photo", "photos"),+ was(s.photos_missing)+ ));+ }+ o+ }+}++fn notes(+ snap: &Snapshot,+ src: &Sources,+ root: &Path,+ names: &mut Names,+ t: &mut Ticker<'_>,+ summary: &mut ExportSummary,+ readme: &mut Readme,+) -> Done<()> {+ let total = snap.notes.len() as u64;+ t.start("notes", total)?;+ let base = root.join("Notes");+ std::fs::create_dir(&base)?;+ let by_guid: HashMap<&str, &NoteFolder> =+ snap.folders.iter().map(|f| (f.guid.as_str(), f)).collect();+ let mut dirs: HashMap<String, PathBuf> = HashMap::new();++ for (i, note) in snap.notes.iter().enumerate() {+ t.tick("notes", i as u64, total)?;+ if note.locked {+ readme.notes_locked += 1;+ continue;+ }+ let body = match ¬e.body {+ Some(b) => b.clone(),+ None if note.title.trim().is_empty()+ && note.snippet.as_deref().unwrap_or("").trim().is_empty() =>+ {+ String::new()+ }+ None => {+ readme.notes_unread += 1;+ continue;+ }+ };+ let dir = match note.folder_guid.as_deref() {+ Some(g) if by_guid.contains_key(g) => {+ folder_dir(g, &by_guid, &base, names, &mut dirs, 0)?+ }+ _ => base.clone(),+ };+ let runs: Vec<quince_icloud::ckdocument::Run> = note+ .runs+ .as_deref()+ .and_then(|r| serde_json::from_str(r).ok())+ .unwrap_or_default();+ let mut md = quince_icloud::markdown::note_to_markdown(&body, &runs);+ let stem = file_name(¬e.title, "Untitled");+ let file = names.unique(&dir, &stem, "md");+ let file_stem = split_ext(&file).0.to_string();++ // Its attachments, in the order they stand in the text, copied beside it when they+ // are on this computer and linked from the foot of the note.+ let mut seen = HashSet::new();+ let mut links = Vec::new();+ for id in runs.iter().filter_map(|r| r.attachment.as_deref()) {+ if !seen.insert(id) {+ continue;+ }+ let safe = crate::media_file_id(id);+ let found = ["file", "drawing", "preview"]+ .iter()+ .map(|part| src.note_media.join(format!("{safe}-{part}")))+ .find(|p| p.is_file());+ let Some(from) = found else {+ // A table is an attachment with no file: nothing is missing.+ if !id.to_ascii_lowercase().contains("table") {+ readme.attachments_missing += 1;+ }+ continue;+ };+ let ext = sniff(&from).unwrap_or("bin");+ let name = names.unique(&dir, &format!("{file_stem} - {}", links.len() + 1), ext);+ copy(&from, &dir.join(&name), t.cancel)?;+ links.push((name, matches!(ext, "jpg" | "png" | "gif" | "heic")));+ }+ if !links.is_empty() {+ md.push_str("\n\n---\n\n");+ for (name, picture) in &links {+ let target = name+ .replace(' ', "%20")+ .replace('(', "%28")+ .replace(')', "%29");+ if *picture {+ md.push_str(&format!("\n\n"));+ } else {+ md.push_str(&format!("[{name}]({target})\n\n"));+ }+ }+ }+ let path = dir.join(&file);+ write(&path, &md)?;+ date(&path, note.modified_at.or(note.created_at));+ summary.notes += 1;+ }+ t.tick("notes", total, total)+}++/// A note folder's directory under `base`, its parents made first; made once and remembered.+fn folder_dir(+ guid: &str,+ by_guid: &HashMap<&str, &NoteFolder>,+ base: &Path,+ names: &mut Names,+ dirs: &mut HashMap<String, PathBuf>,+ depth: usize,+) -> Done<PathBuf> {+ if let Some(d) = dirs.get(guid) {+ return Ok(d.clone());+ }+ let Some(f) = by_guid.get(guid) else {+ return Ok(base.to_path_buf());+ };+ // A loop in the parents (a folder moved inside its own child, half-synced) stops here.+ let parent = match f.parent_guid.as_deref() {+ Some(p) if depth < 32 && p != guid && by_guid.contains_key(p) => {+ folder_dir(p, by_guid, base, names, dirs, depth + 1)?+ }+ _ => base.to_path_buf(),+ };+ let title = if f.is_trash() {+ "Recently Deleted"+ } else {+ &f.title+ };+ let name = names.unique(&parent, &file_name(title, "Folder"), "");+ let dir = parent.join(name);+ std::fs::create_dir_all(&dir)?;+ dirs.insert(guid.to_string(), dir.clone());+ Ok(dir)+}++fn reminders(+ snap: &Snapshot,+ root: &Path,+ tz: &TimeZone,+ stamp: &str,+ names: &mut Names,+ t: &mut Ticker<'_>,+ summary: &mut ExportSummary,+) -> Done<()> {+ let base = root.join("Reminders");+ std::fs::create_dir(&base)?;+ let mut by_list: HashMap<&str, Vec<&Reminder>> = HashMap::new();+ for r in &snap.reminders {+ by_list.entry(r.list_guid.as_str()).or_default().push(r);+ }+ // Lists in their own order, then reminders in a list this computer doesn't know.+ let mut lists: Vec<(String, &str)> = snap+ .lists+ .iter()+ .map(|l| (l.title.clone(), l.guid.as_str()))+ .collect();+ let known: HashSet<&str> = snap.lists.iter().map(|l| l.guid.as_str()).collect();+ let mut stray: Vec<&str> = by_list+ .keys()+ .copied()+ .filter(|g| !known.contains(g))+ .collect();+ stray.sort_unstable();+ lists.extend(+ stray+ .into_iter()+ .map(|g| ("Other Reminders".to_string(), g)),+ );++ let total = lists.len() as u64;+ t.start("reminders", total)?;+ for (i, (title, guid)) in lists.iter().enumerate() {+ t.tick("reminders", i as u64, total)?;+ let items = by_list.get(guid).map(Vec::as_slice).unwrap_or_default();+ let stem = file_name(title, "Reminders");+ // One stem for both files, so the pair stays together.+ let ics_name = names.unique(&base, &stem, "ics");+ let stem = split_ext(&ics_name).0.to_string();+ let md_name = names.unique(&base, &stem, "md");++ let mut ics = String::new();+ calendar_head(&mut ics, title);+ for r in items {+ todo_ics(&mut ics, r, stamp, tz);+ }+ line(&mut ics, "END:VCALENDAR");+ write(&base.join(ics_name), &ics)?;+ write(&base.join(md_name), &reminders_md(title, items, tz))?;+ summary.reminders += items.len();+ }+ t.tick("reminders", total, total)+}++/// A list as a person reads it: a checklist, subtasks under theirs, done ones ticked.+fn reminders_md(title: &str, items: &[&Reminder], tz: &TimeZone) -> String {+ let ids: HashSet<&str> = items.iter().map(|r| r.guid.as_str()).collect();+ let mut children: HashMap<&str, Vec<&Reminder>> = HashMap::new();+ let mut top = Vec::new();+ for r in items {+ match r.parent_guid.as_deref() {+ Some(p) if ids.contains(p) && p != r.guid => children.entry(p).or_default().push(r),+ _ => top.push(*r),+ }+ }+ let mut o = format!("# {title}\n\n");+ if items.is_empty() {+ o.push_str("No reminders.\n");+ }+ fn one(+ o: &mut String,+ r: &Reminder,+ depth: usize,+ children: &HashMap<&str, Vec<&Reminder>>,+ tz: &TimeZone,+ ) {+ let pad = " ".repeat(depth);+ let tick = if r.completed_at.is_some() { "x" } else { " " };+ let mut extra = Vec::new();+ if let Some(due) = r.due_at.and_then(|d| Timestamp::from_second(d).ok()) {+ let z = due.to_zoned(zone_of(r.timezone.as_deref(), tz));+ extra.push(if r.all_day {+ format!("due {}", z.strftime("%-d %b %Y"))+ } else {+ format!("due {}", z.strftime("%-d %b %Y, %H:%M"))+ });+ }+ if r.flagged {+ extra.push("flagged".into());+ }+ match r.priority {+ 1..=4 => extra.push("high priority".into()),+ 5 => extra.push("medium priority".into()),+ 6..=9 => extra.push("low priority".into()),+ _ => {}+ }+ if let Some(rule) = rrule(r) {+ let every = rule+ .trim_start_matches("RRULE:FREQ=")+ .split(';')+ .next()+ .unwrap_or("")+ .to_ascii_lowercase();+ extra.push(format!("repeats {every}"));+ }+ let title = r.title.replace('\n', " ");+ let tail = if extra.is_empty() {+ String::new()+ } else {+ format!(" — {}", extra.join(", "))+ };+ o.push_str(&format!("{pad}- [{tick}] {title}{tail}\n"));+ if let Some(n) = r.notes.as_deref().filter(|n| !n.trim().is_empty()) {+ for l in n.lines() {+ o.push_str(&format!("{pad} {l}\n"));+ }+ }+ if depth < 8 {+ for c in children.get(r.guid.as_str()).into_iter().flatten() {+ one(o, c, depth + 1, children, tz);+ }+ }+ }+ for r in top {+ one(&mut o, r, 0, &children, tz);+ }+ o+}++fn contacts(+ snap: &Snapshot,+ root: &Path,+ t: &mut Ticker<'_>,+ summary: &mut ExportSummary,+) -> Done<()> {+ let total = snap.contacts.len() as u64;+ t.start("contacts", total)?;+ let base = root.join("Contacts");+ std::fs::create_dir(&base)?;+ let mut out = String::new();+ for (i, (c, addresses)) in snap.contacts.iter().enumerate() {+ t.tick("contacts", i as u64, total)?;+ vcard(&mut out, c, addresses);+ }+ write(&base.join("Contacts.vcf"), &out)?;+ summary.contacts = snap.contacts.len();+ t.tick("contacts", total, total)+}++fn calendars(+ snap: &Snapshot,+ root: &Path,+ tz: &TimeZone,+ stamp: &str,+ names: &mut Names,+ t: &mut Ticker<'_>,+ summary: &mut ExportSummary,+) -> Done<()> {+ let base = root.join("Calendar");+ std::fs::create_dir(&base)?;+ let mut by_cal: HashMap<&str, Vec<&Event>> = HashMap::new();+ for e in &snap.events {+ by_cal.entry(e.calendar_guid.as_str()).or_default().push(e);+ }+ let mut cals: Vec<(String, &str)> = snap+ .calendars+ .iter()+ .map(|c| (c.title.clone(), c.guid.as_str()))+ .collect();+ let known: HashSet<&str> = snap.calendars.iter().map(|c| c.guid.as_str()).collect();+ let mut stray: Vec<&str> = by_cal+ .keys()+ .copied()+ .filter(|g| !known.contains(g))+ .collect();+ stray.sort_unstable();+ cals.extend(stray.into_iter().map(|g| ("Other Events".to_string(), g)));++ let total = cals.len() as u64;+ t.start("calendar", total)?;+ for (i, (title, guid)) in cals.iter().enumerate() {+ t.tick("calendar", i as u64, total)?;+ let items = by_cal.get(guid).map(Vec::as_slice).unwrap_or_default();+ let mut ics = String::new();+ calendar_head(&mut ics, title);+ for e in items {+ event_ics(&mut ics, e, stamp, tz);+ }+ line(&mut ics, "END:VCALENDAR");+ let name = names.unique(&base, &file_name(title, "Calendar"), "ics");+ write(&base.join(name), &ics)?;+ summary.events += items.len();+ }+ t.tick("calendar", total, total)+}++/// A Drive item's path under the Drive's root, folder names made safe, from its parents.+fn drive_path(item: &DriveItem, by_id: &HashMap<&str, &DriveItem>) -> Vec<String> {+ let mut parts = vec![file_name(&item.display_name(), "Untitled")];+ let mut at = item.parent_id.as_deref();+ let mut guard = 0;+ while let Some(p) = at.and_then(|id| by_id.get(id)) {+ if p.drivewsid == quince_core::drive::ROOT || guard > 64 {+ break;+ }+ parts.push(file_name(&p.display_name(), "Folder"));+ at = p.parent_id.as_deref();+ guard += 1;+ }+ parts.reverse();+ parts+}++/// Where the Drive cache keeps a file's bytes, and whether every one of them is there — as+/// `quince_vfs::Cache` names and marks them, read without opening (or making) the cache.+fn drive_cached(dir: &Path, item: &DriveItem) -> Option<PathBuf> {+ let safe = |s: &str| -> String {+ s.chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })+ .collect()+ };+ let path = dir.join(format!(+ "{}~{}",+ safe(&item.drivewsid),+ safe(item.etag.as_deref().unwrap_or("-"))+ ));+ let size = u64::try_from(item.size.unwrap_or(0)).unwrap_or(0);+ if size == 0 {+ return None;+ }+ let chunks = usize::try_from(size.div_ceil(quince_vfs::CHUNK)).unwrap_or(usize::MAX);+ let have = std::fs::read(path.with_extension("have")).ok()?;+ let whole = have.len() >= chunks && have[..chunks].iter().all(|&b| b == 1);+ let len = std::fs::metadata(&path).ok()?.len();+ (whole && len >= size).then_some(path)+}++fn drive(+ snap: &Snapshot,+ src: &Sources,+ root: &Path,+ names: &mut Names,+ t: &mut Ticker<'_>,+ summary: &mut ExportSummary,+ readme: &mut Readme,+) -> Done<()> {+ let total = snap.drive.len() as u64;+ t.start("drive", total)?;+ let base = root.join("iCloud Drive");+ let files = base.join("Files");+ std::fs::create_dir_all(&files)?;+ let by_id: HashMap<&str, &DriveItem> = snap+ .drive+ .iter()+ .map(|d| (d.drivewsid.as_str(), d))+ .collect();+ let mut rows: Vec<(String, &DriveItem, bool)> = Vec::new();+ let time = |s: Option<i64>| {+ s.and_then(|s| Timestamp::from_second(s).ok())+ .map(|t| t.to_string())+ .unwrap_or_default()+ };+ for (i, item) in snap.drive.iter().enumerate() {+ t.tick("drive", i as u64, total)?;+ if item.drivewsid == quince_core::drive::ROOT {+ continue;+ }+ let parts = drive_path(item, &by_id);+ let shown = parts.join("/");+ let size = u64::try_from(item.size.unwrap_or(0)).unwrap_or(0);+ // An empty file is whole without any bytes; any other only when the cache has all.+ let cached = drive_cached(&src.drive_cache, item);+ let copied = !item.is_container() && (size == 0 || cached.is_some());+ if !item.is_container() && !copied {+ readme.drive_missing += 1;+ }+ if copied {+ let mut dir = files.clone();+ for p in &parts[..parts.len() - 1] {+ dir.push(p);+ }+ std::fs::create_dir_all(&dir)?;+ let (stem, ext) = split_ext(&parts[parts.len() - 1]);+ let to = dir.join(names.unique(&dir, stem, ext));+ match cached {+ Some(from) => {+ copy(&from, &to, t.cancel)?;+ // The cache's file may run past the end of the file it holds.+ std::fs::OpenOptions::new()+ .write(true)+ .open(&to)?+ .set_len(size)?;+ }+ None => {+ std::fs::File::create(&to)?;+ }+ }+ date(&to, item.modified_at);+ summary.drive_files += 1;+ }+ rows.push((shown, item, copied));+ }+ rows.sort_by(|a, b| a.0.cmp(&b.0));+ let mut csv = String::from("Path,Kind,Size,Created,Modified,In This Export\r\n");+ for (path, item, copied) in rows {+ let kind = match item.kind.as_str() {+ "FOLDER" => "Folder",+ "APP_LIBRARY" => "App Folder",+ _ => "File",+ };+ csv.push_str(&format!(+ "{},{},{},{},{},{}\r\n",+ csv_field(&path),+ kind,+ item.size.map(|s| s.to_string()).unwrap_or_default(),+ time(item.created_at),+ time(item.modified_at),+ if item.is_container() {+ ""+ } else if copied {+ "Yes"+ } else {+ "No"+ }+ ));+ }+ write(&base.join("Listing.csv"), &csv)?;+ t.tick("drive", total, total)+}++fn photos(+ list: &[ExportPhoto],+ src: &Sources,+ root: &Path,+ tz: &TimeZone,+ names: &mut Names,+ t: &mut Ticker<'_>,+ summary: &mut ExportSummary,+) -> Done<()> {+ let total = list.len() as u64;+ t.start("photos", total)?;+ let base = root.join("Photos");+ std::fs::create_dir(&base)?;+ let mut missing = Vec::new();+ for (i, p) in list.iter().enumerate() {+ t.tick("photos", i as u64, total)?;+ let video = p.kind == "video";+ // The original first; a video's streaming copy, or a picture's whole JPEG, when it is+ // what this computer has.+ let order: &[&str] = if video {+ &["original", "video"]+ } else {+ &["original", "full"]+ };+ let found = order+ .iter()+ .map(|s| src.photos.join(s).join(&p.id))+ .find(|f| f.is_file());+ let when = Timestamp::from_second(p.taken_at)+ .unwrap_or(Timestamp::UNIX_EPOCH)+ .to_zoned(tz.clone());+ let given = p.filename.clone().unwrap_or_else(|| {+ format!(+ "{} {}",+ if video { "Video" } else { "Photo" },+ when.strftime("%Y-%m-%d %H.%M.%S")+ )+ });+ let Some(from) = found else {+ missing.push(format!("{}\t{}", when.strftime("%Y-%m-%d %H:%M"), given));+ continue;+ };+ let dir = base+ .join(when.strftime("%Y").to_string())+ .join(when.strftime("%m").to_string());+ std::fs::create_dir_all(&dir)?;+ let safe = file_name(&given, "Photo");+ let (stem, named_ext) = split_ext(&safe);+ let ext = sniff(&from).map_or_else(|| named_ext.to_string(), str::to_string);+ // A name's own spelling of the same type is kept (IMG_1.JPEG stays .JPEG).+ let ext = if named_ext.eq_ignore_ascii_case(&ext)+ || (ext == "jpg" && named_ext.eq_ignore_ascii_case("jpeg"))+ {+ named_ext.to_string()+ } else {+ ext+ };+ let name = names.unique(&dir, stem, &ext);+ let to = dir.join(&name);+ copy(&from, &to, t.cancel)?;+ date(&to, Some(p.taken_at));+ // A Live Photo's moving part, beside it under the same name.+ let live = src.photos.join("live").join(&p.id);+ if p.kind == "live" && live.is_file() {+ let movie = names.unique(&dir, split_ext(&name).0, "MOV");+ copy(&live, &dir.join(&movie), t.cancel)?;+ date(&dir.join(&movie), Some(p.taken_at));+ }+ summary.photos += 1;+ }+ summary.photos_missing = missing.len();+ if !missing.is_empty() {+ let mut text = String::from(+ "These photos and videos weren't on this computer, so they aren't in this export.\nOpen them in Skykeep (or download them) and export again to include them.\n\n",+ );+ for m in &missing {+ text.push_str(m);+ text.push('\n');+ }+ write(&base.join("Not Included.txt"), &text)?;+ }+ t.tick("photos", total, total)+}++// ── Commands ───────────────────────────────────────────────────────────────────────────────++/// Clears the running flag however the export ends.+struct Running;++impl Drop for Running {+ fn drop(&mut self) {+ RUNNING.store(false, Ordering::Release);+ }+}++/// Export everything into a new folder inside `dest`, telling [`EVENT`] as it goes. Photos only+/// when `photos` is true: they can be very large.+#[tauri::command]+pub async fn library_export_start(+ dest: String,+ photos: Option<bool>,+ app: tauri::AppHandle,+ data: State<'_, Data>,+) -> UiResult<ExportSummary> {+ if RUNNING.swap(true, Ordering::AcqRel) {+ return Err("An export is already under way.".into());+ }+ let _running = Running;+ CANCEL.store(false, Ordering::Release);+ let data_dir = crate::state_dir(&app);+ // Checked and read in one hold of the library, then let go of before a file is written.+ let (snap, dest) = {+ let lib = data.0.lock().await;+ let synced: Vec<PathBuf> = ["drive_folder_path", "photos_folder_path"]+ .iter()+ .filter_map(|k| lib.state(k).ok().flatten())+ .filter(|p| !p.is_empty())+ .map(PathBuf::from)+ .collect();+ let dest = check_dest(Path::new(&dest), &data_dir, &synced)?;+ (gather(&lib, photos.unwrap_or(false))?, dest)+ };+ let sources = Sources::at(&data_dir);+ let handle = app.clone();+ let now = jiff::Zoned::now();+ let done = tokio::task::spawn_blocking(move || {+ run(&snap, &sources, &dest, &now, &CANCEL, &mut |p| {+ let _ = handle.emit(EVENT, p);+ })+ })+ .await+ .map_err(|e| e.to_string())?;+ match done {+ Ok(summary) => {+ if let Ok(mut last) = LAST.lock() {+ *last = Some(PathBuf::from(&summary.path));+ }+ Ok(summary)+ }+ Err(Stop::Cancelled) => Err(CANCELLED.into()),+ Err(Stop::Failed(why)) => Err(why),+ }+}++/// Stop the export under way; what it wrote so far is removed.+#[tauri::command]+pub fn library_export_cancel() {+ if RUNNING.load(Ordering::Acquire) {+ CANCEL.store(true, Ordering::Release);+ }+}++/// Show the last finished export in the file manager — that folder only, never a path the page+/// names.+#[tauri::command]+pub fn library_export_reveal(app: tauri::AppHandle) -> UiResult<()> {+ use tauri_plugin_opener::OpenerExt;+ let last = LAST.lock().ok().and_then(|l| l.clone());+ let path = last+ .filter(|p| p.is_dir())+ .ok_or_else(|| "That export isn’t there any more.".to_string())?;+ app.opener()+ .reveal_item_in_dir(&path)+ .map_err(|e| e.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;+ use quince_core::contacts::ContactMethod;+ use quince_icloud::ckdocument::Run;++ /// A library on disk with a little of everything, and its data folder.+ fn library() -> (tempfile::TempDir, Library) {+ let dir = tempfile::tempdir().unwrap();+ let mut lib = Library::open(dir.path()).unwrap();+ lib.put_note_folders(&[+ NoteFolder {+ guid: "F1".into(),+ title: "Home/Work: plans".into(),+ sort_order: 0,+ parent_guid: None,+ },+ NoteFolder {+ guid: "F2".into(),+ title: "Recipes".into(),+ sort_order: 1,+ parent_guid: Some("F1".into()),+ },+ ])+ .unwrap();+ let runs = serde_json::to_string(&vec![+ Run {+ length: 9,+ style: Some(0),+ ..Default::default()+ },+ Run {+ length: 1,+ attachment: Some("ATT-1".into()),+ ..Default::default()+ },+ Run {+ length: 6,+ ..Default::default()+ },+ ])+ .unwrap();+ let note = |guid: &str, folder: Option<&str>, title: &str, body: Option<&str>| Note {+ guid: guid.into(),+ folder_guid: folder.map(Into::into),+ title: title.into(),+ snippet: None,+ body: body.map(Into::into),+ locked: false,+ pinned: false,+ created_at: Some(1_700_000_000),+ modified_at: Some(1_700_000_100),+ editable: true,+ etag: None,+ runs: None,+ };+ lib.put_notes(&[+ Note {+ runs: Some(runs),+ ..note(+ "N1",+ Some("F2"),+ "Pancakes",+ Some("Pancakes\n\u{FFFC}\nflour"),+ )+ },+ note("N2", Some("F2"), "Pancakes", Some("Pancakes\nagain")),+ note(+ "N3",+ None,+ "../../etc/passwd",+ Some("../../etc/passwd\nnot a path"),+ ),+ Note {+ locked: true,+ ..note("N4", None, "Secret", None)+ },+ ])+ .unwrap();+ lib.put_reminder_lists(&[ReminderList {+ guid: "L1".into(),+ title: "Errands; today".into(),+ enabled: true,+ ..Default::default()+ }])+ .unwrap();+ lib.put_reminders(&[+ Reminder {+ guid: "R1".into(),+ list_guid: "L1".into(),+ title: "Buy milk, eggs".into(),+ notes: Some("two litres\nfull fat".into()),+ due_at: Some(1_790_000_000),+ priority: 1,+ flagged: true,+ recur_frequency: Some(1),+ recur_interval: Some(2),+ ..Default::default()+ },+ Reminder {+ guid: "R2".into(),+ list_guid: "L1".into(),+ title: "Done one".into(),+ completed_at: Some(1_780_000_000),+ parent_guid: Some("R1".into()),+ ..Default::default()+ },+ ])+ .unwrap();+ lib.put_contacts(&[Contact {+ guid: "C1".into(),+ first_name: Some("Zoya".into()),+ middle_name: None,+ photo_url: None,+ photo_signature: None,+ photo_crop: None,+ last_name: Some("Ahuja".into()),+ company: Some("Acme, Inc.".into()),+ is_company: false,+ birthday: Some("1990-04-02".into()),+ notes: Some("met at; the park".into()),+ etag: None,+ methods: vec![+ ContactMethod {+ kind: "phone".into(),+ label: Some("_$!<Mobile>!$_".into()),+ value: "+91 90000 00001".into(),+ },+ ContactMethod {+ kind: "email".into(),+ label: Some("home".into()),+ value: "[email protected]".into(),+ },+ ],+ }])+ .unwrap();+ lib.put_addresses(+ &[(+ "C1".into(),+ vec![PostalAddress {+ label: Some("home".into()),+ street: Some("1 Long Road\nFlat 2".into()),+ city: Some("Pune".into()),+ country: Some("India".into()),+ ..Default::default()+ }],+ )],+ true,+ )+ .unwrap();+ lib.put_calendars(&[Calendar {+ guid: "CAL".into(),+ title: "Work".into(),+ enabled: false,+ writable: true,+ ..Default::default()+ }])+ .unwrap();+ lib.put_events(&[+ Event {+ guid: "E1".into(),+ calendar_guid: "CAL".into(),+ title: "Review, with notes: a very long title that has to be folded across lines in the file".into(),+ location: Some("Room 2".into()),+ starts_at: 1_790_000_000,+ ends_at: 1_790_003_600,+ notes: Some("Bring the deck;\nand coffee".into()),+ ..Default::default()+ },+ Event {+ guid: "E2".into(),+ calendar_guid: "CAL".into(),+ title: "Holiday".into(),+ starts_at: 1_789_948_800,+ ends_at: 1_790_035_200,+ all_day: true,+ timezone: Some("UTC".into()),+ ..Default::default()+ },+ ])+ .unwrap();+ lib.put_drive_children(+ quince_core::drive::ROOT,+ &[DriveItem {+ drivewsid: "FOLDER::x::docs".into(),+ parent_id: Some(quince_core::drive::ROOT.into()),+ name: "Docs".into(),+ extension: None,+ kind: "FOLDER".into(),+ size: None,+ child_count: Some(2),+ created_at: None,+ modified_at: None,+ etag: None,+ }],+ )+ .unwrap();+ lib.put_drive_children(+ "FOLDER::x::docs",+ &[+ DriveItem {+ drivewsid: "FILE::x::cv".into(),+ parent_id: Some("FOLDER::x::docs".into()),+ name: "CV, final".into(),+ extension: Some("pdf".into()),+ kind: "FILE".into(),+ size: Some(5),+ child_count: None,+ created_at: Some(1_700_000_000),+ modified_at: Some(1_700_000_000),+ etag: Some("e1".into()),+ },+ DriveItem {+ drivewsid: "FILE::x::big".into(),+ parent_id: Some("FOLDER::x::docs".into()),+ name: "Big".into(),+ extension: Some("mov".into()),+ kind: "FILE".into(),+ size: Some(10_000_000),+ child_count: None,+ created_at: None,+ modified_at: None,+ etag: Some("e2".into()),+ },+ ],+ )+ .unwrap();+ // Caches, as the app lays them out.+ let d = dir.path();+ std::fs::create_dir_all(d.join("note-media")).unwrap();+ std::fs::write(d.join("note-media/ATT-1-file"), b"\x89PNG\r\n\x1a\nxxxx").unwrap();+ std::fs::create_dir_all(d.join("drive-cache")).unwrap();+ std::fs::write(d.join("drive-cache/FILE__x__cv~e1"), b"%PDF-").unwrap();+ std::fs::write(d.join("drive-cache/FILE__x__cv~e1.have"), [1u8]).unwrap();+ (dir, lib)+ }++ fn photo(id: &str, taken: i64, filename: &str) -> quince_core::photos::Photo {+ quince_core::photos::Photo {+ id: id.into(),+ master: format!("M{id}"),+ taken_at: taken,+ added_at: None,+ kind: quince_core::photos::Kind::Image,+ width: 1,+ height: 1,+ duration: None,+ filename: Some(filename.into()),+ size: None,+ uti: None,+ favorite: false,+ hidden: false,+ deleted: false,+ deleted_at: None,+ expunge_at: None,+ title: None,+ caption: None,+ rating: 0,+ keywords: Vec::new(),+ latitude: None,+ longitude: None,+ rendered: 0,+ subtype: 0,+ burst: None,+ burst_pick: false,+ burst_count: 0,+ live_size: None,+ change_tag: None,+ }+ }++ fn now() -> jiff::Zoned {+ "2026-10-21T10:30:00+00:00[UTC]".parse().unwrap()+ }++ /// A tiny iCalendar / vCard reader: lines unfolded, each component's properties with+ /// their parameters dropped and values unescaped.+ fn parse(text: &str, kind: &str) -> Vec<HashMap<String, Vec<String>>> {+ assert!(text.ends_with("\r\n"), "lines end in CRLF");+ let mut lines: Vec<String> = Vec::new();+ for raw in text.split("\r\n") {+ assert!(raw.len() <= 75, "folded at 75 octets: {raw:?}");+ if let Some(rest) = raw.strip_prefix(' ') {+ lines.last_mut().unwrap().push_str(rest);+ } else if !raw.is_empty() {+ lines.push(raw.to_string());+ }+ }+ let mut out = Vec::new();+ let mut cur: Option<HashMap<String, Vec<String>>> = None;+ for l in lines {+ if l == format!("BEGIN:{kind}") {+ cur = Some(HashMap::new());+ continue;+ }+ if l == format!("END:{kind}") {+ out.push(cur.take().unwrap());+ continue;+ }+ let Some(c) = cur.as_mut() else { continue };+ let (head, value) = l.split_once(':').expect("name:value");+ let name = head.split(';').next().unwrap().to_string();+ let mut v = String::new();+ let mut chars = value.chars();+ while let Some(ch) = chars.next() {+ if ch == '\\' {+ match chars.next() {+ Some('n') | Some('N') => v.push('\n'),+ Some(o) => v.push(o),+ None => {}+ }+ } else {+ v.push(ch);+ }+ }+ c.entry(name).or_default().push(v);+ }+ assert!(cur.is_none(), "every component is closed");+ out+ }++ fn one<'a>(c: &'a HashMap<String, Vec<String>>, k: &str) -> &'a str {+ &c.get(k).unwrap_or_else(|| panic!("{k} missing"))[0]+ }++ fn export(+ dir: &Path,+ lib: &Library,+ photos: bool,+ ) -> (PathBuf, ExportSummary, tempfile::TempDir) {+ let out = tempfile::tempdir().unwrap();+ let snap = gather(lib, photos).unwrap();+ let cancel = AtomicBool::new(false);+ let mut seen = Vec::new();+ let summary = run(+ &snap,+ &Sources::at(dir),+ out.path(),+ &now(),+ &cancel,+ &mut |p| seen.push(p),+ )+ .unwrap();+ assert!(seen+ .iter()+ .any(|p| p.service == "drive" && p.done == p.total));+ assert!(+ seen.windows(2).all(|w| w[0].step <= w[1].step),+ "steps only go forward"+ );+ (PathBuf::from(&summary.path), summary, out)+ }++ #[test]+ fn writes_every_service_in_open_formats() {+ let (dir, lib) = library();+ let (root, s, _out) = export(dir.path(), &lib, false);+ assert_eq!(+ root.file_name().unwrap().to_string_lossy(),+ "Skykeep Export 2026-10-21 10.30"+ );+ assert_eq!(+ (s.notes, s.reminders, s.contacts, s.events, s.drive_files),+ (3, 2, 1, 2, 1)+ );++ // Notes: nested folders, names made safe and kept apart, attachments beside.+ let recipes = root.join("Notes/HomeWork plans/Recipes");+ let first = std::fs::read_to_string(recipes.join("Pancakes.md")).unwrap();+ assert!(first.starts_with("# Pancakes"), "{first}");+ assert!(+ first.contains(""),+ "{first}"+ );+ assert!(recipes.join("Pancakes - 1.png").is_file());+ assert!(+ recipes.join("Pancakes 2.md").is_file(),+ "same title, both kept"+ );+ assert!(+ root.join("Notes/etcpasswd.md").is_file(),+ "a title is never a path"+ );+ assert!(+ !root.join("Notes/Secret.md").exists(),+ "a locked note has no text to write"+ );++ // Reminders.+ let ics = std::fs::read_to_string(root.join("Reminders/Errands; today.ics")).unwrap();+ let todos = parse(&ics, "VTODO");+ assert_eq!(todos.len(), 2);+ let milk = todos.iter().find(|t| one(t, "UID") == "R1").unwrap();+ assert_eq!(one(milk, "SUMMARY"), "Buy milk, eggs");+ assert_eq!(one(milk, "DESCRIPTION"), "two litres\nfull fat");+ assert_eq!(one(milk, "DUE"), "20260921T141320Z");+ assert_eq!(one(milk, "PRIORITY"), "1");+ assert_eq!(one(milk, "CATEGORIES"), "Flagged");+ assert_eq!(one(milk, "RRULE"), "FREQ=WEEKLY;INTERVAL=2");+ let done = todos.iter().find(|t| one(t, "UID") == "R2").unwrap();+ assert_eq!(one(done, "STATUS"), "COMPLETED");+ assert_eq!(one(done, "RELATED-TO"), "R1");+ let md = std::fs::read_to_string(root.join("Reminders/Errands; today.md")).unwrap();+ assert!(md.contains("- [ ] Buy milk, eggs — due"), "{md}");+ assert!(+ md.contains("\n - [x] Done one\n"),+ "subtask under its parent: {md}"+ );++ // Contacts.+ let vcf = std::fs::read_to_string(root.join("Contacts/Contacts.vcf")).unwrap();+ let cards = parse(&vcf, "VCARD");+ assert_eq!(cards.len(), 1);+ assert_eq!(one(&cards[0], "FN"), "Zoya Ahuja");+ assert_eq!(one(&cards[0], "ORG"), "Acme, Inc.");+ assert_eq!(one(&cards[0], "TEL"), "+91 90000 00001");+ assert!(+ vcf.contains("TEL;TYPE=Mobile:"),+ "Apple's label read plainly"+ );+ assert_eq!(one(&cards[0], "EMAIL"), "[email protected]");+ assert_eq!(one(&cards[0], "ADR"), ";;1 Long Road\nFlat 2;Pune;;;India");+ assert_eq!(one(&cards[0], "NOTE"), "met at; the park");++ // Calendar: every event, from a calendar hidden on screen too.+ let cal = std::fs::read_to_string(root.join("Calendar/Work.ics")).unwrap();+ let events = parse(&cal, "VEVENT");+ assert_eq!(events.len(), 2);+ let review = events.iter().find(|e| one(e, "UID") == "E1").unwrap();+ assert!(one(review, "SUMMARY").ends_with("folded across lines in the file"));+ assert_eq!(one(review, "DESCRIPTION"), "Bring the deck;\nand coffee");+ assert_eq!(one(review, "DTSTART"), "20260921T141320Z");+ let holiday = events.iter().find(|e| one(e, "UID") == "E2").unwrap();+ assert_eq!(one(holiday, "DTSTART"), "20260921");+ assert_eq!(one(holiday, "DTEND"), "20260922");++ // Drive: the listing whole, the cached file only.+ let csv = std::fs::read_to_string(root.join("iCloud Drive/Listing.csv")).unwrap();+ assert!(csv.contains("\"Docs/CV, final.pdf\",File,5,"), "{csv}");+ assert!(csv.contains("Docs/Big.mov,File,10000000,,,No"), "{csv}");+ assert_eq!(+ std::fs::read(root.join("iCloud Drive/Files/Docs/CV, final.pdf")).unwrap(),+ b"%PDF-"+ );+ assert!(!root.join("iCloud Drive/Files/Docs/Big.mov").exists());++ let readme = std::fs::read_to_string(root.join("README.txt")).unwrap();+ assert!(readme.contains("Wednesday 21 October 2026"), "{readme}");+ assert!(readme.contains("Repeating events are written as stored"));+ assert!(readme.contains("1 locked note is not included"));+ assert!(readme.contains("Photos Not included"));+ assert!(!root.join("Photos").exists(), "photos only when asked for");+ assert!(!root.join(MARKER).exists());+ // Nothing in the data folder was touched.+ assert!(!dir.path().join("photos").exists());+ }++ #[test]+ fn photos_by_month_and_what_was_not_cached_listed() {+ let (dir, mut lib) = library();+ lib.put_photos(&[+ photo("P1", 1_790_000_000, "IMG_0001.HEIC"),+ photo("P2", 1_700_000_000, "IMG_0002.JPG"),+ photo("P3", 1_700_000_000, "IMG_0003.JPG"),+ ])+ .unwrap();+ let d = dir.path().join("photos");+ std::fs::create_dir_all(d.join("original")).unwrap();+ std::fs::create_dir_all(d.join("full")).unwrap();+ std::fs::write(d.join("original/P1"), b"\0\0\0\x18ftypheic....").unwrap();+ // Only the whole JPEG of this one: named as what it is.+ std::fs::write(d.join("full/P2"), b"\xFF\xD8\xFF\xE0jpeg").unwrap();+ let (root, s, _out) = export(dir.path(), &lib, true);+ assert_eq!((s.photos, s.photos_missing), (2, 1));+ assert!(root.join("Photos/2026/09/IMG_0001.HEIC").is_file());+ assert!(root.join("Photos/2023/11/IMG_0002.JPG").is_file());+ let missing = std::fs::read_to_string(root.join("Photos/Not Included.txt")).unwrap();+ assert!(missing.contains("IMG_0003.JPG") && !missing.contains("IMG_0002"));+ }++ #[test]+ fn a_cancel_leaves_nothing_behind() {+ let (dir, lib) = library();+ let out = tempfile::tempdir().unwrap();+ let snap = gather(&lib, false).unwrap();+ let cancel = AtomicBool::new(false);+ let got = run(+ &snap,+ &Sources::at(dir.path()),+ out.path(),+ &now(),+ &cancel,+ &mut |p| {+ if p.service == "contacts" {+ cancel.store(true, Ordering::Relaxed);+ }+ },+ );+ assert_eq!(got, Err(Stop::Cancelled));+ assert_eq!(+ std::fs::read_dir(out.path()).unwrap().count(),+ 0,+ "no partial left"+ );+ }++ #[test]+ fn a_crashed_partial_is_cleared_and_only_ours() {+ let (dir, lib) = library();+ let out = tempfile::tempdir().unwrap();+ std::fs::create_dir(out.path().join(".partial-1")).unwrap();+ std::fs::write(out.path().join(".partial-1").join(MARKER), b"").unwrap();+ std::fs::create_dir(out.path().join(".partial-theirs")).unwrap();+ let snap = gather(&lib, false).unwrap();+ run(+ &snap,+ &Sources::at(dir.path()),+ out.path(),+ &now(),+ &AtomicBool::new(false),+ &mut |_| {},+ )+ .unwrap();+ assert!(!out.path().join(".partial-1").exists());+ assert!(+ out.path().join(".partial-theirs").exists(),+ "not ours: left alone"+ );+ // A second export the same minute is put beside the first, never over it.+ run(+ &snap,+ &Sources::at(dir.path()),+ out.path(),+ &now(),+ &AtomicBool::new(false),+ &mut |_| {},+ )+ .unwrap();+ assert!(out+ .path()+ .join("Skykeep Export 2026-10-21 10.30 2")+ .is_dir());+ }++ #[test]+ fn names_are_made_safe() {+ assert_eq!(file_name("a/b\\c:d", "x"), "abcd");+ assert_eq!(file_name("../..", "Untitled"), "Untitled");+ assert_eq!(file_name("", "Untitled"), "Untitled");+ assert_eq!(file_name(".hidden", "x"), "hidden");+ assert_eq!(file_name("CON", "x"), "_CON");+ assert_eq!(file_name("exe\u{202E}fdp.txt", "x"), "exefdp.txt");+ assert_eq!(file_name(&"long ".repeat(60), "x").chars().count(), 119);+ let mut n = Names::default();+ let d = Path::new("/x");+ assert_eq!(n.unique(d, "Note", "md"), "Note.md");+ assert_eq!(+ n.unique(d, "note", "md"),+ "note 2.md",+ "case-insensitively distinct"+ );+ assert_eq!(n.unique(Path::new("/y"), "Note", "md"), "Note.md");+ }++ #[test]+ fn refuses_the_data_folder_icloud_folders_and_system_folders() {+ let data = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let drive = home.path().join("iCloud Drive");+ std::fs::create_dir_all(drive.join("sub")).unwrap();+ std::fs::create_dir_all(data.path().join("photos")).unwrap();+ let synced = [drive.clone()];+ assert!(check_dest(home.path(), data.path(), &synced).is_ok());+ assert!(+ check_dest(&data.path().join("photos"), data.path(), &synced)+ .unwrap_err()+ .contains("Skykeep’s own data")+ );+ assert!(check_dest(&drive.join("sub"), data.path(), &synced)+ .unwrap_err()+ .contains("in iCloud"));+ assert!(check_dest(Path::new("relative"), data.path(), &synced).is_err());+ assert!(check_dest(&home.path().join("gone"), data.path(), &synced).is_err());+ #[cfg(unix)]+ {+ for sys in ["/", "/etc", "/usr/share", "/var/lib", "/proc"] {+ assert!(+ check_dest(Path::new(sys), data.path(), &synced)+ .unwrap_err()+ .contains("system folder"),+ "{sys}"+ );+ }+ assert!(!is_system(Path::new("/run/media/me/USB")));+ assert!(!is_system(Path::new("/var/home/me")));+ }+ }++ #[test]+ fn folding_never_splits_a_character() {+ let mut out = String::new();+ line(&mut out, &format!("SUMMARY:{}", "é".repeat(80)));+ assert!(out.split("\r\n").all(|l| l.len() <= 75));+ let back: String = out+ .split("\r\n")+ .enumerate()+ .map(|(i, l)| {+ if i == 0 {+ l+ } else {+ l.strip_prefix(' ').unwrap_or(l)+ }+ })+ .collect();+ assert_eq!(back, format!("SUMMARY:{}", "é".repeat(80)));+ }+}diff --git a/src-tauri/src/intake.rs b/src-tauri/src/intake.rsindex 006a4b9..60e19f7 100644--- a/src-tauri/src/intake.rs+++ b/src-tauri/src/intake.rs@@ -1,5 +1,5 @@-//! What comes into Pomander from outside its own windows: a calendar or contact file opened-//! with it (`.ics`, `.vcf`) and the quick-capture launcher actions (`pomander --new reminder`).+//! What comes into Skykeep from outside its own windows: a calendar or contact file opened+//! with it (`.ics`, `.vcf`) and the quick-capture launcher actions (`skykeep --new reminder`).//!//! A file is read here, on this computer, and nothing is sent anywhere until the person says//! so in the import sheet: what it holds is shown first — the events with their days and@@ -264,7 +264,7 @@ pub fn intake_capture_close(app: AppHandle) {}}-/// From the quick-capture window when Pomander is not signed in: the main window, where the+/// From the quick-capture window when Skykeep is not signed in: the main window, where the/// sign-in is.#[tauri::command]pub fn intake_open_main(app: AppHandle) {@@ -770,7 +770,7 @@ pub fn parse_calendar("VTODO" => {refused.push(Refused {title: shown(),- reason: "It’s a to-do, not an event. Pomander imports events.".into(),+ reason: "It’s a to-do, not an event. Skykeep imports events.".into(),});continue;}@@ -904,13 +904,13 @@ const WEEKDAYS: [(&str, Weekday); 7] = [fn repeat_of(c: &Component, start: &When, here: &TimeZone) -> Result<Option<EventRepeat>, String> {let rules: Vec<&Property> = c.all("RRULE").collect();if c.get("RDATE").is_some() || rules.len() > 1 {- return Err("It repeats on extra dates, which Pomander can’t set up.".into());+ return Err("It repeats on extra dates, which Skykeep can’t set up.".into());}let Some(rule) = rules.first() else {return Ok(None);};if c.get("EXDATE").is_some() {- return Err("Its repeat skips some dates, which Pomander can’t set up.".into());+ return Err("Its repeat skips some dates, which Skykeep can’t set up.".into());}let mut freq = None;let mut interval = 1i64;@@ -929,7 +929,7 @@ fn repeat_of(c: &Component, start: &When, here: &TimeZone) -> Result<Option<Even"YEARLY" => "yearly","HOURLY" | "MINUTELY" | "SECONDLY" => {return Err(- "It repeats more than once a day, which Pomander can’t set up.".into(),+ "It repeats more than once a day, which Skykeep can’t set up.".into(),)}_ => return Err("Its repeat can’t be read.".into()),@@ -962,30 +962,30 @@ fn repeat_of(c: &Component, start: &When, here: &TimeZone) -> Result<Option<Even.is_some_and(|(_, day)| *day == first.weekday());if !same {return Err(if value.contains(',') {- "It repeats on several days of the week, which Pomander can’t set up yet."+ "It repeats on several days of the week, which Skykeep can’t set up yet.".into()} else if value.chars().next().is_some_and(|c| c.is_ascii_digit() || c == '-' || c == '+'){- "It repeats on a weekday of the month (like the second Tuesday), which Pomander can’t set up yet.".into()+ "It repeats on a weekday of the month (like the second Tuesday), which Skykeep can’t set up yet.".into()} else {- "It repeats on a different weekday than it starts on, which Pomander can’t set up.".into()+ "It repeats on a different weekday than it starts on, which Skykeep can’t set up.".into()});}}"BYMONTHDAY" => {if value.parse::<i8>().ok() != Some(first.day()) {- return Err("It repeats on other days of the month than it starts on, which Pomander can’t set up yet.".into());+ return Err("It repeats on other days of the month than it starts on, which Skykeep can’t set up yet.".into());}}"BYMONTH" => {if value.parse::<i8>().ok() != Some(first.month()) {- return Err("It repeats in other months than it starts in, which Pomander can’t set up yet.".into());+ return Err("It repeats in other months than it starts in, which Skykeep can’t set up yet.".into());}}- _ => return Err("It repeats in a way Pomander can’t set up yet.".into()),+ _ => return Err("It repeats in a way Skykeep can’t set up yet.".into()),}}let freq = freq.ok_or("Its repeat can’t be read.")?;diff --git a/src-tauri/src/login.rs b/src-tauri/src/login.rsindex fba0fa5..7ae4d4f 100644--- a/src-tauri/src/login.rs+++ b/src-tauri/src/login.rs@@ -96,7 +96,7 @@ fn quoted(path: &str) -> String {#[cfg(not(windows))]fn desktop_file(command: &str, icon: &str) -> String {format!(- "[Desktop Entry]\nType=Application\nName=Pomander\nComment=Keeps iCloud in sync in the background\nExec={command}\nIcon={icon}\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n",+ "[Desktop Entry]\nType=Application\nName=Skykeep\nComment=Keeps iCloud in sync in the background\nExec={command}\nIcon={icon}\nTerminal=false\nNoDisplay=true\nX-GNOME-Autostart-enabled=true\n",)}@@ -141,7 +141,7 @@ fn honoured() -> bool {#[cfg(windows)]const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";#[cfg(windows)]-const RUN_VALUE: &str = "Pomander";+const RUN_VALUE: &str = "Skykeep";/// Windows' own `reg` tool, with no window flashing up.#[cfg(windows)]@@ -224,12 +224,12 @@ pub async fn login_item_set(on: bool, app: AppHandle) -> Result<LoginItem, Strinlogin_item_status(app).await}-#[cfg(test)]+// Its one check is of the Linux autostart entry, which Windows does not have.+#[cfg(all(test, not(windows)))]mod tests {use super::*;/// The Exec line survives any path: spaces quoted, the spec's special characters escaped.- #[cfg(not(windows))]#[test]fn the_exec_line_is_quoted_as_the_spec_says() {assert_eq!(diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 7434031..2db7675 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -16,6 +16,7 @@ mod alerts;mod apps;mod contacts_cmds;mod cpu;+mod export;mod intake;mod login;mod migrate;@@ -36,6 +37,9 @@ mod poster {mod push;mod refresh;mod reminders_cmds;+// Skykeep's results in GNOME's and KDE's own search, on the session bus.+#[cfg(target_os = "linux")]+mod search_provider;mod settings;mod video;@@ -381,10 +385,10 @@ async fn diagnostics_save(app: tauri::AppHandle, data: State<'_, Data>) -> UiRes};let mut out = String::new();use std::fmt::Write as _;- let _ = writeln!(out, "Pomander diagnostic report");+ let _ = writeln!(out, "Skykeep diagnostic report");let _ = writeln!(out,- "Pomander {} · {} · {} {}",+ "Skykeep {} · {} · {} {}",app.package_info().version,os,std::env::consts::ARCH,@@ -423,7 +427,7 @@ async fn diagnostics_save(app: tauri::AppHandle, data: State<'_, Data>) -> UiRes}let dir = app.path().download_dir().map_err(|e| e.to_string())?;let path = dir.join(format!(- "Pomander diagnostics {}.txt",+ "Skykeep diagnostics {}.txt",jiff::Zoned::now().strftime("%Y-%m-%d %H.%M")));tokio::fs::write(&path, out)@@ -459,7 +463,7 @@ async fn note_attachment_open(let bytes = note_media_cached(&app, &id, quince_icloud::note_media::Part::File).await?;let folder: String = id.chars().filter(char::is_ascii_alphanumeric).collect();if folder.is_empty() {- return Err("That attachment is not one Pomander knows.".into());+ return Err("That attachment is not one Skykeep knows.".into());}// The name is whoever shared the note's to choose: made a plain file name here, never a// path, and never one that pretends to be something else.@@ -789,7 +793,7 @@ async fn keep_signed_in(app: &tauri::AppHandle, client: &Arc<Mutex<Client>>) {alerts::tell(app,"Sign in to keep iCloud up to date",- "Apple signed Pomander out. Your copy on this computer is still here.",+ "Apple signed Skykeep out. Your copy on this computer is still here.",);}}@@ -1614,6 +1618,7 @@ async fn calendar_events(to: i64,data: State<'_, Data>,occasions: State<'_, Occasions>,+ feeds_state: State<'_, Feeds>,) -> UiResult<Vec<Event>> {let (mut events, people) = {let library = data.0.lock().await;@@ -1631,6 +1636,7 @@ async fn calendar_events(from,to,));+ events.extend(subscribed_events(&feeds_state, from, to).await);events.sort_by(|a, b| {a.starts_at.cmp(&b.starts_at)@@ -1646,6 +1652,7 @@ async fn calendar_search(query: String,data: State<'_, Data>,occasions: State<'_, Occasions>,+ feeds_state: State<'_, Feeds>,) -> UiResult<Vec<Event>> {let words = quince_core::fold::words(&query);let (mut found, people) = {@@ -1661,9 +1668,11 @@ async fn calendar_search(.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 subscribed = subscribed_events(&feeds_state, from, to).await;let extra = quince_icloud::occasions::birthdays(&people, from, to).into_iter().chain(quince_icloud::occasions::holidays(&feed.1, from, to))+ .chain(subscribed).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);@@ -1715,6 +1724,270 @@ fn spawn_holidays(app: tauri::AppHandle) {});}+/* ---- calendars subscribed to by address ----------------------------------------------- */++use quince_icloud::calendar_feeds::{self as feeds, Subscription};++/// Calendars subscribed to by address, each with its file as last read. Kept in+/// `subscriptions.json` beside the library, each file in `subscriptions/<id>.ics`.+struct Feeds {+ subs: Mutex<Vec<(Subscription, Option<feeds::Feed>)>>,+}++/// Apple's calendar colours, for a subscription whose file names none (icloud.com's order).+const FEED_COLOURS: [&str; 7] = [+ "#ff9500", "#34aadc", "#65db39", "#cc73e1", "#ffcc00", "#a2845e", "#ff2d55",+];++fn feeds_dir(app: &tauri::AppHandle) -> PathBuf {+ state_dir(app).join("subscriptions")+}++fn save_subscriptions(+ app: &tauri::AppHandle,+ subs: &[(Subscription, Option<feeds::Feed>)],+) -> UiResult<()> {+ let list: Vec<&Subscription> = subs.iter().map(|(s, _)| s).collect();+ let text = serde_json::to_string_pretty(&list).map_err(|e| e.to_string())?;+ let path = state_dir(app).join("subscriptions.json");+ let tmp = path.with_extension("json.tmp");+ std::fs::write(&tmp, text).map_err(|e| e.to_string())?;+ std::fs::rename(&tmp, &path).map_err(|e| e.to_string())+}++/// Fetch one subscription's file with the client that reaches its host and nothing else.+async fn fetch_subscription(url: &str) -> UiResult<(String, feeds::Feed)> {+ let host = feeds::host_of(url).ok_or("That address has no server in it.")?;+ let http = quince_auth::listed_only(&[host])+ .user_agent(concat!("Skykeep/", env!("CARGO_PKG_VERSION")))+ .timeout(Duration::from_secs(60))+ .build()+ .map_err(|e| e.to_string())?;+ let text = feeds::fetch(&http, url).await.map_err(|e| e.to_string())?;+ let here = jiff::tz::TimeZone::system();+ let feed = feeds::parse(&text, &here).map_err(|e| e.to_string())?;+ Ok((text, feed))+}++fn now_unix() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0))+}++/// Read the subscriptions kept on disk, then fetch each when it is due — never before the+/// person has subscribed to something, so a new install reaches no host but Apple's.+fn spawn_subscriptions(app: tauri::AppHandle) {+ tauri::async_runtime::spawn(async move {+ let here = jiff::tz::TimeZone::system();+ let kept: Vec<Subscription> =+ std::fs::read_to_string(state_dir(&app).join("subscriptions.json"))+ .ok()+ .and_then(|t| serde_json::from_str(&t).ok())+ .unwrap_or_default();+ {+ let state = app.state::<Feeds>();+ let mut subs = state.subs.lock().await;+ *subs = kept+ .into_iter()+ .map(|s| {+ let feed =+ std::fs::read_to_string(feeds_dir(&app).join(format!("{}.ics", s.id)))+ .ok()+ .and_then(|t| feeds::parse(&t, &here).ok());+ (s, feed)+ })+ .collect();+ }+ app.emit(SYNCED, refresh::status(&app.state::<Data>().0).await)+ .ok();+ loop {+ let due: Vec<Subscription> = app+ .state::<Feeds>()+ .subs+ .lock()+ .await+ .iter()+ .filter(|(s, _)| s.due(now_unix()))+ .map(|(s, _)| s.clone())+ .collect();+ for s in due {+ refresh_subscription(&app, &s.id).await.ok();+ }+ tokio::time::sleep(Duration::from_secs(5 * 60)).await;+ }+ });+}++/// Fetch one subscription again, keeping the copy it had when the fetch does not land.+async fn refresh_subscription(app: &tauri::AppHandle, id: &str) -> UiResult<Subscription> {+ let state = app.state::<Feeds>();+ let url = {+ let subs = state.subs.lock().await;+ subs.iter()+ .find(|(s, _)| s.id == id)+ .map(|(s, _)| s.url.clone())+ .ok_or("That subscription is no longer here.")?+ };+ let fetched = fetch_subscription(&url).await;+ let mut subs = state.subs.lock().await;+ let Some(entry) = subs.iter_mut().find(|(s, _)| s.id == id) else {+ return Err("That subscription is no longer here.".into());+ };+ let outcome = match fetched {+ Ok((text, feed)) => {+ std::fs::create_dir_all(feeds_dir(app)).ok();+ std::fs::write(feeds_dir(app).join(format!("{id}.ics")), text).ok();+ entry.0.fetched_at = Some(now_unix());+ entry.0.problem = None;+ entry.1 = Some(feed);+ Ok(entry.0.clone())+ }+ Err(e) => {+ // Tried, so not tried again until the interval comes round; the old copy stays.+ entry.0.fetched_at = Some(now_unix());+ entry.0.problem = Some(e.clone());+ Err(e)+ }+ };+ save_subscriptions(app, &subs)?;+ drop(subs);+ app.emit(SYNCED, refresh::status(&app.state::<Data>().0).await)+ .ok();+ outcome+}++/// The subscriptions, as the Calendar sidebar lists them.+#[tauri::command]+async fn calendar_subscriptions(feeds: State<'_, Feeds>) -> UiResult<Vec<Subscription>> {+ Ok(feeds+ .subs+ .lock()+ .await+ .iter()+ .map(|(s, _)| s.clone())+ .collect())+}++/// New Calendar Subscription: the address fetched once, here and now, so a wrong one is said+/// at once; its name and colour from the file when it gives them.+#[tauri::command]+async fn calendar_subscribe(+ url: String,+ app: tauri::AppHandle,+ feeds_state: State<'_, Feeds>,+) -> UiResult<Subscription> {+ let url = feeds::normalise_url(&url)+ .map_err(|e| e.to_string())?+ .to_string();+ if feeds_state+ .subs+ .lock()+ .await+ .iter()+ .any(|(s, _)| s.url == url)+ {+ return Err("You’re already subscribed to that calendar.".into());+ }+ let (text, feed) = fetch_subscription(&url).await?;+ let mut subs = feeds_state.subs.lock().await;+ let taken: Vec<String> = subs.iter().map(|(s, _)| s.colour.clone()).collect();+ let colour = feed.colour.clone().unwrap_or_else(|| {+ FEED_COLOURS+ .iter()+ .find(|c| !taken.iter().any(|t| t == *c))+ .unwrap_or(&FEED_COLOURS[subs.len() % FEED_COLOURS.len()])+ .to_string()+ });+ let sub = Subscription {+ id: uuid::Uuid::new_v4().simple().to_string()[..12].to_string(),+ title: feed+ .name+ .clone()+ .or_else(|| feeds::host_of(&url))+ .unwrap_or_else(|| "Subscription".into()),+ url,+ colour,+ // As often as the publisher asks, at least hourly; daily when it does not say.+ refresh_minutes: feed.refresh_minutes.map_or(24 * 60, |m| m.max(60)),+ fetched_at: Some(now_unix()),+ problem: None,+ };+ std::fs::create_dir_all(feeds_dir(&app)).map_err(|e| e.to_string())?;+ std::fs::write(feeds_dir(&app).join(format!("{}.ics", sub.id)), text)+ .map_err(|e| e.to_string())?;+ subs.push((sub.clone(), Some(feed)));+ save_subscriptions(&app, &subs)?;+ Ok(sub)+}++/// Rename, recolour or change how often a subscription is fetched.+#[tauri::command]+async fn calendar_subscription_update(+ id: String,+ title: Option<String>,+ colour: Option<String>,+ refresh_minutes: Option<u32>,+ app: tauri::AppHandle,+ feeds_state: State<'_, Feeds>,+) -> UiResult<()> {+ let mut subs = feeds_state.subs.lock().await;+ let (s, _) = subs+ .iter_mut()+ .find(|(s, _)| s.id == id)+ .ok_or("That subscription is no longer here.")?;+ if let Some(t) = title+ .map(|t| t.trim().to_string())+ .filter(|t| !t.is_empty())+ {+ s.title = t;+ }+ if let Some(c) = colour.filter(|c| c.len() == 7 && c.starts_with('#')) {+ s.colour = c.to_ascii_lowercase();+ }+ if let Some(m) = refresh_minutes {+ s.refresh_minutes = m;+ }+ save_subscriptions(&app, &subs)+}++/// Unsubscribe: the calendar and its copy leave this computer; nothing was ever the account's.+#[tauri::command]+async fn calendar_unsubscribe(+ id: String,+ app: tauri::AppHandle,+ feeds_state: State<'_, Feeds>,+) -> UiResult<()> {+ let mut subs = feeds_state.subs.lock().await;+ subs.retain(|(s, _)| s.id != id);+ std::fs::remove_file(feeds_dir(&app).join(format!("{id}.ics"))).ok();+ save_subscriptions(&app, &subs)+}++/// Fetch a subscription now, as Refresh Calendars does.+#[tauri::command]+async fn calendar_subscription_refresh(+ id: String,+ app: tauri::AppHandle,+) -> UiResult<Subscription> {+ refresh_subscription(&app, &id).await+}++/// Every subscription's events in `[from, to)`.+async fn subscribed_events(feeds_state: &Feeds, from: i64, to: i64) -> Vec<Event> {+ feeds_state+ .subs+ .lock()+ .await+ .iter()+ .filter_map(|(s, f)| {+ f.as_ref()+ .map(|f| feeds::events(f, &s.calendar_guid(), from, to))+ })+ .flatten()+ .collect()+}+/// After a calendar was made, changed or removed: Apple's own list of calendars, kept here,/// so the sidebar shows what iCloud now holds rather than what was asked for.async fn calendars_from_apple(@@ -1806,6 +2079,7 @@ async fn calendar_delete(async fn calendar_list(data: State<'_, Data>,occasions: State<'_, Occasions>,+ feeds_state: State<'_, Feeds>,) -> UiResult<Vec<Calendar>> {let library = data.0.lock().await;let mut calendars = library.calendars().map_err(|e| e.to_string())?;@@ -1821,6 +2095,15 @@ async fn calendar_list(holidays.as_deref(),any_birthdays,));+ calendars.extend(+ feeds_state+ .subs+ .lock()+ .await+ .iter()+ .zip(0..)+ .map(|((s, _), i)| s.calendar(i)),+ );Ok(calendars)}@@ -2369,7 +2652,7 @@ async fn note_runs(guid: String, data: State<'_, Data>) -> UiResult<serde_json::const TABLE_CELL_WRITES: bool = false;const TABLE_LINE_WRITES: bool = false;const TABLE_WRITES_OFF: &str =- "Tables are read-only in Pomander for now: edits made here didn’t merge cleanly on iPhone yet.";+ "Tables are read-only in Skykeep for now: edits made here didn’t merge cleanly on iPhone yet.";/// Add an empty row to a Notes table at `at` (0 is the top), as Notes does, and keep the/// table as Apple now holds it.@@ -2511,7 +2794,7 @@ async fn note_save(let note = note_by_guid(&data, &guid).await?;if !note.editable {return Err(- "This note holds formatting Pomander can't rewrite safely, so it stays read-only."+ "This note holds formatting Skykeep can't rewrite safely, so it stays read-only.".into(),);}@@ -4410,18 +4693,18 @@ fn build_tray(app: &tauri::App) -> tauri::Result<()> {// Four plain lines, nothing nested: the window, the two quick notes a person reaches for// from anywhere, and Quit. A submenu was slow to draw in the panel and one more step;// each app has its own launcher and is a click away in the window.- let open = MenuItem::with_id(app, "open", "Open Pomander", true, None::<&str>)?;+ let open = MenuItem::with_id(app, "open", "Open Skykeep", true, None::<&str>)?;let new_reminder = MenuItem::with_id(app, "new:reminder", "New Reminder", true, None::<&str>)?;let new_note = MenuItem::with_id(app, "new:note", "New Note", true, None::<&str>)?;let line = PredefinedMenuItem::separator(app)?;let line2 = PredefinedMenuItem::separator(app)?;- let quit = MenuItem::with_id(app, "quit", "Quit Pomander", true, None::<&str>)?;+ let quit = MenuItem::with_id(app, "quit", "Quit Skykeep", true, None::<&str>)?;let menu = Menu::with_items(app,&[&open, &line, &new_reminder, &new_note, &line2, &quit],)?;let mut tray = TrayIconBuilder::with_id("quince")- .tooltip("Pomander")+ .tooltip("Skykeep").menu(&menu)// A click opens the window, as a tray icon does on Windows (and in most Linux panels);// the menu is the right click's. A Mac menu-bar extra opens its menu on any click.@@ -4474,11 +4757,20 @@ fn main() {if identifier != current {context.config_mut().identifier = identifier;}+ // The name the desktop knows the main window by: on Wayland GTK sends the program name as+ // the window's app ID, which was the binary's ("quince-app") — so a taskbar or dock could+ // not match it to Skykeep's launcher entry, its name or its icon. Named for the identifier,+ // it is the launcher's own ID (each app's window says its own; apps.rs).+ #[cfg(target_os = "linux")]+ {+ glib::set_prgname(Some(context.config().identifier.as_str()));+ glib::set_application_name("Skykeep");+ }tauri::Builder::default()// One Quince at a time: opening it again brings back the one already running, which// may be sitting in the tray with its window closed..plugin(tauri_plugin_single_instance::init(|app, args, cwd| {- // A file opened with Pomander, or a quick capture (`--new reminder`): handled+ // A file opened with Skykeep, or a quick capture (`--new reminder`): handled// here, in the one already running.if intake::arrived(app, &args, std::path::Path::new(&cwd)) {return;@@ -4490,7 +4782,7 @@ fn main() {}}))// Each window — the library, and every app's own — reopens at the size and place it was- // left, as Apple's apps do. Not whether it shows: that stays Pomander's (hidden at+ // left, as Apple's apps do. Not whether it shows: that stays Skykeep's (hidden at// login, shown once drawn)..plugin(tauri_plugin_window_state::Builder::default()@@ -4730,6 +5022,10 @@ fn main() {feed: Mutex::new((None, Vec::new())),});spawn_holidays(app.handle().clone());+ app.manage(Feeds {+ subs: Mutex::new(Vec::new()),+ });+ spawn_subscriptions(app.handle().clone());spawn_heartbeat(Arc::clone(&client));push::spawn(app.handle().clone(), Arc::clone(&client));spawn_auto_sync(app.handle().clone(), client);@@ -4742,6 +5038,9 @@ fn main() {app.emit(SYNCED, status).ok();});});+ // In the desktop's own search (GNOME Shell, KRunner) for as long as it runs.+ #[cfg(target_os = "linux")]+ search_provider::serve(app.handle().clone());alerts::spawn(app.handle().clone());alerts::spawn_events(app.handle().clone());// A tiling compositor places, sizes and closes windows itself; a title bar with@@ -4770,6 +5069,9 @@ fn main() {Ok(())}).invoke_handler(tauri::generate_handler![+ export::library_export_start,+ export::library_export_cancel,+ export::library_export_reveal,outbox::outbox_status,outbox::outbox_resend,outbox::outbox_discard,@@ -4813,6 +5115,11 @@ fn main() {calendar_delete,calendar_list,calendar_search,+ calendar_subscriptions,+ calendar_subscribe,+ calendar_subscription_update,+ calendar_unsubscribe,+ calendar_subscription_refresh,reminder_lists,reminder_groups,reminder_sections,@@ -4905,6 +5212,7 @@ fn main() {notes_cmds::note_lock_hint,notes_cmds::note_lock_forget,notes_cmds::note_attach_file,+ notes_cmds::note_attach_enabled,reminders_cmds::reminder_detail,reminders_cmds::reminder_tags,reminders_cmds::reminders_tagged,@@ -4939,7 +5247,7 @@ fn main() {reminder_set_repeat,]).build(context)- .expect("Pomander failed to start")+ .expect("Skykeep failed to start").run(|_app, event| {// The iCloud Drive folder goes with the app: left mounted, it would answer// nothing ("Transport endpoint is not connected").diff --git a/src-tauri/src/migrate.rs b/src-tauri/src/migrate.rsindex 60c3b9c..ab195b9 100644--- a/src-tauri/src/migrate.rs+++ b/src-tauri/src/migrate.rs@@ -755,7 +755,7 @@ fn same_bytes(a: &Path, b: &Path) -> io::Result<bool> {}}-/// Whether a Pomander is running under an identifier, and handing a launch to it: the same+/// Whether a Skykeep is running under an identifier, and handing a launch to it: the same/// channel tauri-plugin-single-instance listens on, so the running one opens what was asked/// for (`--app notes`, a file) exactly as it would for a launch under its own identifier.mod instance {@@ -1287,12 +1287,12 @@ mod tests {let h = home();let dir = h.roots.autostart.clone().unwrap();fs::create_dir_all(&dir).unwrap();- let entry = "[Desktop Entry]\nType=Application\nName=Pomander\nExec=\"/opt/Pomander.AppImage\" --background\nIcon=dev.quince.client\nX-GNOME-Autostart-enabled=true\n";+ let entry = "[Desktop Entry]\nType=Application\nName=Skykeep\nExec=\"/opt/Skykeep.AppImage\" --background\nIcon=dev.quince.client\nX-GNOME-Autostart-enabled=true\n";fs::write(dir.join(format!("{OLD_ID}.desktop")), entry).unwrap();run(&h.roots, IDS, &Mover::default());assert!(!dir.join(format!("{OLD_ID}.desktop")).exists());let moved = fs::read_to_string(dir.join(format!("{NEW_ID}.desktop"))).unwrap();- assert!(moved.contains("Exec=\"/opt/Pomander.AppImage\" --background\n"));+ assert!(moved.contains("Exec=\"/opt/Skykeep.AppImage\" --background\n"));assert!(moved.contains(&format!("Icon={NEW_ID}\n")));assert_eq!(fs::read_dir(&dir).unwrap().count(), 1, "no part file left");}diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rsindex 2c31f0d..c82cd11 100644--- a/src-tauri/src/mount.rs+++ b/src-tauri/src/mount.rs@@ -661,7 +661,7 @@ pub fn drive_keep(drivewsid: String, on: bool) -> Result<Vec<String>, String> {.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()- .ok_or("Turn on the iCloud Drive folder in Settings to keep files on this computer.")?;+ .ok_or("Turn on the Drive folder in Settings to keep files on this computer.")?;keeper.set(&drivewsid, on);Ok(keeper.kept())}diff --git a/src-tauri/src/notes_cmds.rs b/src-tauri/src/notes_cmds.rsindex c58cd1d..c25ddd8 100644--- a/src-tauri/src/notes_cmds.rs+++ b/src-tauri/src/notes_cmds.rs@@ -52,6 +52,13 @@ pub fn forget_passwords() {/// Open a locked note: its text and formatting. With no password, the one that opened it/// earlier this session is used; a wrong one is forgotten, never kept.+/// Whether attaching files to notes is switched on (`NOTE_ATTACH_WRITES`): the window shows+/// its paperclip and takes drops only then, so turning the backend flag on is the whole change.+#[tauri::command]+pub fn note_attach_enabled() -> bool {+ quince_icloud::notes::attach::NOTE_ATTACH_WRITES+}+#[tauri::command]pub async fn note_unlock(guid: String,diff --git a/src-tauri/src/outbox.rs b/src-tauri/src/outbox.rsindex 460b84b..c2dd280 100644--- a/src-tauri/src/outbox.rs+++ b/src-tauri/src/outbox.rs@@ -816,7 +816,7 @@ async fn send_reminder(Ok(())}other => Err(Error::Refused(format!(- "Pomander does not know how to send “{other}”."+ "Skykeep does not know how to send “{other}”."))),}}diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rsindex 748ebfc..7a4bb6f 100644--- a/src-tauri/src/refresh.rs+++ b/src-tauri/src/refresh.rs@@ -71,7 +71,7 @@ const COVERED: [(&str, &str); 6] = [("reminders", "Reminders"),("notes", "Notes"),("contacts", "Contacts"),- ("drive", "iCloud Drive"),+ ("drive", "Drive"),("photos", "Photos"),];@@ -360,7 +360,7 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&streturn None;}let report = match ctx.drive.as_deref() {- None => unavailable("drive", "iCloud Drive"),+ None => unavailable("drive", "Drive"),Some(root) => {let _one = crate::DRIVE_PASS.lock().await;let fetched = quince_icloud::drive::fetch_folder(@@ -372,7 +372,7 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st.await;store("drive",- "iCloud Drive",+ "Drive",data,ctx.account.as_deref(),fetched,diff --git a/src-tauri/src/search_provider.rs b/src-tauri/src/search_provider.rsnew file mode 100644index 0000000..6ebebfc--- /dev/null+++ b/src-tauri/src/search_provider.rs@@ -0,0 +1,845 @@+//! Skykeep in the desktop's own search: typing in GNOME's Activities overview or KDE's KRunner+//! shows what the library holds — notes, reminders, events, contacts, files, photos — and+//! choosing one opens its app on it.+//!+//! One well-known name on the session bus, two objects behind it:+//! - `org.gnome.Shell.SearchProvider2` at [`GNOME_PATH`], found by GNOME Shell through+//! `packaging/<id>.search-provider.ini`;+//! - `org.kde.krunner1` at [`KRUNNER_PATH`], found by KRunner through+//! `packaging/<id>.krunner.desktop` in `/usr/share/krunner/dbusplugins/`.+//!+//! Neither desktop needs Skykeep already running: `packaging/<id>.SearchProvider.service` lets+//! the bus start it, hidden (`--background`), on the first search.+//!+//! The answer has to be quick — the shell waits on every provider as the person types — so a+//! search reads the library only if its lock comes free within [`LOCK_WAIT`] (a sync pass may be+//! holding it), and gives up on the whole after [`GIVE_UP`]: nothing found beats a frozen+//! overview.++use quince_core::search::Everything;+use serde::Serialize;+use std::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::{Duration, Instant};+use tauri::{AppHandle, Emitter, Manager};+use zbus::zvariant::Value;++/// The name both desktops call; the same in the `.ini`, the `.service` and the KRunner entry.+pub const BUS_NAME: &str = "io.github.yashwanthkamireddi.Skykeep.SearchProvider";+/// GNOME Shell's object.+pub const GNOME_PATH: &str = "/io/github/yashwanthkamireddi/Skykeep/SearchProvider";+/// KRunner's object.+pub const KRUNNER_PATH: &str = "/io/github/yashwanthkamireddi/Skykeep/KRunner";+/// What an app window is told to show; `payload` is a [`Reveal`], the shape `src/lib/reveal.ts`+/// takes.+pub const REVEAL: &str = "quince://reveal";+/// What the library window is told when the person asks the shell for more: the query to+/// search for there.+pub const SEARCH: &str = "quince://search";+/// The program's own icon, installed with every package.+const MAIN_ICON: &str = "io.github.yashwanthkamireddi.Skykeep";+/// At most this many of each app.+const EACH: usize = 5;+/// How long a search waits for the library's lock.+const LOCK_WAIT: Duration = Duration::from_millis(30);+/// How long a search may take in all before it answers with nothing.+const GIVE_UP: Duration = Duration::from_millis(250);+/// The most results remembered for GetResultMetas and Run to describe.+const REMEMBERED: usize = 600;++/// The apps, in the sidebar's order: the key a window and a reveal use, and the name shown.+const APPS: [(&str, &str); 6] = [+ ("notes", "Notes"),+ ("reminders", "Reminders"),+ ("calendar", "Calendar"),+ ("contacts", "Contacts"),+ ("drivews", "Drive"),+ ("photos", "Photos"),+];++/// One thing found, as the desktop shows it and as its app is asked to reveal it.+#[derive(Clone, Debug, PartialEq)]+pub struct Hit {+ /// The app: a key of [`APPS`].+ pub screen: &'static str,+ pub id: String,+ /// Where it lives, when its app needs that to get there: a reminder's list, an event's+ /// calendar, a file's folder.+ pub within: Option<String>,+ /// When, for an event: the day the calendar turns to.+ pub at: Option<i64>,+ pub title: String,+ /// The app's name, and a line of what it holds.+ pub description: String,+}++impl Hit {+ /// The identifier the desktop hands back: the app and the item, so even an identifier from+ /// before a restart (nothing remembered) still opens the right thing.+ pub fn result_id(&self) -> String {+ format!("{}/{}", self.screen, self.id)+ }++ /// The app's name.+ pub fn app_name(&self) -> &'static str {+ APPS.iter()+ .find(|(k, _)| *k == self.screen)+ .map_or("Skykeep", |(_, n)| *n)+ }++ /// The app's own icon name (`<id>.Notes`), as its launcher entry and window are named.+ pub fn app_icon(&self) -> String {+ format!("{MAIN_ICON}.{}", self.app_name())+ }++ /// GNOME's `gicon`: a serialized GThemedIcon naming the app's own icon first and the+ /// program's after it, so a theme without per-app icons still shows Skykeep's.+ pub fn gicon(&self) -> String {+ format!(". GThemedIcon {} {MAIN_ICON}", self.app_icon())+ }+}++/// What an app window is asked to show: `src/lib/reveal.ts`'s `Reveal`.+#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Reveal {+ pub screen: String,+ pub id: String,+ pub within: Option<String>,+ pub at: Option<i64>,+ pub query: String,+}++/// The day, as a person reads it.+fn day(secs: i64) -> String {+ jiff::Timestamp::from_second(secs)+ .map(|t| {+ t.to_zoned(jiff::tz::TimeZone::system())+ .strftime("%-d %b %Y")+ .to_string()+ })+ .unwrap_or_default()+}++/// The day and time.+fn moment(secs: i64) -> String {+ jiff::Timestamp::from_second(secs)+ .map(|t| {+ t.to_zoned(jiff::tz::TimeZone::system())+ .strftime("%-d %b %Y, %H:%M")+ .to_string()+ })+ .unwrap_or_default()+}++/// One line of text: attachment marks gone, runs of space and line breaks one space, cut short.+fn line(text: &str) -> String {+ let flat = text+ .replace('\u{FFFC}', " ")+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ");+ const MOST: usize = 90;+ if flat.chars().count() <= MOST {+ flat+ } else {+ let cut: String = flat.chars().take(MOST - 1).collect();+ format!("{}…", cut.trim_end())+ }+}++/// "Notes · the snippet", or the app's name alone.+fn described(app: &str, snippet: &str) -> String {+ let snippet = line(snippet);+ if snippet.is_empty() {+ app.to_string()+ } else {+ format!("{app} · {snippet}")+ }+}++/// What a search found, as the desktop's results: each app's few in the sidebar's order.+pub fn hits(found: Everything, each: usize) -> Vec<Hit> {+ let mut out = Vec::new();+ for n in found.notes.into_iter().take(each) {+ let snippet = if n.locked {+ "Locked".to_string()+ } else {+ n.snippet.unwrap_or_default()+ };+ out.push(Hit {+ screen: "notes",+ title: if n.title.trim().is_empty() {+ "New Note".into()+ } else {+ line(&n.title)+ },+ description: described("Notes", &snippet),+ id: n.guid,+ within: None,+ at: None,+ });+ }+ for r in found.reminders.into_iter().take(each) {+ let snippet = match r.due_at {+ Some(due) => format!("Due {}", moment(due)),+ None => r.notes.unwrap_or_default(),+ };+ out.push(Hit {+ screen: "reminders",+ title: line(&r.title),+ description: described("Reminders", &snippet),+ id: r.guid,+ within: Some(r.list_guid),+ at: None,+ });+ }+ for e in found.events.into_iter().take(each) {+ let when = if e.all_day {+ day(e.starts_at)+ } else {+ moment(e.starts_at)+ };+ let snippet = match e.location.as_deref().map(str::trim) {+ Some(place) if !place.is_empty() => format!("{when} · {place}"),+ _ => when,+ };+ out.push(Hit {+ screen: "calendar",+ title: line(&e.title),+ description: described("Calendar", &snippet),+ id: e.guid,+ within: Some(e.calendar_guid),+ at: Some(e.starts_at),+ });+ }+ for c in found.contacts.into_iter().take(each) {+ let snippet = c+ .methods+ .first()+ .map(|m| m.value.clone())+ .or_else(|| c.company.clone())+ .unwrap_or_default();+ out.push(Hit {+ screen: "contacts",+ title: line(&c.display_name()),+ description: described("Contacts", &snippet),+ id: c.guid,+ within: None,+ at: None,+ });+ }+ for f in found.files.into_iter().take(each) {+ let snippet = f+ .modified_at+ .map(|m| format!("Modified {}", day(m)))+ .unwrap_or_default();+ out.push(Hit {+ screen: "drivews",+ title: line(&f.display_name()),+ description: described("Drive", &snippet),+ id: f.drivewsid,+ within: f.parent_id,+ at: None,+ });+ }+ for p in found.photos.into_iter().take(each) {+ let title = p+ .title+ .clone()+ .filter(|t| !t.trim().is_empty())+ .or_else(|| p.filename.clone())+ .unwrap_or_else(|| "Photo".into());+ out.push(Hit {+ screen: "photos",+ title: line(&title),+ description: described("Photos", &day(p.taken_at)),+ id: p.id,+ within: None,+ at: None,+ });+ }+ out+}++/// GNOME's description of one result.+pub fn gnome_meta(hit: &Hit) -> HashMap<String, Value<'static>> {+ HashMap::from([+ ("id".to_string(), Value::from(hit.result_id())),+ ("name".to_string(), Value::from(hit.title.clone())),+ (+ "description".to_string(),+ Value::from(hit.description.clone()),+ ),+ ("gicon".to_string(), Value::from(hit.gicon())),+ ])+}++/// One KRunner match: (id, text, icon, type, relevance, properties).+pub type KMatch = (+ String,+ String,+ String,+ i32,+ f64,+ HashMap<String, Value<'static>>,+);++/// KRunner's description of the `rank`th result: a title the same as the query is an exact+/// match, anything else a possible one, earlier results a little more relevant.+pub fn krunner_match(hit: &Hit, query: &str, rank: usize) -> KMatch {+ // KRunner's match types (Plasma's QueryMatch::Type).+ const POSSIBLE: i32 = 30;+ const EXACT: i32 = 100;+ let exact = hit.title.trim().to_lowercase() == query.trim().to_lowercase();+ let relevance = (if exact { 1.0 } else { 0.7 }) - (rank as f64) * 0.001;+ // The icon: the program's own, which every package installs. KRunner takes a single name+ // with no fallback, and the per-app names are not installed as icons.+ let properties = HashMap::from([+ ("subtext".to_string(), Value::from(hit.description.clone())),+ (+ "category".to_string(),+ Value::from(hit.app_name().to_string()),+ ),+ ]);+ (+ hit.result_id(),+ hit.title.clone(),+ MAIN_ICON.to_string(),+ if exact { EXACT } else { POSSIBLE },+ relevance,+ properties,+ )+}++/// Searches the library: `None` when it could not be read in time.+type Search = dyn Fn(&str) -> Option<Everything> + Send + Sync;+/// Opens an app on one thing.+type Open = dyn Fn(Reveal) + Send + Sync;+/// Opens the library window to search for more.+type More = dyn Fn(String) + Send + Sync;++/// What both objects share: how to search, how to open, and what was last found.+pub struct Core {+ search: Box<Search>,+ open: Box<Open>,+ more: Box<More>,+ seen: Mutex<HashMap<String, Hit>>,+}++impl Core {+ pub fn new(+ search: impl Fn(&str) -> Option<Everything> + Send + Sync + 'static,+ open: impl Fn(Reveal) + Send + Sync + 'static,+ more: impl Fn(String) + Send + Sync + 'static,+ ) -> Arc<Self> {+ Arc::new(Self {+ search: Box::new(search),+ open: Box::new(open),+ more: Box::new(more),+ seen: Mutex::new(HashMap::new()),+ })+ }++ /// What the library holds for `query`, remembered so the desktop can ask after it by id.+ fn find(&self, query: &str) -> Vec<Hit> {+ let found = (self.search)(query).map_or_else(Vec::new, |f| hits(f, EACH));+ let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());+ if seen.len() + found.len() > REMEMBERED {+ seen.clear();+ }+ for hit in &found {+ seen.insert(hit.result_id(), hit.clone());+ }+ found+ }++ /// A result found earlier, by its id.+ fn recall(&self, id: &str) -> Option<Hit> {+ self.seen+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get(id)+ .cloned()+ }++ /// Opens a result's app on it. An id not remembered (asked after a restart) still names+ /// its app and item; only where it lives is unknown, which the app works out.+ fn activate(&self, id: &str, query: String) {+ let reveal = match self.recall(id) {+ Some(hit) => Reveal {+ screen: hit.screen.to_string(),+ id: hit.id,+ within: hit.within,+ at: hit.at,+ query,+ },+ None => {+ let Some((screen, item)) = id.split_once('/') else {+ return;+ };+ if !APPS.iter().any(|(k, _)| *k == screen) {+ return;+ }+ Reveal {+ screen: screen.to_string(),+ id: item.to_string(),+ within: None,+ at: None,+ query,+ }+ }+ };+ (self.open)(reveal);+ }+}++/// Runs a search off the bus's own thread, and answers with nothing past [`GIVE_UP`].+async fn search_off_thread(core: &Arc<Core>, query: String) -> Vec<Hit> {+ let core = Arc::clone(core);+ // On Tauri's runtime: the bus's executor has no timer of its own to give up by.+ tauri::async_runtime::spawn(async move {+ let work = tauri::async_runtime::spawn_blocking(move || core.find(&query));+ tokio::time::timeout(GIVE_UP, work)+ .await+ .ok()+ .and_then(Result::ok)+ .unwrap_or_default()+ })+ .await+ .unwrap_or_default()+}++/// The terms the shell sends, as one query.+fn joined(terms: &[String]) -> String {+ terms.join(" ")+}++/// GNOME Shell's search provider.+pub struct Gnome(pub Arc<Core>);++#[zbus::interface(name = "org.gnome.Shell.SearchProvider2")]+impl Gnome {+ async fn get_initial_result_set(&self, terms: Vec<String>) -> Vec<String> {+ let found = search_off_thread(&self.0, joined(&terms)).await;+ found.iter().map(Hit::result_id).collect()+ }++ /// The narrower search as the person types on: searched again (it is quick), which also+ /// finds what the first search's cut-off left out.+ async fn get_subsearch_result_set(+ &self,+ _previous_results: Vec<String>,+ terms: Vec<String>,+ ) -> Vec<String> {+ let found = search_off_thread(&self.0, joined(&terms)).await;+ found.iter().map(Hit::result_id).collect()+ }++ async fn get_result_metas(+ &self,+ identifiers: Vec<String>,+ ) -> Vec<HashMap<String, Value<'static>>> {+ identifiers+ .iter()+ .filter_map(|id| self.0.recall(id))+ .map(|hit| gnome_meta(&hit))+ .collect()+ }++ async fn activate_result(&self, identifier: String, terms: Vec<String>, _timestamp: u32) {+ self.0.activate(&identifier, joined(&terms));+ }++ async fn launch_search(&self, terms: Vec<String>, _timestamp: u32) {+ (self.0.more)(joined(&terms));+ }+}++/// KDE's KRunner plugin.+pub struct KRunner(pub Arc<Core>);++#[zbus::interface(name = "org.kde.krunner1")]+impl KRunner {+ /// No actions beyond opening a match.+ async fn actions(&self) -> Vec<(String, String, String)> {+ Vec::new()+ }++ #[zbus(name = "Match")]+ async fn find(&self, query: String) -> Vec<KMatch> {+ let found = search_off_thread(&self.0, query.clone()).await;+ found+ .iter()+ .enumerate()+ .map(|(rank, hit)| krunner_match(hit, &query, rank))+ .collect()+ }++ async fn run(&self, match_id: String, _action_id: String) {+ self.0.activate(&match_id, String::new());+ }++ async fn config(&self) -> HashMap<String, Value<'static>> {+ HashMap::new()+ }++ async fn teardown(&self) {}+}++/// Takes the bus name and serves both objects on `connection`'s bus.+pub async fn serve_on(+ builder: zbus::connection::Builder<'_>,+ name: &str,+ core: Arc<Core>,+) -> zbus::Result<zbus::Connection> {+ builder+ .name(name.to_string())?+ .serve_at(GNOME_PATH, Gnome(Arc::clone(&core)))?+ .serve_at(KRUNNER_PATH, KRunner(core))?+ .build()+ .await+}++/// The connection, held for as long as Skykeep runs.+static BUS: OnceLock<zbus::Connection> = OnceLock::new();++/// The library read for a search, if its lock comes free in time: never waits on a sync pass.+fn search_library(app: &AppHandle, query: &str) -> Option<Everything> {+ let data = app.try_state::<crate::Data>()?;+ let until = Instant::now() + LOCK_WAIT;+ let library = loop {+ if let Ok(library) = data.0.try_lock() {+ break library;+ }+ if Instant::now() >= until {+ return None;+ }+ std::thread::sleep(Duration::from_millis(2));+ };+ library.search_everything(query, EACH).ok()+}++/// Brings up the app's window and tells it what to show: at once when the window was already+/// made (its page is listening), once it has drawn when it is new.+fn open_app(app: &AppHandle, reveal: Reveal) {+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ let label = format!("app-{}", reveal.screen);+ let made = app.get_webview_window(&label).is_some();+ crate::apps::open(&app, &reveal.screen);+ if !made {+ // A new window is shown by its window_ready, once its page has drawn — the page is+ // up, and listening, by then. Given up after the same few seconds apps::open waits.+ let until = Instant::now() + Duration::from_secs(5);+ while Instant::now() < until {+ if app+ .get_webview_window(&label)+ .is_some_and(|w| w.is_visible().unwrap_or(false))+ {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ }+ if let Err(e) = app.emit_to(label.as_str(), REVEAL, &reveal) {+ quiet!("a search result could not be shown: {e}");+ }+ });+}++/// The library window, asked to search for `query`.+fn search_in_window(app: &AppHandle, query: String) {+ crate::show_window(app);+ app.emit_to("main", SEARCH, query).ok();+}++/// Takes Skykeep's place in the desktop's search, for as long as it runs. Nothing is lost if+/// there is no session bus or the name is taken: the desktop's search just goes without.+pub fn serve(app: AppHandle) {+ let searching = app.clone();+ let opening = app.clone();+ let core = Core::new(+ move |query| search_library(&searching, query),+ move |reveal| open_app(&opening, reveal),+ move |query| search_in_window(&app, query),+ );+ tauri::async_runtime::spawn(async move {+ let built = match zbus::connection::Builder::session() {+ Ok(builder) => serve_on(builder, BUS_NAME, core).await,+ Err(e) => Err(e),+ };+ match built {+ Ok(connection) => {+ BUS.set(connection).ok();+ }+ Err(e) => quiet!("not in the desktop's search: {e}"),+ }+ });+}++#[cfg(test)]+mod tests {+ use super::*;+ use quince_core::Library;++ fn note(guid: &str, title: &str, snippet: &str) -> quince_core::notes::Note {+ quince_core::notes::Note {+ guid: guid.into(),+ folder_guid: None,+ title: title.into(),+ snippet: Some(snippet.into()),+ body: Some(snippet.into()),+ locked: false,+ pinned: false,+ created_at: Some(1),+ modified_at: Some(1),+ editable: true,+ etag: None,+ runs: None,+ }+ }++ fn event(guid: &str, title: &str) -> quince_core::calendar::Event {+ quince_core::calendar::Event {+ guid: guid.into(),+ calendar_guid: "CAL".into(),+ title: title.into(),+ location: Some(" Room 4 ".into()),+ starts_at: 1_767_225_600,+ ends_at: 1_767_229_200,+ all_day: false,+ timezone: None,+ url: None,+ notes: None,+ etag: None,+ }+ }++ /// Each app's results: its title, its app's name with a line of what it holds, the app's+ /// icon, and what its window needs to find it.+ #[test]+ fn results_say_what_and_where() {+ let mut lots = Vec::new();+ for i in 0..8 {+ lots.push(note(&format!("N{i}"), "", "first\nline \u{FFFC} of it"));+ }+ let found = Everything {+ notes: lots,+ events: vec![event("E1", "Standup")],+ ..Everything::default()+ };+ let all = hits(found, EACH);+ assert_eq!(all.len(), EACH + 1, "five notes at most, then the event");+ let n = &all[0];+ assert_eq!(n.title, "New Note", "an untitled note says so");+ assert_eq!(n.description, "Notes · first line of it");+ assert_eq!(n.result_id(), "notes/N0");+ assert_eq!(+ n.gicon(),+ ". GThemedIcon io.github.yashwanthkamireddi.Skykeep.Notes io.github.yashwanthkamireddi.Skykeep"+ );+ let e = all.last().unwrap();+ assert_eq!(e.screen, "calendar");+ assert_eq!(e.within.as_deref(), Some("CAL"));+ assert_eq!(e.at, Some(1_767_225_600));+ assert!(e.description.starts_with("Calendar · "));+ assert!(e.description.ends_with(" · Room 4"), "{}", e.description);+ assert_eq!(+ e.app_icon(),+ "io.github.yashwanthkamireddi.Skykeep.Calendar"+ );+ }++ #[test]+ fn a_long_snippet_is_one_short_line() {+ let long = "word ".repeat(100);+ let d = described("Notes", &long);+ assert!(d.chars().count() <= "Notes · ".chars().count() + 90);+ assert!(d.ends_with('…'));+ assert_eq!(described("Drive", " "), "Drive");+ }++ #[test]+ fn gnome_and_krunner_describe_the_same_result() {+ let hit = hits(+ Everything {+ notes: vec![note("N1", "Groceries", "milk")],+ ..Everything::default()+ },+ EACH,+ )+ .remove(0);+ let meta = gnome_meta(&hit);+ assert_eq!(meta["id"], Value::from("notes/N1"));+ assert_eq!(meta["name"], Value::from("Groceries"));+ assert_eq!(meta["description"], Value::from("Notes · milk"));+ let (id, text, icon, kind, relevance, props) = krunner_match(&hit, "groceries", 0);+ assert_eq!((id.as_str(), text.as_str()), ("notes/N1", "Groceries"));+ assert_eq!(icon, MAIN_ICON);+ assert_eq!(kind, 100, "the title itself: an exact match");+ assert!(relevance > krunner_match(&hit, "milk", 0).4);+ assert_eq!(krunner_match(&hit, "milk", 0).3, 30);+ assert_eq!(props["category"], Value::from("Notes"));+ assert_eq!(props["subtext"], Value::from("Notes · milk"));+ }++ /// An id from before a restart still opens its app on it; one naming no app opens nothing.+ #[test]+ fn an_unremembered_id_still_opens_its_app() {+ let opened = Arc::new(Mutex::new(Vec::new()));+ let o = Arc::clone(&opened);+ let core = Core::new(|_| None, move |r| o.lock().unwrap().push(r), |_| {});+ core.activate("reminders/R9", "milk".into());+ core.activate("nonsense/X", String::new());+ core.activate("no-slash", String::new());+ let opened = opened.lock().unwrap();+ assert_eq!(opened.len(), 1);+ assert_eq!(opened[0].screen, "reminders");+ assert_eq!(opened[0].id, "R9");+ assert_eq!(opened[0].query, "milk");+ // The shape src/lib/reveal.ts's Reveal takes.+ assert_eq!(+ serde_json::to_value(&opened[0]).unwrap(),+ serde_json::json!({"screen":"reminders","id":"R9","within":null,"at":null,"query":"milk"})+ );+ }++ /// Whether this test runs on a bus of its own (`dbus-run-session -- cargo test …`), never+ /// the person's: their session bus is the one at `$XDG_RUNTIME_DIR/bus`.+ fn private_bus() -> bool {+ let Ok(address) = std::env::var("DBUS_SESSION_BUS_ADDRESS") else {+ return false;+ };+ let own = std::env::var("XDG_RUNTIME_DIR")+ .map(|d| format!("unix:path={d}/bus"))+ .unwrap_or_default();+ !own.is_empty() && !address.starts_with(&own)+ }++ /// The served objects on a private bus, called as GNOME Shell and KRunner call them, over a+ /// library on disk: run under `dbus-run-session -- cargo test -p quince-app search_provider`.+ #[test]+ fn served_on_a_private_bus() {+ if !private_bus() {+ eprintln!("skipped: run under dbus-run-session for a private bus");+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let mut library = Library::open(dir.path()).unwrap();+ library+ .put_notes(&[+ note("N1", "Springfield trip", "pack the tent"),+ note("N2", "Budget", "nothing here"),+ ])+ .unwrap();+ library+ .put_calendars(&[quince_core::calendar::Calendar {+ guid: "CAL".into(),+ title: "Home".into(),+ colour: None,+ ctag: None,+ sort_order: 0,+ enabled: true,+ writable: true,+ is_default: true,+ }])+ .unwrap();+ library+ .put_events(&[event("E1", "Springfield fair")])+ .unwrap();+ let library = Arc::new(Mutex::new(library));+ let opened = Arc::new(Mutex::new(Vec::new()));+ let more = Arc::new(Mutex::new(Vec::new()));+ let (lib, o, m) = (Arc::clone(&library), Arc::clone(&opened), Arc::clone(&more));+ let core = Core::new(+ move |q| lib.lock().unwrap().search_everything(q, EACH).ok(),+ move |r| o.lock().unwrap().push(r),+ move |q| m.lock().unwrap().push(q),+ );+ tauri::async_runtime::block_on(async move {+ let name = "io.github.yashwanthkamireddi.Skykeep.SearchProviderTest";+ let _served = serve_on(zbus::connection::Builder::session().unwrap(), name, core)+ .await+ .unwrap();+ let client = zbus::Connection::session().await.unwrap();+ let gnome =+ zbus::Proxy::new(&client, name, GNOME_PATH, "org.gnome.Shell.SearchProvider2")+ .await+ .unwrap();+ let started = Instant::now();+ let ids: Vec<String> = gnome+ .call("GetInitialResultSet", &(vec!["springfield"],))+ .await+ .unwrap();+ let took = started.elapsed();+ assert_eq!(ids, vec!["notes/N1", "calendar/E1"]);+ assert!(took < Duration::from_millis(50), "took {took:?}");+ let narrower: Vec<String> = gnome+ .call(+ "GetSubsearchResultSet",+ &(ids.clone(), vec!["springfield", "tent"]),+ )+ .await+ .unwrap();+ assert_eq!(narrower, vec!["notes/N1"]);+ let metas: Vec<HashMap<String, zbus::zvariant::OwnedValue>> =+ gnome.call("GetResultMetas", &(ids.clone(),)).await.unwrap();+ assert_eq!(metas.len(), 2);+ let text = |m: &HashMap<String, zbus::zvariant::OwnedValue>, k: &str| {+ String::try_from(m[k].try_clone().unwrap()).unwrap()+ };+ assert_eq!(text(&metas[0], "id"), "notes/N1");+ assert_eq!(text(&metas[0], "name"), "Springfield trip");+ assert_eq!(text(&metas[0], "description"), "Notes · pack the tent");+ assert!(text(&metas[1], "gicon").contains("Skykeep.Calendar"));+ let () = gnome+ .call(+ "ActivateResult",+ &("calendar/E1", vec!["springfield"], 0u32),+ )+ .await+ .unwrap();+ let () = gnome+ .call("LaunchSearch", &(vec!["springfield"], 0u32))+ .await+ .unwrap();++ let krunner = zbus::Proxy::new(&client, name, KRUNNER_PATH, "org.kde.krunner1")+ .await+ .unwrap();+ // KRunner's match: id, text, icon, type, relevance, properties.+ type Match = (+ String,+ String,+ String,+ i32,+ f64,+ HashMap<String, zbus::zvariant::OwnedValue>,+ );+ let matches: Vec<Match> = krunner.call("Match", &("budget",)).await.unwrap();+ assert_eq!(matches.len(), 1);+ assert_eq!(matches[0].0, "notes/N2");+ assert_eq!(matches[0].3, 100);+ let actions: Vec<(String, String, String)> =+ krunner.call("Actions", &()).await.unwrap();+ assert!(actions.is_empty());+ let () = krunner.call("Run", &("notes/N2", "")).await.unwrap();+ });+ let opened = opened.lock().unwrap();+ assert_eq!(opened.len(), 2);+ assert_eq!(+ opened[0],+ Reveal {+ screen: "calendar".into(),+ id: "E1".into(),+ within: Some("CAL".into()),+ at: Some(1_767_225_600),+ query: "springfield".into(),+ }+ );+ assert_eq!(opened[1].screen, "notes");+ assert_eq!(opened[1].id, "N2");+ assert_eq!(*more.lock().unwrap(), vec!["springfield".to_string()]);+ }+}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex e9b61d8..b2695c5 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,8 +1,8 @@{"$schema": "https://schema.tauri.app/config/2",- "productName": "Pomander",+ "productName": "Skykeep","version": "0.1.0",- "identifier": "io.github.yashwanthkamireddi.Pomander",+ "identifier": "io.github.yashwanthkamireddi.Skykeep","build": {"frontendDist": "../dist","beforeBuildCommand": "npm run build"@@ -10,7 +10,7 @@"app": {"windows": [{- "title": "Pomander",+ "title": "Skykeep","width": 1040,"height": 720,"minWidth": 480,@@ -55,9 +55,9 @@}],"shortDescription": "Your iCloud, on this computer",- "longDescription": "Pomander keeps your iCloud notes, reminders, calendar, contacts, Drive and photos on your own computer, so they open instantly and work offline. An independent project, not affiliated with or endorsed by Apple Inc. iCloud is a trademark of Apple Inc.",+ "longDescription": "Skykeep keeps your iCloud notes, reminders, calendar, contacts, Drive and photos on your own computer, so they open instantly and work offline. An independent project, not affiliated with or endorsed by Apple Inc. iCloud is a trademark of Apple Inc.","licenseFile": "../LICENSE",- "homepage": "https://github.com/YashwanthKamireddi/quince",+ "homepage": "https://github.com/YashwanthKamireddi/Skykeep","publisher": "Yashwanth Kamireddi","windows": {"nsis": {@@ -75,15 +75,18 @@"libsecret-1-0","libheif1"],- "desktopTemplate": "../packaging/io.github.yashwanthkamireddi.Pomander.desktop.in",+ "desktopTemplate": "../packaging/io.github.yashwanthkamireddi.Skykeep.desktop.in","files": {- "/usr/share/metainfo/io.github.yashwanthkamireddi.Pomander.metainfo.xml": "../packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xml",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Notes.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Notes.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Reminders.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Reminders.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Calendar.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Calendar.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Contacts.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Contacts.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Drive.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Drive.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Photos.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Photos.desktop"+ "/usr/share/metainfo/io.github.yashwanthkamireddi.Skykeep.metainfo.xml": "../packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xml",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Notes.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Notes.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Reminders.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Reminders.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Calendar.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Calendar.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Contacts.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Contacts.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Drive.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Drive.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Photos.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Photos.desktop",+ "/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini": "../packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini",+ "/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service": "../packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service",+ "/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop": "../packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop"}},"rpm": {@@ -91,15 +94,18 @@"libsecret","libheif"],- "desktopTemplate": "../packaging/io.github.yashwanthkamireddi.Pomander.desktop.in",+ "desktopTemplate": "../packaging/io.github.yashwanthkamireddi.Skykeep.desktop.in","files": {- "/usr/share/metainfo/io.github.yashwanthkamireddi.Pomander.metainfo.xml": "../packaging/io.github.yashwanthkamireddi.Pomander.metainfo.xml",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Notes.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Notes.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Reminders.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Reminders.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Calendar.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Calendar.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Contacts.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Contacts.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Drive.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Drive.desktop",- "/usr/share/applications/io.github.yashwanthkamireddi.Pomander.Photos.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Pomander.Photos.desktop"+ "/usr/share/metainfo/io.github.yashwanthkamireddi.Skykeep.metainfo.xml": "../packaging/io.github.yashwanthkamireddi.Skykeep.metainfo.xml",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Notes.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Notes.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Reminders.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Reminders.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Calendar.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Calendar.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Contacts.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Contacts.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Drive.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Drive.desktop",+ "/usr/share/applications/io.github.yashwanthkamireddi.Skykeep.Photos.desktop": "../packaging/apps/io.github.yashwanthkamireddi.Skykeep.Photos.desktop",+ "/usr/share/gnome-shell/search-providers/io.github.yashwanthkamireddi.Skykeep.search-provider.ini": "../packaging/io.github.yashwanthkamireddi.Skykeep.search-provider.ini",+ "/usr/share/dbus-1/services/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service": "../packaging/io.github.yashwanthkamireddi.Skykeep.SearchProvider.service",+ "/usr/share/krunner/dbusplugins/io.github.yashwanthkamireddi.Skykeep.krunner.desktop": "../packaging/io.github.yashwanthkamireddi.Skykeep.krunner.desktop"}},"appimage": {@@ -107,5 +113,5 @@}}},- "mainBinaryName": "pomander"+ "mainBinaryName": "skykeep"}diff --git a/src/assets/skykeep-mark.png b/src/assets/skykeep-mark.pngnew file mode 100644index 0000000..e729550Binary files /dev/null and b/src/assets/skykeep-mark.png differdiff --git a/src/components/AppIcon.tsx b/src/components/AppIcon.tsxindex 9f02493..18fcd8b 100644--- a/src/components/AppIcon.tsx+++ b/src/components/AppIcon.tsx@@ -1,178 +1,27 @@-import { useId } from "react";-import { dateText } from "../lib/when";+import { CalendarDays, ContactRound, FolderClosed, Image as ImageGlyph, ListChecks, NotebookPen } from "lucide-react";/**- * Each screen's mark in the sidebar, so a row is found by its picture before its name is read.- *- * Photos, Reminders, Notes, iCloud Drive and Contacts are Apple's own icons, light and dark,- * as icloud.com shows them — his choice (2026-10-20), for his own copy of Quince; they are- * Apple's artwork, not to be published with the code. Made 22 and 44 pixels with a Lanczos- * resample, never shrunk by the engine (WebKitGTK shrinks a large picture crudely). Calendar- * stays drawn here, as icloud.com draws it: its weekday and date are today's, which a fixed- * picture could not be. The rest, below, are vector marks in two finishes — a light tile, and- * the deep graphite tile Apple's dark icons sit on.+ * Each app's mark in the sidebar and Settings, as a Mac sidebar marks its places (Finder, Mail):+ * one clean symbol, tinted in the app's own colour, on no tile at all. A row of colourful little+ * tiles read as a toy; a single-colour symbol reads as the system's own.*/-const pictures = import.meta.glob("../assets/app-icons/*.png", { eager: true, import: "default" }) as Record<string, string>;-const picture = (name: string) => pictures[`../assets/app-icons/${name}.png`];-const APPLE: Record<string, string> = { photos: "photos", reminders: "reminders", notes: "notes", drivews: "drive", contacts: "contacts" };+const MARK: Record<string, { glyph: typeof NotebookPen; tint: string }> = {+ notes: { glyph: NotebookPen, tint: "var(--app-notes)" },+ reminders: { glyph: ListChecks, tint: "var(--app-reminders)" },+ calendar: { glyph: CalendarDays, tint: "var(--app-calendar)" },+ contacts: { glyph: ContactRound, tint: "var(--app-contacts)" },+ drivews: { glyph: FolderClosed, tint: "var(--app-drive)" },+ drive: { glyph: FolderClosed, tint: "var(--app-drive)" },+ photos: { glyph: ImageGlyph, tint: "var(--app-photos)" },+};export function AppIcon({ app, size = 22 }: { app: string; size?: number }) {- const apple = APPLE[app];- if (apple) {- const one = (finish: "light" | "dark") => (- <img- className={`ai-${finish}`}- src={picture(`${apple}-${finish}@1x`)}- srcSet={`${picture(`${apple}-${finish}@1x`)} 1x, ${picture(`${apple}-${finish}@2x`)} 2x`}- width={size}- height={size}- alt=""- draggable={false}- />- );- return (- <span className={`app-icon app-icon-apple ai-${app}`} style={{ width: size, height: size, flex: "none" }} aria-hidden="true">- {one("light")}- {one("dark")}- </span>- );- }- const id = useId().replace(/:/g, "");- const today = new Date();- const s = { width: size, height: size, flex: "none" } as const;-- // The tile every icon stands on: light or graphite by the theme, a top light, an edge.- const tile = (- <>- <defs>- <linearGradient id={`${id}t`} x1="0" y1="0" x2="0" y2="1">- <stop offset="0" className="ai-tile-top" />- <stop offset="1" className="ai-tile-bottom" />- </linearGradient>- <linearGradient id={`${id}g`} x1="0" y1="0" x2="0" y2="1">- <stop offset="0" stopColor="#fff" stopOpacity="0.22" />- <stop offset="0.5" stopColor="#fff" stopOpacity="0" />- </linearGradient>- </defs>- <rect width="24" height="24" rx="5.4" fill={`url(#${id}t)`} />- </>- );- const shine = (- <>- <rect width="24" height="24" rx="5.4" fill={`url(#${id}g)`} />- <rect x="0.25" y="0.25" width="23.5" height="23.5" rx="5.2" fill="none" className="ai-edge" strokeWidth="0.5" />- </>- );-- let art: React.ReactNode = null;- switch (app) {- case "reminders":- art = [- [7.2, "#0a84ff"],- [12, "#ff453a"],- [16.8, "#ff9f0a"],- ].map(([y, c]) => (- <g key={String(y)}>- <circle cx="6.6" cy={y as number} r="2.15" fill={c as string} />- <circle cx="6.6" cy={y as number} r="2.15" fill="none" stroke="#000" strokeOpacity="0.12" strokeWidth="0.3" />- <rect x="10.2" y={(y as number) - 0.55} width="9.4" height="1.1" rx="0.55" className="ai-rule" />- </g>- ));- break;- case "notes":- art = (- <>- <defs>- <linearGradient id={`${id}n`} x1="0" y1="0" x2="0" y2="1">- <stop offset="0" stopColor="#ffe066" />- <stop offset="1" stopColor="#ffc800" />- </linearGradient>- </defs>- <path d="M0 5.4A5.4 5.4 0 0 1 5.4 0h13.2A5.4 5.4 0 0 1 24 5.4V7.6H0z" fill={`url(#${id}n)`} />- <path d="M0 7.6h24" stroke="#000" strokeOpacity="0.12" strokeWidth="0.4" strokeDasharray="0.5 0.7" />- {[11.8, 15.2, 18.6].map((y) => (- <rect key={y} x="3.4" y={y} width="17.2" height="0.8" rx="0.4" className="ai-rule" />- ))}- </>- );- break;- case "drivews":- art = (- <>- <defs>- <linearGradient id={`${id}d`} x1="0" y1="0" x2="0" y2="1">- <stop offset="0" stopColor="#64d2ff" />- <stop offset="1" stopColor="#0a84ff" />- </linearGradient>- <linearGradient id={`${id}b`} x1="0" y1="0" x2="0" y2="1">- <stop offset="0" stopColor="#0a6ad6" />- <stop offset="1" stopColor="#0957b3" />- </linearGradient>- </defs>- <path d="M3.6 7.6a1.6 1.6 0 0 1 1.6-1.6h4.1l1.7 1.8h7.8a1.6 1.6 0 0 1 1.6 1.6V10H3.6z" fill={`url(#${id}b)`} />- <path d="M3.6 9.6A1.6 1.6 0 0 1 5.2 8h13.6a1.6 1.6 0 0 1 1.6 1.6v7.6a1.6 1.6 0 0 1-1.6 1.6H5.2a1.6 1.6 0 0 1-1.6-1.6z" fill={`url(#${id}d)`} />- <path d="M3.6 10.4h16.8" stroke="#fff" strokeOpacity="0.35" strokeWidth="0.4" />- </>- );- break;- case "calendar":- art = (- <>- <text x="12" y="8" textAnchor="middle" fontSize="5" fontWeight="600" fill="#ff453a"- fontFamily="-apple-system, 'SF Pro Text', Inter, system-ui, sans-serif" letterSpacing="0.2">- {dateText(today, { weekday: "short" }).slice(0, 3)}- </text>- <text x="12" y="19.4" textAnchor="middle" fontSize="11.6" fontWeight="300" className="ai-ink"- fontFamily="-apple-system, 'SF Pro Display', Inter, system-ui, sans-serif" letterSpacing="-0.4">- {today.getDate()}- </text>- </>- );- break;- case "contacts":- art = (- <>- <rect x="17.6" y="4.2" width="2.2" height="4.4" rx="0.6" fill="#ff9f0a" />- <rect x="17.6" y="9.8" width="2.2" height="4.4" rx="0.6" fill="#30d158" />- <rect x="17.6" y="15.4" width="2.2" height="4.4" rx="0.6" fill="#0a84ff" />- <rect x="3.8" y="3.6" width="13" height="16.8" rx="2" className="ai-card" />- <circle cx="10.3" cy="10.2" r="2.9" className="ai-person" />- <path d="M5.4 18.4c.7-2.7 2.7-4 4.9-4s4.2 1.3 4.9 4z" className="ai-person" />- </>- );- break;- case "photos":- // Photos' flower: eight petals turning about the centre, each its own colour — the- // colours read off Apple's own icon, clockwise from the top: orange, yellow, lime, green,- // blue, lavender, pink, coral — and where two overlap they darken together, multiplied,- // as Apple's do (orange over yellow a deep orange, yellow over lime an olive).- art = (- <g style={{ isolation: "isolate" }}>- {["#ffa31c", "#ffcd00", "#90d300", "#00ce74", "#00a7ec", "#9981d8", "#fe6aab", "#ff5e64"].map((c, k) => (- <rect- key={c}- x="9.15"- y="2.2"- width="5.7"- height="8.5"- rx="2.85"- fill={c}- style={{ mixBlendMode: "multiply" }}- transform={`rotate(${k * 45} 12 12)`}- />- ))}- </g>- );- break;- default:- return <span style={s} aria-hidden="true" />;- }-+ const mark = MARK[app];+ if (!mark) return null;+ const Glyph = mark.glyph;return (- <svg viewBox="0 0 24 24" style={s} aria-hidden="true" className={`app-icon ai-${app}`}>- {tile}- {art}- {shine}- </svg>+ <span className={`app-icon ai-${app}`} style={{ width: size, height: size }} aria-hidden="true">+ <Glyph size={Math.round(size * 0.82)} strokeWidth={1.9} color={mark.tint} />+ </span>);}diff --git a/src/components/GlobalSearch.tsx b/src/components/GlobalSearch.tsxindex ed30be5..fdadad9 100644--- a/src/components/GlobalSearch.tsx+++ b/src/components/GlobalSearch.tsx@@ -98,7 +98,7 @@ function sections(found: Everything): { screen: string; name: string; count: num},{screen: "drivews",- name: "iCloud Drive",+ name: "Drive",count: found.counts[4],rows: found.files.map((f) => ({key: `f${f.drivewsid}`, screen: "drivews", id: f.drivewsid, within: f.parentId,diff --git a/src/components/ImportSheet.tsx b/src/components/ImportSheet.tsxindex b3d482f..758bc04 100644--- a/src/components/ImportSheet.tsx+++ b/src/components/ImportSheet.tsx@@ -6,7 +6,7 @@ import { Picker } from "./Picker";import "../styles/intake.css";/**- * A calendar or contacts file opened with Pomander (src-tauri/src/intake.rs): what it holds,+ * A calendar or contacts file opened with Skykeep (src-tauri/src/intake.rs): what it holds,* read on this computer, and one button that adds it. Nothing reaches iCloud until then, and* what can't be added is listed with why, rather than left out unsaid.*@@ -120,7 +120,7 @@ function EventsSheet({ arrival, onDone }: { arrival: Extract<Arrival, { kind: "e.calendarList().then((all) => {// Only the account's own calendars take a new event: not a subscribed feed, not the- // Birthdays and Holidays calendars Pomander draws itself.+ // Birthdays and Holidays calendars Skykeep draws itself.const writable = all.filter((c) => c.writable && !c.guid.startsWith("quince:"));setCalendars(writable);setTarget((t) => t || (writable.find((c) => c.isDefault) ?? writable[0])?.guid || "");diff --git a/src/components/Mark.tsx b/src/components/Mark.tsxindex 817fd9e..f21de6c 100644--- a/src/components/Mark.tsx+++ b/src/components/Mark.tsx@@ -1,8 +1,9 @@-import icon from "../../src-tauri/icons/icon.svg";+import icon from "../assets/skykeep-mark.png";/**- * Quince's own icon — the same tile the dock, the tray and every alert show — so the first- * screen someone sees is the app they will find later, not a separate line drawing of it.+ * Skykeep's mark — the tower in its cloud, without the tile, the same drawing the dock and every+ * alert show inside theirs — so the first screen someone sees is the app they will find later.+ * One mark serves light and dark alike: it reads on white and on near-black.*/export function Mark({ className }: { className?: string }) {return <img className={className} src={icon} alt="" aria-hidden="true" draggable={false} />;diff --git a/src/components/QuickCapture.tsx b/src/components/QuickCapture.tsxindex d7646e9..dc46457 100644--- a/src/components/QuickCapture.tsx+++ b/src/components/QuickCapture.tsx@@ -22,7 +22,7 @@ const stored = (key: string) => {};/**- * The quick-capture window (`pomander --new reminder`, `--new note`): one field, Enter, and it+ * The quick-capture window (`skykeep --new reminder`, `--new note`): one field, Enter, and it* is in iCloud — a reminder in the list last added to, a note in Notes — and the window goes.* Escape leaves without making anything.*/@@ -100,7 +100,7 @@ export function QuickCapture({ initial }: { initial: Kind }) {setState("saving");setError(null);try {- // Started from the launcher, Pomander may still be signing back in: done here first, so+ // Started from the launcher, Skykeep may still be signing back in: done here first, so// the write does not race it.const status = await api.status();if (!status.signedIn) {@@ -179,9 +179,9 @@ export function QuickCapture({ initial }: { initial: Kind }) {"Saving…") : state === "signin" ? (<>- Sign in to Pomander first.{" "}+ Sign in to Skykeep first.{" "}<button type="button" className="link qc-link" onClick={() => void intakeApi.openMain()}>- Open Pomander+ Open Skykeep</button></>) : error ? (diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex c475ced..3f828e1 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -836,7 +836,7 @@ export const settingsApi = {alertsShown: () => invoke<boolean | null>("alerts_shown"),};-/* ── Intake: files opened with Pomander, and quick capture (src-tauri/src/intake.rs) ── */+/* ── Intake: files opened with Skykeep, and quick capture (src-tauri/src/intake.rs) ── *//** Told to a window when a file has arrived for it; it collects with `intakeApi.pending`. */export const INTAKE = "quince://intake";@@ -861,7 +861,7 @@ export type ImportEvent = {export type ImportContact = { name: string; detail: string | null; known: boolean };-/** What a file opened with Pomander holds, read on this computer before anything is sent. */+/** What a file opened with Skykeep holds, read on this computer before anything is sent. */export type Arrival =| { kind: "events"; file: string; events: ImportEvent[]; refused: { title: string; reason: string }[] }| { kind: "contacts"; file: string; path: string; contacts: ImportContact[] }@@ -875,3 +875,185 @@ export const intakeApi = {/** The main window, for signing in. */openMain: () => invoke<void>("intake_open_main"),};++/**+ * A postal address part by part, as Apple keeps it (`contact_addresses`). The names are+ * Apple's own, which is also what an edit names a part by.+ */+export type PostalAddress = {+ label: string | null;+ /** Every line before the town, line breaks and all. */+ street: string | null;+ subLocality: string | null;+ city: string | null;+ subAdministrativeArea: string | null;+ state: string | null;+ postalCode: string | null;+ country: string | null;+ /** Apple's two-letter code, lower case on the cards it writes. */+ countryCode: string | null;+};++/** One part of an address, by Apple's name for it. */+export type AddressPart = Exclude<keyof PostalAddress, "label">;++/**+ * One change to a card's addresses. `index` is a place in the list as it stands after the+ * edits before it in the same batch, starting from the list the form opened.+ */+export type AddressEdit =+ | { op: "setField"; index: number; field: AddressPart; value: string | null }+ | { op: "setLabel"; index: number; label: string | null }+ | { op: "add"; address: PostalAddress }+ | { op: "remove"; index: number };++export const contactsApi = {+ /** One card's addresses, part by part. */+ addresses: (guid: string) => invoke<PostalAddress[]>("contact_addresses", { guid }),+ /** Edits laid over the card's addresses at Apple; answers the list as written. */+ addressEdit: (guid: string, base: PostalAddress[] | null, edits: AddressEdit[]) =>+ invoke<PostalAddress[]>("contact_address_edit", { guid, base, edits }),+};++/** An early alert: `count` units before a reminder is due. Unit 0 minutes, 1 hours, 2 days,+ * 3 weeks, 4 months — Apple's numbering. */+export type EarlyAlert = { id: string; count: number; unit: number };++/** What sits beside one reminder: its tags (no `#`), link and early alerts. */+export type ReminderDetail = {+ guid: string;+ tags: string[];+ url: string | null;+ earlyAlerts: EarlyAlert[];+ /** File or image attachments, which are not shown here yet. */+ otherAttachments: number;+};++/** A tag across the account, and how many reminders still to do carry it. */+export type TagCount = { name: string; open: number };++/** A smart list on the account: built in (`today`, `flagged`…) or one made by hand (`custom`). */+export type ReminderSmartList = {+ guid: string;+ kind: string;+ title: string | null;+ colour: string | null;+ emblem: string | null;+ pinned: boolean;+ sorting: string | null;+ filter: string | null;+};++/** What a custom smart list holds now, and any part of its rules not read here. */+export type SmartListContents = { reminders: Reminder[]; unknown: string[] };++export const remindersApi = {+ detail: (guid: string) => invoke<ReminderDetail>("reminder_detail", { guid }),+ tags: () => invoke<TagCount[]>("reminder_tags"),+ tagged: (name: string) => invoke<Reminder[]>("reminders_tagged", { name }),+ smartLists: () => invoke<ReminderSmartList[]>("reminder_smart_lists"),+ inSmartList: (guid: string) => invoke<SmartListContents>("reminders_in_smart_list", { guid }),+ tagAdd: (guid: string, name: string) => invoke<void>("reminder_tag_add", { guid, name }),+ tagRemove: (guid: string, name: string) => invoke<void>("reminder_tag_remove", { guid, name }),+ /** A link, or null to clear it. */+ urlSet: (guid: string, url: string | null) => invoke<void>("reminder_url_set", { guid, url }),+ /** Remind `count` units early, or null to clear. */+ earlyAlertSet: (guid: string, count: number | null, unit: number | null) =>+ invoke<void>("reminder_early_alert_set", { guid, count, unit }),+ sectionCreate: (listGuid: string, title: string) =>+ invoke<ReminderSection>("reminder_section_create", { listGuid, title }),+ sectionRename: (guid: string, title: string) =>+ invoke<void>("reminder_section_rename", { guid, title }),+ /** Into a section of its list, or out of every one with null. */+ sectionMove: (listGuid: string, guid: string, section: string | null) =>+ invoke<void>("reminder_section_move", { listGuid, guid, section }),+};++/** A locked note, opened: its text and how it is set. Held in the window's memory only. */+export type UnlockedNote = { body: string; runs: import("../screens/notes/Formatted").Run[] };++/** A file added to a note: where it landed and the note's text with it in place. */+export type NoteAttached = { attachment: string; media: string; uti: string; offset: number; body: string };++/** Locked notes and attachments (src-tauri/src/notes_cmds.rs). */+export const notesLockApi = {+ /**+ * Open a locked note. The password crosses once and is never kept by the window; with none,+ * the one that opened it earlier this session is used.+ */+ noteUnlock: (guid: string, password: string | null) =>+ invoke<UnlockedNote>("note_unlock", { guid, password }),+ /** The hint left with the note's password, if any. */+ noteLockHint: (guid: string) => invoke<string | null>("note_lock_hint", { guid }),+ /** Lock every opened note again. */+ noteLockForget: () => invoke<void>("note_lock_forget"),+ /** Add the file at `path` at `atOffset` (UTF-16 units of `base`, the text on screen). */+ noteAttachFile: (guid: string, path: string, atOffset: number, base: string | null) =>+ invoke<NoteAttached>("note_attach_file", { guid, path, atOffset, base }),+ /**+ * Whether adding files to notes is switched on in the backend+ * (`quince_icloud::notes::attach::NOTE_ATTACH_WRITES`). A backend without the command+ * answers no.+ */+ noteAttachEnabled: () => invoke<boolean>("note_attach_enabled").then((on) => on === true, () => false),+};++/* ── Export Everything: the whole local copy, in open formats (src-tauri/src/export.rs) ── */++/** Told to the window as an export moves along. */+export const EXPORT_PROGRESS = "quince://export";+/** What a cancelled export answers, to tell it from a failure. */+export const EXPORT_CANCELLED = "Export cancelled.";++export type ExportService = "notes" | "reminders" | "contacts" | "calendar" | "drive" | "photos";+/** Which service (`step` of `steps`, from 1) and how far through it. */+export type ExportProgress = { service: ExportService; step: number; steps: number; done: number; total: number };+export type ExportSummary = {+ path: string;+ notes: number;+ reminders: number;+ contacts: number;+ events: number;+ driveFiles: number;+ photos: number;+ photosMissing: number;+};++export const exportApi = {+ /** Writes a new "Skykeep Export …" folder inside `dest`; photos only when asked (they can be huge). */+ start: (dest: string, photos: boolean) => invoke<ExportSummary>("library_export_start", { dest, photos }),+ /** Stops the export under way; nothing it wrote is left. */+ cancel: () => invoke<void>("library_export_cancel"),+ /** Shows the last finished export in the file manager. */+ reveal: () => invoke<void>("library_export_reveal"),+};++/* ---- Calendar: subscriptions by address ------------------------------------------------ */++/** A calendar subscribed to by address (webcal:// or https://), read-only, kept on this computer. */+export type CalendarSubscription = {+ id: string;+ url: string;+ title: string;+ colour: string;+ /** How often it is fetched again, in minutes; 0 for only when asked. */+ refreshMinutes: number;+ fetchedAt: number | null;+ /** Why the last fetch did not land, when it did not. */+ problem: string | null;+};++/** Where a subscription's calendar guid begins. */+export const SUBSCRIPTION_PREFIX = "quince:sub:";++export const calendarFeedsApi = {+ list: () => invoke<CalendarSubscription[]>("calendar_subscriptions"),+ /** Fetched once before it is kept, so a wrong address is said at once. */+ subscribe: (url: string) => invoke<CalendarSubscription>("calendar_subscribe", { url }),+ update: (id: string, change: { title?: string; colour?: string; refreshMinutes?: number }) =>+ invoke<void>("calendar_subscription_update", {+ id, title: change.title ?? null, colour: change.colour ?? null, refreshMinutes: change.refreshMinutes ?? null,+ }),+ unsubscribe: (id: string) => invoke<void>("calendar_unsubscribe", { id }),+ refresh: (id: string) => invoke<CalendarSubscription>("calendar_subscription_refresh", { id }),+};diff --git a/src/main.tsx b/src/main.tsxindex 8369966..7f50518 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -43,7 +43,7 @@ document.addEventListener("contextmenu", (e) => {if (!editable) e.preventDefault();});-// The quick-capture window (`pomander --new reminder`) is one field, not the library.+// The quick-capture window (`skykeep --new reminder`) is one field, not the library.const capture = new URLSearchParams(window.location.search).get("capture");ReactDOM.createRoot(document.getElementById("root")!).render(diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsxindex 6f35110..643fae0 100644--- a/src/screens/ContactsView.tsx+++ b/src/screens/ContactsView.tsx@@ -10,12 +10,16 @@ import { PaneTitle } from "../components/PaneTitle";import { ChevronLeft, Plus, UserPlus, UsersRound, UserRound } from "lucide-react";import {api,+ contactsApi,displayName,messageOf,photoSrc,type Contact,type ContactList,type ContactMethod,+ type AddressEdit,+ type AddressPart,+ type PostalAddress,} from "../lib/ipc";import { Arriving } from "../components/EmptyState";import { useArriving, useSync } from "../lib/sync";@@ -135,10 +139,42 @@ export function ContactsView() {* card as it is then — so a change made on the phone while the form was open stays.*/const draftBase = useRef<Contact | null>(null);+ /**+ * The open card's addresses part by part: as last read, or as just edited here — drawn at+ * once, and put back if Apple turns the change down.+ */+ const [addresses, setAddresses] = useState<{ guid: string; list: PostalAddress[] } | null>(null);+ /** Address writes go to Apple one after another; while any is out, a read does not undo it. */+ const addressQueue = useRef<Promise<unknown>>(Promise.resolve());+ const addressesOut = useRef(0);+ /** The addresses being written, and the list the form opened them from. */+ const [draftAddresses, setDraftAddresses] = useState<DraftAddress[]>([]);+ const addressBase = useRef<PostalAddress[]>([]);+ /** Addresses whose label is being typed, by their key. */+ const [addressCustom, setAddressCustom] = useState<Set<number>>(() => new Set());+ const addressKey = useRef(0);+ /** A just-added address takes the focus, once. */+ const [addedKey, setAddedKey] = useState<number | null>(null);+ const startAddresses = (list: PostalAddress[]) => {+ addressBase.current = list;+ setDraftAddresses(list.map((address, from) => ({ key: ++addressKey.current, from, address })));+ setAddressCustom(new Set());+ setAddedKey(null);+ };const edit = (c: Contact) => {draftBase.current = c;setDraft({ ...c });setCustomAt(new Set());+ if (addresses?.guid === c.guid) startAddresses(addresses.list);+ else {+ startAddresses([]);+ contactsApi+ .addresses(c.guid)+ .then((list) => {+ if (draftBase.current === c) startAddresses(Array.isArray(list) ? list : []);+ })+ .catch(() => {});+ }};const [busy, setBusy] = useState(false);/** The detail whose label was just clicked to copy it, said for a moment. */@@ -272,6 +308,53 @@ export function ContactsView() {if (list !== ALL && !lists.some((l) => l.guid === list)) setList(ALL);}, [lists, list]);+ // The open card's addresses, part by part — read again whenever the library may have moved,+ // unless a change of this screen's own is still on its way to Apple.+ useEffect(() => {+ if (!openGuid || openGuid.startsWith("pending-")) return undefined;+ let cancelled = false;+ if (addressesOut.current === 0)+ contactsApi+ .addresses(openGuid)+ .then((list) => {+ if (!cancelled && addressesOut.current === 0) setAddresses({ guid: openGuid, list: Array.isArray(list) ? list : [] });+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [openGuid, due, outbox.tick]);++ /**+ * Address edits: drawn at once, then sent. Turned down, the list goes back to what it was,+ * then to what Apple holds, and a toast says so with the way to try again.+ */+ const sendAddresses = useCallback(+ (guid: string, base: PostalAddress[], edits: AddressEdit[], after: PostalAddress[]) => {+ setAddresses({ guid, list: after });+ addressesOut.current += 1;+ addressQueue.current = addressQueue.current.then(async () => {+ try {+ const written = await contactsApi.addressEdit(guid, base, edits);+ if (Array.isArray(written)) setAddresses((cur) => (cur?.guid === guid ? { guid, list: written } : cur));+ read(search).catch(() => {});+ } catch (e) {+ setAddresses((cur) => (cur?.guid === guid ? { guid, list: base } : cur));+ toast({+ message: `Address not saved. ${messageOf(e)}`,+ tone: "error",+ action: { label: "Try Again", run: () => sendAddresses(guid, base, edits, after) },+ });+ const held = await contactsApi.addresses(guid).catch(() => null);+ if (Array.isArray(held)) setAddresses((cur) => (cur?.guid === guid ? { guid, list: held } : cur));+ } finally {+ addressesOut.current -= 1;+ }+ });+ },+ [read, search],+ );+/** Who shows: everyone, or the people in the open list. */const shown = useMemo(() => {if (list === ALL) return contacts;@@ -409,14 +492,26 @@ export function ContactsView() {if (!draft) return;const saving = draft;let guid = saving.guid;+ // Addresses are written part by part on their own; the rest of the card only if it changed.+ const base = addressBase.current;+ const edits = saving.guid ? addressEdits(base, draftAddresses) : [];+ const after = predicted(base, draftAddresses);+ const cardChanged = !saving.guid || JSON.stringify(saving) !== JSON.stringify(draftBase.current);+ if (!cardChanged) {+ setDraft(null);+ if (edits.length) sendAddresses(saving.guid, base, edits, after);+ return;+ }+ if (edits.length) setAddresses({ guid: saving.guid, list: after });const ok = await write(async () => {guid = await api.contactSave(saving, saving.guid ? draftBase.current : null);});if (ok) {setDraft(null);setOpenGuid(guid);- }- }, [draft, write]);+ if (edits.length) sendAddresses(guid, base, edits, after);+ } else if (edits.length) setAddresses({ guid: saving.guid, list: base });+ }, [draft, draftAddresses, sendAddresses, write]);/*** Deleting a person is not something to discover by accident. Inside a list, icloud.com@@ -452,6 +547,8 @@ export function ContactsView() {() => contacts.find((c) => c.guid === openGuid) ?? null,[contacts, openGuid]);+ /** The open card's addresses part by part, once read; until then the lines Apple formatted. */+ const structured = open && addresses?.guid === open.guid ? addresses.list : null;// Who is still here of those picked — a search or a list change narrows them.const pickedPeople = useMemo(() => {const chosen = new Set(picked);@@ -917,7 +1014,8 @@ export function ContactsView() {<ul className="contact-method-rows">{draft.methods.map((m, index) =>- !EDITABLE_KINDS.has(m.kind) ? (+ // An existing card's addresses are written part by part, below.+ m.kind === "address" && draft.guid ? null : !EDITABLE_KINDS.has(m.kind) ? (// Shown so it is not a surprise that it exists, but not offered for// editing — this app cannot write a structured address back safely.<li key={index} className="contact-method-fixed">@@ -998,18 +1096,59 @@ export function ContactsView() {)}</ul>- <button- type="button"- className="quiet"- onClick={() =>- setDraft({- ...draft,- methods: [...draft.methods, { kind: "phone", label: "MOBILE", value: "" }],- })- }- >- Add phone, email or link- </button>+ {draft.guid && draftAddresses.length > 0 && (+ <ul className="contact-method-rows contact-address-rows" aria-label="Addresses">+ {draftAddresses.map((d, i) => (+ <AddressEditor+ key={d.key}+ n={i + 1}+ address={d.address}+ custom={addressCustom.has(d.key)}+ autoFocus={addedKey === d.key}+ onChange={(patch) =>+ setDraftAddresses((all) => all.map((x) => (x.key === d.key ? { ...x, address: { ...x.address, ...patch } } : x)))+ }+ onCustom={(on) =>+ setAddressCustom((was) => {+ const next = new Set(was);+ if (on) next.add(d.key);+ else next.delete(d.key);+ return next;+ })+ }+ onRemove={() => setDraftAddresses((all) => all.filter((x) => x.key !== d.key))}+ />+ ))}+ </ul>+ )}++ <div className="contact-form-adds">+ <button+ type="button"+ className="quiet"+ onClick={() =>+ setDraft({+ ...draft,+ methods: [...draft.methods, { kind: "phone", label: "MOBILE", value: "" }],+ })+ }+ >+ Add phone, email or link+ </button>+ {draft.guid && (+ <button+ type="button"+ className="quiet"+ onClick={() => {+ const key = ++addressKey.current;+ setDraftAddresses((all) => [...all, { key, from: null, address: blankAddress() }]);+ setAddedKey(key);+ }}+ >+ Add address+ </button>+ )}+ </div><div className="contact-birthday-field"><label>@@ -1123,7 +1262,7 @@ export function ContactsView() {</div><dl className="contact-methods">- {open.methods.map((m, i) => {+ {(structured ? open.methods.filter((m) => m.kind !== "address") : open.methods).map((m, i) => {const key = `${m.kind}-${i}`;const label = (m.label && labelText(m.label)) || KIND_LABEL[m.kind] || m.kind;return (@@ -1150,7 +1289,10 @@ export function ContactsView() {<a href={webHref(m.value)}>{m.value}</a>) : m.kind === "address" ? (// A postal address is several lines and stays that way.- <span className="contact-address">{m.value}</span>+ <>+ <span className="contact-address">{m.value}</span>+ <a className="contact-maps" href={mapsHref(m.value)}>Show in Maps</a>+ </>) : (m.value)}@@ -1158,6 +1300,31 @@ export function ContactsView() {</div>);})}+ {structured?.map((a, i) => {+ const key = `postal-${i}`;+ const label = (a.label && labelText(a.label)) || "address";+ const text = formatAddress(a);+ return (+ <div key={key} className="contact-postal">+ <dt>+ <button+ type="button"+ className="contact-copy"+ title={`Copy ${label} address`}+ aria-label={`Copy ${label} address`}+ onClick={() => void copyText(text).then((ok) => ok && setCopied(key))}+ >+ <span className={copied === key ? "is-hidden" : undefined}>{label}</span>+ <span className={copied === key ? undefined : "is-hidden"} aria-hidden={copied !== key}>copied</span>+ </button>+ </dt>+ <dd>+ <span className="contact-address">{text}</span>+ <a className="contact-maps" href={mapsHref(text)}>Show in Maps</a>+ </dd>+ </div>+ );+ })}{open.birthday && (<div><dt>birthday</dt>@@ -1166,7 +1333,7 @@ export function ContactsView() {)}</dl>- {open.methods.length === 0 && !open.birthday && (+ {open.methods.length === 0 && !structured?.length && !open.birthday && (<p className="contact-none">No phone numbers or addresses saved.</p>)}{open.notes && <p className="contact-notes">{open.notes}</p>}@@ -1400,3 +1567,199 @@ function sortedContacts(list: Contact[]): Contact[] {return contactCollator.compare(sortKey(a), sortKey(b));});}++/* ── Postal addresses ─────────────────────────────────────────────────────────────────── */++/**+ * The lines of an address in the order its country writes them — the backend's+ * `PostalAddress::formatted`, line for line, so an address just edited here reads exactly as+ * it will once the card is read back from Apple.+ */+type AddressLine = [AddressPart, string][];+const LAYOUTS: Record<string, AddressLine[]> = {+ us: [[["street", ""]], [["subLocality", ""]], [["city", ""], ["state", ", "], ["postalCode", " "]], [["country", ""]]],+ gb: [[["street", ""]], [["subLocality", ""]], [["city", ""]], [["subAdministrativeArea", ""]], [["postalCode", ""]], [["country", ""]]],+ in: [[["street", ""]], [["subLocality", ""]], [["city", ""], ["postalCode", " "]], [["state", ""]], [["country", ""]]],+ de: [[["street", ""]], [["postalCode", ""], ["city", " "]], [["country", ""]]],+ jp: [[["postalCode", ""]], [["state", ""], ["city", " "], ["subLocality", " "]], [["street", ""]], [["country", ""]]],+ other: [[["street", ""]], [["subLocality", ""]], [["city", ""], ["state", " "], ["postalCode", " "]], [["country", ""]]],+};+LAYOUTS.fr = LAYOUTS.de;+const CODES: Record<string, string> = { us: "us", gb: "gb", uk: "gb", in: "in", de: "de", fr: "fr", jp: "jp" };+const NAMES: Record<string, string> = Object.fromEntries(+ ([+ ["us", ["united states", "united states of america", "usa", "us", "u.s.a", "u.s", "america"]],+ ["gb", ["united kingdom", "uk", "u.k", "great britain", "britain", "england", "scotland", "wales", "northern ireland", "gb"]],+ ["in", ["india", "bharat", "in"]],+ ["de", ["germany", "deutschland", "de"]],+ ["fr", ["france", "fr"]],+ ["jp", ["japan", "nippon", "日本", "jp"]],+ ] as const).flatMap(([code, names]) => names.map((n) => [n, code])),+);+/** Apple's code for a country typed by name, for the countries laid out by their own rules. */+function countryCodeFor(name: string): string | null {+ const folded = name.trim().normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/\.+$/, "");+ return NAMES[folded] ?? null;+}+function formatAddress(a: PostalAddress): string {+ const key = (a.countryCode && CODES[a.countryCode.trim().toLowerCase()]) || (a.country && countryCodeFor(a.country)) || "other";+ const lines: string[] = [];+ for (const line of LAYOUTS[key]) {+ let text = "";+ for (const [part, separator] of line) {+ const value = a[part];+ if (!value) continue;+ if (text) text += separator;+ text += value;+ }+ lines.push(...text.split("\n").map((l) => l.trim()).filter(Boolean));+ }+ return lines.join("\n");+}+/** The address on one line, for a map to search for. */+const mapsHref = (text: string) => `geo:0,0?q=${encodeURIComponent(text.split("\n").join(", "))}`;++/** The parts the editor shows, in the order Tab walks them. */+const ADDRESS_PARTS = ["street", "city", "state", "postalCode", "country"] as const;+const PART_NAME: Record<(typeof ADDRESS_PARTS)[number], string> = {+ street: "Street",+ city: "City",+ state: "State",+ postalCode: "Postcode",+ country: "Country",+};+const ADDRESS_LABELS = ["HOME", "WORK", "OTHER"];+const ALL_PARTS: AddressPart[] = ["street", "subLocality", "city", "subAdministrativeArea", "state", "postalCode", "country", "countryCode"];++const blankAddress = (): PostalAddress => ({+ label: "HOME", street: null, subLocality: null, city: null, subAdministrativeArea: null,+ state: null, postalCode: null, country: null, countryCode: null,+});+/** A part as stored: trimmed, and nothing rather than an empty string. */+const tidy = (v: string | null | undefined) => (v && v.trim() ? v.trim() : null);+const isEmptyAddress = (a: PostalAddress) => ALL_PARTS.every((p) => !tidy(a[p]));++/** An address in the editor: where it sat in the list the form opened (null for a new one). */+type DraftAddress = { key: number; from: number | null; address: PostalAddress };++/**+ * What the editor's addresses change from the list it opened with, as the backend's edits:+ * parts and labels first (by their places in that list), then removals from the end back,+ * then additions — so every index names the address it meant.+ */+function addressEdits(base: PostalAddress[], draft: DraftAddress[]): AddressEdit[] {+ const edits: AddressEdit[] = [];+ for (const d of draft) {+ if (d.from === null) continue;+ const was = base[d.from];+ for (const part of ADDRESS_PARTS) {+ const value = tidy(d.address[part]);+ if (value !== tidy(was[part])) edits.push({ op: "setField", index: d.from, field: part, value });+ }+ const label = tidy(d.address.label);+ if (label !== tidy(was.label)) edits.push({ op: "setLabel", index: d.from, label });+ }+ const kept = new Set(draft.map((d) => d.from));+ for (let i = base.length - 1; i >= 0; i--) if (!kept.has(i)) edits.push({ op: "remove", index: i });+ for (const d of draft) {+ if (d.from === null && !isEmptyAddress(d.address)) edits.push({ op: "add", address: settled(d.address, null) });+ }+ return edits;+}++/** An address as the backend will store it: trimmed, and its country's code kept in step. */+function settled(a: PostalAddress, was: PostalAddress | null): PostalAddress {+ const out = { ...a, label: tidy(a.label) };+ for (const p of ALL_PARTS) out[p] = tidy(a[p]);+ if (!was ? !out.countryCode : tidy(was.country) !== out.country) out.countryCode = out.country ? countryCodeFor(out.country) : null;+ return out;+}+/** The list the edits will leave, drawn before Apple has it. */+const predicted = (base: PostalAddress[], draft: DraftAddress[]) =>+ draft.map((d) => settled(d.address, d.from === null ? null : base[d.from])).filter((a) => !isEmptyAddress(a));++/**+ * One address being written, laid out as Contacts on the Mac lays one out: the street over+ * as many lines as it takes, then town, region and postcode on one line, then the country.+ */+function AddressEditor({ n, address, custom, autoFocus, onChange, onCustom, onRemove }: {+ n: number;+ address: PostalAddress;+ custom: boolean;+ autoFocus: boolean;+ onChange: (patch: Partial<PostalAddress>) => void;+ onCustom: (custom: boolean) => void;+ onRemove: () => void;+}) {+ const match = ADDRESS_LABELS.find((v) => v === address.label?.toUpperCase());+ const typing = custom || (address.label !== null && !match);+ const field = (part: (typeof ADDRESS_PARTS)[number], extra?: { autoFocus?: boolean }) => (+ <input+ className={`contact-address-${part}`}+ value={address[part] ?? ""}+ placeholder={PART_NAME[part]}+ aria-label={`${PART_NAME[part]}, address ${n}`}+ autoComplete="off"+ autoFocus={extra?.autoFocus}+ onChange={(e) => onChange({ [part]: e.target.value || null })}+ />+ );+ const street = address.street ?? "";+ return (+ <li className="contact-address-edit">+ <span className="contact-address-kind">address</span>+ <Picker+ label={`Label for address ${n}`}+ className="contact-label-pick"+ value={typing ? CUSTOM : (match ?? "")}+ onChange={(v) => {+ onCustom(v === CUSTOM);+ if (v !== CUSTOM) onChange({ label: v || null });+ }}+ options={[+ ...(address.label === null && !typing ? [{ value: "", label: "no label" }] : []),+ ...ADDRESS_LABELS.map((v) => ({ value: v, label: labelText(v) })),+ { value: CUSTOM, label: "Custom" },+ ]}+ />+ {typing ? (+ <input+ className="contact-method-label contact-address-custom"+ value={address.label ?? ""}+ placeholder="label"+ aria-label={`Custom label for address ${n}`}+ onChange={(e) => onChange({ label: e.target.value || null })}+ />+ ) : (+ <span aria-hidden="true" />+ )}+ <button type="button" className="quiet danger" aria-label={`Remove address ${n}`} onClick={onRemove}>+ ✕+ </button>+ <div className="contact-address-fields">+ <textarea+ className="contact-address-street"+ value={street}+ rows={Math.max(2, street.split("\n").length)}+ placeholder="Street"+ aria-label={`Street, address ${n}`}+ autoFocus={autoFocus}+ onChange={(e) => onChange({ street: e.target.value || null })}+ onKeyDown={(e) => {+ // Return saves, as in every other field; Shift-Return starts another line.+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault();+ e.currentTarget.form?.requestSubmit();+ }+ }}+ />+ <div className="contact-address-line">+ {field("city")}+ {field("state")}+ {field("postalCode")}+ </div>+ {field("country")}+ </div>+ </li>+ );+}diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex 712b9a0..8f89006 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -177,7 +177,7 @@ function DriveTrash({ onClose }: { onClose: () => void }) {{driveName(item)}</span><span className="drive-meta drive-kind">- {item.restorePath ? `From ${item.restorePath.split("/").slice(0, -1).join("/") || "iCloud Drive"}` : kindName(item)}+ {item.restorePath ? `From ${item.restorePath.split("/").slice(0, -1).join("/") || "Drive"}` : kindName(item)}</span><span className="drive-meta">{isContainer(item) ? "" : fileSize(item.size)}</span><span className={`drive-meta${daysLeft(item.expiresAt) !== null && (daysLeft(item.expiresAt) ?? 99) <= 3 ? " is-soon" : ""}`}>@@ -438,7 +438,7 @@ function sameItems(a: DriveItem[], b: DriveItem[]): boolean {}export function DriveView() {- const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "iCloud Drive" }]);+ const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "Drive" }]);const [items, setItems] = useState<DriveItem[]>([]);const [inTrash, setInTrash] = useState(false);const [inRecents, setInRecents] = useState(false);@@ -538,7 +538,7 @@ export function DriveView() {}setInTrash(false);setInRecents(false);- setTrail([{ id: DRIVE_ROOT, name: "iCloud Drive" }, ...crumbs]);+ setTrail([{ id: DRIVE_ROOT, name: "Drive" }, ...crumbs]);revealing.current = r.id;setSelected(r.id);})();@@ -669,6 +669,8 @@ export function DriveView() {// comes back — one small request; none while hidden — so a file saved on the phone appears// here as it would in Finder.const shown = useScreenActive();+ const shownNow = useRef(shown);+ shownNow.current = shown;useEffect(() => {if (!shown) return undefined;// Never over a change of this computer's own still on its way: a check read before a@@ -1026,6 +1028,9 @@ export function DriveView() {.onDragDropEvent((event) => {// A row of Drive's own being moved is not a file arriving from this machine.if (dragItem.current) return;+ // Only while Drive is the screen in front: a file dropped onto a note, with Drive+ // kept in the background, went up to iCloud Drive as well.+ if (!shownNow.current) return;const p = event.payload;// Over a folder's row, the files go into that folder, as Finder drops them; anywhere// else, into the folder that is open.@@ -1776,7 +1781,7 @@ function MoveDialog({onCancel: () => void;onMove: (destinationId: string) => void;}) {- const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "iCloud Drive" }]);+ const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "Drive" }]);const [folders, setFolders] = useState<DriveItem[]>([]);const [loading, setLoading] = useState(false);diff --git a/src/screens/Library.tsx b/src/screens/Library.tsxindex 05a4bc2..6680b8b 100644--- a/src/screens/Library.tsx+++ b/src/screens/Library.tsx@@ -8,6 +8,7 @@ import { PanelLeft } from "lucide-react";import { api, messageOf, OPEN_REMINDER } from "../lib/ipc";import { SyncProvider, useSync } from "../lib/sync";import { AccountCard } from "../components/Account";+import { reveal, type Reveal } from "../lib/reveal";/** Each app is its own chunk, so the window opens on the code for the app it shows, not all@@ -63,7 +64,7 @@ import { GlobalSearch } from "../components/GlobalSearch";const SCREENS: { key: string; name: string }[] = [{ key: "reminders", name: "Reminders" },{ key: "notes", name: "Notes" },- { key: "drivews", name: "iCloud Drive" },+ { key: "drivews", name: "Drive" },{ key: "photos", name: "Photos" },{ key: "calendar", name: "Calendar" },{ key: "contacts", name: "Contacts" },@@ -95,6 +96,20 @@ function UpdateKeys({ screen }: { screen: string | null }) {return null;}+/*+ * A result picked in the desktop's own search (GNOME Shell, KRunner) arrives as an event for+ * this window: the item is handed to its screen (which takes it when it is up), and the+ * screen is brought to the front. Listened for from the moment the code loads, so a window+ * opened for the result does not miss it.+ */+const REVEAL = "quince://reveal";+let revealedScreen: string | null = null;+void listen<Reveal>(REVEAL, (e) => {+ revealedScreen = e.payload.screen;+ reveal(e.payload);+ window.dispatchEvent(new CustomEvent("quince:revealed"));+}).catch(() => {});+/** The screen open last time, so the app reopens where it was left. */const LAST_KEY = "quince.library.screen";const RAIL_KEY = "quince.library.rail";@@ -259,10 +274,18 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v// Clicking a reminder's alert brings the window back on Reminders.useEffect(() => {+ const front = () => {+ const screen = revealedScreen;+ revealedScreen = null;+ if (screen && services.includes(screen)) choose(screen);+ };+ front();+ window.addEventListener("quince:revealed", front);const stop = listen<string>(OPEN_REMINDER, () => {if (services.includes("reminders")) choose("reminders");});return () => {+ window.removeEventListener("quince:revealed", front);void stop.then((unlisten) => unlisten()).catch(() => {});};// eslint-disable-next-line react-hooks/exhaustive-deps@@ -363,12 +386,12 @@ export function Library({ onSignOut }: { onSignOut: (keep: boolean) => Promise<v<h1>Your iCloud data is kept off the web</h1><p>Your Apple Account uses Advanced Data Protection with “Access iCloud Data on the Web”- turned off, so Apple doesn’t let any app outside your devices — Pomander included —+ turned off, so Apple doesn’t let any app outside your devices — Skykeep included —read your iCloud.</p><p>- To use Pomander, turn it on: on your iPhone, open <b>Settings</b>, tap your name, then- <b> iCloud</b>, and turn on <b>Access iCloud Data on the Web</b>. Then sign in to Pomander+ To use Skykeep, turn it on: on your iPhone, open <b>Settings</b>, tap your name, then+ <b> iCloud</b>, and turn on <b>Access iCloud Data on the Web</b>. Then sign in to Skykeepagain.</p></div>diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 9baf14f..bfaea70 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -7,10 +7,15 @@ import { SearchField } from "../components/SearchField";import { PaneTitle } from "../components/PaneTitle";import { Unsent, Waiting } from "../components/Unsent";import { useOutbox } from "../lib/outbox";-import { ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, Pin, PinOff, Share, SquarePen, Trash2 } from "lucide-react";-import { save as saveFileDialog } from "@tauri-apps/plugin-dialog";+import { ChevronLeft, Folder, FolderOpen, FolderPlus, ListChecks, LockKeyhole, LockKeyholeOpen, Paperclip, Pin, PinOff, Share, SquarePen, Trash2 } from "lucide-react";+import { open as openFileDialog, save as saveFileDialog } from "@tauri-apps/plugin-dialog";+import { getCurrentWebview } from "@tauri-apps/api/webview";import { editorDate, groupNotes, listDate, mergeEdits, splitTitle } from "./notes/model";-import { api, messageOf, nestFolders, type Note, type NoteFolder } from "../lib/ipc";+import { api, messageOf, nestFolders, 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";+import { useActiveRef } from "../lib/screen";import { RowMenu } from "../components/RowMenu";import { FormattedBody, type Run } from "./notes/Formatted";import { carryRuns, runsFit } from "./notes/rich";@@ -133,6 +138,14 @@ export function NotesView() {/** What is typed in the search field. While it holds anything, the list is the results. */const [query, setQuery] = useState("");const searching = query.trim().length > 0;+ /**+ * Where a search looks: every folder, as Notes' search does (Ctrl+Shift+F), or only the+ * folder in front (Ctrl+F). Means nothing in All iCloud, which is every folder already.+ */+ const [scope, setScope] = useState<"all" | "folder">("all");+ const scoped = searching && scope === "folder" && folder !== ALL;+ const searchRef = useRef<HTMLInputElement | null>(null);+ const rowsRef = useRef<HTMLDivElement | null>(null);/** Notes outside Recently Deleted, and how many each folder holds. */const [counts, setCounts] = useState<{ all: number; per: Map<string, number> }>({@@ -153,12 +166,15 @@ export function NotesView() {const [found, list] = await Promise.all([api.noteFolders(),// Search reaches every folder, as Apple's does — a note is found wherever it is filed.- searching ? api.notesSearch(query) : api.notesIn(folder === ALL ? null : folder),+ searching+ ? api.notesSearch(query).then((found) =>+ scoped && Array.isArray(found) ? found.filter((n) => n.folderGuid === folder) : found)+ : api.notesIn(folder === ALL ? null : folder),]);setFolders(Array.isArray(found) ? found : []);setNotes(over(Array.isArray(list) ? list : []));setLoaded(true);- }, [folder, query, searching, over]);+ }, [folder, query, searching, scoped, over]);// Reads the library and nothing else. `revision` ticks when a refresh finishes, whether// someone pressed for it or the timer came round, and that is the screen's whole@@ -701,6 +717,105 @@ export function NotesView() {);}, [open, write]);+ /**+ * Locked notes opened this session, by note: their text, in this window's memory only —+ * never the library, never disk. Lock Now lets every one go, and the passwords with them.+ */+ const [unlocked, setUnlocked] = useState<Record<string, UnlockedNote>>({});+ const opened = open?.locked ? (unlocked[open.guid] ?? null) : null;+ const lockNow = useCallback(() => {+ setUnlocked({});+ notesLockApi.noteLockForget().catch(() => {});+ }, []);+ /** How the last note was picked: a click goes on into its password field, an arrow key stays in the list. */+ const pickedBy = useRef<"pointer" | "keys">("keys");++ /**+ * Adding a picture or file: the paperclip, or a file dropped on the note. Both exist only+ * while the backend allows it (see notes/attach.ts).+ */+ const attachOn = useAttachEnabled();+ const [attaching, setAttaching] = useState(false);+ const [dropping, setDropping] = useState(false);+ const attach = useCallback(+ async (paths: string[]) => {+ if (!open || open.locked || !open.editable || paths.length === 0) return;+ const guid = open.guid;+ // What is typed goes first, so the file lands in the text Apple holds.+ editorRef.current?.flushChange();+ await flush();+ const shown = editorRef.current?.current();+ let text = shown?.text ?? body;+ let at = editorRef.current?.caret() ?? text?.length ?? 0;+ setAttaching(true);+ try {+ for (const path of paths) {+ const added = await notesLockApi.noteAttachFile(guid, path, at, text);+ text = added.body;+ at = added.offset + 1;+ toast({ message: `Added “${fileName(path)}”`, tone: "done" });+ }+ // The note as Apple now holds it, file in place.+ const [nextBody, nextRuns] = await Promise.all([api.noteBody(guid), api.noteRuns(guid)]);+ if (nextBody !== null) setLoadedBody({ guid, text: nextBody });+ setLoadedRuns({ guid, runs: Array.isArray(nextRuns) ? nextRuns : [] });+ await read();+ } catch (e) {+ setError(messageOf(e));+ } finally {+ setAttaching(false);+ }+ },+ [open, flush, body, read]+ );+ const pickAttachment = async () => {+ try {+ const chosen = await openFileDialog({ multiple: true, title: "Add to Note" });+ if (!chosen) return;+ await attach(Array.isArray(chosen) ? chosen : [chosen]);+ } catch (e) {+ setError(messageOf(e));+ }+ };+ const live = useActiveRef();+ const canAttachRef = useRef(false);+ const attachRef = useRef(attach);+ attachRef.current = attach;+ useEffect(() => {+ if (!attachOn) return undefined;+ let stop: (() => void) | undefined;+ let cancelled = false;+ // Over the note itself, on the screen in front: a file dropped anywhere else is not for it.+ const overNote = (x: number, y: number) => {+ const ratio = window.devicePixelRatio || 1;+ return Boolean((document.elementFromPoint(x / ratio, y / ratio) as HTMLElement | null)?.closest?.(".note-body"));+ };+ try {+ void getCurrentWebview()+ .onDragDropEvent((event) => {+ const p = event.payload;+ if (!live.current || !canAttachRef.current) return setDropping(false);+ if (p.type === "over" || p.type === "enter") setDropping(overNote(p.position.x, p.position.y));+ else if (p.type === "leave") setDropping(false);+ else if (p.type === "drop") {+ setDropping(false);+ if (overNote(p.position.x, p.position.y)) void attachRef.current(p.paths);+ }+ })+ .then((unlisten) => {+ if (cancelled) unlisten();+ else stop = unlisten;+ })+ .catch(() => {});+ } catch {+ // Outside the app shell there is no webview to listen to; the paperclip still works.+ }+ return () => {+ cancelled = true;+ stop?.();+ };+ }, [attachOn, live]);+// A save confirmation is a moment, not a state.useEffect(() => {if (!saved) return undefined;@@ -709,6 +824,99 @@ export function NotesView() {}, [saved]);const canEdit = Boolean(composing) || Boolean(open && !open.locked && open.editable && body !== null);+ const canAttach = attachOn && !composing && !inTrash && Boolean(open && !open.locked && open.editable && body !== null);+ canAttachRef.current = canAttach;++ /** Delete from the keyboard, asked first: a key is easier to press by mistake than a button. */+ const removeAsked = useCallback(async () => {+ if (!open || open.locked) return;+ // Recently Deleted asks its own, final question.+ if (open.folderGuid === TRASH_FOLDER) return remove();+ const name = wordsOnly(open.title) || "New Note";+ const sure = await confirm({+ title: `Delete \u201c${name}\u201d?`,+ body: "It moves to Recently Deleted, where you can recover it.",+ action: "Delete",+ danger: true,+ symbol: "trash",+ });+ if (sure) await remove();+ }, [open, remove, confirm]);++ /** The row of a note, to put focus on it. */+ const focusRow = (guid: string | null) =>+ window.requestAnimationFrame(() => {+ const row = guid ? rowsRef.current?.querySelector<HTMLElement>(`[data-guid="${CSS.escape(guid)}"]`) : null;+ (row ?? rowsRef.current?.querySelector<HTMLElement>(".note-row"))?.focus();+ });++ /** Up and Down through the list as it is shown, pinned notes first. */+ const step = useCallback(+ (by: 1 | -1) => {+ const order = groupNotes(notes).flatMap((g) => g.notes.map((n) => n.guid));+ if (order.length === 0) return;+ const at = openGuid ? order.indexOf(openGuid) : -1;+ const next = at < 0 ? order[0] : order[Math.max(0, Math.min(order.length - 1, at + by))];+ pickedBy.current = "keys";+ if (next !== openGuid) void selectNote(next);+ focusRow(next);+ },+ [notes, openGuid, selectNote]+ );++ /** Into the search field: this folder (Ctrl+F) or every folder (Ctrl+Shift+F). */+ const find = useCallback((where: "all" | "folder") => {+ setScope(where);+ const field = searchRef.current;+ field?.focus();+ field?.select();+ }, []);++ /** Out of search, back to the list where the open note is. */+ const leaveSearch = useCallback(() => {+ setQuery("");+ setScope("all");+ focusRow(openGuid);+ }, [openGuid]);++ // The keys, as Notes on a Mac has them (Ctrl here). Only while Notes is the screen in front,+ // and never over a sheet or a menu, which answer their own keys.+ const keys = useRef({ create, find, removeAsked, step, leaveSearch, searching });+ keys.current = { create, find, removeAsked, step, leaveSearch, searching };+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (!live.current || e.defaultPrevented || e.isComposing) return;+ if (document.querySelector('[role="menu"], [role="dialog"], [role="alertdialog"], [role="listbox"], .confirm')) return;+ const target = e.target as HTMLElement | null;+ const typing = Boolean(target?.closest?.("input, textarea, select, [contenteditable='true']"));+ const mod = (e.ctrlKey || e.metaKey) && !e.altKey;+ const k = e.key.toLowerCase();+ const k_ = keys.current;+ if (mod && !e.shiftKey && k === "n") {+ e.preventDefault();+ if (!e.repeat) void k_.create();+ } else if (mod && k === "f") {+ e.preventDefault();+ k_.find(e.shiftKey ? "all" : "folder");+ } else if (typing) {+ return;+ } else if (e.key === "Escape" && k_.searching) {+ e.preventDefault();+ k_.leaveSearch();+ } else if (mod && !e.shiftKey && (e.key === "Backspace" || e.key === "Delete")) {+ e.preventDefault();+ if (!e.repeat) void k_.removeAsked();+ } else if (!mod && !e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey && (e.key === "ArrowDown" || e.key === "ArrowUp")) {+ // Not from a control with arrows of its own — a picker, the format panel.+ if (target && target !== document.body && !target.closest(".note-rows, .note-body, .notes-list-head")) return;+ if (target?.closest(".note-body") && target.closest("button, a, [role='checkbox']")) return;+ e.preventDefault();+ k_.step(e.key === "ArrowDown" ? 1 : -1);+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [live]);/** Every change in the editor: to the note being composed, or to the open one. */const apply = (next: string, nextRuns: Run[]) => {@@ -926,15 +1134,39 @@ export function NotesView() {</button></header><SearchField+ ref={searchRef}className="notes-search"- placeholder="Search"+ placeholder={folder !== ALL && scope === "folder" ? `Search ${folders.find((f) => f.guid === folder)?.title ?? "This Folder"}` : "Search"}aria-label="Search notes"+ aria-keyshortcuts="Control+F Control+Shift+F"value={query}onChange={setQuery}+ onClear={() => {+ setQuery("");+ setScope("all");+ searchRef.current?.focus();+ }}onKeyDown={(e) => {- if (e.key === "Escape") setQuery("");+ if (e.key === "Escape") {+ e.preventDefault();+ leaveSearch();+ } else if (e.key === "ArrowDown" && searching) {+ // On into what was found.+ e.preventDefault();+ focusRow(openGuid && notes.some((n) => n.guid === openGuid) ? openGuid : null);+ }}}/>+ {searching && folder !== ALL && (+ <div className="segmented notes-scope" role="group" aria-label="Search in">+ <button type="button" className="segment" aria-pressed={scope === "all"} onClick={() => setScope("all")}>+ All iCloud+ </button>+ <button type="button" className="segment" aria-pressed={scope === "folder"} onClick={() => setScope("folder")}>+ <span className="notes-scope-name">{folders.find((f) => f.guid === folder)?.title ?? "This Folder"}</span>+ </button>+ </div>+ )}{/* Shown only when the folder column has folded away. */}<div className="notes-folder-picker">@@ -951,7 +1183,7 @@ export function NotesView() {<Unsent refused={outbox.refused} what="an edit to a note" onResend={(r) => void outbox.resend(r)} onDiscard={(r) => void outbox.discard(r)} />- <div className="note-rows" role="list">+ <div className="note-rows" role="list" ref={rowsRef}>{sections.map((section) => (<Fragment key={section.key}><h2 className="notes-section">{section.heading}</h2>@@ -959,10 +1191,22 @@ export function NotesView() {<div role="listitem" key={note.guid}><buttonclassName="note-row"+ data-guid={note.guid}aria-current={openGuid === note.guid}- onClick={() => void selectNote(note.guid)}+ onClick={(e) => {+ pickedBy.current = e.detail > 0 ? "pointer" : "keys";+ // A locked note clicked again, already open: on into its password field.+ if (e.detail > 0 && note.locked && note.guid === openGuid)+ document.querySelector<HTMLInputElement>(".notes .note-lock-field")?.focus();+ void selectNote(note.guid);+ }}>- <span className="note-row-title">{wordsOnly(note.title) || "New Note"}</span>+ <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">{wordsOnly(note.title) || "New Note"}</span>+ </span><span className="note-row-meta"><span className="note-row-when">{listDate(note.modifiedAt)}</span><span className="note-row-snippet">@@ -977,14 +1221,26 @@ export function NotesView() {</div>{loaded && notes.length === 0 && !error && !(arriving && !searching) && (- <EmptyState className="notes-empty">{searching ? "No results." : "No notes here."}</EmptyState>+ searching ? (+ <EmptyState className="notes-empty">+ Nothing matches “{query.trim()}”{scoped ? " in this folder" : ""}.+ </EmptyState>+ ) : folder === TRASH_FOLDER ? (+ <EmptyState className="notes-empty" icon={<Trash2 size={28} strokeWidth={1.5} />}>+ Recently Deleted is empty.+ </EmptyState>+ ) : (+ <EmptyState className="notes-empty" icon={<SquarePen size={28} strokeWidth={1.5} />}>+ Notes you write here appear on all your devices.+ </EmptyState>+ ))}{notes.length === 0 && !searching && (<Arriving service="notes" what="notes" className="notes-empty" />)}</section>- <article className="note-body" aria-label="Note">+ <article className={`note-body${dropping ? " is-dropping" : ""}`} aria-label="Note">{(composing || open) && (<div className="note-bar"><button@@ -998,7 +1254,13 @@ export function NotesView() {<ChevronLeft size={18} strokeWidth={2.25} aria-hidden="true" /><span>{heading}</span></button>- <p className="note-when">+ <p+ className={`note-when${+ busy || (!saveFailed && (dirty || composing?.body.trim())) || (open && outbox.waiting.has(open.guid)) || saved+ ? ""+ : " is-date"+ }`}+ >{busy || (!saveFailed && (dirty || composing?.body.trim()))? "Saving…": open && outbox.waiting.has(open.guid)@@ -1027,6 +1289,18 @@ export function NotesView() {>Aa</button>+ {canAttach && (+ <button+ className="tool"+ aria-label="Add a picture or file"+ title="Add a picture or file"+ disabled={attaching || busy}+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => void pickAttachment()}+ >+ <Paperclip size={17} strokeWidth={2} aria-hidden="true" />+ </button>+ )}<buttonclassName="tool"aria-label="Make a checklist"@@ -1118,6 +1392,14 @@ export function NotesView() {)}</div>)}+ {!composing && open?.locked && opened && (+ <div className="toolbar-group note-bar-actions">+ <button className="tool has-label note-lock-now" onClick={lockNow} title="Lock every opened note again">+ <LockKeyholeOpen size={16} strokeWidth={2} aria-hidden="true" />+ Lock Now+ </button>+ </div>+ )}</div>)}@@ -1152,11 +1434,26 @@ export function NotesView() {onBlur={leave}/></div>+ ) : open?.locked && opened ? (+ /* Opened with its password: read here, written on an Apple device. */+ <div className="note-editor is-readonly is-unlocked">+ <h1 className="note-title">{splitTitle(opened.body).title}</h1>+ {runsFit(opened.body, opened.runs) ? (+ <div className="note-text note-read">+ <FormattedBody text={opened.body} runs={opened.runs} skip={splitTitle(opened.body).title.length + 1} />+ </div>+ ) : (+ <pre className="note-text">{splitTitle(opened.body).rest}</pre>+ )}+ <p className="note-readonly">Locked notes open read-only here. Edit them on your iPhone, iPad or Mac.</p>+ </div>) : open?.locked ? (- <EmptyState>- This note is locked. Apple keeps it encrypted, so there is nothing here to show —- open it on a device where you can enter its password.- </EmptyState>+ <LockScreen+ guid={open.guid}+ title={wordsOnly(open.title)}+ autoFocus={pickedBy.current === "pointer"}+ onOpen={(note) => setUnlocked((all) => ({ ...all, [open.guid]: note }))}+ />) : open && body === null ? (/* Nothing to type into until the note's own text has arrived: an empty box over anote whose body had not loaded would write that emptiness back. */@@ -1172,10 +1469,8 @@ export function NotesView() {<pre className="note-text">{splitTitle(body ?? "").rest}</pre>)}<p className="note-readonly">- Pomander can’t yet save changes to this note without risking what is in it — it- is very long, or its copy on iCloud is out of step with your devices — so it is- read-only here. Editing it on an Apple device is safe, and after that Pomander can- usually edit it again.+ Read-only here, to keep everything in it safe. A quick edit on your iPhone, iPad or+ Mac usually makes it editable again.</p></div>) : (diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex f4fcc94..3f5a9d6 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -40,6 +40,7 @@ import { fadeIn } from "../lib/fade";import { DownloadOptions, type Want } from "./photos/DownloadOptions";import { AdjustDate } from "./photos/AdjustDate";import { useReveal } from "../lib/reveal";+import { Picker } from "../components/Picker";/** The sidebar, in Photos' order, each with the symbol Photos gives it. */const VIEWS: { key: PhotoView; label: string; Icon: LucideIcon }[] = [@@ -66,6 +67,13 @@ const ACROSS = [10, 7, 5, 3];const monthOf = (seconds: number) =>new Date(seconds * 1000).toLocaleDateString(undefined, { month: "long", year: "numeric" });+/** "Sunday, 18 October", with the year when it is not this one: a day's heading, as Photos' Days. */+const dayOf = (seconds: number, thisYear: number) => {+ const d = new Date(seconds * 1000);+ return d.toLocaleDateString(undefined, { weekday: "long", day: "numeric", month: "long", ...(d.getFullYear() === thisYear ? {} : { year: "numeric" }) });+};+/** From this step of the zoom in (five across and closer), the library is grouped by day. */+const DAYS_FROM = 2;/** What Photos takes, as icloud.com's picker offers it. */const KINDS = ["jpg", "jpeg", "heic", "heif", "png", "gif", "tif", "tiff", "webp", "dng", "mov", "mp4", "m4v", "avi"];@@ -441,7 +449,7 @@ function idsOf(items: { photo: Photo }[]): Set<string> {* month again — every one was handed the whole selection — 166 ms on a 20,000-photo library.*/function sameMonth(a: MonthProps, b: MonthProps): boolean {- if (a.label !== b.label || a.items !== b.items || a.deleted !== b.deleted || a.eager !== b.eager+ if (a.label !== b.label || a.month !== b.month || a.items !== b.items || a.deleted !== b.deleted || a.eager !== b.eager || a.across !== b.across|| a.fit !== b.fit || a.cell !== b.cell || a.act !== b.act) return false;if (a.chosen !== b.chosen) {// Only the photos whose selection changed are looked at (worked out once per change, not@@ -460,13 +468,41 @@ function sameMonth(a: MonthProps, b: MonthProps): boolean {return true;}+/** Where a month's photos lie — its grid and whatever of it is still to be built — on screen. */+function photosArea(sec: HTMLElement): { top: number; height: number } {+ const first = sec.querySelector<HTMLElement>(":scope > .px-grid, :scope > .px-later") ?? sec;+ const top = first.getBoundingClientRect().top;+ return { top, height: sec.getBoundingClientRect().bottom - top };+}++/**+ * Months on their way are built a slice a frame, one month after another, in the order they+ * came near: the work a fast scroll asks for is spread over frames instead of landing in one.+ */+const BUILD_TILES = 28;+const builds: (() => boolean)[] = [];+let buildFrame = 0;+function buildSoon(job: () => boolean) {+ builds.push(job);+ if (!buildFrame) buildFrame = requestAnimationFrame(buildNext);+}+function buildNext() {+ buildFrame = 0;+ const job = builds[0];+ if (!job) return;+ if (job()) builds.shift();+ if (builds.length) buildFrame = requestAnimationFrame(buildNext);+}+type MonthProps = {label: string;+ month: string;items: { photo: Photo; index: number }[];chosen: Set<string>;anchor: number | null;deleted: boolean;eager: boolean;+ across: number;fit: boolean;cell: number;act: Acts;@@ -474,52 +510,83 @@ type MonthProps = {const Month = memo(function Month({label,+ month,items,chosen,anchor,deleted,eager,+ across,fit,cell,act,}: {label: string;+ month: string;items: { photo: Photo; index: number }[];chosen: Set<string>;anchor: number | null;deleted: boolean;eager: boolean;+ across: number;fit: boolean;cell: number;act: Acts;}) {const ref = useRef<HTMLElement | null>(null);- const [live, setLive] = useState(eager);+ // How many of its photos are built: all at once for the first months, and for the rest a few+ // rows a frame once the month comes near (see buildSoon). Built whole in one go, a month of a+ // hundred and fifty photos was one task of 50–110 ms — a frame dropped every time a fast+ // scroll reached the next month.+ const [built, setBuilt] = useState(eager ? items.length : 0);+ const builtNow = useRef(built);+ builtNow.current = built;+ const step = useRef(across);+ step.current = across;useEffect(() => {const el = ref.current;+ if (builtNow.current >= items.length) return undefined;+ let gone = false;+ const start = () =>+ buildSoon(() => {+ if (gone) return true;+ const rows = Math.max(2, Math.round(BUILD_TILES / step.current));+ const next = Math.min(items.length, builtNow.current + rows * step.current);+ builtNow.current = next;+ setBuilt(next);+ return next >= items.length;+ });if (!el || typeof IntersectionObserver === "undefined") {- setLive(true);- return undefined;+ start();+ return () => {+ gone = true;+ };}// Built well ahead and then kept: a month taken down and built again as it scrolls back// showed as a heading over nothing while its tiles came back.const watch = new IntersectionObserver(([e]) => {if (!e.isIntersecting) return;- setLive(true);watch.disconnect();+ start();},{ root: el.closest(".px-scroll"), rootMargin: "4000px 0px" },);watch.observe(el);- return () => watch.disconnect();- }, []);+ return () => {+ gone = true;+ watch.disconnect();+ };+ }, [items.length]); // eslint-disable-line react-hooks/exhaustive-deps+ // Built part way when the zoom changed: what is built stays on whole rows.+ const shownCount = built >= items.length ? items.length : Math.floor(built / across) * across;+ const live = shownCount > 0;return (- <section ref={ref} className="px-month" aria-label={label || undefined}>+ <section ref={ref} className="px-month" aria-label={label || undefined} data-month={month || undefined}>{label && <h2 className="px-month-title">{label}</h2>}- {live ? (+ {live && (<div className="px-grid" role="list">- {items.map(({ photo, index }) => {+ {(shownCount < items.length ? items.slice(0, shownCount) : items).map(({ photo, index }) => {const t = deleted ? timeLeft(photo, true) : null;return (<Tile@@ -537,12 +604,13 @@ const Month = memo(function Month({);})}</div>- ) : (+ )}+ {shownCount < items.length && (// Not built yet (far from the screen): one block as tall as its rows will be, its tiles// painted on it as plain boxes, so a fast scroll shows photos on their way — never an// empty page. One element, not one a photo: a box each was 20,000 on a large library,// and every focus and every frame paid for them (photos-scale).- <div className="px-later" aria-hidden="true" style={{ "--n": items.length } as React.CSSProperties}>+ <div className="px-later" aria-hidden="true" style={{ "--n": items.length - shownCount } as React.CSSProperties}><i className="px-later-in" /></div>)}@@ -698,23 +766,30 @@ export function PhotosView() {read().catch((e) => setError(messageOf(e)));}, [read, due]);- // Grouped by month, as the library reads; an album is one grid in its own order.+ // Grouped by month, as the library reads — or, zoomed in close, by day, as Photos' Days do;+ // an album is one grid in its own order. Each group knows its month, for the month picker and+ // the line under the title.+ const byDay = zoom >= DAYS_FROM;const months = useMemo(() => {- const out: { label: string; items: { photo: Photo; index: number }[] }[] = [];+ const out: { label: string; month: string; items: { photo: Photo; index: number }[] }[] = [];// An album keeps its own order, and Recently Deleted is in the order things were deleted:// grouped by the month they were taken, the same month came back again and again. Both are// one grid, as icloud.com shows them.- if (drawn.album || drawn.view === "recentlyDeleted") return [{ label: "", items: (photos ?? []).map((photo, index) => ({ photo, index })) }];+ if (drawn.album || drawn.view === "recentlyDeleted") return [{ label: "", month: "", items: (photos ?? []).map((photo, index) => ({ photo, index })) }];+ const thisYear = new Date().getFullYear();(photos ?? []).forEach((photo, index) => {// Rated is grouped by how many stars, as icloud.com's Rated page is.const stars = photo.rating ?? 0;- const label = drawn.view === "rated" && !drawn.album ? `${stars} ${stars === 1 ? "Star" : "Stars"}` : monthOf(sortKey(photo, sort?.by ?? "taken"));+ const rated = drawn.view === "rated" && !drawn.album;+ const at = sortKey(photo, sort?.by ?? "taken");+ const month = rated ? "" : monthOf(at);+ const label = rated ? `${stars} ${stars === 1 ? "Star" : "Stars"}` : byDay ? dayOf(at, thisYear) : month;const last = out[out.length - 1];if (last && last.label === label) last.items.push({ photo, index });- else out.push({ label, items: [{ photo, index }] });+ else out.push({ label, month, items: [{ photo, index }] });});return out;- }, [photos, sort?.by, drawn]);+ }, [photos, sort?.by, drawn, byDay]);const shown = open !== null ? photos?.[open] ?? null : null;/**@@ -879,9 +954,14 @@ export function PhotosView() {return () => tintFrom(document.body);}, [open !== null]); // eslint-disable-line react-hooks/exhaustive-deps+ /** The photo the viewer was on as it closed: the library comes back with it chosen and in view. */+ const backTo = useRef<number | null>(null);+ const openNow = useRef(open);+ openNow.current = open;const close = useCallback(() => {gridBehind(false);land();+ backTo.current = openNow.current;setOpen(null);}, []); // eslint-disable-line react-hooks/exhaustive-depsconst step = useCallback(@@ -1002,6 +1082,19 @@ export function PhotosView() {useEffect(() => {if (open === null && inBurst) void leaveBurst(false);}, [open === null]); // eslint-disable-line react-hooks/exhaustive-deps+ // Closed after going through the photos, as Photos: the one last shown is the one chosen in+ // the library, and the grid has it in view with the keys' focus on it — not the photo it was+ // opened from, forty photos and two months back up the grid.+ useLayoutEffect(() => {+ const at = backTo.current;+ backTo.current = null;+ if (open !== null || at === null || inBurst) return;+ const p = photos?.[at];+ if (!p) return;+ anchor.current = at;+ setChosen((c) => (c.size === 1 && c.has(p.id) ? c : new Set([p.id])));+ reach(at);+ }, [open === null]); // eslint-disable-line react-hooks/exhaustive-deps/*** The window full screen for a photo, as icloud.com's viewer offers: the button, and Escape* leaving full screen before it closes the photo. Closing the photo leaves it too.@@ -1214,7 +1307,11 @@ export function PhotosView() {const k = e.key === "0" ? 1 : lensRef.current.k * (e.key === "-" ? 1 / 1.5 : 1.5);zoomAt(k, box.left + box.width / 2, box.top + box.height / 2);}- else if (e.key === " " && current?.kind === "video") void play(current);+ // Space, as in Photos: a video plays and pauses (its player takes the key first), a Live+ // Photo plays its moving part, and a still goes back to the library it was opened from.+ else if (e.key === " " && current?.kind === "video" && !(videoBase && !unplayable.has(current.id))) void play(current);+ else if (e.key === " " && current?.kind === "live" && videoBase) setMoving((m) => (m === current.id ? null : current.id));+ else if (e.key === " " && current?.kind === "image" && !(e.target as HTMLElement | null)?.closest?.("button, [role=radio], [role=slider]")) close();else if (e.key.toLowerCase() === "i" && !e.metaKey && !e.ctrlKey) setInfo((v) => !v);// As in Photos: "." favorites, Delete sends it to Recently Deleted.// F as well as ".", and H as well as Ctrl+L, as icloud.com takes them.@@ -1570,7 +1667,7 @@ export function PhotosView() {else void changeAll(selected, "expunged", true);} else if (!ctrl && (e.key === "=" || e.key === "+" || e.key === "-")) {// = and − size the thumbnails, as in icloud.com's grid.- setZoom((z) => (e.key === "-" ? Math.max(0, z - 1) : Math.min(ACROSS.length - 1, z + 1)));+ zoomBy(e.key === "-" ? -1 : 1);} else if (!ctrl && e.key.toLowerCase() === "i" && selected.length) {// I: the selected photo, opened with its details.setInfo(true);@@ -1588,6 +1685,114 @@ export function PhotosView() {return () => window.removeEventListener("keydown", onKey);});+ /*+ * Sweeping out a rectangle from the space around the photos selects every photo it touches,+ * as on a Mac — with Ctrl (⌘) or Shift, adding to what was already chosen. Worked out from+ * the grid's geometry, not by measuring tiles: months far from the screen are not built, and+ * a sweep that scrolls the view still reaches them. The view scrolls on its own while the+ * pointer is held past its top or bottom edge.+ */+ const sweepBox = useRef<HTMLDivElement | null>(null);+ const swept = useRef(false);+ const sweepStart = (e: React.PointerEvent<HTMLDivElement>) => {+ swept.current = false;+ const el = scroller.current;+ if (!el || e.button !== 0 || e.pointerType === "touch") return;+ const t = e.target as HTMLElement;+ if (t.closest(".px-tile, button, a, input, .px-sweep") || !photos?.length) return;+ // Past the scrollbar is the scrollbar's.+ if (e.clientX >= el.getBoundingClientRect().left + el.clientWidth) return;+ const box0 = el.getBoundingClientRect();+ const start = { x: e.clientX - box0.left, y: e.clientY - box0.top + el.scrollTop };+ const base = e.ctrlKey || e.metaKey || e.shiftKey ? new Set(chosen) : new Set<string>();+ let pointer = { x: e.clientX, y: e.clientY };+ let moved = false;+ let tick = 0;+ let last = "";+ // The grid's geometry, read once: each group's block (built or not), and the cells' pitch.+ const groups = [...el.querySelectorAll<HTMLElement>(".px-month")].map((sec, k) => {+ const r = photosArea(sec);+ return { top: r.top - box0.top + el.scrollTop, height: r.height, k };+ });+ const style = getComputedStyle(el);+ const inner = el.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);+ const [gap, pad] = fit ? [14, 14] : [2, 0];+ const pitch = (inner - 2 * pad + gap) / across;+ const left0 = parseFloat(style.paddingLeft) + pad;+ const draw = () => {+ const box = el.getBoundingClientRect();+ const now = { x: Math.max(0, Math.min(el.clientWidth, pointer.x - box.left)), y: pointer.y - box.top + el.scrollTop };+ const [x1, x2] = [Math.min(start.x, now.x), Math.max(start.x, now.x)];+ const [y1, y2] = [Math.min(start.y, now.y), Math.max(start.y, now.y)];+ const shown = sweepBox.current;+ if (shown) {+ shown.hidden = false;+ shown.style.cssText = `left:${x1}px;top:${y1}px;width:${x2 - x1}px;height:${y2 - y1}px`;+ }+ const c1 = Math.max(0, Math.floor((x1 - left0) / pitch));+ const c2 = Math.min(across - 1, Math.floor((x2 - left0) / pitch));+ const next = new Set(base);+ if (c2 >= c1) {+ for (const g of groups) {+ if (g.top > y2 || g.top + g.height < y1) continue;+ const items = months[g.k]?.items;+ if (!items?.length) continue;+ const rows = Math.ceil(items.length / across);+ const rowH = g.height / rows;+ const r1 = Math.max(0, Math.floor((y1 - g.top) / rowH));+ const r2 = Math.min(rows - 1, Math.floor((y2 - g.top) / rowH));+ for (let r = r1; r <= r2; r++) {+ for (let c = c1; c <= c2; c++) {+ // Only the photo itself, not the hairline gap after it.+ if (x2 < left0 + c * pitch || x1 > left0 + c * pitch + pitch - gap) continue;+ const it = items[r * across + c];+ if (it) next.add(it.photo.id);+ }+ }+ }+ }+ const key = [...next].join();+ if (key !== last) {+ last = key;+ setChosen(next);+ }+ };+ const loop = () => {+ tick = 0;+ const box = el.getBoundingClientRect();+ const top = box.top + (parseFloat(style.paddingTop) || 0) - 12;+ const by = pointer.y < top ? -Math.min(40, (top - pointer.y) / 2 + 4) : pointer.y > box.bottom - 24 ? Math.min(40, (pointer.y - box.bottom + 24) / 2 + 4) : 0;+ if (by) el.scrollTop += by;+ draw();+ if (by) tick = requestAnimationFrame(loop);+ };+ const move = (ev: PointerEvent) => {+ pointer = { x: ev.clientX, y: ev.clientY };+ if (!moved && Math.hypot(ev.clientX - e.clientX, ev.clientY - e.clientY) < 4) return;+ moved = true;+ if (!tick) tick = requestAnimationFrame(loop);+ };+ const end = () => {+ window.removeEventListener("pointermove", move);+ window.removeEventListener("pointerup", end);+ window.removeEventListener("pointercancel", end);+ cancelAnimationFrame(tick);+ if (sweepBox.current) sweepBox.current.hidden = true;+ if (moved) {+ swept.current = true;+ // The keys go on from the sweep's last photo.+ const ids = [...chosenNow.current];+ const at = ids.length ? Math.max(...ids.map((id) => placeOf.get(id) ?? -1)) : -1;+ anchor.current = at >= 0 ? at : anchor.current;+ }+ };+ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", end);+ window.addEventListener("pointercancel", end);+ };+ const chosenNow = useRef(chosen);+ chosenNow.current = chosen;+// A slideshow of what is selected when that is more than one photo, else of the whole view// from this photo on, as Photos starts one.const startShow = (from: Photo) => {@@ -1724,8 +1929,8 @@ export function PhotosView() {},});- const acts = useRef({ pick, openAt, photoMenu, dragFrom });- acts.current = { pick, openAt, photoMenu, dragFrom };+ const acts = useRef({ pick, openAt, photoMenu, dragFrom, zoomBy });+ acts.current = { pick, openAt, photoMenu, dragFrom, zoomBy };const act = useMemo<Acts>(() => ({pick: (i, e) => acts.current.pick(i, e),@@ -2005,17 +2210,19 @@ export function PhotosView() {// the two always agree.const monthCovers = useMemo<MonthCover[]>(() => {if (drawn.album || drawn.view === "rated") return [];+ // By day, a month is several groups: the picker lists it once, with its first photo.+ const seen = new Set<string>();return months- .filter((m) => m.label && m.items.length)+ .filter((m) => m.month && m.items.length && !seen.has(m.month) && seen.add(m.month)).map((m) => {const cover = m.items[0].photo;const d = new Date(sortKey(cover, sort?.by ?? "taken") * 1000);- return { label: m.label, year: d.getFullYear(), month: d.getMonth(), cover };+ return { label: m.month, year: d.getFullYear(), month: d.getMonth(), cover };});}, [months, drawn, sort?.by]);const goToMonth = (label: string) => {const el = scroller.current;- const at = el?.querySelector<HTMLElement>(`.px-month[aria-label="${CSS.escape(label)}"]`);+ const at = el?.querySelector<HTMLElement>(`.px-month[data-month="${CSS.escape(label)}"]`);// Measured against the scroller itself: offsetTop counts from whatever positioned box// happens to hold the month, which is not always the scroller.if (el && at) {@@ -2044,7 +2251,7 @@ export function PhotosView() {if (months[mid].getBoundingClientRect().bottom > edge) hi = mid;else lo = mid + 1;}- setHere(months[lo]?.getAttribute("aria-label") ?? null);+ setHere(months[lo]?.dataset.month || months[lo]?.getAttribute("aria-label") || null);}, 120);}, [album]);useEffect(() => setHere(null), [view, album]);@@ -2062,8 +2269,8 @@ export function PhotosView() {const onKey = (e: KeyboardEvent) => {if (!live.current) return;if (!(e.ctrlKey || e.metaKey) || e.altKey || viewer.current) return;- if (e.key === "=" || e.key === "+") setZoom((z) => Math.min(ACROSS.length - 1, z + 1));- else if (e.key === "-") setZoom((z) => Math.max(0, z - 1));+ if (e.key === "=" || e.key === "+") acts.current.zoomBy(1);+ else if (e.key === "-") acts.current.zoomBy(-1);else return;e.preventDefault();};@@ -2104,6 +2311,52 @@ export function PhotosView() {fadeIn(scroller.current, { from: 0.35, duration: 160 });}, [drawn]);const across = ACROSS[zoom];+ /*+ * A zoom keeps its place, as Photos': the selected photo — or, with none in view, the photo at+ * the top left — stays where it was on the screen while the grid around it changes size.+ * Before, every step of the zoom left the view at a scroll offset that now meant a different+ * month, and the photo being looked at was gone.+ */+ const keepAt = useRef<{ index: number; top: number } | null>(null);+ function zoomBy(by: number) {+ const next = Math.max(0, Math.min(ACROSS.length - 1, zoom + by));+ if (next === zoom) return;+ const el = scroller.current;+ if (el && el.clientHeight) {+ const box = el.getBoundingClientRect();+ const pad = parseFloat(getComputedStyle(el).paddingTop) || 0;+ const seen = (t: Element | null) => {+ const r = t?.getBoundingClientRect();+ return r && r.bottom > box.top + pad - 8 && r.top < box.bottom ? r : null;+ };+ const mine = anchor.current !== null ? el.querySelector(`.px-tile[data-index="${anchor.current}"]`) : null;+ const tile = (seen(mine) ? mine : document.elementFromPoint(box.left + 8, box.top + pad + 8)?.closest(".px-tile")) as HTMLElement | null;+ if (tile && el.scrollTop > 0) keepAt.current = { index: Number(tile.dataset.index), top: tile.getBoundingClientRect().top - box.top };+ }+ setZoom(next);+ }+ useLayoutEffect(() => {+ const k = keepAt.current;+ keepAt.current = null;+ const el = scroller.current;+ if (!k || !el) return;+ const box = el.getBoundingClientRect();+ const tile = el.querySelector<HTMLElement>(`.px-tile[data-index="${k.index}"]`);+ let top: number | null = null;+ if (tile) top = tile.getBoundingClientRect().top - box.top + el.scrollTop;+ else {+ // Its group not built yet: where its row will be, from the group's own block, whose+ // height is exactly its rows'.+ const g = months.findIndex((m) => m.items.length && k.index >= m.items[0].index && k.index <= m.items[m.items.length - 1].index);+ const sec = el.querySelectorAll<HTMLElement>(".px-month")[g];+ if (sec) {+ const row = Math.floor((k.index - months[g].items[0].index) / across);+ const r = photosArea(sec);+ top = r.top - box.top + el.scrollTop + (row * r.height) / Math.ceil(months[g].items.length / across);+ }+ }+ if (top !== null) el.scrollTop = Math.max(0, top - k.top);+ }, [across]); // eslint-disable-line react-hooks/exhaustive-deps// A cell's width in device pixels, for the size each tile's picture is made at; in steps of// 32, so a window being resized does not redraw every tile on every frame.const [gridWidth, setGridWidth] = useState(0);@@ -2300,8 +2553,48 @@ export function PhotosView() {</button>);+ // In a narrow window the sidebar folds into one pop-up above the library, as Notes' folders+ // do: every place the sidebar goes, in its order. Beside 480px of window the sidebar took+ // half of it and left the photos a strip.+ const goTo = (to: string) => {+ const [kind, id] = [to.slice(0, to.indexOf(":")), to.slice(to.indexOf(":") + 1)];+ endSearch();+ setOpen(null);+ if (kind === "view") {+ setView(id as PhotoView);+ setAlbum(null);+ setAlbumsPage(false);+ setSharedPage(false);+ } else if (kind === "album") {+ const a = albums.find(([x]) => x.id === id)?.[0];+ if (!a) return;+ setAlbum(a);+ setAlbumsPage(false);+ setSharedPage(false);+ } else if (kind === "page" && id === "albums") {+ setAlbumsPage(true);+ setSharedPage(false);+ setFolderPage(null);+ } else if (kind === "page" && id === "shared") {+ setSharedPage(true);+ setAlbumsPage(false);+ }+ };+ const placeNow = sharedPage ? "page:shared" : albumsPage ? "page:albums" : album ? `album:${album.id}` : `view:${view}`;+ const places = [+ ...VIEWS.map((v) => ({ value: `view:${v.key}`, label: v.label })),+ { value: "page:albums", label: "Albums" },+ ...albums.filter(([a]) => !a.folder && !a.id.startsWith("new:")).map(([a]) => ({ value: `album:${a.id}`, label: `\u2003${a.name}` })),+ ...MEDIA.filter((m) => (counts[m.key] ?? 0) > 0 || (!album && !albumsPage && view === m.key)).map((v) => ({ value: `view:${v.key}`, label: v.label })),+ ...UTILITIES.map((v) => ({ value: `view:${v.key}`, label: v.label })),+ { value: "page:shared", label: "Shared Albums" },+ ];+return (<div className={`px${dropping ? " is-dropping" : ""}`} data-drop-label={album ? `Add to ${album.name}` : "Add to Library"}>+ <div className="px-compact">+ <Picker label="Show" value={placeNow} options={places} onChange={goTo} />+ </div><aside className="px-side" aria-label="Photos"><p className="side-heading px-side-heading">Photos</p>{VIEWS.map(source)}@@ -2406,8 +2699,8 @@ export function PhotosView() {</div></header>{here.length === 0 ? (- <EmptyState className="px-empty">- {folder ? "This folder is empty. Make an album in it with +." : "No albums yet. Make one with +, then add photos to it from their menu or by dragging them onto it."}+ <EmptyState className="px-empty" icon={folder ? <FolderIcon size={28} strokeWidth={1.6} /> : <AlbumGlyph />}>+ {folder ? "Make an album in this folder with +." : "Make an album with +, then drag photos onto it."}</EmptyState>) : (<div className="px-cards" role="list">@@ -2553,10 +2846,10 @@ export function PhotosView() {)}{jumping && <JumpTo months={monthCovers} at={jumping} current={here ?? monthCovers[0]?.label ?? null} onPick={goToMonth} onClose={() => setJumping(null)} />}<div className="toolbar-group" role="group" aria-label="Zoom">- <button className="tool px-cap" aria-label="Zoom Out" title="Zoom Out (Ctrl −)" disabled={zoom === 0} onClick={() => setZoom((z) => Math.max(0, z - 1))}>+ <button className="tool px-cap" aria-label="Zoom Out" title="Zoom Out (Ctrl −)" disabled={zoom === 0} onClick={() => zoomBy(-1)}><Minus size={15} strokeWidth={2.2} aria-hidden="true" /></button>- <button className="tool px-cap" aria-label="Zoom In" title="Zoom In (Ctrl +)" disabled={zoom === ACROSS.length - 1} onClick={() => setZoom((z) => Math.min(ACROSS.length - 1, z + 1))}>+ <button className="tool px-cap" aria-label="Zoom In" title="Zoom In (Ctrl +)" disabled={zoom === ACROSS.length - 1} onClick={() => zoomBy(1)}><Plus size={15} strokeWidth={2.2} aria-hidden="true" /></button></div>@@ -2592,16 +2885,30 @@ export function PhotosView() {<Arriving service="photos" what="photos" className="px-empty" />)}{photos && photos.length === 0 && !(arriving && !drawn.query) && (- <EmptyState className="px-empty">+ // One line, saying what the place is for, with its own symbol from the sidebar.+ <EmptyState+ className="px-empty"+ icon={(() => {+ const Icon = drawn.query ? null : drawn.album ? null : [...VIEWS, ...MEDIA, ...UTILITIES].find((v) => v.key === drawn.view)?.Icon;+ return drawn.album ? <AlbumGlyph /> : Icon ? <Icon size={28} strokeWidth={1.6} /> : undefined;+ })()}+ >{drawn.query? `No photos match “${drawn.query}”. Search finds names, titles, captions, keywords, years and months.`- : album- ? "This album is empty. Photos added to it on any device show here."- : view === "recentlyDeleted"- ? "Nothing deleted. Photos you delete stay here for 30 days."- : view === "favorites"- ? "Mark a photo with the heart and it shows here."- : "No photos here yet."}+ : drawn.album+ ? "Photos you add to this album show here."+ : ({+ library: "Your photos and videos show here.",+ recents: "Photos you add show here first.",+ favorites: "Click the heart on a photo to keep it here.",+ videos: "Your videos show here.",+ portrait: "Your Portrait photos show here.",+ panoramas: "Your panoramas show here.",+ screenshots: "Your screenshots show here.",+ rated: "Photos you give stars to show here.",+ hidden: "Photos you hide wait here, out of your library.",+ recentlyDeleted: "Photos you delete stay here for 30 days.",+ } as Partial<Record<PhotoView, string>>)[drawn.view] ?? "Your photos show here."}</EmptyState>)}@@ -2609,8 +2916,14 @@ export function PhotosView() {className="px-scroll"ref={scroller}onScroll={onScroll}+ onPointerDown={sweepStart}onClick={(e) => {- // A click on the space between photos lets the selection go, as in Photos.+ // A click on the space between photos lets the selection go, as in Photos — not the+ // click that ends a sweep.+ if (swept.current) {+ swept.current = false;+ return;+ }if (!(e.target as HTMLElement).closest(".px-tile")) setChosen(new Set());}} data-fit={fit || undefined} style={{ "--across": across } as React.CSSProperties}>{waiting && (@@ -2627,22 +2940,25 @@ export function PhotosView() {<Monthkey={`${k}/${m.label}`}label={m.label}+ month={m.month}items={m.items}chosen={chosen}anchor={anchor.current}deleted={drawn.view === "recentlyDeleted" && !drawn.album}eager={k < 3}+ across={across}fit={fit}cell={cell}act={act}/>))}{tally && <p className="px-tally">{tally}</p>}+ <div className="px-sweep" ref={sweepBox} aria-hidden="true" hidden /></div>{shown && (<div- className={`px-viewer${fullscreen ? " is-full" : ""}${fullscreen && thumbs ? " has-thumbs" : ""}`}+ className={`px-viewer${fullscreen ? " is-full" : ""}${fullscreen && thumbs ? " has-thumbs" : ""}${info ? " has-info" : ""}`}ref={viewer}role="dialog"aria-label={shown.filename ?? "Photo"}@@ -3028,10 +3344,10 @@ export function PhotosView() {<Filmstrip photos={photos} at={open} onPick={(i) => step(i - open)} />)}{info && (- <dl className="px-info">- {/* As in Photos' Info: the caption first, typed in place, and kept on every- device; Return or leaving the field saves it, Escape puts it back. */}- <dd className="px-caption-row" onBlur={(e) => wordsLeft(shown, e)}>+ <aside className="px-info" aria-label="Info">+ {/* As in Photos' Info: the title and caption first, typed in place, and kept on+ every device; Return or leaving the field saves them, Escape puts them back. */}+ <div className="px-caption-row" onBlur={(e) => wordsLeft(shown, e)}><inputkey={`t${shown.id}`}ref={titleField}@@ -3057,101 +3373,107 @@ export function PhotosView() {onFocus={(e) => grow(e.currentTarget)}onKeyDown={(e) => wordKeys(e, shown.caption)}/>- </dd>- {/* Stars, as Info sets them: a click gives that many; the same again takes them away. */}- <dt>Rating</dt>- <dd className="px-rating" role="radiogroup" aria-label="Rating">- {[1, 2, 3, 4, 5].map((n) => (- <button- key={n}- role="radio"- aria-checked={(shown.rating ?? 0) === n}- aria-label={`${n} ${n === 1 ? "star" : "stars"}`}- className={`px-star${(shown.rating ?? 0) >= n ? " is-on" : ""}`}- disabled={view === "recentlyDeleted"}- onClick={() => void rate(shown, (shown.rating ?? 0) === n ? 0 : n)}- >- <Star size={15} fill={(shown.rating ?? 0) >= n ? "currentColor" : "none"} strokeWidth={1.8} />- </button>- ))}- </dd>- <dt>Name</dt>- <dd>{shown.filename ?? "—"}</dd>- <dt>Taken</dt>- <dd className="px-taken">+ </div>+ {/* When, large, with Adjust beside it, as Photos' Info leads with the date. */}+ <div className="px-info-when">+ <div>+ <strong>{new Date(shown.takenAt * 1000).toLocaleDateString(undefined, { dateStyle: "full" })}</strong>+ <span>{new Date(shown.takenAt * 1000).toLocaleTimeString(undefined, { timeStyle: "short" })}</span>+ </div>{view !== "recentlyDeleted" && (<button className="px-link px-adjust" onClick={() => setAdjusting(shown)}>Adjust</button>)}- {new Date(shown.takenAt * 1000).toLocaleDateString(undefined, { dateStyle: "full" })} at{" "}- {new Date(shown.takenAt * 1000).toLocaleTimeString(undefined, { timeStyle: "short" })}- </dd>- <dt>Kind</dt>- <dd>- {shown.kind === "video" ? `Video${shown.duration ? `, ${clock(shown.duration)}` : ""}` : shown.kind === "live" ? "Live Photo" : "Photo"}- </dd>- <dt>Dimensions</dt>- <dd>{shown.width.toLocaleString()} × {shown.height.toLocaleString()}</dd>- {shown.size ? (- <>- <dt>File size</dt>- <dd>{shown.size >= 1024 * 1024 ? `${(shown.size / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(shown.size / 1024))} KB`}</dd>- </>- ) : null}- {shown.latitude != null && shown.longitude != null && (- <>- <dt>Place</dt>- <dd className="px-place">- <span>{degrees(shown.latitude, "N", "S")}, {degrees(shown.longitude, "E", "W")}</span>- <button className="px-link" onClick={() => void api.photoOpenMap(shown.id).catch((e) => setError(messageOf(e)))}>- Open in Map- </button>- </dd>- </>- )}- {/* Keywords, as Info keeps them: each its own chip, taken away with ×; a word- typed and Return adds one. */}- <dt>Keywords</dt>- <dd className="px-words-field">- {(shown.keywords ?? []).map((k) => (- <span key={k} className="px-chip">- {k}- {view !== "recentlyDeleted" && (+ </div>+ {/* The file, as Photos sets it: its name, then what it is, in one quiet block. */}+ <div className="px-info-file">+ <strong>{shown.filename ?? "Photo"}</strong>+ <span>+ {shown.kind === "video" ? `Video${shown.duration ? `, ${clock(shown.duration)}` : ""}` : shown.kind === "live" ? "Live Photo" : "Photo"}+ {shown.width && shown.height && shown.kind !== "video" ? `, ${Math.round((shown.width * shown.height) / 1e6)} MP` : ""}+ </span>+ <span>+ {shown.width.toLocaleString()} × {shown.height.toLocaleString()}+ {shown.size ? `, ${shown.size >= 1024 * 1024 ? `${(shown.size / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(shown.size / 1024))} KB`}` : ""}+ </span>+ </div>+ <dl className="px-facts">+ {/* Stars, as Info sets them: a click gives that many; the same again takes them away. */}+ <div className="px-fact">+ <dt>Rating</dt>+ <dd className="px-rating" role="radiogroup" aria-label="Rating">+ {[1, 2, 3, 4, 5].map((n) => (<button- aria-label={`Remove ${k}`}- onClick={() => void keywords(shown, (shown.keywords ?? []).filter((x) => x !== k))}+ key={n}+ role="radio"+ aria-checked={(shown.rating ?? 0) === n}+ aria-label={`${n} ${n === 1 ? "star" : "stars"}`}+ className={`px-star${(shown.rating ?? 0) >= n ? " is-on" : ""}`}+ disabled={view === "recentlyDeleted"}+ onClick={() => void rate(shown, (shown.rating ?? 0) === n ? 0 : n)}>- <X size={10} strokeWidth={3} aria-hidden="true" />+ <Star size={15} fill={(shown.rating ?? 0) >= n ? "currentColor" : "none"} strokeWidth={1.8} /></button>- )}- </span>- ))}- {view !== "recentlyDeleted" && (- <input- key={`k${shown.id}`}- className="px-keyword-field"- aria-label="Add a Keyword"- placeholder="Add a Keyword"- maxLength={100}- onKeyDown={(e) => {- const word = e.currentTarget.value.trim();- if ((e.key === "Enter" || e.key === ",") && word) {- e.preventDefault();- e.currentTarget.value = "";- if (!(shown.keywords ?? []).some((x) => x.toLowerCase() === word.toLowerCase())) {- void keywords(shown, [...(shown.keywords ?? []), word]);- }- } else if (e.key === "Escape") {- e.currentTarget.value = "";- e.currentTarget.blur();- e.stopPropagation();- }- }}- />+ ))}+ </dd>+ </div>+ {shown.latitude != null && shown.longitude != null && (+ <div className="px-fact">+ <dt>Place</dt>+ <dd className="px-place">+ <span>{degrees(shown.latitude, "N", "S")}, {degrees(shown.longitude, "E", "W")}</span>+ <button className="px-link" onClick={() => void api.photoOpenMap(shown.id).catch((e) => setError(messageOf(e)))}>+ Open in Map+ </button>+ </dd>+ </div>)}- </dd>- </dl>+ {/* Keywords, as Info keeps them: each its own chip, taken away with ×; a word+ typed and Return adds one. */}+ <div className="px-fact">+ <dt>Keywords</dt>+ <dd className="px-words-field">+ {(shown.keywords ?? []).map((k) => (+ <span key={k} className="px-chip">+ {k}+ {view !== "recentlyDeleted" && (+ <button+ aria-label={`Remove ${k}`}+ onClick={() => void keywords(shown, (shown.keywords ?? []).filter((x) => x !== k))}+ >+ <X size={10} strokeWidth={3} aria-hidden="true" />+ </button>+ )}+ </span>+ ))}+ {view !== "recentlyDeleted" && (+ <input+ key={`k${shown.id}`}+ className="px-keyword-field"+ aria-label="Add a Keyword"+ placeholder="Add a Keyword"+ maxLength={100}+ onKeyDown={(e) => {+ const word = e.currentTarget.value.trim();+ if ((e.key === "Enter" || e.key === ",") && word) {+ e.preventDefault();+ e.currentTarget.value = "";+ if (!(shown.keywords ?? []).some((x) => x.toLowerCase() === word.toLowerCase())) {+ void keywords(shown, [...(shown.keywords ?? []), word]);+ }+ } else if (e.key === "Escape") {+ e.currentTarget.value = "";+ e.currentTarget.blur();+ e.stopPropagation();+ }+ }}+ />+ )}+ </dd>+ </div>+ </dl>+ </aside>)}</div>)}diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsxindex 71f7a24..b1e2e7a 100644--- a/src/screens/RemindersView.tsx+++ b/src/screens/RemindersView.tsx@@ -1,5 +1,5 @@import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";-import { foldAway } from "../lib/fade";+import { fadeIn, fadeOut } from "../lib/fade";import { useActiveRef } from "../lib/screen";import { listen } from "@tauri-apps/api/event";import { usePending } from "../lib/pending";@@ -12,7 +12,7 @@ import { SearchField } from "../components/SearchField";import { PaneTitle } from "../components/PaneTitle";import { Portal } from "../components/Portal";import { TimeField } from "../components/TimeField";-import { ChevronLeft } from "lucide-react";+import { ChevronLeft, ListFilter, X } from "lucide-react";import {api,MOST_AT_ONCE,@@ -23,6 +23,10 @@ import {type ReminderSection,type ReminderCounts,type SmartList,+ remindersApi,+ type ReminderDetail,+ type ReminderSmartList,+ type TagCount,} from "../lib/ipc";import { Arriving } from "../components/EmptyState";import { useArriving, useSync } from "../lib/sync";@@ -193,8 +197,34 @@ const asShown = (r: Reminder): Reminder =>r.allDay && r.dueAt !== null ? { ...r, dueAt: dayToLocal(r.dueAt) } : r;+/**+ * Tags, links, early alerts and sections can be changed from here once Apple's side of those+ * writes is switched on. Mirrors `REMINDER_DETAIL_WRITES` in+ * crates/quince-icloud/src/reminders_details.rs: turn both on together.+ */+export const REMINDER_DETAIL_WRITES = false;++/** Apple's early-alert units, by its numbering. */+const ALERT_UNITS = ["minute", "hour", "day", "week", "month"] as const;+/** "30 minutes early", "1 day early". */+function earlyText(count: number, unit: number): string {+ const word = ALERT_UNITS[unit] ?? "minute";+ return `${count} ${word}${count === 1 ? "" : "s"} early`;+}+/** What the phone's Early Reminder menu offers, as [count, unit]. */+const EARLY_CHOICES: [number, number][] = [+ [5, 0], [15, 0], [30, 0], [1, 1], [2, 1], [1, 2], [2, 2], [1, 3], [1, 4],+];++/** A smart list's own colour, or Apple's grey for one that has none. */+const smartColour = (s: ReminderSmartList) =>+ s.colour && /^#[0-9a-f]{6}$/i.test(s.colour) ? s.colour : "var(--sys-gray)";+type Selection =- { type: "smart"; kind: SmartList } | { type: "list"; guid: string };+ | { type: "smart"; kind: SmartList }+ | { type: "list"; guid: string }+ | { type: "tag"; name: string }+ | { type: "custom"; guid: string };export function RemindersView() {const [lists, setLists] = useState<ReminderList[]>([]);@@ -240,6 +270,11 @@ export function RemindersView() {setOpenGuid(r.id);});const [items, setItems] = useState<Reminder[]>([]);+ // Info belongs to the view it was opened in; another view starts with it closed — unless+ // the search across everything is opening this very reminder.+ useEffect(() => {+ if (!revealing.current) setOpenGuid(null);+ }, [picked]);useEffect(() => {const id = revealing.current;if (!id || !items.some((r) => r.guid === id)) return;@@ -268,6 +303,17 @@ export function RemindersView() {const [counts, setCounts] = useState<ReminderCounts | null>(null);/** The headings inside the list that is open, when a real list is open. */const [listSections, setListSections] = useState<ReminderSection[]>([]);+ /** Every tag on the account, with how many reminders still to do carry each. */+ const [tags, setTags] = useState<TagCount[]>([]);+ /** Each reminder's tags, by its id — for the chips on its row. */+ const [tagsOf, setTagsOf] = useState<Map<string, string[]>>(() => new Map());+ /** Smart lists made by hand on the phone or Mac, and how many each holds now. */+ const [customLists, setCustomLists] = useState<ReminderSmartList[]>([]);+ const [customCounts, setCustomCounts] = useState<Map<string, number>>(() => new Map());+ /** Rules of the open smart list this app does not read yet. */+ const [unknownRules, setUnknownRules] = useState<string[]>([]);+ /** The open reminder's tags, link and early alerts. */+ const [detailOf, setDetailOf] = useState<ReminderDetail | null>(null);/** A repeating reminder that was just ticked forward, and where it landed. */const [moved, setMoved] = useState<{ guid: string; text: string } | null>(null,@@ -275,6 +321,11 @@ export function RemindersView() {const inList = selection.type === "list";const listGuid = inList ? selection.guid : null;+ /** The built-in view open, if one is. */+ const smartKind = selection.type === "smart" ? selection.kind : null;+ /** A tag or a hand-made smart list: views gathered from every list, with nowhere to add. */+ const gathered = selection.type === "tag" || selection.type === "custom";+ const openCustom = selection.type === "custom" ? (customLists.find((x) => x.guid === selection.guid) ?? null) : null;const readLists = useCallback(async () => {const [found, tally, folders] = await Promise.all([@@ -287,8 +338,32 @@ export function RemindersView() {setGroups(Array.isArray(folders) ? folders : []);setCounts(tally);setLoaded(true);+ // Tags and smart lists after: an older library without them is still a working one.+ void readExtras().catch(() => {});}, []);+ /** Tags with each one's reminders, and custom smart lists with what each holds. */+ const readExtras = async () => {+ const [allTags, smart] = await Promise.all([+ remindersApi.tags().catch(() => [] as TagCount[]),+ remindersApi.smartLists().catch(() => [] as ReminderSmartList[]),+ ]);+ const named = (Array.isArray(allTags) ? allTags : []).filter((t) => t.name);+ const custom = (Array.isArray(smart) ? smart : []).filter((x) => x.kind === "custom");+ const [tagged, held] = await Promise.all([+ Promise.all(named.map((t) => remindersApi.tagged(t.name).catch(() => [] as Reminder[]))),+ Promise.all(custom.map((x) => remindersApi.inSmartList(x.guid).then((c) => c.reminders.length).catch(() => 0))),+ ]);+ const byReminder = new Map<string, string[]>();+ named.forEach((t, i) => {+ for (const r of tagged[i] ?? []) byReminder.set(r.guid, [...(byReminder.get(r.guid) ?? []), t.name]);+ });+ setTags(named);+ setTagsOf(byReminder);+ setCustomLists(custom);+ setCustomCounts(new Map(custom.map((x, i) => [x.guid, held[i] ?? 0])));+ };+// A list's headings are read with its reminders (readItems), so they arrive together./** What is typed in the search field. While it holds anything, the pane is the results. */@@ -309,12 +384,20 @@ export function RemindersView() {const sel = picked;const seq = ++reads.current;// Search reaches every list, as Apple's does, whatever is open in the sidebar.+ let unknown: string[] = [];const [found, sections] = await Promise.all([searching? api.remindersSearch(query): sel.type === "smart"? api.remindersSmart(sel.kind, endOfToday())- : api.remindersIn(sel.guid, showDone),+ : sel.type === "tag"+ ? remindersApi.tagged(sel.name)+ : sel.type === "custom"+ ? remindersApi.inSmartList(sel.guid).then((c) => {+ unknown = Array.isArray(c.unknown) ? c.unknown : [];+ return c.reminders;+ })+ : api.remindersIn(sel.guid, showDone),sel.type === "list"? api.reminderSections(sel.guid).catch(() => [] as ReminderSection[]): Promise.resolve([] as ReminderSection[]),@@ -325,6 +408,7 @@ export function RemindersView() {setShown(sel);setItems(fresh);setListSections(Array.isArray(sections) ? sections : []);+ setUnknownRules(unknown);return fresh;}, [picked, showDone, query, searching, over]);@@ -450,17 +534,32 @@ export function RemindersView() {};const depart = (guid: string) => {stay(guid);- // A moment to see the tick land (and undo a mistaken one), then the row folds away: its- // height closes as it fades, so the ones below glide up instead of jumping.+ // A moment to see the tick land (and undo a mistaken one), then the row fades and goes.+ // Opacity only, drawn by the page frame by frame (lib/fade): a height fold, or anything+ // handed to the compositor, flickered under WebKitGTK on Hyprland.departure.current.set(guid, [window.setTimeout(() => {setLeaving((was) => new Set(was).add(guid));const row = document.querySelector<HTMLElement>(`.rx-row[data-guid="${CSS.escape(guid)}"]`);- const gone = () => setDeparted((was) => new Set(was).add(guid));- // Folded by the page, frame by frame (lib/fade): handed to the compositor, as the Web- // Animations API hands it, an animation flickered on his screen.+ // A row ticked from the keyboard hands the keys on to the one below it (or above),+ // rather than dropping them on the page as it goes.+ const keys = row?.contains(document.activeElement) ?? false;+ const rowsNow = [...document.querySelectorAll<HTMLElement>(".rx-rows .rx-row")];+ const at = row ? rowsNow.indexOf(row) : -1;+ const heir = keys ? (rowsNow.slice(at + 1).find((el) => !el.classList.contains("is-leaving")) ?? rowsNow[at - 1]) : null;+ const heirGuid = heir?.dataset.guid ?? null;+ const gone = () => {+ setDeparted((was) => new Set(was).add(guid));+ if (heirGuid) {+ requestAnimationFrame(() => {+ const active = document.activeElement;+ if (active && active !== document.body && document.contains(active)) return;+ document.querySelector<HTMLElement>(`.rx-row[data-guid="${CSS.escape(heirGuid)}"]`)?.focus();+ });+ }+ };if (!row) gone();- else foldAway(row, gone);+ else fadeOut(row, gone, 160);}, 600),]);};@@ -593,6 +692,203 @@ export function RemindersView() {);};+ /** The open reminder's tags, link and early alerts, read again. */+ const readDetail = useCallback(async (guid: string | null) => {+ if (!guid || guid.startsWith(STAND_IN)) {+ setDetailOf(null);+ return;+ }+ try {+ const found = await remindersApi.detail(guid);+ setDetailOf((was) => (found && found.guid === guid ? found : was?.guid === guid ? was : null));+ } catch {+ // An older library without details: the panel shows what the reminder itself holds.+ setDetailOf(null);+ }+ }, []);+ useEffect(() => {+ void readDetail(openGuid);+ }, [openGuid, readDetail, revision, outbox.tick]);+ // Tags and smart lists hold what is still to do, so a change sent or ticked moves them.+ useEffect(() => {+ void readExtras().catch(() => {});+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [outbox.tick]);++ const openTag = (name: string) => {+ setQuery("");+ setSelection({ type: "tag", name });+ setDetail(true);+ };++ /**+ * A change to what sits beside a reminder: shown at once in its row and its info, sent to+ * Apple, then the details read again — Apple's copy on success, the old one on a refusal.+ */+ const detailWrite = async (r: Reminder, run: () => Promise<void>, predict?: (d: ReminderDetail) => ReminderDetail) => {+ if (!REMINDER_DETAIL_WRITES || r.guid.startsWith(STAND_IN)) return;+ if (predict) {+ setDetailOf((d) => (d && d.guid === r.guid ? predict(d) : d));+ setTagsOf((m) => {+ const base = { guid: r.guid, tags: m.get(r.guid) ?? [], url: null, earlyAlerts: [], otherAttachments: 0 };+ const next = new Map(m);+ next.set(r.guid, predict(base).tags);+ return next;+ });+ }+ await write(r, run);+ await Promise.all([readDetail(openGuid), readExtras().catch(() => {})]);+ };+ const tagAdd = (r: Reminder, raw: string) => {+ const name = raw.trim().replace(/^#+/, "").replace(/\s+/g, "");+ if (!name) return Promise.resolve();+ return detailWrite(r, () => remindersApi.tagAdd(r.guid, name), (d) =>+ d.tags.some((t) => t.toLowerCase() === name.toLowerCase()) ? d : { ...d, tags: [...d.tags, name] },+ );+ };+ const tagRemove = (r: Reminder, name: string) =>+ detailWrite(r, () => remindersApi.tagRemove(r.guid, name), (d) => ({ ...d, tags: d.tags.filter((t) => t !== name) }));+ const setUrl = (r: Reminder, url: string | null) =>+ detailWrite(r, () => remindersApi.urlSet(r.guid, url), (d) => ({ ...d, url }));+ const setEarly = (r: Reminder, alert: [number, number] | null) =>+ detailWrite(r, () => remindersApi.earlyAlertSet(r.guid, alert?.[0] ?? null, alert?.[1] ?? null), (d) => ({+ ...d,+ earlyAlerts: alert ? [{ id: "pending", count: alert[0], unit: alert[1] }] : [],+ }));++ /** The section of its list a reminder sits in, when that section is still there. */+ const sectionOf = (r: Reminder) =>+ r.sectionGuid && listSections.some((x) => x.guid === r.sectionGuid) ? r.sectionGuid : null;+ const moveToSection = (r: Reminder, section: string | null) =>+ !REMINDER_DETAIL_WRITES || section === sectionOf(r)+ ? Promise.resolve(null)+ : write(r, () => remindersApi.sectionMove(r.listGuid, r.guid, section), patch(r.guid, { sectionGuid: section }));+ /** A new section, named in place at the foot of the list. */+ const [namingSection, setNamingSection] = useState<string | null>(null);+ const createSection = async (title: string) => {+ if (!REMINDER_DETAIL_WRITES || !listGuid || !title.trim()) return;+ const temp: ReminderSection = { guid: `${STAND_IN}section`, listGuid, title: title.trim(), createdAt: null };+ setListSections((was) => [...was, temp]);+ try {+ await remindersApi.sectionCreate(listGuid, title.trim());+ } catch (e) {+ setError(messageOf(e));+ }+ await readItems().catch(() => {});+ };+ const renameSection = async (section: ReminderSection, title: string) => {+ if (!REMINDER_DETAIL_WRITES || !title.trim() || title.trim() === section.title) return;+ setListSections((was) => was.map((x) => (x.guid === section.guid ? { ...x, title: title.trim() } : x)));+ try {+ await remindersApi.sectionRename(section.guid, title.trim());+ } catch (e) {+ setError(messageOf(e));+ }+ await readItems().catch(() => {});+ };++ /** Deleting asks first: there is no bringing a reminder back from here. */+ const askRemove = async (r: Reminder) => {+ const subtasks = items.filter((x) => x.parentGuid === r.guid).length;+ const sure = await confirm({+ title: `Delete \u201c${r.title || "New Reminder"}\u201d?`,+ body: subtasks+ ? `Its ${subtasks === 1 ? "subtask goes" : `${subtasks} subtasks go`} with it, on all your devices.`+ : "It goes from all your devices.",+ action: "Delete",+ danger: true,+ symbol: "trash",+ });+ if (!sure) return;+ if (openGuid === r.guid) setOpenGuid(null);+ // The focus moves on to the row below, or above, so the keys carry on from there.+ const rowsNow = [...document.querySelectorAll<HTMLElement>(".rx-rows .rx-row")];+ const at = rowsNow.findIndex((el) => el.dataset.guid === r.guid);+ const neighbour = rowsNow[at + 1] ?? rowsNow[at - 1];+ const next = neighbour?.dataset.guid ?? null;+ // The row goes at once (remove shows it before Apple answers), and the keys with it.+ void remove(r);+ if (next) {+ requestAnimationFrame(() =>+ document.querySelector<HTMLElement>(`.rx-row[data-guid="${CSS.escape(next)}"]`)?.focus(),+ );+ }+ };++ /**+ * The keys Reminders on the Mac answers, with Ctrl for Command: Ctrl+N a new reminder,+ * Ctrl+Shift+N a new list, Ctrl+F the search, Ctrl+I the selected reminder's info. On a row:+ * Up and Down move, Space ticks it, Return edits it, Delete deletes it (asking first).+ */+ const live = useActiveRef();+ const searchRef = useRef<HTMLInputElement>(null);+ /** Ctrl+N from a view with nowhere to add: the default list opens, and its field takes it. */+ const [wantAdd, setWantAdd] = useState(0);+ useEffect(() => {+ if (!wantAdd) return;+ const field = document.querySelector<HTMLInputElement>(".rx-add input");+ if (!field) return;+ field.focus();+ field.scrollIntoView({ block: "nearest" });+ setWantAdd(0);+ }, [wantAdd, selection, items]);+ const keys = useRef<(e: KeyboardEvent) => void>(() => {});+ keys.current = (e: KeyboardEvent) => {+ if (!live.current || e.defaultPrevented) return;+ // A menu, a picker's list or a sheet over the screen has the keys to itself.+ if (document.querySelector('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"]')) return;+ const target = e.target as HTMLElement | null;+ const typing = !!target?.closest?.("input, textarea, select, [contenteditable]");+ const command = (e.ctrlKey || e.metaKey) && !e.altKey;+ const k = e.key.toLowerCase();+ if (command && k === "n") {+ e.preventDefault();+ if (e.shiftKey) {+ setDetail(false);+ setAddingList(true);+ document.querySelector<HTMLInputElement>(".rx-new-list input")?.focus();+ return;+ }+ if (!targetListGuid) return;+ setDetail(true);+ if (searching) setQuery("");+ if (!canAdd) setSelection({ type: "list", guid: targetListGuid });+ setWantAdd((n) => n + 1);+ return;+ }+ if (command && !e.shiftKey && k === "f") {+ e.preventDefault();+ searchRef.current?.focus();+ searchRef.current?.select();+ return;+ }+ if (command && !e.shiftKey && k === "i") {+ e.preventDefault();+ const row = (document.activeElement as HTMLElement | null)?.closest?.<HTMLElement>(".rx-row");+ const guid = row?.dataset.guid ?? openGuid;+ if (!guid) return;+ setOpenGuid(openGuid === guid ? null : guid);+ // The row keeps the keys, so Ctrl+I again closes what it opened.+ if (row && openGuid === guid) row.focus();+ return;+ }+ if (typing || command || e.altKey) return;+ // Arrows from nowhere in particular start at the first (or last) reminder.+ if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !target?.closest?.(".rx-row, .rx-side, button, [role]")) {+ const rows = [...document.querySelectorAll<HTMLElement>(".rx-rows .rx-row")];+ const pick = e.key === "ArrowDown" ? rows[0] : rows[rows.length - 1];+ if (pick) {+ e.preventDefault();+ pick.focus();+ }+ }+ };+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => keys.current(e);+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);+/** Drag and drop: what is being dragged, and the row it would land before. */const [dragging, setDragging] = useState<string | null>(null);const [dropBefore, setDropBefore] = useState<string | null>(null);@@ -728,7 +1024,8 @@ export function RemindersView() {// The row is there the moment Return is pressed, and the field is ready for the next.const standIn = `${STAND_IN}${Date.now()}`;setDraft("");- const shownHere = inList || kind === "today" || kind === "scheduled" || kind === "flagged" || kind === "all";+ const tagged = selection.type === "tag" ? selection.name : null;+ const shownHere = inList || tagged !== null || kind === "today" || kind === "scheduled" || kind === "flagged" || kind === "all";if (shownHere) setItems((rows) => [...rows,{@@ -740,7 +1037,12 @@ export function RemindersView() {} as Reminder,]);try {- await api.reminderCreate(targetListGuid, title, implied);+ const made = await api.reminderCreate(targetListGuid, title, implied);+ // Typed into a tag, it carries the tag, as on the phone.+ if (tagged && REMINDER_DETAIL_WRITES && typeof made === "string" && made) {+ await remindersApi.tagAdd(made, tagged).catch((e) => setError(messageOf(e)));+ void readExtras().catch(() => {});+ }await readItems();} catch (err) {setItems((rows) => rows.filter((r) => r.guid !== standIn));@@ -753,8 +1055,11 @@ export function RemindersView() {const heading = inList? (lists.find((l) => l.guid === listGuid)?.title ?? "Reminders")- : (SMART.find((s) => s.kind === (selection as { kind: SmartList }).kind)- ?.title ?? "Reminders");+ : selection.type === "tag"+ ? `#${selection.name}`+ : selection.type === "custom"+ ? (openCustom?.title ?? "Smart List")+ : (SMART.find((s) => s.kind === smartKind)?.title ?? "Reminders");const outstanding = items.filter((r) => !r.completedAt).length;/**@@ -765,10 +1070,10 @@ export function RemindersView() {* dishonest part — a list that quietly stops is worse than one that says where it stopped.*/const heldBack = (() => {- if (items.length < MOST_AT_ONCE || !counts) return 0;+ if (items.length < MOST_AT_ONCE || !counts || gathered) return 0;const total = inList? (counts.lists.find(([guid]) => guid === listGuid)?.[1] ?? 0)- : counts[(selection as { kind: SmartList }).kind];+ : smartKind ? counts[smartKind] : 0;return Math.max(0, total - items.length);})();@@ -831,8 +1136,9 @@ export function RemindersView() {const showListName =!searching &&!inList &&- (selection as { kind: SmartList }).kind !== "all" &&- (selection as { kind: SmartList }).kind !== "flagged";+ !gathered &&+ smartKind !== "all" &&+ smartKind !== "flagged";const sections = useMemo(() => {if (searching) {@@ -874,7 +1180,7 @@ export function RemindersView() {];}- const kind = (selection as { kind: SmartList }).kind;+ const kind = smartKind;const now = new Date();const listOf = (guid: string) => lists.find((l) => l.guid === guid);@@ -975,14 +1281,17 @@ export function RemindersView() {const countOf = (guid: string) => counts?.lists.find(([g]) => g === guid)?.[1] ?? 0;const openList = inList ? (lists.find((l) => l.guid === listGuid) ?? null) : null;- const smartOpen =- selection.type === "smart" ? SMART.find((x) => x.kind === selection.kind) : undefined;+ const smartOpen = smartKind ? SMART.find((x) => x.kind === smartKind) : undefined;/** The colour the open view is drawn in: its list's, or its built-in view's. */const accent = searching? "var(--text)": openList? colourOf(openList)- : (smartOpen?.colour ?? "var(--sys-blue)");+ : openCustom+ ? smartColour(openCustom)+ : selection.type === "tag"+ ? "var(--sys-blue)"+ : (smartOpen?.colour ?? "var(--sys-blue)");/*** The sidebar in Apple's order: a list or group at the top level wherever it was walked,@@ -1090,7 +1399,8 @@ export function RemindersView() {);/** Where a reminder typed at the foot of the view is filed, when that is a choice. */- const addRow = targetListGuid && !searching && (+ const canAdd = !gathered || (selection.type === "tag" && REMINDER_DETAIL_WRITES);+ const addRow = targetListGuid && !searching && canAdd && (<form className="rx-add" onSubmit={add}><span className="rx-tick ghost" aria-hidden="true"><Glyph name="plus" />@@ -1124,6 +1434,7 @@ export function RemindersView() {><aside className="rx-side" aria-label="Reminder lists"><SearchField+ ref={searchRef}className="rx-search"placeholder="Search"aria-label="Search reminders"@@ -1184,9 +1495,60 @@ export function RemindersView() {</div>),)}+ {/* Smart lists made by hand, after the lists, as the Mac shows them: a filter in its+ colour, with what it holds now. */}+ {customLists.map((smart) => {+ const title = smart.title ?? "Smart List";+ return (+ <div className="rx-list-row" key={smart.guid}>+ <button+ className="source-row rx-list rx-smart-row"+ aria-current={picked.type === "custom" && picked.guid === smart.guid}+ onClick={() => {+ setQuery("");+ setSelection({ type: "custom", guid: smart.guid });+ setDetail(true);+ }}+ >+ <span className="rx-badge" style={{ background: smartColour(smart) }}>+ {smart.emblem ? <Glyph name={emblemGlyph(smart.emblem)} /> : <ListFilter aria-hidden="true" strokeWidth={2.25} />}+ </span>+ <span className="source-name rx-list-name">{title}</span>+ <span className="count">{customCounts.get(smart.guid) ?? 0}</span>+ </button>+ </div>+ );+ })}</div>{loaded && lists.length === 0 && !arriving && <p className="side-heading">No lists yet</p>}+ {tags.length > 0 && (+ <>+ <p className="side-heading rx-side-heading">Tags</p>+ <div className="rx-tags" role="group" aria-label="Tags">+ {tags.map((t) => {+ const current = !searching && picked.type === "tag" && picked.name.toLowerCase() === t.name.toLowerCase();+ return (+ <button+ key={t.name}+ className="rx-tag-chip"+ data-tag={t.name}+ aria-current={current}+ aria-label={`#${t.name}, ${t.open} ${t.open === 1 ? "reminder" : "reminders"}`}+ onClick={() => {+ setQuery("");+ setSelection({ type: "tag", name: t.name });+ setDetail(true);+ }}+ >+ #{t.name}+ </button>+ );+ })}+ </div>+ </>+ )}+{addingList ? (<form className="rx-new-list" onSubmit={createList}><input@@ -1236,6 +1598,12 @@ export function RemindersView() {</EmptyState>)}+ {unknownRules.length > 0 && selection.type === "custom" && !searching && (+ <p className="rx-capped" role="status">+ Shows what matches the rules read here. Your iPhone has the full list.+ </p>+ )}+{heldBack > 0 && (<p className="rx-capped" role="status">Showing the first {MOST_AT_ONCE.toLocaleString()} — {heldBack.toLocaleString()} more@@ -1245,14 +1613,40 @@ export function RemindersView() {{sections.map((section) => (<Fragment key={section.key}>- {section.heading && (- <h2- className={`rx-section${section.dated ? " is-quiet" : ""}`}- style={section.colour ? { color: section.colour } : undefined}- >- {section.heading}- </h2>- )}+ {section.heading &&+ (inList && REMINDER_DETAIL_WRITES && namingSection === section.key ? (+ <input+ className="field rx-section-name"+ defaultValue={section.heading}+ autoFocus+ aria-label={`Rename section ${section.heading}`}+ onBlur={(e) => {+ setNamingSection(null);+ const found = listSections.find((x) => x.guid === section.key);+ if (found) void renameSection(found, e.target.value);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "Escape") {+ e.currentTarget.value = section.heading ?? "";+ e.currentTarget.blur();+ }+ }}+ />+ ) : (+ <h2+ className={`rx-section${section.dated ? " is-quiet" : ""}${inList ? " is-list-section" : ""}`}+ style={section.colour ? { color: section.colour } : undefined}+ data-section={inList ? section.key : undefined}+ onDoubleClick={+ inList && REMINDER_DETAIL_WRITES && !section.key.startsWith(STAND_IN)+ ? () => setNamingSection(section.key)+ : undefined+ }+ >+ {section.heading}+ </h2>+ ))}<ul className="rx-rows">{section.rows.map(({ reminder, depth }) => {const due =@@ -1262,6 +1656,8 @@ export function RemindersView() {const justMoved = moved?.guid === reminder.guid ? moved.text : null;const home = lists.find((l) => l.guid === reminder.listGuid);const mark = priorityMark(reminder.priority);+ const rowTags =+ isOpen && detailOf?.guid === reminder.guid ? detailOf.tags : (tagsOf.get(reminder.guid) ?? []);return (<likey={reminder.guid}@@ -1280,10 +1676,13 @@ export function RemindersView() {}}onDragEnd={() => { setDragging(null); setDropBefore(null); }}// The row itself takes the keyboard, as on icloud.com and the Mac: arrows go- // from row to row, Space ticks it, Return edits its title. Delete is left out:- // a reminder deleted here cannot be brought back.+ // from row to row, Space ticks it, Return edits its title, Delete deletes it+ // once confirmed — a reminder deleted here cannot be brought back.tabIndex={-1}data-guid={reminder.guid}+ // The list's colour for everything on the row drawn in it: the circle, the+ // priority marks.+ style={{ "--tick": colourOf(home) } as React.CSSProperties}onKeyDown={(e) => {if (e.target !== e.currentTarget) return;const rows = [...document.querySelectorAll<HTMLElement>(".rx-rows .rx-row")];@@ -1300,7 +1699,12 @@ export function RemindersView() {void toggle(reminder);} else if (e.key === "Enter") {e.preventDefault();- e.currentTarget.querySelector<HTMLInputElement>(".rx-title")?.focus();+ const title = e.currentTarget.querySelector<HTMLInputElement>(".rx-title");+ title?.focus();+ title?.select();+ } else if (e.key === "Delete" || e.key === "Backspace") {+ e.preventDefault();+ void askRemove(reminder);}}}// Right-click, as on the Mac: what can be done to this reminder, in one menu.@@ -1338,15 +1742,18 @@ export function RemindersView() {aria-checked={Boolean(reminder.completedAt) || settling.has(reminder.guid)}aria-label={reminder.title}style={{ "--tick": colourOf(home) } as React.CSSProperties}- // The fill springs in on the press itself, and only then: kept as state,- // it sprang in again every time Reminders came back into view.+ // The fill fades in on the press itself, and only then (kept as state, it came+ // in again every time Reminders came back into view): opacity alone, on a+ // twenty-pixel circle, drawn by the page (lib/fade) — never the compositor.onClick={(e) => {- const tick = e.currentTarget;- tick.classList.add("is-pressed");- window.setTimeout(() => tick.classList.remove("is-pressed"), 300);+ const fill = e.currentTarget.querySelector<HTMLElement>(".rx-tick-fill");+ const filling = !reminder.completedAt;toggle(reminder);+ if (filling) requestAnimationFrame(() => fadeIn(fill, { from: 0.25, duration: 140 }));}}- />+ >+ <span className="rx-tick-fill" aria-hidden="true" />+ </button><div className="rx-text"><div className="rx-title-row">@@ -1404,7 +1811,7 @@ export function RemindersView() {<span className="rx-notes">{reminder.notes}</span>)}<Waiting shown={outbox.waiting.has(reminder.guid)} />- {(due || repeat || justMoved || (showListName && home)) && (+ {(due || repeat || justMoved || (showListName && home) || rowTags.length > 0) && (<span className="rx-meta">{justMoved ? (<span className="rx-moved" role="status">@@ -1426,14 +1833,48 @@ export function RemindersView() {<span className="visually-hidden">{repeat}</span></span>)}+ {rowTags.map((name) => (+ <button+ key={name}+ type="button"+ className="rx-tag"+ tabIndex={-1}+ aria-label={`Show reminders tagged ${name}`}+ onClick={() => openTag(name)}+ >+ #{name}+ </button>+ ))}</>)}</span>)}{isOpen && (- <div className="rx-detail">-<DueField reminder={reminder} onChange={(day, time) => void setDue(reminder, day, time)} />+ <div className="rx-detail" role="group" aria-label={`Info for ${reminder.title}`}>+ <label className="rx-field rx-field-notes">+ <span>Notes</span>+ <textarea+ className="field"+ defaultValue={reminder.notes ?? ""}+ key={`n${reminder.guid}`}+ rows={2}+ placeholder="Add Note"+ onBlur={(e) => void setNotes(reminder, e.target.value)}+ />+ </label>+ <UrlField+ reminder={reminder}+ url={detailOf?.guid === reminder.guid ? detailOf.url : null}+ onSave={(url) => void setUrl(reminder, url)}+ />+ <div className="rx-detail-rule" aria-hidden="true" />+ <DueField reminder={reminder} onChange={(day, time) => void setDue(reminder, day, time)} />+ <EarlyField+ reminder={reminder}+ alerts={detailOf?.guid === reminder.guid ? detailOf.earlyAlerts : []}+ onChange={(alert) => void setEarly(reminder, alert)}+ /><div className="rx-field"><span>Repeat</span><Picker@@ -1454,14 +1895,21 @@ export function RemindersView() {/></div>{reminder.dueAt === null && (- <p className="rx-hint">Give this a date before asking it to repeat.</p>+ <p className="rx-hint">Add a date to repeat it.</p>)}+ <div className="rx-detail-rule" aria-hidden="true" />+ <TagsField+ reminder={reminder}+ tags={rowTags}+ onOpen={openTag}+ onAdd={(name) => void tagAdd(reminder, name)}+ onRemove={(name) => void tagRemove(reminder, name)}+ /><div className="rx-field"><span>Priority</span><Pickerlabel={`Priority for ${reminder.title}`}value={String(reminder.priority)}-onChange={(v) => void setPriority(reminder, Number(v))}options={PRIORITIES.map((p) => ({value: String(p.value),@@ -1474,20 +1922,30 @@ export function RemindersView() {<Pickerlabel={`List for ${reminder.title}`}value={reminder.listGuid}-onChange={(guid) => void moveToList(reminder, guid)}options={lists.map((l) => ({ value: l.guid, label: l.title }))}/></div>- <label className="rx-field">- <span>Notes</span>- <textarea- className="field"- defaultValue={reminder.notes ?? ""}- rows={2}- onBlur={(e) => void setNotes(reminder, e.target.value)}- />- </label>+ {inList && listSections.length > 0 && (+ <div className="rx-field">+ <span>Section</span>+ {REMINDER_DETAIL_WRITES ? (+ <Picker+ label={`Section for ${reminder.title}`}+ value={sectionOf(reminder) ?? ""}+ onChange={(guid) => void moveToSection(reminder, guid || null)}+ options={[+ { value: "", label: "None" },+ ...listSections.map((x) => ({ value: x.guid, label: x.title })),+ ]}+ />+ ) : (+ <span className="rx-value">+ {listSections.find((x) => x.guid === sectionOf(reminder))?.title ?? "None"}+ </span>+ )}+ </div>+ )}<div className="rx-detail-actions">{depth > 0 ? (<button@@ -1508,7 +1966,7 @@ export function RemindersView() {className="link danger"aria-label={`Delete ${reminder.title}`}- onClick={() => remove(reminder)}+ onClick={() => void askRemove(reminder)}>Delete</button>@@ -1549,13 +2007,39 @@ export function RemindersView() {{addRow}+ {inList && REMINDER_DETAIL_WRITES && !searching && (+ namingSection === "new" ? (+ <input+ className="field rx-section-name"+ autoFocus+ placeholder="Section name"+ aria-label="New section name"+ onBlur={(e) => {+ setNamingSection(null);+ void createSection(e.target.value);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "Escape") {+ e.currentTarget.value = "";+ e.currentTarget.blur();+ }+ }}+ />+ ) : (+ <button className="link rx-add-section" onClick={() => setNamingSection("new")}>+ Add Section+ </button>+ )+ )}+{loaded && items.length === 0 && !error && lists.length > 0 && (<EmptyState className="rx-empty">{searching? "No reminders match.": inList? showDone- ? "Nothing in this list."+ ? "Nothing in this list yet.": "All done here.": "No Reminders"}</EmptyState>@@ -1586,8 +2070,19 @@ export function RemindersView() {.map((l) => ({ label: l.title, run: () => void moveToList(r, l.guid) })),}]: []),+ ...(REMINDER_DETAIL_WRITES && inList && listSections.length > 0+ ? [{+ label: "Move to Section",+ submenu: [+ ...(sectionOf(r) ? [{ label: "None", run: () => void moveToSection(r, null) }] : []),+ ...listSections+ .filter((x) => x.guid !== sectionOf(r) && !x.guid.startsWith(STAND_IN))+ .map((x) => ({ label: x.title, run: () => void moveToSection(r, x.guid) })),+ ],+ }]+ : []),null,- { label: "Delete", danger: true, run: () => void remove(r) },+ { label: "Delete", danger: true, run: () => void askRemove(r) },];})()}/>@@ -1755,3 +2250,138 @@ function DueField({ reminder, onChange }: { reminder: Reminder; onChange: (day:</div>);}++/**+ * The reminder's link: opened in the browser with a click. Typed in or cleared once Apple takes+ * the change (REMINDER_DETAIL_WRITES); until then shown only where there is one.+ */+function UrlField({ reminder, url, onSave }: { reminder: Reminder; url: string | null; onSave: (url: string | null) => void }) {+ if (!REMINDER_DETAIL_WRITES) {+ if (!url) return null;+ return (+ <div className="rx-field">+ <span>URL</span>+ <a className="rx-url" href={url} target="_blank" rel="noreferrer" title={url}>+ {url.replace(/^https?:\/\//, "").replace(/\/$/, "")}+ </a>+ </div>+ );+ }+ return (+ <label className="rx-field">+ <span>URL</span>+ <input+ className="field"+ type="url"+ key={`${reminder.guid}-${url ?? ""}`}+ defaultValue={url ?? ""}+ placeholder="Add URL"+ aria-label={`URL for ${reminder.title}`}+ onBlur={(e) => {+ const typed = e.target.value.trim();+ if (typed !== (url ?? "")) onSave(typed || null);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ if (e.key === "Escape") {+ e.currentTarget.value = url ?? "";+ e.currentTarget.blur();+ }+ }}+ />+ </label>+ );+}++/** "30 minutes early": a second alert before the due one. Shown once there is a date. */+function EarlyField({ reminder, alerts, onChange }: {+ reminder: Reminder;+ alerts: { count: number; unit: number }[];+ onChange: (alert: [number, number] | null) => void;+}) {+ const said = alerts.map((a) => earlyText(a.count, a.unit)).join(", ");+ if (!REMINDER_DETAIL_WRITES) {+ if (!alerts.length) return null;+ return (+ <div className="rx-field">+ <span>Early alert</span>+ <span className="rx-value">{said}</span>+ </div>+ );+ }+ if (reminder.dueAt === null && !alerts.length) return null;+ const now = alerts[0] ? `${alerts[0].count}:${alerts[0].unit}` : "none";+ const known = EARLY_CHOICES.some(([c, u]) => `${c}:${u}` === now);+ return (+ <div className="rx-field">+ <span>Early alert</span>+ <Picker+ label={`Early alert for ${reminder.title}`}+ value={now}+ onChange={(v) => {+ if (v === now) return;+ const [c, u] = v.split(":").map(Number);+ onChange(v === "none" ? null : [c, u]);+ }}+ options={[+ { value: "none", label: "None" },+ ...(!known && alerts[0] ? [{ value: now, label: said }] : []),+ ...EARLY_CHOICES.map(([c, u]) => ({ value: `${c}:${u}`, label: earlyText(c, u) })),+ ]}+ />+ </div>+ );+}++/** Tags as Apple writes them, #name. Tap one to see everything carrying it. */+function TagsField({ reminder, tags, onOpen, onAdd, onRemove }: {+ reminder: Reminder;+ tags: string[];+ onOpen: (name: string) => void;+ onAdd: (name: string) => void;+ onRemove: (name: string) => void;+}) {+ const [typed, setTyped] = useState("");+ if (!REMINDER_DETAIL_WRITES && tags.length === 0) return null;+ return (+ <div className="rx-field">+ <span>Tags</span>+ <div className="rx-tag-field">+ {tags.map((name) => (+ <span className="rx-tag is-chip" key={name}>+ <button type="button" className="rx-tag-name" onClick={() => onOpen(name)} aria-label={`Show reminders tagged ${name}`}>+ #{name}+ </button>+ {REMINDER_DETAIL_WRITES && (+ <button type="button" className="rx-tag-remove" aria-label={`Remove tag ${name}`} onClick={() => onRemove(name)}>+ <X aria-hidden="true" size={11} strokeWidth={2.5} />+ </button>+ )}+ </span>+ ))}+ {REMINDER_DETAIL_WRITES && (+ <input+ className="rx-tag-input"+ value={typed}+ placeholder={tags.length ? "Add" : "Add Tag"}+ aria-label={`Add a tag to ${reminder.title}`}+ onChange={(e) => setTyped(e.target.value.replace(/\s/g, ""))}+ onKeyDown={(e) => {+ if ((e.key === "Enter" || e.key === "," || e.key === " ") && typed.replace(/^#+/, "")) {+ e.preventDefault();+ onAdd(typed);+ setTyped("");+ } else if (e.key === "Backspace" && !typed && tags.length) {+ onRemove(tags[tags.length - 1]);+ }+ }}+ onBlur={() => {+ if (typed.replace(/^#+/, "")) onAdd(typed);+ setTyped("");+ }}+ />+ )}+ </div>+ </div>+ );+}diff --git a/src/screens/SettingsView.tsx b/src/screens/SettingsView.tsxindex 394d779..7572a35 100644--- a/src/screens/SettingsView.tsx+++ b/src/screens/SettingsView.tsx@@ -1,11 +1,19 @@import { ConfirmSheet } from "../components/Confirm";-import { toastSaved, useErrorToast } from "../components/Toast";-import { useEffect, useState } from "react";+import { toast, toastSaved, useErrorToast } from "../components/Toast";+import { Progress } from "../components/Spinner";+import { useEffect, useState, useSyncExternalStore } from "react";import { getVersion } from "@tauri-apps/api/app";+import { listen } from "@tauri-apps/api/event";+import { open as openFileDialog } from "@tauri-apps/plugin-dialog";import {api,+ EXPORT_CANCELLED,+ EXPORT_PROGRESS,+ exportApi,type AccountInfo,type DriveFolder,+ type ExportProgress,+ type ExportService,type LocalStorage,type LoginItem,messageOf,@@ -184,6 +192,136 @@ function FolderRow({);}+/**+ * Export Everything, kept outside the screen: an export runs on while Settings is closed, and+ * coming back finds it where it is, not idle.+ */+type ExportState =+ | { phase: "idle" }+ | { phase: "running"; progress: ExportProgress | null; cancelling: boolean }+ | { phase: "done"; path: string; photosMissing: number };+let exportState: ExportState = { phase: "idle" };+const exportListeners = new Set<() => void>();+const setExportState = (s: ExportState) => {+ exportState = s;+ exportListeners.forEach((l) => l());+};+const subscribeExport = (l: () => void) => {+ exportListeners.add(l);+ return () => exportListeners.delete(l);+};++const SERVICE_LABEL: Record<ExportService, string> = {+ notes: "Notes",+ reminders: "Reminders",+ contacts: "Contacts",+ calendar: "Calendar",+ drive: "Drive",+ photos: "Photos",+};++/** How far the whole export is, 0 to 1: services done, and the share of the one under way. */+function exportShare(p: ExportProgress | null): number | null {+ if (!p || p.steps === 0) return null;+ const within = p.total > 0 ? p.done / p.total : p.done === p.total ? 1 : 0;+ return (p.step - 1 + within) / p.steps;+}++async function runExport(photos: boolean, onError: (m: string) => void) {+ const dest = await openFileDialog({ directory: true, multiple: false, title: "Choose where to export" });+ if (typeof dest !== "string" || !dest) return;+ setExportState({ phase: "running", progress: null, cancelling: false });+ const stop = listen<ExportProgress>(EXPORT_PROGRESS, (e) => {+ if (exportState.phase === "running") setExportState({ ...exportState, progress: e.payload });+ });+ try {+ const summary = await exportApi.start(dest, photos);+ setExportState({ phase: "done", path: summary.path, photosMissing: summary.photosMissing });+ toast({+ message: `Exported to ${folderName(summary.path)}`,+ tone: "done",+ action: { label: "Show in Folder", run: () => void exportApi.reveal().catch((e) => onError(messageOf(e))) },+ });+ } catch (e) {+ const message = messageOf(e);+ setExportState({ phase: "idle" });+ if (message === EXPORT_CANCELLED) toast("Export cancelled. Nothing was left behind.");+ else onError(message);+ } finally {+ void stop.then((unlisten) => unlisten()).catch(() => {});+ }+}++const folderName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path;++/** The row: what goes out and where, Export, then the bar and Cancel, then Show in Folder. */+function ExportRow({ onError }: { onError: (m: string) => void }) {+ const state = useSyncExternalStore(subscribeExport, () => exportState);+ const [photos, setPhotos] = useState(false);+ const running = state.phase === "running";+ const p = running ? state.progress : null;+ const hint = running+ ? state.cancelling+ ? "Cancelling…"+ : p+ ? `${SERVICE_LABEL[p.service]} · ${p.total > 0 ? `${Math.min(p.done, p.total).toLocaleString()} of ${p.total.toLocaleString()}` : "nothing to export"}`+ : "Getting ready…"+ : state.phase === "done"+ ? `Exported to ${folderName(state.path)}${state.photosMissing > 0 ? ` · ${state.photosMissing.toLocaleString()} ${state.photosMissing === 1 ? "photo wasn't" : "photos weren't"} on this computer` : ""}`+ : "Notes, reminders, contacts, calendars and Drive, in open formats";+ return (+ <div className="settings-row is-stacked" aria-label="Export Everything" role="group">+ <div className="settings-row-line" style={{ alignItems: "center" }}>+ <span className="settings-label settings-stack">+ Export Everything+ <span className="settings-hint" aria-live="polite" title={state.phase === "done" ? state.path : undefined}>+ {hint}+ </span>+ </span>+ {state.phase === "done" && !running && (+ <button className="quiet" onClick={() => void exportApi.reveal().catch((e) => onError(messageOf(e)))}>+ Show in Folder+ </button>+ )}+ {running ? (+ <button+ className="quiet"+ disabled={state.cancelling}+ onClick={() => {+ setExportState({ ...state, cancelling: true });+ void exportApi.cancel().catch(() => {});+ }}+ >+ Cancel+ </button>+ ) : (+ <button className="quiet" onClick={() => void runExport(photos, onError)}>+ Export+ </button>+ )}+ </div>+ {running ? (+ <Progress value={exportShare(p)} label="Export progress" />+ ) : (+ <div className="settings-row-line" style={{ alignItems: "center" }}>+ <span className="settings-label settings-stack">+ <span className="settings-hint">Include Photos · only those on this computer, and it can be large</span>+ </span>+ <button+ className="switch"+ role="switch"+ aria-checked={photos}+ aria-label="Include Photos"+ onClick={() => setPhotos(!photos)}+ >+ <span className="switch-knob" />+ </button>+ </div>+ )}+ </div>+ );+}+export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Promise<void> }) {const [account, setAccount] = useState<AccountInfo | null>(null);const [storage, setStorage] = useState<{ usedBytes: number; totalBytes: number } | null>(null);@@ -361,7 +499,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom{showDrive && (<FolderRowapp="drivews"- label="iCloud Drive folder"+ label="Drive folder"off="Your iCloud Drive in Files and every other app"folder={folder}busy={folderBusy}@@ -373,7 +511,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom{showPhotos && (<FolderRowapp="photos"- label="iCloud Photos folder"+ label="Photos folder"off="Your photos by date and album, for every other app"folder={photosFolder}busy={photosBusy}@@ -397,7 +535,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom[["photos", "Photos", local?.photos],["notes", "Notes", local?.notes],- ["drivews", "iCloud Drive", local?.drive],+ ["drivews", "Drive", local?.drive],["library", "Library", local?.library],["other", "Other", local?.other],] as const@@ -422,6 +560,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom{clearing ? "Clearing…" : "Clear"}</button></div>+ <ExportRow onError={setError} /></section><h2 className="settings-heading">General</h2>@@ -537,7 +676,7 @@ export function SettingsView({ onSignOut }: { onSignOut: (keep: boolean) => Prom</button></div></section>- <p className="settings-note">Pomander talks only to Apple. It has no servers of its own.</p>+ <p className="settings-note">Skykeep talks only to Apple, and to calendars you subscribe to. It has no servers of its own.</p></div>);}diff --git a/src/screens/SignIn.tsx b/src/screens/SignIn.tsxindex c2d9813..0815ad7 100644--- a/src/screens/SignIn.tsx+++ b/src/screens/SignIn.tsx@@ -6,7 +6,7 @@ import { api, messageOf, type SignInResult } from "../lib/ipc";import { onWindows } from "../lib/platform";// Where the copy is kept, as this system names it.-const STORE = onWindows ? "%APPDATA%\\io.github.yashwanthkamireddi.Pomander" : "~/.local/share/io.github.yashwanthkamireddi.Pomander";+const STORE = onWindows ? "%APPDATA%\\io.github.yashwanthkamireddi.Skykeep" : "~/.local/share/io.github.yashwanthkamireddi.Skykeep";/*** An error as a sentence: some of the engine's messages start in lower case and end without@@ -153,12 +153,12 @@ export function SignIn({* the rest a click away for anyone who wants it.*/}<details className="disclosure">- <summary>How Pomander keeps you private</summary>+ <summary>How Skykeep keeps you private</summary><div className="disclosure-body"><p><strong>Private by design.</strong> Your password never leaves this computer.- Pomander proves you know it without sending it, and keeps your session in your- system keyring. No Pomander account, no Pomander servers: it talks only to Apple.+ Skykeep proves you know it without sending it, and keeps your session in your+ system keyring. No Skykeep account, no Skykeep servers: it talks only to Apple, and to calendars you subscribe to.</p><p><strong>Your iCloud, right here.</strong> Your calendar, reminders, notes, contactsdiff --git a/src/screens/calendar/CalendarView.tsx b/src/screens/calendar/CalendarView.tsxindex 1b0e470..3468e49 100644--- a/src/screens/calendar/CalendarView.tsx+++ b/src/screens/calendar/CalendarView.tsx@@ -6,7 +6,7 @@ import { useActiveRef } from "../../lib/screen";import { usePending } from "../../lib/pending";import { inMenu, Portal } from "../../components/Portal";import { TimeField } from "../../components/TimeField";-import { ChevronLeft, ChevronRight, Plus } from "lucide-react";+import { ChevronDown, ChevronLeft, ChevronRight, Ellipsis, MapPin, Plus, Repeat } from "lucide-react";import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import {type EventRepeat,@@ -15,7 +15,11 @@ import {messageOf,type Calendar,type CalendarEvent,- type Reminder, type EventScope } from "../../lib/ipc";+ type Reminder, type EventScope,+ type CalendarSubscription,+ calendarFeedsApi,+ SUBSCRIPTION_PREFIX } from "../../lib/ipc";+import { parseQuick } from "./quick";import { useSync } from "../../lib/sync";import { Picker } from "../../components/Picker";import { RowMenu } from "../../components/RowMenu";@@ -40,6 +44,7 @@ import {spansDays,startOfWeek,wallIn,+ weekNumber,weekSpans,zoneName,} from "./model";@@ -120,6 +125,39 @@ const MONTH_ROWS = 4;/** Calendars the viewer has switched off here, remembered on this computer. */const HIDDEN_KEY = "quince.calendar.hidden";const VIEW_KEY = "quince.calendar.view";+/** Sidebar groups folded away, week numbers shown, and each calendar's default alerts —+ * Apple keeps these as preferences of each Mac, and so does this. */+const FOLDED_KEY = "quince.calendar.folded";+const WEEK_NUMBERS_KEY = "quince.calendar.weekNumbers";+const DEFAULT_ALERTS_KEY = "quince.calendar.defaultAlerts";++type DefaultAlerts = { timed: Record<string, number>; allDay: Record<string, number> };+const readJson = <T,>(key: string, fallback: T): T => {+ try {+ const raw = window.localStorage.getItem(key);+ return raw ? { ...fallback, ...JSON.parse(raw) } : fallback;+ } catch {+ return fallback;+ }+};+const writeJson = (key: string, value: unknown) => {+ try {+ window.localStorage.setItem(key, JSON.stringify(value));+ } catch {+ // A preference of this computer; kept for now if it cannot be written.+ }+};++/** How often a subscription can be fetched again, as Calendar offers it. */+const REFRESHES = [+ { minutes: 60, label: "Every Hour" },+ { minutes: 1440, label: "Every Day" },+ { minutes: 10080, label: "Every Week" },+ { minutes: 0, label: "Only When Asked" },+];++/** A place, for the map app this computer opens `geo:` links with. */+const mapsHref = (place: string) => `geo:0,0?q=${encodeURIComponent(place.split("\n").join(", "))}`;const readSet = (key: string) => {try {@@ -153,6 +191,9 @@ type Draft = {/** How it repeats; `undefined` until read from Apple, `null` for never. */repeat?: EventRepeat | null;repeatChanged?: boolean;+ /** A new event's alerts are its calendar's defaults until one is chosen, and follow a+ * change of calendar or of all-day. */+ alertsDefault?: boolean;};/**@@ -243,13 +284,28 @@ export function CalendarView() {setSelected(midnight(dateOf(e.startsAt)));setView("day");setQuery("");+ // Its calendar shown if it was hidden, and the event itself opened, once it is drawn.+ if (hidden.has(e.calendarGuid)) toggleCalendar(e.calendarGuid);+ setPicked(e.guid);+ setFinding(e.guid);};/** 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 [found, setFoundRaw] = useState<CalendarEvent[]>([]);+ /** The row lit in the results, which Return opens and the arrows move. */+ const [lit, setLit] = useState(0);+ // Coming up first, soonest first; then what has been, latest first — what is looked for is+ // most often next, and a long past pushed it out of sight.+ const setFound = (rows: CalendarEvent[]) => {+ const now = Date.now() / 1000;+ const ahead = rows.filter((e) => e.endsAt >= now).sort((a, b) => a.startsAt - b.startsAt);+ const past = rows.filter((e) => e.endsAt < now).sort((a, b) => b.startsAt - a.startsAt);+ setFoundRaw([...ahead, ...past]);+ setLit(0);+ };const searchField = useRef<HTMLInputElement | null>(null);useEffect(() => {const q = query.trim();@@ -285,6 +341,44 @@ export function CalendarView() {const [naming, setNaming] = useState<string | null>(null);const [calMenu, setCalMenu] = useState<{ cal: Calendar; at: { x: number; y: number; alignRight: boolean } } | null>(null);const [hidden, setHidden] = useState<Set<string>>(() => readSet(HIDDEN_KEY));+ /** Calendars subscribed to by address, as kept on this computer. */+ const [subs, setSubs] = useState<CalendarSubscription[]>([]);+ /** Sidebar groups folded away. */+ const [folded, setFolded] = useState<Set<string>>(() => readSet(FOLDED_KEY));+ const fold = (key: string) =>+ setFolded((was) => {+ const next = new Set(was);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ writeJson(FOLDED_KEY, [...next]);+ return next;+ });+ const [weekNumbers, setWeekNumbersState] = useState<boolean>(() => readJson(WEEK_NUMBERS_KEY, false));+ const setWeekNumbers = (on: boolean) => {+ setWeekNumbersState(on);+ writeJson(WEEK_NUMBERS_KEY, on);+ };+ const [defaultAlerts, setDefaultAlertsState] = useState<DefaultAlerts>(() => readJson(DEFAULT_ALERTS_KEY, { timed: {}, allDay: {} }));+ const setDefaultAlert = (kind: "timed" | "allDay", guid: string, minutes: number | null) =>+ setDefaultAlertsState((was) => {+ const next = { ...was, [kind]: { ...was[kind] } };+ if (minutes === null) delete next[kind][guid];+ else next[kind][guid] = minutes;+ writeJson(DEFAULT_ALERTS_KEY, next);+ return next;+ });+ /** The event picked — the last one clicked — that Return opens, Delete deletes, ⌘D+ * duplicates and ⌘C copies; and the event copied, for ⌘V to put on the selected day. */+ const [picked, setPicked] = useState<string | null>(null);+ const [clip, setClip] = useState<CalendarEvent | null>(null);+ /** Quick Event, opened under the + button. */+ const [quick, setQuick] = useState(false);+ /** New Calendar Subscription, opened from the sidebar's +. */+ const [subscribing, setSubscribing] = useState(false);+ const [addMenu, setAddMenu] = useState<{ x: number; y: number; alignRight: boolean } | null>(null);+ const [groupMenu, setGroupMenu] = useState<{ list: Calendar[]; at: { x: number; y: number; alignRight: boolean } } | null>(null);+ const [moreMenu, setMoreMenu] = useState<{ x: number; y: number; alignRight: boolean } | null>(null);+ const [eventMenu, setEventMenu] = useState<{ event: CalendarEvent; at: { x: number; y: number; alignRight: boolean } } | null>(null);// An event found by the search across everything: its day shown, its calendar too if it// was hidden (and kept shown, as its tick in the list says) — never a found event that// cannot be seen — and the event itself opened, as Calendar opens one found.@@ -365,12 +459,14 @@ export function CalendarView() {const { hold, over } = usePending<CalendarEvent>();const read = useCallback(async () => {- const [found, cals, reminders, lists] = await Promise.all([+ const [found, cals, reminders, lists, feeds] = await Promise.all([api.calendarEvents(range.from, range.to),api.calendarList(),api.remindersDueBetween(range.from, range.to),api.reminderLists().catch(() => []),+ calendarFeedsApi.list().catch(() => [] as CalendarSubscription[]),]);+ setSubs(Array.isArray(feeds) ? feeds : []);setListColours(new Map((Array.isArray(lists) ? lists : []).map((l) => [l.guid, l.colour && /^#[0-9a-f]{6}$/i.test(l.colour) ? l.colour : ""])));setEvents(over(Array.isArray(found) ? found : []));setCalendars(Array.isArray(cals) ? cals : []);@@ -432,6 +528,17 @@ export function CalendarView() {const writable = calendars.filter((c) => c.writable);const target = defaultCalendar(calendars);+ /** A group's Show All and Hide All. */+ const showOnly = (list: Calendar[], show: boolean) =>+ setHidden((was) => {+ const next = new Set(was);+ for (const c of list) {+ if (show) next.delete(c.guid);+ else next.add(c.guid);+ }+ writeJson(HIDDEN_KEY, [...next]);+ return next;+ });const toggleCalendar = (guid: string) =>setHidden((was) => {const next = new Set(was);@@ -620,6 +727,118 @@ export function CalendarView() {(e: CalendarEvent, startsAt: number, endsAt: number) => void save({ ...draftOf(e), startsAt, endsAt }),[save]);+ /** Dragged to another day in Month: the same clock time, that many days on. */+ const moveDays = useCallback((e: CalendarEvent, days: number) => {+ if (!days) return;+ const zone = zoneOf(e);+ void save({ ...draftOf(e), startsAt: addDaysIn(zone, e.startsAt, days), endsAt: addDaysIn(zone, e.endsAt, days) });+ }, [save]);++ /** Where a copy of `e` can go: its own calendar, or the default when that one is read-only. */+ const homeFor = (e: CalendarEvent) => (byGuid.get(e.calendarGuid)?.writable ? e.calendarGuid : targetGuid);+ /** Real events at Apple carry alerts and a repeat to read; birthdays and feeds do not. */+ const atApple = (guid: string) => !guid.startsWith("quince:") && !guid.startsWith("pending:");++ /** ⌘D: a copy at the same time, its alerts and repeat with it, as Calendar duplicates. */+ const duplicate = async (e: CalendarEvent) => {+ const into = homeFor(e);+ if (!into) return;+ const occurrence = e.guid.includes("__");+ const [alerts, repeat] = atApple(e.guid)+ ? await Promise.all([+ api.eventAlerts(e.guid).catch(() => [] as number[]),+ occurrence ? Promise.resolve(null) : api.eventRepeat(e.guid).catch(() => null),+ ])+ : [alertsFor(into, e.allDay), null];+ await save({ ...draftOf(e), guid: null, calendarGuid: into, alerts, alertsChanged: true, repeat, repeatChanged: repeat !== null });+ };+ /** ⌘V: the copied event on the selected day, at its own time of day. */+ const paste = (e: CalendarEvent) => {+ const into = homeFor(e);+ if (!into) return;+ const day = selected;+ let startsAt: number;+ let endsAt: number;+ if (e.allDay) {+ const days = Math.max(1, Math.round((e.endsAt - e.startsAt) / 86_400));+ startsAt = seconds(day);+ endsAt = seconds(addDays(day, days));+ } else {+ const was = dateOf(e.startsAt);+ startsAt = seconds(new Date(day.getFullYear(), day.getMonth(), day.getDate(), was.getHours(), was.getMinutes()));+ endsAt = startsAt + (e.endsAt - e.startsAt);+ }+ void save({ ...draftOf(e), guid: null, calendarGuid: into, startsAt, endsAt, alerts: alertsFor(into, e.allDay), alertsChanged: true });+ };+ /** Delete from the keyboard: asked first, as a key is easily pressed. A repeating event's+ * own question (this one, future or all) is the asking. */+ const deleteAsking = async (e: CalendarEvent) => {+ if (!byGuid.get(e.calendarGuid)?.writable) return;+ if (!e.guid.includes("__")) {+ const sure = await confirm({+ title: `Delete \u201c${e.title || "New Event"}\u201d?`,+ body: "It will be deleted from all your devices.",+ action: "Delete",+ danger: true,+ symbol: "trash",+ });+ if (!sure) return;+ }+ void remove(e.guid);+ };+ /** Return on a picked event: opened beside where it is drawn. */+ const openPicked = (e: CalendarEvent) => {+ const block = document.querySelector(`[data-event="${CSS.escape(e.guid)}"]`);+ const r = block?.getBoundingClientRect();+ openDraft(draftOf(e), r ? { x: r.right, y: r.top, left: r.left } : { x: window.innerWidth / 2, y: 120 });+ };++ /** Quick Event: the line read here, shown, and on Return made as read. */+ const addQuick = async (text: string, details: boolean, at: Anchor) => {+ if (!targetGuid) return;+ const q = parseQuick(text);+ setQuick(false);+ const d: Draft = {+ guid: null, calendarGuid: targetGuid, title: q.title, location: q.location ?? "",+ startsAt: q.startsAt, endsAt: q.endsAt, allDay: q.allDay, notes: "", url: null, timezone: null,+ repeat: q.repeat, repeatChanged: q.repeat !== null,+ };+ setSelected(midnight(dateOf(q.startsAt)));+ if (details || !q.title) {+ openDraft(d, at);+ setFollowDraft(true);+ return;+ }+ await save({ ...d, alerts: alertsFor(targetGuid, q.allDay), alertsChanged: true });+ };++ /** Subscriptions: renamed, recoloured, refreshed or let go, kept on this computer. */+ const updateSub = (id: string, change: { title?: string; colour?: string; refreshMinutes?: number }) => {+ setNaming(null);+ if (change.title !== undefined && !change.title.trim()) return;+ setSubs((list) => list.map((x) => (x.id === id ? { ...x, ...change } : x)));+ setCalendars((cs) => cs.map((c) => (c.guid === SUBSCRIPTION_PREFIX + id ? { ...c, ...(change.title ? { title: change.title } : {}), ...(change.colour ? { colour: change.colour } : {}) } : c)));+ void write(async () => { await calendarFeedsApi.update(id, change); });+ };+ const refreshSub = (id: string) => {+ calendarFeedsApi.refresh(id).then(+ (s) => { toast(`\u201c${s.title}\u201d is up to date`); void read(); },+ (e) => setError(messageOf(e)),+ );+ };+ const unsubscribe = (sub: CalendarSubscription) => {+ void confirm({+ title: `Unsubscribe from \u201c${sub.title}\u201d?`,+ body: "Its events leave this computer. You can subscribe again at any time.",+ action: "Unsubscribe",+ danger: true,+ }).then((sure) => {+ if (!sure) return;+ setCalendars((cs) => cs.filter((c) => c.guid !== SUBSCRIPTION_PREFIX + sub.id));+ setEvents((rows) => rows.filter((e) => e.calendarGuid !== SUBSCRIPTION_PREFIX + sub.id));+ void write(async () => { await calendarFeedsApi.unsubscribe(sub.id); });+ });+ };/*** The popover put away by a click elsewhere keeps what was written in it, as Calendar's* does — a title typed and then a click on the next day had thrown the title away. Escape@@ -633,7 +852,7 @@ export function CalendarView() {d.title !== was.title || d.location !== was.location || d.notes !== was.notes ||(d.url ?? "") !== (was.url ?? "") || d.calendarGuid !== was.calendarGuid ||d.timezone !== was.timezone || d.allDay !== was.allDay ||- d.alertsChanged || d.repeatChanged ||+ (d.alertsChanged && d.alerts !== was.alerts) || (d.repeatChanged && d.repeat !== was.repeat) ||// A new event's times are where it was made; only an existing one's are a change.(d.guid !== null && (d.startsAt !== was.startsAt || d.endsAt !== was.endsAt))));@@ -651,13 +870,33 @@ export function CalendarView() {};}, [undo, takeBack]);+ /** A calendar's default alert for a new event, kept on this computer (Apple's web service+ * has no field for one): minutes before, as the alert pickers count. */+ const defaultsRef = useRef(defaultAlerts);+ defaultsRef.current = defaultAlerts;+ const alertsFor = useCallback((calendarGuid: string, allDay: boolean): number[] => {+ const m = defaultsRef.current[allDay ? "allDay" : "timed"][calendarGuid];+ return m === undefined ? [] : [m];+ }, []);+ /** The popover's changes, a new event's default alerts kept in step with its calendar. */+ const changeDraft = useCallback((next: Draft) => {+ setDraft(next.alertsDefault && !next.guid ? { ...next, alerts: alertsFor(next.calendarGuid, next.allDay) } : next);+ }, [alertsFor]);+/** The draft as it was opened, to tell whether anything in it has been changed since. */const openedAs = useRef<Draft | null>(null);const openDraft = useCallback((d: Draft, at: Anchor) => {// The event already open stays as it is: a second click — a double-click — closed it and// opened it again, and the popover flickered.if (d.guid && draftRef.current?.guid === d.guid) return;- const opened = d.guid ? d : { ...d, alerts: [], repeat: null };+ const opened = d.guid ? d : {+ ...d,+ alerts: d.alerts ?? alertsFor(d.calendarGuid, d.allDay),+ alertsChanged: true,+ alertsDefault: d.alerts === undefined,+ repeat: d.repeat ?? null,+ repeatChanged: Boolean(d.repeat),+ };openedAs.current = opened;setDraft(opened);setAnchor(at);@@ -704,7 +943,15 @@ export function CalendarView() {* inputs have not changed is not drawn again — not the week for every key typed in the* popover, not the year for every minute the clock moves on.*/- const openEvent = useCallback((e: CalendarEvent, at: Anchor) => openDraft(draftOf(e), at), [openDraft]);+ const openEvent = useCallback((e: CalendarEvent, at: Anchor) => {+ setPicked(e.guid);+ openDraft(draftOf(e), at);+ }, [openDraft]);+ /** Right-click on an event: what can be done with it, as Calendar's shortcut menu offers. */+ const menuFor = useCallback((e: CalendarEvent, at: { x: number; y: number }) => {+ setPicked(e.guid);+ setEventMenu({ event: e, at: { ...at, alignRight: false } });+ }, []);const createInMonth = useCallback((day: Date, at: Anchor) => {const start = new Date(day);start.setHours(9, 0, 0, 0);@@ -779,6 +1026,20 @@ export function CalendarView() {if (typing || draft) return;const command = (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey;const k = e.key.toLowerCase();+ // The picked event: Return opens it, Delete asks and deletes it, ⌘D duplicates it, ⌘C+ // copies it; ⌘V puts the copy on the selected day; Escape lets it go.+ const event = picked ? events.find((x) => x.guid === picked) ?? null : null;+ const plain = !e.metaKey && !e.ctrlKey && !e.altKey;+ const inMenuNow = document.querySelector('[role="menu"], [role="alertdialog"], .modal-veil');+ if (event && !inMenuNow) {+ const textSelected = (window.getSelection()?.toString() ?? "") !== "";+ if (plain && e.key === "Enter") { e.preventDefault(); openPicked(event); return; }+ if (plain && (e.key === "Delete" || e.key === "Backspace")) { e.preventDefault(); void deleteAsking(event); return; }+ if (command && k === "d") { e.preventDefault(); void duplicate(event); return; }+ if (command && k === "c" && !textSelected) { e.preventDefault(); setClip(event); toast(`Copied \u201c${event.title}\u201d`); return; }+ if (plain && e.key === "Escape") { setPicked(null); return; }+ }+ if (command && k === "v" && clip && !inMenuNow) { e.preventDefault(); paste(clip); return; }// ⇧⌘T, Go to Date…, as in Calendar's View menu.if ((e.metaKey || e.ctrlKey) && e.shiftKey && !e.altKey && k === "t") {e.preventDefault();@@ -880,35 +1141,67 @@ export function CalendarView() {<aside className="cx-side" aria-label="Calendars"><div className="cx-cals">{[- { heading: "iCloud", list: calendars.filter((c) => c.writable) },- { heading: "Other", list: calendars.filter((c) => !c.writable) },+ { key: "icloud", heading: "iCloud", list: calendars.filter((c) => c.writable) },+ { key: "subs", heading: "Subscriptions", list: calendars.filter((c) => c.guid.startsWith(SUBSCRIPTION_PREFIX)) },+ { key: "other", heading: "Other", list: calendars.filter((c) => !c.writable && !c.guid.startsWith(SUBSCRIPTION_PREFIX)) },]- .filter((g) => g.list.length > 0)- .map((group) => (- <Fragment key={group.heading}>- <p className="side-heading cx-side-heading">- {group.heading}- {group.heading === "iCloud" && (- <button className="icon-button small cx-side-add" aria-label="New Calendar" title="New Calendar" onClick={() => setNaming("new")}>+ .filter((g) => g.list.length > 0 || (g.key === "icloud" && loaded && calendars.length > 0))+ .map((group) => {+ const open = !folded.has(group.key);+ return (+ <Fragment key={group.key}>+ <div className="cx-group" role="group" aria-label={group.heading}>+ <button+ className="side-heading cx-side-heading"+ aria-expanded={open}+ onClick={() => fold(group.key)}+ onContextMenu={(e) => {+ e.preventDefault();+ setGroupMenu({ list: group.list, at: { x: e.clientX, y: e.clientY, alignRight: false } });+ }}+ >+ <ChevronDown size={11} strokeWidth={2.6} aria-hidden="true" className="cx-fold" />+ {group.heading}+ </button>+ {group.key === "icloud" && (+ <button+ className="icon-button small cx-side-add"+ aria-label="Add Calendar"+ title="Add Calendar"+ aria-haspopup="menu"+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ setAddMenu({ x: r.left, y: r.bottom + 4, alignRight: false });+ }}+ ><Plus size={14} strokeWidth={2.2} aria-hidden="true" /></button>)}- </p>- {group.list.map((c) =>- naming === c.guid ? (- <CalendarName key={c.guid} initial={c.title} label={`Rename ${c.title}`} onDone={(t) => updateCalendar(c, { title: t })} onCancel={() => setNaming(null)} />+ </div>+ {open && group.list.map((c) => {+ const sub = c.guid.startsWith(SUBSCRIPTION_PREFIX) ? subs.find((x) => SUBSCRIPTION_PREFIX + x.id === c.guid) ?? null : null;+ return naming === c.guid ? (+ <CalendarName+ key={c.guid}+ initial={c.title}+ label={`Rename ${c.title}`}+ onDone={(t) => (sub ? updateSub(sub.id, { title: t.trim() }) : updateCalendar(c, { title: t }))}+ onCancel={() => setNaming(null)}+ />) : (<labelclassName="source-row cx-cal"key={c.guid}+ title={sub?.problem ? `Not refreshed: ${sub.problem}` : undefined}onContextMenu={(e) => {- // A calendar of this account can be renamed, recoloured or removed, as on icloud.com.- if (!c.writable) return;+ // A calendar of this account, or a subscription, can be renamed and+ // recoloured; Birthdays and holidays are as they are.+ if (!c.writable && !sub) return;e.preventDefault();setCalMenu({ cal: c, at: { x: e.clientX, y: e.clientY, alignRight: false } });}}onDoubleClick={(e) => {- if (!c.writable) return;+ if (!c.writable && !sub) return;e.preventDefault();setNaming(c.guid);}}@@ -920,23 +1213,36 @@ export function CalendarView() {style={{ "--cal": tint(c) } as React.CSSProperties}/><span className="source-name cx-cal-name">{c.title}</span>+ {sub?.problem && <span className="cx-cal-problem" aria-label="Not refreshed">!</span>}</label>- ),- )}- {group.heading === "iCloud" && naming === "new" && (+ );+ })}+ {open && group.key === "icloud" && naming === "new" && (<CalendarName initial="Untitled" label="New calendar name" onDone={createCalendar} onCancel={() => setNaming(null)} />)}</Fragment>- ))}+ );+ })}{loaded && calendars.length === 0 && (<EmptyState className="cal-empty">There are no calendars on this account yet.</EmptyState>)}+ {subscribing && (+ <SubscribeForm+ onDone={(sub) => {+ setSubscribing(false);+ toast(`Subscribed to \u201c${sub.title}\u201d`);+ void read();+ }}+ onCancel={() => setSubscribing(false)}+ />+ )}</div><MiniMonthselected={selected}today={now}busy={busyOn}onPick={setSelected}+ weekNumbers={weekNumbers}/></aside>@@ -964,12 +1270,39 @@ export function CalendarView() {</div><div className="cx-tools">{writable.length > 0 && (- <span className="toolbar-group">- <button className="tool cx-icon" aria-label="New event" title="New Event" onClick={newEvent}>+ <span className="toolbar-group cx-quick-anchor">+ <button+ className="tool cx-icon"+ aria-label="New event"+ title="New Event"+ aria-expanded={quick}+ onClick={() => setQuick((q) => !q)}+ ><Plus size={17} strokeWidth={2} aria-hidden="true" /></button>+ {quick && (+ <QuickEvent+ calendar={target}+ onAdd={(text, details, at) => void addQuick(text, details, at)}+ onClose={() => setQuick(false)}+ />+ )}</span>)}+ <span className="toolbar-group">+ <button+ className="tool cx-icon"+ aria-label="More"+ title="More"+ aria-haspopup="menu"+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ setMoreMenu({ x: r.right, y: r.bottom + 4, alignRight: true });+ }}+ >+ <Ellipsis size={17} strokeWidth={2} aria-hidden="true" />+ </button>+ </span><span className="toolbar-group cx-step"><button className="tool cx-icon" aria-label="Previous" onClick={() => shift(-1)}><ChevronLeft size={17} strokeWidth={2} aria-hidden="true" />@@ -1021,53 +1354,155 @@ export function CalendarView() {onChange={setQuery}onKeyDown={(e) => {if (e.key === "Escape") setQuery("");- if (e.key === "Enter" && found[0]) openFound(found[0]);+ // Its default kept from the event's own field, which takes the focus as it+ // opens: Return there is Save, and it saved and closed the event at once.+ else if (e.key === "Enter" && found[lit]) { e.preventDefault(); openFound(found[lit]); }+ else if (e.key === "ArrowDown" && found.length) { e.preventDefault(); setLit((i) => Math.min(found.length - 1, i + 1)); }+ else if (e.key === "ArrowUp" && found.length) { e.preventDefault(); setLit((i) => Math.max(0, i - 1)); }}}/></div></header>{query.trim() && (- <div className="popover cx-found" role="listbox" aria-label="Events found">+ <div className="popover cx-found" role="listbox" aria-label="Events found" id="cx-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">- {dateText(dateOf(e.startsAt), { weekday: "short", day: "numeric", month: "short", year: "numeric" })}- {e.allDay ? "" : ` · ${clock(e.startsAt)}`}- </span>- </button>- ))+ found.map((e, i) => {+ const pastStarts = i > 0 && found[i - 1].endsAt >= Date.now() / 1000 && e.endsAt < Date.now() / 1000;+ return (+ <Fragment key={e.guid}>+ {pastStarts && <p className="cx-found-section">Earlier</p>}+ <button+ className={`cx-found-row${i === lit ? " is-lit" : ""}`}+ role="option"+ aria-selected={i === lit}+ ref={i === lit ? (el) => el?.scrollIntoView({ block: "nearest" }) : undefined}+ style={{ "--cal": tint(byGuid.get(e.calendarGuid)) } as React.CSSProperties}+ onMouseMove={() => i !== lit && setLit(i)}+ onClick={() => openFound(e)}+ >+ <span className="cx-dot" aria-hidden="true" />+ <span className="cx-found-text">+ <span className="cx-found-title"><Marked text={e.title} query={query} /></span>+ {e.location && <span className="cx-found-where"><Marked text={e.location} query={query} /></span>}+ </span>+ <span className="cx-found-when">+ {dateText(dateOf(e.startsAt), { weekday: "short", day: "numeric", month: "short", year: "numeric" })}+ {e.allDay ? "" : `, ${clock(e.startsAt)}`}+ </span>+ </button>+ </Fragment>+ );+ }))}</div>)}- {calMenu && (+ {calMenu && (() => {+ const cal = calMenu.cal;+ const sub = subs.find((x) => SUBSCRIPTION_PREFIX + x.id === cal.guid) ?? null;+ const colours = CALENDAR_COLOURS.map(([hex, name]) => ({+ label: name,+ checked: (cal.colour ?? "").toLowerCase() === hex,+ run: () => (sub ? updateSub(sub.id, { colour: hex }) : updateCalendar(cal, { colour: hex })),+ }));+ const alertMenu = (kind: "timed" | "allDay") => {+ const current = defaultAlerts[kind][cal.guid];+ return [+ { label: "None", checked: current === undefined, run: () => setDefaultAlert(kind, cal.guid, null) },+ ...(kind === "allDay" ? ALL_DAY_ALERTS : ALERTS).map((a) => ({+ label: a.label,+ checked: current === a.minutes,+ run: () => setDefaultAlert(kind, cal.guid, a.minutes),+ })),+ ];+ };+ return (+ <RowMenu+ at={calMenu.at}+ onClose={() => setCalMenu(null)}+ entries={sub ? [+ { label: "Rename", run: () => setNaming(cal.guid) },+ { label: "Colour", submenu: colours },+ {+ label: "Refresh",+ submenu: REFRESHES.map((r) => ({ label: r.label, checked: sub.refreshMinutes === r.minutes, run: () => updateSub(sub.id, { refreshMinutes: r.minutes }) })),+ },+ { label: "Refresh Now", run: () => refreshSub(sub.id) },+ null,+ { label: "Unsubscribe", danger: true, run: () => unsubscribe(sub) },+ ] : [+ { label: "Rename", run: () => setNaming(cal.guid) },+ { label: "Colour", submenu: colours },+ { label: "Default Alert", submenu: alertMenu("timed") },+ { label: "Default All-Day Alert", submenu: alertMenu("allDay") },+ null,+ ...(cal.isDefault ? [] : [{ label: "Delete Calendar", danger: true, run: () => deleteCalendar(cal) }]),+ ]}+ />+ );+ })()}+ {addMenu && (+ <RowMenu+ at={addMenu}+ onClose={() => setAddMenu(null)}+ entries={[+ { label: "New Calendar", run: () => { if (folded.has("icloud")) fold("icloud"); setNaming("new"); } },+ { label: "New Subscription", run: () => setSubscribing(true) },+ ]}+ />+ )}+ {groupMenu && (+ <RowMenu+ at={groupMenu.at}+ onClose={() => setGroupMenu(null)}+ entries={[+ { label: "Show All", run: () => showOnly(groupMenu.list, true) },+ { label: "Hide All", run: () => showOnly(groupMenu.list, false) },+ ]}+ />+ )}+ {moreMenu && (<RowMenu- at={calMenu.at}- onClose={() => setCalMenu(null)}+ at={moreMenu}+ onClose={() => setMoreMenu(null)}entries={[- { label: "Rename", run: () => setNaming(calMenu.cal.guid) },- {- label: "Colour",- submenu: CALENDAR_COLOURS.map(([hex, name]) => ({ label: name, run: () => updateCalendar(calMenu.cal, { colour: hex }) })),- },+ { label: "Go to Date", run: () => setGoingTo(true) },+ { label: "Show Week Numbers", checked: weekNumbers, run: () => setWeekNumbers(!weekNumbers) },null,- ...(calMenu.cal.isDefault ? [] : [{ label: "Delete Calendar", danger: true, run: () => deleteCalendar(calMenu.cal) }]),+ { label: "New Subscription", run: () => setSubscribing(true) },]}/>)}+ {eventMenu && (() => {+ const e = eventMenu.event;+ const mine = Boolean(byGuid.get(e.calendarGuid)?.writable);+ return (+ <RowMenu+ at={eventMenu.at}+ onClose={() => setEventMenu(null)}+ entries={[+ { label: mine ? "Edit" : "Show", run: () => openPicked(e) },+ ...(writable.length > 0 ? [+ { label: "Duplicate", run: () => void duplicate(e) },+ { label: "Copy", run: () => setClip(e) },+ ] : []),+ ...(mine && writable.length > 1 ? [{+ label: "Calendar",+ submenu: writable.map((c) => ({+ label: c.title,+ checked: c.guid === e.calendarGuid,+ run: () => { if (c.guid !== e.calendarGuid) void save({ ...draftOf(e), calendarGuid: c.guid }); },+ })),+ }] : []),+ ...(e.location ? [{ label: "Open in Maps", run: () => { window.location.href = mapsHref(e.location ?? ""); } }] : []),+ ...(mine ? [null, { label: "Delete", danger: true, run: () => void deleteAsking(e) }] : []),+ ]}+ />+ );+ })()}{view === "month" && (<MonthView@@ -1081,6 +1516,11 @@ export function CalendarView() {onOpen={openEvent}onCreate={createInMonth}onMore={showDay}+ canWrite={canWrite}+ onMoveDays={moveDays}+ onMenu={menuFor}+ picked={picked}+ weekNumbers={weekNumbers}/>)}@@ -1098,6 +1538,9 @@ export function CalendarView() {onMove={moveEvent}onPickDay={showDay}pending={pending}+ onMenu={menuFor}+ picked={picked}+ weekNumbers={weekNumbers}/>{view === "day" && (<DayPane@@ -1106,6 +1549,8 @@ export function CalendarView() {reminders={due}calendars={byGuid}onOpen={openEvent}+ onMenu={menuFor}+ week={weekNumbers ? weekNumber(startOfWeek(selected)) : null}>{/* As macOS 27's Day view sets it: the month above the day, to step across it. */}<MiniMonth@@ -1113,6 +1558,7 @@ export function CalendarView() {today={now}busy={busyOn}onPick={setSelected}+ weekNumbers={weekNumbers}/></DayPane>)}@@ -1134,8 +1580,12 @@ export function CalendarView() {draft={draft}at={anchor}calendars={calendars}- onChange={setDraft}+ onChange={changeDraft}onClose={() => setDraft(null)}+ onDeleteKey={draft.guid ? () => {+ const e = events.find((x) => x.guid === draft.guid);+ if (e) void deleteAsking(e);+ } : undefined}onDismiss={dismiss}onSave={() => void save(draft, true)}onDelete={draft.guid ? () => void remove(draft.guid as string) : undefined}@@ -1186,11 +1636,13 @@ const MiniMonth = memo(function MiniMonth({today,busy,onPick,+ weekNumbers = false,}: {selected: Date;today: Date;busy: (d: Date) => boolean;onPick: (d: Date) => void;+ weekNumbers?: boolean;}) {const [shown, setShown] = useState(() => new Date(selected.getFullYear(), selected.getMonth(), 1));useEffect(() => {@@ -1218,13 +1670,18 @@ const MiniMonth = memo(function MiniMonth({</button></span></div>- <div className="cx-minimonth-grid">+ <div className={`cx-minimonth-grid${weekNumbers ? " has-weeks" : ""}`}>+ {weekNumbers && <span className="cx-minimonth-wd" aria-hidden="true" />}{days.slice(0, 7).map((d) => (<span className="cx-minimonth-wd" key={`wd${d.getDay()}`} aria-hidden="true">{weekdayShort(d).slice(0, 1)}</span>))}{days.map((d, i) => (+ <Fragment key={i}>+ {weekNumbers && i % 7 === 0 && (+ <span className="cx-minimonth-wk" aria-label={`Week ${weekNumber(d)}`}>{weekNumber(d)}</span>+ )}<buttonkey={i}className={`cx-minimonth-day${d.getMonth() !== shown.getMonth() ? " is-out" : ""}${@@ -1235,6 +1692,7 @@ const MiniMonth = memo(function MiniMonth({>{d.getDate()}</button>+ </Fragment>))}</div></div>@@ -1258,6 +1716,11 @@ const MonthView = memo(function MonthView({onOpen,onCreate,onMore,+ canWrite,+ onMoveDays,+ onMenu,+ picked,+ weekNumbers,}: {days: Date[];selected: Date;@@ -1269,8 +1732,84 @@ const MonthView = memo(function MonthView({onOpen: (e: CalendarEvent, at: Anchor) => void;onCreate: (d: Date, at: Anchor) => void;onMore: (d: Date) => void;+ canWrite: (calendarGuid: string) => boolean;+ /** An event dragged to another day: moved that many days, its clock time kept. */+ onMoveDays: (e: CalendarEvent, days: number) => void;+ onMenu: (e: CalendarEvent, at: { x: number; y: number }) => void;+ picked: string | null;+ weekNumbers: boolean;}) {const listColour = useListColour();++ /*+ * Dragging an event to another day, as in Calendar's Month: pressed and moved a few pixels+ * it is carried, the day under the pointer is marked, and let go there it moves by that+ * many days. Followed from the window, and ended by a move with no button held — WebKitGTK+ * did not always deliver the release (see TimeGrid).+ */+ const [carry, setCarry] = useState<{ guid: string; over: number } | null>(null);+ const carried = useRef<{ event: CalendarEvent; from: number; x: number; y: number; over: number; moved: boolean } | null>(null);+ const swallowClick = useRef(false);+ const cellAt = (x: number, y: number) => {+ // Under whatever is drawn over the day — a bar, the event being carried.+ const el = document.elementsFromPoint(x, y).find((n) => n.hasAttribute("data-cell"));+ return el ? Number(el.getAttribute("data-cell")) : null;+ };+ const startCarry = (e: React.PointerEvent, event: CalendarEvent) => {+ if (e.button !== 0 || !canWrite(event.calendarGuid)) return;+ const from = cellAt(e.clientX, e.clientY);+ if (from === null) return;+ carried.current = { event, from, x: e.clientX, y: e.clientY, over: from, moved: false };+ const stop = () => {+ window.removeEventListener("pointermove", move);+ window.removeEventListener("pointerup", up);+ window.removeEventListener("blur", cancel);+ window.removeEventListener("keydown", key, true);+ };+ const finish = (commit: boolean) => {+ const c = carried.current;+ carried.current = null;+ stop();+ setCarry(null);+ if (!c?.moved) return;+ // The click that ends a drag is not a click on the event.+ swallowClick.current = true;+ window.setTimeout(() => (swallowClick.current = false), 0);+ if (commit && c.over !== c.from) onMoveDays(c.event, c.over - c.from);+ };+ const move = (ev: PointerEvent) => {+ const c = carried.current;+ if (!c) return;+ if (ev.buttons === 0) return finish(true);+ if (!c.moved && Math.hypot(ev.clientX - c.x, ev.clientY - c.y) < 5) return;+ const first = !c.moved;+ c.moved = true;+ const over = cellAt(ev.clientX, ev.clientY) ?? c.over;+ if (over !== c.over || first) {+ c.over = over;+ setCarry({ guid: c.event.guid, over });+ }+ };+ const up = () => finish(true);+ const cancel = () => finish(false);+ const key = (ev: KeyboardEvent) => {+ if (ev.key === "Escape" && carried.current?.moved) {+ ev.stopPropagation();+ finish(false);+ }+ };+ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", up);+ window.addEventListener("blur", cancel);+ window.addEventListener("keydown", key, true);+ };+ const eventHandlers = (event: CalendarEvent) => ({+ onPointerDown: (e: React.PointerEvent) => startCarry(e, event),+ onContextMenu: (e: React.MouseEvent) => {+ e.preventDefault();+ onMenu(event, { x: e.clientX, y: e.clientY });+ },+ });const cell = useRef<HTMLButtonElement | null>(null);const focused = useRef(false);const inMonth = selected.getMonth();@@ -1327,7 +1866,7 @@ const MonthView = memo(function MonthView({<span key={d.getDay()}>{weekdayShort(d)}</span>))}</div>- <div className="cal-grid" role="grid" aria-label="Month" ref={grid}>+ <div className={`cal-grid${carry ? " is-carrying" : ""}`} role="grid" aria-label="Month" ref={grid}>{weeks.map((row, w) => {const spans = weekSpans(events, row[0]);return (@@ -1347,15 +1886,20 @@ const MonthView = memo(function MonthView({: list;const more = list.length - visible.length;const isSelected = sameDay(day, selected);+ const cellIndex = w * 7 + i;return (<divclassName={`cx-day${day.getMonth() !== inMonth ? " is-out" : ""}${isWeekend(day) ? " is-weekend" : ""- }${isSelected ? " is-selected" : ""}`}+ }${isSelected ? " is-selected" : ""}${carry?.over === cellIndex ? " is-drop" : ""}`}role="gridcell"aria-selected={isSelected}+ data-cell={cellIndex}key={i}>+ {weekNumbers && i === 0 && (+ <span className="cx-weeknum" aria-label={`Week ${weekNumber(day)}`}>{weekNumber(day)}</span>+ )}<buttonref={isSelected ? cell : undefined}className="cx-day-hit"@@ -1378,13 +1922,14 @@ const MonthView = memo(function MonthView({item.kind === "event" ? (<li key={item.event.guid}><button- className="cx-item"+ className={`cx-item${picked === item.event.guid ? " is-picked" : ""}${carry?.guid === item.event.guid ? " is-carried" : ""}`}data-event={item.event.guid}+ {...eventHandlers(item.event)}style={{ "--cal": tint(calendars.get(item.event.calendarGuid)) } as React.CSSProperties}// Named in full, for the dot that is all a narrow cell shows.aria-label={`${item.event.title}, ${clock(item.event.startsAt)}`}title={dots ? `${item.event.title} · ${clock(item.event.startsAt)}` : undefined}- onClick={(e) => onOpen(item.event, { x: e.clientX, y: e.clientY })}+ onClick={(e) => !swallowClick.current && onOpen(item.event, { x: e.clientX, y: e.clientY })}><span className="cx-dot" aria-hidden="true" /><span className="cx-item-title">{item.event.title}</span>@@ -1419,9 +1964,11 @@ const MonthView = memo(function MonthView({{spans.map((s) => (<buttonkey={`${s.event.guid}-${dayKey(row[0])}`}+ data-event={s.event.guid}+ {...eventHandlers(s.event)}className={`cx-bar-event${s.continuesLeft ? " from-before" : ""}${s.continuesRight ? " to-after" : ""- }`}+ }${picked === s.event.guid ? " is-picked" : ""}${carry?.guid === s.event.guid ? " is-carried" : ""}`}style={{"--cal": tint(calendars.get(s.event.calendarGuid)),@@ -1430,7 +1977,7 @@ const MonthView = memo(function MonthView({top: `${26 + s.lane * LANE}px`,} as React.CSSProperties}- onClick={(e) => onOpen(s.event, { x: e.clientX, y: e.clientY })}+ onClick={(e) => !swallowClick.current && onOpen(s.event, { x: e.clientX, y: e.clientY })}>{s.event.title}</button>@@ -1450,8 +1997,9 @@ type Drag =| { kind: "create"; day: Date; column: number; anchor: number; from: number; to: number }/** `column` is the day the event was taken from, so it can be carried only to days shown. */| { kind: "move"; event: CalendarEvent; column: number; startX: number; startY: number; dx: number; dMinutes: number }- /** Dragging an event's bottom edge: its end moves, its start stays. */- | { kind: "resize"; event: CalendarEvent; startY: number; dMinutes: number };+ /** Dragging an event's bottom edge: its end moves, its start stays — or, by its top edge+ * (`top`), its start moves and its end stays. */+ | { kind: "resize"; event: CalendarEvent; startY: number; dMinutes: number; top?: boolean };const TimeGrid = memo(function TimeGrid({days,@@ -1465,6 +2013,9 @@ const TimeGrid = memo(function TimeGrid({onMove,onPickDay,pending,+ onMenu,+ picked,+ weekNumbers,}: {days: Date[];today: Date;@@ -1478,6 +2029,9 @@ const TimeGrid = memo(function TimeGrid({onPickDay: (d: Date) => void;/** A new event being named in the popover, held on the grid where it was made. */pending?: { startsAt: number; endsAt: number; title: string } | null;+ onMenu: (e: CalendarEvent, at: { x: number; y: number }) => void;+ picked: string | null;+ weekNumbers: boolean;}) {const listColour = useListColour();const scroller = useRef<HTMLDivElement | null>(null);@@ -1555,7 +2109,8 @@ const TimeGrid = memo(function TimeGrid({} else if (current.kind === "resize") {// Never shorter than a quarter hour, as Calendar holds it.const length = (current.event.endsAt - current.event.startsAt) / 60;- next = { ...current, dMinutes: Math.max(15 - length, snap(((clientY - current.startY) / HOUR) * 60)) };+ const by = snap(((clientY - current.startY) / HOUR) * 60);+ next = { ...current, dMinutes: current.top ? Math.min(length - 15, by) : Math.max(15 - length, by) };if (next.dMinutes === current.dMinutes) return;} else {const el = columnsEl.current;@@ -1581,7 +2136,10 @@ const TimeGrid = memo(function TimeGrid({onCreate(base + done.from * 60, base + done.to * 60, false, besideColumn(done.column, clientY));}} else if (done.kind === "resize") {- if (done.dMinutes !== 0) onMove(done.event, done.event.startsAt, done.event.endsAt + done.dMinutes * 60);+ if (done.dMinutes !== 0) {+ if (done.top) onMove(done.event, done.event.startsAt + done.dMinutes * 60, done.event.endsAt);+ else onMove(done.event, done.event.startsAt, done.event.endsAt + done.dMinutes * 60);+ }} else if (done.dx !== 0 || done.dMinutes !== 0) {const shift = done.dMinutes * 60;const moved = (t: number) => {@@ -1678,7 +2236,9 @@ const TimeGrid = memo(function TimeGrid({return (<div className={`cal-hours${days.length === 1 ? " is-day" : ""}`}><div className="cx-grid-head" style={{ "--cols": days.length } as React.CSSProperties}>- <span className="cx-gutter" aria-hidden="true" />+ <span className="cx-gutter cx-head-week" aria-hidden={!weekNumbers}>+ {weekNumbers ? `W${weekNumber(startOfWeek(days[0]))}` : ""}+ </span>{days.map((d, i) => (<buttonclassName={`cal-col-head${sameDay(d, today) ? " is-today" : ""}`}@@ -1699,7 +2259,11 @@ const TimeGrid = memo(function TimeGrid({<buttonkey={s.event.guid}data-event={s.event.guid}- className={`cx-bar-event${s.continuesLeft ? " from-before" : ""}${s.continuesRight ? " to-after" : ""}`}+ onContextMenu={(e) => {+ e.preventDefault();+ onMenu(s.event, { x: e.clientX, y: e.clientY });+ }}+ className={`cx-bar-event${s.continuesLeft ? " from-before" : ""}${s.continuesRight ? " to-after" : ""}${picked === s.event.guid ? " is-picked" : ""}`}style={{"--cal": tint(calendars.get(s.event.calendarGuid)),@@ -1765,12 +2329,16 @@ const TimeGrid = memo(function TimeGrid({<buttonkey={p.event.guid}data-event={p.event.guid}- className={`cx-block${moving || sizing ? " is-moving" : ""}${p.length < 45 ? " is-short" : ""}`}+ className={`cx-block${moving || sizing ? " is-moving" : ""}${p.length < 45 ? " is-short" : ""}${picked === p.event.guid ? " is-picked" : ""}`}+ onContextMenu={(e) => {+ e.preventDefault();+ onMenu(p.event, { x: e.clientX, y: e.clientY });+ }}style={{"--cal": tint(c),- top: `${((p.top + (moving?.dMinutes ?? 0)) / 60) * HOUR}px`,- height: `${Math.max(((p.length + (sizing?.dMinutes ?? 0)) / 60) * HOUR - 2, 20)}px`,+ top: `${((p.top + (moving?.dMinutes ?? 0) + (sizing?.top ? sizing.dMinutes : 0)) / 60) * HOUR}px`,+ height: `${Math.max(((p.length + (sizing ? (sizing.top ? -sizing.dMinutes : sizing.dMinutes) : 0)) / 60) * HOUR - 2, 20)}px`,left: `calc(${(p.column / p.columns) * 100}% + ${(moving?.dx ?? 0) * 100}%)`,width: `calc(${100 / p.columns}% - 3px)`,} as React.CSSProperties@@ -1795,6 +2363,18 @@ const TimeGrid = memo(function TimeGrid({<span className="cx-block-title">{p.event.title}</span><span className="cx-block-time">{clock(p.event.startsAt)}</span>{p.event.location && <span className="cx-block-where">{p.event.location}</span>}+ {canWrite(p.event.calendarGuid) && p.length >= 30 && (+ <span+ className="cx-block-grip is-top"+ aria-hidden="true"+ onPointerDown={(e) => {+ if (e.button !== 0) return;+ e.stopPropagation();+ e.preventDefault();+ setDragNow({ kind: "resize", event: p.event, startY: e.clientY, dMinutes: 0, top: true });+ }}+ />+ )}{canWrite(p.event.calendarGuid) && (<spanclassName="cx-block-grip"@@ -2099,6 +2679,7 @@ function EventPopover({onDismiss,onSave,onDelete,+ onDeleteKey,onNudge,view,}: {@@ -2111,6 +2692,8 @@ function EventPopover({onDismiss: () => void;onSave: () => void;onDelete?: () => void;+ /** Delete pressed outside the fields: asked first. */+ onDeleteKey?: () => void;onNudge?: (by: { days: number } | { minutes: number }) => void;view?: string;}) {@@ -2159,9 +2742,9 @@ function EventPopover({// Delete, as in Calendar: an open event goes when Delete is pressed outside its fields —// and Undo brings it back, since iCloud keeps no bin.const typing = (e.target as HTMLElement | null)?.closest("input, textarea, select, [contenteditable]");- if ((e.key === "Delete" || e.key === "Backspace") && !typing && onDelete && editable) {+ if ((e.key === "Delete" || e.key === "Backspace") && !typing && (onDeleteKey ?? onDelete) && editable) {e.preventDefault();- onDelete();+ (onDeleteKey ?? onDelete)?.();}};const onDown = (e: PointerEvent) => {@@ -2182,7 +2765,7 @@ function EventPopover({window.removeEventListener("keydown", onKey);window.removeEventListener("pointerdown", onDown, true);};- }, [onClose, onDismiss, onDelete, onNudge, editable, view, draft.allDay, draft.guid]);+ }, [onClose, onDismiss, onDelete, onDeleteKey, onNudge, editable, view, draft.allDay, draft.guid]);const set = (patch: Partial<Draft>) => onChange({ ...draft, ...patch });@@ -2208,7 +2791,12 @@ function EventPopover({onSubmit={(e) => { e.preventDefault(); onClose(); }}><h3 className="cx-info-title">{draft.title}</h3>- {draft.location && <p className="cx-info-line">{draft.location}</p>}+ {draft.location && (+ <p className="cx-info-line cx-info-place">+ {draft.location}+ <a className="cx-maps" href={mapsHref(draft.location)} title="Open in Maps">Open in Maps</a>+ </p>+ )}<p className="cx-info-line">{when}</p><p className="cx-info-cal"><span className="cx-info-dot" aria-hidden="true" />{calendar?.title}</p>{draft.url && (@@ -2242,14 +2830,21 @@ function EventPopover({readOnly={!editable}onChange={(e) => set({ title: e.target.value })}/>- <input- className="cx-pop-line"- value={draft.location}- placeholder="Add Location"- aria-label="Location"- readOnly={!editable}- onChange={(e) => set({ location: e.target.value })}- />+ <span className="cx-pop-place">+ <input+ className="cx-pop-line"+ value={draft.location}+ placeholder="Add Location"+ aria-label="Location"+ readOnly={!editable}+ onChange={(e) => set({ location: e.target.value })}+ />+ {draft.location.trim() && (+ <a className="cx-pop-link" href={mapsHref(draft.location.trim())} aria-label="Open in Maps" title="Open in Maps">+ <MapPin size={14} strokeWidth={2} aria-hidden="true" />+ </a>+ )}+ </span><div className="cx-pop-rows"><label className="cx-pop-row"><span>all-day</span>@@ -2342,7 +2937,7 @@ function EventPopover({if (v === "none") next.splice(n, 1);else next[n] = Number(v);// Any beyond the two shown (made on a Mac) are kept, never dropped by an edit here.- set({ alerts: next, alertsChanged: true });+ set({ alerts: next, alertsChanged: true, alertsDefault: false });}}options={alerts === undefined ? [{ value: "loading", label: "…" }] : options}/>@@ -2368,15 +2963,20 @@ function EventPopover({/></div></div>- <input- className="cx-pop-line"- type="url"- value={draft.url ?? ""}- placeholder="Add URL"- aria-label="URL"- readOnly={!editable}- onChange={(e) => set({ url: e.target.value || null })}- />+ <span className="cx-pop-place">+ <input+ className="cx-pop-line"+ type="url"+ value={draft.url ?? ""}+ placeholder="Add URL"+ aria-label="URL"+ readOnly={!editable}+ onChange={(e) => set({ url: e.target.value || null })}+ />+ {draft.url && /^(https?:\/\/|mailto:)/i.test(draft.url.trim()) && (+ <a className="cx-pop-link is-text" href={draft.url.trim()} target="_blank" rel="noreferrer">Open</a>+ )}+ </span><textareaclassName="cx-pop-notes"value={draft.notes}@@ -2421,6 +3021,8 @@ const DayPane = memo(function DayPane({reminders,calendars,onOpen,+ onMenu,+ week,children,}: {day: Date;@@ -2428,6 +3030,9 @@ const DayPane = memo(function DayPane({reminders: Reminder[];calendars: Map<string, Calendar>;onOpen: (e: CalendarEvent, at: Anchor) => void;+ onMenu: (e: CalendarEvent, at: { x: number; y: number }) => void;+ /** The week's number, when week numbers are shown. */+ week: number | null;children?: React.ReactNode;}) {const listColour = useListColour();@@ -2446,6 +3051,10 @@ const DayPane = memo(function DayPane({data-event={e.guid}style={{ "--cal": tint(calendars.get(e.calendarGuid)) } as React.CSSProperties}onClick={(ev) => onOpen(e, pointOf(ev.currentTarget))}+ onContextMenu={(ev) => {+ ev.preventDefault();+ onMenu(e, { x: ev.clientX, y: ev.clientY });+ }}><span className="cx-pane-title">{e.title}</span><span className="cx-pane-when">{when}</span>@@ -2458,7 +3067,10 @@ const DayPane = memo(function DayPane({<aside className="cx-pane" aria-label={dateText(day, { dateStyle: "full" })}>{children && <div className="cx-pane-month">{children}</div>}<h2 className="cx-pane-day">{dateText(day, { weekday: "long" })}</h2>- <p className="cx-pane-date">{dateText(day, { day: "numeric", month: "long", year: "numeric" })}</p>+ <p className="cx-pane-date">+ {dateText(day, { day: "numeric", month: "long", year: "numeric" })}+ {week !== null && <span className="cx-pane-week">Week {week}</span>}+ </p>{nothing ? (<p className="cx-pane-empty">Nothing on this day.</p>) : (@@ -2519,3 +3131,158 @@ function CalendarName({ initial, label, onDone, onCancel }: {/>);}++/** `text` with the words of `query` marked, as Calendar marks what a search matched. */+function Marked({ text, query }: { text: string; query: string }) {+ const words = query.trim().split(/\s+/).filter(Boolean).map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));+ if (!words.length) return <>{text}</>;+ const parts = text.split(new RegExp(`(${words.join("|")})`, "gi"));+ return <>{parts.map((p, i) => (i % 2 ? <mark key={i} className="cx-mark">{p}</mark> : <Fragment key={i}>{p}</Fragment>))}</>;+}++/**+ * Quick Event, under the + as Calendar's is: a line typed as it would be said, read here as it+ * is typed, and shown as the event it will make before Return makes it.+ */+function QuickEvent({ calendar, onAdd, onClose }: {+ calendar: Calendar | null;+ onAdd: (text: string, details: boolean, at: Anchor) => void;+ onClose: () => void;+}) {+ const [text, setText] = useState("");+ const box = useRef<HTMLFormElement | null>(null);+ const q = useMemo(() => (text.trim() ? parseQuick(text) : null), [text]);+ const at = (): Anchor => {+ const r = box.current?.getBoundingClientRect();+ return r ? { x: r.right - 300, y: r.top + 8, left: r.left } : { x: 40, y: 80 };+ };+ const start = q ? dateOf(q.startsAt) : null;+ const lastDay = q ? dateOf(q.allDay ? q.endsAt - 1 : q.endsAt) : null;+ const sameDayEnd = start && lastDay ? sameDay(start, lastDay) : true;+ const day = (d: Date) => dateText(d, { weekday: "long", day: "numeric", month: "long" });+ return (+ <form+ ref={box}+ className="popover cx-quick"+ role="dialog"+ aria-label="Quick Event"+ onSubmit={(e) => {+ e.preventDefault();+ onAdd(text, false, at());+ }}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ onClose();+ }+ }}+ onBlur={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) onClose();+ }}+ >+ <input+ className="field cx-quick-field"+ aria-label="Event, as you would say it"+ placeholder="Lunch with Asha tomorrow at 1pm"+ autoFocus+ value={text}+ onChange={(e) => setText(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.shiftKey || e.ctrlKey || e.metaKey)) {+ e.preventDefault();+ onAdd(text, true, at());+ }+ }}+ />+ {q && start && lastDay && (+ <div className="cx-quick-preview" aria-live="polite" style={{ "--cal": tint(calendar ?? undefined) } as React.CSSProperties}>+ <p className="cx-quick-title">{q.title || "New Event"}</p>+ <p className="cx-quick-when">+ <span>{day(start)}</span>+ <span className="cx-quick-time">+ {q.allDay+ ? sameDayEnd ? "All day" : `All day, until ${day(lastDay)}`+ : `${clock(q.startsAt)} – ${clock(q.endsAt)}${sameDayEnd ? "" : `, ${day(lastDay)}`}`}+ </span>+ </p>+ {(q.repeat || q.location) && (+ <p className="cx-quick-more">+ {q.repeat && (+ <span className="cx-quick-chip"><Repeat size={12} strokeWidth={2.2} aria-hidden="true" />{repeatText(q.repeat)}</span>+ )}+ {q.location && (+ <span className="cx-quick-chip"><MapPin size={12} strokeWidth={2.2} aria-hidden="true" />{q.location}</span>+ )}+ </p>+ )}+ <p className="cx-quick-cal"><span className="cx-dot" aria-hidden="true" />{calendar?.title}</p>+ </div>+ )}+ <div className="cx-quick-actions">+ <button type="button" className="quiet" onClick={() => onAdd(text, true, at())}>Details</button>+ <button type="submit" className="primary" disabled={!q?.title}>Add</button>+ </div>+ </form>+ );+}++/**+ * New Calendar Subscription: an address, fetched once now so a wrong one is said here, then+ * kept and refreshed on this computer. Read-only, as a subscription is.+ */+function SubscribeForm({ onDone, onCancel }: {+ onDone: (sub: CalendarSubscription) => void;+ onCancel: () => void;+}) {+ const [url, setUrl] = useState("");+ const [busy, setBusy] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ return (+ <form+ className="cx-subscribe"+ aria-label="New Calendar Subscription"+ onSubmit={(e) => {+ e.preventDefault();+ if (!url.trim() || busy) return;+ setBusy(true);+ setProblem(null);+ calendarFeedsApi.subscribe(url.trim()).then(+ (sub) => onDone(sub),+ (err) => {+ setBusy(false);+ setProblem(messageOf(err));+ },+ );+ }}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ onCancel();+ }+ }}+ >+ <label className="cx-subscribe-label" htmlFor="cx-subscribe-url">Subscribe to a calendar</label>+ <input+ id="cx-subscribe-url"+ className="field"+ type="url"+ inputMode="url"+ placeholder="webcal:// or https:// address"+ autoFocus+ spellCheck={false}+ value={url}+ disabled={busy}+ onChange={(e) => { setUrl(e.target.value); setProblem(null); }}+ />+ {problem ? (+ <p className="cx-subscribe-note is-problem" role="alert">{problem}</p>+ ) : (+ <p className="cx-subscribe-note">Skykeep reads it from that address and keeps it up to date.</p>+ )}+ <div className="cx-subscribe-actions">+ <button type="button" className="quiet" onClick={onCancel}>Cancel</button>+ <button type="submit" className="primary" disabled={!url.trim() || busy}>{busy ? "Subscribing…" : "Subscribe"}</button>+ </div>+ </form>+ );+}diff --git a/src/screens/calendar/model.ts b/src/screens/calendar/model.tsindex b2192bb..9b1a638 100644--- a/src/screens/calendar/model.ts+++ b/src/screens/calendar/model.ts@@ -323,3 +323,21 @@ export function addDaysIn(zone: string, s: number, days: number): number {const d = new Date(Date.UTC(w.y, w.m - 1, w.d + days));return instantIn(zone, { y: d.getUTCFullYear(), m: d.getUTCMonth() + 1, d: d.getUTCDate(), h: w.h, min: w.min });}++/**+ * The number of the week starting `weekStart`, as Calendar shows them: ISO 8601's where weeks+ * start on Monday (the week holding the year's first Thursday is 1), and elsewhere the week+ * holding 1 January is 1 — the US way, and the way a Sunday- or Saturday-first calendar counts.+ */+export function weekNumber(weekStart: Date, firstDay = WEEK.firstDay): number {+ const start = midnight(weekStart);+ if (firstDay === 1) {+ const thursday = addDays(start, (4 - start.getDay() + 7) % 7);+ const jan1 = new Date(thursday.getFullYear(), 0, 1);+ return Math.floor(Math.round((thursday.getTime() - jan1.getTime()) / 864e5) / 7) + 1;+ }+ // The week's last day decides the year it belongs to: the week holding 1 January is week 1.+ const last = addDays(start, 6);+ const firstWeek = startOfWeek(new Date(last.getFullYear(), 0, 1), firstDay);+ return Math.round((start.getTime() - firstWeek.getTime()) / (7 * 864e5)) + 1;+}diff --git a/src/screens/calendar/quick.ts b/src/screens/calendar/quick.tsnew file mode 100644index 0000000..0474a42--- /dev/null+++ b/src/screens/calendar/quick.ts@@ -0,0 +1,242 @@+/**+ * Quick Event, as Calendar reads one typed in a line: "Lunch with Asha tomorrow 1pm",+ * "Gym every Monday 7am", "Flight Fri 6:30–9". Read here, on this computer, word by word —+ * what names a day, a time, a length, a repeat or a place is taken out, and what is left is+ * the title.+ *+ * English only, as the words are. Anything not understood stays in the title, which the+ * preview shows before anything is saved.+ */+import type { EventRepeat } from "../../lib/ipc";++export type Quick = {+ title: string;+ location: string | null;+ /** Local times, unix seconds. An all-day event runs from midnight to the next. */+ startsAt: number;+ endsAt: number;+ allDay: boolean;+ repeat: EventRepeat | null;+ /** Whether a day or a time was read at all — with neither, it is the next hour today. */+ dated: boolean;+ timed: boolean;+};++const WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];+const MONTHS = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];+/** "mon", "tues", "thurs" and the rest, each to its day. */+const WEEKDAY_WORD = String.raw`(sun(?:day)?|mon(?:day)?|tue(?:s(?:day)?)?|wed(?:nesday)?|thu(?:r(?:s(?:day)?)?)?|fri(?:day)?|sat(?:urday)?)`;+const MONTH_WORD = String.raw`(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)`;+const weekdayOf = (w: string) => WEEKDAYS.findIndex((d) => d.startsWith(w.slice(0, 3)));+const monthOf = (w: string) => MONTHS.findIndex((m) => m.startsWith(w.slice(0, 3)));++/** A clock time: "1pm", "1:30 pm", "13:00", "7", "noon", "midnight". */+const TIME = String.raw`(noon|midday|midnight|\d{1,2}(?::\d{2}|\.\d{2})?\s*(?:a\.?m\.?|p\.?m\.?)?)`;+const DASH = String.raw`\s*(?:-|–|—|to|till|until)\s*`;++type Clock = { h: number; m: number; meridiem: "am" | "pm" | null };++function clockOf(raw: string): Clock | null {+ const t = raw.trim().toLowerCase();+ if (t === "noon" || t === "midday") return { h: 12, m: 0, meridiem: "pm" };+ if (t === "midnight") return { h: 0, m: 0, meridiem: "am" };+ const m = /^(\d{1,2})(?:[:.](\d{2}))?\s*(a\.?m\.?|p\.?m\.?)?$/.exec(t);+ if (!m) return null;+ const h = Number(m[1]);+ const min = m[2] ? Number(m[2]) : 0;+ if (min > 59) return null;+ const meridiem = m[3] ? (m[3][0] === "a" ? "am" : "pm") : null;+ if (meridiem ? h < 1 || h > 12 : h > 23) return null;+ return { h, m: min, meridiem };+}++/** Hours on a 24-hour clock. A bare hour with no am or pm is read as people mean one: 1 to 6+ * in the afternoon, 7 to 11 in the morning — "lunch at 1", "gym at 7". */+function hours24(c: Clock, guess: "am" | "pm" | null = null): number {+ const meridiem = c.meridiem ?? (c.h > 12 || c.h === 0 ? null : guess ?? (c.h >= 1 && c.h <= 6 ? "pm" : c.h === 12 ? "pm" : "am"));+ if (!meridiem) return c.h;+ if (meridiem === "am") return c.h === 12 ? 0 : c.h;+ return c.h === 12 ? 12 : c.h + 12;+}++const midnightOf = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());+const plusDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);+const secondsOf = (d: Date) => Math.floor(d.getTime() / 1000);++/** The next `weekday` after today (today itself only when `orToday`). */+function nextWeekday(today: Date, weekday: number, orToday: boolean) {+ const ahead = (weekday - today.getDay() + 7) % 7;+ return plusDays(today, ahead === 0 && !orToday ? 7 : ahead);+}++/** Whether a numeric date is written day first here ("24/10"), or month first ("10/24"). */+function dayFirst(): boolean {+ try {+ const parts = new Intl.DateTimeFormat(undefined, { day: "numeric", month: "numeric" }).formatToParts(new Date(2026, 9, 24));+ return parts.findIndex((p) => p.type === "day") < parts.findIndex((p) => p.type === "month");+ } catch {+ return true;+ }+}++export function parseQuick(text: string, now: Date = new Date(), dmy: boolean = dayFirst()): Quick {+ let rest = ` ${text.replace(/\s+/g, " ").trim()} `;+ const today = midnightOf(now);+ let day = null as Date | null;+ let start = null as Clock | null;+ let end = null as Clock | null;+ let minutes = null as number | null;+ let repeat = null as EventRepeat | null;+ let location = null as string | null;+ /** "Tonight": a bare hour is the evening's, and with none it is seven. */+ let evening = false;++ /** Take the first match of `re` out of what is left, and hand its groups to `use`. */+ const take = (re: RegExp, use: (m: RegExpExecArray) => boolean | void) => {+ const m = re.exec(rest);+ if (!m) return false;+ if (use(m) === false) return false;+ rest = `${rest.slice(0, m.index)} ${rest.slice(m.index + m[0].length)}`;+ return true;+ };+ const w = (body: string) => new RegExp(String.raw`(?<=\s)${body}(?=[\s,.!?]|$)`, "i");++ // Repeats: "every day", "daily", "every 2 weeks", "every Monday", "weekly", "every year".+ take(w(String.raw`(?:every|each)\s+` + WEEKDAY_WORD), (m) => {+ repeat = { freq: "weekly", interval: 1, count: null };+ day ??= nextWeekday(today, weekdayOf(m[1].toLowerCase()), true);+ }) ||+ take(w(String.raw`(?:every|each)\s+(?:(other|\d+)\s+)?(day|week|month|year)s?`), (m) => {+ const interval = m[1] ? (m[1].toLowerCase() === "other" ? 2 : Number(m[1])) : 1;+ if (!(interval >= 1 && interval <= 99)) return false;+ repeat = { freq: `${m[2].toLowerCase() === "day" ? "dai" : m[2].toLowerCase()}ly` as EventRepeat["freq"], interval, count: null };+ }) ||+ take(w(String.raw`(daily|weekly|monthly|yearly|annually)`), (m) => {+ const word = m[1].toLowerCase();+ repeat = { freq: (word === "annually" ? "yearly" : word) as EventRepeat["freq"], interval: 1, count: null };+ });++ // Days.+ take(w(String.raw`(?:on\s+)?(\d{4})-(\d{1,2})-(\d{1,2})`), (m) => {+ const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));+ if (d.getMonth() !== Number(m[2]) - 1) return false;+ day = d;+ }) ||+ take(w(String.raw`(?:on\s+)?(?:the\s+)?(\d{1,2})(?:st|nd|rd|th)?(?:\s+of)?\s+${MONTH_WORD}(?:,?\s+(\d{4}))?`), (m) => {+ day = dateIn(Number(m[1]), monthOf(m[2].toLowerCase()), m[3] ? Number(m[3]) : null, today);+ if (!day) return false;+ }) ||+ take(w(String.raw`(?:on\s+)?${MONTH_WORD}\.?\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s+(\d{4}))?`), (m) => {+ day = dateIn(Number(m[2]), monthOf(m[1].toLowerCase()), m[3] ? Number(m[3]) : null, today);+ if (!day) return false;+ }) ||+ take(w(String.raw`(?:on\s+)?(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?`), (m) => {+ const [a, b] = [Number(m[1]), Number(m[2])];+ const year = m[3] ? (m[3].length === 2 ? 2000 + Number(m[3]) : Number(m[3])) : null;+ day = dmy ? dateIn(a, b - 1, year, today) : dateIn(b, a - 1, year, today);+ if (!day) return false;+ }) ||+ take(w(String.raw`(?:the\s+)?day\s+after\s+tomorrow`), () => { day = plusDays(today, 2); }) ||+ take(w(String.raw`(today|tonight|tomorrow|tmrw|tmr|yesterday)`), (m) => {+ const word = m[1].toLowerCase();+ day = plusDays(today, word === "yesterday" ? -1 : word.startsWith("tom") || word.startsWith("tm") ? 1 : 0);+ if (word === "tonight") evening = true;+ }) ||+ take(w(String.raw`in\s+(\d{1,3}|a|one|two|three)\s+(day|week)s?`), (m) => {+ const n = { a: 1, one: 1, two: 2, three: 3 }[m[1].toLowerCase()] ?? Number(m[1]);+ day = plusDays(today, n * (m[2].toLowerCase() === "week" ? 7 : 1));+ }) ||+ take(w(String.raw`(?:(next|this|on)\s+)?${WEEKDAY_WORD}`), (m) => {+ const target = weekdayOf(m[2].toLowerCase());+ const which = m[1]?.toLowerCase();+ // "next Friday" is the Friday of next week when said early in the week, as people mean it.+ let d = nextWeekday(today, target, which === "this");+ if (which === "next" && (d.getTime() - today.getTime()) / 864e5 < 7 && target > today.getDay() && today.getDay() !== 0) d = plusDays(d, 7);+ day = d;+ }) ||+ take(w(String.raw`next\s+week`), () => { day = nextWeekday(today, 1, false); });++ // Times: a range, then one time, then a length.+ const atTime = String.raw`(?:at\s+|@\s*|from\s+)?`;+ take(w(atTime + TIME + DASH + TIME), (m) => {+ const a = clockOf(m[1]);+ const b = clockOf(m[2]);+ // "6:30–9" needs a number with a colon or am/pm somewhere, or "1-2" in a title is a range.+ if (!a || !b || !(/[:.apn]|noon|mid/i.test(m[0]) || /^(at|@|from)/i.test(m[0].trim()))) return false;+ start = a;+ end = b;+ }) ||+ take(w(String.raw`(?:at|@)\s*` + TIME), (m) => {+ const c = clockOf(m[1]);+ if (!c) return false;+ start = c;+ }) ||+ take(w(String.raw`(noon|midday|midnight|\d{1,2}(?:[:.]\d{2})?\s*(?:a\.?m\.?|p\.?m\.?)|\d{1,2}[:.]\d{2})`), (m) => {+ const c = clockOf(m[1]);+ if (!c) return false;+ start = c;+ });+ take(w(String.raw`for\s+(\d+(?:\.\d+)?|an?|half\s+an?)\s*(minutes?|mins?|m|hours?|hrs?|h)`), (m) => {+ const n = /half/i.test(m[1]) ? 0.5 : /^an?$/i.test(m[1]) ? 1 : Number(m[1]);+ minutes = Math.round(n * (/^h/i.test(m[2]) ? 60 : 1));+ if (!(minutes > 0 && minutes <= 14 * 24 * 60)) return false;+ });++ // A place: what follows "at" or "@" that is not a time.+ take(/\s(?:at|@)\s+([^,]+?)\s*$/i, (m) => {+ if (clockOf(m[1])) return false;+ location = m[1].trim();+ });++ const title = rest.replace(/\s+/g, " ").replace(/\s+([,.!?])/g, "$1").replace(/^[\s,–—-]+|[\s,–—-]+$/g, "").trim();+ if (evening) start = start ? { ...start, meridiem: start.meridiem ?? (start.h < 12 ? "pm" : null) } : { h: 7, m: 0, meridiem: "pm" };+ const dated = day !== null;+ const timed = start !== null;+ const base: Date = day ?? today;+ let startsAt: number;+ let endsAt: number;+ let allDay = false;+ if (start) {+ const s: Clock = start;+ const h = hours24(s);+ const from = new Date(base.getFullYear(), base.getMonth(), base.getDate(), h, s.m);+ // Today, a time already gone is tomorrow's — unless a day was named.+ if (!dated && from.getTime() < now.getTime() - 60_000) from.setDate(from.getDate() + 1);+ startsAt = secondsOf(from);+ if (end) {+ const e: Clock = end;+ // The end is read on the start's side of noon when it can be: "1-2pm" is 1 to 2 PM.+ const guess: "am" | "pm" = e.meridiem ?? (h >= 12 ? "pm" : "am");+ let eh = hours24(e, guess);+ if (!e.meridiem && eh < 12 && eh * 60 + e.m <= h * 60 + s.m) eh += 12;+ const to = new Date(from.getFullYear(), from.getMonth(), from.getDate(), eh, e.m);+ if (to.getTime() <= from.getTime()) to.setDate(to.getDate() + 1);+ endsAt = secondsOf(to);+ // "1pm-2" meant the start's side too; "11am–1" crosses noon.+ if (!s.meridiem && e.meridiem && endsAt - startsAt > 12 * 3600) startsAt += 12 * 3600;+ } else {+ endsAt = startsAt + (minutes ?? 60) * 60;+ }+ } else if (dated) {+ allDay = minutes === null;+ const d = base;+ startsAt = secondsOf(allDay ? d : new Date(d.getFullYear(), d.getMonth(), d.getDate(), 9));+ endsAt = allDay ? secondsOf(plusDays(d, 1)) : startsAt + (minutes ?? 60) * 60;+ } else {+ // Nothing said of when: the next whole hour, as a new event is.+ const next = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1);+ startsAt = secondsOf(next);+ endsAt = startsAt + (minutes ?? 60) * 60;+ }+ return { title, location, startsAt, endsAt, allDay, repeat, dated, timed };+}++/** A day of a month, this year or the next when it has already gone (a year named, that one). */+function dateIn(day: number, month: number, year: number | null, today: Date): Date | null {+ if (month < 0 || month > 11 || day < 1 || day > 31) return null;+ const y = year ?? today.getFullYear();+ let d = new Date(y, month, day);+ if (d.getMonth() !== month) return null;+ if (year === null && d < today) d = new Date(y + 1, month, day);+ return d;+}diff --git a/src/screens/notes/LockedNote.tsx b/src/screens/notes/LockedNote.tsxnew file mode 100644index 0000000..76d5d6f--- /dev/null+++ b/src/screens/notes/LockedNote.tsx@@ -0,0 +1,119 @@+import { useEffect, useRef, useState } from "react";+import { LockKeyhole } from "lucide-react";+import { messageOf, notesLockApi, type UnlockedNote } from "../../lib/ipc";+import { Spinner } from "../../components/Spinner";++/**+ * A locked note, as Notes shows one: a lock, one line, the password field and Unlock, the hint+ * when asked for. The password lives in this field only while it is typed — it is sent once,+ * then cleared, and never kept by the window (the backend holds it in memory for the session,+ * so the same note opens again without asking until Lock Now or quitting).+ */+export function LockScreen({+ guid,+ title,+ autoFocus,+ onOpen,+}: {+ guid: string;+ title: string;+ /** Into the password field at once — not while someone is moving through the list. */+ autoFocus: boolean;+ onOpen: (opened: UnlockedNote) => void;+}) {+ const field = useRef<HTMLInputElement | null>(null);+ const [password, setPassword] = useState("");+ const [busy, setBusy] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ /** undefined: not asked; null: there is none; a string: the hint. */+ const [hint, setHint] = useState<string | null | undefined>(undefined);+ const [hintBusy, setHintBusy] = useState(false);++ // Another note is another lock: nothing typed or said for one carries to the next.+ useEffect(() => {+ setPassword("");+ setProblem(null);+ setHint(undefined);+ setBusy(false);+ if (autoFocus) field.current?.focus();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [guid]);++ const unlock = async () => {+ if (!password || busy) return;+ const typed = password;+ // Out of the field the moment it is sent: nothing lingers in the page to be read later.+ setPassword("");+ setBusy(true);+ setProblem(null);+ try {+ const opened = await notesLockApi.noteUnlock(guid, typed);+ onOpen(opened);+ } catch (e) {+ const said = messageOf(e);+ setProblem(/password/i.test(said) ? "That password didn’t match. Try again." : said);+ setBusy(false);+ window.requestAnimationFrame(() => field.current?.focus());+ }+ };++ const showHint = async () => {+ setHintBusy(true);+ try {+ setHint((await notesLockApi.noteLockHint(guid)) ?? null);+ } catch (e) {+ setProblem(messageOf(e));+ } finally {+ setHintBusy(false);+ }+ };++ return (+ <div className="note-lock" role="group" aria-label={`${title || "Note"}, locked`}>+ <span className="note-lock-glyph" aria-hidden="true">+ <LockKeyhole size={26} strokeWidth={1.75} />+ </span>+ <h2 className="note-lock-title">This note is locked</h2>+ <p className="note-lock-lede">Enter the note’s password to read it.</p>+ <form+ className="note-lock-form"+ onSubmit={(e) => {+ e.preventDefault();+ void unlock();+ }}+ >+ <input+ ref={field}+ className="field note-lock-field"+ type="password"+ autoComplete="off"+ spellCheck={false}+ placeholder="Password"+ aria-label="Note password"+ aria-invalid={problem ? true : undefined}+ aria-describedby={problem ? "note-lock-problem" : undefined}+ value={password}+ disabled={busy}+ onChange={(e) => {+ setPassword(e.currentTarget.value);+ if (problem) setProblem(null);+ }}+ />+ <button type="submit" className="primary note-lock-open" disabled={!password || busy}>+ {busy ? <Spinner small /> : null}+ {busy ? "Unlocking…" : "Unlock"}+ </button>+ </form>+ <p id="note-lock-problem" className="note-lock-problem" role="alert">+ {problem ?? ""}+ </p>+ {hint === undefined ? (+ <button type="button" className="link note-lock-hint-ask" onClick={() => void showHint()} disabled={hintBusy}>+ Show Hint+ </button>+ ) : (+ <p className="note-lock-hint">{hint ? <>Hint: {hint}</> : "This note has no hint."}</p>+ )}+ </div>+ );+}diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsxindex 2514741..ef00c4c 100644--- a/src/screens/notes/NoteEditor.tsx+++ b/src/screens/notes/NoteEditor.tsx@@ -350,6 +350,8 @@ export type EditorHandle = {flushChange: () => void;/** What the editor holds this moment: its text and how it is set. */current: () => { text: string; runs: Run[] } | null;+ /** Where the cursor is, in UTF-16 units of `current().text`; null with no editor. */+ caret: () => number | null;};type Props = {@@ -781,6 +783,12 @@ export const NoteEditor = forwardRef<EditorHandle, Props>(function NoteEditor(if (later.current !== null) report();},current: () => (view.current ? fromDoc(view.current.state.doc) : null),+ caret: () => {+ const v = view.current;+ if (!v) return null;+ // The text up to the cursor, read the way the whole note is read, is how far in it is.+ return fromDoc(v.state.doc.cut(0, v.state.selection.head)).text.length;+ },}));const [cellMenu, setCellMenu] = useState<CellMenu | null>(null);diff --git a/src/screens/notes/attach.ts b/src/screens/notes/attach.tsnew file mode 100644index 0000000..b3f231d--- /dev/null+++ b/src/screens/notes/attach.ts@@ -0,0 +1,29 @@+import { useEffect, useState } from "react";+import { notesLockApi } from "../../lib/ipc";++/**+ * Whether a picture or file can be added to a note — the paperclip and dropping a file on the+ * note, both. It is the backend's switch and nothing else: `NOTE_ATTACH_WRITES` in+ * crates/quince-icloud/src/notes_attach.rs, reported by `note_attach_enabled`. While that is+ * false (or the command is missing) neither control exists, so turning the backend on is all+ * it takes to bring them in.+ */+let known: boolean | null = null;+let asking: Promise<boolean> | null = null;++export function useAttachEnabled(): boolean {+ const [on, setOn] = useState(known ?? false);+ useEffect(() => {+ if (known !== null) return setOn(known);+ let live = true;+ asking ??= notesLockApi.noteAttachEnabled().then((v) => (known = v));+ void asking.then((v) => live && setOn(v));+ return () => {+ live = false;+ };+ }, []);+ return on;+}++/** A path's last part, for saying what was added. */+export const fileName = (path: string) => path.split(/[\\/]/).pop() || path;diff --git a/src/screens/notes/rich.ts b/src/screens/notes/rich.tsindex 7c6e1fa..ca8a16d 100644--- a/src/screens/notes/rich.ts+++ b/src/screens/notes/rich.ts@@ -65,7 +65,7 @@ export const schema = new Schema({/** A block quote line. */quote: { default: false },},- // Read back exactly what toDOM writes, so a copy pasted within Pomander keeps each+ // Read back exactly what toDOM writes, so a copy pasted within Skykeep keeps each// line's style, tick, indent and numbering. A `<p>` from anywhere else has none of these// and stays plain body.parseDOM: [{ tag: "p", getAttrs: (d) => paragraphAttrs(d as HTMLElement) }],diff --git a/src/screens/photos/SharedAlbums.tsx b/src/screens/photos/SharedAlbums.tsxindex 6435254..f07315f 100644--- a/src/screens/photos/SharedAlbums.tsx+++ b/src/screens/photos/SharedAlbums.tsx@@ -73,8 +73,8 @@ export function SharedAlbums({ ask, onError }: { ask: (q: Question) => Promise<b</div></header>{albums !== null && n === 0 ? (- <EmptyState className="px-empty px-shared-empty" action={{ label: "New Shared Album", run: () => setNaming(true) }}>- No shared albums yet. Make one to share photos with the people you choose.+ <EmptyState className="px-empty px-shared-empty" icon={<Users size={28} strokeWidth={1.6} />} action={{ label: "New Shared Album", run: () => setNaming(true) }}>+ Share photos with the people you choose.</EmptyState>) : (<div className="px-cards" role="list" aria-busy={albums === null}>diff --git a/src/styles/app.css b/src/styles/app.cssindex 2a5e9eb..e0c3273 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -445,48 +445,23 @@cursor: pointer;}-.nav-item > svg { border-radius: 5.4px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.28), 0 0 0 0.5px rgba(0, 0, 0, 0.2); }-/* Apple's own icons come as a light and a dark picture; the theme shows one. */-.app-icon-apple { display: inline-grid; }-.app-icon-apple > img { grid-area: 1 / 1; width: 100%; height: 100%; display: block; }-.app-icon-apple > .ai-dark { display: none; }-@media (prefers-color-scheme: dark) {- :root:not([data-theme="light"]) .app-icon-apple > .ai-light { display: none; }- :root:not([data-theme="light"]) .app-icon-apple > .ai-dark { display: block; }-}-:root[data-theme="dark"] .app-icon-apple > .ai-light { display: none; }-:root[data-theme="dark"] .app-icon-apple > .ai-dark { display: block; }-/* The icon tiles: white in light mode; Apple's graphite in dark, as icloud.com draws them. */-.app-icon .ai-tile-top { stop-color: #ffffff; }-.app-icon .ai-tile-bottom { stop-color: #ececf0; }-.app-icon .ai-edge { stroke: rgba(0, 0, 0, 0.1); }-.app-icon .ai-rule { fill: #c7c7cc; }-.app-icon .ai-ink { fill: #1c1c1e; }-.app-icon .ai-card { fill: #8e8e93; }-.app-icon .ai-person { fill: #fff; }-.app-icon.ai-contacts .ai-tile-top { stop-color: #d8d8dc; }-.app-icon.ai-contacts .ai-tile-bottom { stop-color: #b8b8be; }+/* Each app's mark: one symbol in the app's colour (AppIcon), as a Mac sidebar draws its places.+ The tints are the system's own hues, a shade deeper in light mode so they hold on white. */+.app-icon { display: inline-grid; place-items: center; flex: none; }+:root {+ --app-notes: #c98a00; --app-reminders: #e8590c; --app-calendar: #e0313f;+ --app-contacts: #6e7480; --app-drive: #1f7ae0; --app-photos: #b34fd6;+}@media (prefers-color-scheme: dark) {- :root:not([data-theme="light"]) .app-icon .ai-tile-top { stop-color: #3a3a3e; }- :root:not([data-theme="light"]) .app-icon .ai-tile-bottom { stop-color: #1c1c1f; }- :root:not([data-theme="light"]) .app-icon .ai-edge { stroke: rgba(255, 255, 255, 0.14); }- :root:not([data-theme="light"]) .app-icon .ai-rule { fill: #5a5a60; }- :root:not([data-theme="light"]) .app-icon .ai-ink { fill: #f2f2f7; }- :root:not([data-theme="light"]) .app-icon .ai-card { fill: #636366; }- :root:not([data-theme="light"]) .app-icon .ai-person { fill: #e5e5ea; }- :root:not([data-theme="light"]) .app-icon.ai-contacts .ai-tile-top { stop-color: #3a3a3e; }- :root:not([data-theme="light"]) .app-icon.ai-contacts .ai-tile-bottom { stop-color: #1c1c1f; }+ :root:not([data-theme="light"]) {+ --app-notes: #ffd23f; --app-reminders: #ff8a4c; --app-calendar: #ff5a5f;+ --app-contacts: #aab1bd; --app-drive: #5ab0ff; --app-photos: #d38bff;+ }+}+:root[data-theme="dark"] {+ --app-notes: #ffd23f; --app-reminders: #ff8a4c; --app-calendar: #ff5a5f;+ --app-contacts: #aab1bd; --app-drive: #5ab0ff; --app-photos: #d38bff;}-/* The same, when Settings chooses Dark whatever the system says. */-:root[data-theme="dark"] .app-icon .ai-tile-top { stop-color: #3a3a3e; }-:root[data-theme="dark"] .app-icon .ai-tile-bottom { stop-color: #1c1c1f; }-:root[data-theme="dark"] .app-icon .ai-edge { stroke: rgba(255, 255, 255, 0.14); }-:root[data-theme="dark"] .app-icon .ai-rule { fill: #5a5a60; }-:root[data-theme="dark"] .app-icon .ai-ink { fill: #f2f2f7; }-:root[data-theme="dark"] .app-icon .ai-card { fill: #636366; }-:root[data-theme="dark"] .app-icon .ai-person { fill: #e5e5ea; }-:root[data-theme="dark"] .app-icon.ai-contacts .ai-tile-top { stop-color: #3a3a3e; }-:root[data-theme="dark"] .app-icon.ai-contacts .ai-tile-bottom { stop-color: #1c1c1f; }.nav-name { overflow: hidden; text-overflow: ellipsis; }.sidebar-head { display: flex; align-items: center; justify-content: space-between; margin: 0 0 6px; min-height: 28px; }.sidebar-head h2 { margin: 0 8px; }@@ -878,7 +853,7 @@border-radius: 8px; background: #fff; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3), 0 0 0 0.5px rgba(0, 0, 0, 0.2);}.drive-peek-name { margin: 0; font-size: var(--t-15); font-weight: 600; overflow-wrap: anywhere; }-.drive-peek-facts { margin: 0; color: var(--text-2); font-size: var(--t-12, 12px); }+.drive-peek-facts { margin: 0; color: var(--text-2); font-size: var(--t-13); }.drive-peek-actions { display: flex; gap: 8px; justify-content: center; margin-top: 12px; }/* Grid, as icloud.com and Finder's icon view lay it out: a large mark, the name under it intwo lines at most, the size and date left to List. Actions stay on hover, over the tile. */@@ -897,7 +872,7 @@.drive-rows.is-grid .drive-badge { height: 52px; transform: scale(2.1); transform-origin: center; }.drive-rows.is-grid .drive-name {display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;- overflow: hidden; white-space: normal; word-break: break-word; font-size: var(--t-12, 12px); line-height: 1.3;+ overflow: hidden; white-space: normal; word-break: break-word; font-size: var(--t-13); line-height: 1.3;}.drive-rows.is-grid .drive-meta { display: none; }.drive-rows.is-grid .drive-row-actions {@@ -1246,6 +1221,40 @@/* Apple's label picked from a list; a custom one typed under it, in the same column. */.contact-label-cell { display: flex; flex-direction: column; gap: 4px; min-width: 0; }+/* A postal address being written: its kind and label on the line of every other detail, the+ parts beneath under the label, as Contacts on the Mac sets them — street over as many lines+ as it takes, then town, region and postcode side by side, then the country. */+.contact-address-rows { padding-top: 6px; border-top: 1px solid var(--separator); }+.contact-method-rows li.contact-address-edit {+ grid-template-columns: 96px 112px minmax(0, 1fr) auto;+ row-gap: 6px;+ align-items: center;+}+.contact-address-kind { font-size: var(--t-13); color: var(--text-2); padding-left: 8px; }+.contact-address-fields {+ grid-column: 2 / 4;+ display: flex;+ flex-direction: column;+ gap: 6px;+ min-width: 0;+}+.contact-form .contact-address-street { resize: none; line-height: 1.35; }+.contact-address-line {+ display: grid;+ grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr) minmax(0, 0.9fr);+ gap: 6px;+}+.contact-address-rows li + li { padding-top: 10px; border-top: 1px solid var(--separator); }+.contact-form-adds { display: flex; flex-wrap: wrap; gap: 4px 12px; }++/* Under an address, the one way to see it on a map. */+.contact-maps {+ display: inline-block;+ margin-top: 3px;+ font-size: var(--t-13);+}+.contact-postal dd { display: flex; flex-direction: column; align-items: flex-start; }+.move-sheet-list {flex: 1;min-height: 120px;@@ -1535,14 +1544,14 @@.contact-letter {position: sticky; top: 0; z-index: 1; padding: 10px 10px 4px;background: var(--bg); color: var(--text-3);- font-size: var(--t-12, 12px); font-weight: 600;+ font-size: var(--t-13); font-weight: 600;border-bottom: 1px solid var(--separator);}/* The column headings, in the rows' own grid, quiet until one is the order. */.drive-head { border-bottom: 1px solid var(--separator); border-radius: 0; }.drive-head:hover { background: none; }.drive-head .drive-row-hit { cursor: default; padding-block: 4px; }-.drive-col { padding: 0; border: 0; background: none; box-shadow: none; color: var(--text-3); font: inherit; font-size: var(--t-12, 12px); text-align: left; cursor: pointer; }+.drive-col { padding: 0; border: 0; background: none; box-shadow: none; color: var(--text-3); font: inherit; font-size: var(--t-13); text-align: left; cursor: pointer; }.drive-col.is-on { color: var(--text-2); font-weight: 600; }.drive-col:hover { color: var(--text); }.drive-kind { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }diff --git a/src/styles/calendar.css b/src/styles/calendar.cssindex 2698b6f..9bafdfe 100644--- a/src/styles/calendar.css+++ b/src/styles/calendar.css@@ -721,3 +721,109 @@.cx-zone-region { color: var(--text-3); font-size: var(--t-11); }.cx-zone-option.is-lit { background: var(--accent); color: var(--on-accent, #fff); }.cx-zone-option.is-lit .cx-zone-region, .cx-zone-option.is-lit .cx-zone-offset { color: inherit; opacity: 0.8; }++/* ---- sidebar groups: iCloud, Subscriptions, Other — each folds away -------------------- */++.cx-group { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; }+.cx-group:first-child { margin-top: 0; }+.cx-group .cx-side-heading {+ display: inline-flex; align-items: center; gap: 4px; margin: 0; padding: 2px 8px 2px 4px; border: 0;+ border-radius: 6px; background: none; box-shadow: none; font: inherit; font-size: var(--t-11); font-weight: 600;+ color: var(--text-3); cursor: default;+}+.cx-group .cx-side-heading:hover { color: var(--text-2); }+.cx-group .cx-side-heading:focus-visible { outline: var(--focus-ring); outline-offset: -1px; }+.cx-fold { flex: none; transition: transform 120ms ease; }+.cx-side-heading[aria-expanded="false"] .cx-fold { transform: rotate(-90deg); }+@media (prefers-reduced-motion: reduce) { .cx-fold { transition: none; } }+.cx-cal-problem {+ flex: none; display: grid; place-items: center; width: 15px; height: 15px; border-radius: 50%;+ background: color-mix(in srgb, var(--sys-orange, #ff9500) 22%, transparent); color: var(--sys-orange, #c76b00);+ font-size: 10px; font-weight: 700;+}++/* New Calendar Subscription: a small panel in the sidebar, where the subscription will be. */+.cx-subscribe {+ display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding: 10px;+ border-radius: 10px; background: color-mix(in srgb, var(--text) 5%, transparent);+}+.cx-subscribe-label { font-size: var(--t-13); font-weight: 600; }+.cx-subscribe .field { width: 100%; min-width: 0; }+.cx-subscribe-note { margin: 0; color: var(--text-3); font-size: var(--t-11); line-height: 1.35; }+.cx-subscribe-note.is-problem { color: var(--sys-red); }+.cx-subscribe-actions { display: flex; justify-content: flex-end; gap: 6px; }++/* ---- Quick Event --------------------------------------------------------------------- */++/* Under the +, opaque and simply there, as the other popovers are (no fade: WebKitGTK). */+.cx-quick-anchor { position: relative; }+.cx-quick {+ background: var(--sheet, var(--glass-thick));+ position: absolute; top: calc(100% + 6px); right: -8px; z-index: 35;+ display: flex; flex-direction: column; gap: 10px; width: min(340px, calc(100vw - 32px)); padding: 12px;+}+.cx-quick-field { width: 100%; height: 32px; font-size: var(--t-15); }+/* What the line will make: the event as its block would read, a rule in its calendar's+ colour down the side — the one moment of colour in the panel. */+.cx-quick-preview {+ display: flex; flex-direction: column; gap: 3px; padding: 8px 10px 9px 12px;+ border-left: 3px solid var(--cal); border-radius: 4px 8px 8px 4px;+ background: color-mix(in srgb, var(--cal) 10%, transparent);+}+.cx-quick-preview p { margin: 0; }+.cx-quick-title { font-size: var(--t-15); font-weight: 700; overflow-wrap: anywhere; }+.cx-quick-when { display: flex; flex-wrap: wrap; gap: 2px 8px; font-size: var(--t-13); }+.cx-quick-time { color: var(--text-2); font-variant-numeric: tabular-nums; }+.cx-quick-more { display: flex; flex-wrap: wrap; gap: 6px; padding-top: 3px; }+.cx-quick-chip {+ display: inline-flex; align-items: center; gap: 4px; max-width: 100%; padding: 1px 7px; border-radius: 999px;+ background: color-mix(in srgb, var(--text) 7%, transparent); color: var(--text-2); font-size: var(--t-11);+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+}+.cx-quick-cal { display: flex; align-items: center; gap: 6px; padding-top: 2px; color: var(--text-3); font-size: var(--t-11); }+.cx-quick-actions { display: flex; justify-content: flex-end; gap: 6px; }++/* ---- search results: coming up, then earlier; the words found marked ------------------- */++.cx-found-row { grid-template-columns: 10px minmax(0, 1fr) auto; }+.cx-found-row.is-lit { background: color-mix(in srgb, var(--text) 8%, transparent); }+.cx-found-row:hover { background: color-mix(in srgb, var(--text) 8%, transparent); }+.cx-found-text { display: flex; flex-direction: column; min-width: 0; }+.cx-found-where { overflow: hidden; color: var(--text-3); font-size: var(--t-11); text-overflow: ellipsis; white-space: nowrap; }+.cx-found-section { margin: 6px 10px 2px; color: var(--text-3); font-size: var(--t-11); font-weight: 600; }+.cx-mark { border-radius: 2px; background: color-mix(in srgb, var(--sys-yellow, #ffcc00) 45%, transparent); color: inherit; }++/* ---- week numbers --------------------------------------------------------------------- */++.cx-weeknum {+ position: absolute; top: 7px; left: 6px; z-index: 1; color: var(--text-3);+ font-size: var(--t-11); font-variant-numeric: tabular-nums; pointer-events: none;+}+.cx-minimonth-grid.has-weeks { grid-template-columns: 16px repeat(7, 1fr); }+.cx-minimonth-wk { align-self: center; color: var(--text-3); font-size: 9px; font-variant-numeric: tabular-nums; text-align: left; }+.cx-head-week { display: flex; align-items: flex-end; justify-content: flex-end; padding: 0 8px 6px 0; color: var(--text-3); font-size: var(--t-11); font-variant-numeric: tabular-nums; }+.cx-pane-week { margin-left: 8px; color: var(--text-3); }++/* ---- the picked event, and one being carried to another day ---------------------------- */++.cx-block.is-picked, .cx-bar-event.is-picked { box-shadow: inset 0 0 0 1.5px var(--cal); }+.cx-item.is-picked { background: color-mix(in srgb, var(--cal, var(--text)) 18%, transparent); }+.cx-item.is-carried, .cx-bar-event.is-carried { opacity: 0.45; }+.cal-grid.is-carrying { cursor: grabbing; }+.cal-grid.is-carrying .cx-item, .cal-grid.is-carrying .cx-bar-event { pointer-events: none; }+.cx-day.is-drop { background: color-mix(in srgb, var(--sys-blue) 12%, transparent); box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--sys-blue) 55%, transparent); }+.cx-block-grip.is-top { top: 0; bottom: auto; height: 4px; }++/* ---- places and links in the popover ---------------------------------------------------- */++.cx-pop-place { display: flex; align-items: center; gap: 6px; min-width: 0; }+.cx-pop-place > input { flex: 1; min-width: 0; }+.cx-pop-link {+ flex: none; display: inline-grid; place-items: center; min-width: 22px; height: 22px; padding: 0 4px;+ border-radius: 6px; color: var(--sys-blue); font-size: var(--t-11); text-decoration: none;+}+.cx-pop-link:hover { background: color-mix(in srgb, var(--sys-blue) 12%, transparent); }+.cx-pop-link:focus-visible { outline: var(--focus-ring); }+.cx-info-place { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; }+.cx-maps { color: var(--sys-blue); font-size: var(--t-11); text-decoration: none; }+.cx-maps:hover { text-decoration: underline; }diff --git a/src/styles/intake.css b/src/styles/intake.cssindex cdd7fdc..9168eb9 100644--- a/src/styles/intake.css+++ b/src/styles/intake.css@@ -1,4 +1,4 @@-/* ── Import sheet: a file opened with Pomander (components/ImportSheet.tsx) ─────────────── */+/* ── Import sheet: a file opened with Skykeep (components/ImportSheet.tsx) ─────────────── *//* Under the menus (z-index 80), so its calendar picker opens over it. */.modal-veil.ix-veil { z-index: 70; }diff --git a/src/styles/notes.css b/src/styles/notes.cssindex 55c99e0..8a88708 100644--- a/src/styles/notes.css+++ b/src/styles/notes.css@@ -46,14 +46,12 @@.note-rows { flex: 1; min-height: 0; overflow-y: auto; margin: 0 -4px; padding: 0 4px 12px; }-/* A group's heading, as Notes writes "Today" or "Previous 7 Days" over the list. */+/* A group's heading, as Notes writes "Today" or "Previous 7 Days" over the list. It scrolls+ with its notes: held at the top it needed an opaque band of its own, and over the pane's+ glass that band showed as a stripe of a different grey. */.notes-section {- position: sticky;- top: 0;- z-index: 1;- margin: 10px 0 2px;+ margin: 14px 0 2px;padding: 4px 10px;- background: var(--bg);color: var(--text);font-size: var(--t-13);font-weight: 700;@@ -88,12 +86,17 @@.note-rows:focus-within .note-row[aria-current="true"] .note-row-snippet { color: var(--on-accent-2); }.note-row:focus-visible { outline: 3px solid var(--accent-ring); outline-offset: -1px; }.note-row-title {- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;+ display: flex;+ align-items: center;+ gap: 5px;+ min-width: 0;font-size: var(--t-13);font-weight: 700;}+.note-row-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+/* A locked note keeps its title in the list, as Notes shows it, with a small lock before it. */+.note-row-lock { flex: none; color: var(--text-2); }+.note-rows:focus-within .note-row[aria-current="true"] .note-row-lock { color: var(--on-accent); }.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); }@@ -105,18 +108,29 @@display: flex;align-items: center;gap: 10px;+ /* As tall with its tools as without (a locked note has none): the date never jumps. */+ min-height: calc(var(--h-tool) + 12px);padding: 0 18px 12px 0;}/* The date the note was last changed, centred and quiet over the text, as Notes sets it. */.note-when {flex: 1;+ min-width: 0;margin: 0;+ /* One line beside the tools: cut short in a narrow pane, never stacked four lines deep. */+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;color: var(--text-3);font-size: var(--t-11);text-align: center;}.notes-list-head { padding: 0 4px 10px; }.notes-search { margin-bottom: 8px; }+/* Where a search looks, once something is typed inside a folder: everywhere, or that folder. */+.notes-scope { display: flex; margin: -2px 0 8px; }+.notes-scope .segment { flex: 1; min-width: 0; }+.notes-scope-name { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.note-bar-actions .picker { max-width: 170px; }.note-editor {@@ -197,12 +211,12 @@ textarea.note-title::placeholder { color: var(--text-3); }.nf-mark { color: var(--text-2); text-align: left; font-variant-numeric: tabular-nums; }.nf-check { align-items: center; }.nf-circle {- width: 17px; height: 17px; padding: 0; border: 1.5px solid var(--text-3); border-radius: 50%;- background: none; box-shadow: none; cursor: pointer; transition: background 120ms ease, border-color 120ms ease;+ width: 18px; height: 18px; padding: 0; border: 0; background: var(--text-3); box-shadow: none; cursor: pointer;+ -webkit-mask: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='8.25' fill='none' stroke='black' stroke-width='1.5'/></svg>") center/18px 18px no-repeat; mask: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='8.25' fill='none' stroke='black' stroke-width='1.5'/></svg>") center/18px 18px no-repeat;}.nf-check.is-done .nf-circle {- border-color: var(--accent); background: var(--accent)- url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path d='M4 8.2l2.6 2.6L12 5.4' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>") center/12px no-repeat;+ background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><path d='M5 9.3l2.7 2.7L13 6.6' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>") center/18px 18px no-repeat, var(--accent);+ -webkit-mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='9'/></svg>"); mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='9'/></svg>");}.nf-check.is-done > span:last-child { color: var(--text-3); }.note-formatted a { color: var(--accent-strong); text-decoration: underline; }@@ -260,15 +274,18 @@ textarea.note-title::placeholder { color: var(--text-3); }.note-rich .nf-p[data-style="102"] { counter-increment: nf-num; }.note-rich .nf-p[data-style="102"]::before { content: counter(nf-num) "."; }/* A checklist item's circle: clicking it ticks the line (the editor reads the click). */+/* A checklist circle, crisp as Notes draws it: an 18px vector ring masked over the theme's colour+ and set on whole pixels. The CSS border it replaced was 17px with a 1.5px edge at a fractional+ offset, so every edge fell between pixels and blurred. */.note-rich .nf-p[data-style="103"]::before {- content: ""; position: absolute; inset-inline-start: calc(var(--indent, 0) * 1.5em); top: 0.3em;- width: 17px; height: 17px; box-sizing: border-box; border: 1.5px solid var(--text-3); border-radius: 50%;- cursor: pointer; transition: background-color 120ms ease, border-color 120ms ease;+ content: ""; position: absolute; inset-inline-start: calc(var(--indent, 0) * 1.5em); top: round(0.28em, 1px);+ width: 18px; height: 18px; background: var(--text-3);+ -webkit-mask: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='8.25' fill='none' stroke='black' stroke-width='1.5'/></svg>") center/18px 18px no-repeat; mask: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='8.25' fill='none' stroke='black' stroke-width='1.5'/></svg>") center/18px 18px no-repeat;+ cursor: pointer;}.note-rich .nf-p[data-style="103"][data-checked="true"]::before {- border-color: var(--accent);- background: var(--accent)- url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path d='M4 8.2l2.6 2.6L12 5.4' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>") center/12px no-repeat;+ background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><path d='M5 9.3l2.7 2.7L13 6.6' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>") center/18px 18px no-repeat, var(--accent);+ -webkit-mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='9'/></svg>"); mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18'><circle cx='9' cy='9' r='9'/></svg>");}.note-rich .nf-p[data-style="103"][data-checked="true"] { color: var(--text-3); }/* A table, drawing, picture or scan on a checklist line stands on its own, full width, as Notes@@ -452,3 +469,50 @@ textarea.note-title::placeholder { color: var(--text-3); }/* An attachment not yet known takes no room and says nothing until it is drawn. */.note-rich .nf-attachment.is-pending { padding: 0; margin: 0; background: none; }++/* ---- a locked note ------------------------------------------------------------------+ Calm, as Notes shows one: a lock, one line, the password and Unlock, centred a little above+ the middle of the pane. Nothing moves. */+.note-lock {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 6px;+ padding: 24px 18px 12vh 0;+ text-align: center;+}+.note-lock-glyph {+ display: grid;+ place-items: center;+ width: 60px;+ height: 60px;+ margin-bottom: 10px;+ border-radius: 50%;+ background: color-mix(in srgb, var(--accent) 16%, transparent);+ color: var(--accent-strong);+}+.note-lock-title { margin: 0; color: var(--text); font-size: 17px; font-weight: 650; letter-spacing: -0.01em; }+.note-lock-lede { margin: 0 0 12px; color: var(--text-2); font-size: var(--t-13); }+.note-lock-form { display: flex; flex-direction: column; gap: 8px; width: min(100%, 248px); }+.note-lock-field { width: 100%; text-align: center; }+.note-lock-field::placeholder { text-align: center; }+.note-lock-open { display: inline-flex; align-items: center; justify-content: center; gap: 8px; width: 100%; }+/* The line a wrong password leaves: room kept for it, so nothing below shifts when it comes. */+.note-lock-problem { min-height: 1.4em; margin: 2px 0 0; color: var(--danger); font-size: var(--t-13); }+.note-lock-hint-ask { font-size: var(--t-13); }+.note-lock-hint { max-width: 36ch; margin: 0; color: var(--text-2); font-size: var(--t-13); overflow-wrap: anywhere; }+.note-editor.is-unlocked .note-title { margin-bottom: 10px; }+.note-lock-now { gap: 6px; }++/* A file over the note, ready to drop: the pane outlined in the accent. No motion. */+.note-body.is-dropping { outline: 2px dashed color-mix(in srgb, var(--accent) 70%, transparent); outline-offset: -6px; border-radius: 12px; }++/* An empty list says so in the middle of the pane, not under an empty scroller at its foot. */+.note-rows:empty { display: none; }+.notes-list > .notes-empty { flex: 1; justify-content: center; padding-bottom: 18vh; }+/* A note pane too narrow for the date beside its tools leaves the date out rather than cut it+ to "Septe…"; the list beside it says when, too. "Saving…" and "Waiting to sync" always show. */+.note-body { container-type: inline-size; }+@container (max-width: 460px) { .note-bar:has(.note-bar-actions) .note-when.is-date { visibility: hidden; } }diff --git a/src/styles/photos.css b/src/styles/photos.cssindex 5d51e05..e036e43 100644--- a/src/styles/photos.css+++ b/src/styles/photos.css@@ -95,7 +95,25 @@overflow-y: auto;/* Room for the header floating over it, however many rows it takes (--bar, measured). */padding: calc(var(--bar, 68px) + 12px) 2px 24px;+ /* A photo brought into view by a key lands below the floating header, never under it. */+ scroll-padding-top: calc(var(--bar, 68px) + 8px);+ position: relative;+ /* Its size is its column's, never its photos': said outright, a change in the header (a+ selection's "3 Photos Selected") no longer has the engine lay out every built month again+ to find out. A click that selects went from ~80 ms of work to ~20 in WebKit. */+ contain: strict;+}+/* The rectangle swept out to select (see sweepStart): drawn by paint where it lies, never moved+ as a layer. */+.px-sweep {+ position: absolute;+ z-index: 2;+ border: 1px solid var(--accent);+ border-radius: 2px;+ background: color-mix(in srgb, var(--accent) 14%, transparent);+ pointer-events: none;}+.px-sweep[hidden] { display: none; }.px-bar { isolation: isolate; }.px-bar::before {content: "";@@ -123,6 +141,8 @@0 0 / calc(100% / var(--across, 7)) calc(100% / var(--rows));}.px-scroll[data-fit] .px-later { --gap: 14px; --pad: 14px; }+/* The rest of a month being built, under the rows already built: one gap between, as in the grid. */+.px-grid + .px-later { margin-top: var(--gap); }.px-month-title {margin: 0;padding: 12px 16px 8px;@@ -274,25 +294,44 @@.px-nav:active { transform: scale(0.92); }.px-nav.is-prev { left: 14px; }.px-nav.is-next { right: 14px; }-/* Info: a floating glass card over the photo's right side, as Photos' inspector floats. */+/* Info: a floating card at the photo's right, as Photos' inspector floats. The photo, its next+ arrow and the filmstrip make room for it at once (no glide), so it never covers the photo. */.px-info {position: absolute;z-index: 2;top: 58px;right: 14px;- width: 260px;- max-height: calc(100% - 72px);+ width: 268px;+ display: flex;+ flex-direction: column;+ gap: 14px;+ height: fit-content;+ max-height: calc(100% - 58px - 68px);margin: 0;- padding: 12px 16px 14px;+ padding: 14px 16px 16px;border-radius: var(--r-float);background: var(--glass-thick);box-shadow: var(--glass-float);font-size: var(--t-13);overflow-y: auto;}-.px-info dt { margin-top: 10px; color: var(--text-2); font-size: var(--t-11); font-weight: 600; }-.px-info dt:first-child { margin-top: 0; }-.px-info dd { margin: 2px 0 0; overflow-wrap: anywhere; }+/* Info takes its room by narrowing the stage itself, not by padding inside it: the photo is sized+ in the stage's container units, and WebKit did not size it again when only the padding grew —+ the photo ran on under the panel. */+.px-viewer.has-info .px-stage { margin-right: 232px; }+.px-viewer.has-info .px-nav.is-next { right: 296px; }+/* The filmstrip keeps the window's width, centred under the photo; Info stops above it. */+.px-viewer.has-info .px-strip-run { left: calc(50% - 141px); }+/* Each group under a hairline: the line says where one kind of fact ends. */+.px-info > * + * { padding-top: 12px; border-top: 1px solid var(--separator); }+.px-info-when { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }+.px-info-when > div, .px-info-file { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+.px-info-when strong, .px-info-file strong { font-weight: 600; overflow-wrap: anywhere; }+.px-info-when span, .px-info-file span { color: var(--text-2); font-size: var(--t-12, 12px); font-variant-numeric: tabular-nums; }+.px-facts { display: flex; flex-direction: column; gap: 12px; margin: 0; }+.px-fact dt { color: var(--text-2); font-size: var(--t-11); font-weight: 600; }+.px-fact dd { margin: 3px 0 0; overflow-wrap: anywhere; }+.px-caption-row + * { border-top: 0; padding-top: 0; }.px-video {position: relative;display: grid;@@ -369,7 +408,7 @@.px-show-count { padding: 0 10px; font-size: var(--t-13); font-variant-numeric: tabular-nums; color: rgba(255, 255, 255, 0.75); }/* The caption, typed in place at the head of Info, as Photos has it. */-.px-caption-row { margin: 0 0 4px; }+.px-caption-row { display: flex; flex-direction: column; margin: -4px 0 0; }.px-title-field, .px-caption {display: block;padding: 6px 8px;@@ -405,7 +444,7 @@font-variant-numeric: tabular-nums;}/* Info's stars. */-.px-rating { display: flex; gap: 2px; margin: 4px 0 0 -4px; }+.px-rating { display: flex; gap: 2px; margin-left: -5px; }.px-star {display: grid;place-items: center;@@ -626,8 +665,7 @@.px-dl-row small { color: var(--text-2); font-size: var(--t-12, 12px); }/* Adjust Date and Time. */-.px-taken { display: block; }-.px-adjust { float: right; margin-left: 8px; font-size: var(--t-12, 12px); }+.px-adjust { flex: none; font-size: var(--t-12, 12px); }.px-date-zone { margin: 8px 0 14px; text-align: center; color: var(--text-2); font-size: var(--t-12, 12px); }.px-date-grid { display: grid; grid-template-columns: auto 1fr; gap: 10px 10px; align-items: center; font-size: var(--t-13); }.px-date-grid > span, .px-date-grid > label { text-align: right; }@@ -892,3 +930,38 @@ img[data-failed] { content: url("data:image/gif;base64,R0lGODlhAQABAAAAACw="); }.px-viewer.is-full .px-nav { background: rgba(60, 60, 64, 0.85); color: #f5f5f7; }.px-viewer.is-full .px-nav:hover { background: rgba(80, 80, 86, 0.95); }.px-viewer.is-full .px-info { top: 54px; }+.px-viewer.is-full.has-info .px-stage { margin-right: 282px; }++/* ---- a narrow window ---------------------------------------------------------------------- */+/* The sidebar folds into one pop-up above the library (see goTo), as Notes' folders fold:+ beside 480px of window it took half and left the photos a strip. Last in the file, so it+ outranks the sidebar's own display. */+.px-compact { display: none; }+@media (max-width: 720px) {+ .px { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }+ .px-side { display: none; }+ /* In the band beside the button that brings the app list back, as a toolbar would be. */+ .px-compact { display: flex; position: relative; z-index: 6; height: 32px; margin: -44px 0 12px 34px; }+ .px-compact .picker-button { font-weight: 600; }+}+/* Too narrow to set Info beside the photo — by the viewer's own width, not the window's (with+ the sidebar open, a wide window still leaves the viewer narrow; the window's width let the+ next arrow move into the middle of the photo): Info lies over it, as on iPhone, and the+ arrows and filmstrip keep their places. */+.px-viewer { container: px-viewer / inline-size; }+@container px-viewer (max-width: 700px) {+ .px-viewer.has-info .px-stage { margin-right: 0; }+ .px-viewer.has-info .px-nav.is-next { right: 14px; }+ .px-viewer.has-info .px-strip-run { left: 50%; }+ .px-info { width: min(268px, calc(100% - 28px)); }+}+++/* An empty view: its line in the middle of the pane, below the floating header — before, it sat+ at the top, its symbol under the toolbar. The photos' own scroller, empty, stays under it. */+.px-main > .px-empty {+ position: absolute;+ inset: var(--bar, 68px) 0 var(--bar, 68px) 0;+ z-index: 1;+ justify-content: center;+}diff --git a/src/styles/reminders.css b/src/styles/reminders.cssindex d9b592d..931db23 100644--- a/src/styles/reminders.css+++ b/src/styles/reminders.css@@ -130,6 +130,32 @@.rx-chevron svg { width: 12px; height: 12px; }.rx-group-row[aria-expanded="true"] .rx-chevron { transform: rotate(90deg); }+.rx-smart-row .rx-badge svg { width: 13px; height: 13px; }++/* Tags, as the Mac lists them under My Lists: every #name as a capsule, wrapping. The one open+ is filled, in the system blue. */+.rx-tags { display: flex; flex-wrap: wrap; gap: 6px; padding: 2px 4px 6px; }+.rx-tag-chip {+ max-width: 100%;+ height: 26px;+ padding: 0 11px;+ overflow: hidden;+ border: 0;+ border-radius: 999px;+ background: color-mix(in srgb, var(--text) 7%, transparent);+ color: var(--text);+ font: inherit;+ font-size: var(--t-13);+ text-overflow: ellipsis;+ white-space: nowrap;+ cursor: default;+}+.rx-tag-chip:hover { background: color-mix(in srgb, var(--text) 11%, transparent); }+.rx-tag-chip:focus-visible { outline: var(--focus-ring); outline-offset: 1px; }+.rx-tag-chip[aria-current="true"] { background: color-mix(in srgb, var(--sys-blue) 86%, #000); color: #fff; }+.rx-side-heading { margin-top: 14px; }+.rx-side-heading:first-of-type { margin-top: 0; }+.rx-new-list { display: flex; margin-top: 4px; }.rx-new-list .field, .rx-list-row > .field { flex: 1; }.rx-search { margin-bottom: 10px; }@@ -170,7 +196,19 @@/* Not `.quiet`: that is the app's quiet button, and borrowing it drew each time-of-dayheading as a button. */.rx-section.is-quiet { color: var(--text-2); font-weight: 600; }-.rx-section:first-of-type { margin-top: 4px; }+/* The first heading sits close under the title — only when no rows come before it. */+.rx-section:first-of-type:not(.rx-rows ~ .rx-section) { margin-top: 4px; }+/* A list's own sections, as Reminders draws them: the name in bold over a hairline that runs+ the width of the rows. */+.rx-section.is-list-section {+ margin: 22px 0 0 0;+ padding: 0 0 6px 30px;+ border-bottom: 1px solid var(--separator);+ font-size: var(--t-15);+}+.rx-rows:empty + .rx-section.is-list-section { margin-top: 6px; }+.rx-section-name { display: block; width: calc(100% - 14px); margin: 18px 14px 4px 0; font-weight: 700; }+.rx-add-section { margin: 6px 0 0 30px; font-size: var(--t-13); }.rx-rows { margin: 0; padding: 0; list-style: none; }@@ -182,7 +220,7 @@grid-template-columns: 20px minmax(0, 1fr) auto;column-gap: 10px;align-items: start;- padding: 7px 14px 7px 0;+ padding: 8px 14px 8px 0;}.rx-row::after {content: "";@@ -222,18 +260,10 @@.rx-tick:focus-visible { outline: 3px solid color-mix(in srgb, var(--tick) 40%, transparent); outline-offset: 2px; }.rx-tick:disabled { opacity: 0.5; }.rx-tick[aria-checked="true"] { border-color: var(--tick); }-.rx-tick[aria-checked="true"]::after {- content: "";- position: absolute;- inset: 2.5px;- border-radius: 50%;- background: var(--tick);-}-/* The fill lands the instant it is pressed, with the quick spring Reminders gives it — on the- press only (is-pressed), never again when the list comes back into view. */-.rx-tick.is-pressed[aria-checked="true"]::after { animation: rx-tick-in 220ms cubic-bezier(0.34, 1.56, 0.64, 1) both; }-@keyframes rx-tick-in { from { transform: scale(0.3); opacity: 0.4; } to { transform: scale(1); opacity: 1; } }-@media (prefers-reduced-motion: reduce) { .rx-tick.is-pressed[aria-checked="true"]::after { animation: none; } }+/* The fill: a real element, so a press can fade it in by opacity alone (lib/fade, from the+ click) — no keyframes, nothing handed to the compositor. */+.rx-tick-fill { position: absolute; inset: 2.5px; border-radius: 50%; background: var(--tick); visibility: hidden; }+.rx-tick[aria-checked="true"] .rx-tick-fill { visibility: visible; }.rx-tick.ghost {display: grid;place-items: center;@@ -285,6 +315,24 @@line-height: 1.4;}.rx-due.overdue { color: var(--sys-red); }+/* A tag on a row: #name in a quiet capsule. A press opens everything that carries it. */+.rx-tag {+ display: inline-flex;+ align-items: center;+ height: 17px;+ padding: 0 7px;+ border: 0;+ border-radius: 999px;+ background: color-mix(in srgb, var(--text) 7%, transparent);+ color: var(--text-2);+ font: inherit;+ font-size: var(--t-11);+ line-height: 17px;+ cursor: default;+ white-space: nowrap;+}+button.rx-tag:hover { background: color-mix(in srgb, var(--text) 12%, transparent); color: var(--text); }+.is-done .rx-tag { opacity: 0.7; }.rx-repeat { display: inline-flex; gap: 3px; }.rx-moved { color: var(--accent-strong); font-weight: 600; }@@ -311,12 +359,50 @@}.rx-field {display: grid;- grid-template-columns: 64px minmax(0, 1fr);+ grid-template-columns: 76px minmax(0, 1fr);gap: 10px;align-items: center;+ min-height: 28px;+}+.rx-field > span:first-child { color: var(--text-2); font-size: var(--t-11); }+.rx-field-notes { align-items: start; }+.rx-field-notes > span:first-child { padding-top: 6px; }+.rx-field textarea.field { resize: vertical; min-height: 44px; }+/* A value read from Apple, not a control: the panel's type, quietly. */+.rx-value { color: var(--text); font-size: var(--t-13); }+.rx-url {+ min-width: 0;+ overflow: hidden;+ color: var(--sys-blue);+ font-size: var(--t-13);+ text-decoration: none;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.rx-url:hover { text-decoration: underline; text-underline-offset: 3px; }+/* Between the panel's groups — what it says, when it is due, how it is filed — as Apple+ separates them in its info popover. */+.rx-detail-rule { height: 1px; margin: 2px 0; background: var(--separator); }+.rx-hint { margin: -4px 0 0 86px; color: var(--text-3); font-size: var(--t-11); }+.rx-tag-field { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; min-width: 0; }+.rx-tag.is-chip { padding: 0; height: 22px; background: color-mix(in srgb, var(--sys-blue) 12%, transparent); }+.rx-tag-name,+.rx-tag-remove {+ height: 22px;+ padding: 0 8px;+ border: 0;+ border-radius: 999px;+ background: none;+ color: var(--sys-blue);+ font: inherit;+ font-size: var(--t-13);+ cursor: default;}-.rx-field > span { color: var(--text-2); font-size: var(--t-11); }-.rx-hint { margin: -2px 0 0 74px; color: var(--text-3); font-size: var(--t-11); }+.rx-tag-remove { display: grid; place-items: center; width: 20px; padding: 0; margin-left: -6px; }+.rx-tag-name:hover { text-decoration: underline; text-underline-offset: 2px; }+.rx-tag-name:focus-visible, .rx-tag-remove:focus-visible { outline: var(--focus-ring); }+.rx-tag-input { min-width: 6ch; flex: 1; padding: 2px 0; border: 0; background: none; color: var(--text); font: inherit; font-size: var(--t-13); outline: none; }+.rx-tag-input::placeholder { color: var(--text-3); }.rx-detail-actions { display: flex; justify-content: space-between; margin-top: 2px; }/* The last row: where a new reminder is typed. */