@eloxiv/client 0.0.0-stage → 0.1.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 (269) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Account.d.ts +131 -0
  4. package/dist/Account.d.ts.map +1 -0
  5. package/dist/Account.js +169 -0
  6. package/dist/Account.js.map +1 -0
  7. package/dist/Agent.d.ts +496 -0
  8. package/dist/Agent.d.ts.map +1 -0
  9. package/dist/Agent.js +228 -0
  10. package/dist/Agent.js.map +1 -0
  11. package/dist/AgentSync.d.ts +990 -0
  12. package/dist/AgentSync.d.ts.map +1 -0
  13. package/dist/AgentSync.js +46 -0
  14. package/dist/AgentSync.js.map +1 -0
  15. package/dist/AppState.d.ts +127 -0
  16. package/dist/AppState.d.ts.map +1 -0
  17. package/dist/AppState.js +145 -0
  18. package/dist/AppState.js.map +1 -0
  19. package/dist/AppStateSync.d.ts +193 -0
  20. package/dist/AppStateSync.d.ts.map +1 -0
  21. package/dist/AppStateSync.js +23 -0
  22. package/dist/AppStateSync.js.map +1 -0
  23. package/dist/Auth.d.ts +95 -0
  24. package/dist/Auth.d.ts.map +1 -0
  25. package/dist/Auth.js +139 -0
  26. package/dist/Auth.js.map +1 -0
  27. package/dist/Avatars.d.ts +53 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +121 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/BrowserAnalytics.d.ts +56 -0
  32. package/dist/BrowserAnalytics.d.ts.map +1 -0
  33. package/dist/BrowserAnalytics.js +94 -0
  34. package/dist/BrowserAnalytics.js.map +1 -0
  35. package/dist/Chat.d.ts +712 -0
  36. package/dist/Chat.d.ts.map +1 -0
  37. package/dist/Chat.js +883 -0
  38. package/dist/Chat.js.map +1 -0
  39. package/dist/ChatIntegrity.d.ts +63 -0
  40. package/dist/ChatIntegrity.d.ts.map +1 -0
  41. package/dist/ChatIntegrity.js +89 -0
  42. package/dist/ChatIntegrity.js.map +1 -0
  43. package/dist/ChatSends.d.ts +103 -0
  44. package/dist/ChatSends.d.ts.map +1 -0
  45. package/dist/ChatSends.js +157 -0
  46. package/dist/ChatSends.js.map +1 -0
  47. package/dist/Client.d.ts +113 -0
  48. package/dist/Client.d.ts.map +1 -0
  49. package/dist/Client.js +189 -0
  50. package/dist/Client.js.map +1 -0
  51. package/dist/Collab.d.ts +138 -0
  52. package/dist/Collab.d.ts.map +1 -0
  53. package/dist/Collab.js +454 -0
  54. package/dist/Collab.js.map +1 -0
  55. package/dist/CollabTools.d.ts +129 -0
  56. package/dist/CollabTools.d.ts.map +1 -0
  57. package/dist/CollabTools.js +277 -0
  58. package/dist/CollabTools.js.map +1 -0
  59. package/dist/Connections.d.ts +288 -0
  60. package/dist/Connections.d.ts.map +1 -0
  61. package/dist/Connections.js +316 -0
  62. package/dist/Connections.js.map +1 -0
  63. package/dist/Consent.d.ts +338 -0
  64. package/dist/Consent.d.ts.map +1 -0
  65. package/dist/Consent.js +142 -0
  66. package/dist/Consent.js.map +1 -0
  67. package/dist/Desktop.d.ts +61 -0
  68. package/dist/Desktop.d.ts.map +1 -0
  69. package/dist/Desktop.js +101 -0
  70. package/dist/Desktop.js.map +1 -0
  71. package/dist/Directory.d.ts +36 -0
  72. package/dist/Directory.d.ts.map +1 -0
  73. package/dist/Directory.js +42 -0
  74. package/dist/Directory.js.map +1 -0
  75. package/dist/ErrorReporter.d.ts +48 -0
  76. package/dist/ErrorReporter.d.ts.map +1 -0
  77. package/dist/ErrorReporter.js +70 -0
  78. package/dist/ErrorReporter.js.map +1 -0
  79. package/dist/ExpoSqlite.d.ts +7 -0
  80. package/dist/ExpoSqlite.d.ts.map +1 -0
  81. package/dist/ExpoSqlite.js +7 -0
  82. package/dist/ExpoSqlite.js.map +1 -0
  83. package/dist/FileSync.d.ts +265 -0
  84. package/dist/FileSync.d.ts.map +1 -0
  85. package/dist/FileSync.js +29 -0
  86. package/dist/FileSync.js.map +1 -0
  87. package/dist/FileTables.gen.d.ts +109 -0
  88. package/dist/FileTables.gen.d.ts.map +1 -0
  89. package/dist/FileTables.gen.js +23 -0
  90. package/dist/FileTables.gen.js.map +1 -0
  91. package/dist/Foldkit.d.ts +487 -0
  92. package/dist/Foldkit.d.ts.map +1 -0
  93. package/dist/Foldkit.js +617 -0
  94. package/dist/Foldkit.js.map +1 -0
  95. package/dist/History.d.ts +133 -0
  96. package/dist/History.d.ts.map +1 -0
  97. package/dist/History.js +210 -0
  98. package/dist/History.js.map +1 -0
  99. package/dist/InboxSync.d.ts +428 -0
  100. package/dist/InboxSync.d.ts.map +1 -0
  101. package/dist/InboxSync.js +37 -0
  102. package/dist/InboxSync.js.map +1 -0
  103. package/dist/KernelTables.gen.d.ts +1522 -0
  104. package/dist/KernelTables.gen.d.ts.map +1 -0
  105. package/dist/KernelTables.gen.js +307 -0
  106. package/dist/KernelTables.gen.js.map +1 -0
  107. package/dist/Make.d.ts +75 -0
  108. package/dist/Make.d.ts.map +1 -0
  109. package/dist/Make.js +70 -0
  110. package/dist/Make.js.map +1 -0
  111. package/dist/Models.d.ts +88 -0
  112. package/dist/Models.d.ts.map +1 -0
  113. package/dist/Models.js +80 -0
  114. package/dist/Models.js.map +1 -0
  115. package/dist/Optimistic.d.ts +120 -0
  116. package/dist/Optimistic.d.ts.map +1 -0
  117. package/dist/Optimistic.js +231 -0
  118. package/dist/Optimistic.js.map +1 -0
  119. package/dist/PlatformSync.d.ts +273 -0
  120. package/dist/PlatformSync.d.ts.map +1 -0
  121. package/dist/PlatformSync.js +92 -0
  122. package/dist/PlatformSync.js.map +1 -0
  123. package/dist/Poll.d.ts +113 -0
  124. package/dist/Poll.d.ts.map +1 -0
  125. package/dist/Poll.js +179 -0
  126. package/dist/Poll.js.map +1 -0
  127. package/dist/Preferences.d.ts +18 -0
  128. package/dist/Preferences.d.ts.map +1 -0
  129. package/dist/Preferences.js +22 -0
  130. package/dist/Preferences.js.map +1 -0
  131. package/dist/Proposals.d.ts +29 -0
  132. package/dist/Proposals.d.ts.map +1 -0
  133. package/dist/Proposals.js +41 -0
  134. package/dist/Proposals.js.map +1 -0
  135. package/dist/React.d.ts +17 -0
  136. package/dist/React.d.ts.map +1 -0
  137. package/dist/React.js +17 -0
  138. package/dist/React.js.map +1 -0
  139. package/dist/Reader.d.ts +35 -0
  140. package/dist/Reader.d.ts.map +1 -0
  141. package/dist/Reader.js +136 -0
  142. package/dist/Reader.js.map +1 -0
  143. package/dist/Resources.d.ts +98 -0
  144. package/dist/Resources.d.ts.map +1 -0
  145. package/dist/Resources.js +161 -0
  146. package/dist/Resources.js.map +1 -0
  147. package/dist/Rows.d.ts +4 -0
  148. package/dist/Rows.d.ts.map +1 -0
  149. package/dist/Rows.js +16 -0
  150. package/dist/Rows.js.map +1 -0
  151. package/dist/Runtime.d.ts +254 -0
  152. package/dist/Runtime.d.ts.map +1 -0
  153. package/dist/Runtime.js +1249 -0
  154. package/dist/Runtime.js.map +1 -0
  155. package/dist/RuntimeRuns.d.ts +74 -0
  156. package/dist/RuntimeRuns.d.ts.map +1 -0
  157. package/dist/RuntimeRuns.js +118 -0
  158. package/dist/RuntimeRuns.js.map +1 -0
  159. package/dist/ServicesSync.d.ts +286 -0
  160. package/dist/ServicesSync.d.ts.map +1 -0
  161. package/dist/ServicesSync.js +40 -0
  162. package/dist/ServicesSync.js.map +1 -0
  163. package/dist/Session.d.ts +226 -0
  164. package/dist/Session.d.ts.map +1 -0
  165. package/dist/Session.js +763 -0
  166. package/dist/Session.js.map +1 -0
  167. package/dist/ShareGrant.d.ts +47 -0
  168. package/dist/ShareGrant.d.ts.map +1 -0
  169. package/dist/ShareGrant.js +20 -0
  170. package/dist/ShareGrant.js.map +1 -0
  171. package/dist/Sharing.d.ts +203 -0
  172. package/dist/Sharing.d.ts.map +1 -0
  173. package/dist/Sharing.js +520 -0
  174. package/dist/Sharing.js.map +1 -0
  175. package/dist/Skew.d.ts +52 -0
  176. package/dist/Skew.d.ts.map +1 -0
  177. package/dist/Skew.js +77 -0
  178. package/dist/Skew.js.map +1 -0
  179. package/dist/SpacesSync.d.ts +247 -0
  180. package/dist/SpacesSync.d.ts.map +1 -0
  181. package/dist/SpacesSync.js +30 -0
  182. package/dist/SpacesSync.js.map +1 -0
  183. package/dist/Storage.d.ts +51 -0
  184. package/dist/Storage.d.ts.map +1 -0
  185. package/dist/Storage.js +107 -0
  186. package/dist/Storage.js.map +1 -0
  187. package/dist/Sync.d.ts +48 -0
  188. package/dist/Sync.d.ts.map +1 -0
  189. package/dist/Sync.js +48 -0
  190. package/dist/Sync.js.map +1 -0
  191. package/dist/SyncTables.d.ts +13 -0
  192. package/dist/SyncTables.d.ts.map +1 -0
  193. package/dist/SyncTables.js +13 -0
  194. package/dist/SyncTables.js.map +1 -0
  195. package/dist/Tab.d.ts +36 -0
  196. package/dist/Tab.d.ts.map +1 -0
  197. package/dist/Tab.js +44 -0
  198. package/dist/Tab.js.map +1 -0
  199. package/dist/Transport.d.ts +139 -0
  200. package/dist/Transport.d.ts.map +1 -0
  201. package/dist/Transport.js +232 -0
  202. package/dist/Transport.js.map +1 -0
  203. package/dist/Upload.d.ts +41 -0
  204. package/dist/Upload.d.ts.map +1 -0
  205. package/dist/Upload.js +93 -0
  206. package/dist/Upload.js.map +1 -0
  207. package/dist/WebMcp.d.ts +78 -0
  208. package/dist/WebMcp.d.ts.map +1 -0
  209. package/dist/WebMcp.js +204 -0
  210. package/dist/WebMcp.js.map +1 -0
  211. package/dist/index.d.ts +27 -0
  212. package/dist/index.d.ts.map +1 -0
  213. package/dist/index.js +27 -0
  214. package/dist/index.js.map +1 -0
  215. package/package.json +97 -3
  216. package/src/Account.ts +249 -0
  217. package/src/Agent.ts +387 -0
  218. package/src/AgentSync.ts +59 -0
  219. package/src/AppState.ts +222 -0
  220. package/src/AppStateSync.ts +26 -0
  221. package/src/Auth.ts +225 -0
  222. package/src/Avatars.ts +144 -0
  223. package/src/BrowserAnalytics.ts +133 -0
  224. package/src/Chat.ts +1150 -0
  225. package/src/ChatIntegrity.ts +130 -0
  226. package/src/ChatSends.ts +209 -0
  227. package/src/Client.ts +319 -0
  228. package/src/Collab.ts +524 -0
  229. package/src/CollabTools.ts +381 -0
  230. package/src/Connections.ts +517 -0
  231. package/src/Consent.ts +176 -0
  232. package/src/Desktop.ts +139 -0
  233. package/src/Directory.ts +71 -0
  234. package/src/ErrorReporter.ts +112 -0
  235. package/src/ExpoSqlite.ts +6 -0
  236. package/src/FileSync.ts +34 -0
  237. package/src/FileTables.gen.ts +23 -0
  238. package/src/Foldkit.ts +960 -0
  239. package/src/History.ts +337 -0
  240. package/src/InboxSync.ts +47 -0
  241. package/src/KernelTables.gen.ts +329 -0
  242. package/src/Make.ts +120 -0
  243. package/src/Models.ts +134 -0
  244. package/src/Optimistic.ts +364 -0
  245. package/src/PlatformSync.ts +156 -0
  246. package/src/Poll.ts +227 -0
  247. package/src/Preferences.ts +42 -0
  248. package/src/Proposals.ts +57 -0
  249. package/src/React.ts +26 -0
  250. package/src/Reader.ts +180 -0
  251. package/src/Resources.ts +257 -0
  252. package/src/Rows.ts +16 -0
  253. package/src/Runtime.ts +1409 -0
  254. package/src/RuntimeRuns.ts +180 -0
  255. package/src/ServicesSync.ts +58 -0
  256. package/src/Session.ts +814 -0
  257. package/src/ShareGrant.ts +20 -0
  258. package/src/Sharing.ts +696 -0
  259. package/src/Skew.ts +97 -0
  260. package/src/SpacesSync.ts +61 -0
  261. package/src/Storage.ts +167 -0
  262. package/src/Sync.ts +125 -0
  263. package/src/SyncTables.ts +12 -0
  264. package/src/Tab.ts +59 -0
  265. package/src/Transport.ts +321 -0
  266. package/src/Upload.ts +125 -0
  267. package/src/WebMcp.ts +279 -0
  268. package/src/index.ts +26 -0
  269. package/src/web-globals.d.ts +103 -0
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Headless collaboration helpers over a live document (`@eloxiv/client/collab`, the CollabDocument contract's
3
+ * clients): following a collaborator's viewport, undo that reverses only this client's own changes, and recent edits
4
+ * attributed to the person the kernel recorded for each change. None of them renders anything; an app's screens (or a
5
+ * registry UI item) draw the highlights, the follow banner and the undo buttons from their state.
6
+ */
7
+ import type { CollabOrigin } from "@eloxiv/contracts"
8
+ import * as Y from "yjs"
9
+ import type { CollabConnection, CollabPeer } from "./Collab.ts"
10
+
11
+ /** The origin `connectCollab` applies remote changes with (the same symbol as its `REMOTE_ORIGIN`). */
12
+ const REMOTE = Symbol.for("@eloxiv/client/collab/remote")
13
+
14
+ // ---- Following a collaborator's viewport ------------------------------------------------------------------------
15
+
16
+ /**
17
+ * Where a collaborator is looking, as they publish it in their presence under `viewport` (or another key): which view
18
+ * (a page, a slide, a file), its scroll offsets, zoom and cursor. Every field is optional; what the app means by them
19
+ * is the app's.
20
+ */
21
+ export interface CollabViewport {
22
+ readonly view?: string
23
+ readonly scrollX?: number
24
+ readonly scrollY?: number
25
+ readonly zoom?: number
26
+ readonly cursorX?: number
27
+ readonly cursorY?: number
28
+ }
29
+
30
+ export const VIEWPORT_KEY = "viewport"
31
+ const NUMERIC = ["scrollX", "scrollY", "zoom", "cursorX", "cursorY"] as const
32
+
33
+ /**
34
+ * The viewport in a presence state, checked: an object whose numeric fields are finite numbers and whose `view` is a
35
+ * string of at most 512 characters; other fields are dropped. Anything else (presence is whatever another client
36
+ * sent) is no viewport.
37
+ */
38
+ export const readViewport = (state: unknown, key: string = VIEWPORT_KEY): CollabViewport | undefined => {
39
+ if (typeof state !== "object" || state === null) return undefined
40
+ const raw = (state as Record<string, unknown>)[key]
41
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return undefined
42
+ const value = raw as Record<string, unknown>
43
+ const viewport: Record<string, number | string> = {}
44
+ for (const field of NUMERIC) {
45
+ const n = value[field]
46
+ if (n === undefined) continue
47
+ if (typeof n !== "number" || !Number.isFinite(n)) return undefined
48
+ viewport[field] = n
49
+ }
50
+ if (value["view"] !== undefined) {
51
+ if (typeof value["view"] !== "string" || value["view"].length > 512) return undefined
52
+ viewport["view"] = value["view"]
53
+ }
54
+ return viewport
55
+ }
56
+
57
+ /** A presence state with this client's viewport set (publish it with `connection.setPresence`). */
58
+ export const withViewport = (
59
+ presence: Record<string, unknown> | null | undefined,
60
+ viewport: CollabViewport,
61
+ key: string = VIEWPORT_KEY,
62
+ ): Record<string, unknown> => ({ ...presence, [key]: viewport })
63
+
64
+ export type FollowEvent =
65
+ | { readonly type: "viewport"; readonly peer: CollabPeer; readonly viewport: CollabViewport }
66
+ /** Following ended: asked to (`stopped`), the collaborator left the document (`left`), the connection closed. */
67
+ | { readonly type: "stopped"; readonly reason: "stopped" | "left" | "closed" }
68
+
69
+ export interface FollowController {
70
+ /** The collaborator followed, as last seen. */
71
+ readonly following: CollabPeer | undefined
72
+ /**
73
+ * Follow a collaborator by client id (from `connection.peers`); their current viewport, if any, arrives at once.
74
+ * False (nothing changes) when no such collaborator is on the document now.
75
+ */
76
+ readonly follow: (clientId: number) => boolean
77
+ readonly stop: () => void
78
+ readonly subscribe: (listener: (event: FollowEvent) => void) => () => void
79
+ /** Stop listening to the connection for good. */
80
+ readonly dispose: () => void
81
+ }
82
+
83
+ /**
84
+ * Follow a collaborator's viewport: every change of it arrives once (`onViewport` and a `viewport` event; the same
85
+ * viewport again does not), until following stops. It stops when asked, when the collaborator leaves the document,
86
+ * when their client id is announced by another person (a client id is the client's, but the person is the kernel's
87
+ * stamp, so a different one is someone else), and when the connection closes.
88
+ */
89
+ export const followPeer = (
90
+ connection: CollabConnection,
91
+ options: { readonly onViewport?: (viewport: CollabViewport, peer: CollabPeer) => void; readonly key?: string } = {},
92
+ ): FollowController => {
93
+ const key = options.key ?? VIEWPORT_KEY
94
+ const listeners = new Set<(event: FollowEvent) => void>()
95
+ const emit = (event: FollowEvent) => {
96
+ for (const listener of listeners) listener(event)
97
+ }
98
+ let following: CollabPeer | undefined
99
+ let last: string | undefined
100
+ let disposed = false
101
+
102
+ const end = (reason: "stopped" | "left" | "closed") => {
103
+ if (following === undefined) return
104
+ following = undefined
105
+ last = undefined
106
+ emit({ type: "stopped", reason })
107
+ }
108
+ const deliver = (peer: CollabPeer) => {
109
+ following = peer
110
+ const viewport = readViewport(peer.state, key)
111
+ if (viewport === undefined) return
112
+ const serialised = JSON.stringify(viewport)
113
+ if (serialised === last) return
114
+ last = serialised
115
+ options.onViewport?.(viewport, peer)
116
+ emit({ type: "viewport", peer, viewport })
117
+ }
118
+ const unsubscribe = connection.subscribe((event) => {
119
+ if (event.type === "closed") return end("closed")
120
+ if (event.type !== "peers" || following === undefined) return
121
+ const current = following
122
+ const peer = event.peers.find((p) => p.clientId === current.clientId)
123
+ if (peer === undefined || peer.userId !== current.userId) return end("left")
124
+ deliver(peer)
125
+ })
126
+
127
+ return {
128
+ get following() {
129
+ return following
130
+ },
131
+ follow: (clientId) => {
132
+ if (disposed || connection.status === "closed") return false
133
+ const peer = connection.peers.find((p) => p.clientId === clientId)
134
+ if (peer === undefined) return false
135
+ if (following !== undefined && following.clientId !== clientId) end("stopped")
136
+ last = undefined
137
+ deliver(peer)
138
+ return true
139
+ },
140
+ stop: () => end("stopped"),
141
+ subscribe: (listener) => {
142
+ listeners.add(listener)
143
+ return () => listeners.delete(listener)
144
+ },
145
+ dispose: () => {
146
+ disposed = true
147
+ following = undefined
148
+ unsubscribe()
149
+ listeners.clear()
150
+ },
151
+ }
152
+ }
153
+
154
+ // ---- Local undo -------------------------------------------------------------------------------------------------
155
+
156
+ export interface LocalUndo {
157
+ readonly canUndo: boolean
158
+ readonly canRedo: boolean
159
+ /** Undo this client's last change (in scope); false when there is none. */
160
+ readonly undo: () => boolean
161
+ readonly redo: () => boolean
162
+ /** Run `fn` as one undoable local change (whatever origin the app otherwise uses). */
163
+ readonly transactLocal: <A>(fn: () => A) => A
164
+ /** End the current undo step, so the next change is undone separately. */
165
+ readonly stopCapturing: () => void
166
+ readonly clear: () => void
167
+ readonly subscribe: (listener: () => void) => () => void
168
+ readonly dispose: () => void
169
+ }
170
+
171
+ /** The origin `transactLocal` changes are made with. */
172
+ export const LOCAL_ORIGIN = Symbol.for("@eloxiv/client/collab/local")
173
+
174
+ /**
175
+ * Undo and redo of this client's own changes to a live document, never anyone else's: a collaborator's edits and an
176
+ * agent's (which arrive from the kernel as remote changes) are not on the stack, so undoing leaves them in place and
177
+ * Yjs reverses only what this client did, even where the two interleave. Undoing is itself a local change, sent to the
178
+ * kernel like any other (and refused, like any other, when the caller may not change the document).
179
+ *
180
+ * `scope` names the roots it covers (Y.Text names, default `["content"]`) or gives the shared types themselves;
181
+ * `origins` adds the transaction origins an editor binding uses for local changes (changes with no origin, and
182
+ * `transactLocal`'s, are tracked already). The remote origin is never tracked, even if given.
183
+ */
184
+ export const localUndo = (
185
+ doc: Y.Doc,
186
+ options: {
187
+ readonly scope?: ReadonlyArray<string | Y.AbstractType<any>> | undefined
188
+ readonly origins?: ReadonlyArray<unknown> | undefined
189
+ readonly captureTimeoutMs?: number | undefined
190
+ } = {},
191
+ ): LocalUndo => {
192
+ const scope = (options.scope ?? ["content"]).map((s) => (typeof s === "string" ? doc.getText(s) : s))
193
+ const origins = new Set<unknown>([null, LOCAL_ORIGIN, ...(options.origins ?? [])])
194
+ origins.delete(REMOTE)
195
+ const manager = new Y.UndoManager(scope, {
196
+ trackedOrigins: origins,
197
+ captureTimeout: options.captureTimeoutMs ?? 500,
198
+ })
199
+ const listeners = new Set<() => void>()
200
+ const changed = () => {
201
+ for (const listener of listeners) listener()
202
+ }
203
+ manager.on("stack-item-added", changed)
204
+ manager.on("stack-item-popped", changed)
205
+ manager.on("stack-cleared", changed)
206
+ return {
207
+ get canUndo() {
208
+ return manager.undoStack.length > 0
209
+ },
210
+ get canRedo() {
211
+ return manager.redoStack.length > 0
212
+ },
213
+ undo: () => manager.undo() !== null,
214
+ redo: () => manager.redo() !== null,
215
+ transactLocal: (fn) => {
216
+ let result: ReturnType<typeof fn> | undefined
217
+ doc.transact(() => {
218
+ result = fn()
219
+ }, LOCAL_ORIGIN)
220
+ return result as ReturnType<typeof fn>
221
+ },
222
+ stopCapturing: () => manager.stopCapturing(),
223
+ clear: () => manager.clear(),
224
+ subscribe: (listener) => {
225
+ listeners.add(listener)
226
+ return () => listeners.delete(listener)
227
+ },
228
+ dispose: () => {
229
+ listeners.clear()
230
+ manager.destroy()
231
+ },
232
+ }
233
+ }
234
+
235
+ // ---- Recent edits -----------------------------------------------------------------------------------------------
236
+
237
+ /** A collaborator's recent change to a text, where it now is: an insertion's range, or the point of a deletion. */
238
+ export interface RecentEdit {
239
+ /** Who made it, as the kernel stored it (an agent's edit is its person's, with origin `agent`). */
240
+ readonly userId: string
241
+ readonly origin: CollabOrigin
242
+ readonly kind: "insert" | "delete"
243
+ /** Its position in the text now (UTF-16 offsets); `from === to` for a deletion. */
244
+ readonly from: number
245
+ readonly to: number
246
+ /** When this client received it (its own clock), and the update's sequence number. */
247
+ readonly at: number
248
+ readonly seq: number
249
+ }
250
+
251
+ export interface RecentEdits {
252
+ /** The edits still recent, oldest first, at their current positions (an insertion since deleted is gone). */
253
+ readonly edits: () => ReadonlyArray<RecentEdit>
254
+ /** Called when an edit arrives or one stops being recent. */
255
+ readonly subscribe: (listener: () => void) => () => void
256
+ readonly dispose: () => void
257
+ }
258
+
259
+ interface Tracked {
260
+ readonly userId: string
261
+ readonly origin: CollabOrigin
262
+ readonly kind: "insert" | "delete"
263
+ readonly start: Y.RelativePosition
264
+ readonly end: Y.RelativePosition
265
+ readonly at: number
266
+ readonly seq: number
267
+ }
268
+
269
+ /**
270
+ * Collaborators' recent edits to a text root of a live document (default `content`), attributed to the person the
271
+ * kernel recorded as each update's author (`connection.remoteAuthor`), never to what a client says about itself. The
272
+ * positions follow later edits (Yjs relative positions). Only remote changes delivered one by one are attributed;
273
+ * a whole state (a first sync, or a reset after compaction) is nobody's in particular and adds nothing. An edit stops
274
+ * being recent after `ttlMs` (default 15 s); at most `max` (default 100) are kept.
275
+ */
276
+ export const recentEdits = (
277
+ connection: CollabConnection,
278
+ options: {
279
+ readonly text?: string | undefined
280
+ readonly ttlMs?: number | undefined
281
+ readonly max?: number | undefined
282
+ readonly now?: (() => number) | undefined
283
+ } = {},
284
+ ): RecentEdits => {
285
+ const doc = connection.doc
286
+ const ytext = doc.getText(options.text ?? "content")
287
+ const ttl = options.ttlMs ?? 15_000
288
+ const max = options.max ?? 100
289
+ const now = options.now ?? Date.now
290
+ const listeners = new Set<() => void>()
291
+ let tracked: Array<Tracked> = []
292
+ let timer: ReturnType<typeof setTimeout> | undefined
293
+
294
+ const notify = () => {
295
+ for (const listener of listeners) listener()
296
+ }
297
+ /** Wake when the oldest edit stops being recent, so listeners redraw without it. */
298
+ const schedule = () => {
299
+ if (timer !== undefined) clearTimeout(timer)
300
+ timer = undefined
301
+ const oldest = tracked[0]
302
+ if (oldest === undefined) return
303
+ timer = setTimeout(
304
+ () => {
305
+ timer = undefined
306
+ tracked = tracked.filter((t) => now() - t.at < ttl)
307
+ notify()
308
+ schedule()
309
+ },
310
+ Math.max(0, oldest.at + ttl - now()),
311
+ )
312
+ }
313
+
314
+ const observer = (event: Y.YTextEvent, transaction: Y.Transaction) => {
315
+ if (transaction.origin !== REMOTE) return
316
+ const author = connection.remoteAuthor
317
+ if (author === undefined) return
318
+ const at = now()
319
+ let index = 0
320
+ for (const op of event.delta) {
321
+ if (op.retain !== undefined) index += op.retain
322
+ else if (op.insert !== undefined) {
323
+ const length = typeof op.insert === "string" ? op.insert.length : 1
324
+ tracked.push({
325
+ userId: author.userId,
326
+ origin: author.origin,
327
+ kind: "insert",
328
+ start: Y.createRelativePositionFromTypeIndex(ytext, index),
329
+ end: Y.createRelativePositionFromTypeIndex(ytext, index + length, -1),
330
+ at,
331
+ seq: author.seq,
332
+ })
333
+ index += length
334
+ } else if (op.delete !== undefined) {
335
+ const point = Y.createRelativePositionFromTypeIndex(ytext, index)
336
+ tracked.push({ ...author, kind: "delete", start: point, end: point, at })
337
+ }
338
+ }
339
+ if (tracked.length > max) tracked = tracked.slice(tracked.length - max)
340
+ schedule()
341
+ notify()
342
+ }
343
+ ytext.observe(observer)
344
+
345
+ const resolve = (position: Y.RelativePosition) => Y.createAbsolutePositionFromRelativePosition(position, doc)?.index
346
+
347
+ return {
348
+ edits: () => {
349
+ const result: Array<RecentEdit> = []
350
+ for (const t of tracked) {
351
+ if (now() - t.at >= ttl) continue
352
+ const from = resolve(t.start)
353
+ const to = resolve(t.end)
354
+ if (from === undefined || to === undefined) continue
355
+ // An insertion whose text was deleted since has nothing left to show.
356
+ if (t.kind === "insert" && to <= from) continue
357
+ result.push({
358
+ userId: t.userId,
359
+ origin: t.origin,
360
+ kind: t.kind,
361
+ from,
362
+ to: t.kind === "delete" ? from : to,
363
+ at: t.at,
364
+ seq: t.seq,
365
+ })
366
+ }
367
+ return result
368
+ },
369
+ subscribe: (listener) => {
370
+ listeners.add(listener)
371
+ return () => listeners.delete(listener)
372
+ },
373
+ dispose: () => {
374
+ ytext.unobserve(observer)
375
+ if (timer !== undefined) clearTimeout(timer)
376
+ timer = undefined
377
+ tracked = []
378
+ listeners.clear()
379
+ },
380
+ }
381
+ }