@isometriks/live_cable 0.3.0 → 0.5.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.
@@ -45,6 +45,19 @@ function createDOMFromHTML(html) {
45
45
  return template.content.childNodes[0]
46
46
  }
47
47
 
48
+ const UNTYPED_INPUT_TYPES = new Set(['checkbox', 'radio', 'file', 'hidden', 'submit', 'reset', 'button', 'image'])
49
+
50
+ /**
51
+ * Whether the user enters the element's value, by typing or with a picker or
52
+ * slider.
53
+ * @param {Element} element
54
+ * @returns {boolean}
55
+ */
56
+ function isTypedField(element) {
57
+ return element instanceof HTMLTextAreaElement ||
58
+ (element instanceof HTMLInputElement && !UNTYPED_INPUT_TYPES.has(element.type))
59
+ }
60
+
48
61
  /**
49
62
  * Manages all LiveCable subscriptions across the application.
50
63
  * Ensures that each component (identified by liveId) has at most one
@@ -55,6 +68,8 @@ class SubscriptionManager {
55
68
  #subscriptions = {}
56
69
  /** @type {Object.<string, ComponentState>} */
57
70
  #componentStates = {}
71
+ /** @type {string|null} - Digest from live_cable_identity_tag the socket was opened under */
72
+ #identity = null
58
73
 
59
74
  /**
60
75
  * Register a component state before subscription is created.
@@ -75,31 +90,31 @@ class SubscriptionManager {
75
90
  /**
76
91
  * Subscribe to or reconnect to a LiveCable component.
77
92
  * If a subscription already exists for this liveId, updates the controller
78
- * reference instead of creating a new subscription.
79
- * If a ComponentState exists and the controller element matches, reuses it.
93
+ * reference instead of creating a new subscription - unless the element
94
+ * brings different defaults, in which case the old subscription is replaced
95
+ * so the server builds the component again from them.
96
+ * If a parent's render left a ComponentState for it, the subscription takes it.
80
97
  *
81
98
  * @param {string} id - Raw ID for the component (e.g., "room-1")
82
99
  * @param {string} component - Component class name (e.g., "chat/chat_room")
83
- * @param {Object} defaults - Default values for reactive variables
100
+ * @param {string} defaults - Opaque signed defaults blob, forwarded to the server
84
101
  * @param {Object} controller - Stimulus controller instance
85
102
  * @returns {Subscription} The subscription instance
86
103
  */
