moi-computer 0.11.1-next.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/client/api/app-config.ts +7 -4
  2. package/client/app/AppRouter.tsx +2 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +27 -19
  4. package/client/features/applets/{AppletMount.tsx → AppletContainer.tsx} +7 -5
  5. package/client/features/applets/WidgetShell.tsx +3 -3
  6. package/client/features/applets/applet-cache.ts +3 -5
  7. package/client/features/applets/applet-runtime.ts +27 -12
  8. package/client/features/applets/applet-thumbnail.ts +2 -1
  9. package/client/features/chat/applet-chat-intents.ts +14 -6
  10. package/client/features/chat/composer/attachments/draft-attachments.ts +21 -4
  11. package/client/features/chat/messages/MarkdownContent.tsx +5 -2
  12. package/client/features/chat/sessions/browser-tab-state.ts +18 -0
  13. package/client/features/chat/sessions/useSelectedSession.ts +55 -21
  14. package/client/features/chat/useChat.ts +4 -0
  15. package/client/features/collab/applet-api.ts +34 -0
  16. package/client/features/collab/client.ts +239 -0
  17. package/client/features/collab/components/cursors.tsx +199 -0
  18. package/client/features/collab/components/presence-avatars.tsx +61 -0
  19. package/client/features/collab/components/presence-frame.tsx +126 -0
  20. package/client/features/collab/components/presence-group.tsx +23 -0
  21. package/client/features/collab/components/presence-helpers.ts +50 -0
  22. package/client/features/collab/components/user-avatar-group.tsx +22 -0
  23. package/client/features/collab/components/user-avatar.tsx +40 -0
  24. package/client/features/collab/components/user.tsx +50 -0
  25. package/client/features/collab/hooks.tsx +164 -0
  26. package/client/features/collab/host-state.ts +254 -0
  27. package/client/features/collab/index.ts +5 -0
  28. package/client/features/collab/local-user.ts +46 -0
  29. package/client/features/collab/presence-publisher.ts +30 -0
  30. package/client/features/collab/presence-target.ts +8 -0
  31. package/client/features/collab/provider.tsx +79 -0
  32. package/client/features/collab/proxy-user.ts +35 -0
  33. package/client/features/collab/store.ts +156 -0
  34. package/client/features/collab/testing/component-fixtures.tsx +54 -0
  35. package/client/features/collab/testing/fake-engine.ts +129 -0
  36. package/client/features/collab/users.ts +106 -0
  37. package/client/features/collab/workspace-users-menu.tsx +194 -0
  38. package/client/features/connectors/mcp-icons.ts +0 -2
  39. package/client/features/dev/DevIndexPage.tsx +5 -0
  40. package/client/features/dev/DevRoutes.tsx +16 -4
  41. package/client/features/dev/collab/collab-page.tsx +24 -0
  42. package/client/features/dev/collab/collab-playground.tsx +614 -0
  43. package/client/features/dev/collab/local-user-settings.tsx +166 -0
  44. package/client/features/dev/collab/playground-room.ts +33 -0
  45. package/client/features/dev/{UiComponentsPage.tsx → ui-components/ui-components-page.tsx} +1 -1
  46. package/client/features/overview/WidgetCanvas.tsx +3 -1
  47. package/client/features/views/ViewManager.tsx +12 -7
  48. package/client/features/views/api.ts +2 -2
  49. package/client/features/views/useViewBuilderActions.ts +3 -0
  50. package/client/features/workspace/WorkspaceContext.tsx +1 -1
  51. package/client/features/workspace/WorkspaceLayoutContext.tsx +8 -2
  52. package/client/features/workspace/WorkspaceScreen.tsx +19 -11
  53. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  54. package/client/features/workspace/api.ts +2 -1
  55. package/client/features/workspace/browser-tab-state.ts +44 -0
  56. package/client/features/workspace/layout-save.ts +13 -0
  57. package/client/features/workspace/moi-context.ts +2 -1
  58. package/client/features/workspace/useWorkspaceNavigation.ts +20 -8
  59. package/client/index.css +45 -0
  60. package/client/index.tsx +9 -4
  61. package/client/main.tsx +1 -11
  62. package/client/theme.css +4 -1
  63. package/dist/chunk-2jncyq65.js +1 -0
  64. package/dist/{chunk-brr0zbeh.js → chunk-3a48fyf7.js} +2 -2
  65. package/dist/{chunk-tzz101ea.js → chunk-97eg9mjn.js} +1 -1
  66. package/dist/chunk-e2q5ken7.js +68 -0
  67. package/dist/{chunk-zs4mte79.js → chunk-efdyz6xp.js} +1 -1
  68. package/dist/chunk-h2kj1ysj.js +1 -0
  69. package/dist/chunk-jf6czgrz.js +2 -0
  70. package/dist/chunk-nez8sdta.js +1 -0
  71. package/dist/chunk-nzwgm8vc.css +1 -0
  72. package/dist/chunk-ph0h6h86.js +1 -0
  73. package/dist/chunk-ryg9z3kn.js +10 -0
  74. package/dist/chunk-tpn177bt.js +2 -0
  75. package/dist/chunk-vfpsc75k.js +2 -0
  76. package/dist/{chunk-m1fvqssh.js → chunk-z3byfve5.js} +2 -2
  77. package/dist/index.html +1 -1
  78. package/lib/collab/colors.ts +30 -0
  79. package/lib/collab/protocol.ts +84 -0
  80. package/lib/collab/types.ts +52 -0
  81. package/lib/experimental.ts +14 -0
  82. package/lib/moi-context.ts +11 -3
  83. package/lib/navigation.ts +25 -5
  84. package/lib/types.ts +20 -33
  85. package/package.json +2 -2
  86. package/server/AGENTS.md +1 -1
  87. package/server/api.ts +28 -5
  88. package/server/app-config.ts +127 -34
  89. package/server/applet-typecheck.ts +8 -3
  90. package/server/applets/applet-css.ts +1 -1
  91. package/server/applets/build-applet.ts +9 -3
  92. package/server/applets/declarations/base.d.ts +75 -0
  93. package/server/applets/declarations/collab.d.ts +88 -0
  94. package/server/applets/declarations.ts +46 -0
  95. package/server/applets/index.ts +8 -8
  96. package/server/applets/runtime/collab.ts +94 -0
  97. package/server/applets/runtime/moi.ts +12 -19
  98. package/server/applets/runtime/rpc.ts +2 -4
  99. package/server/chat-selection.ts +22 -0
  100. package/server/cli.ts +86 -21
  101. package/server/collab/cloudflare-access.ts +78 -0
  102. package/server/collab/config.ts +18 -0
  103. package/server/collab/manager.ts +407 -0
  104. package/server/collab/service.ts +136 -0
  105. package/server/collab/skill/index.ts +53 -0
  106. package/server/collab/worker-messages.ts +10 -0
  107. package/server/collab/worker.ts +52 -0
  108. package/server/layout.ts +10 -3
  109. package/server/moi-scaffold.ts +55 -84
  110. package/server/preview.ts +1 -1
  111. package/server/skill-update.ts +7 -9
  112. package/server/skills-template.ts +14 -2
  113. package/server/web.ts +65 -17
  114. package/server/workspace-init.ts +6 -3
  115. package/ui-components/avatar.tsx +24 -11
  116. package/ui-components/button.tsx +9 -9
  117. package/ui-components/docs/avatar.md +11 -30
  118. package/workspace/.claude/skills/moi-workspace/SKILL.md +14 -11
  119. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +262 -0
  120. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +10 -7
  121. package/client/assets/mcp/agentation.png +0 -0
  122. package/dist/agentation-4s0nn45p.png +0 -0
  123. package/dist/chunk-2gs8jjx4.css +0 -1
  124. package/dist/chunk-7vvg5fyz.js +0 -68
  125. package/dist/chunk-94m3q9ce.js +0 -1
  126. package/dist/chunk-by2wqgak.js +0 -1
  127. package/dist/chunk-p34hvqt3.js +0 -1
  128. package/dist/chunk-p83f0jnj.js +0 -2
  129. package/dist/chunk-xg01f6pn.js +0 -10
  130. /package/client/features/dev/{UiComponentPreviews.tsx → ui-components/ui-component-previews.tsx} +0 -0
  131. /package/server/applets/{runtime/base.ts → api-base.ts} +0 -0
