From 8b9374463bd3aa65a981c135d7de53ea29b62105 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 20 Jul 2026 23:59:09 +0000 Subject: [PATCH] Revamp 4.4.1: Remote caret overlay (live cursors) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Complete Milestone 4 with the live remote-cursor overlay deferred from 4.4 (ROADMAP §4.4.1). - offsets.ts: pure mapOffsetToNode — the caret counterpart to mapTokenToNode (resolve a plain-text offset to a text node + local offset; boundaries snap to the earlier text node). - richOffsets.ts: selectionToCaretRange + buildLeafSpans, both reproducing the plain projection richStateToPlain derives (a tag contributes {id}; a delete change-mark projects to '' and its subtree is skipped) so a reported caret lands on the same character in every peer's editor. - RemoteCaretOverlay: a Lexical plugin that paints a coloured caret + name label per remote peer on the segment, measured like the spell overlay; never mutates the node tree, guarded on every measurement. - Reporting: the focused segment's editor computes the caret in its update listener and reports it through EditorPage -> useProjectSync -> setActiveSegment(id, caret), throttled to 100ms. - Tests: spell.offsets (mapOffsetToNode), richOffsets (headless projection incl. delete-mark), e2e (a peer's caret renders in the other tab). Green: 653 unit (+8) / 29 e2e (+1) / typecheck / build (flag-off Supabase-free). Milestone 4 complete. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_015AEnTYBecWG64R3iP8GBiE --- docs/revamp/ROADMAP.md | 2 +- docs/revamp/STATUS.md | 5 +- src/core/spell/offsets.ts | 25 ++++ src/features/editor/EditorPage.tsx | 12 ++ src/features/editor/SegmentRow.tsx | 6 +- src/features/editor/peers/useProjectSync.ts | 7 +- .../editor/rich/RemoteCaretOverlay.tsx | 120 +++++++++++++++++ .../editor/rich/RichSegmentEditor.tsx | 37 +++++- src/features/editor/rich/richOffsets.ts | 74 +++++++++++ tests/e2e/lan-collaboration.spec.ts | 11 ++ tests/unit/richOffsets.test.ts | 121 ++++++++++++++++++ tests/unit/spell.offsets.test.ts | 29 ++++- 12 files changed, 437 insertions(+), 12 deletions(-) create mode 100644 src/features/editor/rich/RemoteCaretOverlay.tsx create mode 100644 src/features/editor/rich/richOffsets.ts create mode 100644 tests/unit/richOffsets.test.ts diff --git a/docs/revamp/ROADMAP.md b/docs/revamp/ROADMAP.md index 512d8af..9358aff 100644 --- a/docs/revamp/ROADMAP.md +++ b/docs/revamp/ROADMAP.md @@ -79,7 +79,7 @@ Roadmap, status checklist, prompt pack, and vision docs committed to the repo. - **4.2 `SupabaseRealtimeTransport` + chunking — M — deps: 4.1.** Implements the existing `SyncTransport` interface unchanged (`start/send/onMessage/destroy`, `hello/bye/state-request/state/update/presence`). Private broadcast channel `project:{cloudId}`; pure `chunking.ts` splits payloads >60KB (Realtime caps ~250KB; base64 +33%); outbound updates debounce-merged via `Y.mergeUpdates` (300ms). Initial state comes from Postgres (4.3), never broadcast for large docs. Transport picked in `createTransport` when project is cloud + signed in; BroadcastChannel/LAN paths untouched. **DoD**: two browsers exchange live edits; protocol unit-covered. - **4.3 Postgres persistence loop — M — deps: 4.2.** `cloud/ydocPersistence.ts`: on open, fetch `ydoc_state` + newer updates, apply as `ORIGIN_REMOTE`; local updates appended debounced; client-side compaction >200 rows via optimistic `claim_compaction(project_id, expected_seq)` RPC (`0005_compaction.sql`). Realtime is latency, Postgres is truth; offline members converge by replay (Yjs idempotent). **DoD**: offline-A/online-B edits converge on reconnect; updates table bounded. - **4.4 Live collab UX: cursors, leases, attribution — M — deps: 4.3, 1.6.** Presence gains `editingSegmentId`/`userId`/`caret`; deterministic lease (lowest peerId) renders other peers' segment read-only with name chip + live preview; `RemoteCaretOverlay` reuses offset→DOM mapping from `src/core/spell/offsets.ts`. Remote suggesting-mode edits arrive pre-attributed via `ChangeMarkNode` — "everyone's changes tracked" falls out of M1 + sync. Guard in `reverseBridge.ts`: rebuild rich from plain on detected stale-LWW mismatch. **DoD**: live cursors; simultaneous entry yields one editor + one viewer; lease releases on blur. *Milestone 4 = real-time collaboration shipped.* *Shipped the lease/attribution/guard core (`sync/lease.ts`, presence `userId`+`caret`, `SegmentRow` read-only + "is editing" chip, reverseBridge stale-LWW guard); the **live remote-caret overlay is deferred to 4.4.1** — the presence model carries `caret` as the seam, but rendering it needs editor→session caret reporting + offset→DOM measurement, a separable slice.* -- **4.4.1 Remote caret overlay — S — deps: 4.4.** Report the local caret (Lexical selection → plain-text offset) through `setActiveSegment(id, caret)`, and render remote peers' carets/selections in each segment with a `RemoteCaretOverlay` reusing the offset→DOM mapping in `src/core/spell/offsets.ts` (as `SpellUnderlinePlugin` does). **DoD**: live remote cursors move as peers type; overlay never mutates the editor tree. +- **4.4.1 Remote caret overlay — S — deps: 4.4.** Report the local caret (Lexical selection → plain-text offset) through `setActiveSegment(id, caret)`, and render remote peers' carets/selections in each segment with a `RemoteCaretOverlay` reusing the offset→DOM mapping in `src/core/spell/offsets.ts` (as `SpellUnderlinePlugin` does). **DoD**: live remote cursors move as peers type; overlay never mutates the editor tree. *Shipped: `mapOffsetToNode` (core) + `richOffsets.ts` (`selectionToCaretRange`/`buildLeafSpans`, reproducing the plain projection incl. delete-mark → '') + `RemoteCaretOverlay`; the focused editor reports its caret throttled to 100ms. **Milestone 4 complete.*** ### Milestone 5 — Roles & workflow - **5.1 Members & roles management — M — deps: 4.1.** `cloud/members.ts` (invite by email via profiles lookup, change role, remove), `MembersPanel`, `0006_member_policies.sql` (PM-only member writes; trigger keeps ≥1 PM). **DoD**: PM invites translator + revisor; non-PM read-only; server rejects non-PM writes. diff --git a/docs/revamp/STATUS.md b/docs/revamp/STATUS.md index 50c6f64..ed425ab 100644 --- a/docs/revamp/STATUS.md +++ b/docs/revamp/STATUS.md @@ -31,8 +31,8 @@ Rules for autonomous sessions: | 4.1 | Cloud project schema + RLS + publish/join | M | 3.1 | done (PR #55) | | 4.2 | SupabaseRealtimeTransport + chunking | M | 4.1 | done (PR #56) | | 4.3 | Postgres persistence loop (catch-up, append, compaction) | M | 4.2 | done (PR #57) | -| 4.4 | Live collab UX: cursors, leases, attribution | M | 4.3, 1.6 | in-review (PR #58) | -| 4.4.1 | Remote caret overlay (live cursors, deferred from 4.4) | S | 4.4 | pending | +| 4.4 | Live collab UX: cursors, leases, attribution | M | 4.3, 1.6 | done (PR #58) | +| 4.4.1 | Remote caret overlay (live cursors, deferred from 4.4) | S | 4.4 | in-review (PR #59) | | 5.1 | Members & roles management | M | 4.1 | pending | | 5.2 | Role-gated editing workflow | M | 5.1, 1.6 | pending | | 5.3 | Approval workflow + attribution in versioning | S | 5.2 | pending | @@ -74,3 +74,4 @@ Rules for autonomous sessions: - 2026-07-20 — Phase 4.1 merged in PR #55. Phase 4.2 built: `SupabaseRealtimeTransport` + chunking (pure client, no schema change). `src/storage/sync/transport/chunking.ts` — the protocol core: base64 wire encoding (`bytesToBase64`/`base64ToBytes`), `encodeMessage(SyncMessage, limit=60000)` frames a message into `WireChunk`s (Realtime is JSON + ~250KB/msg, so binary payloads are base64 +33% and split), and an order-independent `ChunkReassembler` that yields a `SyncMessage` once all chunks of a message id arrive (single-chunk pass-through; payloadless kinds `hello`/`bye`/`state-request` carry `d:''`). `src/storage/sync/transport/supabaseRealtime.ts` — `SupabaseRealtimeTransport implements SyncTransport` over a private Realtime broadcast channel `project:{cloudId}` (`broadcast:{self:false}`, so no self-echo, matching BroadcastChannel); `getSupabase()` is dynamic so no eager supabase-js. Outbound `update`s are coalesced by `OutboundUpdateBatcher` (debounce 300ms → `Y.mergeUpdates` → one broadcast); other kinds send immediately; sends before `SUBSCRIBED` buffer in an outbox flushed on subscribe. The channel is injectable (`channelProvider`) as a test seam. `createTransport(projectId, {cloudId?})` gains a cloud branch (Supabase when `cloudId` set; **BroadcastChannel/Tauri paths byte-identical otherwise**); `syncManager.startProjectSync` computes `cloudId` from `project.cloud` when signed-in + `isCloudConfigured()`, else `undefined`. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-2`; the transport is complete + unit-covered now, but the end-to-end **two-browser live edit** DoD needs the Postgres initial-state loop (4.3) + the auto-start-on-open UI (4.4) — the transport is selectable but not yet auto-wired for cloud projects (that's 4.4), stated honestly. No migration (4.2 is transport-only). Tests: `sync.chunking` (base64 all-bytes/empty round-trip; single + multi-chunk encode/reassemble; out-of-order arrival; two interleaved messages stay separate; payloadless pass-through), `sync.realtimeTransport` (`OutboundUpdateBatcher` merges a burst into one flush that replays both edits via fake timers + no-fire-after-destroy; transport delivers a 50KB multi-chunk `state` to the *other* peer only via a linked in-memory channel pair — caught + fixed a real ordering bug where the outbox flushed before `this.channel` was assigned; pre-subscribe sends buffer then flush). Green: 629 unit (+11) / 27 e2e twice / build (flag-off has zero `GoTrueClient`; flag-on keeps Supabase a lazy chunk out of the entry). - 2026-07-20 — Phase 4.2 merged in PR #56 (STATUS was stale — recorded here). Phase 4.3 built: the Postgres persistence loop (Realtime is latency, Postgres is truth). `supabase/migrations/0007_compaction.sql` — the `claim_compaction(project_id, expected_seq, state, up_to_id)` RPC (SECURITY DEFINER, membership-checked): atomically bumps the `ydoc_state.seq` generation **only while it still matches** `expected_seq`, installs the new compacted snapshot, and prunes `ydoc_updates` with `id <= up_to_id`. Numbering deviation: ROADMAP §4.3 sketched `0005_compaction.sql`, but `0005`/`0006` were taken by the 4.1 project migrations, so it ships as `0007`; and the RPC signature is **widened** from the sketch's `(project_id, expected_seq)` to also carry the new snapshot + pruned-through id, so the whole compaction is one atomic RLS-safe transaction (the append log has no DELETE policy by design — D8 tamper-evidence — so pruning goes through this controlled definer path, membership re-checked inside). `src/storage/cloud/ydocPersistence.ts` — pure client-injected data layer (`fetchSnapshot`/`fetchUpdates`/`appendUpdate`/`countUpdates`/`claimCompaction`, hex-bytea via 4.1's `bytea.ts`) + the `createYdocPersistence({cloudId, doc, client})` loop: **catch-up** fetches `ydoc_state` + the whole `ydoc_updates` log, merges (`Y.mergeUpdates`) and applies as `ORIGIN_REMOTE` (so neither the transport nor this loop re-broadcasts/re-appends it), then pushes anything the local doc holds that the cloud lacks (offline edits / pre-publish history) by diffing state vectors (`Y.encodeStateAsUpdate(doc, remoteSV)` when `localAheadOf`); **append** buffers local `doc.on('update')` deltas (ignoring `ORIGIN_REMOTE`), debounce-merges them (500ms) into one attributed `ydoc_updates` row, and re-buffers/retries on a failed (offline) append; **compaction** triggers once the log passes 200 rows — it re-reads the *authoritative* snapshot+updates from Postgres (never the possibly-lagging local doc) to build the new snapshot, so it subsumes exactly the rows it prunes, then optimistically `claim_compaction`s (loser gets `null` and no-ops — the log is already bounded). Catch-up is re-runnable (idempotent Yjs replay), which is what converges an offline member on reconnect. Wiring: `syncManager.startProjectSync` starts the loop (dynamic `startYdocPersistence`, only when `cloudId` set + signed-in + `isCloudConfigured()`) alongside the realtime transport, kicks off a non-blocking `catchUp()`, stores the handle on the ref-counted session, and destroys it in `stopProjectSync`; local-only projects never touch it. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-3`; the RPC signature widening above; live **reconnect re-sync** (re-`hello`/re-`catchUp` when Realtime drops-then-resubscribes) is left to 4.4, which owns the transport/auto-start UX — 4.3 converges on **reopen** (each open runs catch-up), the DoD proven at the persistence layer. `docs/cloud.md` (§3 migration list + §10 manual verification). Tests: `cloud.ydocPersistence` (catch-up converges a fresh doc from snapshot+log; append coalesces a burst into one row; applied-remote is never re-appended; **offline-A/online-B converge through Postgres with no edit lost** — the DoD, on a shared in-memory server; compaction folds+prunes past the threshold and bumps seq, and a stale optimistic claim returns `null`; `fetchSnapshot`/`fetchUpdates` bytea round-trips). Green: 636 unit (+7) / build (flag-off: **zero** `GoTrueClient`/`claim_compaction` — the loop tree-shakes out entirely when the cloud is unconfigured; flag-on: `GoTrueClient` and the persistence loop each in their own lazy chunk, out of the entry). No new e2e (ROADMAP §4 asks none for 4.3; the two-member live DoD needs a real backend, per the §10 manual matrix). - 2026-07-20 — Phase 4.3 merged in PR #57. Phase 4.4 built: live-collab UX — per-segment edit leases, attribution, and the stale-LWW guard (transport-agnostic, so it works for local BroadcastChannel peers and cloud Realtime peers identically). `src/storage/sync/presence.ts` gains a stable `userId` (Supabase user id when signed in, else the device-local `authorId` — so attribution survives a peer reconnecting under a fresh peerId, D8) and a `CaretRange` on both `PresenceWire` and `PeerPresence`; `syncSession` broadcasts them (`setActiveSegment(id, caret?)`) and `syncManager` resolves `userId` via `ensureLocalAuthor()`/auth. `src/storage/sync/lease.ts` — pure `segmentLease(segmentId, selfPeerId, selfActiveSegmentId, peers)`: among everyone editing a segment the **lowest peerId owns** (D4), the rest are viewers; symmetric + deterministic so two peers entering at once always agree, and the lease **releases the moment the owner blurs** (its `activeSegmentId` moves off) and the next-lowest peer takes over. Wiring: `usePresenceStore` carries `selfPeerId`; `useProjectSync` publishes it; `EditorPage` computes `leaseHolderFor(segmentId)` and passes `leaseLockedBy` to each `SegmentRow`, which renders the target read-only (a separate `editLocked = locked || leaseLockedBy`, kept distinct from the persistent segment lock) with a coloured "{name} is editing" chip. Attribution "everyone's changes tracked" falls out of M1 + sync for free — remote suggesting-mode edits already arrive as pre-attributed `ChangeMarkNode`s. `reverseBridge.ts` stale-LWW guard (risk #5): `target` (char-level Y.Text) and `targetRich` are separate CRDT fields, so a concurrent merge can land a `targetRich` that no longer derives to the merged plain `target`; plain is authoritative, so when `richStateToPlain(targetRich) !== target` the guard drops the stale rich and the editor rebuilds it from plain. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-4`; **the live remote-caret overlay is deferred to Phase 4.4.1** (appended to the table + ROADMAP §4) — the presence model already carries `caret` as the seam, but rendering it needs editor→session caret reporting + offset→DOM measurement (a finicky, separable slice), so 4.4 ships the load-bearing lease/attribution/guard core (the "one editor + one viewer; lease releases on blur" DoD) and the per-segment "is editing" chip as the visible presence cue. Tests: `sync.lease` (alone→own; higher-peerId co-editor→own; lower-peerId→viewer names holder; not-on-segment reports the editor; symmetric one-owner; release; `peersOnSegment`), `sync.presence` (userId + caret round-trip), `sync.reverseBridge` (guard drops a stale targetRich once the merged plain diverges, no-op while they agree), and e2e `lan-collaboration.spec.ts` extended (**simultaneous entry → exactly one read-only viewer + one editable owner; owner blur releases the lease** via two BroadcastChannel tabs). Green: 645 unit (+9) / 28 e2e (+1) / build (flag-off has zero `GoTrueClient`; leases are local-capable so they ship in the entry as intended). +- 2026-07-20 — Phase 4.4 merged in PR #58. Phase 4.4.1 built: the live remote-caret overlay deferred from 4.4 (**Milestone 4 fully complete**). `src/core/spell/offsets.ts` gains pure `mapOffsetToNode(spans, offset)` — the caret counterpart to `mapTokenToNode`, resolving a plain-text offset to a text node + local offset (a text/text boundary snaps to the earlier node's end; a tag boundary or past-the-end returns null → the overlay skips that frame). `src/features/editor/rich/richOffsets.ts` — `selectionToCaretRange(selection)` converts a live Lexical selection to plain anchor/focus offsets and `buildLeafSpans(paragraph)` produces the ordered leaf spans, both reproducing exactly the plain projection `richStateToPlain` derives (a tag contributes `{id}`, a **delete change-mark projects to '' and its subtree is skipped**) so a caret one peer reports lands on the same character in another peer's editor. `RemoteCaretOverlay.tsx` (a Lexical plugin mounted in `RichSegmentEditor` beside the spell overlay) paints a coloured caret + name label for each remote peer whose presence puts them on the segment with a caret, measured via `getElementByKey`+DOM range like `SpellUnderlinePlugin` — it never mutates the node tree and every measurement is guarded (renders nothing on failure). Reporting: the **focused** segment's editor (the only one given `onCaret`) computes `selectionToCaretRange` in its update listener and reports it through `EditorPage`→`useProjectSync`→`setActiveSegment(id, caret)`, throttled to one send per 100ms; `useProjectSync.setActiveSegment` now forwards the caret. Deviations (noted): built on the designated session branch, not `claude/revamp-phase-4-4-1`. Tests: `spell.offsets` extended (`mapOffsetToNode`: inside/boundary/after-tag/end/out-of-range), `richOffsets` (headless: caret offsets + leaf spans agree with the plain projection for text+tag, and a **delete change-mark projects to nothing** so a caret past it collapses correctly), and e2e `lan-collaboration.spec.ts` extended (**a peer's caret renders as a live remote cursor in the other tab**). Green: 653 unit (+8) / 29 e2e (+1) / build (flag-off zero `GoTrueClient`; the overlay is local-capable and ships in the entry, no Supabase). **Milestone 4 (cloud projects + real-time collaboration) complete.** diff --git a/src/core/spell/offsets.ts b/src/core/spell/offsets.ts index 3d461f6..84c4c0a 100644 --- a/src/core/spell/offsets.ts +++ b/src/core/spell/offsets.ts @@ -21,6 +21,31 @@ export interface MappedRange { localEnd: number } +export interface MappedOffset { + key: string + localOffset: number +} + +/** + * Locate a single plain-text `offset` on a text node, for painting a remote + * peer's caret (ROADMAP §4.4.1). Returns the first text span that contains the + * offset (a boundary between two text spans resolves to the end of the earlier + * one — the same screen position), or null when it lands on a non-text node + * (a tag chip) or past the end — the overlay simply skips that frame. + */ +export function mapOffsetToNode(spans: NodeSpan[], offset: number): MappedOffset | null { + if (offset < 0) return null + let acc = 0 + for (const span of spans) { + const spanEnd = acc + span.length + if (span.isText && offset >= acc && offset <= spanEnd) { + return { key: span.key, localOffset: offset - acc } + } + acc = spanEnd + } + return null +} + /** * Locate `[start, end)` within the ordered node spans. Returns the containing * text node with node-local offsets, or null when the token lands in / spans a diff --git a/src/features/editor/EditorPage.tsx b/src/features/editor/EditorPage.tsx index 4ed145f..eafedc7 100644 --- a/src/features/editor/EditorPage.tsx +++ b/src/features/editor/EditorPage.tsx @@ -46,6 +46,7 @@ import { useProjectCrdt } from './useProjectCrdt' import { useProjectSync } from './peers/useProjectSync' import { usePresenceStore } from './peers/usePresenceStore' import { segmentLease } from '@/storage/sync/lease' +import type { CaretRange } from '@/storage/sync/presence' import { canJoin } from '@/core/segments/operations' import { buildSearchUrl } from '@/core/websearch/providers' import { useEditorSettings } from './useEditorSettings' @@ -120,6 +121,16 @@ export default function EditorPage() { setActiveSegment(activeSegmentId) }, [activeSegmentId, setActiveSegment]) + // Report the focused editor's caret to presence (§4.4.1) against the segment + // it belongs to. A ref keeps the callback stable so only the focused row it is + // passed to re-renders, not every row on each caret move. + const activeSegmentIdRef = useRef(undefined) + activeSegmentIdRef.current = activeSegmentId + const reportCaret = useCallback( + (caret: CaretRange) => setActiveSegment(activeSegmentIdRef.current, caret), + [setActiveSegment], + ) + // The remote peer (if any) holding a segment's edit lease against the local // user — used to render that segment read-only with a "name is editing" chip. const leaseHolderFor = useCallback( @@ -619,6 +630,7 @@ export default function EditorPage() { spellEnabled={spellEnabled} commentAuthor={commentAuthor} leaseLockedBy={leaseHolderFor(seg.id)} + onCaret={originalIndex === focusIndex ? reportCaret : undefined} onConfirm={() => confirm(originalIndex)} onUnconfirm={() => unconfirm(originalIndex)} onToggleReviewed={() => toggleReviewed(originalIndex)} diff --git a/src/features/editor/SegmentRow.tsx b/src/features/editor/SegmentRow.tsx index fdb04a7..e97ae2e 100644 --- a/src/features/editor/SegmentRow.tsx +++ b/src/features/editor/SegmentRow.tsx @@ -4,7 +4,7 @@ import { Check, Eye, Lock, MessageSquare, Pencil } from 'lucide-react' import { Textarea } from '@/components/ui/textarea' import { segmentRepo } from '@/storage/repositories/segmentRepo' import type { Segment } from '@/core/types' -import type { PeerPresence } from '@/storage/sync/presence' +import type { CaretRange, PeerPresence } from '@/storage/sync/presence' import { StatusPill } from './StatusPill' import { SegmentComments } from './comments/SegmentComments' import { SegmentActionsMenu } from './segments/SegmentActionsMenu' @@ -63,6 +63,8 @@ interface SegmentRowProps { commentAuthor?: string /** A remote peer holding this segment's edit lease (§4.4) — read-only + chip. */ leaseLockedBy?: PeerPresence + /** Report the local caret for remote-cursor presence (§4.4.1); focused row only. */ + onCaret?: (caret: CaretRange) => void onConfirm: () => void /** Revert a confirmed (translated) segment back to draft. */ onUnconfirm: () => void @@ -87,6 +89,7 @@ export function SegmentRow({ spellEnabled, commentAuthor, leaseLockedBy, + onCaret, onConfirm, onUnconfirm, onToggleReviewed, @@ -384,6 +387,7 @@ export function SegmentRow({ spellEnabled={spellEnabled} commentAuthor={commentAuthor} registerHandle={registerHandle} + onCaret={onCaret} onFocus={onFocus} onConfirm={onConfirm} onToggleReviewed={onToggleReviewed} diff --git a/src/features/editor/peers/useProjectSync.ts b/src/features/editor/peers/useProjectSync.ts index fc3fd4b..a969fbe 100644 --- a/src/features/editor/peers/useProjectSync.ts +++ b/src/features/editor/peers/useProjectSync.ts @@ -3,6 +3,7 @@ import { useLiveQuery } from 'dexie-react-hooks' import { shareRepo } from '@/storage/repositories/shareRepo' import { startProjectSync, stopProjectSync } from '@/storage/sync/syncManager' import type { SyncSessionHandle } from '@/storage/sync/syncSession' +import type { CaretRange } from '@/storage/sync/presence' import { usePresenceStore } from './usePresenceStore' /** @@ -14,7 +15,7 @@ import { usePresenceStore } from './usePresenceStore' * It also exposes `setActiveSegment` so presence can follow the user's focus. */ export function useProjectSync(projectId: string | undefined): { - setActiveSegment: (id: string | undefined) => void + setActiveSegment: (id: string | undefined, caret?: CaretRange) => void } { const share = useLiveQuery( () => (projectId ? shareRepo.get(projectId) : undefined), @@ -60,8 +61,8 @@ export function useProjectSync(projectId: string | undefined): { useEffect(() => () => reset(), [reset]) - const setActiveSegment = useCallback((id: string | undefined) => { - handleRef.current?.setActiveSegment(id) + const setActiveSegment = useCallback((id: string | undefined, caret?: CaretRange) => { + handleRef.current?.setActiveSegment(id, caret) }, []) return { setActiveSegment } diff --git a/src/features/editor/rich/RemoteCaretOverlay.tsx b/src/features/editor/rich/RemoteCaretOverlay.tsx new file mode 100644 index 0000000..368a64a --- /dev/null +++ b/src/features/editor/rich/RemoteCaretOverlay.tsx @@ -0,0 +1,120 @@ +import { useEffect, useState } from 'react' +import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext' +import { $getRoot } from 'lexical' +import { mapOffsetToNode } from '@/core/spell/offsets' +import { usePresenceStore } from '../peers/usePresenceStore' +import { buildLeafSpans } from './richOffsets' + +/** + * Live remote cursors for the rich target editor (ROADMAP §4.4.1). + * + * Paints a coloured caret + name label for each remote peer whose presence has + * them on this segment, positioned from their reported plain-text caret offset + * via the same offset→DOM mapping the spell overlay uses. Like that overlay it + * never mutates the editor node tree (so typing/IME/undo and the `{id}` contract + * are untouched) and every DOM measurement is guarded — on any failure it simply + * renders nothing. Browser-only; the pure offset mapping lives in core/features. + */ + +interface CaretPaint { + peerId: string + name: string + color: string + left: number + top: number + height: number +} + +export function RemoteCaretOverlay({ + segmentId, + containerRef, +}: { + segmentId: string + containerRef: React.RefObject +}) { + const [editor] = useLexicalComposerContext() + const peers = usePresenceStore((s) => s.peers) + const [carets, setCarets] = useState([]) + + // Remote peers on this segment that have a caret, plus a stable key so the + // effect only re-subscribes when their identity or caret position changes. + const remotes = peers.filter((p) => p.activeSegmentId === segmentId && p.caret) + const remotesKey = remotes + .map((p) => `${p.peerId}:${p.caret!.anchor}:${p.caret!.focus}:${p.color}:${p.displayName}`) + .join('|') + + useEffect(() => { + if (remotes.length === 0) { + setCarets([]) + return + } + let frame = 0 + const recompute = () => { + cancelAnimationFrame(frame) + frame = requestAnimationFrame(() => { + try { + const container = containerRef.current + if (!container) return + const spans = editor.getEditorState().read(() => buildLeafSpans($getRoot().getFirstChild())) + const crect = container.getBoundingClientRect() + const next: CaretPaint[] = [] + for (const p of remotes) { + const mapped = mapOffsetToNode(spans, p.caret!.focus) + if (!mapped) continue + const el = editor.getElementByKey(mapped.key) + const domText = el?.firstChild + if (!domText || domText.nodeType !== Node.TEXT_NODE) continue + const off = Math.min(mapped.localOffset, domText.textContent?.length ?? 0) + const range = document.createRange() + range.setStart(domText, off) + range.setEnd(domText, off) + const rect = range.getClientRects()[0] ?? range.getBoundingClientRect() + next.push({ + peerId: p.peerId, + name: p.displayName || 'Anonymous', + color: p.color, + left: rect.left - crect.left, + top: rect.top - crect.top, + height: rect.height || 16, + }) + } + setCarets(next) + } catch { + setCarets([]) + } + }) + } + + // Recompute on any editor change (text edits shift caret positions) and once now. + const unregister = editor.registerUpdateListener(recompute) + recompute() + return () => { + cancelAnimationFrame(frame) + unregister() + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [editor, containerRef, remotesKey]) + + if (carets.length === 0) return null + + return ( +
+ {carets.map((c) => ( +
+ + + {c.name} + +
+ ))} +
+ ) +} diff --git a/src/features/editor/rich/RichSegmentEditor.tsx b/src/features/editor/rich/RichSegmentEditor.tsx index 9e658da..ae5bf0f 100644 --- a/src/features/editor/rich/RichSegmentEditor.tsx +++ b/src/features/editor/rich/RichSegmentEditor.tsx @@ -43,6 +43,9 @@ import { InlineTagChip } from './InlineTagChip' import { SpellUnderlinePlugin } from './SpellUnderlinePlugin' import { TrackedChangesPlugin } from './TrackedChangesPlugin' import { ChangeHoverCard } from './ChangeHoverCard' +import { RemoteCaretOverlay } from './RemoteCaretOverlay' +import { selectionToCaretRange } from './richOffsets' +import type { CaretRange } from '@/storage/sync/presence' /** Initial-state builder: seed a paragraph from plain text, turning `{id}` * placeholders into atomic InlineTagNodes (chips). */ @@ -77,6 +80,7 @@ function insertInlineTag(editor: LexicalEditor, tagId: string, kind: InlineTagKi } const SAVE_DELAY_MS = 300 +const CARET_THROTTLE_MS = 100 export interface RichSegmentEditorProps { segmentId: string @@ -101,6 +105,9 @@ export interface RichSegmentEditorProps { /** Display name attached to comments authored from the format toolbar. */ commentAuthor?: string registerHandle: (handle: SegmentEditorHandle | null) => void + /** Report the local caret as plain-text offsets while focused (§4.4.1); the + * focused segment's editor is the only one given this, so presence follows it. */ + onCaret?: (caret: CaretRange) => void onFocus: () => void onConfirm: () => void onToggleReviewed: () => void @@ -178,6 +185,7 @@ export function RichSegmentEditor(props: RichSegmentEditorProps) { )} + @@ -198,6 +206,10 @@ function EditorLogic(props: RichSegmentEditorProps) { const lastSavedPlainRef = useRef(props.initialPlain) const lastSavedRichRef = useRef(props.initialRich) const saveTimerRef = useRef | null>(null) + // Throttle presence caret reports so a burst of selection changes / keystrokes + // sends at most one every CARET_THROTTLE_MS. + const caretTimerRef = useRef | null>(null) + const pendingCaretRef = useRef(null) // Reflect lock changes onto the editor's editability after mount. useEffect(() => { @@ -244,14 +256,30 @@ function EditorLogic(props: RichSegmentEditorProps) { const setSelection = useEditorSelectionStore.getState().setText + const reportCaret = (caret: CaretRange) => { + pendingCaretRef.current = caret + if (caretTimerRef.current) return + caretTimerRef.current = setTimeout(() => { + caretTimerRef.current = null + const c = pendingCaretRef.current + pendingCaretRef.current = null + if (c) propsRef.current.onCaret?.(c) + }, CARET_THROTTLE_MS) + } + const unregisters = [ editor.registerUpdateListener(({ editorState, prevEditorState }) => { - // Mirror the current text selection to the Lookup panel (cheap read). + // Mirror the current text selection to the Lookup panel (cheap read), and + // report the caret for remote-cursor presence when this editor is focused + // (only the focused segment is given `onCaret`, §4.4.1). editorState.read(() => { const sel = $getSelection() - if ($isRangeSelection(sel) && !sel.isCollapsed()) { - const text = sel.getTextContent() - if (text.trim()) setSelection(text) + if ($isRangeSelection(sel)) { + if (!sel.isCollapsed()) { + const text = sel.getTextContent() + if (text.trim()) setSelection(text) + } + if (propsRef.current.onCaret) reportCaret(selectionToCaretRange(sel)) } }) // Skip selection-only changes (node tree unchanged). @@ -360,6 +388,7 @@ function EditorLogic(props: RichSegmentEditorProps) { return () => { if (saveTimerRef.current) clearTimeout(saveTimerRef.current) + if (caretTimerRef.current) clearTimeout(caretTimerRef.current) unregisters.forEach((u) => u()) propsRef.current.registerHandle(null) } diff --git a/src/features/editor/rich/richOffsets.ts b/src/features/editor/rich/richOffsets.ts new file mode 100644 index 0000000..817ac90 --- /dev/null +++ b/src/features/editor/rich/richOffsets.ts @@ -0,0 +1,74 @@ +import { $getRoot, $isTextNode, type LexicalNode, type Point, type RangeSelection } from 'lexical' +import type { NodeSpan } from '@/core/spell/offsets' +import type { CaretRange } from '@/storage/sync/presence' + +/** + * Map between a Lexical selection and plain-text offsets for remote caret + * rendering (ROADMAP §4.4.1). Both directions must agree with the plain target + * that `richStateToPlain` derives (`$getRoot().getTextContent()`): a tag chip + * contributes its `{id}` placeholder, and a `delete` change-mark projects to ''. + * These helpers reproduce exactly that projection so a caret offset reported by + * one peer lands on the same character in another peer's editor. Must run inside + * an `editor.getEditorState().read()` — Lexical nodes are only valid there. + */ + +function childrenOf(node: LexicalNode): LexicalNode[] { + const getChildren = (node as { getChildren?: () => LexicalNode[] }).getChildren + return typeof getChildren === 'function' ? getChildren.call(node) : [] +} + +/** Plain-text offset of `point` within `node`'s projection, or null if outside it. */ +function offsetWithin(node: LexicalNode, point: Point): number | null { + if ($isTextNode(node)) { + if (node.getKey() === point.key) return Math.min(point.offset, node.getTextContent().length) + return null + } + const kids = childrenOf(node) + if (node.getKey() === point.key) { + // Element point: `offset` is a child index → sum the plain text before it. + let acc = 0 + for (let i = 0; i < point.offset && i < kids.length; i += 1) acc += kids[i].getTextContent().length + return acc + } + if (kids.length === 0) return null // atomic node (tag / line break), point not on it + // A node that projects to '' (a delete change-mark) collapses any inner point + // to its start, matching the plain text where its content does not appear. + const projectsEmpty = node.getTextContent() === '' + let acc = 0 + for (const kid of kids) { + const inner = offsetWithin(kid, point) + if (inner !== null) return projectsEmpty ? 0 : acc + inner + acc += kid.getTextContent().length + } + return null +} + +/** Convert a live range selection to plain-text anchor/focus offsets. */ +export function selectionToCaretRange(selection: RangeSelection): CaretRange { + const para = $getRoot().getFirstChild() + const toOffset = (point: Point): number => { + if (!para) return 0 + return offsetWithin(para, point) ?? para.getTextContent().length + } + return { anchor: toOffset(selection.anchor), focus: toOffset(selection.focus) } +} + +/** + * Ordered leaf spans of the segment's single paragraph with their plain-text + * lengths, built so their lengths sum to the plain target — text nodes and + * atomic nodes (tags, line breaks) become spans; a delete change-mark's subtree + * is skipped (it projects to ''). Mirrors {@link selectionToCaretRange}, so + * `mapOffsetToNode` resolves a reported caret offset to the right text node. + */ +export function buildLeafSpans(node: LexicalNode | null): NodeSpan[] { + if (!node) return [] + if ($isTextNode(node)) { + return [{ key: node.getKey(), length: node.getTextContent().length, isText: true }] + } + const kids = childrenOf(node) + if (kids.length === 0) { + return [{ key: node.getKey(), length: node.getTextContent().length, isText: false }] + } + if (node.getTextContent() === '') return [] // delete change-mark: contributes nothing + return kids.flatMap(buildLeafSpans) +} diff --git a/tests/e2e/lan-collaboration.spec.ts b/tests/e2e/lan-collaboration.spec.ts index 9f2d763..93724d0 100644 --- a/tests/e2e/lan-collaboration.spec.ts +++ b/tests/e2e/lan-collaboration.spec.ts @@ -87,3 +87,14 @@ test('simultaneous entry yields one editor + one viewer, and the lease releases await expect(viewer.getByTestId('lease-chip-1')).toHaveCount(0, { timeout: 10_000 }) await expect(targetEditor(viewer, 1)).toHaveAttribute('contenteditable', 'true') }) + +test("a peer's caret renders as a live remote cursor in the other tab", async ({ context }) => { + const { page1, page2 } = await openSharedProjectInTwoTabs(context) + + // Tab 1 edits segment 1, reporting its caret through presence (§4.4.1). + await targetEditor(page1, 1).click() + await page1.keyboard.type('hi') + + // Tab 2, which is not on that segment, paints tab 1's remote caret + name label. + await expect(page2.getByTestId('remote-caret').first()).toBeAttached({ timeout: 10_000 }) +}) diff --git a/tests/unit/richOffsets.test.ts b/tests/unit/richOffsets.test.ts new file mode 100644 index 0000000..8c4dc77 --- /dev/null +++ b/tests/unit/richOffsets.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from 'vitest' +import { + createEditor, + $getRoot, + $createParagraphNode, + $createTextNode, + $createRangeSelection, + $setSelection, + $getSelection, + $isRangeSelection, + type LexicalEditor, +} from 'lexical' +import { RICH_NAMESPACE, getRichNodes } from '@/core/editor/richText' +import { $createInlineTagNode } from '@/features/editor/rich/InlineTagNode' +import { $createChangeMarkNode } from '@/features/editor/rich/ChangeMarkNode' +import { selectionToCaretRange, buildLeafSpans } from '@/features/editor/rich/richOffsets' + +/** + * The reported caret offsets + rendering spans must agree with the plain target + * `richStateToPlain` derives: a tag contributes `{id}`, a delete change-mark + * contributes ''. These headless tests build real editor states and assert both. + */ +function headlessEditor(): LexicalEditor { + return createEditor({ namespace: RICH_NAMESPACE, nodes: getRichNodes(), onError: () => {} }) +} + +describe('richOffsets: text + inline tag', () => { + it('reports caret offsets in the same space as the plain projection', () => { + const editor = headlessEditor() + let range: unknown + editor.update( + () => { + const para = $createParagraphNode() + const t1 = $createTextNode('Hello ') + const tag = $createInlineTagNode('1') // getTextContent → "{1}" (3 chars) + const t2 = $createTextNode(' wrld') + para.append(t1, tag, t2) + $getRoot().append(para) + // Caret 3 chars into " wrld" → plain 6 + 3 + 3 = 12. + const sel = $createRangeSelection() + sel.anchor.set(t2.getKey(), 3, 'text') + sel.focus.set(t2.getKey(), 3, 'text') + $setSelection(sel) + }, + { discrete: true }, + ) + editor.getEditorState().read(() => { + const s = $getSelection() + if ($isRangeSelection(s)) range = selectionToCaretRange(s) + }) + expect(range).toEqual({ anchor: 12, focus: 12 }) + }) + + it('builds leaf spans whose lengths match the plain projection', () => { + const editor = headlessEditor() + let spans: ReturnType = [] + let plainLen = 0 + editor.update( + () => { + const para = $createParagraphNode() + para.append($createTextNode('Hello '), $createInlineTagNode('1'), $createTextNode(' wrld')) + $getRoot().append(para) + }, + { discrete: true }, + ) + editor.getEditorState().read(() => { + spans = buildLeafSpans($getRoot().getFirstChild()) + plainLen = $getRoot().getTextContent().length + }) + expect(spans.map((s) => [s.length, s.isText])).toEqual([ + [6, true], + [3, false], + [5, true], + ]) + expect(spans.reduce((n, s) => n + s.length, 0)).toBe(plainLen) + }) +}) + +describe('richOffsets: delete change-mark projects to nothing', () => { + it('skips a delete mark in spans and collapses a caret past it', () => { + const editor = headlessEditor() + let spans: ReturnType = [] + let plainLen = 0 + let caret: unknown + editor.update( + () => { + const para = $createParagraphNode() + const del = $createChangeMarkNode({ + changeId: 'c1', + changeType: 'delete', + authorId: 'a', + authorName: 'A', + createdAt: 0, + }) + del.append($createTextNode('GONE')) + const tail = $createTextNode('kept') + para.append($createTextNode('ab'), del, tail) + $getRoot().append(para) + // Plain projection is "ab" + "" + "kept" = "abkept" (6). Caret 2 into "kept". + const sel = $createRangeSelection() + sel.anchor.set(tail.getKey(), 2, 'text') + sel.focus.set(tail.getKey(), 2, 'text') + $setSelection(sel) + }, + { discrete: true }, + ) + editor.getEditorState().read(() => { + spans = buildLeafSpans($getRoot().getFirstChild()) + plainLen = $getRoot().getTextContent().length + const s = $getSelection() + if ($isRangeSelection(s)) caret = selectionToCaretRange(s) + }) + expect(plainLen).toBe(6) // "abkept" — the deleted text is not projected + expect(spans.map((s) => [s.length, s.isText])).toEqual([ + [2, true], + [4, true], + ]) + // "ab" (2) + skipped delete (0) + 2 into "kept" = 4. + expect(caret).toEqual({ anchor: 4, focus: 4 }) + }) +}) diff --git a/tests/unit/spell.offsets.test.ts b/tests/unit/spell.offsets.test.ts index c5136be..d2854d1 100644 --- a/tests/unit/spell.offsets.test.ts +++ b/tests/unit/spell.offsets.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { mapTokenToNode, type NodeSpan } from '@/core/spell/offsets' +import { mapTokenToNode, mapOffsetToNode, type NodeSpan } from '@/core/spell/offsets' // "Hello {1} wrld" → text "Hello " (0..6), tag "{1}" (6..9), text " wrld" (9..14) const SPANS: NodeSpan[] = [ @@ -40,3 +40,30 @@ describe('mapTokenToNode', () => { }) }) }) + +describe('mapOffsetToNode (remote caret, §4.4.1)', () => { + it('maps a caret inside the first text node', () => { + expect(mapOffsetToNode(SPANS, 3)).toEqual({ key: 't1', localOffset: 3 }) + }) + + it('resolves a boundary between two text spans to the end of the earlier one', () => { + // Offset 6 is the end of t1 (and start of the tag) — snap to t1's end. + expect(mapOffsetToNode(SPANS, 6)).toEqual({ key: 't1', localOffset: 6 }) + }) + + it('maps a caret after a tag to the following text node', () => { + // Offset 9 is the tag's end / t2's start. + expect(mapOffsetToNode(SPANS, 9)).toEqual({ key: 't2', localOffset: 0 }) + // Offset 12 is inside t2 → local 3. + expect(mapOffsetToNode(SPANS, 12)).toEqual({ key: 't2', localOffset: 3 }) + }) + + it('maps the caret at the very end to the last text node', () => { + expect(mapOffsetToNode(SPANS, 14)).toEqual({ key: 't2', localOffset: 5 }) + }) + + it('returns null past the end or for a negative offset', () => { + expect(mapOffsetToNode(SPANS, 15)).toBeNull() + expect(mapOffsetToNode(SPANS, -1)).toBeNull() + }) +})