87
104
  subscribe(id, component, defaults, controller) {
88
105
  const liveId = `${component}/${id}`
89
106
 
107
+ if (this.#subscriptions[liveId] && this.#defaultsChanged(this.#subscriptions[liveId], defaults)) {
108
+ this.#subscriptions[liveId].unsubscribe()
109
+ }
110
+
90
111
  if (!this.#subscriptions[liveId]) {
91
112
  const componentState = this.#componentStates[liveId]
92
113
 
93
- // Check if we have a pre-existing component state and if the element matches
94
- if (componentState && componentState.element === controller.element) {
95
- // Create subscription with existing state
96
- this.#subscriptions[liveId] = new Subscription(id, component, defaults, controller, componentState)
97
- // Clean up component state
98
- delete this.#componentStates[liveId]
99
- } else {
100
- // Create new subscription normally
101
- this.#subscriptions[liveId] = new Subscription(id, component, defaults, controller)
102
- }
114
+ // Whichever element its controller connected on: a morph keeps a
115
+ // prerendered root with an id in place of the one the parent's render built
116
+ this.#subscriptions[liveId] = new Subscription(id, component, defaults, controller, componentState)
117
+ delete this.#componentStates[liveId]
103
118
  }
104
119
 
105
120
  this.#subscriptions[liveId].controller = controller
@@ -107,6 +122,23 @@ class SubscriptionManager {
107
122
  return this.#subscriptions[liveId]
108
123
  }
109
124
 
125
+ /**
126
+ * Only a page rendered over HTTP carries a defaults blob; an element rendered
127
+ * over the socket has none and says nothing about them. Signing is
128
+ * deterministic, so the same defaults always produce the same blob. A Turbo
129
+ * preview shows a cached copy of the page, whose blob may be stale; the
130
+ * page itself follows it.
131
+ *
132
+ * @param {Subscription} subscription
133
+ * @param {string} defaults
134
+ * @returns {boolean}
135
+ */
136
+ #defaultsChanged(subscription, defaults) {
137
+ return Boolean(defaults) &&
138
+ defaults !== subscription.defaults &&
139
+ !document.documentElement.hasAttribute('data-turbo-preview')
140
+ }
141
+
110
142
  /**
111
143
  * Remove a subscription from the manager.
112
144
  * Called when the server sends a 'destroy' status, indicating the
@@ -118,6 +150,38 @@ class SubscriptionManager {
118
150
  delete this.#subscriptions[liveId]
119
151
  }
120
152
 
153
+ /**
154
+ * Reopen the socket when the page was rendered for someone other than the
155
+ * socket was opened for.
156
+ *
157
+ * A socket is identified once, at its handshake, and Turbo keeps it open
158
+ * across a sign-in, sign-out or impersonation, so its components would
159
+ * carry on as the previous identity. The live_cable_identity_tag meta tag
160
+ * carries a digest of who each page was rendered for; Turbo merges the new
161
+ * page's head before turbo:before-render, so this runs before the new
162
+ * body's components subscribe. Reopening closes the socket, the server
163
+ * drops its components, and they resubscribe on the new socket as the new
164
+ * session. A page without the tag, and a Turbo preview of a cached page,
165
+ * say nothing.
166
+ */
167
+ syncIdentity() {
168
+ if (document.documentElement.hasAttribute('data-turbo-preview')) {
169
+ return
170
+ }
171
+
172
+ const identity = document.head.querySelector('meta[name="live-cable-identity"]')?.content
173
+
174
+ if (!identity) {
175
+ return
176
+ }
177
+
178
+ if (this.#identity && identity !== this.#identity && consumer.connection.isActive()) {
179
+ consumer.connection.reopen()
180
+ }
181
+
182
+ this.#identity = identity
183
+ }
184
+
121
185
  /**
122
186
  * Unsubscribe components not present in the new page body.
123
187
  * Called before Turbo Drive renders a new page so that only components
@@ -132,7 +196,28 @@ class SubscriptionManager {
132
196
  * @param {HTMLElement} newBody - The incoming page body element from turbo:before-render
133
197
  */
