import { type DocumentChange, getV4Steps, } from '../../core/change/document-change'; import { isElementNode, type JsonEditorValue, type JsonElementNode, type JsonNode, } from '../../core/change/tokens'; import { mapV4StreamPoints, type MapV4PointOptions, } from '../../core/change/v4/map-point'; import type { V4Step } from '../../core/change/v4/types'; import type { Path } from '../../interfaces/path'; import type { Point } from '../../interfaces/point'; import type { Range } from '../../interfaces/range'; import { MAIN_ROOT_KEY, readDocumentRootChildren, } from '../../internal/root-location'; import type { SyncPresencePeerState, SyncPresenceServerFrame, SyncWirePoint, SyncWireSelection, } from '../wire/presence'; const MAX_ENTRY_RING = 64; /** Remote collaborator presence projected onto the local editor's live document. */ export type SyncRemoteCursor = Readonly<{ actor: string; peer: string; selection: Range | null; }>; const rootChildrenOf = ( value: JsonEditorValue, root: string ): readonly JsonNode[] | null => readDocumentRootChildren(value, root) ?? null; const isTextBearingElement = (node: JsonElementNode): boolean => node.children.length > 0 && node.children.some((child) => !isElementNode(child)); const textStreamLengthOf = (node: JsonElementNode): number => { let len = 0; for (const child of node.children) { len += isElementNode(child) ? 1 : child.text.length; } return len; }; /** * Encodes a Plite `Point` (in `root`) as a v4 element-ID + text-stream offset * so remote peers can project it across concurrent edits. */ export const encodePointToWire = ( value: JsonEditorValue, point: Point, root: string = MAIN_ROOT_KEY ): SyncWirePoint | null => { const children = rootChildrenOf(value, root); if (!children) return null; let list: readonly JsonNode[] = children; let lastElement: JsonElementNode | null = null; let lastElementDepth = -1; for (let depth = 0; depth < point.path.length; depth += 1) { const index = point.path[depth]; const node = index === undefined ? undefined : list[index]; if (!node) return null; if (isElementNode(node)) { lastElement = node; lastElementDepth = depth; list = node.children; } else if (depth === point.path.length - 1) { if (!lastElement || typeof lastElement.id !== 'string') return null; let streamOffset = 0; for (let i = 0; i < index; i += 1) { const sibling = lastElement.children[i]; if (!sibling) break; streamOffset += isElementNode(sibling) ? 1 : sibling.text.length; } const clampedLeafOffset = Math.max( 0, Math.min(point.offset, node.text.length) ); return { id: lastElement.id, offset: streamOffset + clampedLeafOffset, ...(root === MAIN_ROOT_KEY ? {} : { root }), }; } else { return null; } } // Fallback when point path ended on an element directly. if ( lastElement && lastElementDepth >= 0 && typeof lastElement.id === 'string' ) { return { id: lastElement.id, offset: Math.max( 0, Math.min(point.offset, textStreamLengthOf(lastElement)) ), ...(root === MAIN_ROOT_KEY ? {} : { root }), }; } return null; }; export const encodeSelectionToWire = ( value: JsonEditorValue, selection: Range | null, root: string = MAIN_ROOT_KEY ): SyncWireSelection | null => { if (!selection) return null; const anchorRoot = selection.anchor.root ?? root; const focusRoot = selection.focus.root ?? root; const anchor = encodePointToWire(value, selection.anchor, anchorRoot); const focus = encodePointToWire(value, selection.focus, focusRoot); if (!anchor || !focus) return null; return { anchor, focus }; }; const nodeAtElementPath = ( value: JsonEditorValue, root: string, path: Path ): JsonElementNode | null => { const children = rootChildrenOf(value, root); if (!children || path.length === 0) return null; let list: readonly JsonNode[] = children; let current: JsonNode | undefined; for (const index of path) { current = list[index]; if (!current || !isElementNode(current)) return null; list = current.children; } return current && isElementNode(current) ? current : null; }; const findElementById = ( value: JsonEditorValue, id: string, preferredRoot?: string, hint?: Readonly<{ path: Path; root: string }> | null ): Readonly<{ node: JsonElementNode; path: Path; root: string }> | null => { if (hint && hint.path.length > 0) { const hinted = nodeAtElementPath(value, hint.root, hint.path); if (hinted && hinted.id === id) { return { node: hinted, path: hint.path, root: hint.root }; } } const searchList = ( nodes: readonly JsonNode[], root: string, prefix: Path ): Readonly<{ node: JsonElementNode; path: Path; root: string }> | null => { for (let i = 0; i < nodes.length; i += 1) { const child = nodes[i]; if (!child || !isElementNode(child)) continue; const path = [...prefix, i]; if (child.id === id) return { node: child, path, root }; const nested = searchList(child.children, root, path); if (nested) return nested; } return null; }; if (preferredRoot) { const preferred = rootChildrenOf(value, preferredRoot); if (preferred) { const hit = searchList(preferred, preferredRoot, []); if (hit) return hit; } } if (preferredRoot !== MAIN_ROOT_KEY) { const mainHit = searchList(value.children, MAIN_ROOT_KEY, []); if (mainHit) return mainHit; } if (value.roots) { for (const [rootName, nodes] of Object.entries(value.roots)) { if (rootName === preferredRoot) continue; const hit = searchList(nodes, rootName, []); if (hit) return hit; } } return null; }; /** * Decodes a v4 wire point back to a live Plite `Point` on `value`. Returns * `null` if the target element no longer exists in `value`. */ export const decodeWirePointToPoint = ( value: JsonEditorValue, wire: SyncWirePoint, hint?: Readonly<{ path: Path; root: string }> | null ): Point | null => { const located = findElementById(value, wire.id, wire.root, hint); if (!located) return null; const { node, path, root } = located; if (!isTextBearingElement(node)) { // Descend to first text leaf if the element wraps block children. let current: JsonNode = node; const leafPath = [...path]; while (isElementNode(current) && current.children.length > 0) { const firstChild: JsonNode | undefined = current.children[0]; if (!firstChild) break; leafPath.push(0); current = firstChild; } if (isElementNode(current)) return null; return { offset: Math.max(0, Math.min(wire.offset, current.text.length)), path: leafPath, ...(root === MAIN_ROOT_KEY ? {} : { root }), }; } const total = textStreamLengthOf(node); const clamped = Math.max(0, Math.min(wire.offset, total)); let cursor = 0; let lastTextIndex = -1; let lastTextLen = 0; for (let i = 0; i < node.children.length; i += 1) { const child = node.children[i]; if (!child) continue; if (isElementNode(child)) { if (clamped === cursor && lastTextIndex !== -1) { return { offset: lastTextLen, path: [...path, lastTextIndex], ...(root === MAIN_ROOT_KEY ? {} : { root }), }; } cursor += 1; continue; } const len = child.text.length; lastTextIndex = i; lastTextLen = len; if (clamped <= cursor + len) { return { offset: clamped - cursor, path: [...path, i], ...(root === MAIN_ROOT_KEY ? {} : { root }), }; } cursor += len; } if (lastTextIndex !== -1) { return { offset: lastTextLen, path: [...path, lastTextIndex], ...(root === MAIN_ROOT_KEY ? {} : { root }), }; } return null; }; export const decodeWireSelectionToRange = ( value: JsonEditorValue, wire: SyncWireSelection | null ): Range | null => { if (!wire) return null; const anchor = decodeWirePointToPoint(value, wire.anchor); const focus = decodeWirePointToPoint(value, wire.focus); if (!anchor || !focus) return null; return { anchor, focus }; }; const PRESENCE_POINT_OPTIONS: MapV4PointOptions = { insertAssociation: 1, splitAssociation: -1, }; const mapWireSelectionThroughSteps = ( selection: SyncWireSelection, steps: readonly V4Step[], beforeDoc?: JsonEditorValue ): SyncWireSelection | null => { if (steps.length === 0) return selection; const { points } = mapV4StreamPoints( steps, [selection.anchor, selection.focus], [PRESENCE_POINT_OPTIONS, PRESENCE_POINT_OPTIONS], beforeDoc ); const anchor = points[0]; const focus = points[1]; if (!anchor || !focus) return null; return { anchor, focus }; }; export const mapWireSelectionThroughChange = ( selection: SyncWireSelection, change: DocumentChange, beforeDoc?: JsonEditorValue ): SyncWireSelection | null => { const steps = getV4Steps(change); if (!steps || steps.length === 0) return selection; return mapWireSelectionThroughSteps(selection, steps, beforeDoc); }; type RingEntry = Readonly<{ before: JsonEditorValue; change: DocumentChange; version: number; }>; const EMPTY_IDS: readonly string[] = Object.freeze([]); const EMPTY_CURSORS: readonly SyncRemoteCursor[] = Object.freeze([]); const samePoint = (left: Point, right: Point): boolean => left.offset === right.offset && left.root === right.root && left.path.length === right.path.length && left.path.every((segment, index) => segment === right.path[index]); const sameRange = (left: Range | null, right: Range | null): boolean => left === right || (left !== null && right !== null && samePoint(left.anchor, right.anchor) && samePoint(left.focus, right.focus)); const sameCursor = ( left: SyncRemoteCursor | undefined, right: SyncRemoteCursor ): boolean => left !== undefined && left.peer === right.peer && left.actor === right.actor && sameRange(left.selection, right.selection); /** * Tracks ephemeral remote collaborator presence, projecting each remote * selection forward through confirmed entries (via a bounded ring buffer + * future-version re-projection) and local unsent edits onto the live editor * document. */ export const createPresenceTracker = () => { const rawPeers = new Map(); const projected = new Map(); const ring: RingEntry[] = []; let confirmedVersion: number | null = null; let cachedIds: readonly string[] = EMPTY_IDS; let cachedCursors: readonly SyncRemoteCursor[] = EMPTY_CURSORS; const anyListeners = new Set<() => void>(); const idListeners = new Set<() => void>(); const peerListeners = new Map void>>(); const notifyAll = ( changedPeers: ReadonlySet, idsChanged: boolean ) => { if (idsChanged) { const nextIds = [...projected.keys()].sort((a, b) => a.localeCompare(b)); cachedIds = nextIds.length === 0 ? EMPTY_IDS : Object.freeze(nextIds); } if (idsChanged || changedPeers.size > 0) { const nextCursors = cachedIds .map((peer) => projected.get(peer)) .filter((cursor): cursor is SyncRemoteCursor => cursor !== undefined); cachedCursors = nextCursors.length === 0 ? EMPTY_CURSORS : Object.freeze(nextCursors); } if (idsChanged) { for (const listener of [...idListeners]) listener(); } for (const peer of changedPeers) { const set = peerListeners.get(peer); if (set) { for (const listener of [...set]) listener(); } } if (idsChanged || changedPeers.size > 0) { for (const listener of [...anyListeners]) listener(); } }; const projectPeer = ( raw: SyncPresencePeerState, currentDoc: JsonEditorValue, unsentChanges: readonly DocumentChange[], unsentBase?: JsonEditorValue ): SyncRemoteCursor => { if (raw.selection === null) { return { actor: raw.actor, peer: raw.peer, selection: null }; } // If a peer sent presence at a future version we have not confirmed yet, // still try decoding directly against currentDoc, and re-project once those // entries arrive in recordConfirmedEntry. let wire: SyncWireSelection | null = raw.selection; if (confirmedVersion !== null && raw.version < confirmedVersion) { for (const entry of ring) { if ( wire && entry.version > raw.version && entry.version <= confirmedVersion ) { wire = mapWireSelectionThroughChange( wire, entry.change, entry.before ); } } } if (wire && unsentChanges.length > 0) { const unsentSteps: V4Step[] = []; for (const unsent of unsentChanges) { const steps = getV4Steps(unsent); if (steps && steps.length > 0) unsentSteps.push(...steps); } if (unsentSteps.length > 0) { wire = mapWireSelectionThroughSteps(wire, unsentSteps, unsentBase); } } if (!wire) { return { actor: raw.actor, peer: raw.peer, selection: null }; } const prevCursor = projected.get(raw.peer); const elementHintOf = (point: Point | undefined) => point && point.path.length > 1 ? { path: point.path.slice(0, -1), root: point.root ?? MAIN_ROOT_KEY, } : null; const anchor = decodeWirePointToPoint( currentDoc, wire.anchor, elementHintOf(prevCursor?.selection?.anchor) ); const focus = decodeWirePointToPoint( currentDoc, wire.focus, elementHintOf(prevCursor?.selection?.focus) ); return { actor: raw.actor, peer: raw.peer, selection: anchor && focus ? { anchor, focus } : null, }; }; const reproject = ( currentDoc: JsonEditorValue, unsentChanges: readonly DocumentChange[], unsentBase?: JsonEditorValue ) => { if (rawPeers.size === 0 && projected.size === 0) return; const changedPeers = new Set(); let idsChanged = false; for (const peerId of [...projected.keys()]) { if (!rawPeers.has(peerId)) { projected.delete(peerId); changedPeers.add(peerId); idsChanged = true; } } for (const [peerId, raw] of rawPeers) { const had = projected.has(peerId); const prev = projected.get(peerId); const next = projectPeer(raw, currentDoc, unsentChanges, unsentBase); if (!had) idsChanged = true; if (!sameCursor(prev, next)) { projected.set(peerId, next); changedPeers.add(peerId); } } if (idsChanged || changedPeers.size > 0) { notifyAll(changedPeers, idsChanged); } }; return { clear: () => { if (rawPeers.size === 0 && projected.size === 0) return; const prevIds = new Set(projected.keys()); rawPeers.clear(); projected.clear(); notifyAll(prevIds, true); }, handleFrame: ( frame: SyncPresenceServerFrame, currentDoc: JsonEditorValue, unsentChanges: readonly DocumentChange[], unsentBase?: JsonEditorValue ) => { switch (frame.type) { case 'presence': { rawPeers.set(frame.peer, { actor: frame.actor, peer: frame.peer, selection: frame.selection, version: frame.version, }); break; } case 'presence_leave': { rawPeers.delete(frame.peer); break; } case 'presence_state': { rawPeers.clear(); for (const peer of frame.peers) { rawPeers.set(peer.peer, peer); } break; } } reproject(currentDoc, unsentChanges, unsentBase); }, recordConfirmedEntry: ( version: number, change: DocumentChange, before: JsonEditorValue, currentDoc: JsonEditorValue, unsentChanges: readonly DocumentChange[], unsentBase?: JsonEditorValue ) => { confirmedVersion = version; ring.push({ before, change, version }); if (ring.length > MAX_ENTRY_RING) ring.shift(); reproject(currentDoc, unsentChanges, unsentBase); }, recordSnapshot: ( version: number, currentDoc: JsonEditorValue, unsentChanges: readonly DocumentChange[], unsentBase?: JsonEditorValue ) => { confirmedVersion = version; ring.length = 0; reproject(currentDoc, unsentChanges, unsentBase); }, reproject, remoteCursor: (peer: string): SyncRemoteCursor | null => projected.get(peer) ?? null, remoteCursorIds: (): readonly string[] => cachedIds, remoteCursors: (): readonly SyncRemoteCursor[] => cachedCursors, subscribeCursor: (peer: string, listener: () => void) => { let set = peerListeners.get(peer); if (!set) { set = new Set(); peerListeners.set(peer, set); } set.add(listener); return () => { set.delete(listener); if (set.size === 0) peerListeners.delete(peer); }; }, subscribeIds: (listener: () => void) => { idListeners.add(listener); return () => { idListeners.delete(listener); }; }, subscribeRemoteCursors: (listener: () => void) => { anyListeners.add(listener); return () => { anyListeners.delete(listener); }; }, }; };