@isometriks/live_cable 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.
@@ -0,0 +1,550 @@
1
+ /**
2
+ * LiveCable Subscription Manager
3
+ *
4
+ * This module implements subscription persistence for LiveCable components.
5
+ * Instead of creating new ActionCable subscriptions every time a Stimulus controller
6
+ * connects/disconnects, we maintain a single subscription per component instance
7
+ * (identified by liveId) and simply update the controller reference.
8
+ *
9
+ * Architecture:
10
+ * - SubscriptionManager: Singleton that manages all active subscriptions
11
+ * - Subscription: Wraps an ActionCable subscription and handles morphdom updates
12
+ * - Controller reconnection: When a controller disconnects/reconnects (e.g., due to
13
+ * Turbo navigation), the subscription persists and just updates its controller reference
14
+ *
15
+ * Benefits:
16
+ * - Reduces WebSocket churn
17
+ * - Maintains server-side state across page transitions
18
+ * - Eliminates race conditions from rapid connect/disconnect cycles
19
+ */
20
+
21
+ import { createConsumer } from "@rails/actioncable"
22
+ import morphdom from "morphdom"
23
+ import DOM from "@isometriks/live_cable/dom"
24
+
25
+ const consumer = createConsumer()
26
+
27
+ /**
28
+ * Create a DOM element from HTML string, skipping comment nodes.
29
+ * @param {string} html - HTML to build DOM from
30
+ * @returns {HTMLElement}
31
+ */
32
+ function createDOMFromHTML(html) {
33
+ const template = document.createElement('template')
34
+ template.innerHTML = html
35
+
36
+ // Find a node that isn't a comment
37
+ const node = template.content.childNodes
38
+ .values()
39
+ .find(n => n.nodeName !== '#comment')
40
+
41
+ if (node) {
42
+ DOM.mutate(node)
43
+ return node
44
+ }
45
+
46
+ return template.content.childNodes[0]
47
+ }
48
+
49
+ /**
50
+ * Manages all LiveCable subscriptions across the application.
51
+ * Ensures that each component (identified by liveId) has at most one
52
+ * active ActionCable subscription at any time.
53
+ */
54
+ class SubscriptionManager {
55
+ /** @type {Object.<string, Subscription>} */
56
+ #subscriptions = {}
57
+ /** @type {Object.<string, ComponentState>} */
58
+ #componentStates = {}
59
+
60
+ /**
61
+ * Register a component state before subscription is created.
62
+ * Used when a child component is rendered before its controller connects.
63
+ *
64
+ * @param {string} liveId - Unique identifier for the component instance
65
+ * @param {HTMLElement} element - The DOM element created from initial render
66
+ * @param {Object} refreshData - Initial refresh data with parts and template
67
+ * @returns {ComponentState} The component state instance
68
+ */
69
+ registerComponent(liveId, element, refreshData) {
70
+ if (!this.#componentStates[liveId]) {
71
+ this.#componentStates[liveId] = new ComponentState(liveId, element, refreshData)
72
+ }
73
+ return this.#componentStates[liveId]
74
+ }
75
+
76
+ /**
77
+ * Subscribe to or reconnect to a LiveCable component.
78
+ * If a subscription already exists for this liveId, updates the controller
79
+ * reference instead of creating a new subscription.
80
+ * If a ComponentState exists and the controller element matches, reuses it.
81
+ *
82
+ * @param {string} id - Raw ID for the component (e.g., "room-1")
83
+ * @param {string} component - Component class name (e.g., "chat/chat_room")
84
+ * @param {Object} defaults - Default values for reactive variables
85
+ * @param {Object} controller - Stimulus controller instance
86
+ * @returns {Subscription} The subscription instance
87
+ */
88
+ subscribe(id, component, defaults, controller) {
89
+ const liveId = `${component}/${id}`
90
+
91
+ if (!this.#subscriptions[liveId]) {
92
+ const componentState = this.#componentStates[liveId]
93
+
94
+ // Check if we have a pre-existing component state and if the element matches
95
+ if (componentState && componentState.element === controller.element) {
96
+ // Create subscription with existing state
97
+ this.#subscriptions[liveId] = new Subscription(id, component, defaults, controller, componentState)
98
+ // Clean up component state
99
+ delete this.#componentStates[liveId]
100
+ } else {
101
+ // Create new subscription normally
102
+ this.#subscriptions[liveId] = new Subscription(id, component, defaults, controller)
103
+ }
104
+ }
105
+
106
+ this.#subscriptions[liveId].controller = controller
107
+
108
+ return this.#subscriptions[liveId]
109
+ }
110
+
111
+ /**
112
+ * Remove a subscription from the manager.
113
+ * Called when the server sends a 'destroy' status, indicating the
114
+ * component instance should be permanently removed.
115
+ *
116
+ * @param {string} liveId - Unique identifier for the component instance
117
+ */
118
+ unsubscribe(liveId) {
119
+ delete this.#subscriptions[liveId]
120
+ }
121
+
122
+ /**
123
+ * Unsubscribe components not present in the new page body.
124
+ * Called before Turbo Drive renders a new page so that only components
125
+ * truly leaving the page are cleaned up — components that persist across
126
+ * pages (e.g. nav widgets) keep their subscriptions and server-side state.
127
+ *
128
+ * Because pages with live components are prevented from being cached (via
129
+ * the turbo-cache-control meta tag), back/forward navigation always triggers
130
+ * a fresh server fetch, so components are always pre-rendered before their
131
+ * ActionCable subscription connects — no cold re-render needed.
132
+ *
133
+ * @param {HTMLElement} newBody - The incoming page body element from turbo:before-render
134
+ */
135
+ prune(newBody) {
136
+ const newLiveIds = this.#extractLiveIds(newBody)
137
+
138
+ Object.entries(this.#subscriptions).forEach(([liveId, subscription]) => {
139
+ if (!newLiveIds.has(liveId)) {
140
+ subscription.unsubscribe()
141
+ }
142
+ })
143
+
144
+ Object.keys(this.#componentStates).forEach(liveId => {
145
+ if (!newLiveIds.has(liveId)) {
146
+ delete this.#componentStates[liveId]
147
+ }
148
+ })
149
+ }
150
+
151
+ /**
152
+ * Extract the set of live IDs present in a body element.
153
+ * Handles both fresh server renders (live-id attributes, not yet mutated)
154
+ * and Turbo cache restores (data-live-id-value attributes, already mutated).
155
+ *
156
+ * @param {HTMLElement} body
157
+ * @returns {Set<string>}
158
+ */
159
+ #extractLiveIds(body) {
160
+ const ids = new Set()
161
+
162
+ body.querySelectorAll('[live-id]').forEach(el => {
163
+ const id = el.getAttribute('live-id')
164
+ const component = el.getAttribute('live-component')
165
+ if (id && component) ids.add(`${component}/${id}`)
166
+ })
167
+
168
+ body.querySelectorAll('[data-live-id-value]').forEach(el => {
169
+ const id = el.getAttribute('data-live-id-value')
170
+ const component = el.getAttribute('data-live-component-value')
171
+ if (id && component) ids.add(`${component}/${id}`)
172
+ })
173
+
174
+ return ids
175
+ }
176
+
177
+ /**
178
+ * Get component state by liveId.
179
+ * Returns the state from either a subscription or a standalone component state.
180
+ * @param {string} liveId - Unique identifier for the component instance
181
+ * @returns {ComponentState|undefined}
182
+ */
183
+ getComponentState(liveId) {
184
+ return this.#subscriptions[liveId]?.componentState || this.#componentStates[liveId]
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Stores component state before subscription is active.
190
+ * Used when a child component is rendered in parent's HTML before
191
+ * the child's Stimulus controller connects and creates subscription.
192
+ */
193
+ class ComponentState {
194
+ /** @type {string} */
195
+ #liveId
196
+ /** @type {Object} - Map of template_id to parts array */
197
+ #partsByTemplate
198
+ /** @type {string|null} - Last template ID received */
199
+ #lastTemplate
200
+ /** @type {HTMLElement} - The DOM element for this component */
201
+ #element
202
+
203
+ /**
204
+ * Creates component state from initial render data.
205
+ *
206
+ * @param {string} liveId - Unique identifier for the component instance
207
+ * @param {HTMLElement} element - The DOM element created from initial render
208
+ * @param {Object} refreshData - Initial refresh data with parts and template
209
+ */
210
+ constructor(liveId, element, refreshData) {
211
+ this.#liveId = liveId
212
+ this.#element = element
213
+ this.#partsByTemplate = {}
214
+ this.#lastTemplate = null
215
+
216
+ // Store initial render data
217
+ if (refreshData) {
218
+ const [template, parts] = [refreshData['h'], refreshData['p']]
219
+ const tid = template || 'default'
220
+ this.#lastTemplate = tid
221
+ this.#partsByTemplate[tid] = parts
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Get the stored DOM element.
227
+ * @returns {HTMLElement}
228
+ */
229
+ get element() {
230
+ return this.#element
231
+ }
232
+
233
+ /**
234
+ * Create a DOM element from stored state.
235
+ * @param {Object} refresh - Optional refresh data to update state
236
+ * @returns {HTMLElement}
237
+ */
238
+ createRefresh(refresh) {
239
+ // If no refresh data provided, use the last rendered template
240
+ if (!refresh) {
241
+ const tid = this.#lastTemplate || 'default'
242
+ const html = this.#partsByTemplate[tid].join('')
243
+ return this.#buildRefreshDOM(html)
244
+ }
245
+
246
+ const [template, parts] = [refresh['h'], refresh['p']]
247
+
248
+ // Use a default template ID for backward compatibility
249
+ const tid = template || this.#lastTemplate || 'default'
250
+ this.#lastTemplate = tid
251
+
252
+ // First render for this template
253
+ if (!this.#partsByTemplate[tid]) {
254
+ this.#partsByTemplate[tid] = parts
255
+ } else {
256
+ // Replace non-null parts
257
+ for (let i = 0; i < parts.length; i++) {
258
+ if (parts[i] !== null) {
259
+ this.#partsByTemplate[tid][i] = parts[i]
260
+ }
261
+ }
262
+ }
263
+
264
+ const html = this.#partsByTemplate[tid].join('')
265
+ return this.#buildRefreshDOM(html)
266
+ }
267
+
268
+ /**
269
+ * Build a DOM element from HTML.
270
+ * @param {string} html - HTML to build DOM from
271
+ * @returns {HTMLElement}
272
+ * @private
273
+ */
274
+ #buildRefreshDOM(html) {
275
+ return createDOMFromHTML(html)
276
+ }
277
+
278
+ /**
279
+ * Set the DOM element reference.
280
+ * @param {HTMLElement} element
281
+ */
282
+ set element(element) {
283
+ this.#element = element
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Represents a single ActionCable subscription to a LiveCable component.
289
+ * Handles receiving updates from the server and applying them to the DOM
290
+ * via morphdom.
291
+ */
292
+ class Subscription {
293
+ /** @type {string} */
294
+ #id
295
+ /** @type {string} */
296
+ #component
297
+ /** @type {Object} */
298
+ #defaults
299
+ /** @type {Object|null} */
300
+ #controller
301
+ /** @type {ComponentState} */
302
+ #componentState
303
+ /** @type {Object} */
304
+ #subscription
305
+ /** @type {string|null} */
306
+ #currentStatus = null
307
+ /**
308
+ * Creates a new subscription to a LiveCable component.
309
+ *
310
+ * @param {string} id - Raw ID for the component (e.g., "room-1")
311
+ * @param {string} component - Component class name (e.g., "chat/chat_room")
312
+ * @param {Object} defaults - Default values for reactive variables
313
+ * @param {Object} controller - Stimulus controller instance
314
+ * @param {ComponentState} [existingState] - Optional existing component state to reuse
315
+ */
316
+ constructor(id, component, defaults, controller, existingState) {
317
+ this.#id = id
318
+ this.#component = component
319
+ this.#defaults = defaults
320
+ this.#controller = controller
321
+
322
+ // Use existing state or create new one
323
+ if (existingState) {
324
+ this.#componentState = existingState
325
+ // Update element reference to controller's element
326
+ this.#componentState.element = controller.element
327
+ } else {
328
+ this.#componentState = new ComponentState(
329
+ `${component}/${id}`,
330
+ controller.element,
331
+ null
332
+ )
333
+ }
334
+
335
+ this.#subscribe()
336
+ }
337
+
338
+ /**
339
+ * Get the component state.
340
+ * @returns {ComponentState}
341
+ */
342
+ get componentState() {
343
+ return this.#componentState
344
+ }
345
+
346
+ /**
347
+ * Update the controller reference.
348
+ * Called when a Stimulus controller reconnects to an existing subscription.
349
+ *
350
+ * @param {Object} controller - Stimulus controller instance
351
+ */
352
+ set controller(controller) {
353
+ this.#controller = controller
354
+ }
355
+
356
+ /**
357
+ * Send a message to the server through the ActionCable subscription.
358
+ *
359
+ * @param {Object} message - Message to send (e.g., action calls, reactive updates)
360
+ */
361
+ send(message) {
362
+ this.#subscription.send(message)
363
+ }
364
+
365
+ /**
366
+ * Unsubscribe from ActionCable and remove from the subscription manager.
367
+ * Called when navigating away from this component's page, or when the
368
+ * server sends a 'destroy' status.
369
+ */
370
+ unsubscribe() {
371
+ this.#subscription.unsubscribe()
372
+ const liveId = `${this.#component}/${this.#id}`
373
+ subscriptionManager.unsubscribe(liveId)
374
+ }
375
+
376
+ /**
377
+ * Create the underlying ActionCable subscription.
378
+ * @private
379
+ */
380
+ #subscribe() {
381
+ this.#subscription = consumer.subscriptions.create({
382
+ channel: "LiveChannel",
383
+ id: this.#id,
384
+ component: this.#component,
385
+ defaults: this.#defaults,
386
+ }, {
387
+ received: this.#received,
388
+ })
389
+ }
390
+
391
+ /**
392
+ * Handle incoming messages from the server.
393
+ * Processes status updates and DOM refreshes.
394
+ *
395
+ * @param {Object} data - Data received from the server
396
+ * @param {string} [data._status] - Status update (e.g., 'subscribed', 'destroy')
397
+ * @param {string} [data._refresh] - HTML to morph into the DOM
398
+ * @param {string} [data._error] - Raw error HTML to replace the component with
399
+ * @private
400
+ */
401
+ #received = (data) => {
402
+ if (data['_status']) {
403
+ this.#handleStatus(data['_status'])
404
+ } else if (data['_refresh']) {
405
+ this.#handleRefresh(data['_refresh'])
406
+ } else if (data['_error']) {
407
+ this.#handleError(data['_error'])
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Handle error messages from the server.
413
+ * Replaces the component element with raw error HTML, then unsubscribes
414
+ * to trigger server-side cleanup via LiveChannel#unsubscribed.
415
+ * @param {string} html - Raw HTML error markup
416
+ * @private
417
+ */
418
+ #handleError(html) {
419
+ if (!this.#controller) {
420
+ return
421
+ }
422
+
423
+ this.#controller.element.outerHTML = html
424
+ this.unsubscribe()
425
+ }
426
+
427
+ /**
428
+ * Handle status updates from the server.
429
+ * Updates the controller's status and handles destroy status.
430
+ * @param {string} status - Status update (e.g., 'subscribed', 'destroy')
431
+ * @private
432
+ */
433
+ #handleStatus(status) {
434
+ this.#currentStatus = status
435
+
436
+ if (this.#controller) {
437
+ this.#controller.statusValue = status
438
+ }
439
+
440
+ // Handle destroy status - permanently remove this subscription
441
+ if (status === 'destroy') {
442
+ this.unsubscribe()
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Handle DOM refreshes from the server.
448
+ * Updates the DOM using morphdom.
449
+ * @param {Object} refresh - Refresh data from the server
450
+ * @private
451
+ */
452
+ #handleRefresh(refresh) {
453
+ // If we're getting a refresh we must be connected
454
+ this.#handleStatus('subscribed')
455
+
456
+ // If no controller is attached, we can't update the DOM
457
+ if (!this.#controller) {
458
+ return
459
+ }
460
+
461
+ morphdom(this.#controller.element, this.#buildRefreshDOM(refresh), {
462
+ // Preserve elements marked with live-ignore attribute
463
+ onBeforeElUpdated(fromEl, toEl) {
464
+ return fromEl.hasAttribute && !fromEl.hasAttribute('live-ignore')
465
+ },
466
+ // Use stable keys for better morphing performance and state preservation
467
+ getNodeKey(node) {
468
+ if (!node) {
469
+ return
470
+ }
471
+
472
+ if (node.getAttribute) {
473
+ const liveKey = node.getAttribute('live-key')
474
+ const id = node.getAttribute('id') || node.id
475
+
476
+ if (liveKey) {
477
+ return liveKey
478
+ }
479
+
480
+ if (id) {
481
+ return id
482
+ }
483
+
484
+ // Combine live-component and live-id for unique component identification
485
+ const liveComponent = node.getAttribute('data-live-component-value')
486
+ const liveId = node.getAttribute('data-live-id-value')
487
+
488
+ if (liveComponent && liveId) {
489
+ return `${liveComponent}/${liveId}`
490
+ }
491
+ }
492
+ }
493
+ })
494
+ }
495
+
496
+ #buildRefreshDOM(refresh) {
497
+ const rootNode = this.#componentState.createRefresh(refresh)
498
+
499
+ // Apply stored status to root element
500
+ if (this.#currentStatus && rootNode.setAttribute) {
501
+ rootNode.setAttribute('data-live-status-value', this.#currentStatus)
502
+ }
503
+
504
+ // Root node will be a component
505
+ DOM.mutate(rootNode)
506
+
507
+ // Check for child components
508
+ rootNode.querySelectorAll('[live-id]').forEach(child => {
509
+ DOM.mutate(child)
510
+ })
511
+
512
+ // Replace Child Components
513
+ const childResults = refresh?.c || {}
514
+ rootNode.querySelectorAll('LiveCable').forEach(component => {
515
+ const liveId = component.getAttribute('child-live-id')
516
+ const childResult = childResults[liveId]
517
+
518
+ const componentState = subscriptionManager.getComponentState(liveId)
519
+
520
+ if (componentState) {
521
+ // ComponentState already exists (either in subscription or standalone)
522
+ component.replaceWith(
523
+ componentState.createRefresh(childResult)
524
+ )
525
+ } else {
526
+ // No state exists yet - create ComponentState
527
+ const childElement = this.#buildChildElement(childResult)
528
+ subscriptionManager.registerComponent(liveId, childElement, childResult)
529
+ component.replaceWith(childElement)
530
+ }
531
+ })
532
+
533
+ return rootNode
534
+ }
535
+
536
+ #buildChildElement(childResult) {
537
+ if (!childResult) {
538
+ return document.createTextNode('')
539
+ }
540
+
541
+ const [template, parts] = [childResult['h'], childResult['p']]
542
+ const html = parts.join('')
543
+
544
+ return createDOMFromHTML(html)
545
+ }
546
+ }
547
+
548
+ const subscriptionManager = new SubscriptionManager()
549
+
550
+ export default subscriptionManager
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@isometriks/live_cable",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "files": [
6
+ "app/assets/javascript"
7
+ ],
8
+ "exports": {
9
+ ".": "./app/assets/javascript/live_cable.js",
10
+ "./controller": "./app/assets/javascript/controllers/live_controller.js",
11
+ "./blessing": "./app/assets/javascript/live_cable_blessing.js",
12
+ "./subscriptions": "./app/assets/javascript/subscriptions.js",
13
+ "./observer": "./app/assets/javascript/observer.js",
14
+ "./dom": "./app/assets/javascript/dom.js"
15
+ },
16
+ "peerDependencies": {
17
+ "@rails/actioncable": ">=7.0",
18
+ "@hotwired/stimulus": ">=3.0",
19
+ "morphdom": "^2.7"
20
+ },
21
+ "scripts": {
22
+ "test": "vitest",
23
+ "test:ui": "vitest --ui",
24
+ "test:coverage": "vitest --coverage",
25
+ "docs:dev": "vitepress dev docs",
26
+ "docs:build": "vitepress build docs",
27
+ "docs:preview": "vitepress preview docs"
28
+ },
29
+ "devDependencies": {
30
+ "@vitest/ui": "^2.1.8",
31
+ "happy-dom": "^15.11.7",
32
+ "vitest": "^2.1.8",
33
+ "vitepress": "^2.0.0-alpha.15",
34
+ "vue": "^3.5.26"
35
+ }
36
+ }