134
198
  prune(newBody) {
135
- const newLiveIds = this.#extractLiveIds(newBody)
199
+ const newElements = this.#extractLiveIds(newBody)
200
+ const newLiveIds = new Set(newElements.keys())
201
+ const rebuilt = new Set()
202
+
203
+ // A component built again from other defaults builds its children again,
204
+ // including those a cached page still shows
205
+ newElements.forEach((element, liveId) => {
206
+ const subscription = this.#subscriptions[liveId]
207
+
208
+ if (subscription && !this.#carriedOver(element) && this.#defaultsChanged(subscription, this.#defaultsOf(element))) {
209
+ rebuilt.add(liveId)
210
+ this.#extractLiveIds(element).forEach((_, childId) => newLiveIds.delete(childId))
211
+ }
212
+ })
213
+
214
+ // Inline children have no live id on a rendered page; a component kept
215
+ // with its defaults rebuilds them, and the set grows to take in grandchildren
216
+ newLiveIds.forEach(liveId => {
217
+ if (!rebuilt.has(liveId)) {
218
+ this.getComponentState(liveId)?.childLiveIds.forEach(childId => newLiveIds.add(childId))
219
+ }
220
+ })
136
221
 
137
222
  Object.entries(this.#subscriptions).forEach(([liveId, subscription]) => {
138
223
  if (!newLiveIds.has(liveId)) {
@@ -148,29 +233,52 @@ class SubscriptionManager {
148
233
  }
149
234
 
150
235
  /**
151
- * Extract the set of live IDs present in a body element.
152
- * Handles both fresh server renders (live-id attributes, not yet mutated)
153
- * and Turbo cache restores (data-live-id-value attributes, already mutated).
236
+ * Extract the live IDs present inside an element, with the element each
237
+ * belongs to. Handles both fresh server renders (live-id attributes, not
238
+ * yet mutated) and Turbo cache restores (data-live-id-value attributes,
239
+ * already mutated).
154
240
  *
155
241
  * @param {HTMLElement} body
156
- * @returns {Set<string>}
242
+ * @returns {Map<string, HTMLElement>}
157
243
  */
158
244
  #extractLiveIds(body) {
159
- const ids = new Set()
245
+ const elements = new Map()
160
246
 
161
247
  body.querySelectorAll('[live-id]').forEach(el => {
162
248
  const id = el.getAttribute('live-id')
163
249
  const component = el.getAttribute('live-component')
164
- if (id && component) ids.add(`${component}/${id}`)
250
+ if (id && component) elements.set(`${component}/${id}`, el)
165
251
  })
166
252
 
167
253
  body.querySelectorAll('[data-live-id-value]').forEach(el => {
168
254
  const id = el.getAttribute('data-live-id-value')
169
255
  const component = el.getAttribute('data-live-component-value')
170
- if (id && component) ids.add(`${component}/${id}`)
256
+ if (id && component) elements.set(`${component}/${id}`, el)
171
257
  })
172
258
 
173
- return ids
259
+ return elements
260
+ }
261
+
262
+ /**
263
+ * Whether Turbo will keep what is already on the page in place of this
264
+ * element: it carries a [data-turbo-permanent] element over, with all it
265
+ * holds, when the new page has a permanent element with the same id.
266
+ *
267
+ * @param {HTMLElement} element - An element in the incoming page
268
+ * @returns {boolean}
269
+ */
270
+ #carriedOver(element) {
271
+ const permanent = element.closest('[id][data-turbo-permanent]')
272
+
273
+ return Boolean(permanent && document.getElementById(permanent.id)?.hasAttribute('data-turbo-permanent'))
274
+ }
275
+
276
+ /**
277
+ * @param {HTMLElement} element
278
+ * @returns {string} The signed defaults blob the element carries
279
+ */
280
+ #defaultsOf(element) {
281
+ return element.getAttribute('live-defaults') ?? element.getAttribute('data-live-defaults-value') ?? ''
174
282
  }
175
283
 
176
284
  /**
@@ -198,6 +306,8 @@ class ComponentState {
198
306
  #lastTemplate
199
307
  /** @type {HTMLElement} - The DOM element for this component */
200
308
  #element
309
+ /** @type {number} */
310
+ #renderCount = 0
201
311
 
