@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/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-and-sign-out)
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/component.html.live.erb`).
149
- - When rendering a component from a view, pass the namespaced underscored path, e.g. `live/counter` (which camelizes to `Live::Counter`).
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 after the DOM has been updated.
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/components/live/counter.rb
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/component.html.live.erb %>
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/component.html.live.erb %>
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.current_user %>
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
- - First part defines `user` and `total` (always executes to define locals)
420
- - Second part depends on `user` local (re-renders only if `user` local was redefined)
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
- The `mark_locals_dirty` mechanism ensures that if a local is recomputed (because its dependencies changed), any parts using that local are also re-rendered.
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 existing component instances when navigating back
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: params[:project_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:
@@ -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
 
@@ -947,8 +963,8 @@ Adds debouncing to reactive and form updates to reduce network traffic.
947
963
  <!-- Form with multiple actions and parameters -->
948
964
  <form live-form="submit->filter change->auto_filter" live-debounce="500">
949
965
  <select name="category">
950
- <option value="all">All</option>
951
- <option value="electronics">Electronics</option>
966
+ <option value="all" <%= 'selected' if category == 'all' %>>All</option>
967
+ <option value="electronics" <%= 'selected' if category == 'electronics' %>>Electronics</option>
952
968
  </select>
953
969
  </form>
954
970
 
@@ -987,7 +1003,6 @@ When `live-ignore` is present on an element, LiveCable (via morphdom) will skip
987
1003
 
988
1004
  - **Usage**: `<div live-ignore>...</div>`
989
1005
  - **Behavior**: Prevents the element's content from being modified by server updates.
990
- - **Default**: Live components automatically have this attribute to ensure the parent component doesn't overwrite the child component's state.
991
1006
 
992
1007
  ### `live-key`
993
1008
 
@@ -1034,7 +1049,7 @@ To prevent double-clicks, mark buttons with `live-disable-with`. The element is
1034
1049
 
1035
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.
1036
1051
 
1037
- The loading state is cleared when the server responds — with a re-render, an error, or a lightweight acknowledgement when the action didn't change any state — so it never gets stuck.
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).
1038
1053
 
1039
1054
  ## Server Events
1040
1055
 
@@ -1090,7 +1105,7 @@ module Live
1090
1105
  end
1091
1106
 
1092
1107
  def next_step(params)
1093
- form_data.merge!(params)
1108
+ form_data.merge!(params.permit(:email, :name, :card_number).to_h)
1094
1109
  self.current_step = case current_step
1095
1110
  when "account" then "billing"
1096
1111
  when "billing" then "confirmation"
@@ -1165,42 +1180,46 @@ end
1165
1180
  `.live.erb` templates automatically forward method calls to your component through `method_missing`, so you can call component methods and reactive variables directly:
1166
1181
 
1167
1182
  ```erb
1168
- <%# app/views/live/product_list/component.html.live.erb %>
1169
- <div class="products">
1170
- <% products.each do |product| %>
1171
- <div class="product">
1172
- <h3><%= product.name %></h3>
1173
- <p><%= product.price %></p>
1174
- </div>
1175
- <% end %>
1176
- </div>
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>
1177
1193
 
1178
- <div class="pagination">
1179
- <button live-action="prev_page">Previous</button>
1180
- <span>Page <%= page + 1 %></span>
1181
- <button live-action="next_page">Next</button>
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>
1182
1199
  </div>
1183
1200
  ```
1184
1201
 
1185
1202
  ### In Regular `.erb` or Other Templating Languages
1186
1203
 
1187
- If you're using regular `.erb` files or other templating languages, you must use the `component` local to access component methods and reactive variables:
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:
1188
1205
 
1189
1206
  ```erb
1190
- <%# app/views/live/product_list/component.html.erb %>
1191
- <div class="products">
1192
- <% component.products.each do |product| %>
1193
- <div class="product">
1194
- <h3><%= product.name %></h3>
1195
- <p><%= product.price %></p>
1196
- </div>
1197
- <% end %>
1198
- </div>
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>
1199
1217
 
1200
- <div class="pagination">
1201
- <button live-action="prev_page">Previous</button>
1202
- <span>Page <%= component.page + 1 %></span>
1203
- <button live-action="next_page">Next</button>
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>
1204
1223
  </div>
1205
1224
  ```
1206
1225
 
@@ -1222,7 +1241,7 @@ Call `stream_from` in the `after_connect` lifecycle callback to subscribe to a c
1222
1241
  module Live
1223
1242
  module Chat
1224
1243
  class ChatRoom < LiveCable::Component
1225
- reactive :messages, -> { [] }, shared: true
1244
+ reactive :messages, -> { [] }
1226
1245
 
1227
1246
  after_connect :subscribe_to_chat
1228
1247
 
@@ -1238,6 +1257,8 @@ module Live
1238
1257
  end
1239
1258
  ```
1240
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
+
1241
1262
  ### Broadcasting to Streams
1242
1263
 
1243
1264
  Any part of your application can broadcast to the stream using ActionCable's broadcast API:
@@ -1317,7 +1338,19 @@ The harness supports client reactive updates (`set_reactive`), broadcast asserti
1317
1338
 
1318
1339
  ## Error Handling
1319
1340
 
1320
- When an unhandled exception is raised inside a component action, LiveCable replaces the component in the DOM with an error message and cleans up the server-side component.
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).
1321
1354
 
1322
1355
  ### Default Behaviour
1323
1356
 
@@ -16,6 +16,7 @@ export default class extends Controller {
16
16
  #subscription
17
17
  #debounces = new Map()
18
18
  #loading
19
+ #wasLoading = false
19
20
 
20
21
  #callActionCallback = (event) => {
21
22
  event.stopPropagation()
@@ -52,12 +53,20 @@ export default class extends Controller {
52
53
  this.#form(action, event)
53
54
  }
54
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
+ }
55
63
  }
56
64
 
57
65
  disconnect() {
58
66
  this.element.removeEventListener("call", this.#callActionCallback)
59
67
  // A new controller brings its own loading state; don't leave this one's
60
68
  // watchdog to fire on an element that has gone
69
+ this.#wasLoading = this.#loading?.active ?? false
61
70
  this.#loading?.reset()
62
71
  }
63
72
 
@@ -99,6 +108,7 @@ export default class extends Controller {
99
108
  #stalled() {
100
109
  const discarded = this.#subscription?.discardPending() ?? 0
101
110
 
111
+ this.#subscription?.catchUp()
102
112
  this.statusValue = 'stalled'
103
113
  this.element.dispatchEvent(new CustomEvent('live:stalled', {
104
114
  bubbles: true,
@@ -10,7 +10,7 @@
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
- * (textContent, or value for inputs) is swapped for it.
13
+ * (its contents, or value for inputs) is swapped for it.
14
14
  *
15
15
  * The state is cleared when the server replies with the component's own
16
16
  * re-render, an error, or an ack (sent when the action didn't re-render the
@@ -177,7 +177,7 @@ export default class LoadingState {
177
177
 
178
178
  this.#disabledElements.set(element, {
179
179
  disabled: element.disabled,
180
- content: text ? (isInput ? element.value : element.textContent) : null,
180
+ content: text ? (isInput ? element.value : element.innerHTML) : null,
181
181
  })
182
182
 
183
183
  element.disabled = true
@@ -205,7 +205,7 @@ export default class LoadingState {
205
205
  if (element instanceof HTMLInputElement) {
206
206
  element.value = content
207
207
  } else {
208
- element.textContent = content
208
+ element.innerHTML = content
209
209
  }
210
210
  }
211
211
  })