import type { CursorsProps as CursorsContainerProps } from 'moi/collab' import type { UserProfile } from '@/lib/collab/types' import type { JsonValue } from 'moi' import { useLayoutEffect, useRef } from 'react' import type { PointerEvent, ReactNode, Ref, RefObject } from 'react' import { IconPointer2 } from '@tabler/icons-react' import { cn } from '@/client/lib/cn' import { Badge } from '@/ui-components/badge' import { presenceChannels, usePresenceChannel, usePresencePublisher, useUsers } from '../hooks' import { userDisplayName } from '@/client/lib/user-display-name' import { hasPresence } from './presence-helpers' export type PointerPosition = { x: number y: number target?: string targetX?: number targetY?: number } function pointerPosition(value: JsonValue): PointerPosition | null { if (!value || typeof value !== 'object' || Array.isArray(value)) return null if (typeof value.x !== 'number' || typeof value.y !== 'number') return null if (!Number.isFinite(value.x) || !Number.isFinite(value.y)) return null return { x: value.x, y: value.y, ...(typeof value.target === 'string' ? { target: value.target } : {}), ...(typeof value.targetX === 'number' && Number.isFinite(value.targetX) ? { targetX: value.targetX } : {}), ...(typeof value.targetY === 'number' && Number.isFinite(value.targetY) ? { targetY: value.targetY } : {}) } } export function CursorsContainer({ id = 'default', ...props }: CursorsContainerProps) { const channel = presenceChannels.cursor(id) const cursors = usePresenceChannel(channel) const publish = usePresencePublisher(channel, null, hasPresence) const byConnection = new Map() for (const { connectionId, userId, value } of cursors) { const point = pointerPosition(value) if (point) byConnection.set(connectionId, { id: userId, point }) } const entries = [...byConnection] const profiles = useUsers(entries.map(([, cursor]) => cursor.id)) return ( ({ connectionId, point, profile: profiles[index] }))} /> ) } export type CursorsProps = { id?: string children: ReactNode className?: string cursors: readonly { connectionId: string; point: PointerPosition; profile?: UserProfile }[] onPositionChange?: (point: PointerPosition | null) => void } export function Cursors({ id = 'default', children, className, cursors, onPositionChange }: CursorsProps) { const root = useRef(null) const layer = useRef(null) // Keep the overlay in the visible viewport when the cursor area itself scrolls. useLayoutEffect(() => { const element = root.current const overlay = layer.current if (!element || !overlay) return const position = () => { overlay.style.transform = `translate(${element.scrollLeft}px, ${element.scrollTop}px)` } position() element.addEventListener('scroll', position) return () => element.removeEventListener('scroll', position) }, []) const move = (event: PointerEvent) => { if (event.pointerType === 'touch') return const element = root.current if ( !element || !(event.target instanceof Element) || event.target.closest('[data-collab-cursors]') !== element ) return const bounds = element.getBoundingClientRect() const target = event.target instanceof Element ? event.target.closest('[data-collab-target]') : null const anchor = target && element.contains(target) ? target : null const rect = anchor?.getBoundingClientRect() onPositionChange?.({ x: event.clientX - bounds.left - element.clientLeft + element.scrollLeft, y: event.clientY - bounds.top - element.clientTop + element.scrollTop, ...(anchor && rect ? { target: anchor.dataset.collabTarget ?? '', targetX: rect.width ? (event.clientX - rect.left) / rect.width : 0, targetY: rect.height ? (event.clientY - rect.top) / rect.height : 0 } : {}) }) } return (
{ if ( event.target instanceof Element && event.target.closest('[data-collab-cursors]') === event.currentTarget ) onPositionChange?.(null) }} > {children}
) } type RemoteCursorProps = { root: RefObject point: PointerPosition profile?: UserProfile } // Semantic anchors follow their own data through scrolling and reordering. // A cursor on a different record's modal has no matching anchor and stays hidden. function RemoteCursor({ root, point, profile }: RemoteCursorProps) { const marker = useRef(null) useLayoutEffect(() => { const element = root.current const node = marker.current if (!element || !node) return const position = (animate = false) => { let x = point.x - element.scrollLeft let y = point.y - element.scrollTop if (point.target) { const target = [...element.querySelectorAll('[data-collab-target]')].find( candidate => candidate.dataset.collabTarget === point.target ) if (!target) { node.hidden = true return } const bounds = element.getBoundingClientRect() const rect = target.getBoundingClientRect() x = rect.left - bounds.left - element.clientLeft + rect.width * (point.targetX ?? 0) y = rect.top - bounds.top - element.clientTop + rect.height * (point.targetY ?? 0) } const transform = `translate(${x}px, ${y}px)` if (node.hidden || node.style.transform !== transform) { // Smooth pointer updates; place new cursors and layout corrections immediately. node.dataset.moving = animate && !node.hidden ? 'true' : 'false' node.style.transform = transform } node.hidden = false } position(true) const reposition = () => position() const observer = new ResizeObserver(reposition) observer.observe(element) const changes = new MutationObserver(reposition) changes.observe(element, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-collab-target'] }) element.addEventListener('scroll', reposition, true) window.addEventListener('resize', reposition) return () => { observer.disconnect() changes.disconnect() element.removeEventListener('scroll', reposition, true) window.removeEventListener('resize', reposition) } }, [root, point]) return } type CursorProps = { profile?: UserProfile ref?: Ref } function Cursor({ profile: user, ref }: CursorProps) { return ( ) }