202
312
  /**
203
313
  * Creates component state from initial render data.
@@ -238,6 +348,25 @@ class ComponentState {
238
348
  return this.#lastTemplate !== null && Boolean(this.#partsByTemplate[this.#lastTemplate])
239
349
  }
240
350
 
351
+ /**
352
+ * How many renders have been stored, counting those that arrived in a
353
+ * parent's refresh.
354
+ * @returns {number}
355
+ */
356
+ get renderCount() {
357
+ return this.#renderCount
358
+ }
359
+
360
+ /**
361
+ * Live ids of the child components placed in the last render.
362
+ * @returns {string[]}
363
+ */
364
+ get childLiveIds() {
365
+ const template = document.createElement('template')
366
+ template.innerHTML = (this.#partsByTemplate[this.#lastTemplate] ?? []).join('')
367
+ return Array.from(template.content.querySelectorAll('LiveCable'), el => el.getAttribute('child-live-id'))
368
+ }
369
+
241
370
  /**
242
371
  * Create a DOM element from stored state.
243
372
  * @param {Object} refresh - Optional refresh data to update state
@@ -251,6 +380,7 @@ class ComponentState {
251
380
  return this.#buildRefreshDOM(html)
252
381
  }
253
382
 
383
+ this.#renderCount++
254
384
  const [template, parts] = [refresh['h'], refresh['p']]
255
385
 
256
386
  // Use a default template ID for backward compatibility
@@ -302,7 +432,7 @@ class Subscription {
302
432
  #id
303
433
  /** @type {string} */
304
434
  #component
305
- /** @type {Object} */
435
+ /** @type {string} */
306
436
  #defaults
307
437
  /** @type {Object|null} */
308
438
  #controller
@@ -312,12 +442,20 @@ class Subscription {
312
442
  #subscription
313
443
  /** @type {string|null} */
314
444
  #currentStatus = null
445
+ /** @type {boolean} - Whether the server has confirmed this subscription on the current socket */
446
+ #confirmed = false
447
+ /** @type {Array<Object>} - Messages held until the subscription is confirmed */
448
+ #pending = []
449
+ /** @type {number} - The render count when the first in-flight message was sent */
450
+ #renderCountAtSend = 0
451
+ /** @type {Map<string, *>} - The value last sent for each live-reactive name */
452
+ #sentValues = new Map()
315
453
  /**
316
454
  * Creates a new subscription to a LiveCable component.
317
455
  *
318
456
  * @param {string} id - Raw ID for the component (e.g., "room-1")
319
457
  * @param {string} component - Component class name (e.g., "chat/chat_room")
320
- * @param {Object} defaults - Default values for reactive variables
458
+ * @param {string} defaults - Opaque signed defaults blob, forwarded to the server
321
459
  * @param {Object} controller - Stimulus controller instance
322
460
  * @param {ComponentState} [existingState] - Optional existing component state to reuse
323
461
  */
@@ -343,6 +481,14 @@ class Subscription {
343
481
  this.#subscribe()
344
482
  }
345
483
 
484
+ /**
485
+ * The signed defaults blob this subscription was created with.
486
+ * @returns {string}
487
+ */
488
+ get defaults() {
489
+ return this.#defaults
490
+ }
491
+
346
492
  /**
347
493
  * Get the component state.
348
494
  * @returns {ComponentState}
@@ -394,12 +540,55 @@ class Subscription {
394
540
  }
395
541
 
396
542
  /**
397
- * Send a message to the server through the ActionCable subscription.
543
+ * Send a message to the server, or hold it until the subscription is
544
+ * confirmed on an open socket.
545
+ *
546
+ * ActionCable drops a message sent while its socket is closed - after a
547
+ * laptop wakes, a network blip, a deploy - and one sent after the socket
548
+ * reopens but before the re-subscribe is confirmed can reach the server
549
+ * before the subscription exists there, which drops it too. Either way the
550
+ * component would wait in its loading state for a reply that is never
551
+ * coming. Held messages go out, in order, once the server confirms the
552
+ * subscription.
398
553
  *
399
554
  * @param {Object} message - Message to send (e.g., action calls, reactive updates)
400
555
  */
401
556
  send(message) {
402
- this.#subscription.send(message)
557
+ if (this.#controller?.inFlight === 1) {
558
+ this.#renderCountAtSend = this.#componentState.renderCount
559
+ }
560
+
561
+ // Only a reply to live-reactive updates alone can be an echo
562
+ if (message.messages.every(({ _action }) => _action === '_reactive')) {
563
+ message.messages.forEach(({ name, value }) => this.#sentValues.set(name, value))
564
+ } else {
565
+ this.#sentValues.clear()
566
+ }
567
+
568
+ if (!this.#confirmed || !this.#subscription.send(message)) {
569
+ this.#pending.push(message)
570
+ }
571
+ }
572
+
573
+ /**
574
+ * How many messages are waiting for a connection.
575
+ * @returns {number}
576
+ */
577
+ get pendingCount() {
578
+ return this.#pending.length
579
+ }
580
+
581
+ /**
582
+ * Drop any messages still waiting for a connection. Called when the loading
583
+ * state gives up on them, so a message the page has said didn't go through
584
+ * can't then go through after a reconnect.
585
+ *
586
+ * @returns {number} How many messages were dropped
587
+ */
588
+ discardPending() {
589
+ const count = this.#pending.length
590
+ this.#pending = []
591
+ return count
403
592
  }
404
593
 
405
594
  /**
@@ -424,10 +613,76 @@ class Subscription {
424
613
  component: this.#component,
425
614
  defaults: this.#defaults,
426
615
  }, {
616
+ connected: this.#connected,
617
+ disconnected: this.#disconnected,
427
618
  received: this.#received,
428
619
  })
429
620
  }
430
621
 
622
+ /**
623
+ * The server confirmed the subscription - on first connect, or again after
624
+ * a reconnect. Anything held while it wasn't goes out now.
625
+ * @private
626
+ */
627
+ #connected = () => {
628
+ this.#confirmed = true
629
+ // ActionCable can replace a stale socket without calling disconnected
630
+ if (this.#settleLostMessages()) {
631
+ this.catchUp()
632
+ }
633
+
634
+ while (this.#pending.length > 0) {
635
+ // The socket closed again mid-flush; the next confirmation resumes it
636
+ if (!this.#subscription.send(this.#pending[0])) {
637
+ this.#confirmed = false
638
+ break
639
+ }
640
+
641
+ this.#pending.shift()
642
+ }
643
+ }
644
+
645
+ /**
646
+ * The socket closed. ActionCable reconnects and re-subscribes by itself;
647
+ * until it has, sends are held and the component says so.
648
+ * @private
649
+ */
650
+ #disconnected = () => {
651
+ this.#confirmed = false
652
+ if (this.#settleLostMessages()) {
653
+ this.catchUp()
654
+ }
655
+ this.#handleStatus('disconnected')
656
+ }
657
+
658
+ /**
659
+ * End the loading state of messages sent on a socket that has since
660
+ * closed - their replies will never arrive. Held messages still will.
661
+ * @returns {boolean} Whether that ended the loading state
662
+ * @private
663
+ */
664
+ #settleLostMessages() {
665
+ const lost = (this.#controller?.inFlight ?? 0) - this.#pending.length
666
+ let settled = false
667
+
668
+ for (let i = 0; i < lost; i++) {
669
+ settled = this.#controller.finishLoading()
670
+ }
671
+
672
+ return settled
673
+ }
674
+
675
+ /**
676
+ * Morph the last render in again if renders arrived after the first
677
+ * in-flight message went out: the pending elements skipped them. For a
678
+ * loading state that ended without a render to apply.
679
+ */
680
+ catchUp() {
681
+ if (this.#componentState.renderCount !== this.#renderCountAtSend) {
682
+ this.#handleRefresh(null)
683
+ }
684
+ }
685
+
431
686
  /**
432
687
  * Handle incoming messages from the server.
433
688
  * Processes status updates and DOM refreshes.
@@ -436,21 +691,46 @@ class Subscription {
436
691
  * @param {string} [data._status] - Status update (e.g., 'subscribed', 'destroy')
437
692
  * @param {string} [data._refresh] - HTML to morph into the DOM
438
693
  * @param {string} [data._error] - Raw error HTML to replace the component with
439
- * @param {boolean} [data._ack] - Acknowledgement that a message was processed
440
- * without producing a re-render; clears the loading state
694
+ * @param {boolean} [data._reply] - Whether a _refresh answers this
695
+ * component's own message; absent from 0.4 servers, whose refreshes all
696
+ * count as replies
697
+ * @param {boolean} [data._subscribed] - Marks the frame the server sends
698
+ * when it (re)subscribes the component
699
+ * @param {boolean} [data._ack] - Answers a message that no re-render of the
700
+ * component's own answered, as when its render rode in its parent's
701
+ * refresh; clears the loading state
702
+ * @param {boolean} [data._rendered] - Marks an _ack whose message's render
703
+ * of the component rode in its parent's refresh
441
704
  * @param {Array} [data._events] - Events to dispatch as CustomEvents; when
442
705
  * attached to a _refresh they fire after the DOM has been morphed
443
706
  * @private
444
707
  */
445
708
  #received = (data) => {
709
+ // A re-subscribe render brings the component up to date; a status frame doesn't
710
+ if (data['_subscribed'] && this.#settleLostMessages() && !data['_refresh']) {
711
+ this.catchUp()
712
+ }
713
+
446
714
  if (data['_status']) {
447
715
  this.#handleStatus(data['_status'])
448
716
  } else if (data['_refresh']) {
449
- this.#handleRefresh(data['_refresh'])
717
+ const legacy = !('_reply' in data)
718
+ this.#handleRefresh(data['_refresh'], { reply: legacy || data['_reply'] === true, legacy })
450
719
  } else if (data['_error']) {
451
720
  this.#handleError(data['_error'])
452
721
  } else if (data['_ack']) {
453
- this.#controller?.finishLoading()
722
+ this.#handleStatus('subscribed')
723
+
724
+ // Pending elements skipped the renders that came while they waited. When
725
+ // the server says one was this message's, inside its parent's refresh,
726
+ // catching up to it replies
727
+ const missed = this.#componentState.renderCount !== this.#renderCountAtSend
728
+
729
+ if (data['_rendered'] && missed && this.#controller?.inFlight === 1) {
730
+ this.#handleRefresh(null, { reply: true })
731
+ } else if (this.#controller?.finishLoading()) {
732
+ this.catchUp()
733
+ }
454
734
  }
455
735
 
456
736
  // Dispatch after the branch above so events attached to a refresh fire
@@ -509,6 +789,8 @@ class Subscription {
509
789
 
510
790
  // Handle destroy status - permanently remove this subscription
511
791
  if (status === 'destroy') {
792
+ // Replies still on their way go to a subscription that no longer exists
793
+ this.#controller?.resetLoading()
512
794
  this.unsubscribe()
513
795
  }
514
796
  }
@@ -517,9 +799,14 @@ class Subscription {
517
799
  * Handle DOM refreshes from the server.
518
800
  * Updates the DOM using morphdom.
519
801
  * @param {Object} refresh - Refresh data from the server
802
+ * @param {Object} [options]
803
+ * @param {boolean} [options.reply] - Whether the refresh answers this
804
+ * component's own message, which ends its loading state
805
+ * @param {boolean} [options.legacy] - Whether it came from a 0.4 server,
806
+ * which never answers an inline child
520
807
  * @private
521
808
  */
522
- #handleRefresh(refresh) {
809
+ #handleRefresh(refresh, { reply = false, legacy = false } = {}) {
523
810
  // If we're getting a refresh we must be connected
524
811
  this.#handleStatus('subscribed')
525
812
 
@@ -528,15 +815,25 @@ class Subscription {
528
815
  return
529
816
  }
530
817
 
818
+ // A focused field whose form or trigger awaits a reply takes its value,
819
+ // unless that echoes what the field itself sent; read before the restore
820
+ const focused = document.activeElement
821
+ const awaiting = focused?.closest('[live-loading]:not([data-live-id-value])')
822
+ const sent = awaiting === focused ? this.#sentValues.get(focused.name) : undefined
823
+
531
824
  // Restore live-loading / live-disable-with state before morphing so the
532
825
  // morph applies the server-rendered truth on top of the original DOM.
533
- // With multiple messages in flight this only restores once the last
534
- // response arrives - until then the morph below preserves the pending
535
- // elements so live-disable-with buttons can't be clicked early.
536
- this.#controller.finishLoading()
826
+ // Only replies count, and with multiple messages in flight this only
827
+ // restores once the last one arrives - until then the morph below
828
+ // preserves the pending elements so live-disable-with buttons can't be
829
+ // clicked early.
830
+ if (reply) {
831
+ this.#controller.finishLoading()
832
+ }
537
833
 
538
834
  const rootElement = this.#controller.element
539
835
  const stillLoading = this.#controller.isLoading
836
+ const childResults = refresh?.c || {}
540
837
 
541
838
  const refreshDOM = this.#buildRefreshDOM(refresh)
542
839
 
@@ -544,6 +841,8 @@ class Subscription {
544
841
  refreshDOM.setAttribute('live-loading', '')
545
842
  }
546
843
 
844
+ let keepFocusedValue = false
845
+
547
846
  morphdom(rootElement, refreshDOM, {
548
847
  // Preserve elements marked with live-ignore attribute
549
848
  onBeforeElUpdated(fromEl, toEl) {
@@ -561,8 +860,41 @@ class Subscription {
561
860
  return false
562
861
  }
563
862
 
863
+ // A nested component's loading state waits for its own answer, unless a
864
+ // 0.4 server, which never answers an inline child, sent its render
865
+ const owner = fromEl.hasAttribute('live-loading') && fromEl.closest('[data-live-id-value]')
866
+
867
+ if (owner && owner !== rootElement) {
868
+ const liveId = `${owner.getAttribute('data-live-component-value')}/${owner.getAttribute('data-live-id-value')}`
869
+
870
+ if (!legacy || !(liveId in childResults)) {
871
+ if (owner !== fromEl) {
872
+ return false
873
+ }
874
+
875
+ toEl.setAttribute('live-loading', '')
876
+ }
877
+ }
878
+
879
+ // defaultValue is what the server last rendered for the field
880
+ if (fromEl === focused) {
881
+ keepFocusedValue = isTypedField(fromEl) &&
882
+ (awaiting ? toEl.defaultValue === sent : fromEl.defaultValue === toEl.defaultValue)
883
+ }
884
+
564
885
  return true
565
886
  },
887
+ // Skipping its children skips morphdom's value sync, so the focused
888
+ // field keeps what the user typed
889
+ onBeforeElChildrenUpdated(fromEl, toEl) {
890
+ // morphdom updates a textarea's text node, which an empty one lacks;
891
+ // once typed into, setting it leaves the value alone
892
+ if (fromEl instanceof HTMLTextAreaElement && fromEl.defaultValue !== toEl.defaultValue) {
893
+ fromEl.defaultValue = toEl.defaultValue
894
+ }
895
+
896
+ return !(keepFocusedValue && fromEl === focused)
897
+ },
566
898
  // Use stable keys for better morphing performance and state preservation
567
899
  getNodeKey(node) {
568
900
  if (!node) {
@@ -611,24 +943,39 @@ class Subscription {
611
943
 
612
944
  // Replace Child Components
613
945
  const childResults = refresh?.c || {}
614
- rootNode.querySelectorAll('LiveCable').forEach(component => {
946
+ const placeholders = [...rootNode.querySelectorAll('LiveCable')]
947
+ const replaced = new Set()
948
+
949
+ while (placeholders.length > 0) {
950
+ const component = placeholders.shift()
615
951
  const liveId = component.getAttribute('child-live-id')
616
952
  const childResult = childResults[liveId]
617
953
 
954
+ if (replaced.has(liveId)) {
955
+ console.error(`[LiveCable] ${liveId} is rendered more than once in a single refresh`)
956
+ component.remove()
957
+ continue
958
+ }
959
+
960
+ replaced.add(liveId)
961
+
618
962
  const componentState = subscriptionManager.getComponentState(liveId)
963
+ let childElement
619
964
 
620
965
  if (componentState) {
621
966
  // ComponentState already exists (either in subscription or standalone)
622
- component.replaceWith(
623
- componentState.createRefresh(childResult)
624
- )
967
+ childElement = (childResult || componentState.hasRender)
968
+ ? componentState.createRefresh(childResult)
969
+ : document.createTextNode('')
625
970
  } else {
626
971
  // No state exists yet - create ComponentState
627
- const childElement = this.#buildChildElement(childResult)
972
+ childElement = this.#buildChildElement(childResult)
628
973
  subscriptionManager.registerComponent(liveId, childElement, childResult)
629
- component.replaceWith(childElement)
630
974
  }
631
- })
975
+
976
+ component.replaceWith(childElement)
977
+ placeholders.push(...(childElement.querySelectorAll?.('LiveCable') ?? []))
978
+ }
632
979
 
633
980
  return rootNode
634
981
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isometriks/live_cable",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "app/assets/javascript",