@isometriks/live_cable 0.4.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.
- package/CHANGELOG.md +368 -196
- package/README.md +87 -54
- package/app/assets/javascript/controllers/live_controller.js +10 -0
- package/app/assets/javascript/loading.js +3 -3
- package/app/assets/javascript/subscriptions.js +137 -60
- package/package.json +1 -1
|
@@ -45,16 +45,17 @@ function createDOMFromHTML(html) {
|
|
|
45
45
|
return template.content.childNodes[0]
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
const
|
|
48
|
+
const UNTYPED_INPUT_TYPES = new Set(['checkbox', 'radio', 'file', 'hidden', 'submit', 'reset', 'button', 'image'])
|
|
49
49
|
|
|
50
50
|
/**
|
|
51
|
-
* Whether the user
|
|
51
|
+
* Whether the user enters the element's value, by typing or with a picker or
|
|
52
|
+
* slider.
|
|
52
53
|
* @param {Element} element
|
|
53
54
|
* @returns {boolean}
|
|
54
55
|
*/
|
|
55
|
-
function
|
|
56
|
+
function isTypedField(element) {
|
|
56
57
|
return element instanceof HTMLTextAreaElement ||
|
|
57
|
-
(element instanceof HTMLInputElement &&
|
|
58
|
+
(element instanceof HTMLInputElement && !UNTYPED_INPUT_TYPES.has(element.type))
|
|
58
59
|
}
|
|
59
60
|
|
|
60
61
|
/**
|
|
@@ -92,7 +93,7 @@ class SubscriptionManager {
|
|
|
92
93
|
* reference instead of creating a new subscription - unless the element
|
|
93
94
|
* brings different defaults, in which case the old subscription is replaced
|
|
94
95
|
* so the server builds the component again from them.
|
|
95
|
-
* If a
|
|
96
|
+
* If a parent's render left a ComponentState for it, the subscription takes it.
|
|
96
97
|
*
|
|
97
98
|
* @param {string} id - Raw ID for the component (e.g., "room-1")
|
|
98
99
|
* @param {string} component - Component class name (e.g., "chat/chat_room")
|
|
@@ -110,16 +111,10 @@ class SubscriptionManager {
|
|
|
110
111
|
if (!this.#subscriptions[liveId]) {
|
|
111
112
|
const componentState = this.#componentStates[liveId]
|
|
112
113
|
|
|
113
|
-
//
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
// Clean up component state
|
|
118
|
-
delete this.#componentStates[liveId]
|
|
119
|
-
} else {
|
|
120
|
-
// Create new subscription normally
|
|
121
|
-
this.#subscriptions[liveId] = new Subscription(id, component, defaults, controller)
|
|
122
|
-
}
|
|
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]
|
|
123
118
|
}
|
|
124
119
|
|
|
125
120
|
this.#subscriptions[liveId].controller = controller
|
|
@@ -201,12 +196,27 @@ class SubscriptionManager {
|
|
|
201
196
|
* @param {HTMLElement} newBody - The incoming page body element from turbo:before-render
|
|
202
197
|
*/
|
|
203
198
|
prune(newBody) {
|
|
204
|
-
const
|
|
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
|
+
})
|
|
205
213
|
|
|
206
|
-
// Inline children
|
|
207
|
-
// rebuilds them
|
|
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
|
|
208
216
|
newLiveIds.forEach(liveId => {
|
|
209
|
-
|
|
217
|
+
if (!rebuilt.has(liveId)) {
|
|
218
|
+
this.getComponentState(liveId)?.childLiveIds.forEach(childId => newLiveIds.add(childId))
|
|
219
|
+
}
|
|
210
220
|
})
|
|
211
221
|
|
|
212
222
|
Object.entries(this.#subscriptions).forEach(([liveId, subscription]) => {
|
|
@@ -223,29 +233,52 @@ class SubscriptionManager {
|
|
|
223
233
|
}
|
|
224
234
|
|
|
225
235
|
/**
|
|
226
|
-
* Extract the
|
|
227
|
-
* Handles both fresh server renders (live-id attributes, not
|
|
228
|
-
* and Turbo cache restores (data-live-id-value attributes,
|
|
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).
|
|
229
240
|
*
|
|
230
241
|
* @param {HTMLElement} body
|
|
231
|
-
* @returns {
|
|
242
|
+
* @returns {Map<string, HTMLElement>}
|
|
232
243
|
*/
|
|
233
244
|
#extractLiveIds(body) {
|
|
234
|
-
const
|
|
245
|
+
const elements = new Map()
|
|
235
246
|
|
|
236
247
|
body.querySelectorAll('[live-id]').forEach(el => {
|
|
237
248
|
const id = el.getAttribute('live-id')
|
|
238
249
|
const component = el.getAttribute('live-component')
|
|
239
|
-
if (id && component)
|
|
250
|
+
if (id && component) elements.set(`${component}/${id}`, el)
|
|
240
251
|
})
|
|
241
252
|
|
|
242
253
|
body.querySelectorAll('[data-live-id-value]').forEach(el => {
|
|
243
254
|
const id = el.getAttribute('data-live-id-value')
|
|
244
255
|
const component = el.getAttribute('data-live-component-value')
|
|
245
|
-
if (id && component)
|
|
256
|
+
if (id && component) elements.set(`${component}/${id}`, el)
|
|
246
257
|
})
|
|
247
258
|
|
|
248
|
-
return
|
|
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') ?? ''
|
|
249
282
|
}
|
|
250
283
|
|
|
251
284
|
/**
|
|
@@ -329,8 +362,9 @@ class ComponentState {
|
|
|
329
362
|
* @returns {string[]}
|
|
330
363
|
*/
|
|
331
364
|
get childLiveIds() {
|
|
332
|
-
const
|
|
333
|
-
|
|
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'))
|
|
334
368
|
}
|
|
335
369
|
|
|
336
370
|
/**
|
|
@@ -414,6 +448,8 @@ class Subscription {
|
|
|
414
448
|
#pending = []
|
|
415
449
|
/** @type {number} - The render count when the first in-flight message was sent */
|
|
416
450
|
#renderCountAtSend = 0
|
|
451
|
+
/** @type {Map<string, *>} - The value last sent for each live-reactive name */
|
|
452
|
+
#sentValues = new Map()
|
|
417
453
|
/**
|
|
418
454
|
* Creates a new subscription to a LiveCable component.
|
|
419
455
|
*
|
|
@@ -522,6 +558,13 @@ class Subscription {
|
|
|
522
558
|
this.#renderCountAtSend = this.#componentState.renderCount
|
|
523
559
|
}
|
|
524
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
|
+
|
|
525
568
|
if (!this.#confirmed || !this.#subscription.send(message)) {
|
|
526
569
|
this.#pending.push(message)
|
|
527
570
|
}
|
|
@@ -584,7 +627,9 @@ class Subscription {
|
|
|
584
627
|
#connected = () => {
|
|
585
628
|
this.#confirmed = true
|
|
586
629
|
// ActionCable can replace a stale socket without calling disconnected
|
|
587
|
-
this.#settleLostMessages()
|
|
630
|
+
if (this.#settleLostMessages()) {
|
|
631
|
+
this.catchUp()
|
|
632
|
+
}
|
|
588
633
|
|
|
589
634
|
while (this.#pending.length > 0) {
|
|
590
635
|
// The socket closed again mid-flush; the next confirmation resumes it
|
|
@@ -604,20 +649,37 @@ class Subscription {
|
|
|
604
649
|
*/
|
|
605
650
|
#disconnected = () => {
|
|
606
651
|
this.#confirmed = false
|
|
607
|
-
this.#settleLostMessages()
|
|
652
|
+
if (this.#settleLostMessages()) {
|
|
653
|
+
this.catchUp()
|
|
654
|
+
}
|
|
608
655
|
this.#handleStatus('disconnected')
|
|
609
656
|
}
|
|
610
657
|
|
|
611
658
|
/**
|
|
612
659
|
* End the loading state of messages sent on a socket that has since
|
|
613
660
|
* closed - their replies will never arrive. Held messages still will.
|
|
661
|
+
* @returns {boolean} Whether that ended the loading state
|
|
614
662
|
* @private
|
|
615
663
|
*/
|
|
616
664
|
#settleLostMessages() {
|
|
617
665
|
const lost = (this.#controller?.inFlight ?? 0) - this.#pending.length
|
|
666
|
+
let settled = false
|
|
618
667
|
|
|
619
668
|
for (let i = 0; i < lost; i++) {
|
|
620
|
-
this.#controller.finishLoading()
|
|
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)
|
|
621
683
|
}
|
|
622
684
|
}
|
|
623
685
|
|
|
@@ -630,32 +692,44 @@ class Subscription {
|
|
|
630
692
|
* @param {string} [data._refresh] - HTML to morph into the DOM
|
|
631
693
|
* @param {string} [data._error] - Raw error HTML to replace the component with
|
|
632
694
|
* @param {boolean} [data._reply] - Whether a _refresh answers this
|
|
633
|
-
* component's own message; absent from
|
|
634
|
-
*
|
|
695
|
+
* component's own message; absent from 0.4 servers, whose refreshes all
|
|
696
|
+
* count as replies
|
|
635
697
|
* @param {boolean} [data._subscribed] - Marks the frame the server sends
|
|
636
698
|
* when it (re)subscribes the component
|
|
637
|
-
* @param {boolean} [data._ack] - Answers a message
|
|
638
|
-
*
|
|
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
|
|
639
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
|
|
640
704
|
* @param {Array} [data._events] - Events to dispatch as CustomEvents; when
|
|
641
705
|
* attached to a _refresh they fire after the DOM has been morphed
|
|
642
706
|
* @private
|
|
643
707
|
*/
|
|
644
708
|
#received = (data) => {
|
|
645
|
-
|
|
646
|
-
|
|
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()
|
|
647
712
|
}
|
|
648
713
|
|
|
649
714
|
if (data['_status']) {
|
|
650
715
|
this.#handleStatus(data['_status'])
|
|
651
716
|
} else if (data['_refresh']) {
|
|
652
|
-
|
|
717
|
+
const legacy = !('_reply' in data)
|
|
718
|
+
this.#handleRefresh(data['_refresh'], { reply: legacy || data['_reply'] === true, legacy })
|
|
653
719
|
} else if (data['_error']) {
|
|
654
720
|
this.#handleError(data['_error'])
|
|
655
721
|
} else if (data['_ack']) {
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
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()
|
|
659
733
|
}
|
|
660
734
|
}
|
|
661
735
|
|
|
@@ -728,9 +802,11 @@ class Subscription {
|
|
|
728
802
|
* @param {Object} [options]
|
|
729
803
|
* @param {boolean} [options.reply] - Whether the refresh answers this
|
|
730
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
|
|
731
807
|
* @private
|
|
732
808
|
*/
|
|
733
|
-
#handleRefresh(refresh, { reply = false } = {}) {
|
|
809
|
+
#handleRefresh(refresh, { reply = false, legacy = false } = {}) {
|
|
734
810
|
// If we're getting a refresh we must be connected
|
|
735
811
|
this.#handleStatus('subscribed')
|
|
736
812
|
|
|
@@ -739,10 +815,11 @@ class Subscription {
|
|
|
739
815
|
return
|
|
740
816
|
}
|
|
741
817
|
|
|
742
|
-
// A focused field whose form or trigger awaits a reply takes
|
|
743
|
-
//
|
|
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
|
|
744
820
|
const focused = document.activeElement
|
|
745
|
-
const
|
|
821
|
+
const awaiting = focused?.closest('[live-loading]:not([data-live-id-value])')
|
|
822
|
+
const sent = awaiting === focused ? this.#sentValues.get(focused.name) : undefined
|
|
746
823
|
|
|
747
824
|
// Restore live-loading / live-disable-with state before morphing so the
|
|
748
825
|
// morph applies the server-rendered truth on top of the original DOM.
|
|
@@ -783,23 +860,26 @@ class Subscription {
|
|
|
783
860
|
return false
|
|
784
861
|
}
|
|
785
862
|
|
|
786
|
-
// A nested component's
|
|
787
|
-
//
|
|
788
|
-
|
|
789
|
-
const owner = fromEl.closest('[data-live-id-value]')
|
|
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]')
|
|
790
866
|
|
|
791
|
-
|
|
792
|
-
|
|
867
|
+
if (owner && owner !== rootElement) {
|
|
868
|
+
const liveId = `${owner.getAttribute('data-live-component-value')}/${owner.getAttribute('data-live-id-value')}`
|
|
793
869
|
|
|
794
|
-
|
|
870
|
+
if (!legacy || !(liveId in childResults)) {
|
|
871
|
+
if (owner !== fromEl) {
|
|
795
872
|
return false
|
|
796
873
|
}
|
|
874
|
+
|
|
875
|
+
toEl.setAttribute('live-loading', '')
|
|
797
876
|
}
|
|
798
877
|
}
|
|
799
878
|
|
|
800
879
|
// defaultValue is what the server last rendered for the field
|
|
801
880
|
if (fromEl === focused) {
|
|
802
|
-
keepFocusedValue =
|
|
881
|
+
keepFocusedValue = isTypedField(fromEl) &&
|
|
882
|
+
(awaiting ? toEl.defaultValue === sent : fromEl.defaultValue === toEl.defaultValue)
|
|
803
883
|
}
|
|
804
884
|
|
|
805
885
|
return true
|
|
@@ -807,16 +887,13 @@ class Subscription {
|
|
|
807
887
|
// Skipping its children skips morphdom's value sync, so the focused
|
|
808
888
|
// field keeps what the user typed
|
|
809
889
|
onBeforeElChildrenUpdated(fromEl, toEl) {
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
// morphdom updates a textarea's text node, which an empty one lacks
|
|
890
|
+
// morphdom updates a textarea's text node, which an empty one lacks;
|
|
891
|
+
// once typed into, setting it leaves the value alone
|
|
815
892
|
if (fromEl instanceof HTMLTextAreaElement && fromEl.defaultValue !== toEl.defaultValue) {
|
|
816
893
|
fromEl.defaultValue = toEl.defaultValue
|
|
817
894
|
}
|
|
818
895
|
|
|
819
|
-
return
|
|
896
|
+
return !(keepFocusedValue && fromEl === focused)
|
|
820
897
|
},
|
|
821
898
|
// Use stable keys for better morphing performance and state preservation
|
|
822
899
|
getNodeKey(node) {
|