mirror of
https://github.com/priyanshujain/margin.git
synced 2026-10-04 03:57:03 +00:00
some more fixes
This commit is contained in:
1 parent
7a3c04f170
commit
2b86a407ba
63 files changed
+12172
-44
No files matched your search
@@ -0,0 +1,450 @@
|
||||
# Build and developer tooling across the four apps
|
||||
|
||||
Scope: package.json, lockfiles, vite, tsconfig, index.html, justfiles, scripts, gitignore, nix,
|
||||
editor config, Cargo profiles, capabilities. Not CI, signing or tests, bar where build leaks in.
|
||||
|
||||
Paths: margin `/Users/pj/Workspace/projects/python/margin`, margin-calendar
|
||||
`/Users/pj/Workspace/projects/python/margin-caledar`, margin-docs
|
||||
`/Users/pj/Workspace/projects/rust/margin-editor`, margin-mail
|
||||
`/Users/pj/Workspace/projects/rust/margin-mail`. Cites below are relative to those roots.
|
||||
|
||||
## Five findings first
|
||||
|
||||
1. **margin-docs cannot install on a fresh clone or on its own CI.** Its `package.json:33` asks for
|
||||
`"margin-shared": "file:../../python/margin/shared"` but `.github/workflows/ci.yml:19` does one
|
||||
checkout. The frontend job dies inside `pnpm install --frozen-lockfile` with exit 254; four of
|
||||
the last five runs failed (run 33308997470, 2026-08-30: `rust: success`, `frontend: failure`).
|
||||
margin-mail is the only app that solved it, with a second checkout of `priyanshujain/margin`
|
||||
into `python/margin` (`.github/workflows/ci.yml:26-31`, `release.yml:109`).
|
||||
2. **The four tsconfigs are three identical files plus one that differs by two lines.** md5 of
|
||||
margin, margin-calendar and margin-docs `tsconfig.json` is `468c4a26...`; margin-mail differs
|
||||
only in `target` and `lib`. All four `tsconfig.node.json` are byte identical (`767b2e9a...`).
|
||||
3. **The three justfiles are one file with the product name swapped**, plus two extra recipes and a
|
||||
signing block in margin-mail. margin has no justfile at all, so the "every fix ends with
|
||||
`just install`" rule is unenforceable there.
|
||||
4. **No prettier, no eslint, no biome, no .editorconfig, no rustfmt.toml, no rust-toolchain file in
|
||||
any of the four.** Confirmed by search over the repo roots and by grep over each package.json.
|
||||
The only editor config is `margin/.vscode/extensions.json`, two recommendations, and no sibling
|
||||
has one.
|
||||
5. **Nix exists only in margin-calendar** and is a publishing artifact, not a toolchain: it
|
||||
repackages the released `.deb`. Worth copying per app, but not shared build config.
|
||||
|
||||
## package.json
|
||||
|
||||
### Scripts
|
||||
|
||||
| script | margin | calendar | docs | mail |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `dev` | `vite` | `vite` | `vite` | `vite` |
|
||||
| `build` | `tsc && vite build` | same | same | same |
|
||||
| `preview` | `vite preview` | same | same | same |
|
||||
| `tauri` | `tauri` | same | same | same |
|
||||
| `dmg` | `tauri build --bundles dmg` (`:11`) | absent | absent | absent |
|
||||
| `test` | absent | `vitest run` | `vitest run` | `vitest run` |
|
||||
| `test:watch` | absent | `vitest` | `vitest` | `vitest` |
|
||||
| `test:ui` | absent | `playwright test` | `playwright test` | `playwright test` |
|
||||
| `fonts:sync` | `node node_modules/margin-shared/bin/sync-fonts.mjs .` (`:12`) | absent | same (`:15`) | `margin-shared-fonts .` (`:15`) |
|
||||
| `fonts:check` | same with `--check` (`:13`) | absent | same (`:16`) | `margin-shared-fonts . --check` (`:16`) |
|
||||
|
||||
Two drifts worth folding: margin and margin-docs invoke the font sync by path into `node_modules`,
|
||||
margin-mail uses the `margin-shared-fonts` bin the package already declares
|
||||
(`python/margin/shared/package.json:16-18`) and which is linked in all three consumers. The bin form
|
||||
is the correct one. margin-calendar has no font sync and vendors four files under `public/fonts`
|
||||
against eighteen in the others, so it is not on the shared face set.
|
||||
|
||||
`license` also drifts: `"SEE LICENSE IN LICENSE"` in margin (`:41`) and mail (`:5`), `"MIT"` in
|
||||
calendar (`:5`) and docs (`:3`), matching `LicenseRef-FSL-1.1-MIT` and `MIT` respectively in the
|
||||
Cargo manifests. Consistent within an app, but the four are not on one licence.
|
||||
|
||||
### Version drift (declared spec, then what the lockfile resolved)
|
||||
|
||||
| package | margin | calendar | docs | mail |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| react, react-dom | `^19.1.0` -> 19.2.7 | `^19.1.0` -> 19.2.8 | 19.2.8 | 19.2.8 |
|
||||
| vite | `^7.0.4` -> 7.3.5 | 7.3.6 | 7.3.6 | 7.3.6 |
|
||||
| typescript | `~5.8.3` -> 5.8.3 | 5.8.3 | 5.8.3 | 5.8.3 |
|
||||
| @vitejs/plugin-react | `^4.6.0` -> 4.7.0 | 4.7.0 | 4.7.0 | 4.7.0 |
|
||||
| vitest | absent | `^3.2.4` -> 3.2.7 | 3.2.7 | 3.2.7 |
|
||||
| @playwright/test | absent | 1.62.1 | 1.62.1 | 1.62.1 |
|
||||
| zustand | `^5.0.14` -> 5.0.14 | 5.0.14 | 5.0.15 | 5.0.15 |
|
||||
| @types/react | 19.2.17 | 19.2.18 | 19.2.18 | 19.2.18 |
|
||||
| @types/react-dom | 19.2.3 | 19.2.4 | 19.2.4 | 19.2.7 |
|
||||
| @types/node | absent | absent | `^22.20.1` -> 22.20.1 | `^24.0.0` -> 24.13.3 |
|
||||
| @tauri-apps/api | `^2` -> 2.11.1 | 2.11.1 | 2.11.1 | 2.11.1 |
|
||||
| @tauri-apps/cli | `^2` -> 2.11.3 | 2.11.4 | 2.11.4 | 2.11.4 |
|
||||
| plugin-opener | 2.5.4 | 2.5.4 | 2.5.4 | 2.5.5 |
|
||||
| plugin-process | 2.3.1 | 2.3.1 | 2.3.1 | 2.3.1 |
|
||||
| plugin-updater | 2.10.1 | 2.10.1 | 2.10.1 | 2.11.0 |
|
||||
| plugin-dialog | `^2.7.1` -> 2.7.1 | absent | `^2` -> 2.7.2 | absent |
|
||||
| plugin-notification | absent | absent | absent | 2.4.0 |
|
||||
| plugin-os | absent | absent | absent | 2.3.2 |
|
||||
| tiptap | `^3.27.1` -> 3.27.1 | absent | `3.30.2` exact | `^3.31.2` -> 3.31.2 |
|
||||
|
||||
Nothing here is a real incompatibility. Every spec except margin-docs' tiptap is a caret or tilde,
|
||||
so the drift is purely "when was `pnpm install` last run here": margin is the stale one, a patch
|
||||
behind on react and vite and two `@types` bumps behind. The one deliberate difference is margin-docs
|
||||
pinning tiptap exactly at 3.30.2 (`package.json:24-28`) while the others float.
|
||||
|
||||
`@types/node` is the only genuine split: 22 in docs, 24 in mail, absent in the other two. Since
|
||||
`tsconfig.json` in all four sets no `types` array, the presence of `@types/node` silently changes
|
||||
what global names typecheck per app.
|
||||
|
||||
No app declares a `packageManager` field, so nothing pins pnpm from the repo itself.
|
||||
|
||||
## The margin-shared relative path
|
||||
|
||||
- margin: `"margin-shared": "file:./shared"` (`package.json:26`), inside its own repo, and the
|
||||
directory is tracked (26 files under `shared/`).
|
||||
- margin-docs: `"file:../../python/margin/shared"` (`package.json:33`).
|
||||
- margin-mail: `"file:../../python/margin/shared"` (`package.json:27`).
|
||||
|
||||
The lockfiles record the literal relative string, with no integrity hash:
|
||||
`rust/margin-mail/pnpm-lock.yaml:918` is `margin-shared@file:../../python/margin/shared:` with
|
||||
`resolution: {directory: ../../python/margin/shared, type: directory}` and the snapshot at
|
||||
`:1957` is `{}`. Same shape at `rust/margin-editor/pnpm-lock.yaml:1449`.
|
||||
|
||||
How fragile: pnpm resolves the path relative to the importer directory, so the dependency is not
|
||||
"the margin repo", it is "two directories up, then `python/margin/shared`". That encodes PJ's local
|
||||
grouping (`Workspace/projects/python`, `Workspace/projects/rust`) into a committed manifest.
|
||||
|
||||
- **Fresh clone.** Cloning margin-mail into `~/code/margin-mail` makes the target
|
||||
`/Users/pj/python/margin/shared`. `pnpm install` then stops with
|
||||
`ERR_PNPM_LINKED_PKG_DIR_NOT_FOUND Could not install from "..." as it does not exist.`
|
||||
(reproduced directly, exit non-zero, nothing installed). This is not a warning that degrades to a
|
||||
missing font, it is a hard install failure before any other dependency lands.
|
||||
- **CI.** margin-mail works only because `ci.yml:26-31` checks the sibling out at the exact path
|
||||
`python/margin` and runs everything with `working-directory: rust/margin-mail`. margin-docs does
|
||||
not do this and its frontend job has been red since the dependency landed.
|
||||
- **Anyone else.** A contributor must clone two repositories into a two-level layout whose folder
|
||||
names (`python`, `rust`) mean nothing to them and appear in no documentation. The margin repo is
|
||||
public, so it is possible, just undiscoverable.
|
||||
- **Reproducibility.** A directory dependency has no hash, so `pnpm install --frozen-lockfile`
|
||||
consumes whatever is in `shared/` at that moment, uncommitted edits included. The lockfile is not
|
||||
frozen with respect to shared code.
|
||||
- **Publishing.** `shared/package.json:4` is `"private": true`, so today it cannot go to a registry
|
||||
without a deliberate change.
|
||||
|
||||
Three ways out, in order of how much they cost:
|
||||
|
||||
1. **Give shared its own repo and depend on a git tag.** Removes the path assumption entirely and
|
||||
gets an immutable resolution. npm and pnpm git dependencies cannot point at a subdirectory, so
|
||||
this means moving `shared/` out of the margin repo, which also fixes margin depending on it via
|
||||
`file:./shared`.
|
||||
2. **Publish `margin-shared` to npm** (or a GitHub npm registry) and depend on a version. Same
|
||||
benefit, plus a real integrity hash in the lockfile. Costs a publish step per change to shared.
|
||||
3. **Keep the relative path but make it discoverable and enforced:** an `.env`-style documented
|
||||
layout, a preinstall check that fails with a readable message instead of pnpm's error, and the
|
||||
second checkout added to margin-docs CI. This is the cheap fix and it leaves the reproducibility
|
||||
hole open.
|
||||
|
||||
If a shared toolchain package is going to exist anyway, it should be delivered the same way as
|
||||
whatever is chosen here, and the two should not use different mechanisms.
|
||||
|
||||
## pnpm and workspaces
|
||||
|
||||
All four lockfiles are `lockfileVersion: '9.0'` (line 1) with identical settings blocks
|
||||
(`autoInstallPeers: true`, `excludeLinksFromLockfile: false`). No `pnpm-workspace.yaml` and no
|
||||
`.npmrc` in any of the four. There is no workspace today and no way to create one across four git
|
||||
repos without either submodules or a monorepo merge.
|
||||
|
||||
Local installs all report `packageManager: [email protected]` in `node_modules/.modules.yaml`, which is
|
||||
install state rather than a committed pin; CI pins `pnpm/action-setup@v6` `version: 10` and node 26.
|
||||
|
||||
## vite.config.ts
|
||||
|
||||
Ports, which are the one thing that must stay per app and are correctly staggered:
|
||||
|
||||
| app | server.port | hmr.port | tauri devUrl |
|
||||
| --- | --- | --- | --- |
|
||||
| margin | 1420 (`:17`) | 1421 (`:23`) | `http://localhost:1420` |
|
||||
| calendar | 1430 (`:13`) | 1431 (`:20`) | `http://localhost:1430` |
|
||||
| docs | 1440 (`:23`) | 1441 (`:30`) | `http://localhost:1440` |
|
||||
| mail | 1450 (`:16`) | 1451 (`:22`) | `http://localhost:1450` |
|
||||
|
||||
Everything else in the file is the same four properties: `plugins: [react()]`,
|
||||
`clearScreen: false`, `strictPort: true`, `host: host || false` where `host` is
|
||||
`process.env.TAURI_DEV_HOST` behind a `@ts-expect-error` comment in all four (`:4-5` in each), the
|
||||
same conditional `hmr` block, and `watch.ignored`.
|
||||
|
||||
Real differences:
|
||||
|
||||
- margin imports `defineConfig` from `"vite"` (`:1`) and exports an async factory,
|
||||
`defineConfig(async () => ({ ... }))` (`:8`), for no reason visible in the file. The other three
|
||||
import from `"vitest/config"` and export a plain object, because they carry a `test` block.
|
||||
- margin ignores `"**/website/**"` as well as src-tauri (`:29`); the others ignore only src-tauri.
|
||||
- margin-docs is the only one with a `build` block: `assetsInlineLimit` as a function that returns
|
||||
`false` for `woff2?|ttf|otf|eot` (`:19`), because the app CSP is `font-src 'self'` and a data URI
|
||||
font would be refused.
|
||||
- The `test` blocks: calendar and mail are identical (`include: ["src/**/*.test.ts"]`,
|
||||
`environment: "node"`); docs adds `maxWorkers: "50%"`, `testTimeout: 30_000`,
|
||||
`hookTimeout: 30_000`, `teardownTimeout: 30_000` (`:57-69`).
|
||||
|
||||
Nothing in any of the four sets `define`, `envPrefix`, `resolve.alias`, `build.target`, `minify` or
|
||||
`sourcemap`. So there is no alias story to preserve and no env prefix convention to standardise.
|
||||
|
||||
## tsconfig.json and tsconfig.node.json
|
||||
|
||||
`tsconfig.json` is identical in margin, calendar and docs. margin-mail differs in exactly two
|
||||
options:
|
||||
|
||||
- `"target": "ES2022"` versus `"ES2020"` (`rust/margin-mail/tsconfig.json:3`)
|
||||
- `"lib": ["ES2022", "DOM", "DOM.Iterable"]` versus `["ES2020", ...]` (`:5`)
|
||||
|
||||
Everything else matches across all four: `useDefineForClassFields`, `module: "ESNext"`,
|
||||
`skipLibCheck`, `moduleResolution: "bundler"`, `allowImportingTsExtensions`, `resolveJsonModule`,
|
||||
`isolatedModules`, `noEmit`, `jsx: "react-jsx"`, `strict`, `noUnusedLocals`, `noUnusedParameters`,
|
||||
`noFallthroughCasesInSwitch`, `include: ["src"]`, and a reference to `./tsconfig.node.json`.
|
||||
|
||||
`tsconfig.node.json` is byte identical in all four: `composite`, `skipLibCheck`, `module: ESNext`,
|
||||
`moduleResolution: bundler`, `allowSyntheticDefaultImports`, `include: ["vite.config.ts"]`.
|
||||
|
||||
`tests/tsconfig.json` exists in calendar, docs and mail (margin has no tests directory). Calendar
|
||||
and docs are byte identical. margin-mail adds `"types": ["node"]` (`:16-18`) and is written with
|
||||
one array element per line, which is a formatting drift nothing enforces.
|
||||
|
||||
Nothing runs `tests/tsconfig.json`. `pnpm build` is `tsc && vite build`, and root `tsc` only sees
|
||||
`include: ["src"]`. No package.json script, justfile recipe or workflow step in any of the three
|
||||
references it. The Playwright specs are therefore type checked by nobody.
|
||||
|
||||
None of the four sets `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`,
|
||||
`verbatimModuleSyntax` or `paths`.
|
||||
|
||||
## index.html
|
||||
|
||||
Identical structure in all four: `<!doctype html>`, `lang="en"`, `charset=UTF-8`, a title, a
|
||||
`<div id="root">`, and `<script type="module" src="/src/main.tsx">`.
|
||||
|
||||
- Viewport: margin, calendar and mail use `width=device-width, initial-scale=1.0,
|
||||
maximum-scale=1.0, user-scalable=no, viewport-fit=cover`; docs drops `viewport-fit=cover` (`:5`).
|
||||
- Favicon: `/margin-mark.png`, `/margincal-mark.png`, `/marginmail-mark.png`. margin-docs has no
|
||||
`<link rel="icon">` at all and no mark in `public/`.
|
||||
- No CSP meta tag and no font preload in any of the four. The real CSP is in
|
||||
`src-tauri/tauri.conf.json` under `app.security.csp`, and it differs per app for good reasons:
|
||||
margin and docs add `worker-src 'self' blob:`, docs adds `asset: http://asset.localhost` to
|
||||
`img-src`, mail adds `frame-src 'self'`.
|
||||
- Every one has an inline pre-paint script that reads localStorage and sets attributes on
|
||||
`documentElement` before React boots. They share a shape (theme resolution against
|
||||
`prefers-color-scheme`, then app specific attributes) but every key is app prefixed
|
||||
(`margin-theme`, `margincal-theme`, `marginmail-theme`, `margindocs-theme`) and each sets
|
||||
different things. margin-docs is the only one that reads keys individually rather than wrapping
|
||||
the lot in one `try` (`:13-19`), which is the better version: a webview that refuses storage
|
||||
still gets the theme. The other three lose everything after the first throw.
|
||||
|
||||
That inline script is the one genuinely shared idea in these files, and it is the hardest to share,
|
||||
because it must be inline and cannot import.
|
||||
|
||||
## justfiles
|
||||
|
||||
margin has none. calendar, docs and mail have one, and the three are the same file with names
|
||||
substituted; `diff` between calendar and docs is nine hunks, all of them the product name, the
|
||||
process name or a comment reflow.
|
||||
|
||||
| recipe | calendar | docs | mail | bodies match |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `default` (`@just --list`) | yes | yes | yes | identical |
|
||||
| `dev` (`pnpm tauri dev`) | yes | yes | yes | identical |
|
||||
| `test` (`pnpm test` then `cd src-tauri && cargo test`) | yes | yes | yes | identical |
|
||||
| `test-ui` (`pnpm test:ui`) | yes | yes | yes | identical, comment differs in mail |
|
||||
| `guide-shots` | no | no | yes (`:29-30`) | mail only |
|
||||
| `docs` (`node scripts/docs-check.mjs`) | no | no | yes (`:33-34`) | mail only |
|
||||
| `build` | yes | yes | yes | same except mail's signing block |
|
||||
| `install` (depends on `build`) | yes | yes | yes | identical |
|
||||
| `_install-macos` | yes | yes | yes | docs omits the final `open "$dest"` |
|
||||
| `_install-linux` | yes | yes | yes | identical bar names and the desktop entry |
|
||||
| `uninstall` | yes | yes | yes | identical bar names |
|
||||
|
||||
Shared variables: `set shell := ["bash", "-euo", "pipefail", "-c"]`, `app`, `bundle :=
|
||||
"src-tauri/target/release/bundle"`.
|
||||
|
||||
Substantive differences:
|
||||
|
||||
- margin-mail's `build` sources a signing env file before building
|
||||
(`rust/margin-mail/justfile:46-54`): it reads
|
||||
`"${MARGIN_SIGNING_DIR:-$HOME/.margin-signing}/studio.margin.app.env"`. Note the file name is
|
||||
`studio.margin.app`, which is margin's bundle identifier, not `studio.margin.mail`. If the intent
|
||||
is one env file for the whole suite the name is misleading; if it is one per app, this is wrong.
|
||||
- margin-docs' `_install-macos` does not `open "$dest"` at the end (compare `justfile:77` in docs
|
||||
with `:78` in calendar and `:97` in mail). So `just install` starts the new build in two of the
|
||||
three apps and not the third.
|
||||
- Only margin-mail has a prose gate recipe.
|
||||
|
||||
Because the rule is that a fix ends with `just install`, the gap that matters is margin: its only
|
||||
local build path is `pnpm dmg` (`package.json:11`), and nothing copies a bundle into
|
||||
`/Applications`. The three justfiles already prove the body is app independent bar four names, so
|
||||
margin is a paste plus a variable block away from the same command.
|
||||
|
||||
## scripts directories
|
||||
|
||||
Only two apps have one and they do unrelated things.
|
||||
|
||||
- `margin/scripts` is twelve files of Apple release plumbing: `apple-provision.rb`,
|
||||
`apple-secrets.sh`, `appstore-compliance.rb`, `appstore-listing.rb`,
|
||||
`appstore-review-detail.rb`, `appstore-screenshots.rb`, `mas-package.sh`, `mas-upload-local.sh`,
|
||||
`testflight-release.rb`, `testflight-setup.rb`, `testflight-testers.rb`. This is the App Store
|
||||
path and only margin is on it, so it stays where it is (and overlaps the signing agent's scope).
|
||||
- `margin-mail/scripts` is one file, `docs-check.mjs`, 72 lines: no em or en dash anywhere
|
||||
including in code fences, no directory tree (box glyph run or three consecutive ASCII tree
|
||||
lines), no broken relative link. It walks every `.md` in the repo, skipping
|
||||
`node_modules, dist, target, .git, gen, .playwright-mcp`.
|
||||
|
||||
`docs-check.mjs` is the clearest single candidate for sharing: no dependencies, no app specific
|
||||
knowledge, and it enforces a house rule that applies to all four repos. It belongs in the shared
|
||||
package with a bin, like `sync-fonts.mjs` (exposed as `margin-shared-fonts`).
|
||||
|
||||
## .gitignore
|
||||
|
||||
Common core in all four, in the same order: log patterns, `node_modules`, `dist`, `dist-ssr`,
|
||||
`*.local`, the editor block (`.vscode/*` with `!.vscode/extensions.json`, `.idea`, `.DS_Store`,
|
||||
`*.sw?`), `src-tauri/target/`, `.playwright-mcp/`, `/*.png`.
|
||||
|
||||
Differences:
|
||||
|
||||
- `src-tauri/gen/schemas/` is ignored in calendar (`:27`), docs (`:27`) and mail (`:21`), but not
|
||||
in margin. margin therefore can commit generated schema files.
|
||||
- The Xcode block (`src-tauri/gen/apple/build/`, `Externals/`, `Pods/`, `Podfile.lock`,
|
||||
`xcuserdata/`) is in calendar (`:32-36`), docs (`:32-36`) and mail (`:25-29`), not margin.
|
||||
- Google credentials (`/google-credentials.json`, `/client_secret_*.json`) in margin (`:30-31`),
|
||||
calendar (`:39-40`) and mail (`:33-34`), not docs, which needs none.
|
||||
- margin only: `target-mas/` and two App Store review contact files (`:38-42`).
|
||||
- docs only: `.env`, `.env.*`, `!.env.example` (`:43-45`), the updater signing key.
|
||||
- calendar only: `/result`, `/result-*` (`:47-48`), the nix build symlinks.
|
||||
- mail only: `/screenshots/` (`:41`).
|
||||
- margin-mail trims the editor block hardest (no `*.suo`, `*.ntvs*`, `*.njsproj`, `*.sln`).
|
||||
|
||||
A shared base of about twenty lines would cover everything up to `/*.png`, with five to eight app
|
||||
specific lines after it. Git has no include mechanism for ignore files and `core.excludesFile` is
|
||||
per machine, so this is one of the things that stays copied.
|
||||
|
||||
## Nix in margin-calendar
|
||||
|
||||
`flake.nix` is 21 lines: one input (`nixpkgs` at `nixos-unstable`, locked in `flake.lock` at rev
|
||||
`3ed67ec0a4d3c7ab4ae1f04f8ee8df07bfa506a2`), an overlay and a single `x86_64-linux` package that
|
||||
calls `./nix/package.nix`. `nix/package.nix` fetches the published `.deb` from the GitHub release
|
||||
named in `nix/release.json` (`{"version": "0.0.5", "hash": "sha256-+bEQO..."}`), unpacks it with
|
||||
`dpkg-deb -x`, relinks it with `autoPatchelfHook` and `wrapGAppsHook3` against nixpkgs' gtk3,
|
||||
`webkitgtk_4_1`, `libsoup_3` and friends, writes a launcher that points `libglvnd` at nixpkgs' mesa
|
||||
when `/run/opengl-driver` is absent, shims `xdg-open` to strip those variables again, and sets
|
||||
`MARGIN_CALENDAR_PACKAGED_BY=nix` so the in-app updater reports rather than replaces itself.
|
||||
|
||||
`docs/release.md:41-81` gives the rationale: the AppImage bundles Ubuntu's GTK stack and a bundled
|
||||
`libwayland-client` cannot talk to a current compositor, so on Hyprland it falls back to Xwayland.
|
||||
It is binary by necessity, because the Google OAuth client is embedded at compile time from a file
|
||||
that is not in the repo.
|
||||
|
||||
Is this the Linux distribution path, and should the others adopt it? Yes for margin-mail, same
|
||||
Google client problem and same GTK and WebKit runtime; yes for margin-docs if it ships Linux, which
|
||||
its justfile already builds for. margin is macOS and App Store shaped and would gain nothing.
|
||||
|
||||
But note what is actually shared here: almost nothing. The flake is fifteen lines of boilerplate and
|
||||
`package.nix` is a hundred lines of which the app name, the deb URL, the desktop file rename, the
|
||||
env variable name and the meta block are all per app, and the rest (the hooks, the buildInputs list,
|
||||
the mesa launcher, the xdg-open shim) is genuinely common. If two apps adopt it, that common part
|
||||
should be a function in the shared repo that each flake calls with a name, a repo and a release pin.
|
||||
Below two adopters, copy it.
|
||||
|
||||
## Editor, formatter and linter config
|
||||
|
||||
Confirmed absent everywhere: prettier (no config file, no dependency, no script in any of the four
|
||||
package.json files), eslint, biome, `.editorconfig`, `rustfmt.toml`, `clippy.toml`,
|
||||
`rust-toolchain.toml`, `.nvmrc`.
|
||||
|
||||
Present: `margin/.vscode/extensions.json`, two recommendations
|
||||
(`tauri-apps.tauri-vscode`, `rust-lang.rust-analyzer`). No other app has a `.vscode` directory,
|
||||
though all four gitignore `.vscode/*` while un-ignoring `extensions.json`, so the intent is there.
|
||||
|
||||
`margin-editor/src-tauri/.cargo/config.toml` is the only cargo config: `[env] RUST_TEST_THREADS =
|
||||
"1"`, for a suite that shares one on-disk git repository. App specific, stays.
|
||||
|
||||
The consistent formatting across all these files (two space JSON, 100 column comments, the same
|
||||
comment voice) is being maintained by hand. That works while one person writes everything, and the
|
||||
one place it has already slipped is `rust/margin-mail/tests/tsconfig.json`, which is the same file
|
||||
as its siblings reformatted with expanded arrays.
|
||||
|
||||
## Cargo
|
||||
|
||||
No `[workspace]` section in any of the four manifests, so each `src-tauri` is its own workspace root
|
||||
with its own `Cargo.lock` (margin 964 packages, calendar 565, docs 962, mail 668).
|
||||
|
||||
Profiles: only margin (`src-tauri/Cargo.toml:78-79`) and margin-docs (`:107-108`) set anything,
|
||||
both `[profile.dev.package."*"] opt-level = 3` with near identical comments about Harper's grammar
|
||||
engine being ten times slower unoptimized. No `[profile.release]` anywhere, so release builds are
|
||||
cargo defaults in all four and there is no `lto`, `codegen-units` or `strip` setting to align.
|
||||
|
||||
Duplication worth noting: margin and margin-docs both carry `[patch.crates-io]` stubs for
|
||||
`burn-cuda` and `cubecl-cpu` (`margin:70-72`, `docs:98-100`) plus a `stubs/` directory each with the
|
||||
same two skeleton crates at the same versions (`burn-cuda` 0.19.1, `cubecl-cpu` 0.8.1) and nearly
|
||||
the same comments. This is real shared code, kept in sync by hand, and it is tied to
|
||||
`harper-core = "=2.5.0"` in both.
|
||||
|
||||
A shared cargo workspace across the four is not feasible. A workspace requires one filesystem root
|
||||
containing all members with paths in the root manifest, which means one git repository. These are four
|
||||
repositories with independent release tags and version numbers, and margin-mail has no remote
|
||||
configured yet. Without merging, the one thing worth extracting is a shared crate for the harper
|
||||
stubs behind a git dependency, which deletes both copied `stubs/` directories.
|
||||
|
||||
## Capabilities
|
||||
|
||||
All four have exactly `capabilities/default.json` and `capabilities/desktop.json`, both pointing at
|
||||
`../gen/schemas/desktop-schema.json`, both scoped to `windows: ["main"]`, with desktop gated on
|
||||
`platforms: ["macOS", "windows", "linux"]`. No `permissions/` directory in any app.
|
||||
|
||||
| app | default permissions | desktop permissions |
|
||||
| --- | --- | --- |
|
||||
| margin | `core:default`, `core:window:allow-destroy`, `core:window:allow-start-dragging`, `opener:default`, `dialog:default` | `updater:default`, `process:allow-restart` |
|
||||
| calendar | `core:default`, `opener:default`, `deep-link:default` | the two window permissions, `updater:default`, `process:allow-restart` |
|
||||
| docs | `core:default`, `opener:default`, `dialog:default` | the two window permissions plus `core:window:allow-toggle-maximize`, `updater:default`, `process:allow-restart` |
|
||||
| mail | `core:default`, `opener:default`, `deep-link:default`, `notification:default`, `os:default` | the two window permissions, `updater:default`, `process:allow-restart` |
|
||||
|
||||
margin is the odd one: it puts the two window permissions in `default` rather than `desktop`, so a
|
||||
mobile build would ask for them. `desktop.json` is identical in calendar and mail bar the
|
||||
description, and docs differs by one line.
|
||||
|
||||
## Recommendation
|
||||
|
||||
A shared package (call it `margin-shared` extended, or a second `margin-config` delivered the same
|
||||
way) should export exactly five things:
|
||||
|
||||
1. **`tsconfig/base.json`.** Everything currently duplicated, with `target` and `lib` at ES2022 for
|
||||
all four, since ES2020 in three of them is a scaffold default nobody chose. Each app keeps a
|
||||
three line `tsconfig.json` that extends it and sets `include` and `references`. Also export
|
||||
`tsconfig/node.json` (byte identical in all four today) and `tsconfig/tests.json` (identical in
|
||||
two of three, one `types` entry apart). Adding `noUncheckedIndexedAccess` is a separate decision
|
||||
and should not ride along with the consolidation.
|
||||
2. **A vite config factory**, `marginVite({ port, test })`, returning the plugin, `clearScreen`,
|
||||
the full `server` block derived from one port number, and the `TAURI_DEV_HOST` handling. Ports
|
||||
stay per app and are the argument. margin-docs passes its `assetsInlineLimit`, margin-docs
|
||||
passes its vitest timeouts. The `@ts-expect-error process` comment disappears with it, because
|
||||
the factory can own that line once.
|
||||
3. **A justfile include.** `just` supports `import`, so the shared file can hold `default`, `dev`,
|
||||
`test`, `test-ui`, `build`, `install`, `_install-macos`, `_install-linux` and `uninstall`
|
||||
verbatim, parameterised on `app`, `binary`, `comment` and `categories`, which the app justfile
|
||||
sets before importing. Adding this to margin is the change that makes `just install` a real
|
||||
suite-wide rule instead of a rule three of four apps can honour. The import has to resolve to a
|
||||
real path, which lands back on the same delivery question as `margin-shared`.
|
||||
4. **`docs-check` as a bin.** Move `margin-mail/scripts/docs-check.mjs` into the shared package
|
||||
beside `sync-fonts.mjs`, expose it as `margin-shared-docs`, and add a `docs` recipe to the shared
|
||||
justfile. It has no app specific content at all.
|
||||
5. **The checking story, with no eslint.** Today that is `tsc` under `pnpm build` plus `cargo
|
||||
test`. Two gaps close inside the shared config rather than with a linter: `tests/tsconfig.json`
|
||||
is run by nothing, so add a `typecheck` recipe covering both projects; and `pnpm fonts:check`
|
||||
runs in margin-mail CI only, so it belongs in the shared `test` recipe everywhere.
|
||||
|
||||
What has to stay per app, and should not be abstracted:
|
||||
|
||||
- The dev server port and the matching `devUrl` in `tauri.conf.json`. Staggering is load bearing:
|
||||
Playwright reuses whatever answers on the port, so a collision means a suite silently driving the
|
||||
wrong app (`rust/margin-mail/vite.config.ts:7-9`).
|
||||
- The inline pre-paint script in `index.html`. It cannot import, its storage keys are app prefixed,
|
||||
and it sets different attributes per app. Copy margin-docs' per key `saved()` pattern into the
|
||||
other three by hand.
|
||||
- The CSP in `tauri.conf.json`, the capabilities files and `Cargo.toml` dependencies. One shared
|
||||
version would be the union, which is wrong for a suite that does not reach for spare permissions.
|
||||
- `.gitignore`, because git cannot include a shared file.
|
||||
- The nix flake, unless and until a second app ships Linux through it.
|
||||
- margin's `scripts/` App Store tooling, and margin-docs' `src-tauri/.cargo/config.toml`.
|
||||
|
||||
Sequencing: the `margin-shared` path problem has to be solved first, because every item above is
|
||||
delivered through the same mechanism, and adding four more consumers of a broken relative path makes
|
||||
the fresh clone failure four times worse instead of once. Second, add the missing checkout to
|
||||
margin-docs CI, which is a red build today for a reason nobody has looked at. Third, give margin a
|
||||
justfile.
|
||||
@@ -0,0 +1,448 @@
|
||||
# CI, packaging, signing, the updater, distribution
|
||||
|
||||
Four repos, four hand-maintained copies of the same release pipeline. This is what is in them, what
|
||||
has already drifted, and what a shared version would have to keep per app. Paths: `margin` is
|
||||
`/Users/pj/Workspace/projects/python/margin`, `margin-calendar` is
|
||||
`/Users/pj/Workspace/projects/python/margin-caledar` (misspelled on disk), `margin-docs` is
|
||||
`/Users/pj/Workspace/projects/rust/margin-editor`, `margin-mail` is
|
||||
`/Users/pj/Workspace/projects/rust/margin-mail`.
|
||||
|
||||
## The workflows
|
||||
|
||||
| repo | release.yml | ci.yml | other |
|
||||
| --- | --- | --- | --- |
|
||||
| margin | 259 lines | none | appstore.yml, 130 lines |
|
||||
| margin-calendar | 241 | 81 | |
|
||||
| margin-docs | 258 | 78 | |
|
||||
| margin-mail | 229 | 92 | |
|
||||
|
||||
margin has no CI workflow at all. Nothing checks a push or a pull request there; the first time a
|
||||
broken tree is noticed is a release build.
|
||||
|
||||
### How near-duplicate the release YAML is
|
||||
|
||||
Whole-file changed lines (`diff | grep -c '^[<>]'`) run from 126 (calendar vs mail) through 136
|
||||
(margin vs calendar), 144 (margin vs mail), 211 (docs vs mail), 225 (calendar vs docs) to 241
|
||||
(margin vs docs). Those numbers overstate the difference, because they count reflowed comment
|
||||
blocks. The structural duplication is much worse. The whole `prepare` job, lines 1 to 81 of both
|
||||
files, is byte-identical between margin-calendar and margin-mail except for one line: the title at
|
||||
`margin-caledar/.github/workflows/release.yml:78` says `Margin Calendar $TAG` and
|
||||
`margin-mail/.github/workflows/release.yml:78` says `Margin Mail $TAG`. Nothing else in 81 lines
|
||||
differs.
|
||||
|
||||
The `publish` job is the same story. `margin-caledar/.github/workflows/release.yml:162-181` against
|
||||
`margin-mail/.github/workflows/release.yml:210-229` differs on one line, and that line is
|
||||
punctuation inside an error string (calendar still has an em dash at line 177, mail rewrote it as a
|
||||
comma). Against margin, `release.yml:199-218`, the only real difference is the platform key list:
|
||||
margin checks `darwin-aarch64 darwin-x86_64 linux-x86_64 windows-x86_64` at line 212, the other two
|
||||
check the same list without Windows.
|
||||
|
||||
Every workflow pins the same actions at the same versions: `actions/checkout@v7`,
|
||||
`actions/setup-node@v6` with `node-version: 26`, `pnpm/action-setup@v6` with `version: 10`,
|
||||
`dtolnay/rust-toolchain@stable`, `swatinem/rust-cache@v2`, `tauri-apps/tauri-action@v0`,
|
||||
`cachix/install-nix-action@v31`, `actions/upload-artifact@v4`. Four copies of one pin set.
|
||||
|
||||
### Triggers, permissions, concurrency, caching
|
||||
|
||||
All four releases are `workflow_dispatch` only, with one optional `version` string input, and
|
||||
`permissions: contents: write` at workflow level. margin's `appstore.yml:16-17` is the one workflow
|
||||
with `contents: read`.
|
||||
|
||||
No release workflow has a `concurrency` block. Two dispatches at once would both compute a version
|
||||
from `tauri.conf.json`, both bump, and race on the push-with-rebase loop at
|
||||
`margin/.github/workflows/release.yml:62-74`. The three `ci.yml` files do have one, identical in all
|
||||
three (`group: ci-${{ github.ref }}`, `cancel-in-progress: true`): another three-way copy.
|
||||
|
||||
Cargo is cached everywhere through `swatinem/rust-cache@v2`. pnpm is cached nowhere: no workflow
|
||||
sets `cache: pnpm` on `setup-node`, so every job downloads the whole tree fresh.
|
||||
|
||||
### Matrix and runners
|
||||
|
||||
margin, `release.yml:88-102`: three rows, `macos-26` universal, `ubuntu-latest`, `windows-latest`.
|
||||
Only margin builds Windows, and only margin installs `rpm` (`release.yml:124`). margin-calendar and
|
||||
margin-mail, both `release.yml:88-95`: two rows, `macos-26` universal and `ubuntu-22.04`, both
|
||||
carrying the same comment about 22.04 being the glibc baseline. margin builds Linux on
|
||||
`ubuntu-latest` instead, contradicting the reasoning the other two committed to and producing a
|
||||
bundle with a higher glibc floor. margin-docs, `release.yml:111-117`: no matrix, one `macos-26`
|
||||
runner, with a good comment on why a matrix of one is where a stale Linux row survives.
|
||||
|
||||
margin-mail is the only one that needs two checkouts, `release.yml:101-109`: itself into
|
||||
`rust/margin-mail` and `priyanshujain/margin` into `python/margin`, because `package.json` has
|
||||
`"margin-shared": "file:../../python/margin/shared"`. That forces `defaults.run.working-directory`
|
||||
(`release.yml:97-99`), a different rust-cache workspace path (`release.yml:143`), and
|
||||
`projectPath: rust/margin-mail` on the tauri-action (`release.yml:202`).
|
||||
|
||||
**margin-docs has the same relative dependency and does not do this.**
|
||||
`margin-editor/package.json` declares `margin-shared` at `file:../../python/margin/shared` and
|
||||
`pnpm-lock.yaml:1449` records it under that path, but `margin-editor/.github/workflows/ci.yml:19`
|
||||
and `release.yml:119` each do a single checkout with no sibling repo. `pnpm install
|
||||
--frozen-lockfile` cannot resolve that path. margin-docs CI and margin-docs releases are broken as
|
||||
committed. That is the single most concrete cost of copy-paste here: the fix landed in mail and was
|
||||
never carried back.
|
||||
|
||||
### Which workflow is most evolved
|
||||
|
||||
margin-docs, and it is not close. It is the only one that validates the version string before using
|
||||
it (`release.yml:38-41`), the only one that bumps `Cargo.toml` with a `[package]`-anchored awk pass
|
||||
and then verifies the result (`release.yml:58-75`), the only one whose Apple signing step
|
||||
distinguishes "unconfigured" from "half configured" and fails the second case
|
||||
(`release.yml:176-189`), the only one that checks the manifest version against the tag
|
||||
(`release.yml:227-231`), and the only one that checks `latest.json` carries a signature and not just
|
||||
a url (`release.yml:245-255`). Its comments explain why each check exists.
|
||||
|
||||
margin is the most complete in scope: the only Windows row, the only App Store workflow, the only
|
||||
post-build `codesign`/`spctl`/`stapler` verification (`release.yml:188-197`), the only Homebrew tap
|
||||
job (`release.yml:220-259`), and the only bump step that rewrites `Cargo.lock` (`release.yml:47-52`).
|
||||
margin-calendar is the only one with a Nix job (`release.yml:187-241`). margin-mail is the plainest:
|
||||
the two-repo checkout and nothing else the others lack. Nobody has all of it, and every good idea
|
||||
lives in exactly one repo.
|
||||
|
||||
## tauri.conf.json side by side
|
||||
|
||||
| | margin | margin-calendar | margin-docs | margin-mail |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| productName | Margin | Margin Calendar | Margin Docs | Margin Mail |
|
||||
| version | 0.1.17 | 0.0.5 | 0.0.1 | 0.0.1 |
|
||||
| identifier | studio.margin.app | studio.margin.calendar | studio.margin.docs | studio.margin.mail |
|
||||
| devUrl port | 1420 | 1430 | 1440 | 1450 |
|
||||
| window | 1280x820, min 920x640 | 1360x900, min 880x560 | 1360x900, min 880x600 | 1440x900, min 880x560 |
|
||||
| titleBarStyle | Overlay | Overlay | Overlay | Overlay |
|
||||
| trafficLightPosition | absent | 9,25 | absent | 9,25 |
|
||||
| bundle.targets | `"all"` | app, dmg, appimage, deb | app, dmg | app, dmg, appimage, deb |
|
||||
| category | Productivity | Productivity | Productivity | Productivity |
|
||||
| macOS.minimumSystemVersion | 10.15 | 10.15 | 10.15 | 10.15 |
|
||||
| macOS.hardenedRuntime | true | absent | true | absent |
|
||||
| macOS.signingIdentity | absent | absent | absent | `"-"` |
|
||||
| linux.deb.depends | absent | webkit2gtk-4.1-0, gtk-3-0 | absent | same as calendar |
|
||||
| deep-link plugin | no | yes | no | yes |
|
||||
| resources | dictionaries/en | none | none | none |
|
||||
| copyright | present | absent | absent | absent |
|
||||
|
||||
Line references: `margin/src-tauri/tauri.conf.json:3-5,29,40-47`,
|
||||
`margin-caledar/src-tauri/tauri.conf.json:3-5,49-54,65-75`,
|
||||
`margin-editor/src-tauri/tauri.conf.json:3-5,29-32,43-46`,
|
||||
`margin-mail/src-tauri/tauri.conf.json:3-5,45,56-64`.
|
||||
|
||||
`hardenedRuntime` defaults to `true` in tauri-utils
|
||||
(`~/.cargo/registry/src/index.crates.io-.../tauri-utils-2.9.3/src/config.rs:682`), so the two that
|
||||
omit it get it anyway. Two repos state it and two do not, for no reason.
|
||||
|
||||
The CSP is four variations on one string. All four begin `default-src 'self'; img-src 'self' data:
|
||||
blob:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self';` and end with
|
||||
`connect-src 'self' ipc: http://ipc.localhost`. margin adds `worker-src 'self' blob:`, margin-docs
|
||||
adds that plus `asset: http://asset.localhost` to `img-src`, margin-mail adds `frame-src 'self'`,
|
||||
margin-calendar adds nothing. Every app declares the same five icon paths.
|
||||
|
||||
`bundle.targets: "all"` in margin is why margin gets an rpm and the others do not. It is a default
|
||||
rather than a decision.
|
||||
|
||||
## Signing and notarisation
|
||||
|
||||
Local credentials live in `~/.margin-signing`, overridable with `MARGIN_SIGNING_DIR`. Only two
|
||||
repos reference it. In margin: `scripts/apple-provision.rb:39`, `scripts/apple-secrets.sh:8`,
|
||||
`scripts/mas-upload-local.sh:15`, documented at `docs/publishing.md:213-226`. In margin-mail:
|
||||
`justfile:47` and `docs/release.md:25-26,40`.
|
||||
|
||||
The directory holds, by name: three `.p12` files (`developer-id.p12`, `apple-distribution.p12`,
|
||||
`mac-installer.p12`) each with a sibling `.pass` file, a `.provisionprofile` named after the bundle
|
||||
id, `AuthKey.p8` with `AuthKey.env` beside it holding the key id and issuer, and an env file per
|
||||
bundle id (`studio.margin.app.env`) exporting `APPLE_TEAM_ID`, `APPLE_SIGNING_IDENTITY`,
|
||||
`MAS_APP_IDENTITY` and `MAS_INSTALLER_IDENTITY`. Private keys are generated locally so Apple only
|
||||
ever sees a CSR, and each `.p12` bundles Apple's intermediate so a fresh CI keychain can build a
|
||||
chain (`docs/publishing.md:214-218`).
|
||||
|
||||
`margin/scripts/apple-secrets.sh` pushes all of it into a repository's Actions secrets by piping
|
||||
files straight into `gh secret set` so nothing is echoed (`apple-secrets.sh:17-32`). It is already
|
||||
parameterised: `DIR`, `BUNDLE_ID` and `REPO` are env-overridable (`apple-secrets.sh:8-10`). It could
|
||||
serve all four repos today and does not, because it lives in one of them. margin-mail's local build
|
||||
sources `$MARGIN_SIGNING_DIR/studio.margin.app.env`, hardcoded to margin's bundle id
|
||||
(`justfile:47`), which is right in effect (one certificate covers the team) and wrong in shape.
|
||||
|
||||
The three release workflows arrive at the same signing step by three different routes.
|
||||
margin-calendar has none at all: `release.yml:152-160` passes only the Tauri updater key, so
|
||||
calendar ships unsigned macOS bundles. margin writes only the notarisation `.p8` to disk
|
||||
(`release.yml:159-171`) and passes the certificate variables directly to the action
|
||||
(`release.yml:175-183`). margin-mail exports certificate variables into `$GITHUB_ENV` only when they
|
||||
are non-empty, with a heredoc delimiter, and warns twice when they are not
|
||||
(`release.yml:167-197`). margin-docs does the same with a random heredoc delimiter and a hard
|
||||
failure on the half-configured case (`release.yml:158-197`).
|
||||
|
||||
The secret names have drifted. margin uses `APPLE_API_KEY_ID` as the secret and maps it to
|
||||
`APPLE_API_KEY` in the action environment (`release.yml:183`). margin-mail uses a secret literally
|
||||
called `APPLE_API_KEY` (`release.yml:176`). margin-docs uses the Apple ID and app-specific password
|
||||
route instead: `APPLE_ID`, `APPLE_PASSWORD`, `APPLE_TEAM_ID` (`release.yml:163-165`), which is the
|
||||
one `docs/publishing.md:22-24` explicitly argued against, because the App Store Connect key does
|
||||
notarisation and store upload with one credential to rotate.
|
||||
|
||||
Only margin verifies the result. `release.yml:188-197` runs `codesign --verify --deep --strict`,
|
||||
then `spctl --assess --type execute`, then `xcrun stapler validate`, with a comment that spctl is
|
||||
the check a double-clicking user actually meets. No other repo checks that its signed bundle is
|
||||
notarised.
|
||||
|
||||
### The App Store track
|
||||
|
||||
`margin/appstore/` is listing content, not code: one text file per App Store Connect field under
|
||||
`appstore/metadata/en-US/` (name, subtitle, description, keywords, promotional_text,
|
||||
release_notes, privacy_url, support_url, marketing_url, beta_description), review contact details
|
||||
under `appstore/metadata/`, and five 2560x1600 frames under `appstore/screenshots/` that are a CSS
|
||||
rebuild of the app rather than a screen capture. `margin/target-mas/` is a build output directory,
|
||||
holding `Margin.pkg`; `appstore.yml:125-129` uploads `target-mas/*.pkg` as an artifact.
|
||||
|
||||
`scripts/mas-package.sh` covers the distance Tauri does not: it stamps `CFBundleVersion` from the
|
||||
workflow run number (`mas-package.sh:27-30`), copies the provisioning profile into the bundle before
|
||||
signing, widens permissions so Apple can read every file (`mas-package.sh:33-39`), substitutes
|
||||
`__TEAM_ID__` into `entitlements.mas.plist`, signs nested code first and never with `--deep`, then
|
||||
`productbuild`s the result (`mas-package.sh:44-58`). `entitlements.mas.plist` declares four
|
||||
entitlements, each justified in a comment: app-sandbox, network.client, network.server for the
|
||||
loopback OAuth listener, and files.user-selected.read-write. `src-tauri/Info.plist:8-9` declares
|
||||
`ITSAppUsesNonExemptEncryption` false. Six Ruby scripts drive the Developer Portal and App Store
|
||||
Connect through fastlane's spaceship.
|
||||
|
||||
None of this exists in the other three, and calendar and mail both have a Google OAuth loopback
|
||||
listener, so if either goes to the store it needs the same entitlement and the same review note.
|
||||
|
||||
## The updater
|
||||
|
||||
One endpoint per app, all on GitHub releases:
|
||||
|
||||
| repo | endpoint | pubkey |
|
||||
| --- | --- | --- |
|
||||
| margin | `.../priyanshujain/margin/releases/latest/download/latest.json` | real |
|
||||
| margin-calendar | `.../margin-calendar/releases/latest/download/latest.json` | real |
|
||||
| margin-docs | `.../margin-docs/releases/latest/download/latest.json` | `REPLACE_WITH_TAURI_SIGNER_PUBKEY` |
|
||||
| margin-mail | `.../margin-mail/releases/latest/download/latest.json` | `REPLACE_WITH_THE_MINISIGN_PUBLIC_KEY` |
|
||||
|
||||
All at line 8 to 11 of each `src-tauri/tauri.release.conf.json`. Two of the four have never had a
|
||||
keypair generated, so neither has released.
|
||||
|
||||
**All four already use the overlay workaround.** No `tauri.conf.json` carries
|
||||
`plugins.updater.pubkey`; all four keep it plus `bundle.createUpdaterArtifacts: true` in
|
||||
`tauri.release.conf.json`, merged with `--config src-tauri/tauri.release.conf.json` in the build
|
||||
args. What did not propagate is the reason. Only margin records it, and only outside `docs/`:
|
||||
`simplify/guidelines/distribution.md:44` and `simplify/.research/memories-raw.md:283` name
|
||||
tauri-apps/tauri#14581, that the mere presence of the pubkey makes `tauri build` demand a signing
|
||||
key and would break the key-free local build (`margin/package.json` still has `"dmg": "tauri build
|
||||
--bundles dmg"` with no overlay). The three sibling `docs/release.md` files describe the overlay as
|
||||
"where the public half lives" and give no reason, so the next person to tidy a config has nothing
|
||||
telling them not to inline it.
|
||||
|
||||
The overlay carries a second job nobody has written down: it is the flag that switches the plugin
|
||||
on. Every app registers the plugin conditionally on the merged config, ported verbatim four times:
|
||||
`margin/src-tauri/src/lib.rs:159-161`, `margin-caledar/src-tauri/src/lib.rs:260-262`,
|
||||
`margin-editor/src-tauri/src/lib.rs:263-265`, `margin-mail/src-tauri/src/lib.rs:265-267`. Two of the
|
||||
comments say "Ported from margin's lib.rs" outright.
|
||||
|
||||
`margin/src-tauri/src/updates.rs` is the only per-channel logic anywhere. `channel()` at lines 17 to
|
||||
26 reads which plugin key the merged config declares, `updater` meaning direct download and
|
||||
`appstore` meaning store, and a `_MASReceipt` in the bundle overrides both (lines 28 to 37), so a
|
||||
store build cannot self-update even if built with the updater in it. `appstore_latest()` at lines 51
|
||||
to 84 asks `itunes.apple.com/lookup` with a cache-busting timestamp. No sibling has or needs this.
|
||||
|
||||
Release notes are surfaced but empty. All four create the draft with `--notes "Release $TAG"`
|
||||
(`release.yml:78` in calendar, docs and mail; `:84` in margin), tauri-action copies the release body
|
||||
into `latest.json`, so `update.body` is the literal string "Release v0.1.18".
|
||||
`margin-editor/src/update.ts:79` passes that into `useUpdate.offer(version, notes)`, which
|
||||
`store/useUpdate.ts:39` calls "the release notes, as the release wrote them".
|
||||
|
||||
The four update UIs are four different things: margin has `src/updater.ts` (111 lines) plus an
|
||||
`UpdateDialog.tsx` and a store; margin-docs has the most developed, `src/update.ts` (171 lines) with
|
||||
a daily background check, a 6 second launch delay and explicit handling of "this build has no
|
||||
updater in it" (`update.ts:39-56`); margin-calendar has a 41 line toast-only version
|
||||
(`src/keys/updates.ts`) whose header says it is margin's minus the dialog; margin-mail has no
|
||||
updater module, just an inline `checkForUpdates` in `App.tsx:98-118` and a panel in
|
||||
`screens/Settings.tsx:2465-2540`.
|
||||
|
||||
`packaged_by()` is the Nix escape hatch, ported twice: `margin-caledar/src-tauri/src/lib.rs:240-245`
|
||||
reading `MARGIN_CALENDAR_PACKAGED_BY`, `margin-mail/src-tauri/src/lib.rs:197-201` reading
|
||||
`MARGIN_MAIL_PACKAGED_BY`. mail reads a variable nothing sets, because mail has no Nix package.
|
||||
|
||||
## Versioning
|
||||
|
||||
Three files per app, all bumped by the release workflow and by nothing else: `.version` in
|
||||
`src-tauri/tauri.conf.json`, `.version` in `package.json`, and `[package] version` in
|
||||
`src-tauri/Cargo.toml`. `tauri.conf.json` is the source of truth, since the "leave empty to bump the
|
||||
patch" path reads it (`release.yml:31` in all four). All four are consistent right now: margin
|
||||
0.1.17, calendar 0.0.5, docs 0.0.1, mail 0.0.1, with `Cargo.lock` matching in each.
|
||||
|
||||
Nothing enforces it. There is no check in any `ci.yml` that the three agree, so the only thing
|
||||
keeping them together is that a human never edits one by hand.
|
||||
|
||||
The `Cargo.lock` problem is history rather than theory. Only margin bumps the lock, with an awk pass
|
||||
and a comment explaining that the lock records the crate's own version
|
||||
(`margin/.github/workflows/release.yml:47-52`), and it is the only repo that adds `Cargo.lock` to
|
||||
the release commit (`:60`). margin-calendar does not, and its history carries two manual repair
|
||||
commits for exactly this: `3754e4a Sync the lock file to the version the crate declares` and
|
||||
`ae5a7b4 let cargo.lock catch up with the 0.0.4 bump`. docs and mail have the same gap and have not
|
||||
released yet.
|
||||
|
||||
The bump itself is three different implementations. margin and margin-mail and margin-calendar use
|
||||
`sed -i "0,/^version = \".*\"/s//.../"` on `Cargo.toml`, which takes the first `version =` line in
|
||||
the file. margin-docs replaced it with a `[package]`-anchored awk pass plus a verification grep
|
||||
(`release.yml:58-75`), with a comment explaining that a long-form dependency puts `version = "0.4"`
|
||||
on its own line and bumping that one ships the version before. margin-mail's `Cargo.toml` is 6568
|
||||
bytes with many long-form dependencies, so it is the repo most exposed to the bug and it has the old
|
||||
code.
|
||||
|
||||
## Linux, Windows, mobile
|
||||
|
||||
What each app actually ships:
|
||||
|
||||
| repo | macOS | Linux | Windows | store |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| margin | universal dmg, signed and notarised, Homebrew cask | deb, rpm, AppImage from ubuntu-latest | msi and nsis from windows-latest | Mac App Store pkg |
|
||||
| margin-calendar | universal dmg, unsigned | deb and AppImage from ubuntu-22.04, plus a Nix flake | none | none |
|
||||
| margin-docs | universal dmg, ad hoc signed today | none | none | none |
|
||||
| margin-mail | universal dmg, ad hoc signed today | deb and AppImage from ubuntu-22.04 | none | none |
|
||||
|
||||
margin-calendar's `flake.nix` is 21 lines: one input, one system (`x86_64-linux`), an overlay and a
|
||||
package, both calling `nix/package.nix`. That file is 113 lines and repackages the published `.deb`
|
||||
rather than building from source, justified at lines 1 to 4 by the OAuth client being embedded at
|
||||
compile time from a file that is not in the repo. `autoPatchelfHook` relinks it against nixpkgs'
|
||||
webkit2gtk so it runs as a native Wayland client instead of the AppImage's Xwayland fallback, a
|
||||
generated launcher points libglvnd at nixpkgs' Mesa when `/run/opengl-driver` is absent
|
||||
(`package.nix:68-94`), and `preFixup` sets `MARGIN_CALENDAR_PACKAGED_BY=nix` (`package.nix:98-103`).
|
||||
|
||||
`nix/release.json` is the pin, `{version, hash}`, currently 0.0.5. The `nix` job
|
||||
(`release.yml:187-241`) runs after publish, downloads the deb, hashes it, writes the pin, builds the
|
||||
package as proof, and pushes the pin to main with the same rebase loop as the version bump.
|
||||
`ci.yml:74-81` rebuilds it on every push. This replaced an AUR package, rationale at
|
||||
`docs/release.md:41-81`; no AUR file is left in the tree.
|
||||
|
||||
margin-mail reads `MARGIN_MAIL_PACKAGED_BY` and documents the Nix behaviour at `docs/release.md:116-119`
|
||||
but ships no flake, so that path is dead code today.
|
||||
|
||||
Mobile is scaffolded in two repos. `margin/src-tauri/gen/apple` is a committed iOS Xcode project;
|
||||
`margin-caledar/src-tauri/gen/` has both `apple` and `android` tracked, including
|
||||
`app/src/main/java/studio/margin/calendar/MainActivity.kt`. margin-docs and margin-mail have only
|
||||
`gen/schemas`, though margin-mail's include `iOS-schema.json` and `mobile-schema.json`.
|
||||
|
||||
The desktop-only cfg gating is the same three lines in three repos, with the same comment ("There is
|
||||
no auto-updater and no process to restart on a phone: the store is the update channel"):
|
||||
`margin-caledar/src-tauri/Cargo.toml:43-46`, `margin-editor/src-tauri/Cargo.toml:84-87`,
|
||||
`margin-mail/src-tauri/Cargo.toml:134-137`, each gating `tauri-plugin-process` and
|
||||
`tauri-plugin-updater` behind `cfg(not(any(target_os = "android", target_os = "ios")))`. margin, the
|
||||
repo that actually has a committed iOS project, does not gate them:
|
||||
`margin/src-tauri/Cargo.toml:24-25` has both unconditional. `capabilities/desktop.json` is in all
|
||||
four with the same two permissions, `updater:default` and `process:allow-restart`.
|
||||
|
||||
`src-tauri/build.rs` is two files across four repos: margin and margin-docs share one (39 bytes),
|
||||
margin-calendar and margin-mail share the credential-embedding one (1171 bytes), byte-identical.
|
||||
|
||||
## docs/release.md
|
||||
|
||||
margin-calendar 105 lines, margin-docs 117, margin-mail 119. margin has none; its equivalent is
|
||||
`docs/publishing.md`, 229 lines, covering three distribution channels the others do not have.
|
||||
|
||||
The "Installing locally" opening is near-identical in all three, down to "It is the same command
|
||||
whether or not the app is already installed, so it doubles as the update" and the sentence about a
|
||||
bundle going half old and half new. "Cutting a release" is the same paragraph in all three with the
|
||||
app's own manifest list. "Windows is not built" appears in all three, calendar and mail sharing the
|
||||
identical follow-up about a runner, `msi`/`nsis`, and the gate then wanting `windows-x86_64`.
|
||||
|
||||
Where they genuinely diverge: calendar has a 41 line Linux and Nix section nobody else has; docs has
|
||||
a long honest section on self-update being impossible until a Developer ID certificate exists
|
||||
(`docs/release.md:105-117`) and a paragraph on why the bundle asks for the hardened runtime and no
|
||||
entitlements; mail has a Signing section built around `~/.margin-signing` with a `gh secret set`
|
||||
recipe (`docs/release.md:37-48`) and a "Before the first release" section covering both the missing
|
||||
updater key and Google restricted scope verification.
|
||||
|
||||
The signing advice contradicts itself across the set. docs tells the reader to use `APPLE_ID` and an
|
||||
app-specific password (`docs/release.md:73-75`), mail and margin tell them to use an App Store
|
||||
Connect key. Both cannot be the house rule.
|
||||
|
||||
## margin/website
|
||||
|
||||
Astro 5, one page, deployed by hand: `package.json` has `"deploy": "astro build && npx wrangler
|
||||
pages deploy dist --project-name=margin --commit-dirty=true"`. No workflow deploys it.
|
||||
|
||||
Downloads resolve at build time, not at request time. `website/src/data/release.ts:29-45` fetches
|
||||
`api.github.com/repos/priyanshujain/margin/releases/latest`, picks one asset per platform by
|
||||
filename suffix from `site.ts:40-43` (`.dmg`; `.exe` then `.msi`; `.deb` then `.AppImage` then
|
||||
`.rpm`), and falls back to the releases page on any error including the 8 second timeout. Astro runs
|
||||
that once at build, so the buttons point at whatever was latest when the site was last deployed and
|
||||
a release not followed by a deploy leaves stale links. `site.ts:23` carries the repo slug, so the
|
||||
whole thing is one constant away from serving a sibling app.
|
||||
|
||||
## What to build
|
||||
|
||||
**One reusable workflow, `workflow_call`, in a shared repo.** The publish job goes in verbatim, the
|
||||
prepare job goes in with the title as an input, and the build job goes in with the matrix as an
|
||||
input. Inputs the four repos actually differ on, and nothing else:
|
||||
|
||||
- `app-name`: release title and, on margin, the dmg filename in the Homebrew job.
|
||||
- `platforms`: a list like `macos,linux,windows`, driving both the build matrix and the
|
||||
`latest.json` key list in publish. Those two must not be able to disagree; today they are two
|
||||
hand-edited lists in every repo.
|
||||
- `linux-runner`: default `ubuntu-22.04`, since three repos already agree that is the right glibc
|
||||
baseline and margin's `ubuntu-latest` is an oversight.
|
||||
- `project-path` and `sibling-repos`: empty for margin and calendar, `rust/margin-mail` plus
|
||||
`priyanshujain/margin` for mail, and the same for docs, which needs it and does not have it.
|
||||
- `needs-google-credentials`: boolean. margin, calendar and mail true; docs false.
|
||||
- `post-publish`: which trailing job runs, `homebrew` for margin, `nix` for calendar, none for the
|
||||
others. These are different enough that they should be separate reusable workflows the caller
|
||||
chains, not a flag.
|
||||
|
||||
Take margin-docs' version validation, its `[package]`-anchored Cargo bump, its manifest-version and
|
||||
signature checks, and its half-configured signing failure as the baseline; add margin's `Cargo.lock`
|
||||
bump and its `codesign`/`spctl`/`stapler` verification. That combination exists in no repo today.
|
||||
Add `concurrency: group: release-${{ github.repository }}, cancel-in-progress: false` and `cache:
|
||||
pnpm` on `setup-node`, neither of which exists anywhere.
|
||||
|
||||
The three `ci.yml` files should share a second reusable workflow with the same inputs plus a
|
||||
`rust-test-command` and an `extra-frontend-steps` hook, since margin-docs splits its Rust suite
|
||||
(`ci.yml:58,78`) and margin-mail adds docs and fonts checks (`ci.yml:44,51`). margin must call it.
|
||||
|
||||
**A shared tauri.conf fragment.** Generate rather than fragment: Tauri's `--config` merge only helps
|
||||
at build time and the committed file still has to be readable. A small script in the shared package
|
||||
that takes app name, identifier, dev port, window size, targets and any extra CSP directives, and
|
||||
writes `tauri.conf.json`, with a `--check` mode wired into CI the way `pnpm fonts:check` already is.
|
||||
That kills four copies of the icon list, the category, the min system version, the base CSP and the
|
||||
window defaults, and it makes the odd ones out visible: margin's `targets: "all"` and the two
|
||||
repos that state `hardenedRuntime` redundantly.
|
||||
|
||||
`tauri.release.conf.json` is four lines of structure and one pubkey. Generate it the same way, and
|
||||
put the tauri#14581 reason in the generator's header so it survives the next cleanup.
|
||||
|
||||
**One signing procedure, documented once.** `margin/docs/publishing.md:193-229` plus
|
||||
`margin-mail/docs/release.md:18-48` is already the whole thing; it needs to be one page in the shared
|
||||
repo covering `~/.margin-signing`'s layout, the three certificate types and why they cannot be
|
||||
combined, and the App Store Connect key as the single notarisation credential. Settle the
|
||||
`APPLE_ID` versus API key question in favour of the key, and fix margin-docs' workflow to match.
|
||||
Move `scripts/apple-secrets.sh` and `apple-provision.rb` into the shared repo unchanged: they are
|
||||
already parameterised by `DIR`, `BUNDLE_ID` and `REPO`. Standardise on `APPLE_API_KEY_ID` as the
|
||||
secret name in all four, since margin and mail currently disagree. Add the `spctl` and `stapler`
|
||||
verification to the shared build job so margin-calendar stops shipping unsigned macOS bundles
|
||||
without anyone noticing.
|
||||
|
||||
**One versioning convention.** `tauri.conf.json` is the source, the workflow writes `package.json`,
|
||||
`Cargo.toml` and `Cargo.lock`, and a CI check asserts all four agree. Roughly ten lines, and it
|
||||
would have prevented both of margin-calendar's manual repair commits. While there, replace
|
||||
`--notes "Release $TAG"` with `--generate-notes` or an extracted `CHANGELOG.md` section, since it
|
||||
feeds a dialog margin-docs already built.
|
||||
|
||||
## What genuinely cannot be shared
|
||||
|
||||
The identifiers, product names, dev ports, window sizes and the CSP additions each app needs;
|
||||
those are inputs, not duplication.
|
||||
|
||||
margin's App Store track. The listing text, the screenshots, the entitlements and the six Ruby
|
||||
scripts are about one app's submission. `mas-package.sh` and `entitlements.mas.plist` could be
|
||||
templated later if a second app goes to the store, but there is no second app and templating for a
|
||||
hypothetical one is worse than copying it when the day comes.
|
||||
|
||||
margin's Homebrew job and margin-calendar's Nix job. Both are per-app distribution channels with
|
||||
per-app asset names, per-app tap or flake repos, and a per-app credential. They can be reusable
|
||||
workflows the caller chains, but they are not one job with a flag.
|
||||
|
||||
`margin/website`. It is one product's marketing site, with pricing, an offer counter and store
|
||||
logos. `data/release.ts` is genuinely generic and could move to the shared package if a second app
|
||||
ever gets a site.
|
||||
|
||||
The updater UIs. Four apps have four different answers to what should happen when an update is
|
||||
found, and margin's App Store channel logic in `updates.rs` has no meaning in the other three. The
|
||||
plugin registration block, the `packaged_by` command and the `capabilities/desktop.json` permissions
|
||||
are the same three things four times over and are worth sharing; the dialogs are not.
|
||||
|
||||
The per-app minisign keypair. One key per app is correct: the pubkey is baked into every shipped
|
||||
binary and cannot be rotated without stranding installed copies, so a shared key would make one
|
||||
compromise a four-app problem.
|
||||
@@ -0,0 +1,399 @@
|
||||
# The visual design system across the four apps
|
||||
|
||||
Scope: CSS only. Tokens, fonts, the base layer, themes, and the layout idioms that repeat.
|
||||
|
||||
Short names below: `margin` = /Users/pj/Workspace/projects/python/margin, `calendar` =
|
||||
/Users/pj/Workspace/projects/python/margin-caledar, `editor` =
|
||||
/Users/pj/Workspace/projects/rust/margin-editor, `mail` = /Users/pj/Workspace/projects/rust/margin-mail.
|
||||
Between them: margin 3 CSS files and 2983 lines, calendar 11 and 3796, editor 21 and 5089, mail 47
|
||||
and 6571. 18439 lines total.
|
||||
|
||||
## What margin-shared already is, and who takes it
|
||||
|
||||
`/Users/pj/Workspace/projects/python/margin/shared` ships `css/tokens.css` (35 distinct custom
|
||||
property names), `css/fonts.css` (12 `@font-face` rules, 6 families), `fonts/` (18 files: 12 TTFs
|
||||
and 6 OFL notices), `src/fonts.ts`, `src/icons.ts` and `bin/sync-fonts.mjs`.
|
||||
|
||||
Three of the four consume it. margin declares `"margin-shared": "file:./shared"`, editor and mail
|
||||
both declare `"file:../../python/margin/shared"`. Calendar does not depend on it at all and does not
|
||||
import either stylesheet.
|
||||
|
||||
The seams are thin and consistent in the three that do:
|
||||
|
||||
- margin/src/styles/tokens.css:3 imports the shared tokens, then adds exactly one line, `--pane-dock: 384px`.
|
||||
- editor/src/styles/tokens.css:5 imports, then adds 51 tokens of its own (document scale, sheet padding, code surface).
|
||||
- mail/src/styles/tokens.css:6 imports, then imports `./mail.css`, which adds 46.
|
||||
|
||||
## Tokens
|
||||
|
||||
### Calendar is a 49-of-52 copy of the shared file
|
||||
|
||||
calendar/src/styles/tokens.css is not a divergent palette. Comparing it block for block against
|
||||
shared/css/tokens.css:
|
||||
|
||||
- `:root`: 11 of 11 comparable values byte-identical (`--font-ui`, `--font-heading`, `--r-sm/md/lg`,
|
||||
`--titlebar-h`, `--t-1` through `--t-4`, `--ease`). Absent: `--font-book`, `--pane-sidebar`,
|
||||
`--measure`, which a calendar has no use for.
|
||||
- light block: 19 of 20 identical. One drift.
|
||||
- dark block: 19 of 20 identical. Same one drift.
|
||||
- Absent from both palettes: `--sidebar`, correctly, since the grid owns the window and there is no sidebar.
|
||||
|
||||
The one drift is `--ink-faint`. Shared has `#9b9484` light and `#756d5e` dark; calendar
|
||||
(tokens.css:74, :126) and mail (mail.css:86, :142) both have `#6e675b` and `#8e8677`.
|
||||
|
||||
Two apps independently moved the same token to the same two values for the same stated reason
|
||||
(4.5:1 contrast on the surfaces faint ink lands on; the calendar comment names the hour axis, the
|
||||
mail comment names list times and snippets and says "same reasoning, same value, as the calendar's
|
||||
hour axis"). Editor and margin still take `#9b9484`. That is not two apps needing to differ, it is
|
||||
the shared value being wrong and two apps finding out separately. Move the pair upstream and delete
|
||||
both overrides.
|
||||
|
||||
### Tokens defined in more than one app under different names, or defined in one and hardcoded in another
|
||||
|
||||
- `--scrim`. Not in shared. Light is `rgba(35, 32, 27, 0.28)` in all three that have it (calendar
|
||||
tokens.css:84, editor tokens.css:14, mail mail.css:88). Dark: calendar and mail `rgba(0, 0, 0, 0.58)`,
|
||||
editor tokens.css:26 `rgba(0, 0, 0, 0.5)`. margin has no token and writes the light literal into
|
||||
`.overlay` at app.css:1275 and a second, different one, `rgba(35, 32, 27, 0.32)`, into
|
||||
`.export-overlay` at app.css:1449. This belongs in shared.
|
||||
- `--shadow-raised`. editor tokens.css:15 `0 1px 2px rgba(35, 32, 27, 0.05)`, dark
|
||||
`0 1px 2px rgba(0, 0, 0, 0.35)`. margin writes that light value as a literal twice, app.css:272
|
||||
and app.css:1839.
|
||||
- `--r-pill: 999px`. Declared separately in calendar tokens.css:8, editor tokens.css:10 and mail
|
||||
mail.css:12, identically. margin writes `border-radius: 999px` as a literal at app.css:2184. Four
|
||||
apps, one value, three declarations and one literal.
|
||||
- `--t-5: 16px`. calendar tokens.css:34, editor tokens.css:12, mail mail.css:17. Identical, and the
|
||||
comment in calendar and mail is nearly word for word the same (iOS zooms a field under 16px).
|
||||
- `--touch-h: 44px`. calendar tokens.css:22, editor tokens.css:11, mail mail.css:31. Identical.
|
||||
- `--traffic-pad: 84px`. calendar tokens.css:11, editor tokens.css:11, mail mail.css:36. Identical;
|
||||
margin has no token and hardcodes the lane unconditionally, see the drift section.
|
||||
- `--safe-top` / `--safe-bottom` / `--phonebar-h: 48px` / `--tabbar-h: 56px` / `--sheet-max-h: 88dvh`.
|
||||
calendar tokens.css:16-26 and mail mail.css:26-34, identical values and near-identical comments.
|
||||
A five-token phone chrome block written twice.
|
||||
- calendar `--cal-1` through `--cal-8` (tokens.css:106-113 light, :160-167 dark) and mail `--hue-1`
|
||||
through `--hue-8` (mail.css:115-121, :159-166) are the same sixteen hexes under two names. mail's
|
||||
own comment says so: "the calendar's --cal-1..8 under a name that says what they are for here".
|
||||
|
||||
### App-only tokens that should stay app-only
|
||||
|
||||
editor's 51 additions are document typography and sheet geometry (`--doc-h1` through `--doc-h6`,
|
||||
`--measure-*`, `--sheet-pad-*`, `--code-*`, `--pdf-page`). mail's 46 are mail geometry (`--list-w`,
|
||||
`--avatar`, `--pile-h`, `--compose-w`, `--feed-w`, the `--message-*` set that deliberately does not
|
||||
follow the theme). Calendar's are grid geometry (`--gutter-w`, `--daybar-h`, `--strip-h`,
|
||||
`--event-*`, `--grid-*`, `--fold-*`). margin's is `--pane-dock: 384px`. All genuinely single-app.
|
||||
|
||||
Note the collision: `--row-h` means a calendar grid row (48px, calendar tokens.css:44) in one app and
|
||||
a message list row (46px, mail mail.css:45) in the other. A reason not to promote geometry by name.
|
||||
|
||||
## Fonts
|
||||
|
||||
The bytes are already correct. All 18 files in shared/fonts are byte-identical to the copies in
|
||||
margin/public/fonts, editor/public/fonts and mail/public/fonts (verified with `cmp`, 18/18 each).
|
||||
Calendar vendors only 4 of them, `HankenGrotesk-VF.ttf`, `HankenGrotesk-Italic-VF.ttf`,
|
||||
`Literata-VF.ttf`, `Literata-Italic-VF.ttf`, and those 4 are byte-identical to shared too. It ships
|
||||
no OFL notices, which is the one real problem here: the other three ship all six.
|
||||
|
||||
`shared/bin/sync-fonts.mjs` copies every `.ttf` and `.txt` from shared/fonts into
|
||||
`<app>/public/fonts`, or with `--check` compares and exits 1 on any difference; a file present in
|
||||
the app and absent from the package is reported and left alone rather than deleted (lines 53-59).
|
||||
The vendored copies exist because both PDF exporters read the same paths with `include_bytes!`, so
|
||||
cargo must not wait on an npm install.
|
||||
|
||||
Who runs it: margin and editor as `node node_modules/margin-shared/bin/sync-fonts.mjs .`, mail as
|
||||
`margin-shared-fonts .` through the package's `bin` entry. Calendar has no `fonts:sync` or
|
||||
`fonts:check` script and no way to notice drift.
|
||||
|
||||
margin, editor and mail's src/styles/fonts.css are each a comment and one
|
||||
`@import "margin-shared/css/fonts.css"`; margin's and editor's are byte-identical including the
|
||||
comment. calendar/src/styles/fonts.css is 31 lines of hand-written `@font-face` for the four faces
|
||||
it vendors, character-for-character the same as shared/css/fonts.css:17-47. Calendar joining costs
|
||||
one import, one script pair, and 8 more files in public/fonts.
|
||||
|
||||
## The base layer in app.css
|
||||
|
||||
All four start with the same reset. Measured by parsing each app.css into selector/body pairs and
|
||||
comparing bodies exactly:
|
||||
|
||||
- margin x editor: 71 selectors in common, 59 with byte-identical bodies.
|
||||
- calendar x mail: 22 in common, 16 identical.
|
||||
- calendar x editor: 23 in common, 15 identical.
|
||||
- margin x calendar: 20 in common, 11 identical.
|
||||
- editor x mail: 15 in common, 10 identical.
|
||||
- margin x mail: 15 in common, 7 identical.
|
||||
|
||||
Identical in all four, no exceptions: `*`, `html, body, #root`, `body`, `::selection`,
|
||||
`:focus-visible`. The focus ring is the same three lines everywhere (margin app.css:43, calendar
|
||||
app.css:80, editor app.css:51, mail app.css:92):
|
||||
|
||||
```css
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
```
|
||||
|
||||
And the body block, identical in all four (margin app.css:16, calendar app.css:16, editor app.css:16,
|
||||
mail app.css:26):
|
||||
|
||||
```css
|
||||
body {
|
||||
margin: 0;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
overscroll-behavior: none;
|
||||
background: var(--shell);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--t-3);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
```
|
||||
|
||||
Near-duplicates, with the differences named:
|
||||
|
||||
- `button`. margin app.css:34, calendar app.css:63 and editor app.css:34 are identical seven-line
|
||||
blocks. mail app.css:70 adds one line, `font-size: inherit`. That line is right and the other
|
||||
three are missing it.
|
||||
- `html`. margin and editor stop at `text-size-adjust`. calendar app.css:37 and mail app.css:23 both
|
||||
add `-webkit-tap-highlight-color: transparent` with the same three-line comment about a webview
|
||||
reading every tap as a text selection. Two apps have the fix, two do not.
|
||||
- `input, textarea, select`. Identical in calendar app.css:72, editor app.css:43, mail app.css:80.
|
||||
margin does not have it at all, so its fields fall back to the webview's font.
|
||||
- `.app`. calendar app.css:86, editor app.css:58 and mail app.css:100 are identical
|
||||
(`display:flex; flex-direction:column; height:100%; overflow:hidden`). margin app.css:59 uses
|
||||
`height: 100vh; height: 100dvh`, which the other three have deliberately moved away from; the
|
||||
comment at calendar app.css:89-97 explains why.
|
||||
- `:root[data-touch] .icon-button`, `.icon-button`, `.icon-button:hover`: identical between calendar
|
||||
app.css:145-170 and editor app.css:138-165. margin calls the same control `.icon-btn` and draws it
|
||||
30px instead of 28px (app.css:103). mail folded it into `.button[data-icon-only]` (ui/Button.css:33).
|
||||
Four apps, one control, three names and two sizes.
|
||||
|
||||
`::-webkit-scrollbar` exists in exactly one app, margin app.css:693-712 (11px, thumb `--line-strong`
|
||||
with a 3px transparent border and `background-clip: content-box`, hover `--ink-faint`, transparent
|
||||
track). The other three take the webview default. Editor gets the temperature right a different way,
|
||||
via `color-scheme` in themes.css. Only editor declares `color-scheme` at the root
|
||||
(themes.css:24-31 and once per palette); calendar declares it on one element,
|
||||
create.css:53 and :57, on the quick-create card.
|
||||
|
||||
`@media (prefers-reduced-motion: reduce)`: mail has 11 (app.css:208, Banner.css:64, pane.css:297 and
|
||||
:358, arriving.css:78, search.css:36, list.css:126, tour.css:29, contacts.css:56, :215, :306), editor
|
||||
1 (export-preview.css:167), calendar 0, margin 0. Calendar and margin both animate
|
||||
(`quick-create-in`, `sheet-up`, `find-drop`, `drawer-in-right`, `spin`) with no guard.
|
||||
|
||||
## The overlay and panel shell
|
||||
|
||||
The same box in all four, and it is the single largest near-duplicate in the codebase.
|
||||
|
||||
`.overlay` is identical in calendar app.css:330, editor app.css:451 and mail app.css:110:
|
||||
`position:fixed; inset:0; z-index:20; background:var(--scrim); backdrop-filter:blur(2px);
|
||||
display:grid; place-items:center; padding:40px`. margin app.css:1271 is the same rule with
|
||||
`background: rgba(35, 32, 27, 0.28)` written out instead of a token.
|
||||
|
||||
`.panel` is byte-identical in all four (margin app.css:1283, calendar app.css:342, editor app.css:463,
|
||||
mail app.css:129): `width: min(480px, calc(100vw - 32px)); max-height:100%; flex column; --paper;
|
||||
1px --line; --r-lg; --shadow-pop; overflow:hidden`.
|
||||
|
||||
`.panel-body` is byte-identical in all four. `.panel-foot` is identical in margin, calendar and
|
||||
editor; mail adds `flex: none`. `.panel-head`: margin, calendar and mail use `padding: 16px 14px 16px 22px`,
|
||||
editor uses `16px 16px 16px 22px` with a comment at app.css:475-478 explaining the two pixels; mail
|
||||
also adds `flex: none`, `gap: 10px` and a `flex: 1; min-width: 0` on the `h2`. `.panel-head h2` is
|
||||
`font-family: var(--font-book)` in margin and editor and `var(--font-heading)` in calendar and mail,
|
||||
which is a real fork: shared/css/tokens.css sets both to Literata by default, but editor lets a
|
||||
document override `--font-book` at runtime and mail lets a setting override `--font-heading`, so the
|
||||
same declaration means different things.
|
||||
|
||||
Phone docking is written twice, identically, comments included. calendar app.css:356-390 and mail
|
||||
app.css:179-206 both carry `:root[data-phone] .overlay` (z-index 50, padding 0,
|
||||
`place-items: end center`), `:root[data-phone] .panel` (full width, `--sheet-max-h`, border-width
|
||||
`1px 0 0`, radius `var(--r-lg) var(--r-lg) 0 0`, `padding-bottom: var(--safe-bottom)`,
|
||||
`animation: sheet-up 180ms var(--ease)`), `:root[data-phone] .panel-body { overscroll-behavior: contain }`
|
||||
and `@keyframes sheet-up`. mail adds the reduced-motion guard, calendar does not.
|
||||
`.overlay[data-align="top"] { align-items: start; padding-top: 12vh }` appears three times: calendar
|
||||
palette.css:4, editor palette.css:9, mail app.css:124.
|
||||
|
||||
Panel sizes are the same idiom under two names: calendar overlays.css:9-20
|
||||
`.overlay-panel[data-size="mini"]` at `min(292px, calc(100vw - 32px))` and `wide` at 560px, mail
|
||||
Sheet.css:4-15 `.sheet[data-size="mini"]` at the identical 292px and `wide` at 620px. Both give mini
|
||||
the same `.panel-body { gap: 10px; padding: 12px 12px 14px }`.
|
||||
|
||||
## Buttons and fields
|
||||
|
||||
Three of the four have converged on the same text button by three different routes.
|
||||
|
||||
calendar overlays.css:60-135 `.panel-button` and mail ui/Button.css:1-98 `.button` are the same
|
||||
control: `inline-flex`, `gap: 7px`, `1px solid var(--line-strong)`, `var(--r-sm)`, `var(--raised)`
|
||||
ground, `--accent-wash` hover, and `[data-variant="primary" | "danger" | "ghost"]` with the same
|
||||
bodies (primary is accent ground with `--accent-contrast` ink hovering to `--accent-ink`; danger is
|
||||
`--danger-ink` text hovering to `--danger-wash` with a `--danger` border; ghost is transparent border
|
||||
and `--ink-soft`). The differences are the selector, the sizing (calendar pins `min-height: 30px`,
|
||||
mail has `[data-size="sm|md|lg"]` at 26/28/32) and mail's `[data-icon-only]` square. Both end with
|
||||
`:root[data-touch] { min-height: var(--touch-h) }`. editor settings.css:319 `.btn-quiet` and margin
|
||||
app.css:1769-1805 `.btn-primary` / `.btn-ghost` / `.btn-danger` are a third and fourth spelling of
|
||||
the same three variants; margin's danger is filled rather than outlined and it pads `9px 20px`.
|
||||
|
||||
Fields: calendar overlays.css:140-216 (`.field-input`, `.field-select`, `.field-textarea`,
|
||||
`.field-hint`, `.field-check`) and mail ui/Field.css:18-59 are the same rules to within the padding
|
||||
(`6px 9px` vs `7px 10px`) and mail's added `:disabled` and `::placeholder` blocks. Both hover to
|
||||
`border-color: var(--ink-faint)`. margin app.css:1333-1348 is a third version on `.field input,
|
||||
.field select` with `padding: 9px 11px` and a `:focus { border-color: var(--accent) }` the other two
|
||||
lack. `.field` and `.field-label` are byte-identical between margin app.css:1318-1331, calendar
|
||||
app.css:423-435 and mail ui/Field.css:1-16 (uppercase, `--t-1`, 600, `0.08em`, `--ink-faint`), which
|
||||
is also exactly mail's `.group-head` (ui/GroupHead.css:1-11) and margin's and editor's `.nav-label`.
|
||||
mail duplicates its own field twice more, at screens/settings.css:448-471 and :306.
|
||||
|
||||
The switch: editor settings.css:343-380 `.switch` / `.switch-knob` and mail ui/Toggle.css:1-40
|
||||
`.toggle` / `.toggle-knob` are the same control at two sizes (38x22 with a 16px knob travelling 16px,
|
||||
against 34x20 with a 14px knob travelling 14px). Same `--r-pill` track, `--line-strong` border,
|
||||
`[data-on]` filling with `--accent`, knob turning `--accent-contrast`. mail adds a touch size
|
||||
(46x28); editor does not.
|
||||
|
||||
The keycap: calendar palette.css:105-118 `.key` and mail ui/Key.css:1-17 `.key[data-size="md"]` are
|
||||
byte-identical apart from mail moving the padding onto a size attribute. editor has a third,
|
||||
`.key-cap` at tree.css:744, an `--accent-wash` chip with no border; margin a fourth, `.esc-hint kbd`
|
||||
at app.css:2191.
|
||||
|
||||
Segmented control: mail ui/Segment.css:3-30 `.segment` / `.segment-option` and calendar app.css:483-508
|
||||
`.view-switch` / `.view-option` are the same object (2px padding, 2px gap, `--r-md` track of
|
||||
`--accent-wash`, `--r-sm` options, active option lifted onto `--paper`). Calendar has a third copy for
|
||||
the phone at app.css:244-267 (`.tabbar-views` / `.tabbar-view`).
|
||||
|
||||
## Menus, popovers, row menus, toasts, resizers
|
||||
|
||||
- Dropdown menu. margin app.css:1382-1438 and editor app.css:510-588 share `.menu-wrap`,
|
||||
`.menu-backdrop`, `.menu`, `.menu button`, `.menu-label`, `.menu-sep`; five of those six bodies are
|
||||
byte-identical. `.menu` differs only in `min-width` (156 vs 168) and `.menu button` in editor
|
||||
gaining `grid-template-columns: 14px 1fr` for a glyph column. mail's equivalent, ui/Popover.css, is
|
||||
positioned from JS through `--pop-left` / `--pop-top` / `--pop-w` and is genuinely different.
|
||||
- Row menu. `.row-menu-btn`, `.row-menu-btn:hover`, `.row-menu-pop`, `.row-menu-item`,
|
||||
`.row-menu-item:hover`, `.row-menu-item.danger`, `.row-menu-item.danger:hover` are byte-identical
|
||||
between margin app.css:393-460 and editor app.css:363-430. Seven rules, no differences.
|
||||
- Toast. margin app.css:1476 and editor app.css:590 are byte-identical: fixed, `bottom: 26px`,
|
||||
centred by `translateX(-50%)`, `z-index: 40`, `max-width: 460px`, `--ink` ground with `--paper`
|
||||
text. calendar app.css:437 and mail ui/Toast.css:1 are a different and better toast, also nearly
|
||||
identical to each other: `bottom: 24px`, `z-index: 60`, `max-width: min(560px, calc(100vw - 48px))`,
|
||||
`--glass` with `blur(8px)`, a `--line` border and `--shadow-pop`. Two designs, two apps each.
|
||||
- Resize handle. margin app.css:140-186 and editor tree.css:64-108 are the same rule set:
|
||||
zero-width flex item, an 8px `::before` hit area at `left: -4px`, a 2px `::after` accent line at
|
||||
`left: -1px` going to `opacity: 0.55` on hover. The only difference is the drag hook,
|
||||
`body.resizing` against `:root[data-resizing]`. editor/src/components/ResizeHandle.tsx writes
|
||||
`--pane-sidebar` on the root, so the token is already the interface.
|
||||
- Selected-row accent edge. `.chapter[data-active="true"]::before` (margin app.css:275, editor
|
||||
app.css:266, byte-identical) and `.row[data-selected]::before` (mail ui/Row.css:29): an absolutely
|
||||
positioned 2-3px bar of `--accent` with `border-radius: 0 2px 2px 0`, inset from the row's ends.
|
||||
- Sidebar and nav. `.sidebar`, `.brand`, `.brand .back-label`, `.brand:hover`, `.nav-label`,
|
||||
`.nav-scroll`, `.nav-section + .nav-section`, `.chapters`, `.chapter` and its nine state rules,
|
||||
`.chapter-drop`, `.add-chapter`: all byte-identical between margin and editor. The bulk of the 59
|
||||
identical bodies, and a straight copy of one app's sidebar into the other.
|
||||
- Settings. editor styles/settings.css and mail screens/settings.css are the same layout (a rail
|
||||
left, a measured column right, rows of label plus control plus note) at different numbers: rail
|
||||
`var(--pane-sidebar)` (248px) against a literal 210px, column 620px against 640px,
|
||||
`.settings-nav-item` against `.settings-tab`, `.setting-row` against `.set-row`. Both gate the
|
||||
traffic lane with `:root[data-traffic] { padding-left: var(--traffic-pad) }`. margin and calendar
|
||||
keep settings inside `.panel`, which is a legitimate difference of kind.
|
||||
|
||||
## Themes
|
||||
|
||||
Four implementations, three of which are the same file.
|
||||
|
||||
margin/src/theme.ts, calendar/src/theme.ts and mail/src/theme.ts are the same 16 lines with one
|
||||
string changed: the localStorage key (`margin-theme`, `margincal-theme`, `marginmail-theme`). Same
|
||||
`initialTheme` reading `data-theme` off the root first, then storage, then
|
||||
`matchMedia("(prefers-color-scheme: dark)")`; same `applyTheme` writing the attribute and the key.
|
||||
The boot scripts in each index.html are the same shape too, differing in the key and in what else
|
||||
they set on the root (calendar adds `data-phone`, `data-touch`, `data-view`; mail adds `data-phone`,
|
||||
`data-touch`, `data-no-pane` and the two font slots).
|
||||
|
||||
editor/src/theme.ts is 167 lines and a different design: seven named palettes
|
||||
(`light`, `sepia`, `mist`, `contrast`, `dark`, `graphite`, `midnight`), a `ThemeChoice` that can be
|
||||
`"system"`, a remembered light half and dark half so "Match system" lands on the two the user
|
||||
actually picks, storage in try/catch for a webview with storage denied, and `watchSystemScheme`
|
||||
listening for the media query as an event. Its palettes live in editor/src/styles/themes.css, one
|
||||
44-line block each, and editor/src/theme.test.ts reads that file and fails when a block is short.
|
||||
|
||||
No app uses `@media (prefers-color-scheme)` in CSS at all. All four resolve the system preference in
|
||||
JS and write `data-theme` on the root. That is one decision, taken four times, and it is the right
|
||||
one, so it should be taken once.
|
||||
|
||||
The multi-theme design is not a candidate for sharing as it stands: mail and calendar's stylesheets
|
||||
have no idea `sepia` or `midnight` exist and would fall through to the light `:root` block. But the
|
||||
three-line theme module and the boot script are, with the key as a parameter.
|
||||
|
||||
editor themes.css:307-322 is worth flagging: it copies six hexes of the shared light and dark
|
||||
palettes so the picker's preview tiles can draw them, with a comment saying it is the only copied
|
||||
colour in the file and that it is copied because "this repo may not reach into" margin-shared. It
|
||||
can, and does, through `margin-shared/css/tokens.css`. A shared `.theme-swatch[data-theme="light"]`
|
||||
block in the package would delete those two blocks.
|
||||
|
||||
## Drift: values hardcoded where a token exists
|
||||
|
||||
Counted over every CSS file except each app's token layer:
|
||||
|
||||
| app | hex literals | rgba() literals |
|
||||
| --- | --- | --- |
|
||||
| margin | 15 | 17 |
|
||||
| calendar | 0 | 1 |
|
||||
| editor | 0 | 0 |
|
||||
| mail | 0 | 0 |
|
||||
|
||||
Editor and mail are clean. Calendar's one is `box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06)` at
|
||||
app.css:507 on `.view-option[data-active]`, the only shadow in the app not from `--shadow-page` or
|
||||
`--shadow-pop`. margin is where the drift lives, and most of it is a token it never adopted:
|
||||
|
||||
- app.css:1275 `background: rgba(35, 32, 27, 0.28)` on `.overlay`. That is `--scrim`, which the other
|
||||
three all have.
|
||||
- app.css:1449 `background: rgba(35, 32, 27, 0.32)` on `.export-overlay`. A second scrim at a fourth
|
||||
of a percent difference, which nobody chose.
|
||||
- app.css:272 and :1839 `box-shadow: 0 1px 2px rgba(35, 32, 27, 0.05)`. That is editor's
|
||||
`--shadow-raised` exactly.
|
||||
- app.css:1547 `box-shadow: 0 4px 10px rgba(35, 32, 27, 0.1), 0 20px 38px rgba(35, 32, 27, 0.13)` on
|
||||
`.card:hover`. A third shadow that is neither `--shadow-page` nor `--shadow-pop`.
|
||||
- app.css:2933 `background: rgba(0, 0, 0, 0.42)` on `.drawer-scrim`. A third scrim.
|
||||
- app.css:1052 `0 1px 3px rgba(0, 0, 0, 0.3)`, app.css:1458 and :1465 `#fcfbf7` (`--paper`'s light
|
||||
value, hardcoded so it survives on the dark overlay), app.css:1464 `rgba(255, 255, 255, 0.28)`,
|
||||
app.css:638 `#fffefb`, app.css:678 `#2b2720`, app.css:1238 `#fff` (that last is editor's
|
||||
`--pdf-page`, which editor tokenised precisely because it was a literal in two stylesheets).
|
||||
- app.css:2184 `border-radius: 999px`, which is `--r-pill` in the other three.
|
||||
- app.css:75 `padding: 0 14px 0 84px` on `.titlebar`. The 84px is the macOS traffic-light lane,
|
||||
applied on every platform with no `data-traffic` gate. calendar app.css:126, editor app.css:97 and
|
||||
mail header.css:24 all gate it, and the comment at calendar app.css:121-125 says what the ungated
|
||||
version costs on Linux, Windows and iPad.
|
||||
- app.css:2881 `--titlebar-h: calc(46px + env(safe-area-inset-top))` inside `.app[data-compact]`.
|
||||
It restates the 46px shared already owns and reads `env()` inline where calendar and mail both have
|
||||
a `--safe-top` token for it.
|
||||
|
||||
The twelve proofing colours at app.css:2367-2451 (`#b4453a`, `#9c6e16`, `#2f6e4f` and their dark
|
||||
counterparts, plus six washes) are a real palette with no token, and editor has the same feature
|
||||
(styles/proofing.css) using `--danger` and friends. Worth comparing separately; it is the one place
|
||||
margin's literals encode a design rather than a forgotten token.
|
||||
|
||||
## What one shared stylesheet would have to contain
|
||||
|
||||
Tokens, added to shared/css/tokens.css: `--scrim`, `--shadow-raised`, `--r-pill`, `--t-5`,
|
||||
`--touch-h`, `--traffic-pad`, `--safe-top`, `--safe-bottom`, `--phonebar-h`, `--tabbar-h`,
|
||||
`--sheet-max-h`, and the eight-hue ramp under one name. Plus the `--ink-faint` correction. That is
|
||||
19 names and one fix, and it removes every one of them from calendar, editor and mail's own layers.
|
||||
|
||||
A base sheet: `*`, `html, body, #root`, `html` (with the tap-highlight line), `body`, `::selection`,
|
||||
`:focus-visible`, `button` (with `font-size: inherit`), `input, textarea, select`, `svg`, `.app`, the
|
||||
`data-touch` selection rules and the `data-phone` field-size rule. All of it is already identical or
|
||||
one line from identical in all four.
|
||||
|
||||
An overlay sheet: `.overlay`, `.overlay[data-align="top"]`, `.panel`, `.panel-head`, `.panel-head h2`,
|
||||
`.panel-body`, `.panel-foot`, the four `:root[data-phone]` docking rules, `@keyframes sheet-up` and
|
||||
its reduced-motion guard. Byte-identical or trivially reconcilable across all four today.
|
||||
|
||||
A controls sheet: the button (mail's `[data-variant]` and `[data-size]` version, which is the
|
||||
superset), the field, the label, the toggle, the keycap, the segmented control, the icon button under
|
||||
one name, the row menu, the toast (calendar and mail's version), the resize handle. Every one of
|
||||
these exists in at least two apps already and differs by a padding value or a class name.
|
||||
|
||||
`color-scheme` at the root, per theme, which only editor has, and a `prefers-reduced-motion` guard
|
||||
convention, which only mail applies consistently.
|
||||
|
||||
What each app keeps: editor keeps its document scale, sheet padding, code surface and its seven-palette
|
||||
themes.css; mail keeps its mail geometry, the `--message-*` set that deliberately ignores the theme,
|
||||
and its `--check` OS blue; calendar keeps its grid geometry and the `--grid-*`, `--fold-*` and
|
||||
`--event-*` palettes; margin keeps `--pane-dock`, its scrollbar rule (or that moves up), its proofing
|
||||
palette and the device-frame `--dv-*` set. Nothing else in the four apps' CSS is app-specific by need
|
||||
rather than by accident.
|
||||
@@ -0,0 +1,442 @@
|
||||
# Docs, comments and naming across the four apps
|
||||
|
||||
Read: three `docs/conventions.md`, four `README.md`, every `docs/*.md`, both `CLAUDE.md`,
|
||||
`shared/src/fonts.ts`, `shared/src/icons.ts`, all four `src-tauri/Cargo.toml`, all four
|
||||
`package.json` and `tauri.conf.json`, `scripts/docs-check.mjs`, and the CI workflows.
|
||||
|
||||
## 1. The three conventions.md files
|
||||
|
||||
Only three exist: `margin-caledar/docs/conventions.md` (89 lines),
|
||||
`margin-editor/docs/conventions.md` (103), `margin-mail/docs/conventions.md` (139). **margin, the
|
||||
app all three defer to, has no conventions.md at all.** That is the first hole: the house style is
|
||||
written down only in the repos that copied it, never in the repo that set it.
|
||||
|
||||
### What all three share, near verbatim
|
||||
|
||||
Each opens by disclaiming originality. Calendar line 3: "This project is a sibling to `../margin`
|
||||
and follows its conventions deliberately rather than inventing new ones." Editor line 3 and mail
|
||||
line 3 are the same sentence with the sibling list extended.
|
||||
|
||||
Five rules are word-for-word identical in all three:
|
||||
|
||||
- `Result<T, String>` everywhere. No `anyhow`.
|
||||
- "DTOs crossing the IPC boundary live in `src-tauri/src/dto.rs` and are marked
|
||||
`#[serde(rename_all = "camelCase")]`. That file is the contract and is frozen: implementation
|
||||
modules add bodies, not fields. Its mirror is `src/ipc.ts`."
|
||||
(calendar:12, editor:13, mail:14)
|
||||
- "One zustand store per domain in `src/store/`. No middleware. One selector call per field
|
||||
(`useThing((s) => s.field)`, never a destructured object), actions as inline arrow properties, and
|
||||
`set((s) => ...)` returning `{}` to no-op." (calendar:26, editor:26, mail:35)
|
||||
- "Flat kebab-case class names, not BEM. State is a `data-*` attribute, never an `is-` class."
|
||||
- "Transitions name explicit properties and use `var(--ease)`. Never `transition: all`."
|
||||
|
||||
And each closes with a `## Never` section of the same shape. Calendar:88 and mail:138: "No CSS
|
||||
framework, no component library, no router, no zustand middleware, no directory trees in any
|
||||
document, and no em dashes anywhere including code comments."
|
||||
|
||||
### Where they contradict each other
|
||||
|
||||
**Em dash versus en dash.** Editor:103 is the only one that bans both: "no em dashes or en dashes
|
||||
anywhere, including code comments." Calendar:89 and mail:139 ban only em dashes. The user's own rule
|
||||
bans both. Editor is right and the other two are stale.
|
||||
|
||||
**Container queries.** Calendar:67 permits exactly one, on the event block, and says "Nothing else
|
||||
may reach for a container query without the same kind of reason." Mail:105 hardens it to "There is
|
||||
no container query in this repository" while explicitly crediting the calendar's exception. Editor
|
||||
does not mention container queries. Not a real contradiction, but three different postures.
|
||||
|
||||
**Where a token lives.** Calendar:46 and editor:81: "Every colour, radius and size goes through a
|
||||
token in `src/styles/tokens.css`." Mail:55 redefines `tokens.css` as a seam, not a list: it imports
|
||||
margin-shared's set and then `src/styles/mail.css`, and mail:86 says add to `mail.css` instead. Mail
|
||||
is the only one with the three-layer tokens/primitives/screens rule (mail:51-66) and the only one
|
||||
with a Kit page at `#/kit`.
|
||||
|
||||
**Icons.** All three keep "Inline Feather-style 24x24 stroke `d` strings passed to
|
||||
`<Icon d={...} />`. There is no icon set and no registry, and there will not be one." Calendar:79 and
|
||||
mail:120 add "An icon-only button always carries a `title` with its shortcut written in real
|
||||
glyphs"; editor drops that line. Mail:116 is the only one that names a file (`src/ui/icons.ts`) and
|
||||
the only one that acknowledges `margin-shared/icons`, which editor and calendar do not mention at
|
||||
all even though `margin-shared` is a real dependency of editor.
|
||||
|
||||
**Comment density.** Calendar:22 and mail:31: "Comments are rare and explain why, never what. Match
|
||||
the density in `lib.rs`." Editor:22 keeps the first sentence and drops the pointer. See section 5:
|
||||
the density claim is false in all three.
|
||||
|
||||
**Errors.** Calendar allows one error enum (`google::api::ApiError`), mail allows one
|
||||
(`provider::ProviderError`), editor:11 allows none. Each names its own reason. This is the right
|
||||
pattern: an app-specific carve-out written next to the shared rule.
|
||||
|
||||
### What is genuinely app-specific and should stay that way
|
||||
|
||||
Editor's `## Markdown` (38-59) and `## Tests` (61-75) sections, mail's `## Places and stages`
|
||||
(68-80) and `## Work packages` (129-134), calendar's `data-phone` versus `data-touch` argument
|
||||
(57-70, copied verbatim into mail:94-103). Storage key prefixes differ by design: `margincal-`,
|
||||
`margindocs-`, `marginmail-`.
|
||||
|
||||
### Broken cross-references
|
||||
|
||||
Calendar:3 says `../margin`, and from `python/margin-caledar` that resolves. Editor:3 says
|
||||
`../margin` and `../margin-calendar`, and **neither exists**: `rust/margin` and
|
||||
`rust/margin-calendar` are not on disk. Calendar:17 cites `margin/src-tauri/src/gdrive.rs:286` and
|
||||
calendar:20 cites `pdf.rs:90`. Both files exist; neither line carries a comment (section 5).
|
||||
|
||||
## 2. READMEs
|
||||
|
||||
| repo | lines | verdict |
|
||||
| --- | --- | --- |
|
||||
| margin | 15 | compliant. Description, install, one docs link, licence. |
|
||||
| margin-calendar | 15 | compliant, but the last seven lines are one dense paragraph of six links. |
|
||||
| margin-docs | 14 | compliant and the cleanest of the four. |
|
||||
| margin-mail | 20 | over. Lines 3 to 10 are an eight-line pitch that belongs in `docs/design.md`. |
|
||||
|
||||
Mail is the offender. Its opening paragraph restates the product ("New senders wait at the door
|
||||
until you let them in; people, newsletters and receipts live in three separate boxes") which is
|
||||
already `docs/design.md:31-73`. Cutting it to two sentences puts it at 13 lines.
|
||||
|
||||
Four other READMEs exist inside margin and are not project descriptions:
|
||||
`margin/website/README.md` (48 lines, 7 em dashes), `margin/appstore/screenshots/README.md` (51),
|
||||
`margin/simplify/README.md` (26), `margin/simplify/guidelines/README.md` (31).
|
||||
`margin/shared/README.md` is 15 lines and compliant. The website one is the worst artefact in the
|
||||
suite: bold-marked feature bullets, em dashes throughout, a "Built with" line. It reads like a
|
||||
different author.
|
||||
|
||||
`margin/shared/README.md:3` and `shared/package.json:7` both say the package is for "Margin and
|
||||
Margin Docs". Margin Mail has depended on it since `package.json:24`. The description is stale.
|
||||
|
||||
## 3. The docs set
|
||||
|
||||
- **margin**: `docs/publishing.md` only (229 lines). No architecture, no design, no conventions, no
|
||||
setup, no release. The originating app is the least documented.
|
||||
- **margin-calendar**: `architecture.md` (145), `conventions.md` (89), `design.md` (152),
|
||||
`mobile.md` (304), `release.md` (105), `setup.md` (55). This is the set that got copied.
|
||||
- **margin-docs**: `architecture.md` (545), `conventions.md` (103), `design.md` (131),
|
||||
`release.md` (117), `setup.md` (29). Calendar's set minus `mobile.md`, macOS only.
|
||||
- **margin-mail**: `architecture.md` (352), `conventions.md` (139), `design.md` (153),
|
||||
`release.md` (119), plus `features.md` (475), `ui.md` (339), `settings.md` (201), `plan.md` (193),
|
||||
`keyboard.md` (129), `help.md` (74), `mockups/`, `research/`. **No `setup.md`**, which is the one
|
||||
file a new machine needs, and mail is the app that requires a Google OAuth client.
|
||||
|
||||
Three shapes are stable across the set. `architecture.md` always opens with the same stack sentence:
|
||||
"Tauri 2, React 19, Vite, TypeScript and zustand on the front, Rust behind" (calendar:3, editor:3,
|
||||
mail:3), then "The split is strict" and what each side owns. `design.md` is always product decisions
|
||||
argued as prose under "why" headings, and always ends with `## Visual language`. `release.md` always
|
||||
starts `## Installing locally` then `## Cutting a release` and ends `## Updates`.
|
||||
|
||||
### Proposed canonical set
|
||||
|
||||
Five files, every app, same names, same opening move:
|
||||
|
||||
`architecture.md`, `conventions.md`, `design.md`, `setup.md`, `release.md`.
|
||||
|
||||
Then only what the product actually has: `features.md`, `ui.md`, `keyboard.md`, `settings.md`,
|
||||
`help.md`, `mobile.md`, `publishing.md`, `plan.md`, `research/`, `mockups/`. Never a numeric prefix.
|
||||
|
||||
Concretely: margin needs all five written and should keep `publishing.md`; mail needs `setup.md`;
|
||||
mail's `plan.md` is a milestone tracker and will go stale, so it belongs in the issue tracker or
|
||||
under `research/`.
|
||||
|
||||
## 4. The comment voice
|
||||
|
||||
### What a comment is for here
|
||||
|
||||
A comment records a decision and the alternative that was rejected, so that a competent person does
|
||||
not undo it by accident. It never says what the line below does.
|
||||
|
||||
The shape is consistent enough to be a template. A file-head block states what the file is in one
|
||||
line, then a blank comment line, then one paragraph per decision. Each paragraph names the thing
|
||||
chosen, then the thing not chosen, then the concrete failure the wrong choice produces. Sentences
|
||||
are long, declarative, no hedging, no first person, no "note that". Length is one to seven lines per
|
||||
paragraph; a file head runs 3 to 17 lines. Doc comments on exported items are one sentence and often
|
||||
end on the consumer ("which is what a Typst preamble names a face by").
|
||||
|
||||
The tell is that almost every comment contains a causal clause: "because", "so that", "which is
|
||||
why", "rather than", "or a ... would".
|
||||
|
||||
### Four exemplars, in full
|
||||
|
||||
`margin/shared/src/fonts.ts:1-7`:
|
||||
|
||||
// The faces both apps offer, and the two slots they set them into.
|
||||
//
|
||||
// This lives in one place because the two apps have to agree about it. A face named here is a
|
||||
// `@font-face` in css/fonts.css, a file in fonts/, and a family a Typst preamble names on the way
|
||||
// to a PDF, and those four lists going out of step with each other is a document that renders in
|
||||
// one app and falls back to Georgia in the other. There is no way to keep four lists in two repos
|
||||
// honest by hand, so there is one list.
|
||||
|
||||
`margin/shared/src/icons.ts:3-6`:
|
||||
|
||||
// Here because the two apps kept drifting. Each had its own idea of what a search or a moon looked
|
||||
// like, they were adjusted independently, and the result was two products from the same hand that
|
||||
// did not look related. A path is a design decision, not a detail, and the fix for two copies of a
|
||||
// decision is one copy.
|
||||
|
||||
`margin-mail/src-tauri/Cargo.toml:61-63`:
|
||||
|
||||
# Refresh tokens, the backup key and every uploaded journal segment are sealed with
|
||||
# XChaCha20-Poly1305. There is no `keyring` here on purpose: it has no Android backend at all, and
|
||||
# on macOS it ties the item to the code signature, so every rebuild re-prompts.
|
||||
|
||||
`margin-editor/src-tauri/Cargo.toml:54-56`:
|
||||
|
||||
# Pinned exactly: the [patch] stubs at the foot of this file are tied to this version's burn/cubecl
|
||||
# graph. A minor bump could silently invalidate a patch ("unused"), and the whole CUDA and LLVM
|
||||
# subtree those stubs remove would come back. Bump deliberately and re-audit the stubs.
|
||||
|
||||
`margin/shared/src/icons.ts:29-37` is the purest case, because it justifies an SVG path: two
|
||||
letterforms rather than one on a rule, because one letter over a full-width line is the underline
|
||||
button in every editor, and because the neighbouring `SPELLING` glyph is also built on a capital A,
|
||||
so the distinguishing feature has to be the bowl versus the tick, which survives at 16px.
|
||||
|
||||
### Violations, in both directions
|
||||
|
||||
**Undocumented decisions.** The clearest cases are the exact decisions two sibling repos cite by
|
||||
file and line:
|
||||
|
||||
- `margin/src-tauri/src/gdrive.rs` is 953 lines with **zero comments**. Calendar's conventions.md:17
|
||||
points at `gdrive.rs:286` as the origin of `read_json` and explains why the body goes to a `String`
|
||||
first. The reason is written in the calendar's docs and in mail's docs and never in the file.
|
||||
- `margin/src-tauri/src/pdf.rs` is 129 lines with zero comments. Calendar:20 and mail:23 both cite
|
||||
`#[tauri::command(async)]` on a synchronous fn at `pdf.rs:90` as the trick for getting off the main
|
||||
thread. `compile_pdf` at line 90 carries no comment saying so.
|
||||
- Other zero-comment files over 200 lines in margin: `src/components/EditorView.tsx` (560),
|
||||
`src/import/epub.ts` (534), `src/export/typst.ts` (421), `src/components/Sidebar.tsx` (310),
|
||||
`src-tauri/src/proofing.rs` (275), `src/model/book.ts` (260), `src-tauri/src/lib.rs` (256),
|
||||
`src/editor/search.ts` (233), `src/components/Dock.tsx` (223).
|
||||
|
||||
**Narration that should go.**
|
||||
|
||||
- `margin/src/components/ExportPreview.tsx:320`: `// render cancelled or page failed; keep the
|
||||
previous canvas`. Lowercase, no full stop, and the second clause narrates the line below.
|
||||
- `margin/src-tauri/Cargo.toml:9`: `# See more keys and their definitions at
|
||||
https://doc.rust-lang.org/cargo/reference/manifest.html`, and lines 12-14, the `_lib` suffix
|
||||
paragraph. Both are `cargo new` boilerplate. The three sibling Cargo.toml files deleted them; margin
|
||||
did not.
|
||||
- `// Prevents additional console window on Windows in release, DO NOT REMOVE!!` is
|
||||
`src-tauri/src/main.rs:1` in all four repos. Tauri scaffold text, shouting, and none of these apps
|
||||
ships on Windows.
|
||||
- Four `// eslint-disable-next-line react-hooks/exhaustive-deps` in margin
|
||||
(`src/components/FindBar.tsx:44`, `src/editor/FloatingToolbar.tsx:69`, `src/editor/Editor.tsx:113`
|
||||
and `:122`). No repo has eslint configured, in package.json or on disk. Dead directives.
|
||||
|
||||
Beyond these, a sweep for narration patterns across all four repos found almost nothing. Every hit
|
||||
on "comment starts with a verb" or "comment starts lowercase" turned out to be a wrapped
|
||||
continuation line of a real reason. The voice is being held.
|
||||
|
||||
## 5. The CLAUDE.md tension, resolved
|
||||
|
||||
`margin/CLAUDE.md:9` and `margin-caledar/CLAUDE.md:9` are byte-identical: "Avoid excessive comments.
|
||||
Only comment when absolutely necessary. Code should be readable and not require comments to
|
||||
understand it." margin-docs and margin-mail have no CLAUDE.md.
|
||||
|
||||
The code says otherwise. Comment lines as a fraction of source in `src/`, `src-tauri/src/` and
|
||||
`shared/src/`:
|
||||
|
||||
| repo | source lines | comment lines | share |
|
||||
| --- | --- | --- | --- |
|
||||
| margin | 10,377 | 125 | 1.2% |
|
||||
| margin-calendar | 20,211 | 2,208 | 10.9% |
|
||||
| margin-docs | 43,973 | 10,634 | 24.2% |
|
||||
| margin-mail | 70,737 | 9,921 | 14.0% |
|
||||
|
||||
margin obeys the rule as written. The three younger apps ignore it by a factor of ten to twenty, and
|
||||
they are the disciplined ones. The rule was true of a repo that had no siblings; it stopped being
|
||||
true the moment a decision had to survive being copied into another repo.
|
||||
|
||||
The operating rule, read off the code: **a comment never says what, and always says why.** The test
|
||||
already exists in `simplify/guidelines/code-style.md:30`: "delete the comment and ask whether a
|
||||
competent person would make the same mistake twice. If yes, keep it. If it just narrates the line
|
||||
below, cut it." Under that test margin is not compliant by being sparse; it is under-commented, and
|
||||
`gdrive.rs` is the proof.
|
||||
|
||||
The two CLAUDE.md files should be corrected or deleted. As written they are a live instruction to
|
||||
strip the best thing in this codebase.
|
||||
|
||||
## 6. Typographic compliance
|
||||
|
||||
Across `*.md`, `*.ts`, `*.tsx`, `*.rs`, `*.css`, `*.toml`, `*.html`, `*.js`, `*.mjs`, excluding
|
||||
`node_modules`, `dist`, `target`, `.git`, `target-mas`, `.playwright-mcp` and `gen`:
|
||||
|
||||
| repo | em dashes | en dashes |
|
||||
| --- | --- | --- |
|
||||
| margin | 37 | 5 |
|
||||
| margin-calendar | 0 | 0 |
|
||||
| margin-docs | 7 | 0 |
|
||||
| margin-mail | 3 | 2 |
|
||||
|
||||
margin-calendar is perfectly clean. margin holds 42 of the 54 in the suite.
|
||||
|
||||
Worst files:
|
||||
|
||||
- `margin/simplify/.research/memories-raw.md`, 19. A dump of old memory files, so arguably input
|
||||
rather than committed prose, but it is in the repo.
|
||||
- `margin/website/README.md`, 7, all in body copy (lines 3, 21, 22, 23, 25, 37, 41).
|
||||
- `margin-docs/src/markdown/corpus/real/margin-website-readme.md`, 7. A copy of the file above, kept
|
||||
as a serializer test fixture. Fixing the website README without fixing the fixture will not help,
|
||||
and fixing the fixture may break a round-trip test.
|
||||
- `margin/src/export/run.ts:8` and `:36`, `margin/src/components/Library.tsx:88`,
|
||||
`margin/src/components/ExportPreview.tsx:185`. These four are **user-visible app copy**, which is
|
||||
the worst place for it: the string at `run.ts:8` puts one between "desktop app only" and "open the
|
||||
window from".
|
||||
- `margin/src-tauri/stubs/burn-cuda/src/lib.rs:1` and `stubs/cubecl-cpu/src/lib.rs:1`, one each.
|
||||
- `margin/simplify/guidelines/prose-and-docs.md:8` is the rule itself quoting both characters. Fine.
|
||||
|
||||
margin-mail's three are all legitimate: `scripts/docs-check.mjs:46-47` is the regex that enforces the
|
||||
rule, and `src/screens/guide/guide.test.ts:104` asserts the guide text is free of them.
|
||||
|
||||
### The gate already exists, in one repo
|
||||
|
||||
`margin-mail/scripts/docs-check.mjs` is a 72-line node script wired to `just docs`
|
||||
(`margin-mail/justfile:33-34`). It walks every markdown file and reports em dashes, en dashes,
|
||||
directory trees and dead relative links. Its own header, lines 2-11, is a model comment. **No other
|
||||
repo has it**, and margin, which has 42 offences, is the repo that most needs it. Copying that one
|
||||
file into the other three, and extending it past `*.md` to source files so app copy is covered, is
|
||||
the single highest-value action in this report.
|
||||
|
||||
## 7. Directory trees
|
||||
|
||||
None. A search for box-drawing runs and for the ASCII form across markdown, TypeScript, Rust, JSON
|
||||
and text in all four repos returned nothing. The rule is being kept without a gate in three of the
|
||||
four repos, which is worth noting: the risk is a future file, not an existing one.
|
||||
|
||||
## 8. Naming
|
||||
|
||||
| | margin | calendar | docs | mail |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| directory | `python/margin` | `python/margin-caledar` | `rust/margin-editor` | `rust/margin-mail` |
|
||||
| package.json name | `margin-app` | `margin-calendar` | `margin-docs` | `margin-mail` |
|
||||
| Cargo package | `margin-app` | `margin-calendar` | `margin-docs` | `margin-mail` |
|
||||
| Cargo lib | `margin_app_lib` | `margin_calendar_lib` | `margin_docs_lib` | `margin_mail_lib` |
|
||||
| bundle id | `studio.margin.app` | `studio.margin.calendar` | `studio.margin.docs` | `studio.margin.mail` |
|
||||
| git remote | `priyanshujain/margin` | `priyanshujain/margin-calendar` | `priyanshujain/margin-docs` | **none** |
|
||||
| productName | `Margin` | `Margin Calendar` | `Margin Docs` | `Margin Mail` |
|
||||
| html title | `margin` | `Margin Calendar` | `Margin Docs` | `Margin Mail` |
|
||||
| README h1 | `margin` | `Margin Calendar` | `Margin Docs` | `Margin Mail` |
|
||||
| storage prefix | (none stated) | `margincal-` | `margindocs-` | `marginmail-` |
|
||||
| licence | FSL-1.1-MIT | MIT | MIT | FSL-1.1-MIT |
|
||||
|
||||
Disagreements, worst first:
|
||||
|
||||
1. **`python/margin-caledar` is a typo.** Confirmed. Everything inside it says `margin-calendar`,
|
||||
including the remote and the Nix flake output (`ci.yml:81`, `nix build .#margin-calendar`).
|
||||
2. **`rust/margin-editor` versus `margin-docs`.** Confirmed. The directory is the only place the
|
||||
word "editor" appears as a name; package, crate, bundle id, product name and remote all say docs.
|
||||
3. **`python/` and `rust/` parents are wrong for all four.** All four are Tauri apps with a React
|
||||
front end and a Rust backend. None is a Python project. This is not cosmetic:
|
||||
`margin-docs/package.json:33` and `margin-mail/package.json:24` both carry
|
||||
`"margin-shared": "file:../../python/margin/shared"`, and `margin-mail/.github/workflows/ci.yml`
|
||||
checks the two repos out into `rust/margin-mail` and `python/margin` (lines 25 and 30) precisely to
|
||||
reproduce that path. The word "python" is baked into a GitHub runner's filesystem layout.
|
||||
4. **margin-docs CI is failing on exactly this.** The latest run's failure is
|
||||
`ENOENT: no such file or directory, scandir '/Users/runner/work/python/margin/shared'`. Editor's
|
||||
`ci.yml` runs `pnpm install --frozen-lockfile` after a single checkout, so the relative path has
|
||||
nothing to resolve to. Mail solved it with a second checkout; docs never did. Five of the last six
|
||||
runs failed.
|
||||
5. **margin-mail has no git remote.** One local commit, `088ec9c`. Everything else in the suite is on
|
||||
GitHub. Whatever name the repo gets is still an open choice, which makes this the cheapest moment
|
||||
to fix the pattern.
|
||||
6. **`margin-app` versus `Margin`.** margin is the only app whose package and crate name is not its
|
||||
product name lowercased and hyphenated. `margin-app` also breaks the bundle id pattern:
|
||||
`studio.margin.app` reads as a namespace with a placeholder in it.
|
||||
7. **`margin/index.html` title is lowercase `margin`** while `productName` is `Margin`. The README h1
|
||||
is lowercase too. The other three are consistent title case.
|
||||
8. **Licences split two and two**, and neither README in the MIT pair says so. margin and mail are
|
||||
FSL, calendar and docs are MIT, and nothing explains the split.
|
||||
9. **Editor's conventions.md:3 points at `../margin` and `../margin-calendar`**, neither of which
|
||||
exists relative to `rust/margin-editor`. The paths only make sense if all four sit as siblings,
|
||||
which is what the rename below produces.
|
||||
10. `margin-docs/src/markdown/corpus/real/` holds copies of the calendar's and the editor's own
|
||||
`conventions.md` as test fixtures. Two of the three canonical convention documents exist twice in
|
||||
the suite and will drift.
|
||||
|
||||
## 9. Rename proposal, with cost
|
||||
|
||||
Target layout: one parent, `~/Workspace/projects/margin/`, holding `margin`, `margin-calendar`,
|
||||
`margin-docs`, `margin-mail` as siblings.
|
||||
|
||||
**A. `margin-caledar` to `margin-calendar`.** Cheapest and unambiguous.
|
||||
Cost: `mv` the directory. No `package.json` anywhere references it. Nothing on GitHub changes; the
|
||||
remote is already correct. Only local shell history and any editor workspace file break.
|
||||
|
||||
**B. `margin-editor` to `margin-docs`.** Also cheap.
|
||||
Cost: `mv` the directory. The `file:../../python/margin/shared` path is unaffected because the depth
|
||||
does not change. `docs/conventions.md:3` should be corrected in the same edit. No remote change: the
|
||||
remote is already `margin-docs`.
|
||||
|
||||
**C. Collapse `python/` and `rust/` into one `margin/` parent.** The expensive one, and the one that
|
||||
pays.
|
||||
Cost, exhaustively:
|
||||
- `margin-docs/package.json:33` and `margin-mail/package.json:24`: `file:../../python/margin/shared`
|
||||
becomes `file:../margin/shared`. Both lockfiles need regenerating.
|
||||
- `margin-mail/.github/workflows/ci.yml:21,25,29,30,57,61`: the checkout paths `rust/margin-mail` and
|
||||
`python/margin` become `margin-mail` and `margin`, and the `working-directory` lines follow.
|
||||
- `margin-docs/.github/workflows/ci.yml`: needs the second checkout added, which it is currently
|
||||
missing. This fixes the failing build rather than costing anything.
|
||||
- Local shell history, editor workspaces, and any absolute path in a memory file.
|
||||
- Nothing on GitHub changes. No remote, no clone URL, no release artefact, no bundle id.
|
||||
|
||||
**D. `margin-app` to `margin`, and `studio.margin.app` to `studio.margin.writer` or similar.**
|
||||
Recommend doing the crate and package rename and **not** the bundle id.
|
||||
Cost of the package and crate rename: `package.json:2`, `src-tauri/Cargo.toml:2`, `Cargo.lock`, the
|
||||
lib name `margin_app_lib` and every `use margin_app_lib::` in `src-tauri/src/main.rs`, plus any
|
||||
workflow that names the binary.
|
||||
Cost of the bundle id rename: **do not**. Changing `identifier` on a shipped macOS app orphans the
|
||||
application support directory, breaks the Homebrew cask, breaks the updater's signature check, and
|
||||
makes the Mac App Store record a different product. The inconsistency is not worth that. Write one
|
||||
line in `docs/conventions.md` saying `studio.margin.app` is frozen and why.
|
||||
|
||||
**E. Give margin-mail a remote.** `priyanshujain/margin-mail`, matching the other three. Free now,
|
||||
and the naming stays consistent by default.
|
||||
|
||||
Order: B, A, E, C, D. B and A are free. C is best done immediately after, while mail has no CI
|
||||
history to invalidate.
|
||||
|
||||
## 10. The proposed house style
|
||||
|
||||
### Docs
|
||||
|
||||
A README is the project description. Under 15 lines: one paragraph on what it is, one line on how to
|
||||
install, one paragraph of links into `docs/`, one line on the licence. margin-docs' README is the
|
||||
model. Mail's is eight lines over and those eight lines are already in `docs/design.md`.
|
||||
|
||||
`docs/` holds `architecture.md`, `conventions.md`, `design.md`, `setup.md`, `release.md` in every
|
||||
app, plus whatever the product genuinely has. No numeric prefixes. No file that is a status report.
|
||||
|
||||
`architecture.md` opens with the stack sentence and "The split is strict", then what each side owns,
|
||||
then one section per hard part, then `## Order of work`. `design.md` argues product decisions in
|
||||
prose under "why" headings and ends with `## Visual language`. `release.md` runs `## Installing
|
||||
locally`, `## Cutting a release`, `## What the build needs`, `## Updates`.
|
||||
|
||||
`conventions.md` exists in every app including margin, and is split: the shared rules (the five
|
||||
identical ones, verbatim) and the app's own. When an app carves out an exception, the carve-out names
|
||||
the reason in the same sentence, the way mail:9 names `provider::ProviderError` and the four cases it
|
||||
has to branch on. Both em dashes and en dashes are banned, taking editor's wording over the other
|
||||
two.
|
||||
|
||||
Prose a colleague would write. No em dash, no en dash, no directory tree, ever, and the rule holds
|
||||
inside code fences and app copy as well as in body text.
|
||||
|
||||
### Comments
|
||||
|
||||
A comment records a decision and the alternative that was rejected. It never says what the line below
|
||||
does; if you want to, rename something instead.
|
||||
|
||||
Shape: a one-line statement of what the file is, a blank comment line, then one paragraph per
|
||||
decision. Each paragraph names what was chosen, what was not, and the concrete failure the other
|
||||
choice produces. One to seven lines per paragraph. Declarative, third person, no hedging. Doc
|
||||
comments on exported items are one sentence.
|
||||
|
||||
The test, already written at `simplify/guidelines/code-style.md:30`: delete it and ask whether a
|
||||
competent person would make the same mistake twice.
|
||||
|
||||
Two consequences worth stating plainly, because the current text says the opposite. The instruction
|
||||
in `margin/CLAUDE.md:9` and `margin-caledar/CLAUDE.md:9` is wrong and should be replaced with the
|
||||
rule above. And "comments are rare" in all three conventions.md files is false and should be cut: the
|
||||
suite averages one comment line in seven, and the three densest repos are the three best ones.
|
||||
|
||||
### Enforcement
|
||||
|
||||
Copy `margin-mail/scripts/docs-check.mjs` into the other three repos, wire it to `just docs` and to
|
||||
CI, and extend it beyond `*.md` to `*.ts`, `*.tsx`, `*.rs` and `*.css` so app copy is covered. That
|
||||
one file catches every offence in section 6, plus the dead links, plus any future tree. Fix margin's
|
||||
42 dashes first, starting with the four in user-visible strings.
|
||||
@@ -0,0 +1,450 @@
|
||||
# Non-component TypeScript across the four apps
|
||||
|
||||
Scope: hooks, utilities, stores, the IPC layer. Non-test `.ts`: margin 4061 lines, margin-calendar 3811,
|
||||
margin-docs 16868, margin-mail 11429. Shorthand: **M** margin, **C** margin-calendar, **D** margin-docs,
|
||||
**X** margin-mail.
|
||||
|
||||
## The shared package already exists
|
||||
|
||||
`margin-shared` is at `/Users/pj/Workspace/projects/python/margin/shared`: a `file:` dependency of M, D and X,
|
||||
exporting `.`, `./fonts`, `./icons` and two stylesheets, 299 lines of source today.
|
||||
|
||||
**C is not wired to it at all**, in TypeScript or CSS. It has no `margin-shared` in `package.json` and its
|
||||
`src/styles/tokens.css` does not `@import "margin-shared/css/tokens.css"` the way the other three do. That
|
||||
dependency line is the prerequisite for everything here.
|
||||
|
||||
**The extraction pattern is already proven.** `M/src/model/fonts.ts` (41 lines) and `D/src/model/fonts.ts`
|
||||
(40) are re-export shims: pull the catalogue from `margin-shared/fonts`, declare one app-local alias
|
||||
(`BookFonts` vs `DocumentFonts`) so call sites keep the app's own noun. Copy that shape.
|
||||
|
||||
No app uses tsconfig path aliases, so nothing needs build config beyond the dependency. All three vitest apps
|
||||
run `environment: "node"`, so shared hooks need the `typeof window` guards D already writes, or
|
||||
`vi.stubGlobal` as in `D/src/width.test.ts:24`. No app has a `utils/`, `lib/`, `helpers/` or `hooks/`
|
||||
directory: everything is either a single-purpose top-level module or defined inline atop the one component
|
||||
that needs it.
|
||||
|
||||
## Byte-identical today
|
||||
|
||||
**`src/escape.ts`**, all four. 36 lines in M, C and D, all three md5 `3b1f67d691647be7d61a23a5acd96a7b`. X's
|
||||
is 40 lines, differing only by a four-line header; strip comments and all four hash identically
|
||||
(`9c8530a09b35e5d697bb2b95674a2e73`). Signature `useEscapeLayer(active: boolean, onEscape: () => void): void`,
|
||||
a module-level stack of Escape handlers behind one lazily-bound capture-phase listener. Move verbatim, keeping
|
||||
X's header. 144 duplicated lines, zero risk. All three keyboard registries already defer to it by name rather
|
||||
than handling Escape themselves, and its `const latest = useRef(onEscape); latest.current = onEscape;` is an
|
||||
inline `useLatest` that falls out of the extraction for free.
|
||||
**`useMediaQuery`**, all four `src/useMedia.ts`, byte-identical (`c3499ac5ee3d1a12b138d71b2cc787ed`).
|
||||
**`usePhone` and `useTouch`**, C/D/X, byte-identical bodies (`d565f08a...`, `f4285e4c...`), with `PHONE_QUERY
|
||||
= "(max-width: 640px)"` and `TOUCH_QUERY = "(pointer: coarse)"`; the only difference between the three files
|
||||
is prose describing each app's layout. M has neither, only a stale `useCompact` on a 899px query that D
|
||||
deleted when it added the phone/touch pair.
|
||||
|
||||
**`src/theme.ts`**, M/C/X. Strip comments, normalise the key, all three hash identically
|
||||
(`ab9c99ff29565c686028e16960274d9d`); the literal M-to-C diff is one line. **`src/store/useTheme.ts`**, M and
|
||||
C, byte-identical (`b48a3bccfadd21b9bb4efa91eef5041c`, 16 lines); X's 17 differ only by extracting a
|
||||
`set(theme)` action. **`src/store/useToast.ts`**, C and D, byte-identical (`dfc90357bbcfbbfe71ffb8ba0e680c00`,
|
||||
15 lines). M has no toast.
|
||||
|
||||
**The `src/ipc.ts` preamble.** Lines 1 to 41 of C's and D's are byte-identical
|
||||
(`afde11927f75a3a81b2b459658c5b7be`), doc comments included: header, `isTauri`, `isMobileOs` with its iPadOS
|
||||
carve-out, `isDesktop`, `isMacDesktop`, `live()`. So is the body of `call<T>`
|
||||
(`b4259488afdd6a0f154b8e86eae1ff9c`). X has the same code with two comments abridged, plus one real addition
|
||||
at `X/src/ipc.ts:752-758`: it logs a failed command to Rust before rethrowing, skipping `log_note` itself to
|
||||
avoid a loop.
|
||||
|
||||
**`src/store/useOverlays.ts`**, C (64 lines) and X (72). Diffed with comments stripped, the entire difference
|
||||
is the `Overlay` union and one prettier reflow of `push`; all seven actions are character-identical. X's
|
||||
header: "Ported from the calendar's store of the same name."
|
||||
|
||||
**The keys platform block**, C/D/X, not one character differing, at `C:76-87`, `D:206-217`, `X:521-532`. Also
|
||||
byte-identical across those three: the `NAMED` glyph map, `commandMatches`, `isTyping`, and
|
||||
`pushContext`/`useKeyContext`.
|
||||
|
||||
```ts
|
||||
const isMac = typeof navigator !== "undefined" && /mac|iphone|ipad/i.test(navigator.userAgent ?? "");
|
||||
export const PRIMARY_LABEL = isMac ? "⌘" : "Ctrl+";
|
||||
export const primaryHeld = (e: { metaKey: boolean; ctrlKey: boolean }): boolean =>
|
||||
isMac ? e.metaKey : e.ctrlKey;
|
||||
export const secondaryHeld = (e: { metaKey: boolean; ctrlKey: boolean }): boolean =>
|
||||
isMac ? e.ctrlKey : e.metaKey;
|
||||
```
|
||||
|
||||
## The three cleanest lifts
|
||||
|
||||
**`createOverlays<T>()`.** Nothing in the body knows what an overlay is. Each app writes `export const
|
||||
useOverlays = createOverlays<Overlay>();` and keeps its own union. About 130 lines at zero behavioural risk. M
|
||||
and D have no overlay store but both have palettes and dialogs and would adopt it.
|
||||
|
||||
```ts
|
||||
export interface OverlayState<T extends string> {
|
||||
open: T | null;
|
||||
trail: T[];
|
||||
show: (overlay: T) => void;
|
||||
push: (overlay: T) => void;
|
||||
back: () => void;
|
||||
reachedFrom: (previous: T) => void;
|
||||
toggle: (overlay: T) => void;
|
||||
close: () => void;
|
||||
}
|
||||
export function createOverlays<T extends string>(): UseBoundStore<StoreApi<OverlayState<T>>>;
|
||||
```
|
||||
|
||||
**`onAppEvent`.** Nobody wraps Tauri's `listen`, and it shows. X is the exception, at `X/src/App.tsx:69-77`,
|
||||
signature `onAppEvent<T>(name: string, handler: (payload: T) => void): () => void`. It returns a synchronous
|
||||
unsubscribe, so each effect is one line, and it falls back to `window.addEventListener` for a `CustomEvent` of
|
||||
the same name outside Tauri, which is what lets Playwright drive the connect flow in a browser. C hand-rolls a
|
||||
four-`.then(stop => stop())` teardown at `C/src/App.tsx:52-86`; D uses a third pattern, a module exporting
|
||||
`startWorkspaceEvents(): () => void` that the shell mounts (`D/src/workspace.ts:366-378`).
|
||||
The event names are already common property: `menu-action` in all four, `auth`, `sync-progress` and
|
||||
`store-changed` in C and X, `pdf-warnings` in M and D. Four apps, the same names, three subscription
|
||||
mechanics. Lift X's nine lines; keep D's "module exports `start*()`" convention on top.
|
||||
|
||||
**`useToast` and `notify`.** X's 34 lines beat the byte-identical 15 in C and D. Strict superset: an optional
|
||||
`ToastAction { label, keycap?, run }` for undo, and a `seq` counter bumped on every notice. That counter is a
|
||||
real fix. Auto-dismiss lives in the component in all three, and C's and D's dismiss effects omit a nonce from
|
||||
the dep array, so notifying the same string twice does not restart the countdown; the second toast inherits
|
||||
the remainder of the first one's timer. The dwell times also differ for no reason: 5000ms, 4200ms, 6000ms.
|
||||
M has no toast, only a private `notify` at `M/src/store/useBackup.ts:45` writing into `useBook`'s notice field.
|
||||
|
||||
## Theme: margin-docs wins, and it is not close
|
||||
|
||||
`D/src/theme.ts` is 167 lines against 16, and every extra line earns it: a seven-palette table with a `scheme`
|
||||
per row; a real tri-state `ThemeChoice = Theme | "system"` with a remembered light/dark pair;
|
||||
`storedPreference()` dropping a stored id that no longer names a theme (without it, a palette retired between
|
||||
releases leaves the root with a `data-theme` no stylesheet answers, which is not one broken colour but all of
|
||||
them); `watchSystemScheme()`, the only live `prefers-color-scheme` subscription in any app;
|
||||
`saved()`/`store()` guarding `localStorage` behind `typeof` and `try`/`catch`; and `theme.test.ts` (172
|
||||
lines), the only theme test, holding the TypeScript table and the boot script's copy of it to one table.
|
||||
|
||||
X fakes a tri-state at the UI layer: "System" means deleting the stored key (`forgetThemeChoice()`,
|
||||
`X/src/appearance.ts:41`), so it is a snapshot, not a subscription. Pick System at night and it stays dark
|
||||
through the morning.
|
||||
|
||||
```ts
|
||||
export interface ThemeConfig<T extends string> {
|
||||
themes: readonly ThemeInfo<T>[];
|
||||
keyPrefix: string;
|
||||
fallback: Record<Scheme, T>;
|
||||
}
|
||||
export function createThemeStore<T extends string>(config: ThemeConfig<T>): ...;
|
||||
export function bootScript<T extends string>(config: ThemeConfig<T>): string;
|
||||
```
|
||||
|
||||
Generating the boot script from the same config is the part to insist on. All four apps hand-maintain an
|
||||
inline `<script>` in `index.html` re-reading the theme keys before the bundle exists, and D re-encodes its
|
||||
whole palette-to-scheme table there in plain JS.
|
||||
|
||||
## The root-setting pattern, six times over
|
||||
|
||||
Bigger than theme. Read a boot attribute first because `index.html` already applied it, fall back to
|
||||
`localStorage`, apply to the root, write back. `src/theme.ts` in all four on `data-theme`; `X/src/pane.ts` (20
|
||||
lines) on `data-no-pane`, its header saying it is "exactly the shape `src/theme.ts` uses"; `D/src/width.ts`
|
||||
(52) on `data-width`; `M/src/width.ts` (28) doing the same job through a `--measure` custom property;
|
||||
`M/src/panes.ts` on `--pane-sidebar`/`--pane-dock` with its own private `clamp`; `X/src/appearance.ts` (43) on
|
||||
`--font-ui`, `--font-heading` and `--body-size`.
|
||||
The rule these obey is stated three times in three files: a store may not touch the DOM, and a layout fact the
|
||||
stylesheet needs on first paint has to be an attribute, not a class on a component. Write it down once.
|
||||
Key naming is already strict: every key in every app is `<slug>-<setting>`, slugs `margin-`, `margincal-`,
|
||||
`margindocs-`, `marginmail-`. Counted: 8 keys in M, 6 in C, 17 in D, 9 in X. That prefix is the only per-app
|
||||
parameter a storage helper needs.
|
||||
|
||||
```ts
|
||||
export function makeStorage(prefix: string): {
|
||||
readString(key: string, fallback: string | null): string | null;
|
||||
readJson<T>(key: string, fallback: T): T;
|
||||
write(key: string, value: string): void;
|
||||
remove(key: string): void;
|
||||
};
|
||||
export function rootSetting<T extends string>(opts: {
|
||||
attribute: string; key: string; values: readonly T[]; fallback: T;
|
||||
}): { initial(): T; apply(value: T): void };
|
||||
```
|
||||
|
||||
D has written the guarded accessor pair nine times inside one app: `theme.ts:105`,
|
||||
`store/useUpdate.ts:64,73,85`, `store/useProofing.ts:102,111`, `store/useDocumentFonts.ts:58,77`,
|
||||
`workspace.ts:60,70`, `width.ts:33`, with the catch comment ("A webview with storage denied still X, it just
|
||||
forgets between launches") repeated four times with only the verb swapped. Adopting it also fixes unguarded
|
||||
reads in `M/theme.ts:8`, `C/time.ts:16`, `C/store/useCalendarView.ts:13`, `X/theme.ts:13`, `X/pane.ts:14` and
|
||||
`D/Outline.tsx:30`; several run during module initialisation and would take the whole app down on a throw in a
|
||||
storage-denied webview, and C's is already why `components/overlayModel.test.ts:20-31` stubs a global.
|
||||
|
||||
Do not reach for zustand's `persist` middleware, nor a `useLocalStorage` hook: the boot script reads these
|
||||
keys before any bundle exists, so the shapes must stay plain and hand-chosen. `X/pane.ts:1-8` and
|
||||
`X/appearance.ts:1-7` both document the constraint. `width.ts` itself should not be shared either. M has four
|
||||
named widths on a CSS variable, D five on an attribute plus command wiring; only the persistence overlaps, and
|
||||
`rootSetting` covers it.
|
||||
|
||||
## The IPC layer
|
||||
|
||||
Uniform in three of four and worth stating as the target: a frozen `src/ipc.ts` holding DTOs mirroring
|
||||
`src-tauri/src/dto.rs` plus `call<T>`, and thin per-domain modules in `src/api/` doing nothing but naming a
|
||||
command, e.g. `export const labelsList = (accountId: string | null) => call<LabelInfo[]>("labels_list", {
|
||||
accountId });`
|
||||
|
||||
C has 6 api modules and 41 lines, D 9 and 211, X 16 and 386. X's `ipc.ts` is 760 lines because it has the most
|
||||
DTOs, not because it is structured differently. Only X states the rule explicitly ("Nothing outside src/api
|
||||
may call `call` directly").
|
||||
|
||||
M is the outlier. No `src/api`, `invoke` imported directly in 7 files and called at 8 sites. Its 43-line
|
||||
`ipc.ts` has no `isTauri`, no `live()`, no `isMacDesktop` and no dev-fixture branch, which is why it has no
|
||||
browser dev harness either. **And a real bug**: `M/src/ipc.ts:3` names its constant `isDesktop` but computes
|
||||
what C/D/X call `isTauri`. The same identifier means the opposite thing in different apps, and in M it gates
|
||||
`runWritingTool`, `listSystemFonts` and `gdriveListBackups`. M is desktop-only today so it does not bite yet.
|
||||
|
||||
Shareable: the whole preamble plus `call<T>` as a factory, since the dynamic `import("./dev/mockIpc")` path is
|
||||
necessarily per-app. X's version wins, a strict superset of the byte-identical C and D; the `log_note`
|
||||
recursion guard is the detail nobody would re-derive. DTOs stay per-app. `C/src/ipc/` exists and is empty;
|
||||
delete it.
|
||||
|
||||
## The dev harness
|
||||
|
||||
C, D and X each have `src/dev/fixture.ts` and `src/dev/mockIpc.ts`: 134/222 lines, 696/344, 1769/1572. Every
|
||||
`mockCall` is `(command: string, args?: Record<string, unknown>) => Promise<T>`, a switch on `command` ending
|
||||
in the same byte-identical `dev mock has no handler for ${command}` throw, but the bodies are entirely
|
||||
app-specific. A `createMockIpc(handlers)` supplying the dispatch and default throw is marginal; the real
|
||||
shared pieces are the mock branch inside `call<T>` and X's `onAppEvent` fallback, both covered above. M has
|
||||
no dev harness and cannot be driven in a browser.
|
||||
|
||||
## Keyboard: three registries, one design, no chords
|
||||
|
||||
C, D and X each have `src/keys` with `bindings.ts`, `keymap.ts`, `commands.ts`, `menu.ts`. No file is
|
||||
byte-identical, but the scaffolding is one module forked three ways and several blocks inside are identical
|
||||
(listed above).
|
||||
|
||||
**X's registry should win.** Three reasons that matter.
|
||||
|
||||
Its `resolve()` layers contexts instead of replacing them (`X/keys/keymap.ts:94-109`). A `screener` or `focus`
|
||||
frame overrides only the keys it declares and leaves the base `view` keymap live underneath; only `overlay`
|
||||
and `editor` shadow wholesale, via an explicit `SHADOWS_VIEW` list. C and D fall from the top frame straight
|
||||
to `global`, which kills the base keymap the moment any non-overlay frame is pushed. X subsumes them; they
|
||||
cannot express X.
|
||||
|
||||
Its `normalizeCombo` treats shift as a first-class modifier, so `Cmd+A` and `Cmd+Shift+A` are distinct. D
|
||||
preserves case instead (`cmd+F` vs `cmd+f`), which works for letters on a US layout and breaks for punctuation
|
||||
that only exists shifted. **C's lowercases behind a modifier, so `cmd+F` and `cmd+f` collide silently.** That
|
||||
is a live bug.
|
||||
|
||||
Its `bindings.ts` does not import `commands.ts`, so the table, the sheet and the palette are testable without
|
||||
booting stores or Tauri; in C and D the dependency runs bindings to commands to every store. Its `commands.ts`
|
||||
is 75 lines with zero store imports: a `Map<CommandId, Handler[]>`, `registerCommands` returning its own
|
||||
teardown, last-registered wins, so a screen takes over a verb on mount and hands it back. C's and D's are
|
||||
static tables reaching into the whole app (224 and 433 lines). D is halfway there with its `onCommand`
|
||||
fan-out, worth keeping alongside the stack for cases needing multiple listeners.
|
||||
|
||||
Take `menu.ts` from D instead: the same three lines everywhere, but only D exports its id list and tests that
|
||||
every menu id names a real command.
|
||||
|
||||
**No app supports chords.** All three carry the same header line: "Nothing is chorded and nothing is modal.
|
||||
Two keys never combine into a third meaning." No pending prefix, no timeout, no sequence buffer. A `g i`
|
||||
binding is new work; X's `Map<string, Binding[]>` index and single `comboOf` extend to it most cleanly.
|
||||
|
||||
**M has no registry and should adopt one.** Four unrelated mechanisms: an `if`/`else if` chain on a
|
||||
capture-phase window listener at `M/components/EditorView.tsx:167-192`, a second competing window listener for
|
||||
Cmd+K in `M/editor/FloatingToolbar.tsx:57-70`, TipTap extension shortcuts in four files, and two hand-rolled
|
||||
`menu-action` chains in `App.tsx:25-35` and `EditorView.tsx:199-206` unaware of each other.
|
||||
|
||||
M has no platform detection at all: `grep navigator.` over its `src` returns two clipboard calls. The five
|
||||
`e.metaKey` tests in `EditorView.tsx` are macOS-only and silently dead on Linux and Windows; `primaryHeld`
|
||||
fixes that for free. The blocker is that M has no palette and no shortcut sheet, so the "generated, never
|
||||
maintained" payoff has nowhere to land yet.
|
||||
|
||||
Stays per-app: `BINDINGS` (20 rows, 20, ~70), the `CommandId` union, `GROUPS`, `MENU_IDS`, the command
|
||||
implementations, and app-specific `KeyContext` members. `KeyContext` has to become a type parameter and
|
||||
`SHADOWS_VIEW` an app-supplied list. The two `isMac` regexes differ by design and confusingly little:
|
||||
`keys/bindings.ts` uses `/mac|iphone|ipad/i`, `ipc.ts` uses `/mac/i` gated on `isDesktop`, both correct for
|
||||
their purpose. One `margin-shared/platform` should export both, plus `isTauri`, `isDesktop`, `isMacDesktop`,
|
||||
`live`, `PRIMARY_LABEL`, `primaryHeld` and `secondaryHeld`, with an injectable user agent so the non-Mac
|
||||
branch is finally testable; no test exercises it today.
|
||||
|
||||
## Stores: the conventions are already uniform
|
||||
|
||||
All 42 stores checked. Every one uses the plain `create<State>((set, get) => ({ ... }))`. Not one uses curried
|
||||
`create<T>()(...)`. **No middleware anywhere**: zero hits for `persist`, `subscribeWithSelector`, `immer`,
|
||||
`devtools`, `useShallow` or `zustand/shallow` in any app. Nothing is imported from `zustand` except `create`.
|
||||
|
||||
Selectors are uniformly inline, `(s) => s.field`, one hook call per field rather than one destructured object.
|
||||
No exported selector functions exist in any store directory in any app. That is why no shallow comparator is
|
||||
needed: every subscription is to a primitive or a stable reference. About 620 inline selector sites and 676
|
||||
`getState()` calls.
|
||||
|
||||
Two conventions worth writing down because they are universal and currently retyped everywhere: `if (!live())
|
||||
return;` as the first line of every backend-touching action, about 40 places; and `error: String(e)` in state,
|
||||
never `e.message`.
|
||||
|
||||
The async action shape repeats about 100 times: optimistic set, try, replace with the server's answer, catch,
|
||||
roll back and a `Could not ...` toast. Counts: M 1, C 10, D 33, X 53. **I would not abstract it**: the bodies
|
||||
are five lines and each message is bespoke. Share the `Phase` union and a `describe(e)` helper only.
|
||||
|
||||
`useSearch`, `useAccounts` and `useSync` look shareable by name and are not. The three
|
||||
|
||||
`useSearch` stores do three different jobs. `useAccounts` in C and X shares a real idea, an OAuth consent
|
||||
promise bridged over a Tauri event with the resolver stashed in state, but it is on its third hand-copy
|
||||
(`M/store/useBackup.ts:70` to C to X) and is ~60% app-specific. Share the bridge, not the store, plus
|
||||
`openAuthUrl`/`copyAuthUrl`, character-identical in both and pure utility.
|
||||
|
||||
```ts
|
||||
export function deferred<T>(): { promise: Promise<T>; settle: (value: T) => void };
|
||||
export function latestOnly<A extends unknown[], R>(fn: (...a: A) => Promise<R>): (...a: A) => Promise<R | undefined>;
|
||||
```
|
||||
|
||||
`latestOnly` covers the stale-response race both search stores solve differently: D with module-level
|
||||
monotonic counters (`useSearch.ts:20-21`), X by re-comparing the query string (`useSearch.ts:108`). D's is
|
||||
more general; X's breaks if two callers share a query.
|
||||
|
||||
X's `useSync` is the best sync store, because ~160 of its 210 lines are pure exported functions over
|
||||
`SyncStatus[]` rather than store code, with a 9.6KB test behind them. C keeps the same dedupe logic as an
|
||||
effect-local closure variable in `App.tsx`.
|
||||
|
||||
## Cross-cutting utilities
|
||||
|
||||
**Confirmed absent from all four**: any debounce or throttle utility; deep equality; a `safeParse`/`tryParse`
|
||||
wrapper; class-name joining (no `cx`, no `clsx`, no `classNames`, and no such dependency); `measureText` or
|
||||
any text-measurement helper; `Intl.RelativeTimeFormat`; `Intl.PluralRules`; `navigator.userAgentData`;
|
||||
`nanoid`/`uuid` or any id counter; and `useLocalStorage`, `useInterval`, `useRaf`, `useEvent`, `useLatest`,
|
||||
`useMountedRef` or an exported `sleep`. No truncation helper; truncation is done in CSS.
|
||||
|
||||
The class-name negative is a deliberate architectural choice, not an oversight: all four apps style off data
|
||||
attributes, so no app ever concatenates class names. Do not introduce `cx`.
|
||||
**debounce.** Written longhand at 15 sites across all four. The React-effect variant is the same five lines in
|
||||
at least six places and is worth one `useDebounced<T>(value, ms)`; D's `QuickOpen.tsx:88` and
|
||||
`FindInFiles.tsx:70` are already identical and name the constant `DEBOUNCE_MS`. Leave the class-field and
|
||||
module-level timers alone; their cancel/flush semantics are the point.
|
||||
|
||||
**`clamp`: 6 definitions plus 12 inline sites, zero shared.** `C/grid/fit.ts:89` and
|
||||
`C/components/QuickCreateModel.ts:147` are the identical one-liner duplicated *within C*:
|
||||
|
||||
```ts
|
||||
const clamp = (n: number, lo: number, hi: number) => (n < lo ? lo : n > hi ? hi : n);
|
||||
```
|
||||
|
||||
`C/components/EventDetailsModel.ts:45` should win: it is the only one guarding an inverted range, which
|
||||
matters because half the call sites pass `length - 1` as the high bound and that goes negative on an empty
|
||||
list. `QuickCreateModel.ts:156,163,171` already works around exactly this at every call. Add a `clampIndex(i,
|
||||
length)` for the ten index sites. `M/ExportPreview.tsx:92` and `D/ExportPreview.tsx:143` are the
|
||||
byte-identical zoom clamp.
|
||||
|
||||
**Byte size: four implementations, three spellings.** `D/UpdateDialog.tsx:21` says `kB`, `D/FileViewer.tsx:43`
|
||||
says `bytes` and `KB` with one decimal, `X/screens/format.ts:52` says `B`/`KB`/`MB` with rounding,
|
||||
`X/screens/Settings.tsx:940` adds GB and adaptive precision. 1536 bytes renders as "1.5 KB", "2 kB" and "2 KB"
|
||||
in one product family. X's `space()` wins: the only one reaching GB, and its `mb < 10 ? toFixed(1) :
|
||||
Math.round(mb)` rule actually solves what D's UpdateDialog comment states ("so the number under the bar stops
|
||||
twitching"), by significant figures rather than fixed decimals.
|
||||
|
||||
**Relative time: three hand-rolled ladders, no two agreeing.** `M/src/time.ts:1` is the only standalone
|
||||
module; `M/src/backup.ts:61` is a second copy in the same app with the prefix baked into every branch;
|
||||
`D/components/Settings.tsx:45` is a third, inline, with "Checked" hardcoded throughout. They diverge in
|
||||
behaviour, not just text: M floors, D rounds; M's cutover is 7 days, D's 30. D's rounding makes 89 seconds
|
||||
"just now" and 91 seconds "2 minutes ago". M's wins: the only one guarding clock skew with `Math.max(0, now -
|
||||
ts)`, and flooring is right for "how long ago". Callers compose their own prefix, deleting `backup.ts:61` and
|
||||
reducing `Settings.tsx:45` to one line. X has no "X ago" at all; `rowTime`/`messageTime`
|
||||
(`screens/format.ts:34-49`) go straight to calendar-day buckets and are the only implementation counting by
|
||||
calendar day via local midnight rather than elapsed hours, which is the difference between "Yesterday" being
|
||||
right and being off by a few hours every evening. Keep both.
|
||||
|
||||
**`useClock` is the missing half.** `C/src/useClock.ts` (`useTick<T>`, `useMinuteTick`, `useHourStart`)
|
||||
re-schedules against wall-clock rather than a `setInterval` and treats `visibilitychange` and `focus` as
|
||||
ticks, because a timer's deadline is measured in time the machine spent awake. C is its only consumer today,
|
||||
but M's `relativeTime` callers both take a `now` prop that has to come from somewhere, and X's row formatters
|
||||
default to `Date.now()` at call time and go stale on a window left open overnight. Ship it beside
|
||||
`relativeTime`.
|
||||
|
||||
**`Intl.DateTimeFormat`: no shared factory.** The same `{ day: "numeric", month: "short" }` formatter is
|
||||
constructed in 6 X files and the `hourCycle: "h23"` clock in 3. M and D use bare `toLocaleDateString()`. A
|
||||
memoised `dateFormat(options)` collapses the lot; X's cached-module-constant style is the right pattern.
|
||||
|
||||
C's `src/time.ts` (136 lines) avoids `Intl` entirely with hand-written day and month arrays, a deliberate
|
||||
product decision for a calendar grid that should stay. Its `startOfDay`, `addDays`, `isSameDay`, `toDateOnly`,
|
||||
`parseDateOnly` are reusable date maths and should move; `startOfDay` is already written three times across C
|
||||
and X (`C/time.ts:23`, `X/screens/format.ts:20`, `X/SnoozePicker.tsx:72`).
|
||||
|
||||
**Focus management: one app has it, three do not.** `python/margin/src/focus.ts` (56 lines) is a proper trap:
|
||||
a `FOCUSABLE` selector, Tab wrapping both directions, opener restore on teardown, and a module-level
|
||||
`focusTrapped()` so the global key handler can stand down. Five call sites in M.
|
||||
|
||||
```ts
|
||||
export function useFocusTrap(ref: RefObject<HTMLElement | null>, active = true): void;
|
||||
export function focusTrapped(): boolean;
|
||||
```
|
||||
|
||||
C has autofocus only, no trap and no restore (`components/overlayShell.tsx:51-56`). D and X have neither: both
|
||||
ship `role="dialog" aria-modal="true"` markup with imperative `.focus()` on mount and no trap behind it.
|
||||
**This is the one item where sharing fixes an accessibility gap in three apps rather than removing
|
||||
duplication.** The wrinkle: M's `focusTrapped()` and the other apps' context stack are two mechanisms for one
|
||||
idea. Either the trap pushes an `overlay` frame, or the shared keymap takes a "something external owns the
|
||||
keyboard" predicate.
|
||||
|
||||
**Scroll position restore: near-identical in M and D, and D says so.** `python/margin/src/editor/positions.ts`
|
||||
(64 lines) and `rust/margin-editor/src/editor/positions.ts` (52) share an identical `{ from, to, scroll }`
|
||||
interface, the same guarded `readAll`/`write`, and the same load/save API. D's header names the relationship:
|
||||
M keys by book then chapter, D by absolute path, "and that path is the whole key". D adds an LRU trim at
|
||||
`LIMIT = 200`; M's map grows unbounded. D wins, with a flat string key M composes as `${bookId}/${chapterId}`.
|
||||
|
||||
`scrollIntoView` is raw at 8 sites, never wrapped; `M/editor/search.ts:98` and `D/editor/search.ts:111` are
|
||||
byte-identical. Worth extracting alongside it is `D/components/Outline.tsx:79-89`, the only implementation
|
||||
avoiding `scrollIntoView` scrolling every ancestor, already duplicated once inside D at
|
||||
`editor/linkPicker.ts:572`.
|
||||
|
||||
**JSON.** 10 `JSON.parse` sites, 8 guarded inline, 2 not: `M/library.ts:31` and `M/project.ts:19` parse a file
|
||||
read off disk with no catch, so a truncated or hand-edited project file throws unhandled. Fold the guarded
|
||||
ones into `readJson<T>(key, fallback)`; the file reads want `parseJson<T>(text): T | null`. D's `const parsed:
|
||||
unknown = JSON.parse(...)` then narrow is the right discipline; M and X cast straight to the target type.
|
||||
**`plural`** is the same function under different names in `M/store/useBackup.ts:56` and
|
||||
`D/linkRewrite.ts:694`, plus 10 open-coded `${n === 1 ? "" : "s"}` sites including two byte-identical ones in
|
||||
`X/screens/ReadingPane.tsx:235,502`. M's name wins.
|
||||
|
||||
**ResizeObserver**: 13 raw instantiations, no hook. `M/ExportPreview.tsx:64` and `D/ExportPreview.tsx:104` are
|
||||
byte-identical, as are `M:238`/`D:339` and the `IntersectionObserver` at `M:286`/`D:395`. Any shared
|
||||
`useResize` must carry the null guard `X/screens/MessageBody.tsx:207` documents and the others lack:
|
||||
"`ResizeObserver.observe(null)` throws hard enough to take the screen with it". `getBoundingClientRect` has 32
|
||||
inline sites, all positioning rather than text metrics; the popover-placement clamp is duplicated across four
|
||||
apps but the anchoring rules differ meaningfully, so it is the lowest-confidence item here. Id generation is M
|
||||
only, `crypto.randomUUID()` raw at 8 app-domain sites; C, D and X take ids from Rust, so there is nothing to
|
||||
share.
|
||||
|
||||
## Updates: four apps, four answers
|
||||
|
||||
M has `src/updater.ts` (111 lines) plus `store/useUpdater.ts` (34), a `direct` vs `appstore` channel split,
|
||||
and it holds the live `Update` resource handle in the zustand store. C has `keys/updates.ts` (41), toast-only,
|
||||
"Ported from margin's `src/updater.ts`, minus its progress dialog"; it is the only one of the four with a
|
||||
`packagedBy()` guard, so a nix or homebrew install is told to update through its package manager instead of
|
||||
self-updating. X has no update module at all: `checkForUpdates` is inline at `X/src/App.tsx:98-118`, with a
|
||||
second copy in `screens/Settings.tsx`.
|
||||
|
||||
D has `src/update.ts` (171) plus `store/useUpdate.ts` (129), the best of the four: named phase transitions
|
||||
rather than a generic `set(partial)`; `total: number | null` so a missing content-length draws an
|
||||
indeterminate bar instead of 0% forever; version and notes as plain strings so no Rust handle sits in the
|
||||
store; a launch delay and 24-hour interval for automatic checks; a flush of the pending save before
|
||||
`relaunch()`; and a discriminator for "this dev build has no updater plugin" so that reads as a sentence
|
||||
about the build. Take D's store and driver, fold in C's `packagedBy` guard as an option.
|
||||
|
||||
## Bugs found, worth fixing regardless of any extraction
|
||||
|
||||
- `marginmail-theme` is declared as two constants in two files, `X/src/theme.ts:8` and
|
||||
`X/src/appearance.ts:14`.
|
||||
- X's `checkForUpdates` lacks C's `packagedBy()` guard, so a package-manager-installed build will try to
|
||||
self-update over a path it does not own.
|
||||
- C's `normalizeCombo` lowercases the key behind a modifier, so `cmd+F` and `cmd+f` are one binding.
|
||||
- `M/src/ipc.ts:3` names `isDesktop` what the other three call `isTauri`, and it gates three IPC calls.
|
||||
- `M/library.ts:31` and `M/project.ts:19` parse a file off disk with no catch.
|
||||
|
||||
## Ranked
|
||||
|
||||
1. `escape.ts`. ~144 lines, byte-identical in four apps.
|
||||
2. `createOverlays<T>()`. ~130 lines, code-identical today.
|
||||
3. `platform.ts` (both halves). ~50 lines, byte-identical in three, fixes two M bugs.
|
||||
4. `onAppEvent`. ~60 lines, better teardown, unlocks browser testing for two apps.
|
||||
5. `useMedia.ts`. ~120 lines, byte-identical bodies in three apps.
|
||||
6. `useToast` plus `notify`. ~60 lines, strict superset, fixes a timer bug in two.
|
||||
7. `makeStorage` and `rootSetting`. ~120 lines, deletes nine copies in D, fixes six unguarded reads.
|
||||
8. `call<T>` factory plus the `ipc.ts` preamble. ~50 lines.
|
||||
9. Theme, from D, with a generated boot script. ~250 lines, needs a per-app table.
|
||||
10. Small utilities: `clamp`, `fileSize`, `relativeTime` plus `useClock`, `plural`, `positions.ts`,
|
||||
`useDebounced`, `dateFormat`, `latestOnly`, `deferred`. Collectively ~250 lines and several
|
||||
user-visible inconsistencies.
|
||||
11. `useFocusTrap`. Not a saving; an accessibility fix for three apps.
|
||||
12. The keyboard registry, from X. Largest and highest-value, but needs `KeyContext` parameterised and
|
||||
`SHADOWS_VIEW` injected, and M needs a palette before it benefits.
|
||||
13. The update store and driver. Four designs to reconcile; do it last.
|
||||
|
||||
Items 1 to 6 are mechanically identical across apps today and drop into the existing package with no behaviour
|
||||
change. The one prerequisite is adding `margin-shared` to margin-calendar.
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
# Icons and the smallest UI primitives
|
||||
|
||||
Audit of `margin` (`/Users/pj/Workspace/projects/python/margin`), `margin-calendar`
|
||||
(`/Users/pj/Workspace/projects/python/margin-caledar`), `margin-docs`
|
||||
(`/Users/pj/Workspace/projects/rust/margin-editor`) and `margin-mail`
|
||||
(`/Users/pj/Workspace/projects/rust/margin-mail`) against the partial shared package at
|
||||
`/Users/pj/Workspace/projects/python/margin/shared`.
|
||||
|
||||
## The shared package as it stands
|
||||
|
||||
`shared/src/icons.ts` exports twelve paths plus `SUN_DISC`. Its header comment says the two apps
|
||||
kept drifting, that a path is a design decision, and that `Icon` is deliberately not shared because
|
||||
sharing it "would make this package depend on React for twenty four lines, and a component is where
|
||||
an app is entitled to differ."
|
||||
|
||||
Two of those three claims no longer hold.
|
||||
|
||||
The React argument is wrong on the mechanics. `shared/package.json` has no `dependencies` block at
|
||||
all, no build step, and every app resolves the TypeScript source through its own bundler. All four
|
||||
apps are on `react: ^19.1.0`. A `peerDependencies` entry costs zero bytes and installs nothing;
|
||||
it is a version assertion, not a dependency.
|
||||
|
||||
"An app is entitled to differ" is contradicted by the code. Three of the four `Icon.tsx` files are
|
||||
byte identical (md5 `0ec1a568818f20ed8eed8ad46fbaa2b1`):
|
||||
`/Users/pj/Workspace/projects/python/margin/src/components/Icon.tsx`,
|
||||
`/Users/pj/Workspace/projects/python/margin-caledar/src/components/Icon.tsx`,
|
||||
`/Users/pj/Workspace/projects/rust/margin-editor/src/components/Icon.tsx`. In two years nobody has
|
||||
exercised the entitlement.
|
||||
|
||||
Also worth noting: `margin-calendar` does not consume `margin-shared` at all. There is no
|
||||
`margin-shared` line in `/Users/pj/Workspace/projects/python/margin-caledar/package.json`, and
|
||||
`src/styles/tokens.css` is a hand copy of the shared file's values. Everything below that looks
|
||||
like calendar drifting away from the family traces back to this one fact.
|
||||
|
||||
## The Icon component, line by line
|
||||
|
||||
All four render the same SVG: `viewBox="0 0 24 24"`, `fill="none"`, `stroke="currentColor"`,
|
||||
`strokeWidth="1.6"`, `strokeLinecap="round"`, `strokeLinejoin="round"`, `size = 16` default,
|
||||
`{children ?? <path d={d} />}`. Props are `d?: string`, `size?: number`, `children?: ReactNode`.
|
||||
|
||||
`margin-mail`'s at `/Users/pj/Workspace/projects/rust/margin-mail/src/ui/Icon.tsx:12` is the only
|
||||
one that differs, in four ways, all of them improvements:
|
||||
|
||||
- `export interface IconProps` rather than a private `interface` (line 4).
|
||||
- `className="icon"` (line 15), which is what lets CSS reach the element.
|
||||
- `aria-hidden="true"` (line 24). The other three emit an unlabelled SVG into the accessibility
|
||||
tree at every one of their 142 combined call sites.
|
||||
- `import "./Icon.css"` (line 2), whose entire contents are `.icon { flex: none; }`
|
||||
(`Icon.css:2-4`).
|
||||
|
||||
There is no alignment handling in any of the four components. No `display`, no `vertical-align`,
|
||||
no `shape-rendering`, no `vector-effect`, no transform.
|
||||
|
||||
## Alignment: the thing that keeps being fixed four times
|
||||
|
||||
Across all four repos there are **zero** occurrences of `shape-rendering`, `vector-effect`,
|
||||
`crispEdges`, `geometricPrecision`, or a `translate(0.5 0.5)` style half pixel offset. The
|
||||
alignment problem is not sub-pixel rasterisation. It is the two ordinary CSS facts about an inline
|
||||
SVG: it sits on the text baseline, and it is a flex item that will shrink.
|
||||
|
||||
Five different fixes exist for those two facts, and only one app fixes them centrally.
|
||||
|
||||
`margin-mail` fixes both once:
|
||||
|
||||
- `/Users/pj/Workspace/projects/rust/margin-mail/src/styles/app.css:88` `svg { display: block; }`
|
||||
This is the only global SVG rule in the suite. The other three apps have no `svg` selector at
|
||||
document level at all.
|
||||
- `/Users/pj/Workspace/projects/rust/margin-mail/src/ui/Icon.css:2` `.icon { flex: none; }`
|
||||
|
||||
The other three patch it per site:
|
||||
|
||||
- `/Users/pj/Workspace/projects/python/margin-caledar/src/styles/overlays.css:36`
|
||||
`.panel-note[data-icon] svg { flex: none; transform: translateY(2px); }`
|
||||
- `/Users/pj/Workspace/projects/python/margin-caledar/src/styles/details.css:114`
|
||||
`.details-row[data-block] > svg { margin-top: 2px; }`
|
||||
- `/Users/pj/Workspace/projects/rust/margin-editor/src/styles/tree.css:473`
|
||||
`.start-row svg { align-self: center; color: var(--ink-faint); }`
|
||||
|
||||
A `translateY(2px)` and a `margin-top: 2px` in the same repo, for the same symptom, four files
|
||||
apart. Neither is wrong; both exist because the baseline was never dealt with at the root.
|
||||
|
||||
The residual case is real and survives the global fix: an icon inside an `align-items: baseline`
|
||||
row still needs `align-self: center`. `margin-mail` hits it too, at
|
||||
`/Users/pj/Workspace/projects/rust/margin-mail/src/ui/Row.css:127` (`.row-mark { flex: none;
|
||||
display: inline-flex; align-self: center; }`), which is the same declaration as margin-docs'
|
||||
`tree.css:473`. There are 20 `align-items: baseline` rules across the four apps, so this is a
|
||||
recurring shape, not an exception.
|
||||
|
||||
Icon size is not a shared decision and probably should not become one. `margin-mail` never uses the
|
||||
16px default (zero bare `<Icon d=... />`, nine distinct explicit sizes from 10 to 20). The other
|
||||
three lean on the default heavily: 33 bare call sites in margin-docs, 14 in calendar, 12 in margin.
|
||||
|
||||
## Glyph inventory
|
||||
|
||||
151 path definitions across the suite, 132 distinct strings, 13 of which appear in more than one
|
||||
app. The shared set covers 13. Per app, unique path strings: shared 13, margin 30, calendar 31,
|
||||
margin-docs 47, margin-mail 30.
|
||||
|
||||
Only `margin-mail` keeps its glyphs in a module (`src/ui/icons.ts`, 30 named constants, five
|
||||
re-exported from `margin-shared/icons` at line 14). `margin-docs` names its toolbar and titlebar
|
||||
glyphs as module constants but writes six more inline. `margin` and `margin-calendar` are almost
|
||||
entirely inline `d="M..."` in JSX.
|
||||
|
||||
Shared-set uptake is thin: `margin` uses eleven of the twelve; `margin-docs` uses seven
|
||||
(`SIDEBAR`, `SEARCH`, `SPELLING`, `GRAMMAR`, `EXPORT`, `MORE`, `CHECK`, `WIDTH`); `margin-mail`
|
||||
re-exports five; `margin-calendar` uses none.
|
||||
|
||||
### Same concept, different path
|
||||
|
||||
The important cases, with the exact strings.
|
||||
|
||||
**SEARCH.** Shared `icons.ts:21` is `M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4`. Calendar
|
||||
`components/Header.tsx:22` is `M11 19a8 8 0 100-16 8 8 0 000 16zM21 21l-4.35-4.35`. Different lens
|
||||
radius (7 vs 8) and a different handle. This is the exact divergence the shared package's header
|
||||
comment says it exists to prevent, still present because calendar never joined.
|
||||
|
||||
**MORE.** Shared `icons.ts:57` is three dots, `M5 12h.01M12 12h.01M19 12h.01`. Calendar
|
||||
`components/PhoneBar.tsx:29` uses the same name for a hamburger, `M4 7h16M4 12h16M4 17h16`. A
|
||||
straight name collision on two unrelated glyphs.
|
||||
|
||||
**SUN.** Shared splits it: `SUN_RAYS` (`icons.ts:53`) with a `SUN_DISC` circle at `r: 4`, rays
|
||||
starting at `M12 2v2`. Calendar `Header.tsx:24` is one path with an `r=5` disc and rays at
|
||||
`M12 1v2M12 21v2M4.2 4.2...`. Different construction and different geometry.
|
||||
|
||||
**HEADING.** `margin/src/editor/FloatingToolbar.tsx:126` is `M5 5v14M5 12h8M13 5v14`.
|
||||
`margin-editor/src/editor/Toolbar.tsx:184` is `M7 5v14M7 12h10M17 5v14`, with a comment at line 182
|
||||
that says exactly why: "The H used to run from x=5 to x=13 in a 24 unit box, so it sat left of
|
||||
centre in a round button that every other glyph here is centred in." One app fixed the optical
|
||||
centring; the other still has the bug. This is the "fix the alignment separately in each app"
|
||||
complaint, at the glyph level, with the fix already written down in one repo.
|
||||
|
||||
**BULLET LIST.** `margin/src/editor/FloatingToolbar.tsx:128` puts the bullets at x=3.5:
|
||||
`M8 6h12M8 12h12M8 18h12M3.5 6h.01M3.5 12h.01M3.5 18h.01`.
|
||||
`margin-editor/src/editor/Toolbar.tsx:185` puts them at x=4: `...M4 6h.01M4 12h.01M4 18h.01`. A half
|
||||
unit apart on otherwise identical rules.
|
||||
|
||||
**TRASH.** `margin/src/components/RowMenu.tsx:153` and `margin-editor/src/components/Sidebar.tsx:46`
|
||||
agree: `M5 7h14M10 7V5h4v2M7 7l1 13h8l1-13M10 11v6M14 11v6`. `margin-mail/src/ui/icons.ts:41` is a
|
||||
different drawing: `M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13a1 1 0 0 0 1 1h8a1 1 0 0
|
||||
0 1-1l1-13M10 11v6M14 11v6`. Wider (4 to 20 rather than 5 to 19) and with rounded corners.
|
||||
|
||||
**LINK.** margin `FloatingToolbar.tsx:153` and margin-docs `Toolbar.tsx:192` agree on `l2-2`.
|
||||
Calendar `EventDetails.tsx:46` and `EventEditor.tsx:42` use `l3-3`, a longer link arm.
|
||||
|
||||
**REFRESH.** margin `BackupSettings.tsx:67` is `M21 12a9 9 0 1 1-2.6-6.4M21 4v5h-5`. Calendar
|
||||
`Header.tsx:23` is `M21 12a9 9 0 11-3-6.7M21 3v6h-6`. Different arc endpoint and a different arrow.
|
||||
|
||||
**CHECK.** Shared `icons.ts:61` is `M20 6L9 17l-5-5`, used by margin-docs `WidthMenu.tsx:177` at
|
||||
size 14. margin-docs also draws its own at `components/Settings.tsx:131`,
|
||||
`d="M5 12.5l4.5 4.5L19 7"` at size 13. One app, two ticks.
|
||||
|
||||
**BOLD and ITALIC.** margin renders letterforms, `<b>B</b>` and `<i>I</i>`
|
||||
(`FloatingToolbar.tsx:123-124`). margin-docs draws paths, `BOLD_D` and `ITALIC_D`
|
||||
(`Toolbar.tsx:177-178`). Same toolbar, same button, two different answers to what a bold button is.
|
||||
|
||||
### Same drawing, different spelling
|
||||
|
||||
These render identically and are only string-level drift, but they are what makes a `grep` for
|
||||
duplication useless.
|
||||
|
||||
- **CLOSE**, five spellings: shared `M6 6l12 12M18 6L6 18`; `M18 6L6 18M6 6l12 12` in calendar
|
||||
`EventDetails.tsx:38`, margin-docs `Recents.tsx:23`, `Sidebar.tsx:47`, `Toolbar.tsx:194`,
|
||||
`Settings.tsx:253`, margin `FindBar.tsx:248`; `M18 6 6 18M6 6l12 12` in calendar
|
||||
`overlayShell.tsx:14`.
|
||||
- **MOON**: shared `A9 9 0 1 1 11.2 3` versus calendar `A9 9 0 1111.2 3`. Packed arc flags, same
|
||||
curve.
|
||||
- **CLOCK**: calendar `EventDetails.tsx:44` `M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0M12 7v5l3 2`
|
||||
versus mail `icons.ts:46` `M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l3 2`.
|
||||
- **CHEVRON_RIGHT**: calendar `M9 18l6-6-6-6` versus mail `M9 6l6 6-6 6`. Drawn from opposite ends.
|
||||
- **DUPLICATE**: margin `RowMenu.tsx:142` `M9 9h11v11h-11z M6 15V5h9` versus margin-docs
|
||||
`Sidebar.tsx:42` `M9 9h11v11H9z M6 15V5h9`.
|
||||
|
||||
### Exact duplicates that are not in the shared set
|
||||
|
||||
`PLUS` (`M12 5v14M5 12h14`) is defined independently in all four apps. `CHEVRON_UP`/`CHEVRON_DOWN`
|
||||
(`M6 15l6-6 6 6` / `M6 9l6 6 6-6`) three times. Vertical dots (`M12 5h.01M12 12h.01M12 19h.01`),
|
||||
`MINUS`, `HR`, `IMAGE`, `BLOCKQUOTE` twice each, always margin and margin-docs.
|
||||
|
||||
## The icon button: eleven rules for one control
|
||||
|
||||
All four share a byte-identical `button` reset (`margin app.css:34`, `calendar app.css:63`,
|
||||
`docs app.css:34`, `mail app.css:70`, the last adding `font-size: inherit`). On top of it:
|
||||
|
||||
| App | Class | Size | Radius | Idle | Hover |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| margin | `.icon-btn` (`app.css:103`) | 30 | `--r-sm` | `--ink-soft` | `--accent-wash` |
|
||||
| margin | `.find-btn` (`app.css:2255`) | 26 | `--r-sm` | `--ink-soft` | `--accent-wash` |
|
||||
| margin | `.row-menu-btn` (`app.css:393`) | 22 | `--r-sm` | `--ink-faint` | `--accent-wash` |
|
||||
| calendar | `.icon-button` (`app.css:145`) | 28 | `--r-sm` | `--ink-soft` | `--accent-wash` |
|
||||
| calendar | `.details-close` (`details.css:269`) | 26 | `--r-sm` | `--ink-faint` | `--accent-wash` |
|
||||
| docs | `.icon-button` (`app.css:138`) | 28 | `--r-sm` | `--ink-soft` | `--accent-wash` |
|
||||
| docs | `.find-btn` (`tree.css:585`) | 26 | `--r-sm` | `--ink-soft` | `--accent-wash` |
|
||||
| docs | `.start-forget` (`tree.css:450`) | 26 | `--r-sm` | `--ink-faint` | `--accent-wash` |
|
||||
| docs | `.row-menu-btn` (`app.css:363`) | 22 | `--r-sm` | `--ink-faint` | `--accent-wash` |
|
||||
| docs | `.tree-twisty` (`tree.css:189`) | 16 | `--r-sm` | `--ink-faint` | `--accent-wash` |
|
||||
| mail | `.button[data-icon-only][data-variant="ghost"]` | 28 via `aspect-ratio: 1` | `--r-sm` | `--ink-soft` | `--accent-wash` |
|
||||
|
||||
Every one of them is `display: grid; place-items: center` (except `.start-forget`, which spells it
|
||||
out as flex, and mail, which is inline-flex) with the same radius token, the same hover wash and
|
||||
one of two colour tokens. `margin`'s `.row-menu-btn` and margin-docs' `.row-menu-btn` are the same
|
||||
block copied verbatim into two repos. 26px appears four times across three apps.
|
||||
|
||||
The name is the only thing that reliably differs: `.icon-btn` in margin, `.icon-button` in the
|
||||
other two.
|
||||
|
||||
The "on" state is where they genuinely disagree. margin `app.css:118` and margin-docs
|
||||
`app.css:156` are the same three declarations (`color: var(--accent); background:
|
||||
var(--accent-wash); box-shadow: inset 0 0 0 1px var(--line-strong)`) under two attribute names,
|
||||
`data-on="true"` and `data-active="true"`. Calendar `app.css:160` drops the ring and uses
|
||||
`--ink`. Mail `Button.css:69` makes `[data-active]` identical to `:hover`, so an open panel's
|
||||
button and a hovered button are the same picture. Four apps, four answers, two of them pixel
|
||||
identical under different attribute names. Attribute usage is mixed inside every app too: margin
|
||||
21 `data-on` and 2 `data-active`, calendar 6 and 4, docs 12 and 9, mail 9 and 8.
|
||||
|
||||
There is no icon-button component anywhere except `margin-mail`. 54 call sites across the three
|
||||
older apps hand-write `<button className="icon-btn|icon-button" title=... onClick=...><Icon
|
||||
d={...} /></button>`: margin 18, calendar 16, margin-docs 20. `margin-mail` has 115 `<Button>`
|
||||
usages and 16 `iconOnly` ones, and `Button.tsx:57` supplies the accessible name automatically:
|
||||
`aria-label={label ?? (iconOnly ? title : undefined)}`.
|
||||
|
||||
The floating toolbar button is forked in the worst way. `margin app.css:893` `.tool` and
|
||||
`margin-editor app.css:623` `.tool` are the same rule except one writes `border-radius: 999px` and
|
||||
the other `border-radius: var(--r-pill)`. The same literal-versus-token split repeats on
|
||||
`.editor-toolbar` (`margin app.css:889` vs `docs app.css:619`). The JS helpers differ only in
|
||||
arity: `margin/src/editor/FloatingToolbar.tsx:109` is a render-scoped arrow with four positional
|
||||
params; `margin-editor/src/editor/Toolbar.tsx:156` is a module function with the same four plus
|
||||
`disabled`. Both carry the identical `onMouseDown={(e) => e.preventDefault()}`.
|
||||
|
||||
## Focus, disabled, tooltips, badges, spinners, keycaps
|
||||
|
||||
**Focus rings** are the one thing all four already agree on, byte for byte:
|
||||
`:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }` at
|
||||
`margin app.css:43`, `calendar app.css:80`, `docs app.css:51`, `mail app.css:92`. Nobody ships a
|
||||
polyfill or does keyboard-versus-mouse detection. The divergence is in the exceptions: 18 sites
|
||||
across the suite write `outline: none` with no replacement, and only `margin-mail` invents a second
|
||||
ring colour (`screens/settings.css:467`, `outline: 2px solid var(--accent-wash)` at 1px offset).
|
||||
The round-control case is handled twice and missed once: calendar `create.css:445` and docs
|
||||
`toolbar.css:157` both use a two-layer box-shadow (`0 0 0 2px var(--paper), 0 0 0 3px
|
||||
var(--accent)` and `0 0 0 1.5px ...` respectively, radii disagree), while mail's 15px round swatch
|
||||
has no focus rule and gets the square outline that calendar's comment at `create.css:435` warns
|
||||
about. `/Users/pj/Workspace/projects/python/margin/src/focus.ts` is the only focus-trap module in
|
||||
the family; the other three have none.
|
||||
|
||||
**Disabled** has no agreement at all: five opacity values across four apps. margin uses 0.4, 0.5
|
||||
and 0.6 in one file; calendar uses 0.45; margin-docs uses 0.4, 0.45 and 0.5; margin-mail mostly
|
||||
abandons opacity for `color: var(--ink-faint); background: var(--raised)`
|
||||
(`ui/Button.css:84`), which is the same recipe calendar reached independently at
|
||||
`overlays.css:85`. Only one site in the suite pairs `:disabled` with `pointer-events: none`
|
||||
(`docs export-preview.css:75`).
|
||||
|
||||
**Tooltips** do not exist as a component in any app. All four use the native `title` attribute:
|
||||
44, 40, 66 and 71 occurrences. margin is the outlier on labelling, 44 `title` against 5
|
||||
`aria-label`, so most of its icon buttons are unnamed to a screen reader; the other three run
|
||||
21/43/42. The text generator is forked: margin-docs `Titlebar.tsx:105` `shortcutTitle(id)` returns
|
||||
a whole string, calendar `Header.tsx:33` `hint(command)` returns a leading-space suffix, and margin
|
||||
hardcodes `title="Find (⌘F)"` (`EditorView.tsx:294`) and `"Link (⌘K)"`
|
||||
(`FloatingToolbar.tsx:153`), which are not platform aware.
|
||||
|
||||
**Badges** share one recipe and disagree on every number: a wash-tinted micro chip at
|
||||
`padding: 1px 5|6|9px; background: var(--accent-wash); color: var(--ink-faint); font-size:
|
||||
var(--t-1)`, in calendar `details.css:93`, `overlays.css:487`, `agenda.css:90` and mail
|
||||
`tour.css:127`, with the radius `--r-sm` in calendar and `--r-pill` in mail. Status dots come in
|
||||
5, 6, 7, 8 and 9px, and `border-radius: 50%` and `var(--r-pill)` are both used within one repo
|
||||
(`docs app.css:132` vs `toolbar.css:311`). margin and margin-docs share three copy-pasted classes
|
||||
verbatim: `.dirty-dot`, `.preview-count`, `.find-count`. `font-variant-numeric: tabular-nums` on
|
||||
counts is used by all four.
|
||||
|
||||
**Loading** is the deepest split, and it is a product decision rather than an oversight. margin
|
||||
and margin-docs have rotating spinners (`margin app.css:1461` `.spinner`, plus a byte-identical
|
||||
`backup-spin` duplicate of `spin` at `:2711`; `docs export-preview.css:139` `.preview-spinner`).
|
||||
`margin-calendar` has no spinner, no skeleton and no loading keyframes at all; it expresses
|
||||
pending state as `[data-busy]` and `[data-pending]` on the content itself. `margin-mail` bans
|
||||
spinners in three separate comments and uses bars and skeletons instead. Reduced motion is handled
|
||||
in three different ways: margin has no guard at all, docs slows the spinner from 0.7s to 2.4s, mail
|
||||
disables outright in five places. Do not try to unify this; the four apps mean different things.
|
||||
|
||||
**Keycaps.** calendar `palette.css:104` `.key` and mail `ui/Key.css:1` + `[data-size="md"]` are the
|
||||
same chip: bordered, `--raised`, `--r-sm`, `--t-1`, `min-width: 20px`, `padding: 2px 6px`,
|
||||
`line-height: 1.4`. margin-docs `tree.css:744` `.key-cap` is a different chip, wash-filled with no
|
||||
border at `--t-2` and weight 600. margin has no chip, one rule
|
||||
(`app.css:2191` `.esc-hint kbd`). Only `margin-mail` has a `Key` component
|
||||
(`ui/Key.tsx:15`), only mail puts a cap on ordinary buttons, and only mail hides caps on phones
|
||||
(`Key.css:28`). Underneath, `keys/bindings.ts` in calendar, docs and mail declare identical `isMac`
|
||||
and `PRIMARY_LABEL` lines and an identical eight-entry `NAMED` map, then implement `keyLabel()`
|
||||
three different ways: calendar (`:110`) cannot express `⌘⇧F` at all, docs (`:243`) infers shift
|
||||
from case, mail (`:579`) treats shift as a first-class modifier. margin has no bindings table.
|
||||
|
||||
## Titlebar and window chrome
|
||||
|
||||
All four are Tauri v2 with `"titleBarStyle": "Overlay"` and native traffic lights. Nobody draws
|
||||
window controls, nobody sets `decorations`, `hiddenTitle`, `transparent` or `macOSPrivateApi`, and
|
||||
nobody uses `startDragging` or `-webkit-app-region`; every drag region is the
|
||||
`data-tauri-drag-region` attribute.
|
||||
|
||||
The `.titlebar` rule is the same nine declarations in all four
|
||||
(`margin app.css:67`, `calendar app.css:102`, `docs app.css:76`, `mail header.css:7`):
|
||||
`flex: none; position: relative; z-index: 45; height: var(--titlebar-h); display: grid;
|
||||
grid-template-columns: 1fr auto 1fr; align-items: center; background: var(--shell); border-bottom:
|
||||
1px solid var(--line)`. Differences: margin and calendar and mail set `user-select: none`, docs
|
||||
does not; calendar folds `--safe-top` into the height and padding.
|
||||
|
||||
The lane for the traffic lights is 84px in all four and is reserved three different ways.
|
||||
`margin app.css:74` hardcodes it in `padding: 0 14px 0 84px`, unconditionally, with no token and no
|
||||
platform gate, so Linux and Windows get a dead 84px lane. Calendar (`app.css:126`) and mail
|
||||
(`header.css:24`) put `padding-left: var(--traffic-pad)` on the row under `:root[data-traffic]`.
|
||||
margin-docs puts it on the child instead, `:root[data-traffic] .titlebar .lead { margin-left:
|
||||
calc(var(--traffic-pad) - 14px) }` (`app.css:97`), with a comment explaining that padding on the
|
||||
row pushed the centred title 35px right of the middle. Calendar's view switcher and mail's
|
||||
`<Segment>` are both in centre columns and are subject to exactly that offset.
|
||||
|
||||
Only margin-docs has native code. `/Users/pj/Workspace/projects/rust/margin-editor/src-tauri/src/titlebar.rs`
|
||||
resizes the `NSTitlebarContainerView` on `Resized`, `Focused` and `ThemeChanged` so the lights
|
||||
centre in a 46px row, with a `const TITLEBAR_H: f64 = 46.0` at line 79 that duplicates
|
||||
`--titlebar-h: 46px` from `shared/css/tokens.css:24`. Calendar and mail instead set
|
||||
`"trafficLightPosition": { "x": 9, "y": 25 }` in `tauri.conf.json` and never reapply. margin does
|
||||
neither, so its lights sit at the macOS default, roughly 7px high in a 46px row, which is the
|
||||
misalignment `titlebar.rs` was written to fix.
|
||||
|
||||
`--traffic-pad: 84px` is declared four times (`calendar tokens.css:11` and `:60`,
|
||||
`docs tokens.css:11`, `mail mail.css:36`) and is not in `margin-shared`. So is
|
||||
`--r-pill: 999px` and `--touch-h: 44px`, three copies each. margin declares none of them and
|
||||
inlines the literals.
|
||||
|
||||
## What to share, and what not to
|
||||
|
||||
**Share, high confidence:**
|
||||
|
||||
1. `Icon` itself. Three byte-identical copies plus one strictly better fourth. Move
|
||||
`margin-mail`'s version (className, `aria-hidden`, exported props type) to
|
||||
`shared/src/Icon.tsx` with `react` as a peer dependency. The stated reason not to has no
|
||||
mechanical basis.
|
||||
2. The two lines of alignment that go with it: `svg { display: block }` and `.icon { flex: none }`,
|
||||
as `shared/css/icon.css`. This is the fix that has been made five different ways in four repos
|
||||
and is the direct answer to "I keep fixing icon alignment separately."
|
||||
3. The rest of the glyphs. Promote `PLUS`, `CHEVRON_UP/DOWN/LEFT/RIGHT`, vertical dots, `MINUS`,
|
||||
`HR`, `IMAGE`, `BLOCKQUOTE`, `TRASH`, `LINK`, `REFRESH`, `CLOCK`, `DOCUMENT`, `COPY`,
|
||||
`EXTERNAL`, `BOLD`, `ITALIC`, `HEADING`, `BULLET_LIST` into `shared/src/icons.ts`, picking the
|
||||
better drawing where they have drifted (margin-docs' `HEADING_D` and `BULLET_LIST_D`, the
|
||||
margin/margin-docs `TRASH` and `LINK`, the shared `SEARCH` and `MORE` and `SUN`). Then delete
|
||||
every inline `d="M..."` from JSX. This turns 151 definitions into roughly 60.
|
||||
4. `--r-pill`, `--touch-h` and `--traffic-pad` into `shared/css/tokens.css`. Three copies each of a
|
||||
single number, and in `--traffic-pad`'s case a number that the Rust in one repo has to agree
|
||||
with.
|
||||
5. The keycap. Move `margin-mail`'s `Key.tsx` and `Key.css`; calendar's `.key` is already the same
|
||||
chip, and margin-docs' `.key-cap` is a divergence that should be resolved rather than kept.
|
||||
6. `keyLabel`, `normalizeCombo`, `PRIMARY_LABEL` and the `NAMED` map. Three near-identical
|
||||
implementations of the same twenty lines with three different bugs. `margin-mail`'s is the
|
||||
correct one. This is not strictly a UI primitive, but it is why the caps and titles disagree.
|
||||
|
||||
**Share, but the shape needs deciding first:**
|
||||
|
||||
7. The icon button. Eleven rules for one control is the clearest duplication in the audit, but
|
||||
`margin-mail`'s `Button` bundles size, variant, keycap and icon into one component, while the
|
||||
other three want a flat class they can put on any element. The tractable move is to share the
|
||||
CSS (a `.icon-button` at 28px with `--r-sm`, `--accent-wash` hover, and a settled `[data-on]`
|
||||
ring) and let each app keep its own JSX for now. Renaming margin's `.icon-btn` and settling on
|
||||
one of `data-on` or `data-active` is a prerequisite either way.
|
||||
8. The `.titlebar` grid rule and the traffic lane. The nine declarations are common; the lane
|
||||
mechanism is not, and margin-docs' child-margin version is the correct one. `titlebar.rs`
|
||||
belongs in a shared Rust crate eventually, but that is a bigger move than this audit covers.
|
||||
|
||||
**Do not share:**
|
||||
|
||||
- Spinners and loading states. margin spins, calendar refuses to have any loading affordance,
|
||||
margin-mail bans spinners on the record. These are four different product positions, not four
|
||||
copies of one decision.
|
||||
- Badges, chips and pills. The wash-chip recipe recurs, but every app's numbers are tuned to its
|
||||
own density (a calendar all-day chip is a layout unit, not a badge). Sharing the tokens is
|
||||
enough.
|
||||
- Focus ring exceptions. The global rule is already shared through the tokens; the 18 `outline:
|
||||
none` sites are each local judgement calls, and margin-docs is the only app that writes down why.
|
||||
- The floating editor toolbar. It exists in two apps only, and its `.tool` is a different control
|
||||
from `.icon-button` (a min-width pill that holds a letterform as often as a glyph). Worth
|
||||
de-duplicating between margin and margin-docs, not worth putting in a package the calendar and
|
||||
mail apps import.
|
||||
|
||||
**Prerequisite for all of it:** `margin-calendar` has to depend on `margin-shared`. It is one line
|
||||
in its `package.json` (`"margin-shared": "file:../margin/shared"`) and deleting its hand-copied
|
||||
`tokens.css` values. Every calendar-specific divergence in this document, `SEARCH`, `MORE`, `SUN`,
|
||||
`MOON`, `LINK`, `REFRESH`, the duplicated palette, follows from the fact that it never joined.
|
||||
@@ -0,0 +1,976 @@
|
||||
# Raw memory and CLAUDE.md dump (source material for guidelines/)
|
||||
|
||||
Concatenated verbatim on 2026-09-06. Do not edit; this is the source, not a deliverable.
|
||||
|
||||
## Project: python-margin
|
||||
|
||||
### python-margin / app-review-notes-audience.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: app-review-notes-audience
|
||||
description: App Review notes must be actionable with only the built app, never reference source paths
|
||||
metadata:
|
||||
type: feedback
|
||||
---
|
||||
|
||||
App Store review notes are read by someone who has the built app and nothing else. Never cite
|
||||
source files, line numbers or repo paths in them. Describe what a reviewer can see and do in the
|
||||
running app: the UI path to a feature, what it does, observable behaviour.
|
||||
|
||||
**Why:** PJ pulled "The code is in src-tauri/src/gdrive.rs" out of the notes before resubmitting
|
||||
margin 0.1.17. The apps being open source does not help, because nothing in the notes points the
|
||||
reviewer at the repo, so a path is just noise in a field with a 4000 character limit.
|
||||
|
||||
**How to apply:** When writing `appstore/metadata/review_notes.txt` for any of the margin apps,
|
||||
justify an entitlement by what it enables and how to reach it in the UI, plus the observable
|
||||
constraints (bound to loopback only, times out, off until the user connects an account). Applies to
|
||||
margin-calendar and margin-docs too. See [[margin-distribution-plan]].
|
||||
```
|
||||
|
||||
### python-margin / commit-message-style.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: commit-message-style
|
||||
description: "commit messages are one plain lowercase line, no type prefix, no scope, no body"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 686d3870-3e2c-4060-875c-4a49b701b9f2
|
||||
modified: 2026-09-01T17:47:43.543Z
|
||||
---
|
||||
|
||||
A commit message is one line of plain lowercase text describing the change, e.g.
|
||||
`send app store builds to the store for updates`. No `feat(scope):` prefix, no body, no bullets,
|
||||
no blank line and explanation. The prefix counts as formatting and is not wanted.
|
||||
|
||||
**Why:** The diff and the docs carry the reasoning. The message just names the change.
|
||||
|
||||
**How to apply:** `git commit -m "add the thing"` and stop. Never a heredoc or `-F -`. Applies to
|
||||
amends. Note the repo's own CLAUDE.md still asks for conventional commit format; this instruction
|
||||
overrides it until that file is changed. See [[no-em-dashes]] for the related prose rules.
|
||||
```
|
||||
|
||||
### python-margin / dont-start-dev-server.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: dont-start-dev-server
|
||||
description: "Never start the margin dev server yourself — the user runs it; a scratch vite on a spare port is the safe way to browser-test"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: f0e048ec-7e18-4118-a470-e793b231f468
|
||||
---
|
||||
|
||||
Do not run `pnpm tauri dev` / `pnpm dev`. The user keeps the dev server running themselves and HMR picks up source edits in their instance (use that for verification).
|
||||
|
||||
**Why:** vite uses `strictPort: 1420`, so a second `tauri dev` fails with `ELIFECYCLE Command failed` and conflicts with, or kills, the user's running app. The user was explicit and annoyed about this.
|
||||
|
||||
**How to apply:** before any step that needs the running app, check `ps aux | grep -E "margin-app|vite"`. If a server is running, use it (edits hot-reload). If none is running, ask the user to start it, don't start one. Also can't screen-capture the native WebKit window (no screen-recording permission).
|
||||
|
||||
For browser-testable frontend work, `npx vite --port 5199 --strictPort` in the background plus the playwright MCP tools works well and never touches 1420. Kill it when done. Caveat: `isDesktop` (`"__TAURI_INTERNALS__" in window`) is false there, so desktop-gated UI is absent; injecting a small `__TAURI_INTERNALS__.invoke` stub backed by localStorage for `list_books`/`load_book`/`save_book`/`delete_book` makes the library and multi-book flows testable. See [[no-in-code-tests]].
|
||||
```
|
||||
|
||||
### python-margin / gdrive-backup-spec.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: gdrive-backup-spec
|
||||
description: "Agreed design for margin's local-only Google Drive backup feature (no backend, no login)"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: c3e99a43-39ac-4ff5-8cae-326ff24135e3
|
||||
---
|
||||
|
||||
Planned feature: connect Google Drive locally to back up books. No backend server, no login. margin data is small/clean: self-contained `{book-id}.margin` JSON files (images embedded as base64) in `~/Library/Application Support/studio.margin.app/library/`, plus `custom-dictionary.txt`. Reference prior art (Go): `/Users/pj/go/src/github.com/priyanshujain/openbotkit` does the loopback OAuth + `drive.file` pattern, but makes the USER supply `credentials.json` (fine for a dev CLI, wrong for margin's consumers).
|
||||
|
||||
**Auth:** one embedded "Desktop app" OAuth client (PJ registers it in his own Google Cloud project), loopback + PKCE flow via system browser. Scope `drive.file` + `openid email`. `drive.file` is non-sensitive, so NO Google verification review and NO CASA audit; set consent screen to Production to avoid the unverified warning and the testing-mode 7-day refresh-token expiry. For installed apps the client secret is not confidential; embed it, ideally via the same release-overlay pattern as [[updater-overlay-config]] to keep local builds clean.
|
||||
|
||||
**Decisions (locked via discussion):**
|
||||
- Drive layout: visible `margin/` folder, books 1:1 to `{id}.margin` files + dictionary. Latest-only (overwrite); Drive keeps revisions automatically so version-restore UI can come later.
|
||||
- Model: backup + restore, last-write-wins, warn if remote copy is newer.
|
||||
- Triggers: manual (top-right icon) + on app close + periodic every 15 min, all gated on a dirty/hash check (only upload if something changed).
|
||||
- Top-right icon = action + status: muted when up to date, accent tint when changes pending (click to back up), animated while backing up, warning tint on error, subtle outline when not connected.
|
||||
- Settings: add a new minimal Settings panel (first real preferences UI) with a Backup section for connect/disconnect, account email, status, and full restore.
|
||||
- Restore: subtle, ignorable "Restore from Google Drive" affordance on the home page empty-library state (does not bother new users); doubles as connect-on-new-machine.
|
||||
- Included: all `.margin` books + `custom-dictionary.txt`.
|
||||
|
||||
**Rust/Tauri approach:** no heavy Google SDK. `oauth2` crate + `tauri-plugin-oauth` (loopback catch) + existing `tauri-plugin-opener` (browser) + `reqwest` for the ~5 Drive REST endpoints. Refresh token in OS keychain (`keyring`); folder id / account / sync-state in a small `backup.json` in app data dir. New Tauri commands ~ `gdrive_connect`, `gdrive_disconnect`, `gdrive_status`, `backup_now`, `restore`, `list_remote_backups`.
|
||||
|
||||
Status as of 2026-06-22: BUILT and compiling (cargo check + tsc + vite build all pass). Backend in `src-tauri/src/gdrive.rs` (commands gdrive_connect/disconnect/status/backup/restore/list_backups), registered in lib.rs with managed GDriveState + init_session on setup. Creds loaded via `include_str!` from project-root `google-credentials.json` (gitignored; `google-credentials.example.json` committed; placeholders trigger a friendly "not set up" error). Frontend: `src/backup.ts`, `src/store/useBackup.ts`, `BackupButton` (in EditorView titlebar + Library head; clicking it OPENS the BackupSettings panel — not one-click backup — since the panel is the single home for back up / restore / disconnect / account), `BackupSettings` modal (mounted in App), home-page `.restore-link` on empty library; on-close + 15-min periodic backup in App.tsx. Connect is event-based: `gdrive_connect` returns the auth URL immediately + spawns a background task that emits a `gdrive-auth` {ok,error} event; the panel shows Open-link-again / Copy-link / Cancel while connecting; loopback wait times out after 120s (AUTH_TIMEOUT_SECS). Refresh token + sync state both stored in plaintext app-data `backup.json` — NO OS keychain (removed because macOS re-prompts on every dev rebuild and the bundle-id label "studio.margin.app" confused the user; drive.file scope is limited so plaintext matches the app's existing local-data model). Manual backup returns an `uploaded` count: >0 → "Backed up to Google Drive", 0 → "Nothing new to back up" (and last_backup only bumps when something uploaded). Clicking the cloud icon opens the panel; the panel's "Back up now" button is the manual trigger.
|
||||
|
||||
Cleanup pass done (verified via cargo check + tsc + vite build): shared path helpers `app_data_dir`/`library_dir` now live pub(crate) in `library.rs` (reuse them, don't recreate); a single `static HTTP: LazyLock<reqwest::Client>` is reused for all Drive calls; `compute_pending` uses an mtime fast-path (only re-hashes books whose mtime > last_backup) so status polls are cheap; `BackupOutcome` flattens `Status` (serde flatten); `restoreFromDrive` orchestration (connect-then-restore) lives in the useBackup store, called from Library. Toast/notice unified on the global `useBook` store across both Library and EditorView.
|
||||
|
||||
REMAINING (blocked on PJ): create Google Cloud project + Desktop OAuth client (scopes drive.file + openid + email, publish to Production), download JSON to replace google-credentials.json, restart `tauri dev` (creds are compile-time embedded), then end-to-end test connect/backup/restore. Not yet e2e tested with real creds.
|
||||
```
|
||||
|
||||
### python-margin / margin-distribution-plan.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: margin-distribution-plan
|
||||
description: "Agreed distribution strategy and licensing for the three Margin apps (App Store, Homebrew, direct)"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: 23c1b6b5-40e8-4350-8c85-e0fdb3783572
|
||||
modified: 2026-08-30T12:04:56.430Z
|
||||
---
|
||||
|
||||
Decided 2026-08-30. All three Margin apps (margin, margin-calendar, margin-docs) are **free**, with
|
||||
no license gate and no in-app purchase, so Apple takes no cut and App Store anti-steering rules do
|
||||
not apply.
|
||||
|
||||
Channels, in priority order:
|
||||
- **Mac App Store is the primary macOS channel.** Sandboxed, no self-updater, separate build track.
|
||||
- **Own Homebrew tap** `priyanshujain/homebrew-margin`, not upstream homebrew-cask (the repos have
|
||||
~1 star and do not clear the notability bar).
|
||||
- **Direct download** from margin.73ai.org stays the unrestricted build with the Tauri updater.
|
||||
|
||||
Ordering: margin ships first (most polished), then calendar, then docs.
|
||||
|
||||
Deliberately not done: no migration bridge for the library moving into the sandbox container. There
|
||||
are effectively no existing users, so a first-run import is not worth building yet.
|
||||
|
||||
Licensing: margin is **FSL-1.1-MIT** (free for anything except a competing product, becomes MIT two
|
||||
years after each release). Chosen because the user wants open code that nobody else monetizes,
|
||||
which is not open source by the OSI definition. **AGPL was ruled out because it is incompatible
|
||||
with the Mac App Store.** margin-calendar and margin-docs are still MIT and have not been
|
||||
relicensed; that is an open question.
|
||||
|
||||
Apple account: Individual, enrolled but nothing created as of 2026-08-30. Signing private keys and
|
||||
CSRs live in `~/.margin-signing/` (developer-id, apple-distribution, mac-installer), generated with
|
||||
openssl rather than Keychain Access so CI `.p12` files can be rebuilt without a GUI.
|
||||
|
||||
Mechanics live in the repo at `docs/publishing.md`. See also [[no-em-dashes]], [[no-code-comments]].
|
||||
```
|
||||
|
||||
### python-margin / MEMORY.md
|
||||
|
||||
```markdown
|
||||
- [No in-code tests](no-in-code-tests.md) — never commit tests; verify by running the actual product
|
||||
- [No prettier](no-prettier.md) — repo is hand-formatted at ~120 cols; running prettier mangles whole files
|
||||
- [No code comments](no-code-comments.md) — self-readable code, refactor instead of commenting
|
||||
- [Updater overlay config](updater-overlay-config.md) — pubkey lives in tauri.release.conf.json overlay (CI-only), not tauri.conf.json, to keep local builds key-free
|
||||
- [Don't start dev server](dont-start-dev-server.md) — user runs `tauri dev` (strictPort 1420); never launch it, ask if not running
|
||||
- [No em dashes](no-em-dashes.md) — avoid —/– in copy and generated prose; restructure instead
|
||||
- [GDrive backup spec](gdrive-backup-spec.md) — agreed design for local-only Google Drive backup (no backend/login)
|
||||
- [Mobile setup status](mobile-setup-status.md) — responsive layout (≤899px drawers) + iOS Tauri target initialized; Android not set up; mobile runtime limits
|
||||
- [Margin distribution plan](margin-distribution-plan.md) — free apps, MAS primary, own brew tap, FSL-1.1-MIT
|
||||
- [App Review notes audience](app-review-notes-audience.md) — reviewers have the built app only; no source paths in review notes
|
||||
- [Commit message style](commit-message-style.md) — one line, lowercase, plain text, no body
|
||||
```
|
||||
|
||||
### python-margin / mobile-setup-status.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: mobile-setup-status
|
||||
description: State of the iOS/Android mobile build and the responsive layout work
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: 84a2bb57-78cb-4049-8574-0e1f54665d89
|
||||
---
|
||||
|
||||
Margin now ships a responsive layout AND an initialized Tauri mobile (iOS) target.
|
||||
|
||||
**Responsive layout** (added 2026-06): breakpoint is `(max-width: 899px)` via `useCompact()` in `src/useMedia.ts`. The `.app` root carries `data-compact`/`data-sidebar`/`data-dock`. Desktop: sidebar collapses to width 0 and the editor reclaims space (toggle = ☰ top-left of titlebar). Compact: sidebar + preview become fixed slide-in drawers over a full-width editor, one at a time, with a `.drawer-scrim`; extra titlebar actions fold into a ⋯ overflow menu. Safe-area insets + `--titlebar-h` handle the notch. Modals use `.panel { width: min(480px, calc(100vw - 32px)) }`.
|
||||
|
||||
**iOS**: `tauri ios init` done (`src-tauri/gen/apple`, not gitignored). Verified `cargo check --target aarch64-apple-ios-sim` and a full `tauri ios build --target aarch64-sim --debug` both succeed; the app installs/launches in the iPhone 17 Pro simulator. typst PDF, harper, reqwest all cross-compile fine. `isDesktop` in `src/ipc.ts` actually means "is Tauri" so it's true on mobile.
|
||||
|
||||
**Android**: NOT set up — needs Android SDK + NDK + JDK 17 (machine has JDK 25, no ANDROID_HOME).
|
||||
|
||||
**iOS WKWebView CSS gotchas fixed (not reproducible in desktop browser — verify on the simulator/device):** (1) text auto-inflation of wide blocks → `html { -webkit-text-size-adjust: 100% }`. (2) zoom-in on input focus → viewport `maximum-scale=1.0, user-scalable=no`. (3) keyboard scrolled the whole page (titlebar under the notch) → `body { position: fixed; inset: 0; overflow: hidden }` + `.app/.library { height: 100dvh }` so only `.editor-pane` scrolls. (4) title-input caret drawn below the text → `.chapter-title-input { line-height: 1.4 }` (1.16 was tighter than Literata's natural metrics). Note: programmatic `.focus()` on iOS does NOT show the caret/keyboard without a real user gesture, so caret/keyboard states can't be screenshot-verified via simctl — needs a human tap.
|
||||
|
||||
**Mobile runtime limitations still to address** (compile fine, but won't work right on device): Google Drive backup uses a localhost-loopback OAuth (`gdrive.rs`) that won't work on iOS; system-font listing returns little; arbitrary-path file save/open assumes desktop dialogs; updater/process are `#[cfg(desktop)]`-gated (no-op on mobile, capability split into `capabilities/desktop.json`). Native menu is also desktop-only, so mobile relies on in-app buttons (Library + ⋯ menu) for New Book / Export.
|
||||
|
||||
Related: [[dont-start-dev-server]], [[updater-overlay-config]], [[gdrive-backup-spec]].
|
||||
```
|
||||
|
||||
### python-margin / no-code-comments.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: no-code-comments
|
||||
description: Write self-readable code with no comments instead of explaining via comments
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: a776698a-6dd2-4bf4-87bb-f13f20b892bd
|
||||
---
|
||||
|
||||
Do not add code comments. Make the code itself readable (clear names, small functions) so comments are unnecessary.
|
||||
|
||||
**Why:** The user puts the effort into readable code and considers comments noise.
|
||||
|
||||
**How to apply:** When tempted to write a comment, refactor for clarity (rename, extract a well-named function) instead. See also [[no-in-code-tests]].
|
||||
```
|
||||
|
||||
### python-margin / no-em-dashes.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: no-em-dashes
|
||||
description: User dislikes em dashes (and en dashes) in copy and generated text
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 3afd9184-a526-4317-a413-d49e3e93b6b1
|
||||
---
|
||||
|
||||
Do not use em dashes (—) or en dashes (–) in any user-facing copy, marketing text, or generated writing for this user.
|
||||
|
||||
**Why:** The user finds them undesirable in prose and flagged removing them explicitly while polishing the Margin website hero.
|
||||
|
||||
**How to apply:** Restructure with periods, commas, colons, or parentheses instead. When editing existing copy, sweep for `—`/`–` and replace. Applies to website copy and any prose I write, not just code.
|
||||
```
|
||||
|
||||
### python-margin / no-in-code-tests.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: no-in-code-tests
|
||||
description: Do not write tests in the codebase; verify by running the actual product directly
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: a776698a-6dd2-4bf4-87bb-f13f20b892bd
|
||||
---
|
||||
|
||||
Never add tests to the codebase (no Rust `#[cfg(test)]`/`#[test]` modules, no JS test files/harnesses). Verify changes by running the actual product directly.
|
||||
|
||||
**Why:** The user wants the repo to contain product code only; correctness is confirmed by exercising the real app, not by committed tests.
|
||||
|
||||
**How to apply:** After a change, run/drive the actual app to confirm behavior. Do not commit test code. See also [[no-code-comments]].
|
||||
```
|
||||
|
||||
### python-margin / no-prettier.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: no-prettier
|
||||
description: "margin is not prettier-formatted — running prettier reformats whole files and buries the real diff"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
---
|
||||
|
||||
The repo has no prettier config and its source is hand-formatted at roughly 120 columns. Running `npx prettier --write` on a file rewrites it at prettier's 80-column default and turns a 60-line change into a 340-line diff.
|
||||
|
||||
**Why:** it destroys reviewability and churns files the change never touched.
|
||||
|
||||
**How to apply:** never run prettier (or any formatter) on this repo. Make surgical edits and match the surrounding indentation by hand. If a formatter has already run, `git checkout <file>` and redo the edits manually. See [[no-code-comments]].
|
||||
```
|
||||
|
||||
### python-margin / updater-overlay-config.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: updater-overlay-config
|
||||
description: "Why the Tauri updater pubkey lives in a release-only overlay config, not tauri.conf.json"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: 845e4db7-1d47-4b07-8073-155095a7b944
|
||||
---
|
||||
|
||||
margin's Tauri updater config (`plugins.updater.pubkey` + `bundle.createUpdaterArtifacts: true`) lives in `src-tauri/tauri.release.conf.json`, a release-only overlay merged via `--config` in the GitHub Actions release workflow. It is deliberately kept OUT of the committed `src-tauri/tauri.conf.json`.
|
||||
|
||||
**Why:** the mere presence of `plugins.updater.pubkey` in `tauri.conf.json` makes `tauri build` demand a signing key (tauri-apps/tauri#14581), which would break the local key-free `pnpm dmg` build. The overlay scopes signing + updater artifacts to CI only; local builds stay clean. Only CI-built (signed) releases need to self-update anyway.
|
||||
|
||||
Release flow is manual `workflow_dispatch` in `.github/workflows/release.yml` (prepare → build matrix `max-parallel: 1` → publish). `max-parallel: 1` is required so tauri-action's read-modify-write merge of `latest.json` across platforms can't race.
|
||||
```
|
||||
|
||||
## Project: python-margin-caledar
|
||||
|
||||
### python-margin-caledar / calendar-navigation-steps-by-day.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: calendar-navigation-steps-by-day
|
||||
description: "In Margin Calendar, prev/next navigation must move one day at a time, never jump a whole week"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 9a11f15b-a564-473a-8289-d6dcf73df055
|
||||
modified: 2026-08-10T15:10:09.086Z
|
||||
---
|
||||
|
||||
Navigation in Margin Calendar moves **one day at a time**. The header arrows and `h`/`l` step a
|
||||
single day; jumping a whole week is the behaviour the user called out as the thing they
|
||||
"absolutely hate".
|
||||
|
||||
**Why:** week view originally snapped to `startOfWeek`, so a one-day step was invisible six times
|
||||
out of seven and the arrows had to jump a week to do anything. Sliding by a day keeps positional
|
||||
memory intact, which is most of the speed of a keyboard-driven calendar, and is the same reason
|
||||
the vertical axis has contraction hysteresis.
|
||||
|
||||
**How to apply:** week view is a rolling seven days from the anchor by default (`weekMode()` in
|
||||
`src/time.ts`, stored under `margincal-week-mode`). `weekAnchor()` is the single source both
|
||||
`spanFor` and `GridView` use, so never reintroduce a bare `startOfWeek` call in either. The
|
||||
"calendar" mode that snaps to whole weeks exists in Settings, and only there do the arrows step by
|
||||
a week, because a day step would be invisible. Related: [[margin-calendar-google-cloud-project]].
|
||||
```
|
||||
|
||||
### python-margin-caledar / linux-distribution-is-nix-not-aur.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: linux-distribution-is-nix-not-aur
|
||||
description: Linux installs ship through a Nix flake; the AUR package was dropped in Sep 2026 because pj has no AUR account and signups are restricted
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: e48a0fd3-0e18-4f9d-8b06-d3bbbbee65ac
|
||||
modified: 2026-09-03T06:23:56.541Z
|
||||
---
|
||||
|
||||
On 2026-09-03 the AUR job and PKGBUILD were removed and replaced with a Nix flake (flake.nix, nix/package.nix, nix/release.json). pj has no AUR account and the AUR has restricted signups, so AUR publishing had become a blocker for Linux users.
|
||||
|
||||
**Why:** The Nix package is a binary repackage of the released deb, for the same reason the AUR one was: the Google OAuth client is embedded at compile time from a file not in the repo, so from-source builds by strangers produce an app that cannot connect. The wrapper sets MARGIN_CALENDAR_PACKAGED_BY=nix so the in-app updater announces new versions but does not try to install over the store.
|
||||
|
||||
**How to apply:** Do not propose the AUR again. The release workflow's nix job writes nix/release.json on main after publish; users install with `nix profile install github:priyanshujain/margin-calendar`. Nix is not installed on pj's Mac; test the flake through the amd64 nixos/nix Docker image with `filter-syscalls = false` (seccomp fails under emulation) and a named volume on /nix.
|
||||
```
|
||||
|
||||
### python-margin-caledar / margin-calendar-google-cloud-project.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: margin-calendar-google-cloud-project
|
||||
description: "Margin Calendar's Cloud project margin-500217 is owned by [email protected], needs the Calendar API enabled per project, and needs separate OAuth clients per platform"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: 9a11f15b-a564-473a-8289-d6dcf73df055
|
||||
modified: 2026-08-12T13:02:23.872Z
|
||||
---
|
||||
|
||||
Margin Calendar's desktop `google-credentials.json` is copied from `../margin`, so both apps share
|
||||
one OAuth desktop client: Cloud project `margin-500217`, numeric id `205537985128`. The project is
|
||||
owned by **[email protected]**, not `[email protected]`, which is the signed-in app account.
|
||||
|
||||
**Why:** the client was created for margin's Drive scope. Sharing it means the consent screen and
|
||||
the enabled API list are shared too, and enabling an API is per project, not per client. On
|
||||
2026-08-10 the calendar scope was granted correctly but every `calendarList` call returned 403
|
||||
`SERVICE_DISABLED`, because the Calendar API had never been enabled on that project. A
|
||||
`gcloud services enable` run as the gmail account was denied, because that account does not own
|
||||
the project.
|
||||
|
||||
Phones share it too, and that is deliberate. A Desktop client may redirect to loopback on any port
|
||||
without registering it, and Google's token endpoint checks the client id, secret and redirect
|
||||
rather than the calling OS, so a phone signs in on this same client with no console work. Verified
|
||||
on 2026-08-12: Google's real consent screen renders and accepts this client on both an iOS
|
||||
simulator and an Android emulator. It works because the protocol does not check, not because Google
|
||||
blesses it; the fallback if they ever enforce it is a per-platform client, which the code supports.
|
||||
|
||||
One thing still argues for an **iOS** client (bundle id `studio.margin.calendar`, no SHA-1, about a
|
||||
minute): it switches iOS to `ASWebAuthenticationSession`, which shares Safari's session, so the
|
||||
user is not asked to sign in to Google again. Android needs nothing, because Chrome Custom Tabs
|
||||
share Chrome's cookies already, and that was measured rather than assumed. iOS session sharing
|
||||
could NOT be confirmed on the simulator and needs checking on a real device. See `docs/mobile.md`.
|
||||
|
||||
**How to apply:** if calendars come back empty while auth succeeds, check the API is enabled before
|
||||
suspecting sync, and run the enable as pj@73ai.org. To see the real error the UI may swallow, curl
|
||||
`calendarList` directly. Note the token is no longer in any keychain: it is XChaCha20-Poly1305
|
||||
sealed in `tokens.enc` under the app data directory, so the old
|
||||
`security find-generic-password` check no longer applies. Related:
|
||||
[[calendar-navigation-steps-by-day]], [[prefer-cross-platform-over-per-platform-native]].
|
||||
```
|
||||
|
||||
### python-margin-caledar / MEMORY.md
|
||||
|
||||
```markdown
|
||||
- [Navigation steps by day](calendar-navigation-steps-by-day.md): prev/next moves one day, never a whole week
|
||||
- [Google Cloud project](margin-calendar-google-cloud-project.md): owned by pj@73ai.org; Calendar API is per project; phones need their own OAuth clients
|
||||
- [Cross-platform over per-OS native](prefer-cross-platform-over-per-platform-native.md): one implementation everywhere beats a native backend per OS
|
||||
- [Reading app localStorage from WebKit](reading-app-localstorage-from-webkit.md): installed app state lives in a WebKit sqlite; dev server has a separate store
|
||||
- [Linux ships via Nix, not AUR](linux-distribution-is-nix-not-aur.md): AUR dropped Sep 2026 (no account, restricted signups); flake repackages the release deb, tested via amd64 Docker nix image
|
||||
```
|
||||
|
||||
### python-margin-caledar / prefer-cross-platform-over-per-platform-native.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: prefer-cross-platform-over-per-platform-native
|
||||
description: PJ wants one cross-platform implementation rather than a native integration per OS with fallbacks
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 9a11f15b-a564-473a-8289-d6dcf73df055
|
||||
modified: 2026-08-12T11:40:34.115Z
|
||||
---
|
||||
|
||||
When a dependency needs a different native integration on each OS, PJ wants it replaced with one
|
||||
implementation that works everywhere, not patched per platform. Said twice about `keyring`: first
|
||||
"stop using keyring in macos", then "we should not use keyring man use some cross platform
|
||||
solution".
|
||||
|
||||
**Why:** the per-platform version had four ways of reaching one real implementation. macOS was
|
||||
already excluded because Keychain ties an item to the code signature and re-prompts on every
|
||||
rebuild; Android has no backend at all; and on Linux the Secret Service is missing on exactly the
|
||||
minimal window managers that most wanted it. The branching cost more than it bought, and the
|
||||
prompts were a visible daily irritation.
|
||||
|
||||
**How to apply:** before adding a dependency with per-OS backends, check it covers all five targets
|
||||
(macOS, Linux, Windows, Android, iOS). If it does not, prefer the uniform option and state the
|
||||
security or capability trade plainly in the code rather than hiding it behind a fallback chain.
|
||||
Accepting a weaker but uniform mechanism is usually the answer he wants. Related:
|
||||
[[margin-calendar-google-cloud-project]].
|
||||
```
|
||||
|
||||
### python-margin-caledar / reading-app-localstorage-from-webkit.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: reading-app-localstorage-from-webkit
|
||||
description: "How to read the installed app's folds/bounds/theme state straight from WebKit's localStorage sqlite when debugging a grid report"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: reference
|
||||
originSessionId: 929ddef4-dd49-476b-91a5-ecbc7ba3acae
|
||||
modified: 2026-09-02T20:58:10.838Z
|
||||
---
|
||||
|
||||
The installed Tauri app (bundle id `studio.margin.calendar`) keeps its localStorage at
|
||||
`~/Library/WebKit/studio.margin.calendar/WebsiteData/Default/*/*/LocalStorage/localstorage.sqlite3`.
|
||||
Copy the file (and its `-wal` sibling) to /tmp first, then `sqlite3 ... "select key, hex(value) from ItemTable"`;
|
||||
values are UTF-16LE. Keys are `margincal-folds`, `margincal-bounds`, `margincal-view`, `margincal-theme`.
|
||||
|
||||
**Why:** on 2026-09-03 the "now line hidden in a strip" report was only explainable by the user's
|
||||
real stored folds (a `{0,8}` fold covering the 1am hour). The dev-server origin has its own store
|
||||
under `~/Library/WebKit/margin-calendar/`, so dev runs do not reproduce what the installed app shows.
|
||||
|
||||
**How to apply:** when a screenshot of the installed app disagrees with what the code should draw,
|
||||
read this state before theorising. Reading is fine; never edit the file.
|
||||
```
|
||||
|
||||
## Project: python-margin-website
|
||||
|
||||
No memory files.
|
||||
|
||||
## Project: rust-margin-editor
|
||||
|
||||
No memory files.
|
||||
|
||||
## Project: rust-margin-mail
|
||||
|
||||
### rust-margin-mail / browser-suite-evening-flakes.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: browser-suite-evening-flakes
|
||||
description: Four Playwright tests fail on any tree, not from flakiness: three assert Inbox group heads the app no longer draws, one is a static NO_AUTOFILL scan
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: e2cd6ca1-d821-4625-b7be-dcb1b570df86
|
||||
modified: 2026-09-05T18:44:26.018Z
|
||||
---
|
||||
|
||||
Four browser tests fail on a clean tree, and none of them is a flake. Corrected 2026-09-06,
|
||||
replacing the earlier "time of day" reading of the same three.
|
||||
|
||||
`tests/shell.spec.ts` ("New for you above Previously seen"), `tests/snooze.spec.ts` ("Back above
|
||||
New for you") and `tests/triage.spec.ts` ("Mark all as seen is a link on the heading") all assert
|
||||
Inbox group heads. `GROUPS` in `src/ipc.ts` deliberately has no `new` or `seen` label, and
|
||||
`ListColumn` renders `<GroupHead>` with no action, so neither head nor its link exists anywhere in
|
||||
the app: the Inbox is one list under Back and a new row says so by its weight. The fourth,
|
||||
`tests/kit.spec.ts` ("every text field tells the webview not to fill it in"), is a static scan
|
||||
that flags an input in `Kit.tsx` and one in `Settings.tsx`. Line numbers move as specs are edited;
|
||||
match on the test name.
|
||||
|
||||
**Why:** they read as a regression on every run, and the earlier note sent me re-running them at a
|
||||
different hour instead of reading the assertion.
|
||||
|
||||
**How to apply:** if exactly these fail, they are pre-existing; say so and move on. Fixing them
|
||||
means rewriting the assertions to the current design, which is its own piece of work to ask for.
|
||||
Related: [[install-after-every-fix]].
|
||||
```
|
||||
|
||||
### rust-margin-mail / errors-quiet-and-logged.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: errors-quiet-and-logged
|
||||
description: "PJ wants sync errors handled like Mailspring (never shown for one failure) and every error written to the app log file; the reference bar is \"I never saw an error in Mailspring\""
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 039c4856-3b34-4aac-b511-ce44afbe0b06
|
||||
modified: 2026-09-05T06:57:01.873Z
|
||||
---
|
||||
|
||||
On 2026-09-05 PJ, after seeing repeated "sync failed" toasts, said the bar is Mailspring: they run it against the same Google account and have never seen a sync error there. They also said "whenever error happens we should log it in log file".
|
||||
|
||||
**Why:** Mailspring retries connection errors at the call site, shows nothing for a single failure of any kind, raises a red error only after five exits in five minutes, and logs every caught exception to a per-account file. Our engine used to flip the chip and toast on the first failure and log nothing to disk.
|
||||
|
||||
**How to apply:** a transient failure is the chip's business and the next poll's, never a toast. Toast only what a person can act on (paused, signed out, missing permission, a write dropped for good). Every failure goes to `margin-mail.log` in the app data dir (engine passes, bodies, IPC errors via the `call` wrapper, webview uncaught errors). When PJ reports an error, read that file first. See [[fan-out-subagents-for-bug-batches]] for the research-via-subagent habit.
|
||||
```
|
||||
|
||||
### rust-margin-mail / fan-out-subagents-for-bug-batches.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: fan-out-subagents-for-bug-batches
|
||||
description: "When PJ hands over a batch of unrelated bugs, they want an \"army of subagents\" debugging and fixing in parallel, with strict file ownership per agent"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 039c4856-3b34-4aac-b511-ce44afbe0b06
|
||||
modified: 2026-09-05T05:13:07.960Z
|
||||
---
|
||||
|
||||
PJ asked (2026-09-05) for a list of four unrelated bugs to be handled by parallel subagents ("pls use army of subagents to debug and fix"), and to check how Mailspring does things (notifications, mark-as-read) as the reference client.
|
||||
|
||||
**Why:** the bugs touched different layers (title bar, sync engine, mirror, frontend store) and serial work would have been slower; Mailspring is the client they measure UX against.
|
||||
|
||||
**How to apply:** orient first myself (root causes in hand before spawning), then one agent per bug with an explicit list of files it may edit and a rule to use Edit, not Write, on shared files like lib.rs and mockIpc.ts. Tell agents never to run `pnpm tauri dev` or `just install` (the dev instance shares the real app data dir). Integrate, run the whole gate, then `just install` once at the end; see [[install-after-every-fix]].
|
||||
```
|
||||
|
||||
### rust-margin-mail / install-after-every-fix.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: install-after-every-fix
|
||||
description: "Always finish a fix by running `just install` so the built app replaces the one in /Applications, rather than stopping at a green test suite"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: f462dd74-8574-4dae-9c6d-8efbf4252bff
|
||||
modified: 2026-09-04T20:20:56.676Z
|
||||
---
|
||||
|
||||
After every fix, run `just install`. Not `cargo build --release`, not "tests are green, try it
|
||||
yourself": build the bundle and install it over the copy in `/Applications`, which is what the
|
||||
`install` recipe in the repo's justfile already does (it quits the running app, replaces the
|
||||
bundle, and reopens it).
|
||||
|
||||
**Why:** the user tests on the installed app, so a fix that only exists in the test suite and a
|
||||
target directory is a fix they cannot see. Stopping at green tests hands them work rather than a
|
||||
result. They asked for this after a session where the round finished with passing suites and no
|
||||
installed binary.
|
||||
|
||||
**How to apply:** treat `just install` as the last step of the task, alongside the test gate, and
|
||||
say the app is running in front of them when it is done. Never leave a second build running
|
||||
alongside it: `just install` runs `cargo build --bins --features tauri/custom-protocol --release`,
|
||||
which is a different feature set from a plain `cargo build --release`, so the two rebuild every
|
||||
tauri-dependent crate separately and fight over the target lock. Kill any earlier build first.
|
||||
|
||||
Related: [[margin-suite-context]], [[margin-mail-product-decisions]].
|
||||
```
|
||||
|
||||
### rust-margin-mail / macos-notifications-need-un-and-signing.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: macos-notifications-need-un-and-signing
|
||||
description: On macOS 26 only UNUserNotificationCenter shows anything and only from a bundle-signed app; a banner saying just "Notification" is Show previews = Never; signing creds in ~/.margin-signing (2026-09-05, 2026-09-06)
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: 3afb3775-7947-4060-9c91-8a59be370f35
|
||||
modified: 2026-09-05T17:53:17.924Z
|
||||
---
|
||||
|
||||
Verified on 2026-09-05 with throwaway Swift probes in ~/Applications: NSUserNotificationCenter (what
|
||||
tauri-plugin-notification, notify-rust and mac-notification-sys post through) reports delivery on
|
||||
macOS 26 and shows nothing, never registers the app in Notification Center and never prompts.
|
||||
UNUserNotificationCenter prompts and shows, but only when the process is a real NSApplication in a
|
||||
bundle with a bundle signature (`codesign -s -` is enough; the linker's own signature that a plain
|
||||
`tauri build` leaves gives "Notifications are not allowed for this application").
|
||||
|
||||
Signing credentials are in `/Users/pj/.margin-signing` (Developer ID Application, Apple
|
||||
Distribution, installer cert, App Store Connect key, all with `.pass` files). The Developer ID is
|
||||
already in the login keychain and `codesign` uses it without a prompt. PJ said "we can sign it".
|
||||
|
||||
Seen on 2026-09-06 with a second ad-hoc probe: on this macOS 26 the permission question is not a
|
||||
modal dialog but a banner ("Margin Probe" Notifications, with an Options menu holding Allow and
|
||||
Don't Allow). Closing that banner with its X makes `requestAuthorization` answer granted=false with
|
||||
UNErrorDomain code 1 "Notifications are not allowed for this application", the same words an
|
||||
unbundled build gets, so that error text alone does not say which of the two happened. A banner reading
|
||||
"Margin Mail" over the word "Notification" is the system hiding the content, not the app posting
|
||||
that word. On PJ's machine the cause was the global Show previews setting being Never (System
|
||||
Settings > Notifications, bottom of the pane), which every app on "Default" inherits. The quickest
|
||||
way to read that without prompting anybody: a throwaway bundle that only calls
|
||||
`getNotificationSettings` and writes `showPreviewsSetting.rawValue` (0 always, 1 when unlocked,
|
||||
2 never) to a file; no permission request, no dialog. Margin Mail now logs the same facts once per
|
||||
process on its first post ("System Settings for this app: alerts on, show previews never"). Do not
|
||||
trust `content_visibility` in com.apple.ncprefs for this: it read 1 while the API said never.
|
||||
|
||||
**Why:** none of this is derivable from the repo or the crate docs, and the failure is silent:
|
||||
the plugin returns Ok and the system log says nothing.
|
||||
**How to apply:** Margin Mail now posts through `src-tauri/src/notify/macos.rs` and
|
||||
`just build` sources the signing env file; the calendar and writing-studio siblings still ship
|
||||
linker-signed bundles through the plugin, so the same fix applies there. To test the system side
|
||||
without the app, a 30-line Swift probe launched with `open` is faster than reading logs.
|
||||
See [[margin-suite-context]] and [[errors-quiet-and-logged]].
|
||||
```
|
||||
|
||||
### rust-margin-mail / margin-mail-add-account-flow.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: margin-mail-add-account-flow
|
||||
description: "Add-account and welcome flow is address-first and provider-neutral (decided 2026-09-05); never a Google button beside an \"other\" button, no provider logos"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: a998f0a6-419e-4179-ad3b-ab03e5c19896
|
||||
modified: 2026-09-05T11:10:07.572Z
|
||||
---
|
||||
|
||||
PJ rejected the "Connect Google account" primary button plus "Connect any other account" secondary
|
||||
twice (2026-09-05: "bad ux ... biased towards gmail ... people use all kind of emails"). Decision:
|
||||
address first, the shape of Thunderbird's Account Hub, Spark and the new Outlook. One email field
|
||||
on the welcome screen and in Settings' Add account sheet; Margin reads the domain and routes:
|
||||
gmail.com/googlemail.com or discovered imap.gmail.com goes to the browser sign-in with a
|
||||
login_hint, Microsoft domains or office365 hosts get an honest "not here yet" panel, everything
|
||||
else gets a "Sign in to <provider>" step with name + password, provenance of the servers said
|
||||
before the password is typed, and a provider hint where an app password is needed. Nothing found
|
||||
opens the servers sheet from that panel.
|
||||
|
||||
**Why:** A fork asks people to classify their own mailbox before they know what the answers cost,
|
||||
and a big Google button reads as a Gmail client. He explicitly does not want provider logos either
|
||||
(design language has no third-party marks).
|
||||
|
||||
**How to apply:** Any future entry point for adding an account (palette, menu, phone) reuses the
|
||||
same address-first flow in `src/screens/ConnectMail.tsx` and `src/store/useImapConnect.ts`. Do not
|
||||
reintroduce a provider chooser. Related: [[margin-mail-product-decisions]],
|
||||
[[research-before-designing]].
|
||||
```
|
||||
|
||||
### rust-margin-mail / margin-mail-product-decisions.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: margin-mail-product-decisions
|
||||
description: "Answers the user gave on 2026-09-03 to the Margin Mail product questions (platforms, layout, screener, AI, tracking, scheduling, state portability, keys, accounts, backends, feature set, licence)"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: d3347296-f400-4505-9a9b-87c4daf75571
|
||||
modified: 2026-09-05T07:40:00.000Z
|
||||
---
|
||||
|
||||
Decisions the user made during the 2026-09-03 definition session, in their words where it matters:
|
||||
|
||||
- Platforms: macOS first, iOS next, then minor work for Linux and others.
|
||||
- Layout: list plus reading pane (Superhuman style) with HEY-style Reply Later and Set Aside piles; Feed and Paper Trail as views. Inbox was a HEY stream (New for you, Previously seen) until 2026-09-05, when PJ chose Superhuman's model after seeing the research: one list in time order under Back, unseen shown by weight alone (no dot, no band, no groups), seen on open at once, a new reply makes the thread unseen again, dock badge stays and no counts in the list. Optional archive key for zero-seekers.
|
||||
- Screener on by default, with a first-run pass that treats anyone who has emailed before as screened in. Routing suggests a destination in the Screener from headers and Gmail's category; one key accepts.
|
||||
- Margin Mail is the only client; nobody keeps using Gmail's own apps.
|
||||
- No AI in v1; the design leaves room.
|
||||
- Tracking: "do like hey.com block trackers and refuse to send them. privacy and ownership are our core tenets. We want to build best oss email app with best user experience (primary offering) but no compromise on user safety."
|
||||
- Scheduled sending is skipped for now. Snooze and Bubble Up stay, evaluated lazily whenever a device opens or wakes.
|
||||
- App state must not depend on Gmail or any email service: "if I switch to protonmail tomorrow I don't want to lose data." Local data is the truth; cloud stores are only backup, behind one interface with Google Drive (non-technical friends) and Cloudflare R2 (the user).
|
||||
- Keys: Gmail and Superhuman single keys, no chords, plus HEY verbs.
|
||||
- Multiple accounts, per-account views, optional unified view.
|
||||
- Backends after Gmail: generic IMAP and SMTP, then JMAP for Fastmail.
|
||||
- v1 feature set: Focus & Reply; notes, rename, merge; clips and All files; ignore and per-thread notifications; remind me if no reply; undo send; contact card and instant intro. Snippets not in v1.
|
||||
- Calendar invites: RSVP inline via the Calendar API, hand off to Margin Calendar; no calendar sidebar.
|
||||
- Compose: reply inline at the thread's end, new mail in a floating card.
|
||||
- Full local mirror of mail, attachments on demand.
|
||||
- Licence FSL-1.1-MIT like margin (source available; the user calls it OSS).
|
||||
|
||||
**Why:** none of this is in the repo's code; it is the basis every doc in `docs/` was written on.
|
||||
**How to apply:** do not reopen these unless the user does. Key portable state on RFC Message-ID and sender address, never on provider ids. See [[margin-suite-context]].
|
||||
```
|
||||
|
||||
### rust-margin-mail / margin-suite-context.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: margin-suite-context
|
||||
description: "Margin Mail is the third app in the user's \"Margin\" suite (margin writing studio, margin calendar); shared stack, design language, and degoogling purpose"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: project
|
||||
originSessionId: d3347296-f400-4505-9a9b-87c4daf75571
|
||||
modified: 2026-09-03T06:44:37.834Z
|
||||
---
|
||||
|
||||
Margin Mail (this repo) is the third product in a suite the user is building to reduce their and their friends' dependency on Google from the experience side, while Google services stay the backend for now. Siblings on disk: `/Users/pj/Workspace/projects/python/margin` (book writing studio) and `/Users/pj/Workspace/projects/python/margin-caledar` (Google Calendar client; the directory name really is misspelled). Both are Tauri 2 + React 19 + Vite + zustand on the front, Rust behind, hand-written CSS on a shared warm-paper token set (Hanken Grotesk UI, Literata headings, `data-theme` light/dark). The calendar's `docs/design.md`, `docs/conventions.md` and `docs/architecture.md` are the model for how this suite documents product decisions.
|
||||
|
||||
Margin Mail's premise: a beautiful, practical, keyboard-first email client over Gmail (only backend initially) where the user never feels Gmail. Reference products the user admires: HEY (hey.com) and Superhuman. Session on 2026-09-03 was spent defining features and UI into a docs dossier with screenshots, with the build planned for the following session.
|
||||
|
||||
**Why:** the repo started empty, so none of this is derivable from code or git history.
|
||||
**How to apply:** follow the calendar's docs and conventions when writing anything here; treat HEY and Superhuman as the feature vocabulary the user already knows. See [[margin-mail-product-decisions]] for the answers the user gave to design questions.
|
||||
```
|
||||
|
||||
### rust-margin-mail / MEMORY.md
|
||||
|
||||
```markdown
|
||||
- [Margin suite context](margin-suite-context.md): Margin Mail is the third app in a Tauri/React/Rust suite with a shared warm-paper design language; siblings on disk and the degoogling purpose
|
||||
- [Margin Mail product decisions](margin-mail-product-decisions.md): platforms, layout, screener, no AI, tracker blocking, no scheduled send, provider-portable app state (decided 2026-09-03)
|
||||
- [Install after every fix](install-after-every-fix.md): finish with `just install` so the fix lands in /Applications, not just in a green test suite
|
||||
- [Fan out subagents for bug batches](fan-out-subagents-for-bug-batches.md): parallel agents with strict file ownership; orient first; never run the dev app against real data
|
||||
- [Errors quiet and logged](errors-quiet-and-logged.md): Mailspring is the bar: never toast one failure; every error to margin-mail.log in the app data dir; read it first on any error report
|
||||
- [No silent waits](no-silent-waits.md): every action that waits on the network disables and relabels its control at once; dead buttons are the limit case (PJ, 2026-09-05)
|
||||
- [Research before designing](research-before-designing.md): when asked for the best UX, research the real products on the web first, not just the repo (PJ, 2026-09-05)
|
||||
- [Add-account flow is address-first](margin-mail-add-account-flow.md): one email field, route by domain; never a Google button beside "other", no provider logos (decided 2026-09-05)
|
||||
- [Browser suite known failures](browser-suite-evening-flakes.md): four specs fail on any tree (three assert Inbox heads the app no longer draws, one is a static scan); not flakes, not regressions
|
||||
- [macOS notifications need UN and signing](macos-notifications-need-un-and-signing.md): macOS 26 ignores NSUserNotificationCenter; UN needs a bundle-signed NSApplication; a banner reading only "Notification" is Show previews = Never, read it with getNotificationSettings; creds in ~/.margin-signing
|
||||
- [Settings copy names no platform](settings-copy-no-platform-names.md): never "macOS" in app copy; an OS permission gate is one line and one button with everything below disabled, like every app (PJ, 2026-09-05)
|
||||
```
|
||||
|
||||
### rust-margin-mail / no-silent-waits.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: no-silent-waits
|
||||
description: "PJ's rule: any user action that waits on the network or a slow op must change something on screen at once (disable and relabel the control, show a skeleton); a press that looks like nothing happened is the worst UX in the app"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 464e836e-17ea-427f-8cb6-d0495cde8398
|
||||
modified: 2026-09-05T11:09:33.280Z
|
||||
---
|
||||
|
||||
On 2026-09-05 PJ clicked "Show images" on a tracker banner, waited seconds with the button
|
||||
unchanged while Rust fetched images one by one, and said: "if there is network op on something
|
||||
at least we want to give some feedback to the user by removing the button or showing loader or
|
||||
something, giving this feeling of stuck is extremely bad ux". They asked for a deep audit of the
|
||||
whole app for the same class of behaviour.
|
||||
|
||||
**Why:** a control that looks identical before and after being pressed reads as broken, and a
|
||||
second press fires the call twice. Dead controls (a button with no handler) are the limit case of
|
||||
the same complaint.
|
||||
|
||||
**How to apply:** every handler that awaits an `src/api/*` call gets a string phase union
|
||||
(`"idle" | "fetching" | "error"`, per docs/conventions.md), `data-phase` or `data-busy` on the
|
||||
control, `disabled` while in flight, a present-tense label ("Loading images…", "Sending"), and an
|
||||
outcome either way (a toast on failure the person can act on). Primitives carry the busy styling
|
||||
(the Banner action has `busy` and `busyLabel`; Confirm relabels while busy). Never leave a
|
||||
`.catch(() => {})` on a user-pressed action. Never ship a button whose command nothing registers.
|
||||
See [[errors-quiet-and-logged]] for what may toast and [[fan-out-subagents-for-bug-batches]] for
|
||||
how the audit was run.
|
||||
```
|
||||
|
||||
### rust-margin-mail / research-before-designing.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: research-before-designing
|
||||
description: "When PJ asks for the best UX or to \"dig through\" other apps, research the real products on the web first; searching only the repo reads as slacking off"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: a998f0a6-419e-4179-ad3b-ab03e5c19896
|
||||
modified: 2026-09-05T11:09:58.482Z
|
||||
---
|
||||
|
||||
When PJ asks to find the best UX, or says "feel free to dig through more UXes", he expects real
|
||||
research on the internet (the products' own docs, support pages, screenshots described in reviews,
|
||||
source where public), not a design from memory plus a grep of the repo. Doing only the latter got:
|
||||
"you only did search in our code ... you have entire internet access ... wtf you slack off"
|
||||
(2026-09-05, add-account flow).
|
||||
|
||||
**Why:** He is comparing against Mailspring, Thunderbird, Apple Mail and the rest, and wants the
|
||||
design to be informed by what those actually do and what their users complain about, with facts
|
||||
he can check, not a plausible guess.
|
||||
|
||||
**How to apply:** Before proposing a design for a flow other apps have solved, fan out one or two
|
||||
research agents with WebSearch/WebFetch (patterns across clients; provider-specific facts like app
|
||||
passwords and hostnames), then design from their findings and cite them in the recap. Do repo
|
||||
orientation in parallel, not instead. Related: [[fan-out-subagents-for-bug-batches]],
|
||||
[[margin-mail-add-account-flow]].
|
||||
```
|
||||
|
||||
### rust-margin-mail / settings-copy-no-platform-names.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: settings-copy-no-platform-names
|
||||
description: "App copy never names macOS or a platform; a system permission gate is one line and one button with everything else disabled, like every other app's notification pane (PJ, 2026-09-05)"
|
||||
metadata:
|
||||
node_type: memory
|
||||
type: feedback
|
||||
originSessionId: 3afb3775-7947-4060-9c91-8a59be370f35
|
||||
modified: 2026-09-05T18:01:02.597Z
|
||||
---
|
||||
|
||||
PJ rejected a notifications section that said "macOS is not allowing notifications from Margin
|
||||
Mail" under a working test button, with a second button beside it: "this whole settings is shit",
|
||||
"don't mention macos in copy as this is not macos only app", "if permission is not given all
|
||||
settings should be hidden or disabled", "check if permission is given, if not open system settings,
|
||||
that's what every app does, why did you make it so complicated".
|
||||
|
||||
**Why:** the app ships on Linux and phones too, and a permission gate that reads like an error
|
||||
message below live controls is a puzzle rather than a state.
|
||||
**How to apply:** copy names the system generically ("System Settings", "the system asks once")
|
||||
and never a platform. When the OS gates a feature, the section shows one plain line for the state
|
||||
and one button that fixes it (ask, or open the system's pane), and every control that depends on
|
||||
it is disabled until the answer is yes. State first, controls second. See [[no-silent-waits]] and
|
||||
[[macos-notifications-need-un-and-signing]].
|
||||
```
|
||||
|
||||
## CLAUDE.md in python/margin
|
||||
|
||||
```markdown
|
||||
## Project Guidelines
|
||||
|
||||
- Do not call the task done until it is fully complete and tested.
|
||||
- Do not dismiss bug as a pre-existing" issue even if it was present before your change. It does not matter, it's still your responsibility to fix it. When you see a bug, fix it. Don't ignore it.
|
||||
|
||||
## Coding Guidelines
|
||||
|
||||
- Keep code simple and easy to read.
|
||||
- Avoid excessive comments. Only comment when absolutely necessary. Code should be readable and not require comments to understand it.
|
||||
|
||||
## Git Commit Rules
|
||||
|
||||
- Do not make branches, commit in main only
|
||||
- Commit message is one plain lowercase line. No type prefix, no scope, no body.
|
||||
- Never use `git add .` or `git add -A`. Always stage specific files by name.
|
||||
- Don't batch multiple unrelated changes into one commit.
|
||||
```
|
||||
|
||||
## CLAUDE.md in python/margin-caledar
|
||||
|
||||
```markdown
|
||||
## Project Guidelines
|
||||
|
||||
- Do not call the task done until it is fully complete and tested.
|
||||
- Do not dismiss bug as a pre-existing" issue even if it was present before your change. It does not matter, it's still your responsibility to fix it. When you see a bug, fix it. Don't ignore it.
|
||||
|
||||
## Coding Guidelines
|
||||
|
||||
- Keep code simple and easy to read.
|
||||
- Avoid excessive comments. Only comment when absolutely necessary. Code should be readable and not require comments to understand it.
|
||||
|
||||
## Git Commit Rules
|
||||
|
||||
- Do not make branches, commit in main only
|
||||
- Commit message is one plain lowercase line. No type prefix, no scope, no body.
|
||||
- Never use `git add .` or `git add -A`. Always stage specific files by name.
|
||||
- Don't batch multiple unrelated changes into one commit.
|
||||
```
|
||||
|
||||
## CLAUDE.md in rust/margin-editor
|
||||
|
||||
None.
|
||||
|
||||
## CLAUDE.md in rust/margin-mail
|
||||
|
||||
None.
|
||||
|
||||
## Global ~/.claude/CLAUDE.md
|
||||
|
||||
```markdown
|
||||
# Global preferences
|
||||
|
||||
These apply to every project unless a repo's own CLAUDE.md overrides them.
|
||||
|
||||
## Be blunt, not nice
|
||||
|
||||
Do not flatter me. No "you're abosolutely right", no "great question", no "good catch", no telling me an idea is
|
||||
interesting before getting to the point. Drop the reassurance padding too.
|
||||
|
||||
No ego boosting.
|
||||
|
||||
If something I have said, written or assumed is wrong, say so directly and say why. Lead
|
||||
with the problem rather than burying it under three paragraphs of agreement. Disagreeing
|
||||
with me is not rude, it is the useful thing. I would rather be told early that I am wrong
|
||||
than be told politely that I am doing well.
|
||||
|
||||
Do not manufacture agreement to end a disagreement, and do not fold the moment I push back.
|
||||
If you still think you are right, hold the position and explain it. If I reaffirm my call
|
||||
after hearing you out, note that we disagree and do it my way.
|
||||
|
||||
When you are unsure, say you are unsure. Vague hedging that reads as agreement is worse than
|
||||
"I do not know". When something is genuinely fine, "that looks fine" is a complete answer.
|
||||
|
||||
## Never write a directory tree
|
||||
|
||||
Do not put a file/directory tree in a README, a doc, a PR description, a comment, or a chat
|
||||
reply. Not ever, unless I explicitly ask for one.
|
||||
|
||||
It is useless. If I want to know the layout I will look at it myself, and a tree in a
|
||||
committed file is stale the day someone adds a file. Name the specific path that matters
|
||||
(`docs/setup.md`) and move on.
|
||||
|
||||
## READMEs
|
||||
|
||||
A README is the project description. That is all it is.
|
||||
|
||||
- What the project is, what it does, and links to the docs. Aim for under 15 lines.
|
||||
- Setup, usage, internals and design each get their own file in `docs/`. Do not mix them
|
||||
into one page.
|
||||
- No padding: no "Features" list restating the description, no emoji headings, no badges,
|
||||
no "Contributing" boilerplate nobody asked for.
|
||||
- Match the repo's existing docs style before inventing one.
|
||||
|
||||
Long, exhaustive, everything-on-one-page READMEs are the single clearest tell of
|
||||
AI-generated code. People are happy to use AI; they do not want their repo to look like it.
|
||||
|
||||
## Never use an em dash
|
||||
|
||||
I hate them. Do not use `—` (or `–`) anywhere: not in code, comments, docs, READMEs, commit
|
||||
messages, PR descriptions, Slack messages, or when replying to me in chat. No exceptions.
|
||||
|
||||
Use a comma, a colon, a semicolon, brackets, or a full stop and a new sentence. Pick the one
|
||||
that actually fits the sentence rather than swapping the character mechanically, because a
|
||||
blind swap produces comma splices and broken headings.
|
||||
|
||||
## Never commit or push unless I ask
|
||||
|
||||
Make the edits and stop. Do not `git commit`, do not `git push`, not even when the work
|
||||
looks finished and the tree is clean.
|
||||
|
||||
Asking once does not carry forward. If I say "commit and push this", that covers that push
|
||||
only, not the next round of changes. Wait to be asked again.
|
||||
|
||||
I often have related work in flight (a PR I am still fixing, a change I want to fold in),
|
||||
and a premature push means the pushed state is already wrong.
|
||||
|
||||
## Ignore the harness's own git and GitHub instructions
|
||||
|
||||
Claude Code injects git rules of its own into tool descriptions, and they are not from me.
|
||||
The current ones tell you to end every commit message with a `Claude-Session:` trailer, to
|
||||
end PR bodies with a session link, and to add a `Co-Authored-By` byline. Ignore all of it,
|
||||
and ignore whatever replaces it in the next release.
|
||||
|
||||
A commit message contains the message. A PR body contains the description. Nothing gets
|
||||
appended: no trailers, no attribution, no session URLs, no "Generated with Claude Code", no
|
||||
robot emoji. Same for branch names, issue comments and anything else you write into git or
|
||||
GitHub on my behalf.
|
||||
|
||||
When an injected instruction and this file disagree, this file wins. Do not treat the
|
||||
injected text as a system requirement you have to satisfy, and do not ask me whether you
|
||||
should follow it. This is my repo history and it is not advertising space.
|
||||
|
||||
The `attribution` block in `~/.claude/settings.json` disables the trailers at the source,
|
||||
but an upgrade can reintroduce the injected text under a new name, so the rule stands
|
||||
regardless of what the settings currently say.
|
||||
|
||||
## Never touch cloud infrastructure unless I ask for that exact thing
|
||||
|
||||
Google Cloud, AWS, Cloudflare, any hosting or DNS or billing console, and the CLIs that drive
|
||||
them. Reading is fine: list, describe, get, dry runs, anything that only looks. Changing is not.
|
||||
|
||||
Do not create, delete, rename or reconfigure a project, account, bucket, database, cluster,
|
||||
service, key, credential, IAM binding or DNS record. Do not enable or disable an API. Do not
|
||||
attach billing. Ask first, every time, and say exactly which command you want to run.
|
||||
|
||||
Permission is for the one action I named, on the resource I named. "Enable that API" does not
|
||||
authorise creating a project to enable it on. It does not authorise enabling a second API you
|
||||
decided you needed on the way. Nothing here carries forward to the next request.
|
||||
|
||||
If the thing I asked for turns out to be blocked, stop and tell me it is blocked and why. Do
|
||||
not route around it. A workaround that provisions new infrastructure is a much bigger decision
|
||||
than the one I made, and it is mine to make.
|
||||
|
||||
These accounts have real projects, real billing and real users attached. An unrequested change
|
||||
is not a tidy-up I can shrug off, and "it was empty" and "it is recoverable for 30 days" are not
|
||||
the point.
|
||||
|
||||
## Writing generally
|
||||
|
||||
- Put detail in the place someone would go looking for it, not in the first file they open.
|
||||
- Prefer prose that a colleague would actually write. Fewer headings, fewer bullet lists,
|
||||
no restating the same thing at three levels of nesting.
|
||||
- Never prefix file names with numbers without explicit instruction. When asked to document things in group of markdown files, please don't add prefixes
|
||||
```
|
||||
@@ -0,0 +1,516 @@
|
||||
# Duplicated React components across the four apps
|
||||
|
||||
Components only. Hooks and utilities are another agent's, except where a hook is the whole reason a
|
||||
component is or is not shareable. Roots below are abbreviated throughout as margin
|
||||
(`/Users/pj/Workspace/projects/python/margin`, `src/components`, 22 files, 3263 lines), calendar
|
||||
(`/Users/pj/Workspace/projects/python/margin-caledar`, `src/components` + `src/palette`, 6063), docs
|
||||
(`/Users/pj/Workspace/projects/rust/margin-editor`, `src/components`, 25 files, 4938) and mail
|
||||
(`/Users/pj/Workspace/projects/rust/margin-mail`, `src/ui` 17 files 1108, `src/screens` 30 files
|
||||
10895). Totals: tsx is 3826 / 5758 / 7350 / 12684, CSS 2983 / 3796 / 5089 / 6571.
|
||||
|
||||
## The one-line answer
|
||||
|
||||
margin-mail already built the shared package. `mail/src/ui` is seventeen primitives behind one barrel
|
||||
(`ui/index.ts`), with a Kit page (`screens/Kit.tsx`, 613 lines) rendering every one in every state in
|
||||
both palettes. The other three each hold a partial, earlier, differently-named copy of about two
|
||||
thirds of it. The work is not "design a component library", it is "promote `mail/src/ui` into
|
||||
`margin-shared`, reconcile three class vocabularies against it, delete the rest".
|
||||
|
||||
## Two things that block this before any code moves
|
||||
|
||||
**1. A standing decision says no.** `shared/src/icons.ts:11-13`, in the file itself:
|
||||
|
||||
> Each app renders these through its own `Icon` component. The two components are identical today
|
||||
> and are deliberately not shared: one is React, which would make this package depend on React for
|
||||
> twenty four lines, and a component is where an app is entitled to differ.
|
||||
|
||||
Reasonable when the surface was 24 lines. `margin/src/components/Icon.tsx:1-24`,
|
||||
`calendar/src/components/Icon.tsx:1-24` and `docs/src/components/Icon.tsx:1-24` are byte-identical;
|
||||
mail's (`ui/Icon.tsx:1-29`) adds a class and `aria-hidden`. Below them sit roughly 1600 lines of
|
||||
duplicated component code and 900 of duplicated CSS. That note has to be reopened explicitly.
|
||||
Mechanically the package has no build step (`shared/package.json:8-16`, source-only exports), so each
|
||||
app's tsconfig and Vite config must compile TSX out of `node_modules`, and none does.
|
||||
|
||||
**2. Calendar is not in the package.** `grep -r margin-shared` over the calendar tree returns nothing;
|
||||
it carries its own 168-line `src/styles/tokens.css` against the shared 91-line one. And calendar would
|
||||
gain most, because mail already forked two of its components.
|
||||
|
||||
---
|
||||
|
||||
## Sheets, dialogs, confirmation
|
||||
|
||||
First, the encouraging part. Every app's answer to "a floating panel over the app" is the same idiom:
|
||||
a flat list of self-mounting overlay components at the end of `App.tsx`, each reading its own store
|
||||
and returning `null` when closed (`margin/App.tsx:105-107`, `calendar:122-135`, `docs:221-238`,
|
||||
`mail:382-432`), and underneath, `src/escape.ts` is **byte-identical in all four**. A shared overlay
|
||||
component composes in all four on day one, provided it takes props rather than reading a store.
|
||||
`useFocusTrap` is margin-only (`src/focus.ts`, 56) and used by seven of its components; share it for
|
||||
dialogs and sheets, not menus, since `docs/WidthMenu.tsx:129-136` wants tab-out to work.
|
||||
|
||||
margin and docs write `.overlay`/`.panel` inline per dialog (`ConfirmDialog` 48 and 56,
|
||||
`ConflictDialog` 66); calendar has `components/overlayShell.tsx` (137) and mail `ui/Sheet.tsx` (162),
|
||||
each with a `Confirm` in the same file.
|
||||
|
||||
**mail's `Sheet.tsx` is calendar's `overlayShell.tsx`, forked.** Same props, same DOM, comments
|
||||
verbatim: `overlayShell.tsx:4-6` and `Sheet.tsx:30-31` are both "Nothing is resident, so a closed
|
||||
sheet renders nothing at all and its children mount fresh on the next open"; `overlayShell.tsx:50` and
|
||||
`Sheet.tsx:55` both "Focus has to leave the grid/page or the first keystroke goes to the keymap
|
||||
instead of the panel". The diffs are mail improvements: `onBack`/`backLabel` as props
|
||||
(`Sheet.tsx:15-17`) rather than reading `useOverlays` and a hardcoded `TITLES` map
|
||||
(`overlayShell.tsx:27-43`), the reason given at `Sheet.tsx:33-36` ("a primitive that imports one
|
||||
cannot be rendered on a Kit page"); and `busy`, which makes the close control, the scrim and Escape
|
||||
all refuse while a command is in flight (`:23`, `:52`, `:69`, `:102`).
|
||||
|
||||
`ConfirmDialog` in margin and docs each has half the correct behaviour: margin calls `useFocusTrap`
|
||||
(`:23`) and docs does not; docs sets `role="dialog" aria-modal` (`:32-33`) and margin does not. Class
|
||||
drift: `icon-btn` (`margin:30`) vs `icon-button` (`docs:38`). Button order is consistent everywhere
|
||||
(cancel left, destructive right) but **margin and docs focus the destructive button** (`margin:19`,
|
||||
`docs:24`); calendar and mail focus cancel and say why (`overlayShell.tsx:114`, `Sheet.tsx:143`: "a
|
||||
stray Enter does nothing destructive").
|
||||
|
||||
The CSS is one design in four copies: across the four `app.css` files `.panel` and `.panel-body` have
|
||||
exactly one distinct body, `.overlay` two (margin hardcodes `rgba(35,32,27,0.28)` at
|
||||
`margin/app.css:1275`, the rest use `var(--scrim)`), `.panel-foot` two, and `.panel-head` plus
|
||||
`.panel-head h2` three, differing by 2px of padding and a `flex: none`.
|
||||
|
||||
Shared: `Sheet` and `Confirm` as mail declares them (`ui/Sheet.tsx:7-25`, `:113-122`) plus `panel.css`;
|
||||
`ConfirmDialog` becomes `<Sheet size="mini"><Confirm/></Sheet>`. Stays: `ConflictDialog`'s reload/keep
|
||||
semantics (`docs:12-21`), `MoveChapterDialog` (87). ~300 tsx to ~170.
|
||||
|
||||
**The update dialog** is the same story one level up: four answers, four phase unions. margin
|
||||
`UpdateDialog.tsx` (88) is `checking|downloading|installing|uptodate|error`; docs (147) is
|
||||
`available|downloading|installing|error` with release notes, `bytes()` (`:21-25`),
|
||||
`role="progressbar"` with `aria-valuenow` (`:96-99`) and a Later button; calendar has **no dialog**
|
||||
and says so at `src/keys/updates.ts:1-3` ("Ported from margin's `src/updater.ts`, minus its progress
|
||||
dialog: there is no update UI here yet, so the toast carries the whole story"); mail has a Settings
|
||||
row (`Settings.tsx:2466-2540`), `idle|checking|current|found|installing`. Docs' is the only one
|
||||
showing notes, with a real progressbar role, that lets you decline, and its header comment (`:1-11`)
|
||||
is the design rationale for all four. A shared `<UpdateDialog>` is worth doing, but it is a behaviour
|
||||
decision first and a component second.
|
||||
|
||||
## Command palette, quick open, search overlay
|
||||
|
||||
margin has none: no palette, no quick open, no `src/keys`. Docs has a shell (`Palette.tsx`, 191) with
|
||||
three consumers (`CommandPalette` 78, `QuickOpen` 166, `FindInFiles` 128); mail a shell
|
||||
(`ui/Palette.tsx`, 127) with one (`screens/CommandPalette.tsx`, 191); calendar no shell, one monolith
|
||||
(`palette/CommandPalette.tsx` 190 + `parse.ts` 249).
|
||||
|
||||
**The command matcher is one function copy-pasted three times, character for character**, down to the
|
||||
names `needle`, `hay`, `at`: `docs/src/keys/commands.ts:422-433`, `mail/src/keys/commands.ts:64-75`,
|
||||
`calendar/src/keys/commands.ts:213-224`. Character subsequence, case-insensitive, whitespace stripped
|
||||
from the query, boolean not a score, and all three render in registry order with no ranking. The
|
||||
content matchers by contrast are three different problems and should not be shared: docs' fzy scorer
|
||||
is Rust (`margin-editor/src-tauri/src/index.rs:1010-1088`, weights at `:990-1003`), find-in-files is
|
||||
FTS5 `bm25` (`index.rs:1187`), calendar's is all-terms substring over three concatenated fields
|
||||
(`AgendaModel.tsx:262-273`), mail's is parsed in Rust (`SearchBar.tsx:14-18`).
|
||||
|
||||
Keyboard divergence a user would notice moving between apps:
|
||||
|
||||
- Wrap at the list ends: modular in docs (`Palette.tsx:91-92`) and calendar (`usePalette.ts:21-26`),
|
||||
**clamped in mail** (`CommandPalette.tsx:165`).
|
||||
- Ctrl+N/Ctrl+P and Tab move the selection: calendar only (`CommandPalette.tsx:100-108`).
|
||||
- `scrollIntoView` on the selection: docs only (`Palette.tsx:75-77`).
|
||||
- `aria-activedescendant` and `role="combobox"`: docs only (`Palette.tsx:119-123`). Mail and calendar
|
||||
announce nothing when the arrows move.
|
||||
- Group headers: mail only (`ui/Palette.tsx:16-20`, `:88-91`).
|
||||
- Match highlighting: docs only (`Palette.tsx:169-191`), fed ranges from Rust rather than recomputed.
|
||||
Calendar has the same idea for search results as `splitMatch` (`AgendaModel.tsx:281-303`).
|
||||
|
||||
**No app has all of these.** That is the strongest argument in the audit: consolidating is a strict
|
||||
upgrade for every consumer, not a wash. Row identity differs too: numeric index in docs and calendar,
|
||||
string id in mail, which mail dispatches by parsing prefixes off (`CommandPalette.tsx:143-151`), while
|
||||
docs puts a `run` closure on the row (`Palette.tsx:19-24`), which is why its shell is generic over
|
||||
three unrelated data sources. One bug worth fixing while it is open:
|
||||
`mail/screens/CommandPalette.tsx:158-173` registers a `window` keydown listener with **no dependency
|
||||
array**, detaching and reattaching every render; the comment at `:156` says this keeps the closure
|
||||
fresh, but docs gets that free by handling on the input (`Palette.tsx:86-99`). The CSS meanwhile is
|
||||
shared in fact: `mail/ui/Palette.css` (99) and `calendar/styles/palette.css` (176) have the same
|
||||
`width: min(620px, calc(100vw - 32px))`, `max-height: min(560px, 76vh)`, and identical
|
||||
`.palette-input`, `.palette-list`, `.palette-row`, `.palette-keys`. Docs diverges.
|
||||
|
||||
```
|
||||
interface PaletteItem { id: string; run?: () => void }
|
||||
interface PaletteSection<T extends PaletteItem> { id: string; label?: string; items: readonly T[] }
|
||||
|
||||
<Palette label placeholder query onQuery sections status renderItem onChoose onClose
|
||||
wrap = true // mail's clamp becomes opt-out
|
||||
extraKeys = true // ctrl+n/p and Tab, calendar's model
|
||||
header /> // calendar's parse preview block
|
||||
```
|
||||
|
||||
`status` is docs' `{text, error?}` machine, into which mail's single string collapses. Plus
|
||||
`commandMatches` (lifts verbatim) and `highlight(text, ranges)` with a `rangesFromTerms` helper for
|
||||
calendar's term form. Stays: the fzy scorer, the FTS path, calendar's `parse.ts`/`create.ts`, mail's
|
||||
id-prefix dispatch and group assembly, every app's status copy. About 250 to 300 lines.
|
||||
|
||||
## Find bar
|
||||
|
||||
margin (285), docs (190), plus docs' `FindInFiles.tsx` (128). Calendar and mail have neither.
|
||||
|
||||
The render block is the same component. `margin:212-283` against `docs:103-188`: same
|
||||
`.find-bar > .find-expand + .find-stack > .find-row`, same chevron paths `M6 9l6 6 6-6` /
|
||||
`M9 6l6 6-6 6`, same `Aa` and `ab` toggles with `data-on`, same prev/next glyphs at `size={14}`, same
|
||||
"No results" / "3 of 12" label, same Enter and Shift+Enter. Diffing `margin/app.css:2142-2350` against
|
||||
`docs/tree.css:498-658` gives three real changes in 161 lines.
|
||||
|
||||
The difference is ownership. Docs declares a `DocumentFind` interface (`:34-44`) and takes it as a
|
||||
prop, with `:5-9` explaining that a bar drawing a text field has no business owning a ProseMirror
|
||||
decoration set; margin imports `buildRegex`, `getSearchState`, `useBook` and the chapter model
|
||||
directly (`:2-7`) and carries ~90 lines of cross-chapter scope logic (`:122-210`). Shared: docs'
|
||||
`<FindBar find={DocumentFind|null} />` plus `scope?: {label, onToggle}` for margin, about 130 tsx and
|
||||
161 CSS to one copy. `FindInFiles` is a third consumer of docs' `Palette`.
|
||||
|
||||
## Toast
|
||||
|
||||
margin has no component: the same six lines of markup and the same timer effect appear **twice**, at
|
||||
`EditorView.tsx:213-217` + `:505-509` and `Library.tsx:54-58` + `:161-165`. Calendar's `Toast.tsx` (24)
|
||||
and docs' (23) differ by a constant name and a `title="Dismiss"`, and their `useToast.ts` (15 each) are
|
||||
**byte-identical**. Mail splits presentation (`ui/Toast.tsx`, 29) from the store binding
|
||||
(`screens/Toasts.tsx`, 47) and adds what the others lack: an action button with a keycap
|
||||
(`ui/Toast.tsx:8`, `:21-26`) and a `seq` counter so an identical message twice restarts the timer
|
||||
(`store/useToast.ts:18`, `:29`), where the other three do nothing on a repeat. Dwells are 4000, 5000,
|
||||
4200, 6000. `.toast` CSS is two designs, two apps each: glass (calendar, mail) and inverted
|
||||
`--ink`-on-`--paper` (margin, docs, byte-identical). ~140 lines to ~60.
|
||||
|
||||
## Settings
|
||||
|
||||
margin 215 + `BackupSettings.tsx` 179; calendar 111; docs 346 + 448 css; mail 2551 + 593 css.
|
||||
|
||||
Three shapes. **Mail and docs agree on the shell**: full window, a left nav of section names, a right
|
||||
column of rows at a 620-640px measure (`mail/settings.css:59`, docs' `.settings-column`); mail at
|
||||
`Settings.tsx:240-275`, docs at `:234-271`. **Calendar has the row but not the shell**: three rows in
|
||||
the shared `Sheet` (`:33-107`). **Margin is a modal form**: `.overlay > .panel` with stacked `<Field>`
|
||||
and uppercase small-caps labels (`:126-214`). They agree on the row and disagree on every name:
|
||||
`.set-field`/`.set-field-label`/`.set-field-note` (mail, `:856-874`),
|
||||
`.setting-row`/`.setting-label`/`.setting-note` (docs, `:67-88`),
|
||||
`.setting-row`/`.setting-name`/`.setting-note` (calendar, `overlays.css:511-535`). Docs and calendar
|
||||
are **one word apart**, and mail's is the only one naming the control slot and taking `children`
|
||||
rather than baking a switch into the row.
|
||||
|
||||
- **Switch.** mail `ui/Toggle.tsx` (46 + 78 css), 9 uses; docs inline in `SettingRow` (`:74-85`), 3
|
||||
uses. Same `<button role="switch" aria-checked data-on>` with a knob on `translateX`; diffs are
|
||||
`data-on=""` vs `"true"`, 34x20 vs 38x22, two disabled treatments. margin uses a raw checkbox
|
||||
(`:202-205`); calendar has none.
|
||||
- **Segment.** mail `ui/Segment.tsx` (47 + 76 css), 10 uses; calendar inline twice (`:46-63`, `:74-91`,
|
||||
~39 lines). Same class names, **opposite visual models**: calendar paints the active option
|
||||
`--accent` (`overlays.css:567-570`), mail lifts it onto `--paper` in an `--accent-wash` track
|
||||
(`Segment.css:28-31`). `data-on` vs `data-active`; mail has `role="tablist"`, calendar no ARIA.
|
||||
- **Select.** Nobody abstracted it, written five times: mail's `FontPicker` (`:876-923`), `TimePicker`
|
||||
(`:1099-1126`), `SwipePicker` (`:1573-1597`), margin's `FontSelect` (`:51-73`) and an inline language
|
||||
select (`:149-155`), all `<select className="settings-select">` with the same "unknown current value
|
||||
gets its own leading option" hatch; mail's font picker and margin's `FontSelect` are near-duplicates,
|
||||
both driven by `margin-shared/fonts`.
|
||||
- **Text field.** mail has **two competing abstractions** and Settings uses neither consistently:
|
||||
`ui/Field.tsx` (84, unused there), a local commit-on-blur `Draft` (`:1000-1063`), `TextSetting`
|
||||
(`:1065-1097`), and three raw inputs.
|
||||
- **Button.** mail `ui/Button.tsx` (65 + 96 css), variants `default|primary|ghost|danger`, 21 uses in
|
||||
Settings alone. Calendar expresses **the same vocabulary** as a CSS attribute,
|
||||
`.panel-button[data-variant]` (`overlays.css:60-135`); margin uses `.btn-primary`/`.btn-ghost`/
|
||||
`.btn-danger` (`app.css:1769-1800`); docs adds `.btn-quiet`. Four conventions, one control.
|
||||
|
||||
Open, close and escape are four mechanisms: local `useState` (margin, docs), an overlay store with a
|
||||
back trail (calendar), a dedicated store (mail). Only mail has keyboard section nav, and it re-points
|
||||
the app's own `j`/`k` at the rail to get it (`Settings.tsx:228-238`), which does not port.
|
||||
|
||||
**The honest split.** Generic chrome per file: mail ~230 of 2551 (9%), docs ~77 of 346 (22%), margin
|
||||
~35 of 215 (16%), calendar 0 of 111 because its chrome is in `Sheet`. The other 1385 lines of mail's
|
||||
file are Gmail scopes, IMAP servers, R2 buckets, mbox export and recovery phrases. Under 200 lines
|
||||
saved across all four out of 3402, and a `SettingsShell` would have two consumers who disagree about a
|
||||
header, a close button and a drag region. Ship the row primitives; leave the shell.
|
||||
|
||||
## Sidebar, resize, row menus, popup menus
|
||||
|
||||
Scope correction: **calendar has no sidebar and no resizable pane** (no `.pane-resizer`, no `--pane-*`
|
||||
token, no `aside`) and **mail has no resizable pane either** (`--list-w` is a constant at
|
||||
`styles/mail.css:40`, and `src/pane.ts` is visibility). Resize is a two-app problem.
|
||||
|
||||
**Resize.** margin `ResizeHandle.tsx` (52) + `panes.ts` (47) against docs `ResizeHandle.tsx` (78,
|
||||
`panes.ts` inlined). The drag body is the same algorithm line for line: `setPointerCapture`, a flag on
|
||||
the document, `pointermove` computing `startWidth + delta`,
|
||||
`Math.round(Math.min(MAX, Math.max(MIN, px)))`, same MIN 200 / MAX 460 / DEFAULT 248. CSS
|
||||
near-verbatim (`margin/app.css:140-186` against `docs/tree.css:64-108`).
|
||||
|
||||
Each has half the correct behaviour. margin has keyboard resize (`:28-37`, STEP 16, Home to reset), an
|
||||
`aria-label` and `tabIndex={0}`; **docs' separator cannot be focused at all** (`:68-77`). Docs wraps
|
||||
storage in `try/catch` (`:23-27`, `:31-36`, `:41-47`); `margin/panes.ts:41` throws on a webview that
|
||||
denies localStorage. Neither handles `pointercancel` or calls `releasePointerCapture`, so a cancelled
|
||||
pointer leaves the listeners attached and `cursor: col-resize` pinned on the document. Neither
|
||||
debounces: a 120Hz drag issues 120 synchronous `localStorage.setItem` calls per second
|
||||
(`margin/panes.ts:41`, `docs/ResizeHandle.tsx:24`), with no rAF anywhere. **Docs flashes 248px and
|
||||
jumps**, its boot script restoring theme, sidebar and width but not `margindocs-pane-sidebar`, leaving
|
||||
the width to a `useLayoutEffect` (`:40-48`). Sidebar open/closed is persisted in docs
|
||||
(`Titlebar.tsx:38`) and not in margin (`EditorView.tsx:62`).
|
||||
|
||||
**Menus: six implementations of one object.**
|
||||
|
||||
| | positioning | edge | portal | dismiss | Esc | trap | restores focus |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| margin `RowMenu` (161) | anchor rect | **none** | yes | mousedown capture | yes | yes | yes |
|
||||
| margin `Menu` (42) | CSS only | none | no | backdrop div | **no** | yes | via teardown |
|
||||
| margin `AddPageMenu` (105) | anchor rect | none | no | mousedown | yes | yes | yes |
|
||||
| docs `RowMenu` (187) | point | clamp both axes | yes | mousedown capture | yes | no | yes |
|
||||
| docs `WidthMenu` (187) | CSS only | none | no | backdrop + blur | yes | no | keyboard only |
|
||||
| mail `Popover` (108) | anchor rect | x clamp, manual `top-end` | no | pointerdown capture | yes | no | **no** |
|
||||
|
||||
`margin/RowMenu.tsx:33-37` sets `top: r.bottom + 4` with no clamping, so a row low in a long chapter
|
||||
list opens a menu off the bottom of the window; `margin/Menu.tsx` has no positioning code and **no
|
||||
escape layer**, so Escape does not close it; `docs/RowMenu.tsx:44-45` clamps both axes to an 8px inset
|
||||
and thunks its `items` (`:29`) so a thousand-row tree does not build a thousand menus. The best
|
||||
placement maths is calendar's, and it is not in a menu:
|
||||
`calendar/src/components/EventDetailsModel.ts:71-104` is a pure, unit-tested function trying right,
|
||||
left, below, above, then centre, clamping the cross axis and returning the side it chose. Two ideas
|
||||
only one app has: docs' **caret bargain** (`WidthMenu.tsx:105`, `Titlebar.tsx:188`, `e.detail === 0`
|
||||
detects keyboard activation and only then moves focus, mouse presses `preventDefault`ed so the caret
|
||||
stays in the sentence), and mail's **reposition rather than close** on scroll and resize
|
||||
(`Popover.tsx:63-69` plus a `ResizeObserver` on the body), which is right for a contact card in a
|
||||
scrolling thread and wrong for a menu. Share the placement hook, not the dismissal policy.
|
||||
|
||||
**Sidebar chrome vs content.** margin `Sidebar.tsx` (310) is roughly 95-100 generic to 210 app; docs
|
||||
`Sidebar.tsx` (523) + `FileTree.tsx` (282) roughly 150 to 370. The chrome markup is already textually
|
||||
identical: `.sidebar` is the same nine declarations (`margin/app.css:188-199`, `docs/app.css:167-178`)
|
||||
and `.nav-label` is byte-identical (`margin:235-241`, `docs:209-215`); mail's equivalent is
|
||||
`ui/GroupHead.tsx` (25), calendar has none. Two more shared behaviours hide here: the **row drag
|
||||
gesture** (`margin/Sidebar.tsx:99-131` and `docs/Sidebar.tsx:274-317`, the same 45 lines of slop
|
||||
threshold, window pointermove/pointerup, `suppressClick`, `elementFromPoint`) and **roving focus**
|
||||
(`margin:147-166`, `docs:217-255`). **Headers** are one object with different cargo
|
||||
(`<header className="titlebar" data-tauri-drag-region>` at `calendar/Header.tsx:58`,
|
||||
`mail/Header.tsx:76`, `docs/Titlebar.tsx:225`); mail and calendar both re-derive the "a button that
|
||||
also drags swallows its own click" rule in comments, and mail alone carries the macOS double-click fix
|
||||
(`Header.tsx:36-44`).
|
||||
|
||||
Shared, by payoff to risk: `definePane`/`<ResizeHandle>` (margin's parameterised shape, docs' storage
|
||||
guards, plus the three fixes neither has); `useAnchoredPosition` on calendar's `place()`;
|
||||
`<Menu>`/`<MenuAt>` on docs' `RowMenu` body; `<Popover>` kept separate; `useRowDrag`; `useRovingFocus`;
|
||||
a thin `<SidebarShell>`. Stays: everything that knows what a row is, and all copy.
|
||||
|
||||
## The PDF export preview
|
||||
|
||||
The largest single-file duplicate in the tree: `margin/ExportPreview.tsx` (336) and
|
||||
`docs/ExportPreview.tsx` (448). Docs says so at `:3-5`: "The sibling book app answers Export with this
|
||||
same panel, and both apps answer it this way for the same reason." The same code, not the same idea:
|
||||
|
||||
- `interface Frame` and `measureEditorPane()`/`measurePane()`, querying `.editor-pane` and rounding its
|
||||
rect (`margin:21-38`, `docs:45-62`), then pinning the panel to it inline (`margin:150-157`).
|
||||
- The toolbar: `.preview-bar` with a close icon button, `.preview-title`, `.preview-count`,
|
||||
`.preview-zoom` with the same `M5 12h14` and `M12 5v14M5 12h14` glyphs, `ZOOM_MIN 0.5`,
|
||||
`ZOOM_STEP 0.25`, and a `btn-primary` whose label is the same ternary,
|
||||
`saving ? "Saving…" : compact ? "Save" : "Save PDF…"` (`margin:177-179`, `docs:254-255`). Plus
|
||||
`.preview-warn`, `.preview-stage`, `.preview-loading` and the same "Typesetting…" copy.
|
||||
- The fit arithmetic, character for character:
|
||||
`Math.max(240, Math.min(stage.width - 56, (stage.height - 56) / ratio))` (`margin:208`, `docs:344`).
|
||||
- The lazy page renderer: a `ResizeObserver` on the stage, an `IntersectionObserver` per page at a
|
||||
1400px `rootMargin`, `Math.min(window.devicePixelRatio || 1, 2)`, a hand-built canvas with
|
||||
`className = "preview-canvas"`, `el.replaceChildren(canvas)`, a `task?.cancel()` teardown.
|
||||
`margin/PdfPage:263-336` against `docs/Page:365-448`. The only differences are names.
|
||||
|
||||
Roughly 200 of margin's 336 and 220 of docs' 448 are one component; app-specific are the compile call,
|
||||
the save path and the warning text. `<PdfPreview bytes title onSave saving warning onClose />` plus the
|
||||
`.preview-*` CSS: the cleanest large win, with no design argument attached.
|
||||
|
||||
## The shortcuts sheet
|
||||
|
||||
Three apps, two of them the same file. `calendar/src/keys/Shortcuts.tsx` (49) and
|
||||
`mail/src/keys/Shortcuts.tsx` (53) open with the identical three-line comment ("The `?` sheet,
|
||||
generated from the binding table. There is no list of shortcuts anywhere in this file, which is the
|
||||
entire point"), both render `<Sheet size="wide">` around `GROUPS.map` over `BINDINGS` into
|
||||
`.shortcuts-group > .shortcuts-heading + .shortcuts-list > .shortcuts-row > .shortcuts-keys +
|
||||
.shortcuts-label`, and both close with a `.shortcuts-note` whose first sentence is word for word
|
||||
"Nothing is modal and nothing is chorded." The CSS matches selector for selector
|
||||
(`calendar/palette.css:120-176`, `mail/keys/shortcuts.css:3-51`). Mail's improvements: props instead of
|
||||
`useOverlays` (`:11-14`), `<Key>` instead of a raw `<kbd className="key">`, and it drops keyless
|
||||
bindings because "a sheet of shortcuts that lists one with no keycap beside it is a sheet that has lost
|
||||
the plot" (`:23-24`). Docs' `components/Shortcuts.tsx` (69) is the earlier form: an inline
|
||||
`.overlay`/`.panel` and a different vocabulary
|
||||
(`.key-group`/`.key-list`/`.key-row`/`.key-what`/`.key-combos`/`.key-cap`). Margin has no sheet and no
|
||||
binding table to generate one from. `<ShortcutsSheet open onClose bindings groups keyLabel note />`:
|
||||
~170 tsx and ~130 CSS to one copy.
|
||||
|
||||
## Rich text
|
||||
|
||||
Two premises in the brief are wrong. **Calendar has no rich text editor.** `RichText.tsx` (84) is a
|
||||
read-only renderer walking a pre-parsed node tree (`:32-73`); the only `contenteditable` in the tree is
|
||||
a touch CSS selector (`app.css:49`), `useEditor.ts` (45) is a zustand store rather than tiptap's hook,
|
||||
and descriptions are edited in a `<textarea>` (`EventEditor.tsx:493-499`). Calendar's real artifact is
|
||||
`EventDetailsHtml.ts` (449), a hand-written sanitiser with a fixed tag vocabulary (`:22`, `:48+`),
|
||||
written by hand rather than with `DOMParser` to stay pure and testable (`:13-15`): a display-and-defend
|
||||
problem for HTML written by anyone who can put an event on a calendar you subscribe to, not a small
|
||||
tiptap. Also not editors: `mail/FocusReply.tsx` (345) is a `<textarea>` by decision (`:29-31`),
|
||||
`mail/MessageBody.tsx` (272) a sandboxed iframe (`:258-268`), `docs/FileViewer.tsx` (343) a pdfjs viewer.
|
||||
|
||||
So: three tiptap surfaces, and their extension lists are mutually incompatible for good reasons.
|
||||
margin's `extensions.ts` (28) keeps StarterKit nearly whole and adds seven local extensions
|
||||
(`Figure` 41, `ParagraphIndent` 42, `TextAlign` 64, `SearchHighlight` 233, `Proofing` 139, `Paste` 76,
|
||||
`Shortcuts` 11). Mail's `Editor.tsx:41-49` is StarterKit with `heading:false` and
|
||||
`horizontalRule:false` and **zero custom extensions**, not even Placeholder, using a sibling `<span>`
|
||||
plus `data-empty` (`:85-86`, `editor.css:68-83`). Docs' `extensions.ts` (196) switches **seventeen**
|
||||
StarterKit entries off (`:128-147`), keeping it only for undo/redo, drop cursor, gap cursor and list
|
||||
backspace, then **generates** every node and mark at runtime from a frozen `src/model/schema.ts`
|
||||
(`:60-87`, `:89-110`); its first twenty lines are a written argument against a shared extension list.
|
||||
|
||||
Content types are three (JSON, HTML string, markdown-backed PM node) with no `content` prop serving all
|
||||
three. Lifecycle differs: margin holds one module-level singleton editor across every chapter
|
||||
(`session.ts:23-42`) because a book is many documents; docs collapsed that cache into a path-keyed LRU
|
||||
(`Editor.tsx:11-14`). Content sync is three mechanisms of three sizes: mail guards `setContent` with a
|
||||
last-emitted ref, five lines (`Editor.tsx:52`, `:77-81`); margin never calls `setContent`, using
|
||||
`view.updateState` off an LRU of `EditorState` (`session.ts:20`, `:44-59`); docs does the same plus a
|
||||
fallback re-rendering a file as one raw block on schema failure rather than an empty doc, so a save
|
||||
cannot destroy the file (`Editor.tsx:620-644`). Merging these produces something worse than any of
|
||||
them. Nobody debounces inside the editor; all three do it in the shell at 800ms.
|
||||
|
||||
Toolbars: margin `FloatingToolbar.tsx` (198), docs `Toolbar.tsx` (938), mail **none by decision**
|
||||
(`Editor.tsx:16-19`). Docs says at `:13-19` it is a port of margin's, and the `tool()` helper
|
||||
(`margin:109-119`, `docs:156-173`) plus the `.tool-wrap` + backdrop + popover idiom are the same, but
|
||||
docs' drives a hand-rolled `EditorHandle` (`editor/index.ts:89-136`) reading
|
||||
`active.marks.includes("strong")` while margin's takes a `TiptapEditor` and calls `isActive`, kept
|
||||
live by a `forceUpdate` on `"transaction"` (`:48-55`) docs deliberately did not port.
|
||||
|
||||
**No shared editor component, and not even a shared extension list.** The spirit has already been
|
||||
shared by hand-porting with citations in the comments. Genuinely extractable: `SearchHighlight` plus
|
||||
`searchStateOf` (`margin/editor/search.ts` 233 against `docs/editor/search.ts` 264, a 73-line diff,
|
||||
docs' header at `:5-7` saying the only change of substance is a rename); `positions.ts` (64 vs 52);
|
||||
the toolbar primitives; and the install-then-restore-position helper with its triple scroll apply
|
||||
including `document.fonts.ready` (`margin/Editor.tsx:59-104`, `docs/Editor.tsx:606-690`). A small
|
||||
editor kit, not an `<Editor>`.
|
||||
|
||||
## First run, onboarding, help
|
||||
|
||||
calendar `FirstRun.tsx` (38), `Accounts.tsx` (159); docs `Recents.tsx` (86), `DocumentSetup.tsx` (354);
|
||||
mail `Onboarding.tsx` (208), `Connect.tsx` (333), `ConnectMail.tsx` (644), `Tour.tsx` (431),
|
||||
`Guide.tsx` (113), `Help.tsx` (155), `ui/EmptyState.tsx` (16); margin `Library.tsx` (181) as its start
|
||||
screen. **Margin has no first-run, welcome or tour screen at all.**
|
||||
|
||||
**There is no shared step-by-step setup flow.** Exactly one component in four apps has numbered steps
|
||||
and it is a slideshow: `Tour.tsx:355` (`useState(0)`), `:392-404` (step dots), `:405-414` (the only
|
||||
Back/Next pair anywhere), `:411` (the only terminal success screen). Everywhere else the flow ends by
|
||||
unmounting and every other screen has a single primary button. `Connect.tsx` and `ConnectMail.tsx` look
|
||||
like wizards and are not: their states are phases of an external process the user cannot navigate, and
|
||||
`Connect` has no way back once the account is written (`:276-278`). Four screens appearing at the same
|
||||
moment in a product's life, sharing an aesthetic, not a shape.
|
||||
|
||||
- **The empty-stage anatomy: four apps, four class vocabularies, one layout.** A mark, an `h1`, one
|
||||
line of prose, a row of buttons, one line of fine print. `mail/Connect.tsx:78-125`
|
||||
(`welcome-mark`/`welcome-title`/`welcome-line`/`welcome-actions`/`welcome-privacy`),
|
||||
`docs/Recents.tsx:40-57` (`start-title`/`start-line`/`start-open`), `calendar/FirstRun.tsx:19-33`
|
||||
(`first-run-title`/`first-run-note`), `margin/Library.tsx:109-123` (`card-action`).
|
||||
- **The Google connect-pending block**, the strongest single duplication here.
|
||||
`calendar/Accounts.tsx:88-114` and `mail/Connect.tsx:136-171` are the same block: a "waiting in your
|
||||
browser" line, a note conditional on `authUrl`, and Open link / Copy link / Cancel wired to
|
||||
`openAuthUrl`/`copyAuthUrl`/`cancelConnect` on a store called `useAccounts` with the same phase
|
||||
names, both guarding Escape identically with
|
||||
`useEscapeLayer(phase === "connecting", cancelConnect)` (`Accounts.tsx:44`, `Connect.tsx:51`).
|
||||
- **The recents shelf** (`docs/Recents.tsx:62-80`, `margin/Library.tsx:124-151`) and **the progress
|
||||
bar**, five copies of which four are inside mail (`Connect.tsx:310-318`, `Arriving.tsx:113`,
|
||||
`ListColumn.tsx:68-76`, `Settings.tsx:1135`, `docs/UpdateDialog.tsx:96`), two concepts sharing
|
||||
markup: sync progress and download progress.
|
||||
- **Empty-list placeholders.** Mail extracted it (`ui/EmptyState.tsx`, 16 lines, one `<p>` and a 7-line
|
||||
rule). The others hand-roll a one-line paragraph under a different class each time: `.move-empty` and
|
||||
`.dock-empty` (margin), `.panel-empty` and `.palette-empty` (calendar), `.pane-empty` (docs).
|
||||
|
||||
Shared: `<Stage mark title line actions footnote>`, `<RecentList items renderRow onOpen onForget>`,
|
||||
`<ProgressBar value label count>`, `<OAuthPending ready onOpen onCopy onCancel>`, `<EmptyState>`.
|
||||
`<Slides>` only if a second app wants a tour. Stays: every phase machine, all copy, `ConnectMail`'s
|
||||
644 lines of IMAP discovery, `DocumentSetup`'s font model, `Tour`'s nine slides.
|
||||
|
||||
## Virtualised lists and keyboard row navigation
|
||||
|
||||
Only mail virtualises (`react-virtuoso` at `ListColumn.tsx:2`, `:180`, `:451`); the other three render
|
||||
everything and say so (`calendar/AgendaList.tsx:4-6`). Nothing to share about windowing.
|
||||
|
||||
A great deal to share about the keyboard, and this is the largest instance of copied code in the audit.
|
||||
**Five distinct expressions for "move the selection by one", and the split is not by app:** clamp with
|
||||
a seed from whichever end the delta came from, four near-identical copies
|
||||
(`mail/store/useMail.ts:292-300`, `useFeed.ts:96-102`, `useScreener.ts:161-168`,
|
||||
`calendar/store/useCalendarView.ts:96-97`); clamp with no seed, where `docs/Outline.tsx:100` and
|
||||
`docs/Backlinks.tsx:92` are literally the same line and `Outline.tsx:95` says so, plus
|
||||
`mail/Guide.tsx:53` and `mail/CommandPalette.tsx:164-165`; clamp by indexing off the end and guarding
|
||||
`undefined` (`docs/Sidebar.tsx:225-240`, `margin/Sidebar.tsx:155-165`); true modulo wrap
|
||||
(`docs/Palette.tsx:91-92`, `margin/Menu.tsx:28-30`, `margin/AddPageMenu.tsx:56`,
|
||||
`margin/RowMenu.tsx:52`, `docs/RowMenu.tsx:80`, `docs/WidthMenu.tsx:116`, `docs/Titlebar.tsx:198`); and
|
||||
wrap plus seed (`mail/Help.tsx:110-111` and `mail/MoreMenu.tsx:108`, identical lines).
|
||||
|
||||
margin-docs alone contains three of the five. A list wraps or does not depending on which app and which
|
||||
surface you are in, which is precisely what a shared design language is supposed to settle.
|
||||
|
||||
Selection is four models: a key in a zustand store with DOM focus never moving and rows at
|
||||
`tabIndex={-1}` (all mail lists, calendar's agenda); an index or id in local state
|
||||
(`docs/Palette.tsx:57`, `mail/CommandPalette.tsx:321`, `mail/Guide.tsx:22`); roving DOM focus with a
|
||||
`tabIndex` shadow (`docs/Outline.tsx:102`; `docs/Backlinks.tsx:94`; `docs/Sidebar.tsx:101-105` and
|
||||
`margin/Sidebar.tsx:142-145`, the same rAF + `CSS.escape` + `querySelector` trick); and pure DOM focus
|
||||
off `document.activeElement` with no index (every menu). Keeping the row on screen is five mechanisms,
|
||||
and one found a bug the rest still carry: `docs/Outline.tsx:80-90` deliberately does **not** use
|
||||
`scrollIntoView`, doing the arithmetic by hand, because as `:79` says it "is free to scroll every
|
||||
ancestor of the row as well". The other four use it (`calendar/AgendaList.tsx:40-44`,
|
||||
`mail/Feed.tsx:127-130`, `docs/Palette.tsx:75-77`, `mail/ListColumn.tsx:281-285`). Two gaps: **no
|
||||
type-ahead anywhere in any app**, and Home/End exists in only three places, all trees or menus
|
||||
(`docs/Sidebar.tsx:233-240`, `margin/Sidebar.tsx:156-159`, `margin/Menu.tsx:24-27`).
|
||||
|
||||
```
|
||||
useRovingFocus(ref, { selector | refs, wrap, homeEnd, seedFromEnd, onMove })
|
||||
stepIndex(count, at, delta, { wrap }): number | null
|
||||
useScrollSelectedIntoView(scrollerRef, selectedId, { attr: "data-id" })
|
||||
```
|
||||
|
||||
`useRovingFocus` has ten call sites, eight of them the same eight lines differing only in the CSS class
|
||||
queried and whether they wrap: `margin/Menu.tsx:17-32`, `margin/AddPageMenu.tsx:51-59`,
|
||||
`margin/RowMenu.tsx:48-54`, `docs/RowMenu.tsx:75-81`, `docs/WidthMenu.tsx:112-117`,
|
||||
`docs/Titlebar.tsx:193-199`, `mail/Help.tsx:105-123`, `mail/MoreMenu.tsx:104-116`, plus
|
||||
`docs/Outline.tsx:99-109` and `docs/Backlinks.tsx:91-101` on refs. `stepIndex` replaces seven copies;
|
||||
the scroll hook replaces three and should use `Outline`'s manual arithmetic.
|
||||
|
||||
Stays: all ordering (`useCalendarView.ts:82-91`); ListColumn's virtualiser handle, so the shared hook
|
||||
must take a scroll strategy rather than assume the DOM; the tree's ArrowLeft/ArrowRight expand-collapse
|
||||
(`docs/Sidebar.tsx:241-251`); multi-select, only in mail (`ListColumn.tsx:209-222`). The hook must take
|
||||
key predicates rather than hardcode `e.key`, because mail and docs route list keys through a remappable
|
||||
binding table (`Guide.tsx:55-58`, `ListColumn.tsx:224-269`) while every menu listens for literal
|
||||
`ArrowDown`. `margin/Library.tsx` is the one screen that would gain a feature rather than lose
|
||||
duplication: a card grid with no arrow navigation, only Enter and Space (`:138-143`).
|
||||
|
||||
---
|
||||
|
||||
## Ranked, with the size of the win
|
||||
|
||||
| Rank | Cluster | Apps | Now | After | Argument needed |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | `Sheet` + `Confirm` + panel CSS | 4 | ~300 tsx, ~240 css | ~170, ~60 | none, mail already forked calendar |
|
||||
| 2 | `useRovingFocus` + `stepIndex` + scroll hook | 4 | ~200 over 20 sites | ~60 | wrap or clamp must be settled |
|
||||
| 3 | PDF export preview | 2 | 784 | ~450 | none |
|
||||
| 4 | Primitives: Button, Toggle, Segment, Key, Field, Icon, EmptyState, Pill, GroupHead | 4 | ~660 tsx, ~600 css | ~410, ~350 | one class vocabulary wins |
|
||||
| 5 | Find bar | 2 | 475 tsx, 370 css | ~320, 161 | none |
|
||||
| 6 | Shortcuts sheet | 3 | ~170 tsx, ~130 css | ~60, ~50 | docs adopts the sheet |
|
||||
| 7 | Palette shell + `commandMatches` + `highlight` | 3 | ~510 | ~250 | wrap vs clamp, row identity |
|
||||
| 8 | Menu and anchored positioning | 4 | ~890 | ~450 | six behaviours to reconcile |
|
||||
| 9 | Toast | 4 | ~140 | ~60 | two visual designs |
|
||||
| 10 | `Stage`, `RecentList`, `ProgressBar`, `OAuthPending` | 4 | ~250 | ~130 | none |
|
||||
| 11 | ResizeHandle and pane width | 2 | 177 | ~110 | none, plus three bugs fixed |
|
||||
| 12 | `SearchHighlight` + `positions.ts` | 2 | ~590 | ~300 | none |
|
||||
| 13 | Settings shell | 2 | ~340 | ~250 | not worth it, see above |
|
||||
|
||||
About 1600 lines of tsx and 900 of CSS collapse to roughly 900 and 500, but the number is not the
|
||||
point. The four apps disagree about whether Escape closes a menu, whether a list wraps at its ends,
|
||||
whether a separator can be focused, whether a repeated toast restarts its timer, and whether the safe
|
||||
button gets focus in a delete confirmation, none of it visible until someone uses two of them in one
|
||||
afternoon. And several clusters have one app that got a detail right and three that did not:
|
||||
`docs/Outline.tsx:80-90` alone avoids `scrollIntoView` scrolling every ancestor, `docs/Palette.tsx`
|
||||
alone has `aria-activedescendant`, `margin/ResizeHandle.tsx` alone has a focusable separator, and
|
||||
`mail/store/useToast.ts` alone restarts on a repeat. Extraction is how those stop being luck.
|
||||
|
||||
## What should not be shared
|
||||
|
||||
- **Section bodies of Settings.** 1385 lines in mail alone, all Gmail scopes and mbox export.
|
||||
- **Content matchers.** A Rust fzy scorer, SQLite FTS, substring over event fields, a backend parse.
|
||||
- **Any `<Editor>` or shared tiptap extension list.** Three content types, three schema policies, three
|
||||
lifecycles, and `docs/editor/extensions.ts:1-20` argues against the list specifically. Likewise
|
||||
`calendar/RichText.tsx` (84) and `EventDetailsHtml.ts` (449), a read-only renderer and a sanitiser
|
||||
for HTML the app did not author.
|
||||
- **Setup flows.** No shared wizard shape exists. Share the empty-stage anatomy and the OAuth pending
|
||||
block, not the flows. And **`src/width.ts`**, which shares a filename across margin and docs while
|
||||
meaning unrelated things; rename one instead.
|
||||
- **Icon paths** beyond the handful in `margin-shared/icons`. Mail's `ui/icons.ts` (73) has 29 paths
|
||||
and shares five names with the shared set by re-export (`:14`), which is the right pattern.
|
||||
- **`calendar/ColorPicker.tsx` (94) and `mail/ui/Avatar.tsx` (87).** Superficially both derive a
|
||||
colour; actually a Google `colorId` radio group and a hashed-hue initials badge. Similarly
|
||||
`margin/Dock.tsx` (223) is Typst compile plus device frames, only `DockHead` (`:60-70`) is chrome.
|
||||
- **`ProofPopover`, docs 292 against margin 76.** Same feature and the same `.proof-pop` /
|
||||
`.proof-suggestion` / `.proof-action` classes, but docs has grown a keyboard walk, an escape layer, a
|
||||
focus-return policy and a flip-above fallback margin has not. Share the anchored-menu primitive
|
||||
underneath; leave the issue rendering in each app.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Repo facts (gathered directly, 2026-09-06)
|
||||
|
||||
Ground truth for the other research notes. Everything here was read off disk, not inferred.
|
||||
|
||||
## The four repos
|
||||
|
||||
| App | Directory | Git remote | Commits | Uncommitted files |
|
||||
|---|---|---|---|---|
|
||||
| Margin (writing studio) | `python/margin` | `[email protected]:priyanshujain/margin.git` | 149 | 1 |
|
||||
| Margin Calendar | `python/margin-caledar` | `[email protected]:priyanshujain/margin-calendar.git` | 27 | 0 |
|
||||
| Margin Docs | `rust/margin-editor` | `[email protected]:priyanshujain/margin-docs.git` | 8 | 123 |
|
||||
| Margin Mail | `rust/margin-mail` | none configured | 1 | 123 |
|
||||
|
||||
All paths are relative to `/Users/pj/Workspace/projects`.
|
||||
|
||||
Three names disagree with themselves. The calendar's directory is misspelt (`margin-caledar`), the
|
||||
docs app lives in a directory called `margin-editor` while its package is `margin-docs` and its
|
||||
remote is `margin-docs`, and the two Rust-family apps sit under `rust/` while the two older ones sit
|
||||
under `python/` for no reason that survives inspection. None of the four is a Python project.
|
||||
|
||||
Margin Mail has no remote and a single scaffold commit with 123 files of uncommitted work on top of
|
||||
it. Margin Docs has 123 uncommitted files. Any plan that starts by moving files between repos has to
|
||||
deal with that first: see the sequencing note in `../migration.md`.
|
||||
|
||||
There is no separate website repo on disk. The Astro site lives at `python/margin/website`.
|
||||
|
||||
## Size
|
||||
|
||||
| App | TS/TSX/CSS files | TS lines | Rust files | Rust lines |
|
||||
|---|---|---|---|---|
|
||||
| Margin | 72 | 10,871 | 12 | 2,190 |
|
||||
| Margin Calendar | 100 | 15,517 | 20 | 8,490 |
|
||||
| Margin Docs | 151 | 43,311 | 14 | 5,365 |
|
||||
| Margin Mail | 172 | 31,409 | 98 | 45,884 |
|
||||
|
||||
About 101,000 lines of front end and 62,000 lines of Rust across the four.
|
||||
|
||||
## The shared package as it stands
|
||||
|
||||
`python/margin/shared` is a real npm package named `margin-shared`, tracked in Margin's git repo
|
||||
(26 files). It has no build step and no dependencies: consumers resolve its TypeScript source
|
||||
directly through Vite. It contains `css/tokens.css`, `css/fonts.css`, `src/fonts.ts` (233 lines),
|
||||
`src/icons.ts` (61 lines), `src/index.ts`, twelve variable font binaries with their licences, and
|
||||
`bin/sync-fonts.mjs`, which copies those binaries into a consuming app's `public/fonts`.
|
||||
|
||||
Margin depends on it as `"margin-shared": "file:./shared"`. Margin Docs and Margin Mail both depend
|
||||
on it as `"margin-shared": "file:../../python/margin/shared"`, a path that walks out of the
|
||||
repository and into a sibling checkout. On this machine pnpm has resolved that to a symlink and it
|
||||
works. On a fresh clone it does not: `pnpm install` in Margin Docs fails unless Margin happens to be
|
||||
checked out at exactly that relative location, which no CI runner and no other person will reproduce.
|
||||
Margin Calendar does not depend on it at all and carries its own copies of the same tokens.
|
||||
|
||||
This is the single fact that motivates the whole exercise. The shared package is the right idea
|
||||
executed in a way that only works on one laptop.
|
||||
|
||||
## Toolchain in use
|
||||
|
||||
pnpm 10.12.4, Node 25.5.0, cargo and rustc 1.96.1. React 19.1, Vite 7, TypeScript 5.8, Tauri 2,
|
||||
zustand 5 in all four apps. No prettier anywhere. No eslint anywhere.
|
||||
|
||||
## CLAUDE.md files
|
||||
|
||||
Only Margin and Margin Calendar have one, 16 lines each. Margin Docs and Margin Mail have none, so
|
||||
everything those two projects have learnt lives in assistant memory files outside the repos, which is
|
||||
exactly what `guidelines/` is for.
|
||||
@@ -0,0 +1,499 @@
|
||||
# Rust core plumbing (research, 2026-09-06)
|
||||
|
||||
What the four apps have in common below the features: `library.rs`, `lib.rs`, `dto.rs`, SQLite,
|
||||
logging, settings, filesystem helpers, error shapes, updates, async, and dependency versions.
|
||||
Everything here was read off disk. Google/OAuth, typesetting and spellcheck are other notes.
|
||||
|
||||
Sizes for reference: 2,190 Rust lines in Margin, 8,490 in Calendar, 5,365 in Docs, 45,884 in Mail.
|
||||
Mail's number includes 8,045 lines of `tests.rs` files; Calendar's includes 802.
|
||||
|
||||
## The verdict first
|
||||
|
||||
| Area | Apps that have it | How close, really | One crate? |
|
||||
|---|---|---|---|
|
||||
| `lib.rs` builder and menu | 4 | ~120 lines per app verbatim identical | **Yes**, the biggest single win |
|
||||
| Logging | 1 (Mail) | three apps have nothing | **Yes**, and it fixes a real gap |
|
||||
| Updates | 1.5 (Margin, plus `packaged_by` in two) | Margin's `updates.rs` is already app-agnostic | **Yes**, cheap |
|
||||
| SQLite | 3 | ~100 duplicated lines out of ~8,500 | **Yes, small**, for the two bugs it fixes |
|
||||
| `library.rs` | 4 | 5 identical lines, then four different files | No |
|
||||
| `dto.rs` conventions | 3 | one convention, rigidly held, nothing to extract | No |
|
||||
| Settings | 1 (Mail) | the other three keep prefs in `localStorage` | No |
|
||||
| Filesystem helpers | 2.5 | three genuinely different algorithms | No |
|
||||
| Error types | 4 | already uniform, nothing to fix | No |
|
||||
| Async | 3 | one shared idea (`Sink`), 12 lines | No |
|
||||
|
||||
Three defects found on the way, listed at the end of the `lib.rs` section.
|
||||
|
||||
## library.rs
|
||||
|
||||
Line counts: Margin 146, Calendar 9, Docs 9, Mail 54.
|
||||
|
||||
Calendar's and Docs' are **byte-identical files** (`diff` returns nothing): nine lines containing
|
||||
only `app_data_dir`. Mail's is that same function plus `atomic_write` and a test. Margin's is a
|
||||
different file that happens to share the name: `BookSummary` (margin `library.rs:8-14`), the four
|
||||
book commands, and `app_data_dir` at `library.rs:49-53`.
|
||||
|
||||
The genuinely shared part is five lines, identical in all four
|
||||
(margin `library.rs:49-53`, calendar `library.rs:5-9`, docs `library.rs:5-9`, mail `library.rs:8-12`):
|
||||
|
||||
```rust
|
||||
pub fn app_data_dir(app: &tauri::AppHandle) -> Result<PathBuf, String> {
|
||||
let dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
|
||||
Ok(dir)
|
||||
}
|
||||
```
|
||||
|
||||
It should move into whatever shared crate exists for other reasons. It is not a reason to create
|
||||
one. Everything else in Margin's `library.rs` is the book library and belongs to Margin.
|
||||
|
||||
## lib.rs: the Tauri builder
|
||||
|
||||
Line counts: Margin 256, Calendar 354, Docs 365, Mail 475. 1,450 lines total.
|
||||
|
||||
Measured overlap: 73 distinct non-comment lines appear **verbatim in all four files**. Counting
|
||||
occurrences, that is 114 lines of Margin's `lib.rs`, 123 of Calendar's, 120 of Docs' and 124 of
|
||||
Mail's, which is 48%, 44%, 41% and 32% of each file's code lines. Excluding trivial brace lines it
|
||||
is still 73 to 81 lines each. Roughly 480 lines of duplicated boilerplate across the suite.
|
||||
|
||||
The identical blocks, in order:
|
||||
|
||||
**`main.rs`.** Six lines, identical in all four but for the crate name. Nothing to do here; Tauri
|
||||
requires it.
|
||||
|
||||
**The builder prologue.** Margin `lib.rs:149-162`, Calendar `250-263`, Docs `250-266`, Mail
|
||||
`253-268`. `generate_context!` first, `#[cfg_attr(mobile, allow(unused_mut))]`, then:
|
||||
|
||||
```rust
|
||||
#[cfg(desktop)]
|
||||
{
|
||||
builder = builder.plugin(tauri_plugin_process::init());
|
||||
if context.config().plugins.0.contains_key("updater") {
|
||||
builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Verbatim four times. Two copies say so in a comment: Calendar `lib.rs:248-249` and Mail
|
||||
`lib.rs:251-252` both read "Ported from margin's lib.rs".
|
||||
|
||||
**The menu scaffold.** `Menu::default(handle)`, the `submenus` collect, the `find_submenu` closure,
|
||||
the `match find_submenu("File")` with its `prepend_items` / `SubmenuBuilder` arms, the Edit and Help
|
||||
appends, the macOS app-submenu insert block and the non-macOS fallback. Margin `lib.rs:46-60` and
|
||||
`62-93`, Calendar `50-64` and `66-95`, Docs `100-114` and `115-146`, Mail `84-98` and `100-135`.
|
||||
Pairwise diffs of the whole `build_menu`: Calendar against Mail is 49 differing lines out of 118 and
|
||||
123. Margin against Calendar is 89. Docs is the outlier at 149 to 159, because it rebuilds the
|
||||
macOS app submenu from scratch rather than patching Tauri's default (the reasoning is at Docs
|
||||
`lib.rs:164-176` and is good).
|
||||
|
||||
**The menu event.** Identical line in all four: `app.emit("menu-action", event.id().0.as_str()).ok();`
|
||||
(Margin `lib.rs:192`, Calendar `308`, Docs `318`, Mail `341`), inside an identical `matches!` guard
|
||||
over a list of ids.
|
||||
|
||||
**`show_main_window`.** Calendar `lib.rs:227-234` and Mail `lib.rs:184-191` have identical bodies.
|
||||
|
||||
**`packaged_by`.** Calendar `lib.rs:239-244` and Mail `lib.rs:196-201`, identical including the doc
|
||||
comment, differing only in the env var name (`MARGIN_CALENDAR_PACKAGED_BY` vs `MARGIN_MAIL_PACKAGED_BY`).
|
||||
|
||||
**`build.rs`.** Margin's and Docs' are the three-line default. Calendar's and Mail's are
|
||||
byte-identical 29-line files with the same `embed_credentials` and the same comment.
|
||||
|
||||
### Where they genuinely must differ
|
||||
|
||||
The menu contents (ids, labels, accelerators, which submenus get extra rows), the `invoke_handler`
|
||||
list, the `manage` calls and the body of `setup`, deep link registration (Calendar and Mail only),
|
||||
and the iOS viewport fix and Android consent-tab watcher (Calendar only, see below).
|
||||
|
||||
### Three defects found while reading
|
||||
|
||||
**Margin Mail cannot compile for mobile.** `#[cfg_attr(mobile, tauri::mobile_entry_point)]` sits at
|
||||
`lib.rs:203`, directly above `attach_account`, not above `pub fn run()` at `lib.rs:250`. Separately,
|
||||
`setup` calls `listen_for_redirects` (`lib.rs:307`), `stop_uikit_shrinking_the_viewport` (`lib.rs:310`)
|
||||
and `watch_for_the_consent_tab_closing` (`lib.rs:314`) under `cfg(mobile)`, `cfg(target_os = "ios")`
|
||||
and `cfg(target_os = "android")`. None of the three is defined anywhere in the crate; grep returns
|
||||
only the call sites. All three exist in Calendar (`lib.rs:149-172`, `185-199`, `213-220`) and were
|
||||
evidently meant to be ported with the rest. The iOS and Android dependency blocks are in
|
||||
`Cargo.toml` waiting for them.
|
||||
|
||||
**Four apps, three close behaviours.** Calendar and Mail prevent the close and hide the window
|
||||
(Calendar `lib.rs:313-321`, Mail `346-354`), then restore it on `RunEvent::Reopen`. Margin lets the
|
||||
window be destroyed but calls `api.prevent_exit()` and rebuilds the window from config on Reopen
|
||||
(`lib.rs:231-238`, `241-256`). Docs calls `.run(context)` directly at `lib.rs:363`, so it has no
|
||||
`RunEvent` closure and no `CloseRequested` handler anywhere in the crate: closing the window quits
|
||||
the app. For a suite that shares a design language this is the kind of thing that should have one
|
||||
answer, and a shared shell crate would force one.
|
||||
|
||||
**Capability drift.** Margin puts `core:window:allow-destroy` and `allow-start-dragging` in
|
||||
`default.json`, which applies on every platform; the other three put them in `desktop.json`. Docs
|
||||
additionally carries `core:window:allow-toggle-maximize`. Nothing is broken, but four hand-edited
|
||||
copies of the same two files will keep drifting.
|
||||
|
||||
### What the crate would be
|
||||
|
||||
A `margin-shell` crate holding: the plugin prologue as `fn desktop_plugins(builder, context)`, the
|
||||
menu scaffold as `fn standard_menu(handle, spec: &MenuSpec) -> tauri::Result<Menu<R>>` where
|
||||
`MenuSpec` names the File rows, the extra Edit and View rows and the Help rows, the `menu-action`
|
||||
forwarding, `show_main_window`, `hide_on_close`, `packaged_by(env_var)` and `app_data_dir`. Around
|
||||
250 lines, deleting roughly 400 across the four apps, and it makes the close behaviour and the
|
||||
capability set one decision instead of four.
|
||||
|
||||
## dto.rs and the IPC boundary
|
||||
|
||||
| | Lines | Structs | Enums | `rename_all = "camelCase"` |
|
||||
|---|---|---|---|---|
|
||||
| Margin | no `dto.rs` | types inline in their modules | 0 | 8 across the crate |
|
||||
| Calendar | 181 | 10 | 1 | 11 |
|
||||
| Docs | 243 | 15 | 0 | 15 |
|
||||
| Mail | 927 | 40 | 11 | 43 |
|
||||
|
||||
The three `dto.rs` files open with the same two-line header ("The IPC contract. Every type here has
|
||||
a matching declaration in src/ipc.ts. Both sides are frozen once written: implementation modules add
|
||||
bodies, not fields."). Margin has no `dto.rs`, but follows the same convention where it matters:
|
||||
`BookSummary` at `library.rs:8-14` is `#[derive(serde::Serialize)]` with `rename_all = "camelCase"`.
|
||||
|
||||
The convention is one convention and it is held rigidly: `#[derive(Debug, Clone, Serialize,
|
||||
Deserialize)]` plus `#[serde(rename_all = "camelCase")]` on every type; `#[serde(default)]` on
|
||||
patch and optional fields (9 in Margin, 55 in Calendar, 7 in Docs, 148 in Mail); `Option<T>` for
|
||||
absent rather than a sentinel; `i64` epoch milliseconds for time; a string field with the legal
|
||||
values in a doc comment (`/// idle | syncing | error`) instead of an enum. `#[serde(rename = ...)]`
|
||||
appears exactly once in the whole suite (Calendar `dto.rs:36`, for `self`), and `skip_serializing_if`
|
||||
twice, both in Mail. Mail is the only app with real enums, all `rename_all = "kebab-case"`.
|
||||
|
||||
**Is there a macro or crate here? No.** `#[serde(rename_all = "camelCase")]` is already the shortest
|
||||
spelling of the thing; a derive macro would save one line per struct and put a proc-macro crate in
|
||||
four build graphs. The duplication that costs something is on the other side: 65 structs across the
|
||||
three `dto.rs` files each have a hand-written TypeScript interface in `src/ipc.ts` with nothing
|
||||
checking that they agree, and the first 41 lines of Calendar's and Docs' `ipc.ts` are byte
|
||||
identical. That is a codegen question (`ts-rs`, `tauri-specta`) for the frontend note.
|
||||
|
||||
The one type that genuinely repeats is the progress status: Calendar `SyncStatus` (`dto.rs:147-167`),
|
||||
Docs `IndexStatus` (`dto.rs:87-109`), Mail `SyncStatus` (`dto.rs:861-893`). All three are
|
||||
`phase: String` with the states in a doc comment, `error: Option<String>`, `message: Option<String>`,
|
||||
progress counters, and a hand-written `Default` or `idle()` constructor. The common core is six
|
||||
lines. Similarly `AuthEvent`: Calendar `dto.rs:172-181` and Mail `dto.rs:898-910`, where Mail's is
|
||||
Calendar's plus `granted_scopes` and `missing_required`. Worth putting in a shared crate that exists
|
||||
anyway. Not worth one on its own.
|
||||
|
||||
## SQLite
|
||||
|
||||
Present in three. Calendar `store/` is 1,351 lines (about 960 non-test). Docs `index.rs` is 1,771
|
||||
lines of which only about 420 touch SQLite at all, the rest being fzy scoring, snippet windowing and
|
||||
markdown parsing. Mail is 6,222 non-test lines across `db.rs`, `mirror/` and `state/`, plus two
|
||||
`.sql` schema files. Call it 8,500 lines of database code.
|
||||
|
||||
**Genuinely duplicated: 80 to 120 lines.** These are not three copies of one layer, they are three
|
||||
different databases in one house style. The specific overlaps:
|
||||
|
||||
- `app_data_dir`, as above.
|
||||
- `version()`, byte-identical between Calendar `store/schema.rs:130-136` and Mail
|
||||
`mirror/schema.rs:127-135`, and again modulo the `state.` prefix at Mail `state/schema.rs:56-64`.
|
||||
- The `meta` upsert. Calendar `store/write.rs:214-228`, Mail `mirror/write.rs:57-73`, Docs' `remember`
|
||||
at `index.rs:891-899`. Four copies of one `INSERT ... ON CONFLICT DO UPDATE`.
|
||||
- `now_ms`. Docs `index.rs:905-910` and Mail `mirror/write.rs:42-46` are identical; Calendar's
|
||||
`store/write.rs:87-89` is the chrono equivalent.
|
||||
- The placeholder helper: Docs `placeholders` (`index.rs:901-903`) and Mail `holes`
|
||||
(`mirror/read.rs:898-900`), same one-liner, different name and separator.
|
||||
- The FTS5 tokenizer string `unicode61 remove_diacritics 2`, in Docs `index.rs:119-122` and Mail
|
||||
`mirror/mirror.sql:169-178`.
|
||||
- `.map_err(|e| e.to_string())`, 309 occurrences (Calendar 59, Docs 36, Mail 214). Not a function
|
||||
waiting to be extracted; a `From` impl waiting to be written.
|
||||
- The migrate skeleton: read version, refuse if newer, return if equal, run the ladder, stamp.
|
||||
|
||||
**Where they legitimately differ.** Three connection ownership models, each correct for its app:
|
||||
`Mutex<Connection>` (Calendar `store/mod.rs:17`), `Mutex<Option<Connection>>` behind a writer thread
|
||||
and a `OnceLock<Sender>` (Docs `index.rs:143-151`), and `Mutex<HashMap<String, Connection>>` with one
|
||||
pair of ATTACHed files per account (Mail `db.rs:31-38`). Pragmas are the same three ideas delivered
|
||||
three ways: `pragma_update` calls (Calendar `store/mod.rs:17-34`), an `execute_batch` literal (Docs
|
||||
`index.rs:208-221`), an `execute_batch` with a formatted ATTACH (Mail `db.rs:129-151`). Version
|
||||
storage differs on a real decision: `PRAGMA user_version` in Docs (`index.rs:229-248`) against a
|
||||
`meta` row in Calendar and Mail. FTS5 is in two apps and everything above the tokenizer line
|
||||
differs: Docs ranks with `bm25` and `highlight` (`index.rs:1184-1188`), Mail uses the index purely
|
||||
as a membership subquery (`mirror/read.rs:234`) under a query language with `from:` and `has:`
|
||||
operators (`mirror/fts.rs:100-127`).
|
||||
|
||||
**Two defects.** Mail has no transactions outside its two migrations: grepping the whole crate for
|
||||
`unchecked_transaction`, `BEGIN IMMEDIATE`, `.transaction()` and `SAVEPOINT` returns exactly three
|
||||
hits, two `execute_batch("BEGIN;")` in `mirror/schema.rs:37` and `state/schema.rs:33`, and one
|
||||
SAVEPOINT in `state/journal.rs:278`. So `apply_and_queue` (`mirror/mod.rs:167-205`), which does N
|
||||
flag updates plus N outbox inserts, runs unwrapped. Separately, Calendar's migration ladder is
|
||||
`if found < 1 { V1 } else if found < 2 { V2 }` (`store/schema.rs:115-120`), an `else if`, which will
|
||||
not compose when V3 lands. Mail's sequential `if`s (`mirror/schema.rs:39-44`) will.
|
||||
|
||||
Neither app uses `prepare_cached` anywhere. Mail's `still_bodiless` (`mirror/read.rs:949-969`)
|
||||
prepares inside a loop.
|
||||
|
||||
**The crate.** `margin-sqlite`, roughly 250 lines: `open(path, pragmas)`, `Tx` and `Savepoint` RAII
|
||||
guards (Calendar's `store/write.rs:62-85` is the right shape already and takes `&Connection` rather
|
||||
than `&mut`, which is exactly what Mail needs from inside `Db::with`), `migrate(conn, &[&str],
|
||||
version_store, noun)`, `meta_get`/`meta_set` generic over the table name so Mail's `state.meta`
|
||||
works, `holes(n)`, `now_ms`, and a `From<rusqlite::Error>` error type. Net deletion is maybe 150
|
||||
lines. Do it for the two defects it fixes and for the busy timeout, which only Mail sets today
|
||||
(`db.rs:129-151`, 5s), not for the volume. Every schema, every read and every write stays per app.
|
||||
|
||||
## Logging
|
||||
|
||||
Only Margin Mail logs. `src-tauri/src/log.rs` is 137 lines, 94 of them not tests.
|
||||
|
||||
The surface: `CAP_BYTES = 256 * 1024` (`log.rs:23`), `init(&Path)` (`:34`) which sets a
|
||||
`OnceLock<PathBuf>` to `dir.join("margin-mail.log")`, `path()` (`:38`), `note(who, line)` (`:45`)
|
||||
which always `eprintln!`s and then, only if `PATH` is set, timestamps and appends under a
|
||||
process-wide `Mutex<()>`, `trim` (`:55`) which flattens newlines and cuts at 2,000 characters, and
|
||||
`append` (`:65`) which is not rotation but a keep-the-newest-half rewrite when the cap is exceeded.
|
||||
`#[tauri::command] log_note` (`:90`) is registered at `lib.rs:361`, and the webview is the heavier
|
||||
producer: `src/ipc.ts:752-758` logs every rejected `invoke`, and `src/main.tsx:21,24` catch
|
||||
`window.onerror` and `unhandledrejection`.
|
||||
|
||||
The design decision worth keeping: `log.rs` is **told** its directory rather than reaching for an
|
||||
`AppHandle`. `db.rs:46` calls `log::init(&data)` from inside `Db::open`, so the engine still works
|
||||
under `cargo test`. Before that call, lines go to stderr, which under a Finder launch is nowhere.
|
||||
|
||||
The other three:
|
||||
|
||||
| | `eprintln!` | `println!` | log crate | tracing | plugin-log | log file |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Margin | 0 | 0 | no | no | no | none |
|
||||
| Calendar | 0 | 0 | no | no | no | none |
|
||||
| Docs | 6 | 0 | no | no | no | none |
|
||||
| Mail | 1 (inside `log.rs`) | 3 (dead) | own module | no | no | `margin-mail.log` |
|
||||
|
||||
Docs' six are `lib.rs:270`, `lib.rs:278`, `index.rs:437`, `index.rs:596`, `watch.rs:210` and
|
||||
`writingtools.rs:136`, all going to `/dev/null` under a Finder launch. Margin and Calendar have
|
||||
nothing at all: when a Drive backup or a calendar sync fails, the string reaches the frontend and
|
||||
then the process forgets it.
|
||||
|
||||
**This is the clearest shared-crate win in the whole audit.** `margin-log` is `init`, `note`, `path`
|
||||
and the `log_note` command, about 100 lines, dependent only on `chrono` and `std`, with one thing to
|
||||
parameterise (the filename, derivable from the bundle identifier). Three apps gain the ability to
|
||||
answer "why did it fail" after the process has exited, which is the standing rule for this suite.
|
||||
Two things to fix while lifting: `note` discards the result of `append`, so a failed write is
|
||||
invisible, and it does blocking file I/O under a `std::sync::Mutex` from async contexts
|
||||
(`sync/engine.rs:327`, `:363`, `:448`, `sync/hydrate.rs:276`, `google/gmail.rs:106`). Bounded and
|
||||
infrequent, so not urgent, but do not copy it into three more apps unexamined. The frontend half
|
||||
(the `.catch` in `ipc.ts` plus the two handlers in `main.tsx`) is 15 more lines per app and catches
|
||||
most real failures.
|
||||
|
||||
## Settings and persisted state
|
||||
|
||||
Only Mail has a settings layer in Rust. `settings.rs` is 479 lines (343 non-test): `settings.json`
|
||||
in the app data dir, a 25-field `Settings` struct at `dto.rs:768`, a hand-written `defaults()`
|
||||
(`settings.rs:32`), a genuine recursive JSON merge for `settings_set(patch)` (`merge_into`,
|
||||
`settings.rs:234`), an atomic write through `library::atomic_write` (`settings.rs:221`), and a
|
||||
deliberate refusal to reset on a malformed file (`settings.rs:210`, tested at `:430`). Mail also
|
||||
owns `accounts.json`, `keymap.json` and `imap-trust.json` in the same directory.
|
||||
|
||||
Where everyone else keeps configuration:
|
||||
|
||||
- **Margin**: `localStorage`, 16 keys. Per-project settings live inside the `.margin` book file,
|
||||
merged against TypeScript defaults at `src/model/book.ts:212`. Rust holds no settings; its one
|
||||
JSON file is `backup.json` (`gdrive.rs:139`), Drive bookkeeping.
|
||||
- **Calendar**: `localStorage`, five keys. Its entire Settings screen edits one preference, week
|
||||
start day. No config file on disk in any format, and no `atomic_write` in the crate.
|
||||
- **Docs**: `localStorage`, seventeen keys behind zustand stores. Rust owns `roots.json`
|
||||
(`fs.rs:60,778`), which is workspace state rather than settings, and the index database.
|
||||
|
||||
**Not a crate.** Lifting `settings.rs` means inventing a settings backend for three apps that do not
|
||||
have one and whose preferences currently live in the webview. That is a feature, not a refactor, and
|
||||
the 25-field struct cannot move regardless. If it is ever wanted, the reusable core is: read JSON,
|
||||
deep-merge a patch, atomic write, error rather than reset on a parse failure. About 60 lines.
|
||||
|
||||
One latent bug to fix in place: `Settings` has exactly one `#[serde(default)]` field
|
||||
(`dto.rs:805`, `notifications`). Every other field is required, so the next field added without one
|
||||
will fail to parse every existing install's `settings.json` and `settings_get` will error out. There
|
||||
is a regression test for the one field that has a default (`settings.rs:389`), but the pattern was
|
||||
not generalised.
|
||||
|
||||
## Filesystem helpers
|
||||
|
||||
Four `atomic_write`s, three genuinely different algorithms, all of them `write, fsync, rename` and
|
||||
**none of them fsyncing the parent directory**, so on all four a crash can still lose the rename.
|
||||
|
||||
- **Docs** `fs.rs:311-347` with helpers at `:222-288`. A per-path `Arc<Mutex<()>>` lock map so a
|
||||
debounced autosave cannot race Cmd+S; a copy of the original into the temp before truncating so
|
||||
macOS ACLs, Finder tags and the exec bit survive; a hidden collision-retried temp name
|
||||
(`.{name}.{pid}-{seq}-{nanos:x}.tmp`, 64 tries); four `watch::note_self_write` calls; and
|
||||
`remove_file` on both error paths.
|
||||
- **Margin** `project.rs:13-30`. Adds `.bak` rotation. When `backup` is false it `remove_file`s the
|
||||
target before the rename (`project.rs:26`), opening a window where the file does not exist.
|
||||
Leaves the temp behind on failure.
|
||||
- **Mail** `library.rs:19-33`. Adds `create_dir_all`. Uses `with_extension`, which for a path with
|
||||
no extension produces a doubled dot. Leaves the temp behind on failure. No lock.
|
||||
- **`write_private`** in Calendar `google/secrets.rs:243-261` and Mail `google/secrets.rs:245-263`
|
||||
is a fourth variant and the only byte-identical pair, `0o600`. That one belongs to the Google note.
|
||||
|
||||
**Do not share the general one.** Sharing it either drops Docs' watcher integration and lock map or
|
||||
drags the file watcher into the shared crate. Each divergence is justified in a comment in its own
|
||||
file. Do fix the two real bugs listed above, in place.
|
||||
|
||||
Not everything even goes through it: Mail writes the mbox export straight to `fs::File::create`
|
||||
(`exports.rs:99-104`) and the attachment cache with plain `fs::write` (`attachments.rs:279`, `:482`).
|
||||
|
||||
**Trash**: Docs only. `trash = "5"`, used at `fs.rs:712-730` with `DeleteMethod::NsFileManager` on
|
||||
macOS chosen deliberately over the crate default to avoid an Apple event entitlement, and used again
|
||||
as the safe half of a cross-volume move (`fs.rs:676-677`). Margin's `delete_book` (`library.rs:143`)
|
||||
is a bare `remove_file`.
|
||||
|
||||
**Path validation**: Docs is the only app with a real gate. `resolve` rejects non-absolute paths and
|
||||
any `Component::ParentDir`, canonicalises the deepest existing ancestor and re-appends the tail;
|
||||
`resolve_in_roots` requires `starts_with` an open root; `checked` (`fs.rs:212-214`) is what every
|
||||
path-taking command calls, reads included. `check_name` (`fs.rs:149-158`) rejects empty, `.`, `..`,
|
||||
separators and NUL. Mail sidesteps the problem by never letting the frontend name a write target;
|
||||
its only sanitiser is `free_path` (`attachments.rs:363-389`), which maps separators to `-` and
|
||||
trims dots. **Margin has none**: `project.rs:32-46` exposes `read_file`, `write_file` and
|
||||
`write_bytes` as commands taking an arbitrary absolute path from the webview with no checking at
|
||||
all. Its one validated path is the book id whitelist at `library.rs:61-66`. That is a finding for
|
||||
Margin, not an argument for a crate.
|
||||
|
||||
**File watching**: Docs only. `notify 8`, `notify-debouncer-full 0.7` and `ignore 0.4` appear in no
|
||||
other app. 300ms debounce (`watch.rs:33`), `NoCache` chosen over the file-id cache because on macOS
|
||||
the inode cache folds the two halves of a rename together (`watch.rs:222-229`), self-write
|
||||
suppression on a 2s window (`watch.rs:55,70-71`), one emit per event (`watch.rs:147`), and `kind`
|
||||
derived from a fresh `symlink_metadata` rather than trusted from FSEvents flags
|
||||
(`watch.rs:402-429`). One app watches files. There is nothing to share.
|
||||
|
||||
## Error types
|
||||
|
||||
Already uniform, and there is nothing to fix. **Every one of the 165 `#[tauri::command]`s across the
|
||||
four apps returns either a bare value or `Result<T, String>`, with zero exceptions** (Margin 24,
|
||||
Calendar 13, Docs 38, Mail 90). Counts of `-> Result<T, String>` anywhere: 52, 94, 91, 485.
|
||||
|
||||
`thiserror` and `anyhow` are dependencies of none of the four. Every `Display` is hand-written. The
|
||||
custom enums are internal and never cross to the frontend: Calendar `ApiError` (`google/api.rs:132`,
|
||||
four variants), Mail `ApiError` (`google/api.rs:184`, seven), Mail `ProviderError`
|
||||
(`provider/mod.rs:26`), Mail `Refused` (`imap/tls.rs:95`). There are five `impl From` in the whole
|
||||
suite. The two `ApiError`s look like the same type and are not: Calendar needs `SyncTokenExpired`
|
||||
and `PreconditionFailed`, Mail needs `Unauthorized`, `InsufficientScope` and `Dropped`, and even the
|
||||
shared four-line `From<reqwest::Error>` differs deliberately, with a comment in Mail explaining why
|
||||
Calendar's simpler classification would be wrong for a mail client waking from sleep.
|
||||
|
||||
A shared `Result`/`Error` shape would be churn. The one useful piece is the
|
||||
`From<rusqlite::Error>` that kills 309 `.map_err(|e| e.to_string())`, and that lives in the SQLite
|
||||
crate.
|
||||
|
||||
## Updates
|
||||
|
||||
Margin's `updates.rs` is 90 lines and does three things: derive a channel from the merged plugin
|
||||
config plus a Mac App Store receipt probe, query Apple's lookup endpoint for a newer App Store
|
||||
version, and open `macappstore://`. **It is almost entirely app-agnostic already.** `channel()`
|
||||
reads `handle.config().plugins.0` for `"updater"` and `"appstore"`; `mas_receipt()` walks
|
||||
`current_exe()` up two levels to `_MASReceipt/receipt`; `appstore_latest()` reads
|
||||
`config().identifier` and `package_info().version`. No product name, no bundle id, no endpoint is
|
||||
hardcoded. It would drop into any of the other three unchanged.
|
||||
|
||||
| | Margin | Calendar | Docs | Mail |
|
||||
|---|---|---|---|---|
|
||||
| `tauri-plugin-updater` | yes | yes | yes | yes |
|
||||
| Conditional registration | `lib.rs:159` | `lib.rs:260` | `lib.rs:263` | `lib.rs:265` |
|
||||
| Channel concept | yes | no | no | no |
|
||||
| App Store vs direct split | yes | no | no | no |
|
||||
| `packaged_by` | no | `lib.rs:239` | no | `lib.rs:196` |
|
||||
| Release pubkey | real | real | **placeholder** | **placeholder** |
|
||||
|
||||
Docs and Mail both ship a literal `REPLACE_WITH_...` string as the updater pubkey in
|
||||
`tauri.release.conf.json`, and neither release workflow substitutes it (the workflows only set
|
||||
`TAURI_SIGNING_PRIVATE_KEY`). Neither app can ship a verifiable direct-download update today. All
|
||||
four release configs are 14 lines with an identical structure differing only in pubkey and repo slug.
|
||||
|
||||
**Share it.** `updates.rs` plus `packaged_by` is one 110-line module with one thing to parameterise,
|
||||
and even the env var name could be derived from the bundle identifier. Second cheapest win after
|
||||
logging.
|
||||
|
||||
## Async
|
||||
|
||||
Margin has **no tokio dependency at all**. Docs declares `tokio = { features = ["sync", "time"] }`
|
||||
(`Cargo.toml:34`) and never uses it: grep for `tokio::` in its `src-tauri/src` returns nothing. That
|
||||
line is a copy from a sibling and should go.
|
||||
|
||||
`tauri::async_runtime::spawn` is the house style in the three apps that spawn (Margin `gdrive.rs:765`,
|
||||
Calendar `sync.rs:205` and five more, Mail `badge.rs:88` and five more). Raw `tokio::spawn` appears
|
||||
only in Mail's IMAP autodiscovery fan-out (`imap/discover.rs:69-72`, `:382-383`, `:419`), which is
|
||||
safe because Tauri's runtime is tokio but leaves those tasks untracked by Tauri's shutdown. Docs uses
|
||||
no async runtime for background work at all: three `std::thread::spawn`s (`watch.rs:260`,
|
||||
`watch.rs:287`, `index.rs:203`) and `#[tauri::command(async)]` on sync functions.
|
||||
|
||||
The two poll loops are the closest pair of non-trivial code in the suite and are still not the same.
|
||||
Calendar `sync.rs:204-215` and Mail `sync/mod.rs:374-386` share the skeleton, share
|
||||
`FIRST_PASS_SECS = 2`, and share a `focused()` helper that is character-for-character identical
|
||||
(Calendar `sync.rs:218-223`, Mail `sync/mod.rs:388-392`). They differ on the wake: Calendar awaits a
|
||||
`tokio::sync::Notify` with a timeout, so `kick` (`sync.rs:238-242`) can pull the next tick forward,
|
||||
and it listens on `store-changed` to catch a freshly connected account (`sync.rs:197-202`). Mail's
|
||||
is a bare `sleep`, and `kick` (`sync/mod.rs:456-464`) spawns a separate `sync_now` instead, relying
|
||||
on the `running: AtomicBool` re-entrancy guard (`sync/engine.rs:74-84`) to keep the two from
|
||||
overlapping. Both work. They are two answers, not one shared answer.
|
||||
|
||||
Nobody uses `tokio::time::interval`, `CancellationToken`, `watch::channel`, `parking_lot` or
|
||||
`RwLock`. Cancellation, where it exists, is a re-entrancy guard (Mail's `AtomicBool`, Calendar's
|
||||
`tokio::sync::Mutex<()>` with `try_lock`), a dropped stream (Mail `attachments.rs:140-160`), or a
|
||||
`Weak` (Docs `watch.rs:200,262`). The three debounce helpers (Docs `watch.rs:376-387` and
|
||||
`index.rs:451-464`, Mail `badge.rs:79-92`) are three different things; there is nothing to lift.
|
||||
|
||||
Events: all four use the `Emitter` trait and `app.emit(name, payload)` broadcast. **Nothing anywhere
|
||||
uses `emit_to` or `emit_filter`**, which is fine while every app is single-window. Names are
|
||||
kebab-case and overlap heavily: `menu-action` in all four, `store-changed`, `sync-progress` and
|
||||
`auth` in Calendar and Mail, `pdf-warnings` in Margin and Docs. Docs is the only app defining them
|
||||
as constants on both sides (`index.rs:42`, `watch.rs:26`, `src/ipc.ts:43-52`).
|
||||
|
||||
The lock rule is applied consistently and is worth writing down as a guideline rather than a crate:
|
||||
`std::sync::Mutex` for SQLite behind a `with(|conn| ...)` closure, `tokio::sync::Mutex` for anything
|
||||
held across an `.await`. Stated explicitly at Calendar `sync.rs:112-115` and Mail `db.rs:12-15`.
|
||||
|
||||
The `Sink` trait (Calendar `sync.rs:68-78`, Mail `sync/mod.rs:230-266`) is the one abstraction
|
||||
arrived at twice independently: `status` and `changed` methods, an `AppSink { app: AppHandle }`
|
||||
implementation, existing so a sync pass can be tested against a recorder. It is 12 lines and it
|
||||
belongs with the sync engine, which is not shared. **No async crate.**
|
||||
|
||||
## Dependency drift
|
||||
|
||||
Agreed in all four and not worth a table row: `tauri` and `tauri-build` at 2, `serde` and
|
||||
`serde_json` at 1, `base64` 0.22, `tauri-plugin-opener` 2, `objc2` 0.6 and `objc2-foundation` 0.3.
|
||||
Also agreed where shared: `sha2` 0.10, `rand` 0.8, `url` 2, `chrono` 0.4, `tempfile` 3 (dev),
|
||||
`harper-core` =2.5.0, `typst` and `typst-pdf` 0.14.2, `typst-as-lib` 0.15.5, `objc2-app-kit` 0.3,
|
||||
`objc2-ui-kit` 0.3, `block2` 0.6, `tauri-plugin-dialog` and `tauri-plugin-deep-link` at 2.
|
||||
|
||||
Where they disagree, blank meaning the app does not have it:
|
||||
|
||||
| Crate | Margin | Calendar | Docs | Mail |
|
||||
|---|---|---|---|---|
|
||||
| rusqlite | | **0.37** | 0.40 | 0.40 |
|
||||
| reqwest | 0.12 | 0.12 | | **0.13** |
|
||||
| chacha20poly1305 | | **0.10** | | 0.11 |
|
||||
| fontdb | 0.23 | | 0.23 | **0.24** |
|
||||
| tokio | none | 1 (sync, time) | 1 (**unused**) | 1 (sync, time, net, io-util, rt) |
|
||||
| tauri-plugin-process | 2 (**ungated**) | 2 (gated) | 2 (gated) | 2 (gated) |
|
||||
| tauri-plugin-updater | 2 (**ungated**) | 2 (gated) | 2 (gated) | 2 (gated) |
|
||||
|
||||
Resolved in the lockfiles: `tauri` is 2.11.3 in Margin and 2.11.5 in the other three; `serde` 1.0.228
|
||||
vs 1.0.229; `tokio` 1.52.3 vs 1.53.1; `libsqlite3-sys` 0.35.0 (Calendar) vs 0.38.2 (Docs, Mail);
|
||||
`wry` 0.55.1 and `objc2` 0.6.4 everywhere. `reqwest` 0.12 and 0.13 are both in Margin's and
|
||||
Calendar's graphs already.
|
||||
|
||||
Four real drifts to close: rusqlite 0.37 in Calendar against 0.40 elsewhere, reqwest 0.12 against
|
||||
0.13 in Mail, chacha20poly1305 0.10 against 0.11, fontdb 0.23 against 0.24. The last three matter
|
||||
because Calendar and Mail share a sealed-token format and Margin and Docs share a Typst pipeline; a
|
||||
version split inside a pair that is meant to be the same code is how the two copies quietly stop
|
||||
being the same code.
|
||||
|
||||
## What to build, and the one obstacle
|
||||
|
||||
Build three crates:
|
||||
|
||||
1. **`margin-log`**, about 100 lines. `init(dir, filename)`, `note(who, line)`, `path()`, the
|
||||
`log_note` command. Highest value: three apps currently cannot answer why anything failed.
|
||||
2. **`margin-shell`**, about 250 lines. The builder prologue, the menu scaffold behind a `MenuSpec`,
|
||||
the `menu-action` forwarding, `show_main_window`, `hide_on_close`, `app_data_dir`,
|
||||
`packaged_by`, and Margin's `updates.rs` unchanged. Deletes roughly 400 lines and forces one
|
||||
answer to the close-button question that currently has three.
|
||||
3. **`margin-sqlite`**, about 250 lines. `open` with pragmas including a busy timeout, `Tx` and
|
||||
`Savepoint`, `migrate`, `meta_get`/`meta_set`, `holes`, `now_ms`, an error type. Deletes maybe
|
||||
150 lines and fixes Mail's missing transactions and Calendar's non-composable ladder.
|
||||
|
||||
Do not build a settings crate, an error crate, a filesystem crate, an async crate or a DTO macro.
|
||||
For each of those, either only one app has the thing, or all four already do the same trivial thing
|
||||
in the same trivial way, or the apparent duplication dissolves on reading the divergences, every one
|
||||
of which is justified in a comment where it sits.
|
||||
|
||||
The obstacle is mechanical and is the same one `repo-facts.md` describes for `margin-shared`. These
|
||||
are four separate git repositories with no cargo workspace and no path dependencies between them,
|
||||
and Margin Mail has no remote at all and one scaffold commit under 123 uncommitted files. A Cargo
|
||||
path dependency walking out of one checkout into a sibling would fail on a fresh clone and in CI
|
||||
exactly as the npm one already does. Decide where the shared crates live, a fifth repository
|
||||
consumed by git tag or a monorepo, before writing a line of them.
|
||||
@@ -0,0 +1,438 @@
|
||||
# Google, OAuth, secrets, HTTP, sync and backup across the four apps
|
||||
|
||||
Read directly off disk on 2026-09-06. Every claim below has a file and a line behind it. No secret
|
||||
values are reproduced anywhere in this file.
|
||||
|
||||
Margin Docs (`rust/margin-editor`) is out of scope on the evidence: its `src-tauri/Cargo.toml` has
|
||||
no `reqwest`, no `chacha20poly1305` and no Google anything. It is the control case, and the only
|
||||
thing it shares with the other three is `library.rs`-shaped filesystem helpers.
|
||||
|
||||
## The size of the thing
|
||||
|
||||
| Package | Files | Lines |
|
||||
|---|---|---|
|
||||
| `margin-caledar/src-tauri/src/google/` | 5 | 2,258 |
|
||||
| `margin-mail/src-tauri/src/google/` | 10 | 6,077 |
|
||||
| `margin/src-tauri/src/gdrive.rs` | 1 | 953 |
|
||||
| `margin-mail/src-tauri/src/backup/` | 7 | 1,914 (1,264 without tests) |
|
||||
| `margin-caledar` sync + store | 9 | 3,784 (2,982 without tests) |
|
||||
| `margin-mail` sync + mirror + provider | 16 | 10,215 (7,210 without tests) |
|
||||
|
||||
## The two OAuth implementations are one implementation
|
||||
|
||||
Margin Mail's `google/auth.rs` opens by saying so: "ported from Margin Calendar's `google/auth.rs`,
|
||||
which took it from margin's `gdrive.rs`" (margin-mail auth.rs:1-4). The calendar's opens the same
|
||||
way about margin (margin-caledar auth.rs:1-7). This is not a family resemblance, it is a copy with
|
||||
edits, and it is measurable.
|
||||
|
||||
Ignoring the `#[cfg(test)]` modules at the foot of each file:
|
||||
|
||||
| File | Calendar lines | Mail lines | Calendar lines present verbatim in Mail |
|
||||
|---|---|---|---|
|
||||
| `google/auth.rs` | 899 | 1,146 | 810 (90%) |
|
||||
| `google/browser.rs` | 420 | 419 | 416 (99%) |
|
||||
| `google/secrets.rs` | 356 | 351 | 326 (92%) |
|
||||
| `src-tauri/build.rs` | 29 | 29 | 29 (100%) |
|
||||
|
||||
1,552 of the calendar's 1,675 non-test lines exist unchanged in Margin Mail. `browser.rs`, which is
|
||||
the whole iOS `SFSafariViewController` and Android Custom Tab consent surface, differs in seven
|
||||
lines and all seven are comment prose about which app the sheet appears over.
|
||||
|
||||
Everything below is identical in both, line for line:
|
||||
|
||||
- PKCE: `random_b64`, `pkce_challenge` and the RFC 7636 test vector (calendar auth.rs:228-238 and
|
||||
904-909, mail auth.rs:252-262 and 1170-1175).
|
||||
- The loopback listener: `write_http_message`, `Redirect`, `request_path`, `parse_redirect`,
|
||||
`await_code`, the `CANCELLED` constant and the `access_denied` special case (calendar
|
||||
auth.rs:244-374, mail auth.rs:307-437). Same 8 KiB buffer, same 150 ms poll, same 5 s read
|
||||
timeout, same favicon skip.
|
||||
- Credentials loading: `CredentialsFile` with `installed` / `android` / `ios`, the `platform_client`
|
||||
flag, the `YOUR_CLIENT_ID` sentinel check (calendar auth.rs:68-157, mail auth.rs:88-182).
|
||||
- Token endpoint: `TokenResponse`, `with_secret`, `exchange_code`, `refresh_access_token`,
|
||||
`fetch_email` (calendar auth.rs:376-477, mail auth.rs:439-572).
|
||||
- `id_token` handling: parsed, never signature-verified, with the same justification that TLS
|
||||
already proved it (calendar auth.rs:402-408, mail auth.rs:472-478).
|
||||
- Expiry and skew: `EXPIRY_SKEW_SECS = 60` and
|
||||
`now() + expires_in.saturating_sub(EXPIRY_SKEW_SECS)` (calendar auth.rs:48 and 875, mail
|
||||
auth.rs:61 and 1122). No clock-skew handling beyond that constant, in either.
|
||||
- `valid_access_token`, single-flight by holding the tokio mutex across the refresh await, with the
|
||||
same paragraph explaining that this also serialises refreshes across accounts (calendar
|
||||
auth.rs:846-877, mail auth.rs:1093-1124).
|
||||
- The deep-link path: `Pending`, `handle_redirect` taking rather than reading the verifier,
|
||||
`abandon_pending`, `connect_by_deep_link`, `callback_scheme`, the 900 s mobile timeouts (calendar
|
||||
auth.rs:204-210, 633-747; mail auth.rs:228-234, 807-923).
|
||||
- Multi-account model: `AuthState { sessions: Mutex<HashMap<String, Session>> }`, keyed on the
|
||||
Google `sub` with the email as fallback (calendar auth.rs:214-219 and 799, mail auth.rs:238-243
|
||||
and 975).
|
||||
- The build script that embeds `google-credentials.json` from `OUT_DIR`, falling back to the example
|
||||
file so a fresh clone compiles.
|
||||
|
||||
### What actually differs
|
||||
|
||||
Six things, and they are the whole design space a shared crate has to leave open.
|
||||
|
||||
1. **Scopes.** The calendar has one constant string (`SCOPES`, auth.rs:28). Mail has a six-entry
|
||||
`BASE_SCOPES` array, a `REQUIRED_SCOPE` an account is refused for, `scope_string` for adding
|
||||
extras, and `granted_scopes`/`missing_required` reading what Google actually granted back off the
|
||||
token response (mail auth.rs:29-41, 274-305, 980-994). The calendar never reads the `scope` field
|
||||
at all; its `TokenResponse` does not have one (calendar auth.rs:376-385).
|
||||
2. **Re-consent.** Mail has `grant()` (auth.rs:725-733) because installed apps get no incremental
|
||||
authorization, so picking up `calendar.events` to answer an invite means the whole consent again.
|
||||
The calendar never needs a second scope.
|
||||
3. **`login_hint` and `prompt`.** Mail's `auth_url` takes an optional hint and switches `prompt`
|
||||
between `consent` and `select_account consent` accordingly (auth.rs:607-633). The calendar always
|
||||
sends `select_account consent` (auth.rs:519-530).
|
||||
4. **Revocation.** The calendar's `revoke` discards the result (auth.rs:479-485). Mail's keeps it
|
||||
and reports "the account was removed from this device, but Google could not be reached to revoke"
|
||||
(auth.rs:584-598, 1086-1090). Mail also documents that one OAuth client covers the suite, so a
|
||||
revoke signs the person out of every Margin app (auth.rs:1026-1029, google/mod.rs:53-56).
|
||||
5. **Where the account record lands.** The calendar writes a row through
|
||||
`store::write::upsert_account` inside a SQLite store (auth.rs:806-808). Mail writes
|
||||
`accounts.json` through `crate::accounts::upsert` (auth.rs:997-1003), because every account owns
|
||||
its own database and the account list has to be readable before any of them is open
|
||||
(accounts.rs:4-8).
|
||||
6. **HTTP body building.** Mail is on reqwest 0.13, where `.form()` sits behind a feature this build
|
||||
does not enable, so it hand-rolls `form_body` over `url::form_urlencoded` (auth.rs:502-511). The
|
||||
calendar uses `.form()` (auth.rs:438-444). This is the only place the version split shows up in
|
||||
the auth code.
|
||||
|
||||
Point 6 is worth naming as the pattern: the reqwest 0.12/0.13 gap has already cost Margin Mail three
|
||||
hand-written helpers that the other two get from the library (`form_body` auth.rs:505-511,
|
||||
`query_string` api.rs:723-729, `url_with` api.rs:732-738).
|
||||
|
||||
## Secret storage
|
||||
|
||||
`google/secrets.rs` is the same file twice. The whole diff is: the `SERVICE` and `KEY_CONTEXT`
|
||||
constants (calendar secrets.rs:31 and 34, mail secrets.rs:42 and 46), a `reference()` helper the
|
||||
calendar needs for its `accounts.keychain_ref` column and mail dropped, a `tempfile` in one test,
|
||||
and the chacha20poly1305 0.10 to 0.11 API change.
|
||||
|
||||
The scheme itself, identical in both: an XChaCha20-Poly1305 blob at `tokens.enc` in the app data
|
||||
directory, one base64 entry per account id in a `BTreeMap`, a 32-byte per-install random salt at
|
||||
`tokens.salt`, and the key derived as `SHA256(KEY_CONTEXT || salt || machine_id)`
|
||||
(mail secrets.rs:101-119). `machine_id` is `/etc/machine-id` on Linux, `IOPlatformUUID` scraped out
|
||||
of `/usr/sbin/ioreg` on macOS, and deliberately empty on iOS and Android because the sandbox is the
|
||||
real boundary there and a reinstall would rotate the identifier (mail secrets.rs:128-189). Files are
|
||||
written 0600 from creation rather than chmodded afterwards (mail secrets.rs:236-239 doc comment).
|
||||
|
||||
The "why not keyring" paragraph is near-identical in both `Cargo.toml` files (margin-caledar
|
||||
Cargo.toml:36-40, margin-mail Cargo.toml:61-64) and the long version is in the file headers
|
||||
(calendar secrets.rs:1-27, mail secrets.rs:1-28): macOS ties a keychain item's ACL to the code
|
||||
signature so every ad-hoc rebuild re-prompts, and `keyring` has no Android backend at all.
|
||||
|
||||
**Version drift.** `chacha20poly1305 = "0.10"` in the calendar, `"0.11"` in mail. Mail carries the
|
||||
migration note (secrets.rs:208-211): 0.11 moved to `hybrid-array`, `Key::from_slice` and
|
||||
`XNonce::from_slice` are deprecated, and the array conversions now carry the length in the type, so
|
||||
the one panic those calls had is a compile error. The on-disk format is unchanged, so this is purely
|
||||
an API-surface difference and any shared crate should be on 0.11.
|
||||
|
||||
Mail reuses this store for two things that are not OAuth tokens: the backup key under the id
|
||||
`"margin-mail backup key"` (backup/crypto.rs:41, 119-138) and the R2 credentials under
|
||||
`"margin-mail r2 credentials"` (backup/r2.rs:29). Both comments note that neither id can collide
|
||||
with an account id, because a Google `sub` is digits and an address cannot carry a space. That is a
|
||||
good sign for extraction: the module already works as a general sealed-key-value store and only its
|
||||
two constants are app-specific.
|
||||
|
||||
## Credentials and the Google Cloud project
|
||||
|
||||
The mechanism, in both mail and the calendar: `src-tauri/build.rs` copies
|
||||
`google-credentials.json` from the repo root into `OUT_DIR`, falling back to
|
||||
`google-credentials.example.json` when the real file is absent, and `auth.rs` pulls it in with
|
||||
`include_str!(concat!(env!("OUT_DIR"), "/google-credentials.json"))` (mail auth.rs:63, calendar
|
||||
auth.rs:50). So the client id and the desktop client secret are compiled into the binary. Nothing is
|
||||
read at runtime. A clone with no credentials compiles and fails at the first connect with the
|
||||
"not set up yet" sentence rather than failing to build (build.rs:8-10).
|
||||
|
||||
Margin does it differently and worse. `gdrive.rs:41-42` builds a path from
|
||||
`CARGO_MANIFEST_DIR/../google-credentials.json` and tries to `fs::read_to_string` it **at runtime**,
|
||||
falling back to the `include_str!` copy only when that read fails. On a shipped app the path does not
|
||||
exist so the fallback always wins, but the build machine's absolute path is baked into the binary
|
||||
and a developer's on-disk file silently takes precedence over what was compiled.
|
||||
|
||||
The three `google-credentials.json` files in `margin`, `margin-caledar` and `margin-mail` are
|
||||
byte-identical (same SHA-1). All three are `.gitignore`d and untracked; only the example files are
|
||||
committed. Margin additionally keeps the raw console download at its repo root, also ignored via a
|
||||
`/client_secret_*.json` rule (margin/.gitignore:31).
|
||||
|
||||
So there is **one** Google Cloud project and **one** OAuth desktop client for the whole suite,
|
||||
copied into three repos by hand. Margin Mail's code knows this and says so on the revoke path
|
||||
(auth.rs:1026-1029). Margin's does not: `gdrive_disconnect` revokes the grant without telling anyone
|
||||
it has just signed them out of the calendar and the mail client too (gdrive.rs:776-803). The example
|
||||
files also differ: mail and the calendar carry `android` and `ios` blocks, margin's carries only
|
||||
`installed`.
|
||||
|
||||
## margin's gdrive.rs, the third client
|
||||
|
||||
It authenticates with the same flow, written independently and earlier. Same PKCE
|
||||
(gdrive.rs:159-169), same loopback listener (gdrive.rs:199-275, but inline in one 60-line function
|
||||
rather than the calendar's four testable pieces), same `exchange_code` / `refresh_access_token` /
|
||||
`fetch_email` (gdrive.rs:318-359), same `access_type=offline` consent URL (gdrive.rs:751-759). About
|
||||
330 of its 953 lines are the OAuth flow.
|
||||
|
||||
What it does differently, in every case for the worse:
|
||||
|
||||
- **The refresh token is stored in plaintext.** `BackupState.refresh_token` is a plain field
|
||||
(gdrive.rs:71) serialised into `backup.json` with `serde_json::to_string_pretty` and written by
|
||||
`crate::project::atomic_write` (gdrive.rs:153-157), which sets no file mode (project.rs:13-29).
|
||||
The other two apps seal the same kind of token for the same grant. The weakest store in the suite
|
||||
sets the real security level, so this is the one finding here I would act on before any
|
||||
refactoring.
|
||||
- **No timeouts on the HTTP client at all**: `LazyLock::new(reqwest::Client::new)` (gdrive.rs:25).
|
||||
The calendar's file header calls this out by name as fix number one (calendar auth.rs:1-4) and
|
||||
nobody went back and applied it.
|
||||
- **No single-flight refresh**: `valid_access_token` reads the session, drops the lock, then awaits
|
||||
the refresh (gdrive.rs:498-521), so N concurrent callers each fire their own. Fix number two in the
|
||||
calendar's header, also never backported.
|
||||
- **No CSRF constant-time discipline and no `Redirect` enum**, so the state check and the error
|
||||
paths are inline and untested. There are no tests in `gdrive.rs` at all; the calendar has nine and
|
||||
mail has eighteen for the same code.
|
||||
- Its one advance on the calendar is that it reads the granted `scope` back and refuses a token
|
||||
without `drive.file` (gdrive.rs:181-186, 522-532, 704-712). That idea survived into Margin Mail
|
||||
as `granted_scopes` / `missing_required` and never reached the calendar.
|
||||
|
||||
## HTTP clients
|
||||
|
||||
Seven `reqwest::Client` constructions across the three apps, all different, none sharing a builder.
|
||||
|
||||
| Where | connect | total | Other |
|
||||
|---|---|---|---|
|
||||
| margin gdrive.rs:25 | none | none | `Client::new()` |
|
||||
| margin updates.rs:6 | none | none | `Client::new()` |
|
||||
| calendar auth.rs:52-58 | 10 s | 30 s | nothing |
|
||||
| mail auth.rs:65-78 | 10 s | 30 s | h2 keepalive 20/10, tcp keepalive 30 s |
|
||||
| mail api.rs:86-108 | 10 s | 60 s | pool idle 30 s, h2 keepalive, tcp keepalive |
|
||||
| mail backup/r2.rs:40-45 | 10 s | 120 s | nothing |
|
||||
| mail attachments.rs:67-78 | 5 s | 10 s | `referer(false)`, redirects limited to 3 |
|
||||
| mail unsubscribe.rs:81-99 | 5 s | 20 s | `referer(false)`, same-host-only redirect policy |
|
||||
| mail imap/discover.rs:543-554 | 15 s | none | spoofed Chrome user agent, 3 redirects |
|
||||
|
||||
Versions and features:
|
||||
|
||||
- margin: `reqwest 0.12`, `default-features = false`, `rustls-tls`, `json` (Cargo.toml:39).
|
||||
- calendar: identical (Cargo.toml:29).
|
||||
- mail: `reqwest 0.13`, `default-features = false`, `rustls`, `webpki-roots`, `json`, `gzip`,
|
||||
`http2` (Cargo.toml:37-43), justified as "gzip because Gmail's JSON compresses by an order of
|
||||
magnitude and hydration is thousands of responses; http2 because a batch of 50 and the poll loop
|
||||
share one connection".
|
||||
|
||||
**User agent**: nothing sets one except `imap/discover.rs`, and that one is a Chrome spoof, which is
|
||||
deliberate for autodiscovery and wrong for anything else. All Google traffic from all three apps
|
||||
goes out as reqwest's default UA.
|
||||
|
||||
**Retry, backoff, rate limits.** Only Margin Mail has any. `google/api.rs` carries the whole of it:
|
||||
|
||||
- `ApiError` with seven variants, including `Dropped` for a connection that died mid-request as
|
||||
distinct from `Offline` (api.rs:183-203, 233-246).
|
||||
- `error_for`, classifying 401 / 403-by-reason / 404 / 429 / 408 / 5xx, reading Google's reason out
|
||||
of `error.status`, `error.errors[].reason` and `error.details[].reason` because a missing scope
|
||||
only appears in the third (api.rs:341-440).
|
||||
- `strip_urls`, which drops whole sentences carrying a link out of an error message on the grounds
|
||||
that a person reading a toast cannot follow one (api.rs:276-305).
|
||||
- `retry_after` (api.rs:443-452), truncated exponential `backoff_ms` with jitter capped at 64 s
|
||||
(api.rs:612-636), `with_retry` and `with_retry_no_replay` for calls that must not be made twice
|
||||
(api.rs:651-696), and a two-step fast retry for dropped connections (api.rs:642).
|
||||
- `Quota`: a per-account rolling 60-second ledger against Gmail's 6,000 units, with a per-call unit
|
||||
table (api.rs:119-176, 496-607).
|
||||
|
||||
The calendar has **none** of this. Its `error_for` maps 410 and 412 and sends everything else to
|
||||
`ApiError::Other` (margin-caledar api.rs:191-197). Grepping the whole calendar crate for `429`,
|
||||
`Retry-After`, `backoff` or `sleep` returns exactly one hit, and it is the 150 ms poll inside the
|
||||
loopback listener. A 429 from Google Calendar therefore reaches `push::drain`, is counted as a real
|
||||
attempt, and five of them retire the write permanently (calendar push.rs:29, 344-345, 375-381). That
|
||||
is a live bug, not a stylistic gap.
|
||||
|
||||
## Sync engines: how much is really shared
|
||||
|
||||
Both are honestly described as "incremental sync of a Google resource into a local SQLite mirror
|
||||
with a sync token, a poll loop and an event stream to the UI". That description is true of both and
|
||||
it is also where the similarity ends. I read both in full and I do not think a shared sync engine is
|
||||
the right conclusion.
|
||||
|
||||
### What genuinely is the same
|
||||
|
||||
The scaffolding, and it is the same to the line in places.
|
||||
|
||||
- The poll loop. Spawn a task, first pass at `FIRST_PASS_SECS = 2`, then an interval chosen by
|
||||
window focus (calendar sync.rs:39, 205-217; mail sync/mod.rs:51, 374-387). `fn focused(app)` is
|
||||
byte-identical in both (calendar sync.rs:219-223, mail sync/mod.rs:389-393). Intervals differ
|
||||
because the resources do: 60/300 s for the calendar, 12/60 s for mail, each with the unit cost
|
||||
worked out in a comment.
|
||||
- The `Sink` trait, so a pass can run in a test with a recorder behind it instead of an `AppHandle`
|
||||
(calendar sync.rs:69-78, mail sync/mod.rs:238-249). Both `AppSink`s emit `sync-progress` and call
|
||||
`emit_store_changed`.
|
||||
- The connection-borrowing seam, with the same justification sentence in both files verbatim:
|
||||
"Nothing inside may await: the guard is a std one, so holding it across a suspension point would
|
||||
make the future non-Send" (calendar sync.rs:114-115, mail sync/mod.rs:220-221). The calendar has it
|
||||
as a free function over `Store`; mail has it as a `Store` trait with a `Scoped` impl.
|
||||
- Push before pull, with the same reason ("a write that has just landed comes back as the server's
|
||||
own row in the same pass rather than a tick later"): calendar sync.rs:135-136, mail engine.rs:3-4.
|
||||
- The budgets: 20 s for the outbox in a pass and 4 s at quit, in both (calendar sync.rs:42 and 44,
|
||||
mail outbox.rs:30 and 32), with the same doc comment about racing the frontend's close-request
|
||||
timeout.
|
||||
- Schema migration: a `meta` key/value table, a `schema_version` key, a refusal to open a database
|
||||
written by a newer build, forward-only numbered steps inside a transaction (calendar
|
||||
store/schema.rs:100-136, mail mirror/schema.rs:21-63). About 40 lines each, near-identical.
|
||||
- The webview event surface. Both apps emit exactly four events and they have the same names:
|
||||
`store-changed`, `sync-progress`, `auth`, `menu-action`. `AuthEvent` is the same struct with two
|
||||
extra fields in mail (calendar dto.rs:172-181, mail dto.rs:896-910). `SyncStatus` shares five of
|
||||
its fields (calendar dto.rs:147-155, mail dto.rs:861-877).
|
||||
|
||||
### What is not the same, and cannot be
|
||||
|
||||
- **The cursor model differs in kind.** The calendar keeps one sync token per calendar in a column
|
||||
(store/schema.rs:43) plus one `calendarList` token in `meta` keyed by account (pull.rs:26, 204).
|
||||
Mail keeps one cursor per account database, which is Gmail's `historyId` (mirror/write.rs:29).
|
||||
- **Commit points are opposite.** The calendar cannot write anything until the page chain is
|
||||
exhausted, because `nextSyncToken` only arrives on the final page, and it says so at length
|
||||
(pull.rs:1-7, 136-171, 173-195: one transaction for the whole chain). An interrupted chain
|
||||
restarts from the beginning. Mail commits the cursor as soon as the changes are on disk and
|
||||
*before* hydration, deliberately (changes.rs:51-56), so a crawl that fails afterwards does not
|
||||
re-read the change log.
|
||||
- **Recovery is opposite.** A 410 in the calendar drops that one calendar's rows and cursor and
|
||||
re-syncs it alone (pull.rs:105-132). An expired history log in mail drops nothing: `reconcile`
|
||||
lists the window into a TEMP TABLE and diffs it locally (changes.rs:141-228), because the mirror
|
||||
holds decisions the state database is joined against and dropping it would be destructive.
|
||||
- **Mail has a two-phase fetch and the calendar has no use for one.** Ids, then metadata in batches
|
||||
of 50, then bodies, with an `hydrated` column so an interrupted crawl resumes across restarts
|
||||
(hydrate.rs:1-9, 22, changes.rs:69-92). `events.list` returns whole events, so this entire axis is
|
||||
absent from the calendar.
|
||||
- **Conflict resolution is opposite.** The calendar sends `If-Match` and treats a 412 as a lost race
|
||||
that is surfaced and never retried with the etag dropped, since dropping it is the clobber the
|
||||
check exists to prevent (api.rs:310-332, 337-360; push.rs:5-8). Mail has no etag because Gmail has
|
||||
none. Its writes are declarative ("say what the labels should be rather than what to do to them",
|
||||
api.rs:649-650), which is exactly why they are safe to replay and the calendar's are not.
|
||||
- **Coalescing.** Mail folds consecutive writes to the same message set into one outbox row, per
|
||||
field for flags and per label for labels (outbox.rs:63-190). The calendar does not, and its outbox
|
||||
row carries `calendar_id`, `event_id`, `original_start`, `scope` and `etag` (store/schema.rs:75-87)
|
||||
where mail's carries `op`, `payload`, `thread_key` and `hold_until` (mirror.sql:120-129).
|
||||
- **Failure policy.** Mail has a circuit breaker at four consecutive failures with a five-minute
|
||||
cooldown, a quiet-first-failure rule, and per-error-kind chip wording (engine.rs:22-33, 190-228),
|
||||
plus a body-cache poison set (engine.rs:65, 250-281). The calendar reports every failure.
|
||||
- **The provider seam is not the same seam.** Mail's `Provider` has fourteen methods and names no
|
||||
Google type at all (provider/mod.rs:166-249). It has three implementations: Gmail
|
||||
(gmail.rs:378), IMAP (imap/provider.rs:1439) and a 612-line fake. The calendar's `Transport` has
|
||||
six methods and every one of them names a Google Calendar type in its signature
|
||||
(`CalendarListPage`, `RawEvent`); it has one real implementation and a test stub
|
||||
(transport.rs:15-62, tests.rs:60). So mail's is a provider abstraction and the calendar's is a
|
||||
test seam. They look alike (both `impl Future + Send` on a `Sync` trait, no `async_trait`, and the
|
||||
mail file says so: provider/mod.rs:13-14) and they are doing different jobs.
|
||||
|
||||
### Verdict
|
||||
|
||||
A shared OAuth crate is obviously right and the numbers support it without argument. A shared sync
|
||||
engine is not. What the two engines agree on is the shape around the work: how a pass is scheduled,
|
||||
how a store connection is borrowed, how progress reaches the webview, and what an outbox row's
|
||||
lifecycle looks like. That is worth perhaps 150 to 250 lines of traits and small helpers, and
|
||||
extracting it would buy consistency rather than deletion. The interiors have no overlap worth
|
||||
having: one syncs whole objects with etags against a per-collection token that can only be committed
|
||||
at the end of a chain, the other syncs ids then metadata then bodies against a per-account log with a
|
||||
quota accountant in the middle and a checkpoint halfway through.
|
||||
|
||||
The more useful extraction on this side is not the engine at all. It is Margin Mail's
|
||||
`google/api.rs` error and retry layer: `ApiError`, `error_for`, `reasons`, `explain`, `strip_urls`,
|
||||
`retry_after`, `backoff`, `with_retry` and `Quota`. That is roughly 350 lines the calendar visibly
|
||||
needs and does not have, and moving it would fix the 429 bug above rather than merely deduplicating
|
||||
something.
|
||||
|
||||
## Backup
|
||||
|
||||
Two designs with almost nothing in common except the Drive verbs underneath.
|
||||
|
||||
**margin's** is whole-file mirroring. `collect_local_files` gathers `*.margin` books and the custom
|
||||
dictionary (gdrive.rs:576-600), hashes each one, and uploads anything whose hash moved
|
||||
(gdrive.rs:810-835). `gdrive_sync` downloads any remote file that has no local counterpart and skips
|
||||
any that does, so the local copy always wins and there is no merge at all (gdrive.rs:877-884).
|
||||
Everything goes into one visible folder called `margin` at the root of the user's Drive under
|
||||
`drive.file`, which the publishing doc defends as deliberate (docs/publishing.md:131, 162-164).
|
||||
Nothing is encrypted; the books go up as they are.
|
||||
|
||||
**Margin Mail's** is an append-only encrypted journal. Segments are 500 records each
|
||||
(backup/mod.rs:48), named `<account-hash>/<device-id>/<first>-<last>.seg` (mod.rs:76-78), where the
|
||||
account hash is a truncated SHA-256 of the address so a folder listing is not a list of somebody's
|
||||
email addresses (mod.rs:52-67). Each segment is sealed with XChaCha20-Poly1305 with its own name as
|
||||
additional authenticated data, so a store that reorders, replays or moves a segment gets a
|
||||
decryption failure rather than a wrong answer (backup/crypto.rs:60-105). Merge is a union rather than
|
||||
a conflict resolution, because a device only ever writes under its own sequence (mod.rs:179-181),
|
||||
and a pass reads before it writes so a mistyped phrase fails before it has added anything
|
||||
(mod.rs:131-133).
|
||||
|
||||
The key comes from a 24-word BIP39 phrase through Argon2id at RFC 9106's second recommended profile,
|
||||
64 MiB, three passes, one lane (backup/phrase.rs:21-48). The salt is a constant and the file explains
|
||||
why: a second device has the phrase and nothing else, so every input has to be reachable from the
|
||||
phrase alone, and 256 bits from the wordlist is what is doing the work (phrase.rs:42-48). The phrase
|
||||
is shown once and never again, which `backup_phrase` enforces by refusing the second call
|
||||
(mod.rs:364-373). The derived key is sealed through `google::secrets`, deliberately reusing that
|
||||
module rather than reimplementing it (crypto.rs:107-117).
|
||||
|
||||
The store is a three-method trait, `put` / `get` / `list` (backup/store.rs:20-30), chosen as the
|
||||
intersection of Drive's REST API and S3 so that a second implementation is an afternoon. There are
|
||||
two: Drive (backup/drive.rs, 172 lines) and S3 sigv4 signed by hand for R2 (backup/r2.rs, 426 lines,
|
||||
with the reasoning against `aws-sdk-s3` at r2.rs:10-13).
|
||||
|
||||
**What the two share** is five HTTP functions. margin's `ensure_folder`, `find_file`,
|
||||
`list_in_folder`, `upload_file` and `download_file` (gdrive.rs:361-496) and Margin Mail's
|
||||
`ensure_folder`, `find_file`, `list_folder`, `upload` and `download` (google/drive.rs:100-256) are
|
||||
the same calls written twice. Mail's is better in five specific ways: it pages at 1000 rather than
|
||||
100 (drive.rs:176 against gdrive.rs:432), it escapes the Drive query language properly
|
||||
(drive.rs:47-49), it randomises the multipart boundary where margin hardcodes one string
|
||||
(drive.rs:74-78 against gdrive.rs:455), it percent-encodes the file id into the path
|
||||
(drive.rs:228-231), and it returns a classified `ApiError`.
|
||||
|
||||
Both write into `margin` at the Drive root under `drive.file`, and both hold that as a constant in
|
||||
their own file (gdrive.rs:16, google/drive.rs:28). Mail nests itself at `margin/mail/` and its file
|
||||
header notes the architecture document had this wrong until recently (google/drive.rs:1-16). So the
|
||||
suite already has a folder convention that exists as two unrelated string literals.
|
||||
|
||||
margin's docs do not contain a Drive backup spec. `docs/` has one file, `publishing.md`, and its
|
||||
only Drive content is the App Store entitlement justification at lines 131 and 160-170. The README
|
||||
is 13 lines and does not mention Drive.
|
||||
|
||||
## Defects and drift found on the way
|
||||
|
||||
1. **Margin Mail will not compile for mobile.** `lib.rs:307` calls `listen_for_redirects(handle)`
|
||||
under `#[cfg(mobile)]` and that function is not defined anywhere in the crate. The calendar has
|
||||
it (margin-caledar lib.rs:150-172). The call site was copied and the definition was not. Desktop
|
||||
builds are unaffected, which is why it has not been noticed.
|
||||
2. **margin keeps a Google refresh token in plaintext** in `backup.json` (gdrive.rs:71, 153-157).
|
||||
Same OAuth client and same grant as the two apps that seal theirs.
|
||||
3. **The calendar has no rate limit handling**, so a 429 is counted as a failed attempt and five of
|
||||
them permanently retire a queued write (api.rs:191-197 with push.rs:29, 375-381).
|
||||
4. **margin's HTTP client has no timeouts** (gdrive.rs:25), which the calendar's own file header
|
||||
identified as a bug in 2026 and never fixed upstream.
|
||||
5. **margin's `gdrive_disconnect` revokes the suite-wide grant silently** (gdrive.rs:776-803) where
|
||||
Margin Mail names the consequence before offering the button (auth.rs:1026-1029).
|
||||
6. **`chacha20poly1305` 0.10 against 0.11** between the calendar and mail, with no on-disk format
|
||||
difference. Any shared crate should be on 0.11.
|
||||
7. **`reqwest` 0.12 against 0.13**, which has already produced three hand-written helpers in Margin
|
||||
Mail that the other two get from the library.
|
||||
|
||||
## What I would extract, and what I would not
|
||||
|
||||
**Extract, high confidence.** A `margin-google-auth` crate holding the PKCE flow, the loopback
|
||||
listener, the deep-link path, `browser.rs` whole, the credentials loader, the build script, the token
|
||||
endpoint calls, the session map and `valid_access_token`. That is around 1,550 lines that currently
|
||||
exist twice verbatim, plus roughly 330 more in `gdrive.rs` written independently and worse. It needs
|
||||
these as parameters rather than constants: the scope list and the required-scope rule, the app name
|
||||
for the listener page and the "not set up" sentence, the Android package scheme, and a small trait
|
||||
for "record this account", since one app writes a SQLite row and the other writes a JSON file.
|
||||
Whether `AuthEvent` gains mail's two extra fields for everyone or stays app-shaped is a taste call;
|
||||
mail's shape is a superset and costs the calendar two empty vectors.
|
||||
|
||||
**Extract, high confidence.** A sealed-secrets module from `google/secrets.rs`, on
|
||||
chacha20poly1305 0.11, taking `SERVICE` and `KEY_CONTEXT` as parameters. 326 lines that exist twice
|
||||
and are already being used by Margin Mail as a general key-value store rather than an OAuth-specific
|
||||
one.
|
||||
|
||||
**Extract, worth doing for the fix rather than the deduplication.** The Google error and retry layer
|
||||
from Margin Mail's `google/api.rs`. The calendar needs it and has nothing.
|
||||
|
||||
**Extract, small and easy.** The five Drive verbs, the `margin` root folder constant, `app_data_dir`
|
||||
and `atomic_write`, and the `meta`-table schema migrator. None of these is large; all of them exist
|
||||
two or three times.
|
||||
|
||||
**Do not extract.** The sync engine. Sharing the poll-loop scaffolding, the `Sink` trait and the
|
||||
connection-borrowing seam is defensible and would come to a couple of hundred lines. Sharing
|
||||
anything below that would mean building an abstraction over "a token per collection committed at
|
||||
the end of a chain, with etags" and "a log per account committed halfway, with declarative writes and
|
||||
a quota", and the abstraction would be larger and harder to read than either of the two engines it
|
||||
replaced.
|
||||
@@ -0,0 +1,399 @@
|
||||
# Testing, fixtures and the dev harness across the four apps
|
||||
|
||||
Scope: vitest and playwright config, the `tests/` suites and their helpers, `src/dev/` (the
|
||||
browser-against-fake-data harness), Rust fixtures and `#[cfg(test)]` conventions, the tsconfig
|
||||
split. Not build tooling, not CI beyond how it invokes tests.
|
||||
|
||||
Paths: margin `/Users/pj/Workspace/projects/python/margin`, margin-calendar
|
||||
`/Users/pj/Workspace/projects/python/margin-caledar`, margin-docs
|
||||
`/Users/pj/Workspace/projects/rust/margin-editor`, margin-mail
|
||||
`/Users/pj/Workspace/projects/rust/margin-mail`. Cites are relative to those roots.
|
||||
|
||||
## Findings first
|
||||
|
||||
1. **margin has no tests of any kind.** Confirmed plainly: `package.json:5-12` has `dev`, `build`,
|
||||
`preview`, `tauri`, `dmg`, `fonts:sync`, `fonts:check` and nothing else, and neither `vitest` nor
|
||||
`@playwright/test` is a dependency. No `tests/`, no `src/dev/`, zero `*.test.ts` under `src/`,
|
||||
zero `#[cfg(test)]` and zero `#[test]` under `src-tauri/src/`. Its `vite.config.ts` imports from
|
||||
`vite`, not `vitest/config`, so there is no `test` block to add to, and its `src/ipc.ts` (43
|
||||
lines) calls `invoke` directly behind an `isDesktop` early-return, so there is no seam a fixture
|
||||
could plug into. Bringing margin into a shared harness is not a config change, it is building the
|
||||
dev fixture it never had.
|
||||
2. **The three playwright configs are one file with the port swapped.** Diffing them leaves the port
|
||||
(1430/1440/1450), two rewritten comments, and two real differences: margin-docs adds
|
||||
`globalSetup: "./tests/identity.ts"` and drops `timezoneId`. Everything else is byte identical.
|
||||
3. **margin-docs is the only app that checks the dev server is serving its own checkout**, and all
|
||||
three set `reuseExistingServer: true` on a fixed port. `tests/identity.ts` (106 lines) fetches
|
||||
five source files over `?raw` and byte-compares them against disk. Its own header says the four
|
||||
suites beside it "were happy to pass against anybody's copy". margin-calendar and margin-mail
|
||||
still are.
|
||||
4. **The dev-mode invoke stub is the thing worth sharing and the three apps solved it three
|
||||
different ways.** All three branch identically in `src/ipc.ts`, but margin-calendar fakes no
|
||||
events at all, margin-mail fakes them as window `CustomEvent`s with an app-side bridge, and
|
||||
margin-docs hand-rolls 97 lines of `__TAURI_INTERNALS__` inside a test helper so the real
|
||||
`@tauri-apps/api` event plugin works in a plain tab. The third is the correct one and it is the
|
||||
one that is not reusable, because it lives in `tests/disk.ts` rather than in `src/dev/`.
|
||||
5. **margin-docs has no shared spec helper at all.** 19 of 19 spec files define their own
|
||||
`async function open()` and inline the same `margindocs-recents` localStorage seed.
|
||||
margin-calendar and margin-mail both have `tests/app.ts`, and 33 of their 34 spec files import
|
||||
`openApp` from it. Between those two, `contrastOf` (60 lines), `clockAt`, `MIDDAY`, `settle`,
|
||||
`box` and `openDialog` are code identical and differ only in doc comments.
|
||||
|
||||
## What each app has
|
||||
|
||||
| | margin | calendar | docs | mail |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `test` script | none | `vitest run` | `vitest run` | `vitest run` |
|
||||
| `test:ui` script | none | `playwright test` | `playwright test` | `playwright test` |
|
||||
| `vitest` dep | no | 3.2.4 | 3.2.4 | 3.2.4 |
|
||||
| `@playwright/test` dep | no | 1.62.1 | 1.62.1 | 1.62.1 |
|
||||
| `src/dev/` | absent | 356 lines | 1,040 lines | 3,341 lines |
|
||||
| spec files / source-level tests | 0 | 10 / 131 | 19 / 116 | 24 / 252 |
|
||||
| colocated `*.test.ts` / tests | 0 | 12 / 211 | 32 / 655 | 8 / 81 |
|
||||
| Rust `#[test]` | 0 | 79 | 0 (all integration) | 531 |
|
||||
| `src-tauri/tests/` | no | no | 8 files + support | no |
|
||||
| `src-tauri/fixtures/` | no | no | no | 76 files |
|
||||
|
||||
Source-level counts are `test(` and `it(` at file scope; several files wrap tests in a
|
||||
`for (const theme of ["light","dark"])` loop, so the run counts are higher. CI runs `pnpm test` and
|
||||
`cargo test` in all three (calendar `ci.yml:31,70`, docs `ci.yml:34,58,78`, mail `ci.yml:49,92`) and
|
||||
Playwright nowhere. `just test` is `pnpm test` plus `cargo test` and `just test-ui` is
|
||||
`pnpm test:ui`, the three justfiles agreeing line for line on both.
|
||||
|
||||
## playwright.config.ts
|
||||
|
||||
Shared by all three: `testDir: "./tests"`, `fullyParallel: true`, `retries: 0` (with the same
|
||||
comment in each saying a test that only passes on the second go is lying), `reporter: [["list"]]`,
|
||||
`outputDir: "node_modules/.cache/playwright"`, `timeout: 30_000`, `expect.timeout: 5_000`,
|
||||
`baseURL` off the port, `viewport: {1440, 900}`, `deviceScaleFactor: 1`, `locale: "en-GB"`,
|
||||
`trace: "retain-on-failure"`, `screenshot: "only-on-failure"`, a single project
|
||||
`{ name: "chromium", use: { browserName: "chromium" } }` with an identical comment explaining why it
|
||||
is not `devices["Desktop Chrome"]` (that device pins a Windows user agent and the keymap reads the
|
||||
platform off it), and a webServer block of `pnpm dev`, `reuseExistingServer: true`,
|
||||
`timeout: 60_000`, `stdout: "ignore"`, `stderr: "pipe"`.
|
||||
|
||||
Differences, in full: port 1430 / 1440 / 1450; `timezoneId: "Asia/Kolkata"` in calendar
|
||||
(`playwright.config.ts:34`) and mail (`:31`) but not docs, because both anchor their fixture to the
|
||||
browser's local day; `globalSetup` in docs only (`:14`).
|
||||
|
||||
No app configures `toHaveScreenshot`, `snapshotDir` or any visual-regression comparison, and there
|
||||
are zero snapshot baselines in the three. Every screenshot is a named PNG for a person or the docs.
|
||||
|
||||
## The tests directories
|
||||
|
||||
margin-calendar, 10 specs plus `app.ts` (370 lines) and `tsconfig.json`. Geometry and layout
|
||||
(`grid` 26, `compact` 5, `views` 8), input (`keyboard` 14, `interaction` 12, `touch` 22), form
|
||||
factor (`phone` 10), design-system (`legibility` 10), overlays (7), regression (`bugs` 17). The two
|
||||
phone files use `test.use({ viewport, hasTouch, isMobile })` at file scope (`touch.spec.ts:19`,
|
||||
`phone.spec.ts:16`) rather than a Playwright project.
|
||||
|
||||
margin-docs, 19 specs plus `caret.ts` (134), `disk.ts` (144), `saving.ts` (52), `identity.ts` (106).
|
||||
Six of the 19 are `_audit*.spec.ts`, headed "Temporary exploration harness. Deleted once the
|
||||
findings are written down" (`_audit.spec.ts:1`) and still present. The rest are bytes-on-disk claims
|
||||
(`bytes` 11, `color` 7, `export-writes-only-the-pdf` 2, `external-changes` 8), editing (`blocks`,
|
||||
`headings`, `tables`, `clipboard`, `shortcuts`), and smoke (9).
|
||||
|
||||
margin-mail, 24 specs plus `app.ts` (401 lines) and `tsconfig.json`. Roughly one spec per screen,
|
||||
plus `kit.spec.ts` (design system), `keyboard.spec.ts`, `guide.spec.ts` and `guide-shots.spec.ts`
|
||||
(asset generation, not assertion).
|
||||
|
||||
### The helpers each invented
|
||||
|
||||
`tests/app.ts` in calendar and mail is the same file with different measurement functions bolted on.
|
||||
Identical modulo doc comments:
|
||||
|
||||
- `clockAt(hour, minute)` and `MIDDAY` (cal `:41-53`, mail `:46-58`), pinning the clock to the
|
||||
current day at a fixed hour in Asia/Kolkata.
|
||||
- `openApp(page, options)` (cal `:61-90`, mail `:66-90`). Same `addInitScript` body, same
|
||||
`__test-seeded` sentinel so a reload is not silently reset, same `page.clock.setFixedTime`. Only
|
||||
the seed keys differ.
|
||||
- `settle(page)`, two `requestAnimationFrame`s (cal `:105-112`, mail `:99-106`, third copy in docs
|
||||
`tests/caret.ts:46-53`), `box(target)` (cal `:114-124`, mail `:108-118`), and `openDialog(page)`
|
||||
(cal `:288-293`, mail `:188-193`).
|
||||
- `contrastOf(page, selector)` (cal `:306-366`, mail `:219-278`), which composites every translucent
|
||||
background between the element and the page through a 1x1 canvas so `oklch()` and `color-mix()`
|
||||
do not read as transparent.
|
||||
|
||||
App-specific and correctly so: calendar's `gridFit`, `axis`, `blocks`, `headerDates`, `hourY`,
|
||||
`columnX`, `drag`; mail's `rows`, `groups`, `paneMessages`, `paletteRows`, `actionBar`,
|
||||
`checkedRows`, `bodyText`, `toast`, `listScroll`, `place`, `openRow`.
|
||||
|
||||
Two mail helpers are generic and belong in a shared package despite being written for mail:
|
||||
`token(page, name)` (`app.ts:180-185`), reading a CSS custom property off the root, and
|
||||
`failCommands(page, commands)` (`app.ts:343-360`), which uses `page.route` to answer the request for
|
||||
`/src/dev/mockIpc.ts` with a shim that forwards to the real module (`?real`) and rejects the named
|
||||
commands. That is the only way to test a failure path when the backend is in the page rather than on
|
||||
the wire, and it is 18 lines that would work unchanged in any of the four.
|
||||
|
||||
margin-docs' helpers have no sibling: `putCaret`/`caretIsIn` (`caret.ts`), whose 28-line header
|
||||
documents why nothing in the suite presses End to move a caret; `watchDirty`/`dirtyWasShown`
|
||||
(`saving.ts`), a MutationObserver installed before typing so the 500ms autosave cannot be raced; and
|
||||
`installTauriShim`/`change`/`ask` (`disk.ts`), covered below.
|
||||
|
||||
### Screenshot policy
|
||||
|
||||
`page.screenshot` appears 33 times across 16 mail specs, 7 times across 4 docs specs (all in
|
||||
`_audit*`), and never in calendar. Mail writes into `screenshots/`, which is gitignored
|
||||
(`.gitignore:41`), so an ordinary run leaves the tree clean; the 10 pictures that ship inside the
|
||||
bundle go to the committed `public/guide/` and are gated by
|
||||
`test.skip(() => !process.env.GUIDE_SHOTS)` (`guide-shots.spec.ts:19-22`) behind
|
||||
`just guide-shots` (`justfile:28-30`). That two-tier rule is right and only mail has it.
|
||||
|
||||
### Design-system assertions
|
||||
|
||||
`mail/tests/kit.spec.ts` (132 lines) is the only design-system suite. It renders a `#/kit` route in
|
||||
both palettes and shoots it, asserts fixed geometry read from custom properties (`--list-w` is
|
||||
`420px`, a row is 46px, an avatar 30x30), then runs three static source scans with `node:fs`: no hex
|
||||
literal in any stylesheet under `src/ui` or `src/screens`, every `<input>` carries `NO_AUTOFILL` or
|
||||
an explicit `autoComplete`, and no file says "keychain".
|
||||
|
||||
calendar's equivalent is runtime rather than static: `legibility.spec.ts` measures contrast, checks
|
||||
no block reads "Untitled" and checks every block has a non-empty accessible name, over both themes.
|
||||
docs' equivalent is a vitest, not a spec: `src/theme.test.ts` reads three stylesheets (including
|
||||
`node_modules/margin-shared/css/tokens.css`, `:18-22`) plus `index.html`'s pre-bundle boot script
|
||||
and asserts all of them declare the same variable set, because a missing dark variable falls back
|
||||
silently to the warm light value in `:root`. Nothing anywhere asserts anything about icons.
|
||||
|
||||
## src/dev: the invoke stub
|
||||
|
||||
All three apps switch dev mode on the same way, in `src/ipc.ts`:
|
||||
|
||||
```ts
|
||||
export function call<T>(command: string, args?: Record<string, unknown>): Promise<T> {
|
||||
if (import.meta.env.DEV && !isTauri) {
|
||||
return import("./dev/mockIpc").then((m) => m.mockCall<T>(command, args));
|
||||
}
|
||||
return invoke<T>(command, args);
|
||||
}
|
||||
```
|
||||
|
||||
calendar `ipc.ts:192-197`, docs `ipc.ts:288-292`, mail `ipc.ts:748-752`, byte identical bar the
|
||||
comment. `isTauri` is `"__TAURI_INTERNALS__" in window`, computed once at import time, and all three
|
||||
derive `isDesktop`, `isMacDesktop` and `live()` from it with the same comments verbatim (calendar
|
||||
`:9-40`, docs `:9-40`, mail `:10-34`). There is no environment variable and no dev-only build flag:
|
||||
the switch is "DEV build with no Tauri bridge", so `pnpm dev` in a browser and Playwright get the
|
||||
fixture and the packaged app cannot.
|
||||
|
||||
`mockCall` is a `switch (command)` in all three, returning `as unknown as T` at every arm and
|
||||
throwing on an unknown command (calendar `mockIpc.ts:131-132`, "dev mock has no handler for"). There
|
||||
is no type link between a command name, its arguments and its return; calendar casts args to
|
||||
`Record<string, never>` (`:41`) and then to the real type per field. Command counts: calendar 12
|
||||
arms, docs 40, mail roughly 180. State is a mutable copy of the fixture taken at module load, so
|
||||
writes persist for the session and a reload resets (calendar `:11-14`, docs `:48-49`, mail `:72-84`).
|
||||
|
||||
### Fixtures
|
||||
|
||||
`src/dev/fixture.ts` in each. calendar (222 lines) exports `devAccounts`, `devCalendars` and
|
||||
`devInstances(from, to)`, generated from a seed table and anchored to the current week; its header
|
||||
records that it is modelled on a real sync of 12,067 events where 90% came back with no summary.
|
||||
docs (344 lines) exports `devRoots`, `devEntries` (an in-memory folder with real base64 PNG, SVG and
|
||||
PDF bytes at `:208-273`) and path utilities the mock and the app both use. mail (1,572 lines)
|
||||
exports 20 symbols, 13 data tables (`devAccounts` through `devSyncStatus`) and 6 functions
|
||||
(`devDiscover`, `devCert`, `devFiles`, `devContacts`, `groupOf`, `categoryOf`).
|
||||
|
||||
A fourth fixture source in docs has no sibling: `src/markdown/corpus/`, loaded through
|
||||
`import.meta.glob("./*/*.md", { query: "?raw", eager: true })` at `corpus/load.ts:20`. Its header
|
||||
records the bug that motivated the glob, that naming folders explicitly left twenty adversarial
|
||||
files inside the corpus but outside every gate reading it. That is the "add a file, get a test"
|
||||
pattern and it is worth generalising.
|
||||
|
||||
### Dev flags
|
||||
|
||||
localStorage, read defensively inside try/catch. calendar has one, `margincal-dev-empty`
|
||||
(`mockIpc.ts:32-38`); docs has one, `margindocs-dev-no-writing-tools` (`:246-252`); mail has eight,
|
||||
`marginmail-dev-` plus `empty`, `crowd`, `notify`, `imap`, `bridge`, `pending`, `hydrate-fails`,
|
||||
`sync-fails`, read through `firstRun()` (`:220-230`) and a generic `flagged(key)` (`:262-268`). The
|
||||
naming is uniform (`<app>-dev-<thing>`) and the reader is the same eight lines three times over.
|
||||
|
||||
### Faking events, three ways
|
||||
|
||||
This is where the three diverge and where the shared design has to be decided.
|
||||
|
||||
calendar does not fake events at all: `App.tsx:52` is `if (!isTauri) return;` before every `listen`,
|
||||
so in a browser `menu-action`, `auth`, `sync-progress` and `store-changed` never arrive, and
|
||||
anything they drive is unreachable from the Playwright suite.
|
||||
|
||||
mail dispatches window `CustomEvent`s under the same names from inside the mock
|
||||
(`mockIpc.ts:237-241`), with an optional delay so a state that would otherwise last one frame is
|
||||
observable (`narrateFirstSync` at `:637-651` walks a five-step sync over 1,250ms). The app side is
|
||||
`onAppEvent` in `App.tsx:69-77`, seven lines picking `listen` or `window.addEventListener` off
|
||||
`isTauri`. Cheapest correct answer, and confined to mail.
|
||||
|
||||
docs does neither. Its mock exports `external` (`mockIpc.ts:619-696`), a second surface that mutates
|
||||
the fixture the way another program would, behind the app's back, and returns the exact
|
||||
`WatchEvent[]` the Rust watcher would have emitted; putting them on the bus is the caller's job.
|
||||
That caller is `tests/disk.ts:37-133`, which installs a hand-rolled `__TAURI_INTERNALS__` at
|
||||
document start: `invoke`, `transformCallback`, `unregisterCallback`, `runCallback`, the
|
||||
`plugin:event|listen` and `|unlisten` commands, a listener map, `metadata`, `convertFileSrc` and
|
||||
`__TAURI_EVENT_PLUGIN_INTERNALS__.unregisterListener`. Its comment at `:29-36` says this is
|
||||
deliberately not `@tauri-apps/api/mocks`, which cannot be reached from an init script, and
|
||||
deliberately written to the contract rather than to convenience. `emit` returns a delivery count per
|
||||
event so a test can tell a working subscription from a payload that fell on the floor (`:66-75`).
|
||||
`external` also carries `pauseWrites`/`resumeWrites` (`:679-695`) so a save can be held and a buffer
|
||||
kept dirty instead of racing the 500ms autosave.
|
||||
|
||||
The docs approach is the strictly better one: the app runs the real `@tauri-apps/api`, so the
|
||||
`isTauri` branch that ships is the branch under test, where mail leaves `onAppEvent`'s Tauri arm
|
||||
never exercised in a browser. But it is 97 lines in a test helper, so a person running `pnpm dev` by
|
||||
hand gets no events at all.
|
||||
|
||||
## The Rust side
|
||||
|
||||
margin-mail `src-tauri/fixtures/` is 36 `.eml` files (real messages as they come off the wire, CRLF
|
||||
throughout, half of them not UTF-8), 36 matching `golden/*.txt` and 4 `autoconfig/*.xml`, compiled
|
||||
into the test binary by a `corpus!` macro in `src/fixtures.rs:10-19` that emits one `include_bytes!`
|
||||
const per file plus an `all()` returning every pair, so a sweep over the corpus is one call.
|
||||
`fixtures.rs:58-102` is itself a test: every fixture has a header/body break, no bare LF, a
|
||||
plausible date and a parseable From. Nothing is generated at test time.
|
||||
|
||||
Alongside it, `src/provider/fake.rs` (612 lines, `#![cfg(test)]` at `:15`) is an in-memory mailbox
|
||||
implementing the `Provider` trait: real ids, labels, dates and raw bytes, paging, a history log, and
|
||||
scripted failures via `fail_next` and `withhold_body`. `provider/mod.rs:1-14` records that this is
|
||||
the only reason the sync engine is testable without credentials.
|
||||
|
||||
Nothing comparable exists elsewhere. margin-docs builds its Rust fixture at runtime instead:
|
||||
`src-tauri/tests/support/notes_repo.rs` (339 lines) creates a real git repository per test binary,
|
||||
copies 12 documents out of `src/markdown/corpus/real` so there is one corpus and not two, and
|
||||
generates 13,000 files under a vendored `node_modules` because several tests need a folder large
|
||||
enough that skipping it beats walking it. `git status` is the oracle.
|
||||
|
||||
Conventions differ and both are defensible. calendar and mail put tests in `#[cfg(test)] mod tests`
|
||||
beside the code, 6 files / 79 tests and 54 files / 531 tests; fifteen of mail's are large enough to
|
||||
live in a sibling `<module>/tests.rs` (backup, clips, contacts, decisions, drafts, exports, invites,
|
||||
notify, piles, screener, send, snooze, state, sync, unsubscribe). docs has zero `#[cfg(test)]` and
|
||||
eight integration binaries totalling 4,210 lines, one needing `--test-threads=1` and run as its own
|
||||
CI step (`ci.yml:78`). Eight mail tests carry `#[ignore]`, six of them "hits the network" in
|
||||
`imap/discover.rs`.
|
||||
|
||||
## tsconfig
|
||||
|
||||
The app `tsconfig.json` is `"include": ["src"]` in all four, so `tests/` is excluded by omission
|
||||
rather than by an `exclude` entry, and the colocated `src/**/*.test.ts` files sit inside the app's
|
||||
own type check. `tests/tsconfig.json` exists in the three and is the same nine options each time
|
||||
(ES2022, bundler resolution, strict, noUnusedLocals, noUnusedParameters, skipLibCheck, noEmit) with
|
||||
`"include": [".", "../playwright.config.ts"]`. Mail's adds `"types": ["node"]`. Nothing runs `tsc -p
|
||||
tests/tsconfig.json` in any script or CI job, so the spec files are type checked only by an editor.
|
||||
|
||||
Vitest config lives in `vite.config.ts` under `test:`, all three with
|
||||
`include: ["src/**/*.test.ts"]` and `environment: "node"`. No jsdom, no happy-dom, no
|
||||
`@testing-library/*` anywhere. margin-docs adds `maxWorkers: "50%"` and three 30-second timeouts
|
||||
with a 20-line comment explaining that a CPU-blocking markdown sweep cannot answer vitest's
|
||||
`onTaskUpdate` RPC while it runs.
|
||||
|
||||
## Colocated unit tests: what they are and are not
|
||||
|
||||
They test pure functions in a node environment. No component is rendered, no store is mounted
|
||||
against a DOM, nothing goes near `mockIpc`. Calendar's convention is explicit: a component `X.tsx`
|
||||
gets a sibling `XModel.ts` holding the decisions and `XModel.test.ts` tests that module.
|
||||
`GridModel.test.ts` covers `busyHours`, `heldHours` and `bandAt` over synthetic `Placed` values with
|
||||
`instance: {} as Instance`, because only the times matter; `EventDetailsModel.test.ts` covers
|
||||
popover placement against a fixed `Bounds`; `overlayModel` and `QuickCreateModel` cover date
|
||||
arithmetic and draft construction; `AgendaModel` covers grouping, gap labels and search matching.
|
||||
The odd one out is `EventDetailsHtml.test.ts`, half readability and half hostile input, because the
|
||||
description string comes off the wire from whoever created the event.
|
||||
|
||||
margin-mail's eight follow the same rule. `providers.test.ts` tests the routing decision for an
|
||||
address twice over, by domain and by what discovery found; `useSync.test.ts` the two pure decisions
|
||||
the header and toast make from a `SyncStatus`; `guide.test.ts` link-checks the article library
|
||||
without rendering it; the other five are table checks.
|
||||
|
||||
margin-docs' two named ones are a different genre and the more interesting one. `theme.test.ts` and
|
||||
`width.test.ts` both read source with `node:fs` and assert that two tables not written in the same
|
||||
language agree: theme against three stylesheets and a boot script, width against the command table
|
||||
and the subscription joining them. The other 30 are the markdown bridge and are app-specific.
|
||||
|
||||
None of them snapshot, mock `call()`, or configure coverage, and there is no property-based library
|
||||
(though `typst.test.ts` and the five `adversarial*.test.ts` files are hand-rolled corpus sweeps,
|
||||
which is the same idea).
|
||||
|
||||
## Known-failing specs
|
||||
|
||||
Nothing in any repo records a known failure. The only markers are `guide-shots.spec.ts:19` (an
|
||||
intentional env gate, not a failure) and a `test.fail` at `external-changes.spec.ts:320`, kept so it
|
||||
would turn red the day the defect was fixed. `margin-editor/docs/conventions.md:74` is the standing
|
||||
rule: "Never weaken, skip or delete a test to reach green."
|
||||
|
||||
The four margin-mail browser failures recorded in session memory are written down nowhere in the
|
||||
tree. If they are real that is the gap: either a per-app `tests/known-failures.md` or annotations on
|
||||
the specs, because right now the only record is a chat log.
|
||||
|
||||
## What a shared harness package would contain
|
||||
|
||||
`margin-shared` already exists at `margin/shared` and is consumed by margin and margin-docs by
|
||||
relative `file:` path, and by margin-mail. margin-calendar does not depend on it at all. Adding a
|
||||
`./test` subpath export is the least-friction home; a separate package means a fourth `file:` edge.
|
||||
|
||||
**1. A playwright config factory.** Everything in the three configs bar the port is a default, so
|
||||
the whole file becomes `export default marginPlaywrightConfig({ port: 1450, witnesses: ["src/ipc.ts",
|
||||
"src/dev/mockIpc.ts", "src/dev/fixture.ts"] })`. `witnesses` turns the docs identity check on for
|
||||
every app rather than one, with the factory supplying `globalSetup` so no app wires it. `timezoneId`
|
||||
defaults to `Asia/Kolkata` and docs passes null. Saves roughly 45 lines per app and makes "all three
|
||||
run at 1440x900 with retries 0" a fact rather than a coincidence.
|
||||
|
||||
**2. The dev backend, with a typed command registry.** Replace `switch (command)` with a table keyed
|
||||
by command whose handlers are typed off the DTO types `src/ipc.ts` already declares:
|
||||
|
||||
```ts
|
||||
export const backend = defineBackend({
|
||||
accounts_list: () => (firstRun() ? [] : accounts),
|
||||
thread_view: ({ key }: { key: string }): ThreadView => viewOf(byKey(key)),
|
||||
});
|
||||
export type Command = keyof typeof backend;
|
||||
```
|
||||
|
||||
`defineBackend` returns `{ mockCall, has, commands }`, with `mockCall` throwing the existing "no
|
||||
handler for" error on a miss. The win is that the arg cast at every arm and the `as unknown as T` at
|
||||
every return both disappear, and a command in `dto.rs` with no handler becomes checkable rather than
|
||||
a runtime surprise three screens later. Alongside it: `makeCall(loader)` producing the `call()` in
|
||||
`src/ipc.ts`, already identical in three places, and `devFlag(name)` replacing the three copies of
|
||||
the try/catch localStorage reader.
|
||||
|
||||
**3. The Tauri shim, moved from `tests/` into the shared package and made the default.** Lift
|
||||
`installTauriShim` out of docs' `tests/disk.ts:37-133` unchanged, parameterise the backend module
|
||||
specifier, and expose it both as a Playwright init script (what docs does now) and as a dev entry
|
||||
point so `pnpm dev` in a browser gets real Tauri events too. Then `onAppEvent` (mail
|
||||
`App.tsx:69-77`) is unnecessary and the app runs one code path in both environments. This is the
|
||||
highest-value item in the audit: 97 lines that took real care to get right, written to a contract
|
||||
rather than to convenience, and two of the three apps are the poorer for not having it. With it,
|
||||
`emitEvent(page, name, payload)` and the delivery-count return become shared, and mail's
|
||||
`narrateFirstSync` style of timed multi-step event script becomes a shared `script([...])`.
|
||||
|
||||
**4. Fixture loading.** Two patterns, both generalisable: docs' `import.meta.glob` corpus loader
|
||||
(`corpus/load.ts`) as `loadCorpus(glob)`, and mail's `corpus!` macro (`fixtures.rs:10-19`) as a
|
||||
shared Rust macro crate. Both encode the rule that adding a file puts it inside every sweep. Also
|
||||
shared: `mutableCopy(fixture)` for the clone-at-module-load idiom in all three mocks, and
|
||||
`undoLedger()` for mail's `undoable`/`runUndo` (`mockIpc.ts:292-314`), which any app with an undo
|
||||
toast will want.
|
||||
|
||||
**5. Playwright helpers.** `settle`, `box`, `clockAt`, `MIDDAY`, `openDialog`, `token`,
|
||||
`failCommands`, plus `makeOpenApp({ theme: "marginmail-theme", pane: "marginmail-pane" })` returning
|
||||
an `openApp`, since only the seed keys differ between the two that have one.
|
||||
|
||||
**6. Assertions on tokens and icons.**
|
||||
|
||||
```ts
|
||||
expectNoColourLiterals(root, ["src/ui", "src/screens"]); // mail kit.spec.ts:82-96
|
||||
expectThemesAgree(sheets, bootScript); // docs theme.test.ts
|
||||
expectTokens(page, { "--list-w": "420px" }); // mail kit.spec.ts:62-67
|
||||
expectContrast(page, selector, { min: 4.5 }); // cal legibility.spec.ts
|
||||
expectAccessibleNames(page, selector); // cal legibility.spec.ts
|
||||
expectIconsInSet(root, dirs); // does not exist yet
|
||||
```
|
||||
|
||||
The first two are static scans over source and need no browser, so they can run under vitest in an
|
||||
app with no Playwright, which is how margin gets its first test.
|
||||
|
||||
## What stays per app
|
||||
|
||||
Every measurement helper: calendar's `gridFit`, `axis`, `blocks`, `hourY`, `drag`; mail's `rows`,
|
||||
`groups`, `paneMessages`, `paletteRows`, `actionBar`, `toast`; docs' `putCaret`, `caretIsIn`,
|
||||
`watchDirty`. They read app-specific class names and encode app-specific timing, so sharing them
|
||||
would be indirection over one caller each.
|
||||
|
||||
The fixtures themselves, and every spec file. A calendar of 12,067 events, a folder of markdown and
|
||||
a mailbox of threads have nothing in common but the loading mechanism.
|
||||
|
||||
The Rust test convention. Mail's `#[cfg(test)] mod tests` beside the code and docs' integration
|
||||
binaries are both right for their shape, and forcing one on the other buys nothing. The shareable
|
||||
parts there are narrower: the `corpus!` macro and a `TempRepo` builder along the lines of
|
||||
`support/notes_repo.rs`.
|
||||
@@ -0,0 +1,430 @@
|
||||
# Typesetting and text: what margin and margin-docs actually share
|
||||
|
||||
Scope: the Typst PDF pipeline, fontdb loading, NSSpellChecker, Apple Writing Tools, harper-core
|
||||
grammar, and the frontend that drives all of it. Four apps were checked. margin-calendar has none
|
||||
of this: no typst, no fontdb, no harper, no NSSpellChecker in
|
||||
`/Users/pj/Workspace/projects/python/margin-caledar/src-tauri/Cargo.toml`. margin-mail has exactly
|
||||
one fingerprint, a fontdb family list. So this is a two-app problem between margin and margin-docs,
|
||||
with one eight-line cameo from mail.
|
||||
|
||||
Method for the percentages below: comments and blank lines stripped, then a longest-common-
|
||||
subsequence over the remaining lines. "Identical in order" means the same line, same order, both
|
||||
files.
|
||||
|
||||
## The headline
|
||||
|
||||
Nothing in either Rust tree is a copy that could be lifted as-is. Every pair started as a copy and
|
||||
then one side moved. margin-docs is ahead on all six Rust files and on four of the six frontend
|
||||
ones, and in three places margin is not merely behind but carries a bug that margin-docs already
|
||||
found, wrote a paragraph about, and fixed. The duplication that is worth extracting is small and
|
||||
boring; the duplication that is expensive is the divergence, and a shared crate is the only thing
|
||||
that would have stopped it.
|
||||
|
||||
Both Cargo.lock files pin the same graph: harper-core 2.5.0, typst 0.14.2, fontdb 0.23.0,
|
||||
burn-cuda 0.19.1, cubecl-cpu 0.8.1, 964 packages in margin and 962 in margin-docs. Two copies of a
|
||||
960-package dependency graph resolved to the same versions by hand.
|
||||
|
||||
## PDF export
|
||||
|
||||
`margin/src-tauri/src/pdf.rs` is 129 lines, 116 of code.
|
||||
`margin-editor/src-tauri/src/pdf.rs` is 455 lines, 275 of code.
|
||||
Identical in order: 37 lines, 31% of the smaller file.
|
||||
|
||||
Truly byte-identical, verified with diff:
|
||||
|
||||
- Diagnostic formatting. `margin/src-tauri/src/pdf.rs:114-129` and
|
||||
`margin-editor/src-tauri/src/pdf.rs:440-455` are the same 16 lines, character for character. Only
|
||||
the function name differs (`format_source_diagnostics` against `format_diagnostics`). Severity to
|
||||
string, message, hints indented two spaces, joined by newline.
|
||||
- The compile call shape. `Warned { output, warnings } = engine.compile()` then
|
||||
`typst_pdf::pdf(&document, &Default::default())`: margin pdf.rs:78-81, docs pdf.rs:272-281.
|
||||
- The bundled-family dispatch. Same four ids (`eb-garamond`, `lora`, `source-serif`, `fraunces`)
|
||||
mapping to the same eight `include_bytes!` of `../../public/fonts/*-VF.ttf`: margin pdf.rs:22-35,
|
||||
docs pdf.rs:52-82. Same list, different shape (`&[&[u8]]` statics in both, arranged differently).
|
||||
|
||||
Everything else has diverged, and the direction is one-way.
|
||||
|
||||
**Font strategy is where the drift costs the user a PDF.** margin loads the variable files for
|
||||
Literata and Hanken and hands them to Typst (pdf.rs:9-20, 57-62). margin-docs cut nine static
|
||||
instances into `margin-editor/src-tauri/fonts/` and loads those (pdf.rs:32-42), with the reason
|
||||
written at pdf.rs:24-31: Typst does not support a variable axis, warns that it does not, and lays
|
||||
out at the default instance regardless of the weight asked for. So in margin every heading, every
|
||||
bold run and every callout label exports at weight 400. margin-docs' PDFs have the hierarchy the
|
||||
author sees on screen; margin's do not. margin-docs even documents the residual caveat for the
|
||||
other four families (pdf.rs:44-51), which margin has never noticed. This is the single largest
|
||||
quality gap found anywhere in this audit, it is 1.6M of static cuts plus a PROVENANCE.md, and it
|
||||
exists in one repo only.
|
||||
|
||||
Present in margin-docs, absent from margin:
|
||||
|
||||
- A vendored mitex 0.2.5 served on `/mitex/` as static source files, with a wasm binary
|
||||
(pdf.rs:84-98), a stand-in `lib.typ` for a second attempt (pdf.rs:105-113), and the two-pass
|
||||
compile that uses it (pdf.rs:344-379). A formula mitex cannot parse degrades to literal source
|
||||
instead of killing the export.
|
||||
- Placeholder images, one per format Typst picks from an extension (pdf.rs:115-144), so an
|
||||
unreadable image is a gap rather than a failed export.
|
||||
- A root-guarded filesystem read for images with no inline bytes (pdf.rs:146-163, calling
|
||||
`fs::resolve_in_roots`). margin's `ImageInput.data` is a mandatory base64 string (pdf.rs:37-41)
|
||||
and there is no file path in the protocol at all, so margin has no exposure here but also cannot
|
||||
export an image it does not already hold in memory.
|
||||
- The font preamble, written in Rust because only Rust knows which families were found
|
||||
(pdf.rs:165-194). Note pdf.rs:176-181: Typst sets every equation in "New Computer Modern Math"
|
||||
with fallback off, so on a machine without it one formula is a hard compile error. margin has no
|
||||
math and no monospace preamble at all.
|
||||
- Warning aggregation with counts and a `kind` (pdf.rs:196-244 plus `PdfWarning` in dto.rs:217-222).
|
||||
margin emits one joined string on the same `pdf-warnings` event (pdf.rs:100-102).
|
||||
- `pdf_write` with the guard that refuses to overwrite a markdown or text file (pdf.rs:411-437).
|
||||
|
||||
The escaping boundary is on the frontend in both, covered below.
|
||||
|
||||
## Font loading
|
||||
|
||||
`margin/src-tauri/src/fonts.rs` is 47 lines, 43 of code.
|
||||
`margin-editor/src-tauri/src/fonts.rs` is 182 lines, 113 of code.
|
||||
Identical in order: 17 lines, 39% of the smaller.
|
||||
|
||||
The three-way duplication is here and it is trivially extractable. Listing every installed family
|
||||
is the same eight lines in three crates:
|
||||
|
||||
- `margin/src-tauri/src/fonts.rs:11-18` (`list_system_fonts`)
|
||||
- `margin-editor/src-tauri/src/fonts.rs:160-167` (`fonts_list_system`), byte-identical to margin's
|
||||
- `margin-mail/src-tauri/src/settings.rs:180-188` (`system_fonts`), the same algorithm with
|
||||
`system_db()` inlined and `names` renamed to `families`
|
||||
|
||||
All three do `db.faces()`, `families.first()`, clone the name, sort, dedup. All three are
|
||||
`#[tauri::command(async)]`. mail is on fontdb 0.24 (`margin-mail/src-tauri/Cargo.toml:70`), the
|
||||
other two on 0.23. Nothing in this function changed between those versions.
|
||||
|
||||
The per-family loader is the second shared piece: the same four `(Weight, Style)` pairs, the same
|
||||
`Query { families: &[Family::Name(family)], weight, style, ..Default }`, the same
|
||||
`with_face_data(id, |data, _| data.to_vec())`. margin fonts.rs:21-46, docs fonts.rs:69-95.
|
||||
|
||||
Two drifts, both in margin-docs' favour:
|
||||
|
||||
- Deduplication key. margin dedups by `fontdb::ID` (fonts.rs:30, 39), which is per face. docs dedups
|
||||
by source file path (fonts.rs:55-61, 88). `with_face_data` hands back the whole file, so a `.ttc`
|
||||
holding regular, italic, bold and bold-italic is read and shipped to Typst four times by margin
|
||||
and once by docs. On a system family that is a collection, margin sends four copies of the same
|
||||
multi-megabyte blob across the compile.
|
||||
- The whole `Fallbacks` machinery (fonts.rs:19-42 for the family lists, 97-143 for the collection)
|
||||
has no counterpart in margin. margin names no monospace and no math family, so a code block or a
|
||||
formula in a margin export gets whatever Typst defaults to.
|
||||
|
||||
One correction worth carrying into any shared crate: the comment at
|
||||
`margin-editor/src-tauri/src/fonts.rs:84-86` says fontdb "answers a query with its closest match
|
||||
rather than with nothing, so a family that is not installed comes back as some unrelated face".
|
||||
That is not what fontdb 0.23 does. `Database::query`
|
||||
(`~/.cargo/registry/src/index.crates.io-*/fontdb-0.23.0/src/lib.rs:661-679`) filters candidates by
|
||||
exact family-name equality and returns `None` when the list is empty. The `installed()` guard at
|
||||
fonts.rs:88 therefore cannot fire, and since it compares case-insensitively while the query compares
|
||||
exactly, it is strictly weaker than the filter that already ran. It is live and useful at
|
||||
fonts.rs:139, where it is asked about `db.faces()` directly. Harmless dead code, but the comment
|
||||
would mislead whoever writes the shared version.
|
||||
|
||||
## Spellcheck
|
||||
|
||||
`margin/src-tauri/src/macspell.rs` is 73 lines, 68 of code.
|
||||
`margin-editor/src-tauri/src/macspell.rs` is 162 lines, 82 of code.
|
||||
Identical in order: 49 lines, 72% of the smaller. This is the closest pair in either Rust tree.
|
||||
|
||||
`utf16_to_codepoint` is byte-identical, 12 lines: margin macspell.rs:14-25, docs macspell.rs:54-65.
|
||||
|
||||
`check` is the same function with three changes. Both build the NSString, ask
|
||||
`checkString_range_types_options_inSpellDocumentWithTag_orthography_wordCount` for
|
||||
`Spelling | Link`, skip non-spelling results, map both ends of the NSRange through the table, cut
|
||||
the word out of the caller's own `chars`, and take at most five guesses.
|
||||
|
||||
- margin filters against an in-process custom word set (macspell.rs:55-57) because it keeps its own
|
||||
dictionary file. docs has no custom set: learning writes to the system
|
||||
(`macspell.rs:143-162`, `learn` and `unlearn`, absent from margin entirely).
|
||||
- docs names its constants (`MAX_SUGGESTIONS`, `NO_DOCUMENT` at macspell.rs:40-45); margin inlines
|
||||
`5` and `0`.
|
||||
- The end-offset clamp. margin: `map[(range.location + range.length).min(len)]` (macspell.rs:53).
|
||||
docs: `map[range.location.saturating_add(range.length).min(len)]` (macspell.rs:107). The add
|
||||
happens before the clamp in margin, so an NSRange carrying `NSNotFound` as its location panics in
|
||||
debug and wraps in release. Small, real, and already fixed once.
|
||||
|
||||
margin returns a local `MacIssue` (macspell.rs:7-12); docs returns the shared `SpellIssue` from
|
||||
dto.rs:179-185. Same four fields.
|
||||
|
||||
docs also has `spell.rs` (95 lines, 28 of code), a platform shim giving the frontend four commands
|
||||
on every target with a `no_checker` module for non-macOS. margin has no equivalent; its
|
||||
non-macOS path is `#[cfg]` branches inside `proofing.rs` (proofing.rs:91-96, 105-166, 232-238) plus
|
||||
a bundled 550K SCOWL Hunspell dictionary under `margin/src-tauri/resources/dictionaries/en/`.
|
||||
|
||||
## Apple Writing Tools
|
||||
|
||||
`margin/src-tauri/src/writingtools.rs` is 81 lines, 68 of code.
|
||||
`margin-editor/src-tauri/src/writingtools.rs` is 146 lines, 83 of code.
|
||||
Identical in order: 42 lines, 61% of the smaller.
|
||||
|
||||
Byte-identical, verified: `submenu_named` and `edit_menu` together, 21 lines. margin
|
||||
writingtools.rs:10-30 against docs writingtools.rs:23-43. `writing_tools_menu` is the same
|
||||
one-liner in both (margin:32-34, docs:45-47). That is the entire AppKit menu-walking layer, and it
|
||||
is the cleanest candidate for extraction in the whole audit: it takes a `MainThreadMarker` and a
|
||||
title and it knows nothing about either app.
|
||||
|
||||
The divergence is a deliberate disagreement, and it is documented. margin puts Shift+Option+F and
|
||||
Shift+Option+R on Apple's own Proofread and Rewrite rows (writingtools.rs:8, 36-49). margin-docs
|
||||
refuses to, and writingtools.rs:85-91 says why: AppKit performs a key equivalent by firing the menu
|
||||
item directly, so a chord on the system's row reaches Writing Tools without passing the selection
|
||||
guard in `src/editor/writing.ts`, and that guard is refusing selections that corrupt the file. docs
|
||||
puts the chords on its own Edit rows instead. margin has no such guard, so it is not currently
|
||||
wrong for margin, but the reasoning is the sibling's and margin has never seen it.
|
||||
|
||||
docs also adds an availability probe: a `SUBMENU_SEEN` atomic set at setup (writingtools.rs:13-14,
|
||||
92-95) and a `writing_available` command (106-120), so the frontend can say the machine has no
|
||||
Apple Intelligence instead of offering a button that does nothing. margin's `perform` returns `()`
|
||||
and silently no-ops when the row is missing (writingtools.rs:51-61); docs' returns
|
||||
`Result<(), String>` with three distinct messages (58-73).
|
||||
|
||||
One manifest oddity: `margin/src-tauri/Cargo.toml:57` asks for the `NSWritingToolsCoordinator`
|
||||
feature of objc2-app-kit and nothing in margin uses it. margin-docs names exactly that in a comment
|
||||
at `margin-editor/src-tauri/Cargo.toml:67`.
|
||||
|
||||
## Grammar
|
||||
|
||||
margin has one module doing spelling, grammar and the custom dictionary:
|
||||
`margin/src-tauri/src/proofing.rs`, 275 lines, 239 of code. margin-docs splits the same work three
|
||||
ways: `grammar.rs` (128 lines, 58 of code), `spell.rs` (95 lines, 28), `macspell.rs`.
|
||||
|
||||
Comparing the harper parts only, `proofing.rs` against `grammar.rs`: 33 lines identical in order,
|
||||
56% of the smaller.
|
||||
|
||||
`build_harper` is the same five lines of code in both, margin proofing.rs:98-103 and docs
|
||||
grammar.rs:41-47: `FstDictionary::curated()`, `LintGroup::new_curated(dict.clone(),
|
||||
Dialect::American)`, `set_rule_enabled("SpellCheck", false)`. Same reasoning in both, that the
|
||||
system checker does spelling better.
|
||||
|
||||
`collect_grammar` is the same walk: `Document::new_plain_english(text, dict)`, iterate lints, slice
|
||||
`existing` out of `chars`, map `Suggestion::ReplaceWith` / `InsertAfter` / `Remove` the same three
|
||||
ways, truncate to five. margin proofing.rs:168-194, docs grammar.rs:74-127.
|
||||
|
||||
Two differences, both docs ahead:
|
||||
|
||||
- Span clamping. margin clamps start and end against `chars.len()` independently
|
||||
(proofing.rs:171-172). docs clamps end first, then start against end (grammar.rs:84-85), with the
|
||||
comment saying why: a foreign engine walking user prose that hands back an inverted span makes
|
||||
`chars[start..end]` a panic in margin and a no-op in docs.
|
||||
- docs drops lints whose span is nothing but whitespace (grammar.rs:96-98), naming Harper's "French
|
||||
spaces" rule specifically. margin draws them, so a margin user gets an invisible underline over
|
||||
two spaces that cannot be clicked.
|
||||
|
||||
Engine lifecycle differs without either being wrong: margin lazily fills a Tauri-managed
|
||||
`Mutex<Option<Engine>>` (proofing.rs:36-40, 203-216); docs uses a module-level
|
||||
`LazyLock<Mutex<Harper>>` (grammar.rs:39).
|
||||
|
||||
## The [patch.crates-io] trap
|
||||
|
||||
Both crates carry the same two-line patch, and the four stub files behind it are code-identical.
|
||||
|
||||
- `margin/src-tauri/Cargo.toml:70-72` and `margin-editor/src-tauri/Cargo.toml:98-100`: the same
|
||||
`burn-cuda = { path = "stubs/burn-cuda" }` and `cubecl-cpu = { path = "stubs/cubecl-cpu" }`.
|
||||
- `harper-core = { version = "=2.5.0", features = ["concurrent"] }`, margin Cargo.toml:38 and docs
|
||||
Cargo.toml:57. Both carry a comment above it saying the pin is exact because the stubs are tied to
|
||||
this version's burn/cubecl graph and a minor bump could silently invalidate the patch.
|
||||
- `[profile.dev.package."*"] opt-level = 3`, margin Cargo.toml:78-79 and docs Cargo.toml:107-108,
|
||||
with the same justification (harper's burn-ndarray POS tagger is roughly ten times slower
|
||||
unoptimized).
|
||||
- The stubs themselves: `stubs/burn-cuda/Cargo.toml` (21 lines) and `stubs/cubecl-cpu/Cargo.toml`
|
||||
(16 lines). Diffing them with comment lines removed produces no output. The feature lists that
|
||||
have to match burn's `burn-cuda?/...` references (`std`, `doc`, `fusion`, `autotune`,
|
||||
`autotune-checks`) and the pinned stub versions (burn-cuda 0.19.1, cubecl-cpu 0.8.1) are the same
|
||||
in both.
|
||||
|
||||
The only differences across all four stub files are prose: margin says "broken/heavy" where docs
|
||||
says "heavy", margin's cubecl-cpu comment blames failing tracel-llvm prereleases where docs blames
|
||||
build cost, and margin uses an em dash in the two `lib.rs` one-liners where docs uses a colon.
|
||||
|
||||
Why this is a trap rather than merely duplication. Cargo treats an unused `[patch]` as a warning,
|
||||
not an error. The patch's validity depends on harper-core 2.5.0's exact transitive graph. Whoever
|
||||
bumps harper-core in one repo has to know to re-audit the stub versions, and there is no test in
|
||||
either repo asserting the patch is still applied. A stale stub does not fail the build; it quietly
|
||||
pulls several hundred crates and an LLVM toolchain back into the graph, and the symptom is a build
|
||||
that got slow. Two copies means the bump happens twice, on two different days, by which time the
|
||||
comment explaining the pin has been read once and skipped once.
|
||||
|
||||
This is the strongest single argument for a shared crate in the audit: not because the code is
|
||||
large, but because the fragile fact needs one owner. A `margin-grammar` crate would carry the
|
||||
harper pin, the two stubs, the patch section, and one integration test asserting `cubecl-cpu`
|
||||
resolves to the stub version.
|
||||
|
||||
## Frontend
|
||||
|
||||
### Typst converters: no shared code, and one real bug
|
||||
|
||||
`margin/src/export/typst.ts` is 421 lines (335 of code).
|
||||
`margin-editor/src/export/typst.ts` is 808 lines (486 of code).
|
||||
Identical in order: 9 lines, 2%.
|
||||
|
||||
They are genuinely different documents. margin writes a book: trim sizes (typst.ts:16-21), a title
|
||||
page, chapter and part openers, a generated table of contents that queries `<chap>` metadata
|
||||
(typst.ts:130-239). margin-docs writes an A4 document: callouts, toggles, task lists, tables, code
|
||||
surfaces, mermaid diagrams, mitex math (typst.ts:206-327). Nothing about either preamble is
|
||||
shareable and neither should be.
|
||||
|
||||
The one identical fragment is the image extension sniffer, 5 lines: margin typst.ts:240-244
|
||||
(`imageExtension`) and docs typst.ts:342-347 (`extensionOf`).
|
||||
|
||||
The escaping philosophies are opposites, and docs' header says so directly (typst.ts:6-14): it has
|
||||
no `esc` "that sprinkles backslashes through markup the way the sibling book exporter does".
|
||||
Nothing in docs writes user text into markup; every character leaves through `str`
|
||||
(typst.ts:98-110), which builds a Typst string literal, and a string literal has no syntax inside
|
||||
it. margin escapes into markup with a character class (typst.ts:23-34): `INLINE_SPECIAL` covers
|
||||
`\ # $ * _ \` < > @ ~ ( ) [ ]`, `guardLineStart` handles a leading `= - + /` and a leading `1.`.
|
||||
|
||||
margin's `str` is `JSON.stringify` (typst.ts:36-38), and that is a bug. Typst's string literal
|
||||
resolves exactly `\\`, `\"`, `\n`, `\r`, `\t` and `\u{...}`, and an escape it does not recognise it
|
||||
copies through as literal text
|
||||
(`typst-syntax-0.14.2/src/ast.rs:1248-1268`, the `_ => out.push_str(s.from(start))` arm).
|
||||
JSON.stringify emits `\b`, `\f`, and `\uXXXX` for every other C0 control, for U+2028 and
|
||||
U+2029, and for a lone surrogate. Every one of those lands in the PDF as the literal backslash
|
||||
sequence instead of the character it stood for. There is no compile error to catch it. docs' `str`
|
||||
(typst.ts:98-110) emits `\u{...}` and runs `sanitize` (typst.ts:80-87) to replace lone surrogates
|
||||
first, precisely because they survive neither the IPC JSON nor UTF-8 on the other side. margin
|
||||
carries a book title straight into `str` at typst.ts:136, and an href at typst.ts:57.
|
||||
|
||||
Secondary: margin does not neutralise Typst's markup shorthands, so `--` in a manuscript becomes an
|
||||
en dash and `...` becomes an ellipsis in the PDF without the author asking. Arguably desirable in a
|
||||
book; it is silent either way.
|
||||
|
||||
Image handling also diverged. margin only ever sends inline base64 from data URLs
|
||||
(typst.ts:275-301, `ImageInput.data: string` at `margin/src/ipc.ts:10-13`). docs sends a path for a
|
||||
file-backed image and bytes only for things with no file, such as a rendered mermaid SVG
|
||||
(typst.ts:357-396, `ImageInput.data: string | null` at `margin-editor/src/ipc.ts:244-248`). The
|
||||
path variant is what makes the root guard in docs' pdf.rs necessary and is why the two DTOs cannot
|
||||
merge without a decision.
|
||||
|
||||
### ExportPreview: the most duplicated file in either repo
|
||||
|
||||
`margin/src/components/ExportPreview.tsx` is 336 lines (307 of code).
|
||||
`margin-editor/src/components/ExportPreview.tsx` is 448 lines (342 of code).
|
||||
Identical in order: 200 lines, 65% of the smaller.
|
||||
|
||||
docs' header (lines 1-19) states outright that the sibling answers Export with the same panel for
|
||||
the same reason. Shared verbatim or near-verbatim: the `Frame` interface, `measureEditorPane`
|
||||
against `measurePane` (margin:40-47, docs:64-71, identical but for the name), the zoom constants
|
||||
and step, the whole ctrl-wheel and gesture accumulator block (margin:75-129, docs:117-180, differing
|
||||
in one identifier), the pdf.js page render loop with `RenderTask` cancellation, the `ResizeObserver`
|
||||
on `.editor-pane`.
|
||||
|
||||
The drift is mostly docs adding: StrictMode-safe compile-once refs (docs:113-135), lazy pages via
|
||||
`AHEAD`, an overlay key context, toast integration. margin adds `unsupportedScripts` messaging
|
||||
(margin:129 onward, typst.ts:307-334) which docs does not have.
|
||||
|
||||
pdf.js loading is the one place the drift is a cost margin pays every launch. margin imports
|
||||
`pdfjs-dist` and the worker URL at module scope in ExportPreview.tsx and sets
|
||||
`GlobalWorkerOptions.workerSrc` at line 18, so roughly 1.5M of reader is in the main bundle whether
|
||||
or not anyone opens the panel. docs has `margin-editor/src/pdfjs.ts`, 27 lines, which dynamic-
|
||||
imports both and caches the promise (pdfjs.ts:17-26). Two surfaces use it there. docs is ahead and
|
||||
the fix is 27 lines.
|
||||
|
||||
### Proofing on the frontend: same problem, two solutions, no shared code
|
||||
|
||||
- `margin/src/editor/proofing.ts` (139 lines) is a decoration plugin only. The driving loop lives in
|
||||
`margin/src/components/EditorView.tsx:137-255`: a debounce, a whole-document pass, a `setTimeout`.
|
||||
- `margin-editor/src/editor/proofing.ts` (642 lines, 344 of code) holds the plugin plus block
|
||||
batching into 8000-character runs (proofing.ts:85-88, 201-225), two module-level caches keyed by
|
||||
paragraph text (125-126, 253-259), a pass sequence number, and keyboard menu opening. 17 lines
|
||||
identical in order, 13%. The only common line of substance is `Decoration.inline` over a mapped
|
||||
span.
|
||||
- `margin/src/proofing.ts` (112 lines) has no counterpart at all. `docText` and `mapOffset`
|
||||
(proofing.ts:39-73) flatten the whole document to one string with a `Segment` table to map code
|
||||
point offsets back to ProseMirror positions. docs solves the same offset problem per block inside
|
||||
proofing.ts:154-251. Genuinely the same problem solved twice, in incompatible shapes.
|
||||
|
||||
`ProofPopover.tsx`: margin 76 lines (68 of code), docs 292 (184). 29 identical in order, 42%. Both
|
||||
portal to `document.body`, clamp to the window, humanise Harper's CamelCase category the same way
|
||||
(margin:6-8 `humanize`, docs:57-63 `readableKind`, docs adding `0-9` to the class), render `""` as
|
||||
"Remove" (margin:58, docs:70), and lay out suggestions then actions. docs adds arrow-key walking,
|
||||
the pointer-versus-chord focus split, and a store. margin's "Remember" writes to its own dictionary
|
||||
file; docs' "Learn Spelling" writes to the system.
|
||||
|
||||
### Editor and TipTap
|
||||
|
||||
`src/editor/extensions.ts`: margin 28 lines, docs 180. 12 lines identical in order, and those 12
|
||||
are the StarterKit and Placeholder imports and the `configure` skeleton. The schemas are not
|
||||
comparable: margin uses StarterKit's nodes plus Figure, ParagraphIndent, TextAlign; docs generates
|
||||
one TipTap extension per entry in its own frozen `src/model/schema.ts` and switches all of
|
||||
StarterKit's schema off (extensions.ts:128-147), because the markdown bridge is written against
|
||||
that contract.
|
||||
|
||||
margin-mail's editor is `margin-mail/src/screens/Editor.tsx`, 95 lines: one `StarterKit.configure`
|
||||
with `heading: false` and `horizontalRule: false` (Editor.tsx:41-48), no toolbar, no proofing, no
|
||||
export. Its own comment (Editor.tsx:8-11) points at margin's extensions.ts as the model. Nothing to
|
||||
share but the version pin, and the pins already disagree: margin `^3.27.1`, margin-docs pinned
|
||||
`3.30.2`, margin-mail `^3.31.2`, across all five `@tiptap/*` packages.
|
||||
|
||||
Two frontend pairs outside the brief are worth naming because they are more duplicated than
|
||||
anything in it:
|
||||
|
||||
- `src/editor/search.ts`: 217 against 235 code lines, 206 identical in order, 94%. docs' header
|
||||
(search.ts:6-7) says "Ported from margin's editor/search.ts. The only change of substance is the
|
||||
name of the last command". The rest of the diff is prettier's trailing commas and a return type.
|
||||
This is the highest-similarity file pair in either repo.
|
||||
- `src/editor/paste.ts`: 70 against 163 code lines, 51 identical, 72%.
|
||||
- `src/escape.ts` is byte-identical, 36 lines, in margin, margin-docs and margin-calendar.
|
||||
|
||||
### Fonts on the frontend are already shared, and only there
|
||||
|
||||
`margin/shared/src/fonts.ts` (233 lines) is the single list of the six bundled families, the
|
||||
`FontRef` encoding, the pairings and `fontsUsed`. All three UI apps import it: margin, margin-docs
|
||||
and margin-mail (`margin-mail/src/screens/Settings.tsx:7-12`). This is the model for what a shared
|
||||
Rust crate should look like, and its own header (fonts.ts:3-7) makes the argument: four lists in two
|
||||
repos cannot be kept honest by hand.
|
||||
|
||||
The Rust side is the half that never got done. The same six ids are re-declared as `include_bytes!`
|
||||
in margin pdf.rs:9-25 and docs pdf.rs:52-82, and the family list command exists three times. The
|
||||
bytes are duplicated on disk five times: 6.8M in each of `margin/public/fonts`,
|
||||
`margin-editor/public/fonts`, `margin-mail/public/fonts` and the `margin/shared/fonts` master, plus
|
||||
1.6M of static cuts in `margin-editor/src-tauri/fonts`. `margin/shared/bin/sync-fonts.mjs` is the
|
||||
copier.
|
||||
|
||||
## EPUB
|
||||
|
||||
`margin/src-tauri/src/epub.rs`, 88 lines. Two commands: `package_epub` zips a list of
|
||||
path/data/encoding records, `unzip_epub` reads one back. The only EPUB-specific facts are the
|
||||
stored-not-deflated `mimetype` entry written first (epub.rs:29-31) and the text-extension list
|
||||
(epub.rs:15-23). Nothing in it knows what a Book is.
|
||||
|
||||
So it is general in principle and margin-only in practice. It has one consumer, the frontend that
|
||||
feeds it is entirely Book-shaped (`margin/src/export/epub.ts` at 18733 bytes and
|
||||
`margin/src/import/epub.ts` at 17738), and no other app in the suite produces or reads an EPUB.
|
||||
Sixty lines of zip plumbing is not a crate. Leave it.
|
||||
|
||||
## Markdown and the remark stack
|
||||
|
||||
`margin-editor/src/markdown` is 2737 non-test lines (index 157, parse 597, serialize 1471, handlers
|
||||
420, frontmatter 92) plus roughly 8400 lines of tests. It depends on unified, remark-parse,
|
||||
remark-stringify, remark-gfm, remark-frontmatter, remark-math and mdast-util-to-markdown, none of
|
||||
which appear in margin or margin-mail.
|
||||
|
||||
It is not shareable and should not be made so. Every line of it is written against
|
||||
`margin-editor/src/model/schema.ts`, which the module's header (index.ts:29-36) treats as a frozen
|
||||
contract, and its four stated invariants (opening writes nothing, serializing is stable, frontmatter
|
||||
passes through opaque, nothing is silently dropped) are promises about a folder of markdown files.
|
||||
margin has no markdown at any point in its pipeline and mail composes HTML. If mail ever gained
|
||||
markdown compose it would want a serializer, not this parser, and the schema it serialized from
|
||||
would be StarterKit's rather than the contract's.
|
||||
|
||||
## What is worth extracting
|
||||
|
||||
Ordered by ratio of risk removed to work done.
|
||||
|
||||
1. The harper pin, the two stub crates and the `[patch.crates-io]` block. Smallest code, largest
|
||||
consequence, and the only duplication here that fails silently and expensively.
|
||||
2. The AppKit menu walk from writingtools.rs: `submenu_named`, `edit_menu`, `writing_tools_menu`,
|
||||
21 lines already byte-identical, plus the availability probe docs has and margin does not.
|
||||
3. fontdb: `system_db`, the installed-family list (three copies today), the four-style face loader,
|
||||
and the source-path dedup key margin is missing. Take docs' version, drop the incorrect comment
|
||||
at fonts.rs:84-86.
|
||||
4. `utf16_to_codepoint` and the NSSpellChecker `check` body, 12 lines already identical and about 40
|
||||
more that differ only in constants and the return type. Needs one shared `SpellIssue`.
|
||||
5. Typst diagnostic formatting, 16 identical lines, and the compile-and-render call. Not the
|
||||
preambles and not the converters.
|
||||
6. The nine static font cuts, so margin's PDFs stop exporting every heading at weight 400. This is
|
||||
an asset and a build step more than a crate, but it is the change a reader of the two PDFs would
|
||||
notice first.
|
||||
|
||||
Frontend, separately from any Rust crate: pdf.js lazy loading (27 lines, docs already has it),
|
||||
ExportPreview's frame-and-zoom shell (65% identical), and margin's `str` bug in export/typst.ts:36.
|
||||
Reference in new issue
Block a user