diff --git a/.tool-versions b/.tool-versions index 3688e5c9..86e31f63 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1 +1 @@ -bun 1.4.4 +bun 1.4.5 diff --git a/AGENTS.md b/AGENTS.md index c9851b13..df49a38f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ - TinyDocy is a lightweight collaborative editor testbed for docs.plus, positioned as an online-capable demo where abuse and OWASP-minded guardrails matter; stack is Next.js 16 App Router + Tiptap 3 + Yjs + Hocuspocus + SQLite, with Bun runtime - Persistence is Hocuspocus 4 WebSocket + SQLite via custom `bun run hocus` (`scripts/hocus-server.ts`: `Bun.serve` + `Hocuspocus.handleConnection`, `bun:sqlite`) with fetch/store persistence in `lib/hocus-persistence.ts` on the `extension-sqlite`-compatible `documents` table, custom WS guardrails in `lib/security/*`, and optional official `extension-logger` / `extension-throttle` / `extension-redis` toggled by `HOCUS_*` env; local dev starts both services with `make dev` (`make -j2`) -- Runtime: everything runs on Bun ≥ 1.4.4 (`.tool-versions`) — `bunfig.toml` `[run] bun = true` makes `bun ` and `bun run` start package bins (Next.js, ESLint, Playwright, commitlint) on the Bun runtime, but plain `bunx` ignores it and uses Node when installed, so call local bins as `bun ` (e.g. `bun playwright test`) and remote ones as `bunx --bun`; CI puts a failing `node` stub on PATH after install so nothing falls back to Node; SQLite is `bun:sqlite` everywhere (`openSqlite()` in `lib/sqlite-open.ts`, used by the Next.js API, Hocus and scripts; `.get()` returns `null` for no row); the app `tsconfig.json` uses Bun types and `bun run typecheck` checks it plus `tsconfig.sw.json` +- Runtime: everything runs on Bun ≥ 1.4.5 (`.tool-versions`) — `bunfig.toml` `[run] bun = true` makes `bun ` and `bun run` start package bins (Next.js, ESLint, Playwright, commitlint) on the Bun runtime, but plain `bunx` ignores it and uses Node when installed, so call local bins as `bun ` (e.g. `bun playwright test`) and remote ones as `bunx --bun`; CI puts a failing `node` stub on PATH after install so nothing falls back to Node; SQLite is `bun:sqlite` everywhere (`openSqlite()` in `lib/sqlite-open.ts`, used by the Next.js API, Hocus and scripts; `.get()` returns `null` for no row); the app `tsconfig.json` uses Bun types and `bun run typecheck` checks it plus `tsconfig.sw.json` - Root `README.md` is the only README (reader-first: features, quick start, architecture, config tables, deploy requirements, docs index); release history lives in `CHANGELOG.md`; tests docs live in `tests/TESTING.md`; operations runbooks live in `docs/operations/` (abuse guardrails, analytics, service worker); avoid full PM2/Traefik step-by-step guides - Code quality/tooling: Biome for formatting/linting, ESLint scoped to Next.js rules, strict TypeScript; Husky runs lint-staged pre-commit and commitlint on commit-msg - Naming and exports: kebab-case files, PascalCase components with title-case acronyms, camelCase hooks/utils, named exports by default @@ -46,7 +46,7 @@ - **Desktop renderer:** the static export (`bun run build:desktop`, `NEXT_PUBLIC_APP_TARGET=desktop`). - **Library UI:** `components/library/`, shared with the web library, styled in its own CSS so the web build stays +0 B. - **Landing dark:** server and library features ship behind flags that default to off, because every merge deploys. -- Editor-chunk budget: the fence is `main` plus the D23 ledger (details spec §1 rule 5). As of 2026-11-22 only about 6 B of slack remains beyond the unspent ledger lines, so a PR without a ledger line must add 0 B to the editor chunk group (lazy chunks). Spending more needs an owner-approved ledger amendment. +- Editor-chunk budget: the CI fence (`scripts/check-editor-chunk-size.ts`, `main` plus the D23 ledger in details spec §1 rule 5) is a tripwire, not a gate on product work: the owner decided on 2026-11-22 that byte budgets must not block features or need their approval. A PR that grows the editor chunk group measures the growth with clean builds, records a ledger line with the measured bytes and raises `EDITOR_CHUNK_LEDGER_BYTES` by the same amount in the same PR; keep lazy-loading what is cheap to keep lazy, but never trade visible behaviour or UX to save bytes, and call out growth above about 1 KB gz of first load in the PR body - Merging many parallel PRs: batch reviewed PRs on an `integrate/…` branch so CI runs once (GitHub then marks the included PRs merged). `main`'s CI no longer cancels a started run (#143), so every merge's run finishes and the newest commit deploys. Once the owner turns on the merge queue, queue PRs instead of hand-built batches. - Tabs are synced through Y.Doc `global-tabs` behind the `DocumentIndex` port (`lib/platform/document-index.ts`; web implementation `GlobalTabsIndex` in `lib/platform/web/global-tabs-index.ts`, React adapter `useSyncedTabs`, contract suite in `tests/unit/platform/`) with Playground fixed at index 0; `activeTabId` is local per user; close operations call `DELETE /api/documents/[id]`, which is HTTP rate-limited separately from WS throttles on Hocuspocus; the canonical editor implementation lives in `components/document-editor/` (legacy `components/tiptap-templates/simple` has been removed) - Simplified toolbar (contract A15) is CSS only: `data-toolbar-density="simple"` on the row applies the ladder's T2–T4 `collapse-tier` mixin at every width (the ladder still collapses further below T4/T5); the setting is the `toolbarDensity` slot in `tinydocy-ui` (survives Forget), read by `useToolbarDensity` (`useSyncExternalStore`, no ready flag: the editor is `ssr: false` and a ready effect would flash the full row); `view.simpleToolbar` writes it, ⋯ shows it as a checkbox from the lazy menu chunk diff --git a/CHANGELOG.md b/CHANGELOG.md index ca4eadaf..ee7ce78d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,234 @@ since the previous tag. ## [Unreleased] +### Desktop storage: lock waits, and derived rows without the fsync + +Two Windows soak failures on #170 and #171, fixed in the engine. + +- **Desktop:** every SQLite connection waits up to 3 s for a lock + (`busy_timeout`) instead of failing at once. On Windows a scanner or a + process still letting go of a new file held it for a moment, and the + next write failed with "database is locked" (T4-copy). TRUNCATE + checkpoints still never wait, so a running daily copy can't stretch a + quit. +- **Desktop:** derived rows (`derive.put`) commit at `synchronous=NORMAL`. + They are a cache: a power cut loses them and their `derived_seq` + together, and the document is derived again. Backlinks queued behind a + derive no longer wait for F_FULLFSYNC or FlushFileBuffers (T21: 4.9 ms → + 0.9 ms median on an Apple silicon Mac). Everything else stays FULL; the + architecture spec's D-A6 records the amendment. +- **Tests:** contention tests hold a lock from a second process (a write + and the daily copy wait it out; a reader never slows shutdown), and the + derive commit's `synchronous` trace is checked. T21 runs its harness 5 + times on one seeded library and gates on the median of the runs, with + p95 over every round and the derive's SQL time reported. + +**Deploy:** none. + +### Selection bubble P1: Style ▾, strike, code, clear and a gap-free link field + +The selection bubble gains the rest of its v2 row (spec +`2026-11-17-bubble-and-quick-insert-design.md` §7, v1 contract A21): +Style ▾ │ B I U S ‹› Tx │ A▁▾ 🔗 🖌, and named colour rows. With P2–P4, the +editor chunk group grows 26 B: 394,545 B gz against 394,519 B on `main` at +`2764fb5`. That is a D23 ledger line the owner approved on 2026-11-22 +(`EDITOR_CHUNK_LEDGER_BYTES` 2,205 → 2,231 B), covering the style-lift hook, +List and Quote in the style value and the Insert sheet's nested load. The +per-item lift behind the text styles is injected from the lazy chunks. +Merging `main` `2764fb5` first measured +981 B: the lazy menus imported +lucide's Type, which made Turbopack split the editor group's small modules +into two files. The menus now draw their own copy of the icon +(`components/smart-toolbar/type-icon.ts`). The +"/" chunk is under its 7 KB budget, 7,099 B gz by its own test +(`SLASH_BUDGET=1`; 7,334 B on the P4 tip): the phone Insert sheet now gets +the "/" items at load instead of importing them. The bubble chunk is +14,860 B gz (9,797 B on `main` at `2764fb5`) and the colour chunk +6,580 B gz (3,639 B). + +#### Added + +- **Bubble:** Style ▾ shows the selection's block type as one word (Text, + H1–H6, Title, List, Quote, Code, Mixed), sized once to the longest word, + and opens Turn into away from the text. Strike, inline code and clear + formatting join B, I and U. A comment slot is reserved at the end and + renders nothing until the comments work registers `comment.add`. +- **Turn into:** one menu body for the bubble and the row's Text style ▾: + Text, Heading 1–3, More headings ▸ (4–6), the three lists, Quote and Code + block, with icons, shortcuts and a trailing ✓, and no Markdown chips. + The row keeps Your formats below them. +- **Text styles:** Text and the headings turn the selected list items or + quote lines into that block, lifted to the top level, in one undo step, + wherever they run (Turn into, the palette, the "/" menu, the phone's + Style rows, the shortcuts); unselected items and lines stay in their list + or quote, and a range across a paragraph and a list converts every + block. The lift loads with the bubble (on idle), the menus, the phone + bar or the palette; before any of them, a style shortcut or a "/" pick + in a list restyles in place, as before. +- **Turn into:** after select all it converts everything but the title + ("The title stays a heading."); Code block and Quote lift list items and + quote lines first; Code block over formatting says "Formatting + removed"; a range with table cells converts around them ("Table cells + keep their type."). Each pill has Undo. Opened toward the text, it goes + past the selection's lines, never over them. +- **Colour:** the bubble's and the row's colour menus are named rows: + Recent, then Text | Highlight side by side (Default and No highlight + first, five colours each, the rest under More colours ▸ and More + highlights ▸), with ✓ on the current value, typeahead and the hover + preview. From the bubble the menu opens below or above the selection, + never over it. Enter or Space picks and closes the menu (a change from + O4, spec §7.10), and the pick is announced with Undo. +- **Phone:** the Aa sheet keeps the swatch grid, six per line, names the + current colours under it, and each tap shows a pill naming the colour + ("Teal text") with a 44px Undo. +- **Bubble:** a keyboard selection (Shift+arrows, ⌘A) shows the bubble + 300 ms after Shift is released and the selection is still, never while + Shift is held or a key repeats. +- **Bubble:** Alt+F10 shows a bubble that is still waiting (its delay) at + once, with focus on Style ▾. +- **Bubble:** applying inline code over linked or coloured text says "Link + and colour removed" (or "Link removed", "Colour removed") on the status + pill, with Undo. + +#### Changed + +- **Text style:** the paragraph style is named "Text" everywhere (the + registry label, so the row, the palette, the "/" menu and the phone + agree), and the row's face reads "List" or "Quote" inside a list or + quote, as the bubble's does. +- **Bubble:** inside inline code, B, I, U, S, colour and link say "Inline + code can't take other formatting." instead of the generic refusal; the + Paint format brush says the same on inline code on every surface + (phone cells included), where it said "Code has no formatting." +- **Bubble:** a lighter edge in light mode, its own darker-than-page + surface in dark mode (`oklch(0.24 0 0)`, edge `oklch(1 0 0 / 36%)`), focus + rings drawn inside each button, a dashed bar for a mixed mark, and a + `CanvasText` edge under forced colours. +- **Bubble:** motion follows the O10 token: 120 ms scale-in from the anchor + side, 80 ms fade out, and none at all under reduced motion + (`prefers-reduced-motion` or `data-motion="reduce"`). + +#### Fixed + +- **RTL:** the "/" menu's Markdown hint caps sit at the row's inline end + again (they had drifted next to the labels); the row ⋯ menu's rows line + up; menu shortcut glyphs read left to right; the phone Insert sheet keeps + a note ("3 × 3") next to its label, so it no longer reads as the next + column's. + +- **Bubble:** clicking 🔗 and pasting or typing a URL at once no longer + replaces the selected words: focus moves to the link field in the click + itself, and the bubble hides in the same task. +- **Bubble:** Esc while the bubble is still waiting to show (its delay or + a keyboard selection's settle) cancels it. + +### Phone Insert sheet, Style first in the Aa sheet, words on tablet stand-ins (P4) + +Phase P4 of the selection bubble and quick insert design (spec §8.3, §13.1, +§13.2). Phones get an Insert sheet in place of the desktop dropdown, the Aa +sheet leads with Style, and touch tablets name the row's unclear stand-ins. + +#### Added + +- **Phone:** the bar's Insert cell opens a bottom sheet + (`components/smart-toolbar/phone/insert-sheet.tsx`): the "/" menu's items + as a two-column grid of 44px cells. Suggested (the "/" menu's own rows for the + recent kinds) comes first when there are any, then "Blocks" (the caret's block is empty) + or "Turn into" (it has text), then Insert. Kinds that can't run here show + their reason on a second line. Table and Embed open their step inside the + sheet; Diagram lists the templates. A pick closes the sheet and puts the + caret in the new block, with the keyboard back. "/embed" on a phone opens + the sheet at the embed step. The sheet rides above the keyboard while the + link field has focus, and a pick refused since it opened (a + collaborator's edit) says why inside it. Its cells and steps are their own + lazy chunk, fetched when the browser is idle and on the cell's press. +- **Touch tablets:** on a coarse pointer from 768px, the row's stand-ins + read `T Format ▾`, `¶ Layout ▾` and `⫶ Block ▾` (O8 a), from first paint + (CSS in `app/globals.css`). Below an 848px window the row has no room for + their 120px in a code block or table, so (owner decision, option b) Redo + moves from the row to the top of ⋯ there, and the list button keeps only + List ▾. ⌘⇧Z still redoes. Desktop's ⋯ menu is unchanged. + +#### Changed + +- **Toolbar:** the stand-ins are named "Format" (was "More text + formatting"), "Layout" (was "Paragraph") and "Block: Section tools" and so + on (was "Section tools"), so each name begins with the word shown on it + (WCAG 2.5.3). The phone's slot cell takes the same name. +- **Phone:** the Aa sheet starts with Style: Text and H1–H3, a More + headings disclosure for H4–H6 (open when the current style is one of + them, closable all the same), then the lists and Quote, the current style + pressed. Colours follow. Both sheets end in a 16px fade while they scroll, + above the home indicator. + +Measured against `main` at 84a9458, with the "/" menu's P2 and the grouped ⋯ +menu's P3 work merged in: the editor chunk group gets 23 B smaller (393,995 B +gz against 394,018 B). The phone bar chunk grows 978 B gz (18,175 B), and the +sheet body is a chunk of its own, 3,926 B gz. The app's CSS grows 494 B gz +(16,487 B): 138 B for the tablet words and 71 B for the touch step that +moves Redo; the rest is P2 and P3. + +### Quick insert P2: Suggested, the "/" hint and footer, and the `+` on empty lines + +The "/" menu gains what the second reference set showed it lacked, and a +pointer path to it (spec `2026-11-17-bubble-and-quick-insert-design.md` +§8.2, §8.5; v1 contract A20). The editor chunk group is unchanged +(393,817 B gz, −3 B against `main` at `1548d5e`); the slash chunk grows +from 5,772 B to 7,041 B gz, and its test budget (`SLASH_BUDGET=1`) is +raised from 6 KB to 7 KB (7,168 B) by the owner's decision of 2026-11-22. +The growth by feature (gz): the `+`'s undo handling 336 B, the footer +269 B, the "Type to search" hint 258 B, Suggested 154 B, the RTL anchor +66 B; "New" badges compile out while none is declared. The bubble chunk, which now mounts the +`+`, from 9,798 B to 10,930 B gz. The footer lives in `slash-menu.tsx` +rather than its own `slash-footer.tsx` (the plan's file list): it shares +the menu's state and placement, and a separate module would only add +bytes. + +#### Added + +- **"/" menu:** a Suggested section leads with your last 3 inserted kinds + (table, image, divider…) that can go at the caret; each stays in its own + section too. A new writer sees no Suggested section; "Forget my choices" + clears it. A query hides it and puts a recent kind first among equal + matches. +- **"/" menu:** "Type to search" sits after the "/" while the query is + empty and nothing follows the caret (never during IME composition); a + pinned footer teaches the active row's Markdown shortcut ("Type ## then + space for Heading 2") and has a Close button (Esc still works). On touch + the footer is only a 44 px Close. Hints stay left to right in RTL ("1.", + never ".1"). +- **"/" menu:** rows can carry a "New" badge until a date, hidden once you + have used that kind; none are declared yet. +- **`+` on an empty line:** on a mouse or trackpad, a `+` in the start + margin of an empty paragraph (in line with the heading grips; the right + margin in RTL) types the "/" for you, so the ordinary "/" menu opens. It + shows beside the caret 300 ms after you stop typing, or under the + pointer after a 150 ms rest, never in the title, a list, a quote or a + table cell, and never on touch. The "/" it types is an ordinary one: a + query, a pick, Esc and undo work as after a typed "/". Only with the + query still empty, Esc removes it without an undo step and a pick + undoes to the empty line. It is mounted by + the lazy bubble chunk's desktop wrapper, so it appears once that chunk + has loaded (a deviation from the spec's §15 file split, which put it in + `SlashMenuHost`: that would have grown the editor chunk). +- **Insert menu:** each row shows its "/" alias ("/table", "/code"). + +#### Changed + +- **"/" menu:** 320 px wide (was 288); in an RTL paragraph its right edge + is at the "/". +- **Placeholder:** an empty paragraph reads "Type / for blocks" (was + "Type something..."). + +### Row ⋯ menu in three labelled groups (BQ4) + +The row's ⋯ menu is now Text (Superscript, Subscript, Inline code, Clear +formatting, Paint format), View (Simplified toolbar, Appearance) and Help +(All actions…), with "Forget my choices…" alone at the end. Each group has a +visible heading and `role="group"` with the same label, and every row keeps a +16 px leading slot so the labels line up (Simplified toolbar shows its check +there). Nothing is added or removed. Page width follows with the preferences +work. Editor chunk +1 B against `main` at `84a9458`, from chunk-name hashes only; no eager code. + ### Desktop P2.6f: repair and rebuild the library Repair and rebuild for the format-2 library (offline data-model revision @@ -88,6 +316,148 @@ group +152 B gz on its D23 line (measured +152 B on `main` at `1548d5e`, - **Editor budget:** the D23 ledger gains P2.12's 152 B line (2,205 B, or 2,285 B with M19's conditional line), owner-approved 2026-11-22. +### Bun 1.4.5 (security release) + +TinyDocy moves from Bun 1.4.4 to 1.4.5, released 2026-11-19. 1.4.5 is a +security release covering HTTP/3, TLS, DNS, zlib and BoringSSL, and it moves +`bun:sqlite` from SQLite 3.53.4 to 3.54.1 (on macOS, Bun 1.4.5 uses the +system SQLite, 3.54.0 on the machine this was tested on). `bun.lock` is +unchanged. Deploys now refuse to run on a host whose Bun is not the one the +commit pins. + +#### Changed + +- **Runtime:** `.tool-versions`, `packageManager` and `engines` pin Bun + 1.4.5. CI, the nightly and the desktop workflows read `.tool-versions`. +- **Deploy:** `scripts/deploy.sh` compares the host's `bun --version` with + the Bun the commit's `.tool-versions` pins. If they differ, it exits 11 + before it creates the build checkout, installs anything or restarts Hocus. + The deploy runbook has a new + [Upgrading Bun](docs/operations/deploy-runbook.md#upgrading-bun) section. + +#### Added + +- **Tooling:** `bun run test:fast` (`bun test --parallel`, which also + isolates each file) and `bun run typecheck:fast` (`bun check --no-script` + over the same four projects as `bun run typecheck`). They + are for local speed only. CI still gates on `bun run test` (serial) and + `bun run typecheck` (`tsc`), because `bun check` follows TypeScript 7 + semantics. +- **Tests:** `tests/unit/ci/deploy-bun-version.test.ts` runs the real + `deploy.sh` against a throwaway repository and checks that a version + mismatch or a missing pin stops it before the build. + +#### Security + +- Bun 1.4.5's fixes to HTTP/3, TLS, DNS, zlib and BoringSSL reach the Next.js + server, Hocus and the purge on the next deploy. +- SQLite 3.54 refuses `ALTER TABLE` on columns named `rowid`, `oid` or + `_rowid_`. No code does that: `desktop/storage`, `lib` and `scripts` only + read `rowid` in `SELECT`s (`copy-library.ts`), and the only + `ALTER TABLE` (a test migration) adds a column named `extra`. +- The desktop storage and `scripts/` tests (193), including the purge's + `VACUUM INTO` backups, which the test reopens and compares, pass on the + macOS system SQLite. CI covers Linux on SQLite 3.54.1. +- Bun 1.4.5 validates custom root CAs more strictly. TinyDocy passes no + custom CA (`ca`, `NODE_EXTRA_CA_CERTS`, `rejectUnauthorized`) anywhere. + +#### Deploy + +- **Done 2026-11-22:** the owner installed Bun 1.4.5 on the host with the + pinned installer, before this merged: + ```bash + ssh @ 'curl -fsSL https://bun.com/install | bash -s "bun-v1.4.5"' + ssh @ '~/.bun/bin/bun --version' # prints 1.4.5 + ``` + The running apps switch to 1.4.5 when a deploy next restarts them. Any + deploy does that, including this one. No other step is needed: the + automatic deploy of this merge is enough, or run `gh workflow run deploy.yml`. +- The deploy that ships this change still runs the host's previous + `deploy.sh`, which has no version check. The check applies from the + deploy after it. From then on, a deploy on a host that is not on 1.4.5 + fails with exit 11 and changes nothing on the host. +- Every later Bun upgrade follows the runbook: merge the `.tool-versions` + change with automatic deploys off, upgrade the host, then deploy. + +### Links between documents LK1: the document links core + +The pieces desktop and the web library need to link one document to +another (search-linking design §4.1–§4.7, §5, D25). Nothing in the web +sandbox uses them: the editor gains a `linkHost` pass-through that the web +never sets, so the web keeps #168's `isWebLink` policy. Editor chunk group +−3 B gz against `main` 1e535b4 (its D23 ledger line is 60 B); web CSS +unchanged. + +#### Added + +- **Links:** `lib/links/doc-link.ts` parses `tinydocy:doc/`, + `tinydocy:doc/#` and `tinydocy:here#` + strictly, tells a form from a later version apart from an invalid one, + and recognises our scheme behind whitespace, controls, zero-width and + bidi characters in any case, so none of them reaches an external opener. +- **Links:** `createLinkHost` (`lib/links/link-host.ts`) builds the + Hyperlink options a host passes the editor, with one identity for its + life: + - `isAllowedUri`: document links that parse, and https, http and mailto + (`isWebLink`), applied by #168's `LinkPolicyHyperlink` to commands, + paste, rendering and opening. No `protocols`, so typing `tinydocy:` + never autolinks; + - `linkIcon`: one icon per state, in the link's own colour — FileText + (opens), Hash (`here#`), FileMinus (In Trash) and FileQuestion (Not + available, Not a valid link, Needs a newer version); the states that + don't open are `role="img"` with their label, and `refreshIcons` + redraws icons and labels after index changes + (`createIconRefresher` debounces it, 100 ms); + - `navigate`: ⌘-click opens in this tab, ⌘⇧-click or middle-click in a + new one, `here#` jumps in place, web links open as before after a + second allowlist check; a link that can't open shows its preview card, + or is announced from the keyboard. One announcement per follow. + `onFollow` gives the shell the source document and a Yjs relative + position for Back; + - `popovers`: a document link's preview shows its title and place + ("Library › folder", In Trash) or why it can't open, with Open, Copy + Link and Remove Link (never the default focus) — never the href or + key. Web links keep the package's preview; + - `openAtHeading` goes to the heading after a document opens, looking it + up again after the first sync before saying "The section this link + pointed to was removed." + - `lib/links/doc-links.css` dashes the underline of links that don't + open, inner styled runs included. +- **Links:** `lib/links/extract-links.ts`, the links-only pass: + `deriveDocument` lists link rows (section, key, heading, text, context; + text capped at 200 characters; deduplicated on key, heading and section, + at most 2,000 per document) and heading rows in one walk, under 8 ms at + 500 headings and 10,000 links. `toLinkRows` and `toHeadingRows` map them + to format 2's `links` and `doc_headings` columns; `linksHash` and + `DERIVE_VERSION` (1) tell when to derive again, and `trackLinkChanges` + marks a document dirty only when its links may have changed. +- **Links:** `stripPrivateDocLinks` turns links to documents that aren't + shared into plain text in one transaction when a document is shared + (D-O8), keeping `here#` links; `countPrivateDocLinks` and + `consentLinksLine` give the consent line ("3 links to your other + documents will become plain text." with Keep Links). +- **Platform:** `LibraryIndex` entries carry their `linkKey`, and the + snapshot lists `trashed` documents. `MemoryDocumentIndex` mints keys and + the contract suite covers both and the snapshot's identity. +- **Desktop:** `RpcLibraryIndex` passes the same suite. `create` mints the + 32-hex `link_key` with the id and sends it, and the engine's `createDoc` + keeps it (refusing a malformed one). `sidebar` returns each document's + `linkKey`, and `trashList` adds `trashed`: every document in the Trash, + alone or in a folder, with its key. No schema change. +- **Editor:** `DocumentEditor` takes an optional, stable `linkHost` and + spreads it into the Hyperlink configuration; it imports only its type + (import-boundary rule). `DocumentEditor` passes its props through as + given, so new props need no plumbing. +- **Links:** `lib/web-link.ts` holds `isWebLink`, shared by the editor + config and the link host so the two policies can't drift. +- **Tests:** unit tests for every module (a navigate table, a no-host + safety test on the real editor, bare Y.Doc derive tests and a timing + budget), and a links view in the library harness (`?view=links`, with a + read-only toggle and `&matrix=1`) with Playwright specs for every state, + the gesture table in both modes, previews, `here#` jumps, the external + opener, and a visual matrix (icon colour, 4.5:1 contrast, dashed runs, + RTL) in light and dark. + ### P2.12 part 1: print stylesheet, block move, word count and the Markdown paste rule Printing (and Save as PDF) now prints only the document. The block move and diff --git a/README.md b/README.md index 4b60ad42..3a26299e 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ documents, so don't type anything private. ## Quick start -Requires [Bun](https://bun.sh) 1.4.4 or later. Node.js is not needed: Next.js, +Requires [Bun](https://bun.sh) 1.4.5 or later. Node.js is not needed: Next.js, ESLint, Playwright and the git hooks run on the Bun runtime (`[run] bun = true` in `bunfig.toml`), and unit tests use `bun test`. diff --git a/app/globals.css b/app/globals.css index 59fb0fee..2dfe8968 100644 --- a/app/globals.css +++ b/app/globals.css @@ -227,3 +227,72 @@ button[aria-pressed="mixed"]::after { color: GrayText; } } + +/* + * Touch tablets (O8 a, spec §13.2): the row's stand-ins whose icons don't + * explain themselves show one fixed word between the icon and the chevron + * ("Format", "Layout", "Block"; each stand-in's name begins with it, WCAG + * 2.5.3, `collapse-menus.tsx`). Here, with the app's first CSS, so the row + * has its final width at first paint and never shifts, at no cost to the + * editor chunk group. + */ +@media (min-width: 768px) and (pointer: coarse) { + :is( + [data-toolbar-group="marks"], + [data-toolbar-group="paragraph"], + [data-toolbar-group="slot"] + ) + > [data-collapse-standin] + [data-toolbar-item]::after { + order: 1; + font-size: 0.8125rem; + font-weight: 500; + } + + :is( + [data-toolbar-group="marks"], + [data-toolbar-group="paragraph"], + [data-toolbar-group="slot"] + ) + > [data-collapse-standin] + [data-toolbar-item] + > svg:last-child { + order: 2; + } + + [data-toolbar-group="marks"] + > [data-collapse-standin] + [data-toolbar-item]::after { + content: "Format" / ""; + } + + [data-toolbar-group="paragraph"] + > [data-collapse-standin] + [data-toolbar-item]::after { + content: "Layout" / ""; + } + + [data-toolbar-group="slot"] + > [data-collapse-standin] + [data-toolbar-item]::after { + content: "Block" / ""; + } +} + +/* + * The touch ladder's last step (owner decision 2026-11-22, option b): the + * words add 120px, which a row narrower than 832px (the row spans the + * window less 16px, so a window under 848px) has no room for in a code or + * table block. There Redo leaves the row for the top of ⋯ (the same query, + * `TOUCH_ROW_REDO_IN_MORE` in `row/row-menu-bodies.tsx`), and the list + * split keeps only List ▾ (one tap more for the last list type). ⌘⇧Z + * still redoes. + */ +@media (min-width: 768px) and (max-width: 847.98px) and (pointer: coarse) { + [data-variant="fixed"] + [data-toolbar-group="history"] + [data-action-id="history.redo"], + [data-variant="fixed"] .st-split[data-list-face] > [data-action-id^="list."] { + display: none; + } +} diff --git a/components/document-editor/document-editor-config.ts b/components/document-editor/document-editor-config.ts index 16272e7b..fa51da8f 100644 --- a/components/document-editor/document-editor-config.ts +++ b/components/document-editor/document-editor-config.ts @@ -71,7 +71,9 @@ import { TitleDocument } from "@/extensions/title-document"; import { TokenHighlight } from "@/extensions/token-highlight"; import { WriteGate } from "@/extensions/write-gate/write-gate"; import { SUBSCRIPT_SHORTCUT } from "@/lib/app-shortcuts"; +import type { LinkHost } from "@/lib/links/link-host-types"; import { lowlight } from "@/lib/lowlight"; +import { isWebLink } from "@/lib/web-link"; import { SafeCodeBlock } from "./safe-code-block"; @@ -95,18 +97,15 @@ const SubscriptByTarget = Subscript.extend({ }); /** - * The web editor's link policy: `https:`, `http:` and `mailto:` only, after - * leading whitespace. A scheme a browser would still read through inner - * whitespace or a leading control (`ht\ttps:`) is refused: the safe side. - * The extension's own check is a denylist, so an `ms-msdt:` or `search-ms:` - * link would otherwise reach the OS. It is `isAllowedUri`, the one policy for commands, autolink and paste - * rules; `LinkPolicyHyperlink` applies the same option to HTML paste and to - * rendering, so a host that passes its own `isAllowedUri` replaces it at all - * three. Parse and render call it with one string and no context (a missing - * href arrives as "undefined" or "null"), so a host policy must not need one. + * The editor's link policy is `isWebLink` (`lib/web-link.ts`). It is + * `isAllowedUri`, the one policy for commands, autolink and paste rules; + * `LinkPolicyHyperlink` applies the same option to HTML paste and to + * rendering, so a host that passes its own `isAllowedUri` replaces it at + * all three. Parse and render call it with one string and no context (a + * missing href arrives as "undefined" or "null"), so a host policy must not + * need one. */ -export const isWebLink = (href: string): boolean => - /^\s*(https?|mailto):/i.test(href); +export { isWebLink }; /** The one protocol check for parse and render: the policy on any value. */ const allows = (options: HyperlinkOptions, href: unknown) => @@ -146,7 +145,7 @@ export const LinkPolicyHyperlink = Hyperlink.extend({ const PLACEHOLDER_TEXT: Record = { heading: "Heading", - paragraph: "Type something...", + paragraph: "Type / for blocks", codeBlock: "Write code...", }; @@ -215,6 +214,12 @@ interface BuildDocumentEditorExtensionsOptions { * freezes). Runs inside the sync binding: record only, never write. */ onInvalidContent?: (error: Error) => void; + /** + * Document links (search-linking §4.1): the host's Hyperlink options for + * `tinydocy:` (isAllowedUri, navigate, linkIcon, popovers). Passed + * through as they are; the web sandbox passes none. + */ + linkHost?: LinkHost; } function createHeadingFilterFoldAdapter() { @@ -246,6 +251,7 @@ export function buildDocumentEditorExtensions({ onFilterChange, onTocUpdate, onInvalidContent, + linkHost, }: BuildDocumentEditorExtensionsOptions) { return [ StarterKit.configure({ @@ -276,6 +282,7 @@ export function buildDocumentEditorExtensions({ rel: "noopener noreferrer nofollow ugc", class: null, }, + ...linkHost, }), InlineCode, SafeCodeBlock.configure({ lowlight }), diff --git a/components/document-editor/document-editor.tsx b/components/document-editor/document-editor.tsx index 2bec8832..580cd1bc 100644 --- a/components/document-editor/document-editor.tsx +++ b/components/document-editor/document-editor.tsx @@ -71,6 +71,7 @@ import { useIsBreakpoint } from "@/hooks/use-is-breakpoint"; import { useToolbarDensity } from "@/hooks/use-toolbar-density"; import { useYjsDocument } from "@/hooks/use-yjs-document"; import { SCROLL_CLEARANCE } from "@/lib/editor-scroll-clearance"; +import type { LinkHost } from "@/lib/links/link-host-types"; import { createSchemaGuard, type SchemaGuardState } from "@/lib/schema-guard"; import { stylesApplied } from "@/lib/styles-applied"; import { setTheme } from "@/lib/theme"; @@ -100,6 +101,11 @@ interface DocumentEditorProps { * guard defers its Yjs repair until it clears. Reading mode sets it. */ readOnly?: boolean; + /** + * Document links (search-linking §4.1), from `createLinkHost`. Keep one + * object for the editor's life: a new one rebuilds the extensions. + */ + linkHost?: LinkHost; /** * The outline overlays the page instead of docking beside it. Decided * by the page frame (`PageFrame`, preferences design §5.9). @@ -178,6 +184,7 @@ function DocumentEditorContent({ playgroundRegenerateTrigger, onPlaygroundRegenerate, readOnly, + linkHost, outlineOverlay = false, statusChip, rejectedReason, @@ -246,8 +253,9 @@ function DocumentEditorContent({ onFilterChange: setFilterState, onTocUpdate: tocStore.set, onInvalidContent: schemaGuard.onInvalidContent, + linkHost, }), - [documentId, ydoc, awareness, tocStore, schemaGuard], + [documentId, ydoc, awareness, tocStore, schemaGuard, linkHost], ); const editor = useEditor({ @@ -479,17 +487,8 @@ function DocumentEditorContent({ ); } -export function DocumentEditor({ - documentId, - onTitleChange, - initialContent, - playgroundRegenerateTrigger, - onPlaygroundRegenerate, - readOnly, - outlineOverlay, - statusChip, -}: DocumentEditorProps = {}) { - const docId = documentId ?? "default"; +export function DocumentEditor(props: DocumentEditorProps = {}) { + const docId = props.documentId ?? "default"; const { ydoc, awareness, provider, synced, serverSynced, rejectedReason } = useYjsDocument(docId); @@ -506,18 +505,13 @@ export function DocumentEditor({ } return ( + // Every prop passes through as given; new ones need no plumbing here. diff --git a/components/document-editor/mobile-toolbar-content.tsx b/components/document-editor/mobile-toolbar-content.tsx index 3076c09c..2c477ca9 100644 --- a/components/document-editor/mobile-toolbar-content.tsx +++ b/components/document-editor/mobile-toolbar-content.tsx @@ -17,6 +17,7 @@ import { import { ActionButton } from "@/components/smart-toolbar/action-button"; import { FormatSheetBody } from "@/components/smart-toolbar/phone/format-sheet"; +import { InsertSheet } from "@/components/smart-toolbar/phone/insert-sheet"; import { type MobileBarMode, nextMobileBarMode, @@ -139,8 +140,9 @@ interface MobileToolbarContentProps { /** Esc on a cell: back to the document with its selection. */ onEscape?: () => void; /** - * The last cells (List ▾, Indent, Insert ▾: `PhoneMenuCells`), rendered - * by the editor shell so the row's menus stay in the editor chunk. + * List ▾, Indent and the context slot (`PhoneMenuCells`), rendered by + * the editor shell so the row's menus stay in the editor chunk. Insert + * (its sheet) follows them, from this chunk. */ menuCells: ReactNode; } @@ -151,11 +153,11 @@ interface MobileToolbarContentProps { * undo, redo (from 404px; below, the sheet carries it, so the slot cell * never shifts the others), Aa (the * "Text format" sheet: style, size, colours, align, more), B, I, then - * `menuCells` (list, indent, the context slot, Insert). Toggles show their - * state with `aria-pressed` (#269). Hidden in a read-only document (#308), - * which also closes the sheet. While text is selected it swaps to - * `PhoneSelectionCells` (PR E, spec §4.7), never while focus is in the bar - * or the sheet is open; ✕ keeps the normal cells until the selection + * `menuCells` (list, indent, the context slot), then Insert (its sheet, + * spec §8.3). Toggles show their state with `aria-pressed` (#269). Hidden + * in a read-only document (#308), which also closes the sheets. While text + * is selected it swaps to `PhoneSelectionCells` (PR E, spec §4.7), never + * while focus is in the bar or a sheet is open; ✕ keeps the normal cells until the selection * collapses. Clear of the home indicator while the keyboard is closed * (`data-keyboard`, `phone.scss`). The status pill (design pass §5) sits * 8px above it, a sibling of the cells, never in a masked element. Its own @@ -168,6 +170,7 @@ export function MobileToolbarContent({ menuCells, }: MobileToolbarContentProps) { const [sheetOpen, setSheetOpen] = useState(false); + const [insertOpen, setInsertOpen] = useState(false); /** Opened for `formats.remove`: Your formats starts at its Remove list. */ const [removing, setRemoving] = useState(false); const recent = useRememberedChoice(RECENT_COLORS_CHOICE); @@ -189,7 +192,7 @@ export function MobileToolbarContent({ const [focusInBar, setFocusInBar] = useState(false); const [mode, setMode] = useState("all"); const nextMode = nextMobileBarMode({ - hasTextSelection: selectionKey !== null && !sheetOpen, + hasTextSelection: selectionKey !== null && !sheetOpen && !insertOpen, focusInBar, dismissedForSelection: dismissed, current: mode, @@ -299,6 +302,14 @@ export function MobileToolbarContent({ [editor, readOnly, onSheetOpenChange], ); + const onInsertOpenChange = useCallback( + (open: boolean) => { + setPageInert(editor, open); + setInsertOpen(open); + }, + [editor], + ); + /** Closes the sheet for an action that moves focus elsewhere itself. */ const closeSheet = useCallback(() => { keepFocusOnCloseRef.current = true; @@ -306,8 +317,10 @@ export function MobileToolbarContent({ }, [onSheetOpenChange]); useEffect(() => { - if (readOnly) onSheetOpenChange(false); - }, [readOnly, onSheetOpenChange]); + if (!readOnly) return; + onSheetOpenChange(false); + onInsertOpenChange(false); + }, [readOnly, onSheetOpenChange, onInsertOpenChange]); useEffect(() => () => setPageInert(editor, false), [editor]); @@ -396,6 +409,15 @@ export function MobileToolbarContent({ {menuCells} )} + {/* Mounted in both modes: it answers "/" and palette picks of Table + and Embed (`insert.open`) even while the selection cells show. */} + {sheetOpen ? null : } ); diff --git a/components/smart-toolbar/bubble/bubble-action-button.tsx b/components/smart-toolbar/bubble/bubble-action-button.tsx new file mode 100644 index 00000000..7e89b771 --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-action-button.tsx @@ -0,0 +1,116 @@ +"use client"; + +import type { Editor } from "@tiptap/react"; + +import { ToolbarButton } from "@/components/ui/toolbar-button"; +import { useActionView } from "@/hooks/use-editor-context"; +import { editorActions } from "@/lib/editor-actions"; +import { INLINE_CODE_REASON } from "@/lib/editor-actions/inline-code-reason"; +import { + ariaKeyShortcuts, + toShortcutKeys, +} from "@/lib/editor-actions/key-combo"; +import { runAction } from "@/lib/editor-actions/registry"; +import { isMac } from "@/lib/shortcuts"; + +/** Keeps the editor selection: act on click, never move focus on press. */ +const keepSelection = (event: React.MouseEvent) => event.preventDefault(); + +/** + * The registry's generic refusals for the bubble's mark, link and colour + * items (`core/inline.ts`, `surface-actions.ts`), copied here because the + * strings stay in the registry. A unit test keeps the two in step. + */ +export const GENERIC_MARK_REASONS: ReadonlySet = new Set([ + "Formatting isn't available here.", + "Links can't go here.", + "Text colour isn't available here.", +]); + +/** + * The reason a refused bubble item gives: inside inline code, which takes + * no other mark, a generic refusal says why (spec §7.2). Every other + * reason (read-only, the title, code blocks) stays the registry's. Kept in + * the bubble chunk so the editor chunk's registry stays as it is. + */ +export function useBubbleReason( + editor: Editor, + reason: string | undefined, +): string | undefined { + const code = useActionView("mark.inlineCode", editor); + return reason !== undefined && + code?.active && + GENERIC_MARK_REASONS.has(reason) + ? INLINE_CODE_REASON + : reason; +} + +/** + * `ActionButton`'s bubble variant, mirroring `components/smart-toolbar/ + * action-button.tsx` (contract §3.5: label, icon, Markdown hint, shortcut, + * `aria-pressed` incl. "mixed", disabled with a reason), plus the inline + * code reason (`useBubbleReason`). A copy, not a prop on `ActionButton`: + * that module is in the editor chunk, and the phase's gate is 0 B. Keep the + * two in step. B I U S, ‹› and Link use it; Tx and 💬 keep `ActionButton`. + */ +export function BubbleActionButton({ + id, + editor, + onRun, +}: { + id: string; + editor: Editor; + /** + * Wraps the run, for what the bubble does around it (the link handoff, + * the pill after ‹›). It must call `run` once. + */ + onRun?: (run: () => boolean) => void; +}) { + const view = useActionView(id, editor); + const action = editorActions.get(id); + const reason = useBubbleReason( + editor, + !view || view.enabled === true ? undefined : view.enabled.reason, + ); + if (!action || !view) return null; + const Icon = action.icon; + const toggle = action.isActive !== undefined; + const tooltip = action.markdownHint ? ( + + {action.label} + + {action.markdownHint.trim()} + + + ) : ( + action.label + ); + return ( + { + const run = () => runAction(editor, action); + if (onRun) onRun(run); + else run(); + }} + > + {Icon ? + ); +} diff --git a/components/smart-toolbar/bubble/bubble-color-split.tsx b/components/smart-toolbar/bubble/bubble-color-split.tsx new file mode 100644 index 00000000..0bf30175 --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-color-split.tsx @@ -0,0 +1,81 @@ +"use client"; + +import type { Editor } from "@tiptap/react"; + +import { ToolbarButton } from "@/components/ui/toolbar-button"; +import { useActionView } from "@/hooks/use-editor-context"; +import { editorActions } from "@/lib/editor-actions"; +import { runAction } from "@/lib/editor-actions/registry"; +import { colorLabel } from "@/lib/editor-actions/surface-actions"; +import { BaselineIcon, ChevronDownIcon } from "@/lib/icons"; +import { + TEXT_COLOR_CHOICE, + useRememberedChoice, +} from "@/lib/remembered-choice"; + +import { swatchStyle } from "../color/swatch"; +import { ColorPopoverButton } from "../color-controls"; +import { useBubbleReason } from "./bubble-action-button"; +import type { BubblePlacement } from "./bubble-rules"; + +const APPLY_ID = "color.text.apply"; + +/** + * The bubble's text colour split (spec §7.1 slot 7): the face reapplies + * the remembered colour ("Apply text colour: Red"), the 24px chevron opens + * the colour menu away from the text. Mirrors `ColorSplit`'s text half + * (`components/smart-toolbar/color-controls.tsx`) plus the inline code + * reason (`useBubbleReason`): a copy, not a prop on `ColorSplit`, because + * that module is in the editor chunk and the phase's gate is 0 B. Keep the + * two in step. + */ +export function BubbleColorSplit({ + editor, + placement, +}: { + editor: Editor; + placement: BubblePlacement; +}) { + const view = useActionView(APPLY_ID, editor); + const remembered = useRememberedChoice(TEXT_COLOR_CHOICE); + const reason = useBubbleReason( + editor, + !view || view.enabled === true ? undefined : view.enabled.reason, + ); + if (!view) return null; + const faceLabel = `Apply text colour: ${colorLabel(remembered.last)}`; + return ( +
+ event.preventDefault()} + onClick={() => { + const action = editorActions.get(APPLY_ID); + if (action) runAction(editor, action, remembered.last); + }} + > + + + +
+ ); +} diff --git a/components/smart-toolbar/bubble/bubble-controller.ts b/components/smart-toolbar/bubble/bubble-controller.ts index 47cfd174..55c39076 100644 --- a/components/smart-toolbar/bubble/bubble-controller.ts +++ b/components/smart-toolbar/bubble/bubble-controller.ts @@ -9,7 +9,12 @@ import { import type { Editor, EditorEvents } from "@tiptap/core"; import type { Transaction } from "@tiptap/pm/state"; -import { BUBBLE_OFFSET, type BubblePlacement } from "./bubble-rules"; +import { + BUBBLE_OFFSET, + BUBBLE_RESIZE_DELAY_MS, + BUBBLE_SHOW_DELAY_MS, + type BubblePlacement, +} from "./bubble-rules"; /** * Selection bubble controller (spec §12.1): shows, hides and positions one @@ -19,10 +24,8 @@ import { BUBBLE_OFFSET, type BubblePlacement } from "./bubble-rules"; * (`@tiptap/extension-bubble-menu` 3.33); line numbers below cite it. */ -/** Delay before a non-empty selection shows the bubble (`updateDelay`, :378). */ -export const BUBBLE_SHOW_DELAY_MS = 250; -/** Debounce for repositioning on resize and scroll (`resizeDelay`, :379). */ -export const BUBBLE_RESIZE_DELAY_MS = 60; +// The delays live with the pure rules, where the e2e can read them too. +export { BUBBLE_RESIZE_DELAY_MS, BUBBLE_SHOW_DELAY_MS } from "./bubble-rules"; /** What the controller drives: the view's root, rules and callbacks. */ export interface BubbleHost { @@ -36,11 +39,19 @@ export interface BubbleHost { onHide(): void; /** After each applied position (or reference-hidden) result. */ onPosition(): void; + /** + * Quiet time after Shift is released before a keyboard-made selection + * shows (spec §7.2, O7 b). 0 or omitted: off, keyboard selections use + * the normal show delay. + */ + readonly keyboardSettleMs?: number; } /** One editor's bubble: its visibility, position and teardown. */ export interface BubbleController { readonly visible: boolean; + /** A show is waiting: the show delay or a keyboard settle. */ + readonly pending: boolean; /** Re-evaluates now, without the show delay. */ update(): void; updatePosition(): void; @@ -51,6 +62,24 @@ export interface BubbleController { destroy(): void; } +const MODIFIER_KEYS = new Set(["Shift", "Control", "Meta", "Alt"]); +const SELECTION_KEYS = new Set([ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + "PageUp", + "PageDown", +]); + +/** Shift+Arrow/Home/End/PageUp/PageDown, or Ctrl/⌘+A. */ +function isKeyboardSelection(event: KeyboardEvent): boolean { + if (event.shiftKey && SELECTION_KEYS.has(event.key)) return true; + return (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "a"; +} + type Timer = ReturnType | undefined; /** One controller per editor (StrictMode effects run twice). */ @@ -70,6 +99,19 @@ function changesSelectionOrDoc( return changes(transaction) || appended.some(changes); } +/** `ySyncPluginKey`'s meta key (y-tiptap): marks remote Yjs transactions. */ +const Y_SYNC_META = "y-sync$"; + +/** A selection change made here, not applied from a collaborator. */ +function isLocalSelectionChange( + transaction: Transaction, + appended: readonly Transaction[], +): boolean { + const local = (tr: Transaction) => + tr.selectionSet && !tr.getMeta(Y_SYNC_META); + return local(transaction) || appended.some(local); +} + /** * Creates the bubble controller for `editor`, replacing any earlier one. * The root is appended to `scrollTarget` (`.document-editor-wrapper`) on @@ -93,6 +135,14 @@ export function createBubbleController( let dragging = false; let preventHide = false; let showTimer: Timer; + let settleTimer: Timer; + /** The selection being changed came from a keydown (O7 b). */ + let keyboardSelecting = false; + /** A keyboard selection is waiting for its settle (set by `evaluate`). */ + let settling = false; + let shiftHeld = false; + /** A key is auto-repeating: it never shows the bubble. */ + let repeating = false; let deferTimer: Timer; let resizeTimer: Timer; let stopAutoUpdate: (() => void) | undefined; @@ -162,7 +212,11 @@ export function createBubbleController( /** :624-639. Cancels a pending show; the root leaves before `onHide`. */ function hide() { clearTimeout(showTimer); + clearTimeout(settleTimer); showTimer = undefined; + settleTimer = undefined; + keyboardSelecting = false; + settling = false; if (!visible) return; visible = false; positionRun += 1; @@ -177,7 +231,11 @@ export function createBubbleController( /** Re-evaluates now (`updateHandler`, :579-603). Never shows mid-drag. */ function update() { clearTimeout(showTimer); + clearTimeout(settleTimer); showTimer = undefined; + settleTimer = undefined; + keyboardSelecting = false; + settling = false; if (destroyed || editor.isDestroyed || view.composing) return; if (editor.state.selection.empty || !host.shouldShow()) { hide(); @@ -199,12 +257,62 @@ export function createBubbleController( } if (dragging) return; clearTimeout(showTimer); + showTimer = undefined; + // Only a hidden bubble settles; a shown one repositions as before. + if (!visible && keyboardSelecting && (host.keyboardSettleMs ?? 0) > 0) { + settling = true; + armSettle(); + return; + } showTimer = setTimeout(() => { showTimer = undefined; update(); }, BUBBLE_SHOW_DELAY_MS); } + /** + * (Re)starts the keyboard settle (O7 b): only once Shift is up and no key + * is repeating; the Shift keyup and each further change call it again. + */ + function armSettle() { + clearTimeout(settleTimer); + settleTimer = undefined; + if (shiftHeld || repeating) return; + settleTimer = setTimeout(() => { + settleTimer = undefined; + update(); + }, host.keyboardSettleMs); + } + + // Capture, on the window: ProseMirror's own keydown handler (Tiptap's + // Mod-a runs `selectAll` synchronously in it) must find the flag set. + const onKeyDown = (event: KeyboardEvent) => { + if (!(event.target instanceof Node && dom.contains(event.target))) return; + shiftHeld = event.shiftKey; + repeating = event.repeat; + if (MODIFIER_KEYS.has(event.key)) return; + keyboardSelecting = isKeyboardSelection(event); + }; + + // On the window: Shift may be released outside the editor. While Shift is + // held the flag stays: Chromium can fire `selectionchange` after a fast + // arrow's keyup. Releasing Shift with nothing pending (a no-op + // Shift+Arrow) leaves nothing to settle. + const onKeyUp = (event: KeyboardEvent) => { + repeating = false; + if (event.key === "Shift" || !event.shiftKey) shiftHeld = false; + if (settling) armSettle(); + else if (!shiftHeld) keyboardSelecting = false; + }; + + // Keys released while the window was away never report their keyup. + const onWindowBlur = () => { + shiftHeld = false; + repeating = false; + if (settling) armSettle(); + else keyboardSelecting = false; + }; + /** Evaluates once the selection has settled (focus :459-462, IME :431-442). */ function evaluateLater() { clearTimeout(deferTimer); @@ -222,6 +330,13 @@ export function createBubbleController( if (!visible && editor.state.selection.empty) return; if (view.composing) return; if (!changesSelectionOrDoc(transaction, appendedTransactions)) return; + // A remote change or a doc-only one must not restart the settle. + if ( + settling && + !isLocalSelectionChange(transaction, appendedTransactions) + ) { + return; + } evaluate(); }; @@ -263,6 +378,10 @@ export function createBubbleController( }; const onPointerDown = () => { + keyboardSelecting = false; + settling = false; + clearTimeout(settleTimer); + settleTimer = undefined; dragging = true; }; @@ -300,6 +419,9 @@ export function createBubbleController( window.removeEventListener("pointercancel", onPointerUp); window.removeEventListener("resize", onReposition); scrollTarget.removeEventListener("scroll", onReposition); + window.removeEventListener("keydown", onKeyDown, { capture: true }); + window.removeEventListener("keyup", onKeyUp, { capture: true }); + window.removeEventListener("blur", onWindowBlur); clearTimeout(deferTimer); clearTimeout(resizeTimer); deferTimer = undefined; @@ -318,6 +440,9 @@ export function createBubbleController( dom.addEventListener("contextmenu", onHideEvent); dom.addEventListener("compositionend", evaluateLater); dom.addEventListener("pointerdown", onPointerDown); + window.addEventListener("keydown", onKeyDown, { capture: true }); + window.addEventListener("keyup", onKeyUp, { capture: true }); + window.addEventListener("blur", onWindowBlur); window.addEventListener("pointerup", onPointerUp); window.addEventListener("pointercancel", onPointerUp); window.addEventListener("resize", onReposition); @@ -327,6 +452,9 @@ export function createBubbleController( get visible() { return visible; }, + get pending() { + return showTimer !== undefined || settleTimer !== undefined; + }, update, updatePosition, hide, diff --git a/components/smart-toolbar/bubble/bubble-rules.ts b/components/smart-toolbar/bubble/bubble-rules.ts index 13d6156c..b71763d4 100644 --- a/components/smart-toolbar/bubble/bubble-rules.ts +++ b/components/smart-toolbar/bubble/bubble-rules.ts @@ -11,11 +11,17 @@ import { * rules are unit tested without a browser. */ -/** B · I · U, text colour, link. Every one is also a row control. */ +/** + * B · I · U · S · ‹› · Tx, text colour, link (spec §7.1). Every one is + * also in the row: a button, or an item of ⋯ More formatting. + */ export const BUBBLE_ACTION_IDS = [ "mark.bold", "mark.italic", "mark.underline", + "mark.strike", + "mark.inlineCode", + "format.clear", "color.text.apply", "mark.link", ] as const; @@ -163,6 +169,16 @@ export interface BubbleRect { export type BubblePlacement = "top" | "bottom"; +/** Delay before a non-empty selection shows the bubble (`updateDelay`, :378). */ +export const BUBBLE_SHOW_DELAY_MS = 250; +/** Debounce for repositioning on resize and scroll (`resizeDelay`, :379). */ +export const BUBBLE_RESIZE_DELAY_MS = 60; +/** + * A keyboard selection shows once Shift is up and the selection has been + * still this long, never on auto-repeat (spec §7.2, O7 b). + */ +export const KEYBOARD_SETTLE_MS = 300; + /** Gap between the selection and the bubble, as the plugin's `offset`. */ export const BUBBLE_OFFSET = 8; diff --git a/components/smart-toolbar/bubble/bubble-style-menu.tsx b/components/smart-toolbar/bubble/bubble-style-menu.tsx new file mode 100644 index 00000000..c94a752b --- /dev/null +++ b/components/smart-toolbar/bubble/bubble-style-menu.tsx @@ -0,0 +1,232 @@ +"use client"; + +import { DirectionProvider } from "@base-ui/react/direction-provider"; +import type { Editor } from "@tiptap/react"; +import { useCallback, useLayoutEffect, useRef, useState } from "react"; + +import { + DropdownMenu, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu-trigger"; +import { ToolbarButton } from "@/components/ui/toolbar-button"; +import { editorActions } from "@/lib/editor-actions"; +import { ChevronDownIcon } from "@/lib/icons"; + +import { clearOfSelection } from "../color/clear-of-selection"; +import { + focusLostOnClose, + menuBody, + prefetchMenuBodies, + useMenuGate, +} from "../lazy-menu"; +import { TypeIcon } from "../type-icon"; +import type { BubblePlacement } from "./bubble-rules"; +import { + STYLE_FACE_NAMES, + STYLE_FACES, + type StyleFace, + useStyleFace, +} from "./style-face"; + +const Content = menuBody((bodies) => bodies.ToolbarMenuContent); +/** `ToolbarMenuContent`'s gap to its trigger. */ +const MENU_GAP = 4; +const TurnIntoMenuItems = menuBody((bodies) => bodies.TurnIntoMenuItems); + +/** Spec §7.1 Sizes: the face is at least 64px, and a word past 96px… */ +const FACE_MIN = 64; +const FACE_MAX = 96; +/** …gives way to the type's icon: `padding-inline: 8px 4px`, gap, chevron. */ +const FACE_CHROME = 8 + 4 + 4 + 12; + +/** The registry action whose icon stands for each face. */ +const FACE_ICON_IDS: Partial> = { + List: "list.bullet", + Quote: "insert.quote", + Code: "insert.codeBlock", +}; + +/** + * The icon face, for a locale whose longest word would pass 96px: the + * registry's own icons (no new icon import, so the editor chunk keeps its + * shape), Type for Text, Title and Mixed. + */ +function FaceIcon({ face }: { face: StyleFace }) { + const id = + FACE_ICON_IDS[face] ?? + (face.startsWith("H") ? `style.heading${face.slice(1)}` : ""); + const Icon = editorActions.get(id)?.icon ?? TypeIcon; + return