@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.
- package/CHANGELOG.md +739 -0
- package/README.md +101 -56
- package/app/assets/javascript/controllers/live_controller.js +61 -7
- package/app/assets/javascript/live_cable.js +2 -0
- package/app/assets/javascript/loading.js +61 -9
- package/app/assets/javascript/subscriptions.js +389 -42
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ it. Remove both at once, since either one on its own breaks every connection.
|
|
|
41
41
|
Together they keep working, but they make a per-socket object part of the
|
|
42
42
|
connection's identity, which stops `ActionCable.server.remote_connections` from
|
|
43
43
|
ever finding your users' sockets. See the
|
|
44
|
-
[architecture guide](https://livecable.io/guide/architecture#sign-in-
|
|
44
|
+
[architecture guide](https://livecable.io/guide/architecture#sign-in-sign-out-and-revocation)
|
|
45
45
|
for what to do about sockets when a user signs in or out.
|
|
46
46
|
|
|
47
47
|
## JavaScript Setup
|
|
@@ -127,7 +127,9 @@ LiveCable's subscription manager keeps subscriptions alive when a Stimulus contr
|
|
|
127
127
|
|
|
128
128
|
### Turbo Drive
|
|
129
129
|
|
|
130
|
-
The underlying WebSocket connection stays open across Turbo Drive page navigations. When navigating to a new page, LiveCable closes subscriptions for components that do not appear on the new page and removes their server-side instances. Components that appear on both pages — such as a persistent nav widget — keep their subscriptions and server-side state untouched.
|
|
130
|
+
The underlying WebSocket connection stays open across Turbo Drive page navigations. When navigating to a new page, LiveCable closes subscriptions for components that do not appear on the new page and removes their server-side instances. Components that appear on both pages — such as a persistent nav widget — keep their subscriptions and server-side state untouched, along with the components they render inline. If the new page renders such a component with different defaults, it is built again from those, and so are the components it renders inline.
|
|
131
|
+
|
|
132
|
+
If your sockets are authenticated, put `live_cable_identity_tag(current_user)` in your layout's `<head>`: when a sign-in, sign-out or impersonation changes who the page is for, the client reopens its socket so components act for the new session. See [Sign-in, Sign-out and Revocation](https://livecable.io/guide/architecture#sign-in-sign-out-and-revocation).
|
|
131
133
|
|
|
132
134
|
LiveCable automatically adds `<meta name="turbo-cache-control" content="no-cache">` to pages that contain live components, preventing Turbo from restoring a stale cached snapshot on back/forward navigation. If you need to override this — for example to set `no-store` — add your own `turbo-cache-control` meta tag and LiveCable will leave it alone.
|
|
133
135
|
|
|
@@ -145,8 +147,8 @@ Note on component location and namespacing:
|
|
|
145
147
|
|
|
146
148
|
- Live components must be defined inside the `Live::` module so they can be safely loaded from a string name.
|
|
147
149
|
- We recommend placing component classes under `app/live/` (so `Live::Counter` maps to `app/live/counter.rb`).
|
|
148
|
-
- Corresponding views should live under `app/views/live/...` (e.g. `app/views/live/counter
|
|
149
|
-
- When rendering a component from a view, pass the
|
|
150
|
+
- Corresponding views should live under `app/views/live/...` (e.g. `app/views/live/counter.html.live.erb`).
|
|
151
|
+
- When rendering a component from a view, pass the underscored name without the `Live` prefix, e.g. `'counter'` (which camelizes to `Live::Counter`) or `'chat/message'` (`Live::Chat::Message`).
|
|
150
152
|
|
|
151
153
|
LiveCable uses `ActiveModel::Callbacks` to provide lifecycle callbacks that you can hook into at different stages of a component's lifecycle.
|
|
152
154
|
|
|
@@ -156,7 +158,9 @@ LiveCable uses `ActiveModel::Callbacks` to provide lifecycle callbacks that you
|
|
|
156
158
|
|
|
157
159
|
- **`before_disconnect`** / **`after_disconnect`**: Called when the component is unsubscribed from the channel. Use `before_disconnect` for cleanup: stop timers, unsubscribe from external services, or save state before disconnection.
|
|
158
160
|
|
|
159
|
-
- **`before_render`** / **`after_render`**: Called before and after each render and broadcast, including the initial render. Use `before_render` for preparing data, performing calculations, or validating state. Use `after_render` for triggering side effects or cleanup
|
|
161
|
+
- **`before_render`** / **`after_render`**: Called before and after each render and broadcast, including the initial render and each time a parent renders the component as a child, but not during the HTTP prerender. Use `before_render` for preparing data, performing calculations, or validating state. Use `after_render` for triggering side effects or cleanup once the component has rendered.
|
|
162
|
+
|
|
163
|
+
- **`before_dispatch`**: Called before each action and `live-reactive` write the client sends, and nothing else. Use it to re-check authorization on every message; `throw :abort` skips the message. See [Authorizing Every Message](https://livecable.io/guide/architecture#authorizing-every-message).
|
|
160
164
|
|
|
161
165
|
### Registering Callbacks
|
|
162
166
|
|
|
@@ -222,6 +226,13 @@ On subsequent updates (action calls, reactive variable changes):
|
|
|
222
226
|
3. Component is rendered and broadcast
|
|
223
227
|
4. `after_render` callbacks are called
|
|
224
228
|
|
|
229
|
+
When a connected parent renders a child, as part of the parent's broadcast:
|
|
230
|
+
1. `before_render` callbacks are called on the child
|
|
231
|
+
2. The child is rendered into the parent's output
|
|
232
|
+
3. `after_render` callbacks are called on the child
|
|
233
|
+
|
|
234
|
+
The first time this happens the child hasn't connected yet, so these run before its connect callbacks, without `current_user` or other connection identifiers. See [When a Parent Renders a Child](https://livecable.io/guide/lifecycle-callbacks#when-a-parent-renders-a-child).
|
|
235
|
+
|
|
225
236
|
When a component is unsubscribed:
|
|
226
237
|
1. `before_disconnect` callbacks are called
|
|
227
238
|
2. Connection is cleaned up and streams are stopped
|
|
@@ -253,7 +264,7 @@ Supported reactive variable types: `integer`, `string`, `boolean`, `array`, `has
|
|
|
253
264
|
### 1. Create a Component
|
|
254
265
|
|
|
255
266
|
```ruby
|
|
256
|
-
# app/
|
|
267
|
+
# app/live/counter.rb
|
|
257
268
|
module Live
|
|
258
269
|
class Counter < LiveCable::Component
|
|
259
270
|
reactive :count, -> { 0 }
|
|
@@ -276,7 +287,7 @@ end
|
|
|
276
287
|
Component templates should start with a root element. LiveCable will automatically add the necessary attributes to wire up the component:
|
|
277
288
|
|
|
278
289
|
```erb
|
|
279
|
-
<%# app/views/live/counter
|
|
290
|
+
<%# app/views/live/counter.html.erb %>
|
|
280
291
|
<div>
|
|
281
292
|
<h2>Counter: <%= count %></h2>
|
|
282
293
|
<button live-action="increment">+</button>
|
|
@@ -288,10 +299,10 @@ LiveCable automatically injects the required attributes (`live-id`, `live-compon
|
|
|
288
299
|
|
|
289
300
|
#### Optimized Rendering with `.live.erb`
|
|
290
301
|
|
|
291
|
-
For better performance, you should use `.html.live.erb` templates instead of `.html.erb`. These templates use the Herb templating engine to parse your template and send only the updated parts over the wire, rather than the full HTML on every render:
|
|
302
|
+
For better performance, you should use `.html.live.erb` templates instead of `.html.erb`. These templates use the Herb templating engine to parse your template and send only the updated parts over the wire, rather than the full HTML on every render. The template stays the same; only its extension changes:
|
|
292
303
|
|
|
293
304
|
```erb
|
|
294
|
-
<%# app/views/live/counter
|
|
305
|
+
<%# app/views/live/counter.html.live.erb %>
|
|
295
306
|
<div>
|
|
296
307
|
<h2>Counter: <%= count %></h2>
|
|
297
308
|
<button live-action="increment">+</button>
|
|
@@ -369,6 +380,7 @@ When a reactive variable changes (e.g., `self.count = 5`), LiveCable:
|
|
|
369
380
|
4. **Makes the skip decision**:
|
|
370
381
|
- **Skip** if none of the part's dependencies changed
|
|
371
382
|
- **Render** if any component dependency, method dependency, or local dependency changed
|
|
383
|
+
- **Always render** a part that assigns a top-level local a later tag reads, even inside an `if`, so that tag gets the current value
|
|
372
384
|
- **Always render** on initial render (`:all`) or template switches (`:dynamic`)
|
|
373
385
|
|
|
374
386
|
5. **Returns selective updates**: Only the parts that need updating are rendered and sent to the client as an array:
|
|
@@ -408,7 +420,7 @@ The `Reset` button is never re-rendered since it contains no dynamic content.
|
|
|
408
420
|
Templates can define local variables that are used in later parts:
|
|
409
421
|
|
|
410
422
|
```erb
|
|
411
|
-
<% user = component.
|
|
423
|
+
<% user = component.owner %>
|
|
412
424
|
<% total = component.calculate_total %>
|
|
413
425
|
|
|
414
426
|
<div>Welcome <%= user.name %></div>
|
|
@@ -416,11 +428,10 @@ Templates can define local variables that are used in later parts:
|
|
|
416
428
|
```
|
|
417
429
|
|
|
418
430
|
LiveCable tracks:
|
|
419
|
-
-
|
|
420
|
-
-
|
|
421
|
-
- Third part depends on `total` local (re-renders only if `total` local was redefined)
|
|
431
|
+
- The `<% %>` tags that assign `user` and `total` always run, so the locals are always current
|
|
432
|
+
- The `<div>`s that read `user` and `total` depend on those locals, so they re-render whenever the component renders
|
|
422
433
|
|
|
423
|
-
|
|
434
|
+
For anything costly, prefer a component method: methods are tracked by the reactive variables they read. A local assigned inside a block exists only inside it, as in Ruby.
|
|
424
435
|
|
|
425
436
|
**Performance Benefits:**
|
|
426
437
|
|
|
@@ -448,14 +459,15 @@ The `live` helper automatically:
|
|
|
448
459
|
- Creates component instances with unique IDs
|
|
449
460
|
- Wraps the component in proper Stimulus controller attributes
|
|
450
461
|
- Passes default values to reactive variables
|
|
451
|
-
- Reuses
|
|
462
|
+
- Reuses a child's instance across its parent's renders
|
|
463
|
+
|
|
464
|
+
A top-level component's defaults are signed into the page as JSON and sent back when it connects. Pass JSON-native values such as an id: a Symbol or a nested hash key arrives as a String, and a record or any other object that isn't JSON-native raises an `ArgumentError`. They're signed, not encrypted, so anyone viewing the page can read them; never pass a secret. See [Writable Variables and Defaults](https://livecable.io/guide/architecture#writable-variables-and-defaults).
|
|
452
465
|
|
|
453
466
|
If you already have a component instance, use `render` directly:
|
|
454
467
|
|
|
455
468
|
```erb
|
|
456
469
|
<%
|
|
457
|
-
@counter = Live::Counter.new('my-counter')
|
|
458
|
-
@counter.count = 10
|
|
470
|
+
@counter = Live::Counter.new('my-counter', count: 10)
|
|
459
471
|
%>
|
|
460
472
|
<%= render(@counter) %>
|
|
461
473
|
```
|
|
@@ -512,7 +524,7 @@ module Live
|
|
|
512
524
|
class TaskManager < LiveCable::Component
|
|
513
525
|
reactive :tasks, -> { [] }
|
|
514
526
|
reactive :settings, -> { {} }
|
|
515
|
-
reactive :project, -> { Project.find_by(id:
|
|
527
|
+
reactive :project, ->(c) { Project.find_by(id: c.defaults[:project_id]) }
|
|
516
528
|
|
|
517
529
|
actions :add_task, :update_setting, :update_project_name
|
|
518
530
|
|
|
@@ -534,6 +546,8 @@ module Live
|
|
|
534
546
|
end
|
|
535
547
|
```
|
|
536
548
|
|
|
549
|
+
In component code these values are change-tracking wrappers once the component is connected, and plain values during the HTTP prerender. `case`, `is_a?(Hash)`, `where(hash)`, bind values in a string condition (`where('id IN (?)', ids)`) and assigning a model to an association need the plain value, so pass `tasks.to_a`, `settings.to_h` or `LiveCable::Delegator.unwrap(project)`, which work in both cases. Templates get the plain value already (`component.tasks` still returns the wrapper). Passing a reactive value, an element of one, or a collection built from one to a child with `live(...)` keeps its change tracking, so the child's changes re-render the parent too.
|
|
550
|
+
|
|
537
551
|
### Nested Structures
|
|
538
552
|
|
|
539
553
|
Change tracking works recursively through nested structures:
|
|
@@ -589,7 +603,7 @@ self.count.+(1)
|
|
|
589
603
|
self.name.concat("Doe")
|
|
590
604
|
```
|
|
591
605
|
|
|
592
|
-
For more details on the change tracking architecture, see [
|
|
606
|
+
For more details on the change tracking architecture, see the [architecture guide](https://livecable.io/guide/architecture).
|
|
593
607
|
|
|
594
608
|
## Shared Variables
|
|
595
609
|
|
|
@@ -649,7 +663,7 @@ module Live
|
|
|
649
663
|
end
|
|
650
664
|
```
|
|
651
665
|
|
|
652
|
-
**Use case**: FilterPanel can read the cart to show item count in a badge, but doesn't need to re-render every time an item is added—only when the filter changes.
|
|
666
|
+
**Use case**: FilterPanel can read the cart to show item count in a badge, but doesn't need to re-render every time an item is added—only when the filter changes. Whenever FilterPanel re-renders for its own reasons, parts that read `cart_items` (directly or through a method) re-render too, so the badge picks up the latest count.
|
|
653
667
|
|
|
654
668
|
## Action Whitelisting
|
|
655
669
|
|
|
@@ -722,6 +736,8 @@ reactive :filter, -> { "all" }, writable: true # Writable local
|
|
|
722
736
|
reactive :search, -> { "" }, shared: true, writable: true # Writable shared variable
|
|
723
737
|
```
|
|
724
738
|
|
|
739
|
+
A shared variable is writable from the client only if every component class that shares the name declares it `writable: true`, since the client chooses which components it subscribes to.
|
|
740
|
+
|
|
725
741
|
### Working with ActionController::Parameters
|
|
726
742
|
|
|
727
743
|
The `params` argument is an `ActionController::Parameters` instance, which means you can use strong parameters and all the standard Rails parameter handling methods:
|
|
@@ -836,7 +852,7 @@ Serializes a form and submits it to a component action.
|
|
|
836
852
|
```html
|
|
837
853
|
<!-- Default event (submit) -->
|
|
838
854
|
<form live-form="save">
|
|
839
|
-
<input type="text" name="title">
|
|
855
|
+
<input type="text" name="title" value="<%= title %>">
|
|
840
856
|
<button type="submit">Save</button>
|
|
841
857
|
</form>
|
|
842
858
|
|
|
@@ -847,7 +863,7 @@ Serializes a form and submits it to a component action.
|
|
|
847
863
|
|
|
848
864
|
<!-- Multiple actions -->
|
|
849
865
|
<form live-form="submit->save change->auto_save">
|
|
850
|
-
<input type="text" name="content">
|
|
866
|
+
<input type="text" name="content" value="<%= content %>">
|
|
851
867
|
</form>
|
|
852
868
|
```
|
|
853
869
|
|
|
@@ -897,6 +913,18 @@ Updates a reactive variable when an input changes. The corresponding reactive va
|
|
|
897
913
|
<input type="text" name="query" live-reactive="keydown keyup">
|
|
898
914
|
```
|
|
899
915
|
|
|
916
|
+
The value sent depends on the input: a checkbox sends `true` or `false` (whether it is checked, regardless of its `value` attribute), a `<select multiple>` sends an Array of the selected option values, and everything else, radio buttons included, sends its `value` as a String.
|
|
917
|
+
|
|
918
|
+
```html
|
|
919
|
+
<input type="checkbox" name="notify" live-reactive <%= 'checked' if notify %>>
|
|
920
|
+
|
|
921
|
+
<select multiple name="tags" live-reactive="change">
|
|
922
|
+
<% %w[ruby rails].each do |tag| %>
|
|
923
|
+
<option value="<%= tag %>" <%= 'selected' if tags.include?(tag) %>><%= tag %></option>
|
|
924
|
+
<% end %>
|
|
925
|
+
</select>
|
|
926
|
+
```
|
|
927
|
+
|
|
900
928
|
**Transformation:** `live-reactive` becomes `data-action="live#reactive"`, and `live-reactive="keydown"` becomes `data-action="keydown->live#reactive"`
|
|
901
929
|
|
|
902
930
|
### `live-debounce`
|
|
@@ -935,8 +963,8 @@ Adds debouncing to reactive and form updates to reduce network traffic.
|
|
|
935
963
|
<!-- Form with multiple actions and parameters -->
|
|
936
964
|
<form live-form="submit->filter change->auto_filter" live-debounce="500">
|
|
937
965
|
<select name="category">
|
|
938
|
-
<option value="all"
|
|
939
|
-
<option value="electronics"
|
|
966
|
+
<option value="all" <%= 'selected' if category == 'all' %>>All</option>
|
|
967
|
+
<option value="electronics" <%= 'selected' if category == 'electronics' %>>Electronics</option>
|
|
940
968
|
</select>
|
|
941
969
|
</form>
|
|
942
970
|
|
|
@@ -975,7 +1003,6 @@ When `live-ignore` is present on an element, LiveCable (via morphdom) will skip
|
|
|
975
1003
|
|
|
976
1004
|
- **Usage**: `<div live-ignore>...</div>`
|
|
977
1005
|
- **Behavior**: Prevents the element's content from being modified by server updates.
|
|
978
|
-
- **Default**: Live components automatically have this attribute to ensure the parent component doesn't overwrite the child component's state.
|
|
979
1006
|
|
|
980
1007
|
### `live-key`
|
|
981
1008
|
|
|
@@ -1022,7 +1049,7 @@ To prevent double-clicks, mark buttons with `live-disable-with`. The element is
|
|
|
1022
1049
|
|
|
1023
1050
|
For forms, put `live-disable-with` on the submit button(s); form values are serialized before anything is disabled. Reactive inputs (`live-reactive`) get the `live-loading` attribute but are never disabled, so typing is not interrupted.
|
|
1024
1051
|
|
|
1025
|
-
The loading state is cleared when the server
|
|
1052
|
+
The loading state is cleared when the server answers the message — with the component's own re-render, an error, or a lightweight acknowledgement when no re-render of its own is sent. A render it didn't ask for, such as one pushed by `stream_from`, leaves it on. A message sent while the socket is down is held and sent once it reconnects, and the component's root reads `data-live-status-value="disconnected"` meanwhile. If no reply comes within 30 seconds, the loading state gives up, the status becomes `stalled`, and a `live:stalled` event is dispatched. See [Loading States](https://livecable.io/guide/loading-states).
|
|
1026
1053
|
|
|
1027
1054
|
## Server Events
|
|
1028
1055
|
|
|
@@ -1078,7 +1105,7 @@ module Live
|
|
|
1078
1105
|
end
|
|
1079
1106
|
|
|
1080
1107
|
def next_step(params)
|
|
1081
|
-
form_data.merge!(params)
|
|
1108
|
+
form_data.merge!(params.permit(:email, :name, :card_number).to_h)
|
|
1082
1109
|
self.current_step = case current_step
|
|
1083
1110
|
when "account" then "billing"
|
|
1084
1111
|
when "billing" then "confirmation"
|
|
@@ -1153,42 +1180,46 @@ end
|
|
|
1153
1180
|
`.live.erb` templates automatically forward method calls to your component through `method_missing`, so you can call component methods and reactive variables directly:
|
|
1154
1181
|
|
|
1155
1182
|
```erb
|
|
1156
|
-
<%# app/views/live/product_list
|
|
1157
|
-
<div
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
<
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1183
|
+
<%# app/views/live/product_list.html.live.erb %>
|
|
1184
|
+
<div>
|
|
1185
|
+
<div class="products">
|
|
1186
|
+
<% products.each do |product| %>
|
|
1187
|
+
<div class="product">
|
|
1188
|
+
<h3><%= product.name %></h3>
|
|
1189
|
+
<p><%= product.price %></p>
|
|
1190
|
+
</div>
|
|
1191
|
+
<% end %>
|
|
1192
|
+
</div>
|
|
1165
1193
|
|
|
1166
|
-
<div class="pagination">
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1194
|
+
<div class="pagination">
|
|
1195
|
+
<button live-action="prev_page">Previous</button>
|
|
1196
|
+
<span>Page <%= page + 1 %></span>
|
|
1197
|
+
<button live-action="next_page">Next</button>
|
|
1198
|
+
</div>
|
|
1170
1199
|
</div>
|
|
1171
1200
|
```
|
|
1172
1201
|
|
|
1173
1202
|
### In Regular `.erb` or Other Templating Languages
|
|
1174
1203
|
|
|
1175
|
-
If you're using regular `.erb` files or other templating languages, you must use the `component` local to
|
|
1204
|
+
If you're using regular `.erb` files or other templating languages, you must use the `component` local to call component methods. Reactive variables are locals in every template and hold the plain value, while `component.items` returns the change-tracking wrapper:
|
|
1176
1205
|
|
|
1177
1206
|
```erb
|
|
1178
|
-
<%# app/views/live/product_list
|
|
1179
|
-
<div
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
<
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1207
|
+
<%# app/views/live/product_list.html.erb %>
|
|
1208
|
+
<div>
|
|
1209
|
+
<div class="products">
|
|
1210
|
+
<% component.products.each do |product| %>
|
|
1211
|
+
<div class="product">
|
|
1212
|
+
<h3><%= product.name %></h3>
|
|
1213
|
+
<p><%= product.price %></p>
|
|
1214
|
+
</div>
|
|
1215
|
+
<% end %>
|
|
1216
|
+
</div>
|
|
1187
1217
|
|
|
1188
|
-
<div class="pagination">
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1218
|
+
<div class="pagination">
|
|
1219
|
+
<button live-action="prev_page">Previous</button>
|
|
1220
|
+
<span>Page <%= page + 1 %></span>
|
|
1221
|
+
<button live-action="next_page">Next</button>
|
|
1222
|
+
</div>
|
|
1192
1223
|
</div>
|
|
1193
1224
|
```
|
|
1194
1225
|
|
|
@@ -1210,7 +1241,7 @@ Call `stream_from` in the `after_connect` lifecycle callback to subscribe to a c
|
|
|
1210
1241
|
module Live
|
|
1211
1242
|
module Chat
|
|
1212
1243
|
class ChatRoom < LiveCable::Component
|
|
1213
|
-
reactive :messages, -> { [] }
|
|
1244
|
+
reactive :messages, -> { [] }
|
|
1214
1245
|
|
|
1215
1246
|
after_connect :subscribe_to_chat
|
|
1216
1247
|
|
|
@@ -1226,6 +1257,8 @@ module Live
|
|
|
1226
1257
|
end
|
|
1227
1258
|
```
|
|
1228
1259
|
|
|
1260
|
+
Streams stop when the component disconnects. To stop one sooner, as when a chat switches rooms, call `stop_stream_from` with its name, or `stop_stream` to stop them all.
|
|
1261
|
+
|
|
1229
1262
|
### Broadcasting to Streams
|
|
1230
1263
|
|
|
1231
1264
|
Any part of your application can broadcast to the stream using ActionCable's broadcast API:
|
|
@@ -1305,7 +1338,19 @@ The harness supports client reactive updates (`set_reactive`), broadcast asserti
|
|
|
1305
1338
|
|
|
1306
1339
|
## Error Handling
|
|
1307
1340
|
|
|
1308
|
-
When an unhandled exception is raised
|
|
1341
|
+
When an unhandled exception is raised by a component action, a `live-reactive` write, a `before_dispatch` or `stream_from` callback, or while the component subscribes or renders, LiveCable replaces the component in the DOM with an error message and cleans up the server-side component. An error while a parent renders a child, including one from the child's initial values or render callbacks, replaces the parent.
|
|
1342
|
+
|
|
1343
|
+
### Handling Errors with `rescue_from`
|
|
1344
|
+
|
|
1345
|
+
Components include `ActiveSupport::Rescuable`, so they can handle an error themselves. The message is still answered, and anything the handler changes is re-rendered:
|
|
1346
|
+
|
|
1347
|
+
```ruby
|
|
1348
|
+
rescue_from ActiveRecord::RecordNotFound do
|
|
1349
|
+
self.notice = 'That record is gone.'
|
|
1350
|
+
end
|
|
1351
|
+
```
|
|
1352
|
+
|
|
1353
|
+
See [Error Handling](https://livecable.io/guide/error-handling).
|
|
1309
1354
|
|
|
1310
1355
|
### Default Behaviour
|
|
1311
1356
|
|
|
@@ -4,7 +4,9 @@ import LoadingState from "@isometriks/live_cable/loading"
|
|
|
4
4
|
|
|
5
5
|
export default class extends Controller {
|
|
6
6
|
static values = {
|
|
7
|
-
|
|
7
|
+
// Opaque signed blob produced by the server; forwarded verbatim to the
|
|
8
|
+
// channel on subscribe, where it is verified and decoded.
|
|
9
|
+
defaults: String,
|
|
8
10
|
status: String,
|
|
9
11
|
component: String,
|
|
10
12
|
actions: Array,
|
|
@@ -14,6 +16,7 @@ export default class extends Controller {
|
|
|
14
16
|
#subscription
|
|
15
17
|
#debounces = new Map()
|
|
16
18
|
#loading
|
|
19
|
+
#wasLoading = false
|
|
17
20
|
|
|
18
21
|
#callActionCallback = (event) => {
|
|
19
22
|
event.stopPropagation()
|
|
@@ -24,7 +27,7 @@ export default class extends Controller {
|
|
|
24
27
|
}
|
|
25
28
|
|
|
26
29
|
connect() {
|
|
27
|
-
this.#loading = new LoadingState(this.element)
|
|
30
|
+
this.#loading = new LoadingState(this.element, { onStalled: () => this.#stalled() })
|
|
28
31
|
this.element.addEventListener("call", this.#callActionCallback)
|
|
29
32
|
|
|
30
33
|
this.#subscription = SubscriptionManager.subscribe(
|
|
@@ -34,6 +37,12 @@ export default class extends Controller {
|
|
|
34
37
|
this
|
|
35
38
|
)
|
|
36
39
|
|
|
40
|
+
// The subscription outlives a controller, so messages held from before a
|
|
41
|
+
// disconnect need this controller's watchdog
|
|
42
|
+
for (let i = this.#subscription.pendingCount; i > 0; i--) {
|
|
43
|
+
this.#loading.start()
|
|
44
|
+
}
|
|
45
|
+
|
|
37
46
|
// Create callbacks for each action or form
|
|
38
47
|
this.actionsValue.forEach((action) => {
|
|
39
48
|
this[`action_$${action}`] = ({ params, currentTarget }) => {
|
|
@@ -44,10 +53,21 @@ export default class extends Controller {
|
|
|
44
53
|
this.#form(action, event)
|
|
45
54
|
}
|
|
46
55
|
})
|
|
56
|
+
|
|
57
|
+
// Reconnected after a morph moved the element: the reset in disconnect
|
|
58
|
+
// left its pending elements without the renders they skipped
|
|
59
|
+
if (this.#wasLoading) {
|
|
60
|
+
this.#wasLoading = false
|
|
61
|
+
this.#subscription.catchUp()
|
|
62
|
+
}
|
|
47
63
|
}
|
|
48
64
|
|
|
49
65
|
disconnect() {
|
|
50
66
|
this.element.removeEventListener("call", this.#callActionCallback)
|
|
67
|
+
// A new controller brings its own loading state; don't leave this one's
|
|
68
|
+
// watchdog to fire on an element that has gone
|
|
69
|
+
this.#wasLoading = this.#loading?.active ?? false
|
|
70
|
+
this.#loading?.reset()
|
|
51
71
|
}
|
|
52
72
|
|
|
53
73
|
sendCall(action, params = {}, trigger = null) {
|
|
@@ -57,11 +77,12 @@ export default class extends Controller {
|
|
|
57
77
|
)
|
|
58
78
|
}
|
|
59
79
|
|
|
60
|
-
// Called by the subscription when the server answers a message
|
|
61
|
-
//
|
|
62
|
-
// state once all in-flight messages have been answered
|
|
80
|
+
// Called by the subscription when the server answers a message (its
|
|
81
|
+
// reply, an ack, or an error). Restores any live-loading / live-disable-with
|
|
82
|
+
// state once all in-flight messages have been answered, and returns true
|
|
83
|
+
// when it did.
|
|
63
84
|
finishLoading() {
|
|
64
|
-
this.#loading?.finish()
|
|
85
|
+
return this.#loading?.finish() ?? false
|
|
65
86
|
}
|
|
66
87
|
|
|
67
88
|
// Whether any message is still awaiting a server response
|
|
@@ -69,11 +90,32 @@ export default class extends Controller {
|
|
|
69
90
|
return this.#loading?.active ?? false
|
|
70
91
|
}
|
|
71
92
|
|
|
93
|
+
// How many messages are still awaiting a server response
|
|
94
|
+
get inFlight() {
|
|
95
|
+
return this.#loading?.inFlight ?? 0
|
|
96
|
+
}
|
|
97
|
+
|
|
72
98
|
// Called by the subscription when the component is being torn down.
|
|
73
99
|
resetLoading() {
|
|
74
100
|
this.#loading?.reset()
|
|
75
101
|
}
|
|
76
102
|
|
|
103
|
+
// The loading state gave up waiting for a reply. Anything still held for a
|
|
104
|
+
// reconnect is dropped with it, so a message the page has said didn't go
|
|
105
|
+
// through can't go through later - the user would click again, and it
|
|
106
|
+
// would run twice. A message already sent can't be recalled; the event
|
|
107
|
+
// says how many were dropped so the page can word its message.
|
|
108
|
+
#stalled() {
|
|
109
|
+
const discarded = this.#subscription?.discardPending() ?? 0
|
|
110
|
+
|
|
111
|
+
this.#subscription?.catchUp()
|
|
112
|
+
this.statusValue = 'stalled'
|
|
113
|
+
this.element.dispatchEvent(new CustomEvent('live:stalled', {
|
|
114
|
+
bubbles: true,
|
|
115
|
+
detail: { discarded },
|
|
116
|
+
}))
|
|
117
|
+
}
|
|
118
|
+
|
|
77
119
|
#callMessage(params, action) {
|
|
78
120
|
return {
|
|
79
121
|
_action: action,
|
|
@@ -115,8 +157,20 @@ export default class extends Controller {
|
|
|
115
157
|
return {
|
|
116
158
|
_action: '_reactive',
|
|
117
159
|
name: target.name,
|
|
118
|
-
value: target
|
|
160
|
+
value: this.#reactiveValue(target),
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
#reactiveValue(target) {
|
|
165
|
+
if (target.type === 'checkbox') {
|
|
166
|
+
return target.checked
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (target.type === 'select-multiple') {
|
|
170
|
+
return Array.from(target.selectedOptions, (option) => option.value)
|
|
119
171
|
}
|
|
172
|
+
|
|
173
|
+
return target.value
|
|
120
174
|
}
|
|
121
175
|
|
|
122
176
|
#form(action, { currentTarget, params }) {
|
|
@@ -4,8 +4,10 @@ import DOM from '@isometriks/live_cable/dom'
|
|
|
4
4
|
|
|
5
5
|
const observer = new LiveObserver()
|
|
6
6
|
observer.start()
|
|
7
|
+
SubscriptionManager.syncIdentity()
|
|
7
8
|
|
|
8
9
|
document.addEventListener('turbo:before-render', (event) => {
|
|
10
|
+
SubscriptionManager.syncIdentity()
|
|
9
11
|
SubscriptionManager.prune(event.detail.newBody)
|
|
10
12
|
})
|
|
11
13
|
|
|
@@ -10,14 +10,28 @@
|
|
|
10
10
|
* a `live-loading` attribute.
|
|
11
11
|
* - Elements with a `live-disable-with` attribute are disabled while the
|
|
12
12
|
* message is in flight. If the attribute has a value, the element's label
|
|
13
|
-
* (
|
|
13
|
+
* (its contents, or value for inputs) is swapped for it.
|
|
14
14
|
*
|
|
15
|
-
* The state is cleared when the server
|
|
16
|
-
* or an ack (sent when
|
|
17
|
-
* Multiple in-flight messages are counted; the DOM is
|
|
18
|
-
* all of them have been answered.
|
|
15
|
+
* The state is cleared when the server replies with the component's own
|
|
16
|
+
* re-render, an error, or an ack (sent when the action didn't re-render the
|
|
17
|
+
* component by itself). Multiple in-flight messages are counted; the DOM is
|
|
18
|
+
* only restored once all of them have been answered.
|
|
19
|
+
*
|
|
20
|
+
* If no reply comes for `LoadingState.timeout` milliseconds while a message
|
|
21
|
+
* is in flight, the state gives up: it resets and calls `onStalled`. That is
|
|
22
|
+
* the backstop for a reply that is never coming - the server stopped while
|
|
23
|
+
* running the message, say - which would otherwise leave a button disabled
|
|
24
|
+
* until the page is reloaded.
|
|
19
25
|
*/
|
|
20
26
|
export default class LoadingState {
|
|
27
|
+
/**
|
|
28
|
+
* Milliseconds to wait for any reply before giving up. Long enough to
|
|
29
|
+
* cover a reconnect after a deploy, since messages held for one count too.
|
|
30
|
+
* Set it before components connect to change it everywhere.
|
|
31
|
+
* @type {number}
|
|
32
|
+
*/
|
|
33
|
+
static timeout = 30_000
|
|
34
|
+
|
|
21
35
|
/** @type {HTMLElement} */
|
|
22
36
|
#root
|
|
23
37
|
/** @type {number} */
|
|
@@ -26,12 +40,20 @@ export default class LoadingState {
|
|
|
26
40
|
#markedElements = new Set()
|
|
27
41
|
/** @type {Map<Element, Object>} - Original state of disabled elements */
|
|
28
42
|
#disabledElements = new Map()
|
|
43
|
+
/** @type {Function|null} */
|
|
44
|
+
#onStalled
|
|
45
|
+
/** @type {number|null} */
|
|
46
|
+
#timer = null
|
|
29
47
|
|
|
30
48
|
/**
|
|
31
49
|
* @param {HTMLElement} root - The component's root element
|
|
50
|
+
* @param {Object} options
|
|
51
|
+
* @param {Function} [options.onStalled] - Called after the state gives up
|
|
52
|
+
* waiting and resets itself
|
|
32
53
|
*/
|
|
33
|
-
constructor(root) {
|
|
54
|
+
constructor(root, { onStalled = null } = {}) {
|
|
34
55
|
this.#root = root
|
|
56
|
+
this.#onStalled = onStalled
|
|
35
57
|
}
|
|
36
58
|
|
|
37
59
|
/**
|
|
@@ -42,6 +64,14 @@ export default class LoadingState {
|
|
|
42
64
|
return this.#inFlight > 0
|
|
43
65
|
}
|
|
44
66
|
|
|
67
|
+
/**
|
|
68
|
+
* How many messages are awaiting a server response.
|
|
69
|
+
* @returns {number}
|
|
70
|
+
*/
|
|
71
|
+
get inFlight() {
|
|
72
|
+
return this.#inFlight
|
|
73
|
+
}
|
|
74
|
+
|
|
45
75
|
/**
|
|
46
76
|
* Mark the component as loading.
|
|
47
77
|
* Called right before a message is sent to the server.
|
|
@@ -52,7 +82,9 @@ export default class LoadingState {
|
|
|
52
82
|
* elements. Disabled for reactive inputs so typing doesn't lose focus.
|
|
53
83
|
*/
|
|
54
84
|
start(trigger = null, { disable = true } = {}) {
|
|
55
|
-
this.#inFlight++
|
|
85
|
+
if (this.#inFlight++ === 0) {
|
|
86
|
+
this.#arm()
|
|
87
|
+
}
|
|
56
88
|
|
|
57
89
|
this.#mark(this.#root)
|
|
58
90
|
|
|
@@ -79,9 +111,12 @@ export default class LoadingState {
|
|
|
79
111
|
this.#inFlight--
|
|
80
112
|
|
|
81
113
|
if (this.#inFlight > 0) {
|
|
114
|
+
// Still waiting on others, but the server is evidently answering
|
|
115
|
+
this.#arm()
|
|
82
116
|
return false
|
|
83
117
|
}
|
|
84
118
|
|
|
119
|
+
this.#disarm()
|
|
85
120
|
this.#restore()
|
|
86
121
|
return true
|
|
87
122
|
}
|
|
@@ -92,9 +127,26 @@ export default class LoadingState {
|
|
|
92
127
|
*/
|
|
93
128
|
reset() {
|
|
94
129
|
this.#inFlight = 0
|
|
130
|
+
this.#disarm()
|
|
95
131
|
this.#restore()
|
|
96
132
|
}
|
|
97
133
|
|
|
134
|
+
#arm() {
|
|
135
|
+
this.#disarm()
|
|
136
|
+
this.#timer = setTimeout(() => this.#stall(), LoadingState.timeout)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
#disarm() {
|
|
140
|
+
clearTimeout(this.#timer)
|
|
141
|
+
this.#timer = null
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
#stall() {
|
|
145
|
+
this.#timer = null
|
|
146
|
+
this.reset()
|
|
147
|
+
this.#onStalled?.()
|
|
148
|
+
}
|
|
149
|
+
|
|
98
150
|
#mark(element) {
|
|
99
151
|
element.setAttribute('live-loading', '')
|
|
100
152
|
this.#markedElements.add(element)
|
|
@@ -125,7 +177,7 @@ export default class LoadingState {
|
|
|
125
177
|
|
|
126
178
|
this.#disabledElements.set(element, {
|
|
127
179
|
disabled: element.disabled,
|
|
128
|
-
content: text ? (isInput ? element.value : element.
|
|
180
|
+
content: text ? (isInput ? element.value : element.innerHTML) : null,
|
|
129
181
|
})
|
|
130
182
|
|
|
131
183
|
element.disabled = true
|
|
@@ -153,7 +205,7 @@ export default class LoadingState {
|
|
|
153
205
|
if (element instanceof HTMLInputElement) {
|
|
154
206
|
element.value = content
|
|
155
207
|
} else {
|
|
156
|
-
element.
|
|
208
|
+
element.innerHTML = content
|
|
157
209
|
}
|
|
158
210
|
}
|
|
159
211
|
})
|