@@ -0,0 +1,34 @@
1
+ import type * as CollabApi from 'moi/collab'
2
+ import { UserAvatarGroup } from './components/user-avatar-group'
3
+ import { User } from './components/user'
4
+ import { UserAvatar } from './components/user-avatar'
5
+ import { Cursors } from './components/cursors'
6
+ import { PresenceFrame } from './components/presence-frame'
7
+ import { PresenceGroup } from './components/presence-group'
8
+ import { PresenceAvatars } from './components/presence-avatars'
9
+ import {
10
+ useMe,
11
+ usePeers,
12
+ usePresence,
13
+ usePublishPresence,
14
+ useUser,
15
+ useWorkspaceUsers
16
+ } from './hooks'
17
+
18
+ export type AppletCollabApi = typeof CollabApi
19
+
20
+ export const appletCollabApi = {
21
+ Cursors,
22
+ User,
23
+ UserAvatar,
24
+ UserAvatarGroup,
25
+ PresenceFrame,
26
+ PresenceAvatars,
27
+ PresenceGroup,
28
+ useMe,
29
+ usePeers,
30
+ useUser,
31
+ useWorkspaceUsers,
32
+ usePresence,
33
+ usePublishPresence
34
+ } satisfies AppletCollabApi
@@ -0,0 +1,239 @@
1
+ import { wsUrl } from '@/client/lib/ws-url'
2
+ import { COLLAB_PROTOCOL_VERSION } from '@/lib/collab/protocol'
3
+ import type {
4
+ CollabClientMessage,
5
+ CollabServerMessage,
6
+ UserProfile,
7
+ ConnectionLocation,
8
+ PresenceRegistration
9
+ } from '@/lib/collab/types'
10
+
11
+ import {
12
+ getCurrentUser,
13
+ getWorkspaceDirectory,
14
+ subscribeCurrentUserStore,
15
+ subscribeWorkspaceUsersStore
16
+ } from './host-state'
17
+ import type { WorkspaceDirectory } from './host-state'
18
+ import { CollabStore, DISCONNECTED_STATE } from './store'
19
+ import type { ClientState, PresenceEntry } from './store'
20
+
21
+ type Unsubscribe = () => void
22
+
23
+ // A workspace exposes one engine to React. The playground implements this same
24
+ // contract; sockets, timers, and registration storage stay behind it.
25
+ export type CollabEngineApi = {
26
+ readonly workspaceId: string
27
+ readonly enabled: boolean
28
+ start: () => Unsubscribe
29
+ getSnapshot: () => ClientState
30
+ getUsersSnapshot: () => ClientState
31
+ getPresenceSnapshot: (appletId: string, channel: string) => readonly PresenceEntry[]
32
+ subscribe: (listener: () => void) => Unsubscribe
33
+ getCurrentUser: () => UserProfile | undefined
34
+ subscribeCurrentUser: (listener: () => void) => Unsubscribe
35
+ getWorkspaceDirectory: () => WorkspaceDirectory | undefined
36
+ subscribeWorkspaceUsers: (listener: () => void) => Unsubscribe
37
+ getLocation: () => ConnectionLocation | null
38
+ setLocation: (location: ConnectionLocation | null) => void
39
+ setPresence: (registration: PresenceRegistration) => void
40
+ deletePresence: (registrationId: string) => void
41
+ }
42
+
43
+ const noop = () => {}
44
+ const EMPTY_PRESENCE: readonly PresenceEntry[] = []
45
+
46
+ export const NO_ENGINE: CollabEngineApi = {
47
+ workspaceId: '',
48
+ enabled: false,
49
+ start: () => noop,
50
+ getSnapshot: () => DISCONNECTED_STATE,
51
+ getUsersSnapshot: () => DISCONNECTED_STATE,
52
+ getPresenceSnapshot: () => EMPTY_PRESENCE,
53
+ subscribe: () => noop,
54
+ getCurrentUser,
55
+ subscribeCurrentUser: subscribeCurrentUserStore,
56
+ getWorkspaceDirectory: () => undefined,
57
+ subscribeWorkspaceUsers: () => noop,
58
+ getLocation: () => null,
59
+ setLocation: noop,
60
+ setPresence: noop,
61
+ deletePresence: noop
62
+ }
63
+
64
+ // One presence connection per mounted workspace with an explicit profile.
65
+ export class CollabClient implements CollabEngineApi {
66
+ readonly store = new CollabStore()
67
+ private socket: WebSocket | null = null
68
+ private retry: ReturnType<typeof setTimeout> | undefined
69
+ private heartbeat: ReturnType<typeof setInterval> | undefined
70
+ private unsubscribeCurrentUser: (() => void) | undefined
71
+ private presenceTimer: ReturnType<typeof setTimeout> | undefined
72
+ private queuedPresence = new Map<string, CollabClientMessage>()
73
+ private stopped = true
74
+ private attempts = 0
75
+ private lastMessageAt = 0
76
+ private userId = getCurrentUser()?.id
77
+
78
+ constructor(
79
+ readonly workspaceId: string,
80
+ readonly enabled = true
81
+ ) {
82
+ this.store.setSender(message => this.send(message))
83
+ }
84
+
85
+ getSnapshot = (): ClientState => (this.enabled ? this.store.getSnapshot() : DISCONNECTED_STATE)
86
+ getUsersSnapshot = (): ClientState =>
87
+ this.enabled ? this.store.getUsersSnapshot() : DISCONNECTED_STATE
88
+ getPresenceSnapshot = (appletId: string, channel: string): readonly PresenceEntry[] =>
89
+ this.enabled ? this.store.getPresenceSnapshot(appletId, channel) : EMPTY_PRESENCE
90
+ subscribe = (listener: () => void): Unsubscribe =>
91
+ this.enabled ? this.store.subscribe(listener) : noop
92
+ getCurrentUser = getCurrentUser
93
+ subscribeCurrentUser = subscribeCurrentUserStore
94
+ getWorkspaceDirectory = (): WorkspaceDirectory | undefined =>
95
+ getWorkspaceDirectory(this.workspaceId)
96
+ subscribeWorkspaceUsers = (listener: () => void): Unsubscribe =>
97
+ subscribeWorkspaceUsersStore(this.workspaceId, listener)
98
+ getLocation = (): ConnectionLocation | null => (this.enabled ? this.store.getLocation() : null)
99
+ setLocation = (location: ConnectionLocation | null): void => {
100
+ this.store.setLocation(location)
101
+ }
102
+ setPresence = (registration: PresenceRegistration): void => {
103
+ if (this.enabled) this.store.setPresence(registration)
104
+ }
105
+ deletePresence = (registrationId: string): void => {
106
+ if (this.enabled) this.store.deletePresence(registrationId)
107
+ }
108
+
109
+ start(): () => void {
110
+ if (!this.enabled) return noop
111
+ if (!this.stopped) return () => {}
112
+ this.stopped = false
113
+ this.userId = getCurrentUser()?.id
114
+ this.unsubscribeCurrentUser = subscribeCurrentUserStore(() => {
115
+ const profile = getCurrentUser()
116
+ if (profile?.id !== this.userId) {
117
+ this.userId = profile?.id
118
+ this.store.disconnect()
119
+ clearTimeout(this.retry)
120
+ if (this.socket) this.socket.close()
121
+ else this.connect()
122
+ } else if (profile) this.send({ type: 'profile', profile })
123
+ })
124
+ this.connect()
125
+ return () => this.stop()
126
+ }
127
+
128
+ private wantsConnection(): boolean {
129
+ return !this.stopped && getCurrentUser() !== undefined
130
+ }
131
+
132
+ private connect(): void {
133
+ if (!this.wantsConnection()) {
134
+ this.store.disconnect()
135
+ return
136
+ }
137
+ if (this.socket) return
138
+ clearTimeout(this.retry)
139
+ this.store.connecting()
140
+ const socket = new WebSocket(
141
+ wsUrl(`/api/workspaces/${encodeURIComponent(this.workspaceId)}/collab/ws`)
142
+ )
143
+ this.socket = socket
144
+ socket.onopen = () => {
145
+ if (socket !== this.socket) return
146
+ this.lastMessageAt = Date.now()
147
+ const profile = getCurrentUser()
148
+ if (!profile) {
149
+ socket.close()
150
+ return
151
+ }
152
+ this.heartbeat = setInterval(() => {
153
+ if (Date.now() - this.lastMessageAt > 45_000) socket.close()
154
+ else this.rawSend({ type: 'ping' })
155
+ }, 15_000)
156
+ this.rawSend({
157
+ type: 'join',
158
+ version: COLLAB_PROTOCOL_VERSION,
159
+ profile,
160
+ location: this.store.getLocation()
161
+ })
162
+ }
163
+ socket.onmessage = event => {
164
+ if (socket !== this.socket) return
165
+ this.lastMessageAt = Date.now()
166
+ try {
167
+ const message = JSON.parse(String(event.data)) as CollabServerMessage
168
+ if (message.type === 'welcome') this.attempts = 0
169
+ const rejectedJoin =
170
+ message.type === 'error' && this.store.getSnapshot().status !== 'connected'
171
+ this.store.receive(message)
172
+ if (rejectedJoin) socket.close()
173
+ } catch {
174
+ this.store.disconnect('The collaboration connection returned an invalid message.')
175
+ socket.close()
176
+ }
177
+ }
178
+ socket.onerror = () => socket.close()
179
+ socket.onclose = () => {
180
+ if (socket !== this.socket) return
181
+ clearInterval(this.heartbeat)
182
+ clearTimeout(this.presenceTimer)
183
+ this.presenceTimer = undefined
184
+ this.queuedPresence.clear()
185
+ this.socket = null
186
+ this.store.disconnect()
187
+ if (this.wantsConnection()) {
188
+ const delay = Math.min(500 * 2 ** this.attempts++, 10_000)
189
+ this.retry = setTimeout(() => this.connect(), delay)
190
+ }
191
+ }
192
+ }
193
+
194
+ private send(message: CollabClientMessage): void {
195
+ if (
196
+ !getCurrentUser() &&
197
+ (message.type === 'location' ||
198
+ message.type === 'presence:set' ||
199
+ message.type === 'presence:delete')
200
+ )
201
+ return
202
+ if (message.type === 'presence:set') {
203
+ this.queuedPresence.set(message.registrationId, message)
204
+ if (!this.presenceTimer) {
205
+ this.presenceTimer = setTimeout(() => {
206
+ this.presenceTimer = undefined
207
+ for (const update of this.queuedPresence.values()) this.rawSend(update)
208
+ this.queuedPresence.clear()
209
+ }, 50)
210
+ }
211
+ return
212
+ }
213
+ if (message.type === 'presence:delete') this.queuedPresence.delete(message.registrationId)
214
+ this.rawSend(message)
215
+ }
216
+
217
+ private rawSend(message: CollabClientMessage): void {
218
+ if (this.socket?.readyState === WebSocket.OPEN) {
219
+ try {
220
+ this.socket.send(JSON.stringify(message))
221
+ } catch {
222
+ this.socket.close()
223
+ }
224
+ }
225
+ }
226
+
227
+ private stop(): void {
228
+ this.stopped = true
229
+ this.unsubscribeCurrentUser?.()
230
+ clearTimeout(this.retry)
231
+ clearTimeout(this.presenceTimer)
232
+ this.presenceTimer = undefined
233
+ clearInterval(this.heartbeat)
234
+ this.queuedPresence.clear()
235
+ this.socket?.close()
236
+ this.socket = null
237
+ this.store.disconnect()
238
+ }
239
+ }
@@ -0,0 +1,199 @@
1
+ import type { CursorsProps } from 'moi/collab'
2
+ import type { JsonValue } from 'moi'
3
+ import { useLayoutEffect, useRef } from 'react'
4
+ import type { PointerEvent, Ref, RefObject } from 'react'
5
+ import { IconPointer2 } from '@tabler/icons-react'
6
+
7
+ import { cn } from '@/client/lib/cn'
8
+ import { Badge } from '@/ui-components/badge'
9
+
10
+ import { presenceChannels, usePresenceChannel, usePresencePublisher, useUser } from '../hooks'
11
+ import { userDisplayName } from '../users'
12
+ import { hasPresence } from './presence-helpers'
13
+
14
+ type PointerPosition = { x: number; y: number; target?: string; targetX?: number; targetY?: number }
15
+ function pointerPosition(value: JsonValue): PointerPosition | null {
16
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null
17
+ if (typeof value.x !== 'number' || typeof value.y !== 'number') return null
18
+ if (!Number.isFinite(value.x) || !Number.isFinite(value.y)) return null
19
+ return {
20
+ x: value.x,
21
+ y: value.y,
22
+ ...(typeof value.target === 'string' ? { target: value.target } : {}),
23
+ ...(typeof value.targetX === 'number' && Number.isFinite(value.targetX)
24
+ ? { targetX: value.targetX }
25
+ : {}),
26
+ ...(typeof value.targetY === 'number' && Number.isFinite(value.targetY)
27
+ ? { targetY: value.targetY }
28
+ : {})
29
+ }
30
+ }
31
+
32
+ export function Cursors({ id = 'default', children, className }: CursorsProps) {
33
+ const root = useRef<HTMLDivElement>(null)
34
+ const layer = useRef<HTMLDivElement>(null)
35
+ // Keep the overlay in the visible viewport when the cursor area itself scrolls.
36
+ useLayoutEffect(() => {
37
+ const element = root.current
38
+ const overlay = layer.current
39
+ if (!element || !overlay) return
40
+ const position = () => {
41
+ overlay.style.transform = `translate(${element.scrollLeft}px, ${element.scrollTop}px)`
42
+ }
43
+ position()
44
+ element.addEventListener('scroll', position)
45
+ return () => element.removeEventListener('scroll', position)
46
+ }, [])
47
+ const channel = presenceChannels.cursor(id)
48
+ const cursors = usePresenceChannel<JsonValue>(channel)
49
+ const publish = usePresencePublisher<JsonValue>(channel, null, hasPresence)
50
+ const byConnection = new Map<string, { id: string; point: PointerPosition }>()
51
+ for (const { connectionId, userId, value } of cursors) {
52
+ const point = pointerPosition(value)
53
+ if (point) byConnection.set(connectionId, { id: userId, point })
54
+ }
55
+ const move = (event: PointerEvent<HTMLDivElement>) => {
56
+ if (event.pointerType === 'touch') return
57
+ const element = root.current
58
+ if (
59
+ !element ||
60
+ !(event.target instanceof Element) ||
61
+ event.target.closest('[data-collab-cursors]') !== element
62
+ )
63
+ return
64
+ const bounds = element.getBoundingClientRect()
65
+ const target =
66
+ event.target instanceof Element
67
+ ? event.target.closest<HTMLElement>('[data-collab-target]')
68
+ : null
69
+ const anchor = target && element.contains(target) ? target : null
70
+ const rect = anchor?.getBoundingClientRect()
71
+ publish({
72
+ x: event.clientX - bounds.left - element.clientLeft + element.scrollLeft,
73
+ y: event.clientY - bounds.top - element.clientTop + element.scrollTop,
74
+ ...(anchor && rect
75
+ ? {
76
+ target: anchor.dataset.collabTarget ?? '',
77
+ targetX: rect.width ? (event.clientX - rect.left) / rect.width : 0,
78
+ targetY: rect.height ? (event.clientY - rect.top) / rect.height : 0
79
+ }
80
+ : {})
81
+ })
82
+ }
83
+ return (
84
+ <div
85
+ ref={root}
86
+ data-collab-cursors={id}
87
+ className={cn('relative', className)}
88
+ onPointerEnter={move}
89
+ onPointerMove={move}
90
+ onPointerLeave={event => {
91
+ if (
92
+ event.target instanceof Element &&
93
+ event.target.closest('[data-collab-cursors]') === event.currentTarget
94
+ )
95
+ publish(null)
96
+ }}
97
+ >
98
+ {children}
99
+ <div
100
+ ref={layer}
101
+ className="pointer-events-none absolute inset-0 overflow-hidden"
102
+ aria-hidden="true"
103
+ >
104
+ {[...byConnection].map(([connectionId, { id, point }]) => (
105
+ <RemoteCursor key={connectionId} root={root} point={point} id={id} />
106
+ ))}
107
+ </div>
108
+ </div>
109
+ )
110
+ }
111
+
112
+ type RemoteCursorProps = {
113
+ root: RefObject<HTMLDivElement | null>
114
+ point: PointerPosition
115
+ id: string
116
+ }
117
+ // Semantic anchors follow their own data through scrolling and reordering.
118
+ // A cursor on a different record's modal has no matching anchor and stays hidden.
119
+ function RemoteCursor({ root, point, id }: RemoteCursorProps) {
120
+ const marker = useRef<HTMLSpanElement>(null)
121
+ useLayoutEffect(() => {
122
+ const element = root.current
123
+ const node = marker.current
124
+ if (!element || !node) return
125
+ const position = (animate = false) => {
126
+ let x = point.x - element.scrollLeft
127
+ let y = point.y - element.scrollTop
128
+ if (point.target) {
129
+ const target = [...element.querySelectorAll<HTMLElement>('[data-collab-target]')].find(
130
+ candidate => candidate.dataset.collabTarget === point.target
131
+ )
132
+ if (!target) {
133
+ node.hidden = true
134
+ return
135
+ }
136
+ const bounds = element.getBoundingClientRect()
137
+ const rect = target.getBoundingClientRect()
138
+ x = rect.left - bounds.left - element.clientLeft + rect.width * (point.targetX ?? 0)
139
+ y = rect.top - bounds.top - element.clientTop + rect.height * (point.targetY ?? 0)
140
+ }
141
+ const transform = `translate(${x}px, ${y}px)`
142
+ if (node.hidden || node.style.transform !== transform) {
143
+ // Smooth pointer updates; place new cursors and layout corrections immediately.
144
+ node.dataset.moving = animate && !node.hidden ? 'true' : 'false'
145
+ node.style.transform = transform
146
+ }
147
+ node.hidden = false
148
+ }
149
+ position(true)
150
+ const reposition = () => position()
151
+ const observer = new ResizeObserver(reposition)
152
+ observer.observe(element)
153
+ const changes = new MutationObserver(reposition)
154
+ changes.observe(element, {
155
+ childList: true,
156
+ subtree: true,
157
+ attributes: true,
158
+ attributeFilter: ['data-collab-target']
159
+ })
160
+ element.addEventListener('scroll', reposition, true)
161
+ window.addEventListener('resize', reposition)
162
+ return () => {
163
+ observer.disconnect()
164
+ changes.disconnect()
165
+ element.removeEventListener('scroll', reposition, true)
166
+ window.removeEventListener('resize', reposition)
167
+ }
168
+ }, [root, point])
169
+ return <Cursor ref={marker} id={id} />
170
+ }
171
+
172
+ type CursorProps = {
173
+ id: string
174
+ ref?: Ref<HTMLSpanElement>
175
+ }
176
+ function Cursor({ id, ref }: CursorProps) {
177
+ const user = useUser(id)
178
+ return (
179
+ <span
180
+ ref={ref}
181
+ // Position before revealing it, so the first update cannot animate from (0, 0).
182
+ hidden
183
+ aria-hidden="true"
184
+ data-collab-color={user?.color ?? 'unknown'}
185
+ className="pointer-events-none absolute top-0 left-0 transition-transform duration-100 ease-linear data-[moving=false]:transition-none motion-reduce:transition-none"
186
+ >
187
+ <span className="relative block animate-in duration-200 zoom-in-75 fade-in">
188
+ <IconPointer2
189
+ size={24}
190
+ stroke={1.5}
191
+ className="-translate-x-0.5 -translate-y-0.5 fill-collab stroke-white drop-shadow-xs"
192
+ />
193
+ <Badge className="absolute top-3.5 left-3.5 bg-collab text-collab-foreground">
194
+ <span className="truncate">{user ? userDisplayName(user) : 'Someone'}</span>
195
+ </Badge>
196
+ </span>
197
+ </span>
198
+ )
199
+ }
@@ -0,0 +1,61 @@
1
+ import type { PresenceAvatarsProps } from 'moi/collab'
2
+ import { useContext } from 'react'
3
+ import type { HTMLAttributes, ReactNode, Ref } from 'react'
4
+ import { motion } from 'motion/react'
5
+ import { cn } from '@/client/lib/cn'
6
+ import { PresenceGroupContext, usePresenceTarget, useTargetPresence } from './presence-helpers'
7
+ import { UserAvatar } from './user-avatar'
8
+
9
+ export function PresenceAvatars({ id, present, align, children, className }: PresenceAvatarsProps) {
10
+ const target = usePresenceTarget(id)
11
+ const presence = useTargetPresence(target, present)
12
+ const grouped = useContext(PresenceGroupContext).length > 0
13
+ return (
14
+ <PresenceAvatarsPrimitive
15
+ {...presence.props}
16
+ users={presence.users}
17
+ // Controlled presence can occupy several targets at once; only focus moves between them.
18
+ animate={grouped && present === undefined}
19
+ align={align}
20
+ className={className}
21
+ >
22
+ {children}
23
+ </PresenceAvatarsPrimitive>
24
+ )
25
+ }
26
+
27
+ type PresenceAvatarsPrimitiveProps = HTMLAttributes<HTMLDivElement> & {
28
+ ref?: Ref<HTMLDivElement>
29
+ users: readonly { id: string; connectionId: string }[]
30
+ children: ReactNode
31
+ animate?: boolean
32
+ align?: PresenceAvatarsProps['align']
33
+ }
34
+
35
+ // A target owns its own gutter. Optional group-scoped layout IDs let the same
36
+ // user's face glide between targets without searching or guessing DOM order.
37
+ function PresenceAvatarsPrimitive({
38
+ users,
39
+ children,
40
+ animate = false,
41
+ align = 'center',
42
+ className,
43
+ ...rest
44
+ }: PresenceAvatarsPrimitiveProps) {
45
+ return (
46
+ <div className={cn('relative pl-8', className)} {...rest}>
47
+ {children}
48
+ <div
49
+ data-align={align}
50
+ className="pointer-events-none absolute inset-y-0 left-0 flex items-center -space-x-3 data-[align=end]:items-end data-[align=start]:items-start"
51
+ aria-hidden="true"
52
+ >
53
+ {users.map(({ id, connectionId }) => (
54
+ <motion.span key={id} layoutId={animate ? `presence:${connectionId}` : undefined}>
55
+ <UserAvatar id={id} size="sm" className="animate-in duration-200 zoom-in-75 fade-in" />
56
+ </motion.span>
57
+ ))}
58
+ </div>
59
+ </div>
60
+ )
61
+ }
@@ -0,0 +1,126 @@
1
+ import type { PresenceFrameProps } from 'moi/collab'
2
+ import { useLayoutEffect, useRef } from 'react'
3
+ import type { HTMLAttributes, ReactNode, Ref } from 'react'
4
+ import { cn } from '@/client/lib/cn'
5
+ import type { UserColor } from '@/lib/collab/colors'
6
+ import { Badge } from '@/ui-components/badge'
7
+ import { useUsers } from '../hooks'
8
+ import { userDisplayName } from '../users'
9
+ import { usePresenceTarget, useTargetPresence } from './presence-helpers'
10
+
11
+ export function PresenceFrame({ id, present, align, children, className }: PresenceFrameProps) {
12
+ const target = usePresenceTarget(id)
13
+ const presence = useTargetPresence(target, present)
14
+ return (
15
+ <PresenceOutline
16
+ {...presence.props}
17
+ ids={presence.users.map(user => user.id)}
18
+ align={align}
19
+ className={className}
20
+ >
21
+ {children}
22
+ </PresenceOutline>
23
+ )
24
+ }
25
+
26
+ type PresenceOutlineProps = HTMLAttributes<HTMLDivElement> & {
27
+ ref?: Ref<HTMLDivElement>
28
+ // Everyone at this element; the first user's color draws the frame.
29
+ ids: readonly string[]
30
+ children: ReactNode
31
+ align?: PresenceFrameProps['align']
32
+ }
33
+
34
+ // One visible element gets a frame matching its shape; other content gets one shared frame.
35
+ export function PresenceOutline({
36
+ ids,
37
+ align,
38
+ children,
39
+ className,
40
+ ...rest
41
+ }: PresenceOutlineProps) {
42
+ const resolved = useUsers(ids).filter(user => user !== undefined)
43
+ return (
44
+ <div className={cn('relative', className)} {...rest}>
45
+ {/* Keep the overlay first so showing it never changes the content's spacing. */}
46
+ <FrameOutline
47
+ names={resolved.map(userDisplayName).join(', ')}
48
+ color={resolved[0]?.color}
49
+ align={align}
50
+ />
51
+ {children}
52
+ </div>
53
+ )
54
+ }
55
+
56
+ const FRAME_GAP = 4
57
+ const FRAME_RADIUS = 6
58
+
59
+ const CORNERS = [
60
+ 'borderTopLeftRadius',
61
+ 'borderTopRightRadius',
62
+ 'borderBottomRightRadius',
63
+ 'borderBottomLeftRadius'
64
+ ] as const
65
+
66
+ type FrameOutlineProps = {
67
+ names: string
68
+ color: UserColor | undefined
69
+ align?: PresenceFrameProps['align']
70
+ }
71
+
72
+ function FrameOutline({ names, color, align = 'end' }: FrameOutlineProps) {
73
+ const node = useRef<HTMLDivElement | null>(null)
74
+ // Refit after rendering and whenever the content resizes.
75
+ useLayoutEffect(() => {
76
+ const outline = node.current
77
+ const frame = outline?.parentElement
78
+ if (!names || !outline || !frame) return
79
+ const fit = () => {
80
+ // Ignore the overlay, hidden elements, and helpers outside normal flow.
81
+ const inside = [...frame.children].filter(child => {
82
+ if (child === outline) return false
83
+ const { display, position } = getComputedStyle(child)
84
+ return display !== 'none' && position !== 'absolute' && position !== 'fixed'
85
+ })
86
+ const bareText = [...frame.childNodes].some(
87
+ child => child.nodeType === Node.TEXT_NODE && child.textContent?.trim()
88
+ )
89
+ const only = inside.length === 1 && !bareText ? inside[0] : null
90
+ const subject = only instanceof HTMLElement ? only : null
91
+ const target = subject ?? frame
92
+ const bounds = target.getBoundingClientRect()
93
+ const origin = frame.getBoundingClientRect()
94
+ const box = outline.style
95
+ // Rectangles preserve fractions; absolute positions start inside the wrapper's border.
96
+ box.left = `${bounds.left - origin.left - frame.clientLeft + frame.scrollLeft - FRAME_GAP}px`
97
+ box.top = `${bounds.top - origin.top - frame.clientTop + frame.scrollTop - FRAME_GAP}px`
98
+ box.width = `${bounds.width + FRAME_GAP * 2}px`
99
+ box.height = `${bounds.height + FRAME_GAP * 2}px`
100
+ box.setProperty('--presence-target-width', `${bounds.width}px`)
101
+ // Expand one element's corners by the gap; otherwise use the default radius.
102
+ const shape = subject ? getComputedStyle(subject) : null
103
+ for (const corner of CORNERS) {
104
+ box[corner] = shape ? `calc(${shape[corner]} + ${FRAME_GAP}px)` : `${FRAME_RADIUS}px`
105
+ }
106
+ }
107
+ fit()
108
+ const observer = new ResizeObserver(fit)
109
+ observer.observe(frame)
110
+ for (const child of frame.children) if (child !== outline) observer.observe(child)
111
+ return () => observer.disconnect()
112
+ })
113
+ return (
114
+ <div
115
+ ref={node}
116
+ hidden={!names}
117
+ data-align={align}
118
+ data-collab-color={color ?? 'unknown'}
119
+ className="group/frame pointer-events-none absolute m-0! animate-in ring-2 ring-collab duration-150 fade-in"
120
+ >
121
+ <Badge className="absolute bottom-full mb-1.5 max-w-[min(var(--presence-target-width),10rem)] bg-collab text-collab-foreground group-data-[align=end]/frame:-right-0.5 group-data-[align=start]/frame:-left-0.5">
122
+ <span className="truncate">{names}</span>
123
+ </Badge>
124
+ </div>
125
+ )
126
+ }
@@ -0,0 +1,23 @@
1
+ import type { PresenceGroupProps } from 'moi/collab'
2
+ import { useContext, useId, useMemo } from 'react'
3
+ import { LayoutGroup, MotionConfig } from 'motion/react'
4
+ import { presenceTarget } from '../presence-target'
5
+ import { PresenceGroupContext } from './presence-helpers'
6
+
7
+ export function PresenceGroup({ id, children }: PresenceGroupProps) {
8
+ const parent = useContext(PresenceGroupContext)
9
+ const scope = useMemo(() => {
10
+ presenceTarget(id)
11
+ return [...parent, id]
12
+ }, [parent, id])
13
+ // The shared path identifies data across browsers; the generated ID keeps
14
+ // avatar animations inside this particular rendered group.
15
+ const animationId = useId()
16
+ return (
17
+ <MotionConfig reducedMotion="user">
18
+ <LayoutGroup id={animationId}>
19
+ <PresenceGroupContext value={scope}>{children}</PresenceGroupContext>
20
+ </LayoutGroup>
21
+ </MotionConfig>
22
+ )
23
+ }