phlex-reactive 0.16.12 → 0.16.14

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.
@@ -854,8 +854,18 @@ function refusedHeader(response) {
854
854
  // (streamOwnReply wraps its render, innermost); a reply none of whose streams
855
855
  // rendered releases now. An error reply (keep true) never marks either, but
856
856
  // releases nothing: the server refused those values rather than answering them.
857
- function renderOwnReply(root, html, keep = null) {
858
- const own = { root, streams: 0, keep }
857
+ //
858
+ // Returns a promise that settles once the reply is drawn (issue #464), so the
859
+ // dispatch lane leaves the activity counter after the morph, not a repaint
860
+ // before it. Every listener has had its say by the time renderStreamMessage
861
+ // returns (dispatch is synchronous), so a stream whose event was not cancelled
862
+ // is one Turbo will render: the promise waits for each such render to finish
863
+ // (the innermost wrapper below — after an exit effect, after the opt-in
864
+ // client's hold). With none left to wait for — no stream, or every render
865
+ // prevented — it settles after one repaint. Never later than `cap` ms: a render
866
+ // chain that never finishes must not wedge the request queue.
867
+ function renderOwnReply(root, html, keep = null, cap = 30000) {
868
+ const own = { root, streams: 0, keep, events: [] }
859
869
  const previous = replyRoot
860
870
  replyRoot = own
861
871
  try {
@@ -864,6 +874,21 @@ function renderOwnReply(root, html, keep = null) {
864
874
  replyRoot = previous
865
875
  }
866
876
  if (own.streams === 0) releaseHeld(root, keep)
877
+ const renders = own.events.filter((entry) => !entry.event.defaultPrevented).map((entry) => entry.done)
878
+ // Resolves with the first render's error, if one threw (Turbo logs it).
879
+ const drawn = renders.length > 0 ? Promise.all(renders).then((errors) => errors.find(Boolean)) : nextRepaint()
880
+ let timer
881
+ const bound = new Promise((resolve) => (timer = setTimeout(resolve, cap)))
882
+ return Promise.race([drawn, bound]).finally(() => clearTimeout(timer))
883
+ }
884
+
885
+ // Turbo's own nextRepaint: a frame, or a task in a hidden tab (where frames
886
+ // stop) and wherever there is no requestAnimationFrame.
887
+ function nextRepaint() {
888
+ return new Promise((resolve) => {
889
+ if (document.visibilityState === "hidden" || typeof requestAnimationFrame !== "function") setTimeout(resolve, 0)
890
+ else requestAnimationFrame(() => resolve())
891
+ })
867
892
  }
868
893
 
869
894
  function streamOwnReply(event) {
@@ -872,15 +897,22 @@ function streamOwnReply(event) {
872
897
  const render = detail?.render
873
898
  if (!own || typeof render !== "function") return
874
899
  own.streams++
900
+ let finished
901
+ own.events.push({ event, done: new Promise((resolve) => (finished = resolve)) })
875
902
  detail.render = async (el) => {
876
903
  replying.set(own.root, (replying.get(own.root) || 0) + 1)
904
+ let failure
877
905
  try {
878
906
  return await render(el)
907
+ } catch (error) {
908
+ failure = error
909
+ throw error
879
910
  } finally {
880
911
  const left = replying.get(own.root) - 1
881
912
  if (left) replying.set(own.root, left)
882
913
  else replying.delete(own.root)
883
914
  releaseHeld(own.root, own.keep)
915
+ finished(failure)
884
916
  }
885
917
  }
886
918
  }
@@ -988,9 +1020,20 @@ export function registerReactiveDev() {
988
1020
  // is fully applied by the time the call returns — there is no async window to await
989
1021
  // (the "value settles a beat after a morph/seed" case the issue describes is
990
1022
  // covered by the System test helpers' re-resolve-by-id polling, not this counter).
1023
+ //
1024
+ // Each busy window (busy edge to idle edge) also collects the failures raised
1025
+ // inside it (issue #464): a dispatch that failed (every reactive:error kind,
1026
+ // apply included), a feature that could not load, a deferred render that
1027
+ // failed. reactive:idle's detail carries them as `errors`, and <html> carries
1028
+ // data-reactive-errors (the same list, as JSON) from that idle edge until the
1029
+ // next busy edge — so a system test can tell a failed round trip from one that
1030
+ // rendered. A failure raised while nothing is in flight belongs to no window
1031
+ // and is not kept.
991
1032
  export const ACTIVE_ATTR = "data-reactive-active"
1033
+ export const ERRORS_ATTR = "data-reactive-errors"
992
1034
 
993
1035
  let activityCount = 0
1036
+ let activityErrors = []
994
1037
 
995
1038
  // Increment the global in-flight count; on the 0 -> 1 edge, mark <html> and fire
996
1039
  // reactive:busy. Fully defensive — a non-browser/test document with no
@@ -998,7 +1041,17 @@ let activityCount = 0
998
1041
  // side effects (a global signal must never throw during bootstrap or a round trip).
999
1042
  export function enterReactiveActivity() {
1000
1043
  activityCount++
1001
- if (activityCount === 1) syncReactiveActivity("reactive:busy")
1044
+ if (activityCount === 1) {
1045
+ activityErrors = []
1046
+ syncReactiveActivity("reactive:busy")
1047
+ }
1048
+ }
1049
+
1050
+ // Note a failure in the open busy window: { action, kind, status, root }, each
1051
+ // null when it does not apply. Called BEFORE the failing operation exits.
1052
+ export function recordReactiveError({ action = null, kind, status = null, root = null }) {
1053
+ if (activityCount === 0) return
1054
+ activityErrors.push({ action: action ?? null, kind, status: status ?? null, root: root || null })
1002
1055
  }
1003
1056
 
1004
1057
  // Decrement the global in-flight count, clamped at 0 so an unbalanced exit can
@@ -1020,8 +1073,10 @@ export function reactiveActivityCount() {
1020
1073
  // since the module is imported once per bun run.
1021
1074
  export function resetReactiveActivity() {
1022
1075
  activityCount = 0
1076
+ activityErrors = []
1023
1077
  const root = typeof document !== "undefined" ? document.documentElement : null
1024
1078
  root?.removeAttribute?.(ACTIVE_ATTR)
1079
+ root?.removeAttribute?.(ERRORS_ATTR)
1025
1080
  }
1026
1081
 
1027
1082
  // Write the <html> marker from the current count and fire the edge event on
@@ -1031,11 +1086,15 @@ export function resetReactiveActivity() {
1031
1086
  function syncReactiveActivity(eventName) {
1032
1087
  if (typeof document === "undefined") return
1033
1088
  const root = document.documentElement
1089
+ const idle = eventName === "reactive:idle"
1034
1090
  if (typeof root?.toggleAttribute === "function") {
1035
1091
  root.toggleAttribute(ACTIVE_ATTR, activityCount > 0)
1092
+ if (idle && activityErrors.length > 0) root.setAttribute(ERRORS_ATTR, JSON.stringify(activityErrors))
1093
+ else root.removeAttribute(ERRORS_ATTR)
1036
1094
  }
1037
1095
  if (typeof document.dispatchEvent === "function" && typeof CustomEvent === "function") {
1038
- document.dispatchEvent(new CustomEvent(eventName, { detail: { count: activityCount } }))
1096
+ const detail = idle ? { count: activityCount, errors: activityErrors.slice() } : { count: activityCount }
1097
+ document.dispatchEvent(new CustomEvent(eventName, { detail }))
1039
1098
  }
1040
1099
  }
1041
1100
 
@@ -1357,6 +1416,12 @@ const CLIENT_OPS = Object.freeze({
1357
1416
  show_modal: (el) => showModal(el),
1358
1417
  close_dialog: (el) => closeDialog(el),
1359
1418
 
1419
+ // Click op (issue #471): HTMLElement#click(), the browser's own activation
1420
+ // (a link visit through Turbo Drive, a form submit, a checkbox toggle).
1421
+ // FIRST match only (FIRST_MATCH_OPS). Gesture-only: the server refuses it in
1422
+ // every pushed op (JS::GESTURE_OPS).
1423
+ click: (el) => el.click?.(),
1424
+
1360
1425
  // Text op (issue #159): set textContent — XSS-safe by construction (never
1361
1426
  // innerHTML), strictly less powerful than set_attr. Change-guarded like
1362
1427
  // #mirrorText. With global: true it is the cross-root text escape: paint a
@@ -2055,6 +2120,10 @@ function bindingsAlreadyRan(event, controller) {
2055
2120
  return false
2056
2121
  }
2057
2122
 
2123
+ // Ops that act on the first match only (issue #471): clicking every match
2124
+ // would follow several links or submit several forms.
2125
+ const FIRST_MATCH_OPS = new Set(["click"])
2126
+
2058
2127
  // Interpret a [[name, args], ...] op list against the frozen CLIENT_OPS
2059
2128
  // whitelist (issues #95/#96/#97). `resolveTargets(args)` returns the element(s)
2060
2129
  // an op applies to — the controller scopes to its root (excluding nested
@@ -2071,8 +2140,9 @@ function applyOps(list, resolveTargets, onZeroTargets) {
2071
2140
  console.warn(`[phlex-reactive] unknown client op ${JSON.stringify(name)} — skipped`)
2072
2141
  continue
2073
2142
  }
2074
- const targets = resolveTargets(args)
2143
+ let targets = resolveTargets(args)
2075
2144
  if (targets.length === 0 && onZeroTargets) onZeroTargets(name, args)
2145
+ if (targets.length > 1 && FIRST_MATCH_OPS.has(name)) targets = targets.slice(0, 1)
2076
2146
  if (targets.length > 0) args = readArgs(name, args, resolveTargets, onZeroTargets)
2077
2147
  if (!args) continue
2078
2148
  for (const el of targets) {
@@ -2568,8 +2638,14 @@ export function __loadReactiveFeatureForTest(name) {
2568
2638
  // modules the default bundle handed over still loaded — or, `cold`, with none
2569
2639
  // loaded at all: the state of a page that imported phlex/reactive/core.
2570
2640
  export function __resetReactiveFeaturesForTest(cold) {
2571
- // (The default entry has no table to reset: its features are static.)
2572
- if (!__SPLIT__) return
2641
+ // The default entry has no table to reset: its features are static. A second
2642
+ // copy of the runtime installs its own counters into them, though, so put
2643
+ // this instance's back.
2644
+ if (!__SPLIT__) {
2645
+ persistFeature.install(FEATURE_SHARED)
2646
+ deferFeature.install(FEATURE_SHARED)
2647
+ return
2648
+ }
2573
2649
  FEATURES.clear()
2574
2650
  for (const [name, entry] of PRODUCTION_FEATURES) FEATURES.set(name, entry)
2575
2651
  // (Only the opt-in entry registers any; with the default entry alone the
@@ -2596,6 +2672,7 @@ function forgetWaiting(root, name, pending) {
2596
2672
  const FEATURE_SHARED = {
2597
2673
  enter: enterReactiveActivity,
2598
2674
  exit: exitReactiveActivity,
2675
+ fail: recordReactiveError,
2599
2676
  count: countReactiveRequest,
2600
2677
  // The editable collector and server text (issue #351), for the draft.
2601
2678
  text: editableValue,
@@ -3219,6 +3296,7 @@ export default class extends Controller {
3219
3296
  #featureFailed(name, phase, error) {
3220
3297
  logFeatureFailure(name, phase, error)
3221
3298
  this.#markError("feature")
3299
+ recordReactiveError({ kind: "feature", root: this.element.id })
3222
3300
  // A lazy shell whose module will never come (a failed import stays failed
3223
3301
  // until the page is reloaded) must not go on shimmering as if it loaded.
3224
3302
  if (phase === "load" && this.element.getAttribute?.("data-reactive-defer-pending")) {
@@ -4145,6 +4223,7 @@ export default class extends Controller {
4145
4223
  }
4146
4224
  return this.#enqueue(action, rawParams)
4147
4225
  }
4226
+ recordReactiveError({ action, kind: extra.kind, status: extra.status, root: this.element.id })
4148
4227
  this.#emit("reactive:error", { action, params: sentParams, ...extra, retry })
4149
4228
  }
4150
4229
 
@@ -4390,7 +4469,9 @@ export default class extends Controller {
4390
4469
  if (__SPLIT__) this.#devtools((devtools) => devtools.recordBody(debug, errorBody, fresh))
4391
4470
  else devtoolsFeature.recordBody(debug, errorBody, fresh)
4392
4471
  }
4393
- renderOwnReply(this.element, errorBody, true)
4472
+ const drawn = renderOwnReply(this.element, errorBody, true, this.#timeoutMs())
4473
+ settle?.handoff?.()
4474
+ await drawn
4394
4475
  }
4395
4476
  this.#markError("http")
4396
4477
  this.#emitError(action, params, allParams, { kind: "http", status: response.status, body: errorBody })
@@ -4424,7 +4505,7 @@ export default class extends Controller {
4424
4505
  // focused input + caret on unchanged nodes — see issue #28. As the root's
4425
4506
  // own reply, it clears what the root held (issue #370), but what it
4426
4507
  // refused (issue #413).
4427
- renderOwnReply(this.element, html, refusedHeader(response))
4508
+ const drawn = renderOwnReply(this.element, html, refusedHeader(response), this.#timeoutMs())
4428
4509
  // Debug-only (issue #181): the morph may apply a microtask later, so check
4429
4510
  // the resurrected-hide case AFTER it lands. Off the debug path, resurrect is
4430
4511
  // null — zero cost.
@@ -4437,8 +4518,24 @@ export default class extends Controller {
4437
4518
  // complete a tick later. Apps needing post-morph timing listen to Turbo's
4438
4519
  // own events; this one is for "the action round trip succeeded".
4439
4520
  this.#emit("reactive:applied", { action, params: allParams, html })
4521
+ // The round trip ends once the reply is drawn (issue #464): the finally's
4522
+ // settle (and with it the activity counter's idle edge) runs after the
4523
+ // morph, and the next queued action starts after it too. The busy state
4524
+ // reverts first, still a repaint before the streams render.
4525
+ settle?.handoff?.()
4526
+ // A stream that threw while Turbo rendered it is a client-side apply
4527
+ // failure. Recorded here, not in the catch below: the rest of the reply
4528
+ // is already drawn, so nothing reverts (the optimistic inverse would undo
4529
+ // over the server's state) and the reply still counts as applied.
4530
+ const failure = await drawn
4531
+ if (failure) {
4532
+ this.#markError("apply")
4533
+ recordReactiveError({ action, kind: "apply", root: this.element.id })
4534
+ this.#emit("reactive:error", { action, params: allParams, kind: "apply" })
4535
+ }
4440
4536
  // What core.proceed resolves with: a feature can tell a reply that
4441
- // applied from a failure (every other exit returns nothing).
4537
+ // applied from a failure (every other exit returns nothing). A reply
4538
+ // with a stream that threw still applied the rest.
4442
4539
  return html
4443
4540
  } catch (error) {
4444
4541
  // The server already processed this action successfully (we're past the
@@ -4449,6 +4546,8 @@ export default class extends Controller {
4449
4546
  // action the server already completed.
4450
4547
  console.error("[phlex-reactive] action error", error)
4451
4548
  this.#revertOptimistic(pending.inverse)
4549
+ this.#markError("apply")
4550
+ recordReactiveError({ action, kind: "apply", root: this.element.id })
4452
4551
  this.#emit("reactive:error", { action, params: allParams, kind: "apply" })
4453
4552
  } finally {
4454
4553
  // Settle the loading state (issue #99): decrement the pending counter,
@@ -5019,15 +5118,28 @@ export default class extends Controller {
5019
5118
  // #perform runs in its finally on EVERY exit path (success or any failure).
5020
5119
  enterReactiveActivity()
5021
5120
 
5121
+ // Two steps (issue #464). `handoff` reverts this enqueue's busy state when
5122
+ // the reply is handed to Turbo, a repaint before it renders, so an in-place
5123
+ // morph's server state (a trigger it renders disabled) wins over the undo.
5124
+ // The settle itself leaves the activity count only once the reply is drawn,
5125
+ // running the hand-off first if no reply got that far.
5126
+ let unbusied = false
5022
5127
  let settled = false
5023
- return () => {
5128
+ const handoff = () => {
5129
+ if (unbusied) return
5130
+ unbusied = true
5131
+ this.#unmarkBusy(action, trigger)
5132
+ // Busy reverts regardless of outcome, guarded per element.
5133
+ for (const op of pending.undo) op()
5134
+ }
5135
+ const settle = () => {
5024
5136
  if (settled) return // one settle per enqueue, even if called twice
5025
5137
  settled = true
5026
- this.#unmarkBusy(action, trigger)
5138
+ handoff()
5027
5139
  exitReactiveActivity()
5028
- // Busy reverts on SETTLE regardless of outcome, guarded per element.
5029
- for (const op of pending.undo) op()
5030
5140
  }
5141
+ settle.handoff = handoff
5142
+ return settle
5031
5143
  }
5032
5144
 
5033
5145
  // Layer 1 — the always-on busy markers. Trigger + root carry the action token;
@@ -64,6 +64,9 @@ module Phlex
64
64
  end
65
65
  raise ArgumentError, "reactive_editable on_enter: got a JS chain with no ops — a dead Enter" if on_enter.empty?
66
66
 
67
+ # Issue #471: the Enter runs root-scoped, with no trigger element —
68
+ # js.click's default (:trigger) would resolve to nothing.
69
+ Phlex::Reactive::JS.refuse_trigger!(on_enter, "a reactive_editable on_enter: chain")
67
70
  on_enter.ops.to_json
68
71
  end
69
72
 
@@ -547,6 +547,15 @@ module Phlex
547
547
  "submit event this trigger is bound to. Bind the submit op to another event " \
548
548
  "(change/input), or gate it behind a reducer's $ops / reactive_on_complete."
549
549
  end
550
+ # Issue #471: el.click() dispatches the very click this trigger is
551
+ # bound to, and the binding prevents its default — the activation
552
+ # would be lost.
553
+ if event == "click" && self_click?(ops)
554
+ raise ArgumentError,
555
+ "on_client(:click, js.click) on its own trigger cancels itself — the synthetic click " \
556
+ "re-enters this binding, which prevents its default. Bind it to another event " \
557
+ "(\"keydown.space\"), or click another element (js.click(\"#target\"))."
558
+ end
550
559
  shortcut = client_shortcut!(event, shortcut, window:, outside:)
551
560
  keeps_default!("on_client(#{event.inspect})", prevent, shortcut) unless prevent == true
552
561
  window_bound = window || outside || !shortcut.nil?
@@ -1139,20 +1148,40 @@ module Phlex
1139
1148
  # `from:` values are RAW CSS selectors (the escape-hatch posture of
1140
1149
  # reactive_filter/reactive_tags) — the sources are author-owned markup,
1141
1150
  # not reactive_field bindings — resolved root-scoped (#15 ownership).
1151
+ #
1152
+ # `clear: :reset` (issue #466) puts each source back to its RENDERED
1153
+ # default instead of emptying it, the way a form reset would: a
1154
+ # default-on checkbox stays ticked for the next entry, a text input
1155
+ # returns to its `value`, a select to its `selected` option.
1142
1156
  def reactive_nested_add(association, from: nil, clear: false)
1143
1157
  data = {
1144
1158
  action: "click->reactive#nestedAdd",
1145
1159
  reactive_association_param: nested_identifier!(:reactive_nested_add, :association, association)
1146
1160
  }
1161
+ clear_param = nested_clear_param!(clear)
1147
1162
  unless from.nil?
1148
1163
  data[:reactive_nested_from_param] = nested_from_param!(from)
1149
- # STRING "true", not boolean: a valueless boolean attr reads "" (falsy)
1150
- # client-side — the on()/tags precedent.
1151
- data[:reactive_nested_clear_param] = "true" if clear
1164
+ data[:reactive_nested_clear_param] = clear_param if clear_param
1152
1165
  end
1153
1166
  { type: "button", data: }
1154
1167
  end
1155
1168
 
1169
+ # The clear: wire value: "true" (empty the sources), "reset" (back to
1170
+ # their rendered defaults, issue #466), or nil (leave them). STRINGS,
1171
+ # not booleans: a valueless boolean attr reads "" (falsy) client-side —
1172
+ # the on()/tags precedent. Anything else is a typo: fail at render.
1173
+ def nested_clear_param!(clear)
1174
+ case clear
1175
+ when false, nil then nil
1176
+ when true then "true"
1177
+ when :reset then "reset"
1178
+ else
1179
+ raise ArgumentError,
1180
+ "reactive_nested_add(clear:) takes true (empty the sources), :reset (put them back to " \
1181
+ "their rendered defaults) or false, got #{clear.inspect}"
1182
+ end
1183
+ end
1184
+
1156
1185
  # Validate + compile a fill-then-add `from:` map into its JSON wire
1157
1186
  # (issue #208). Each key is a ROW FIELD name (plain identifier, like the
1158
1187
  # association); each value is a SOURCE CONTROL selector (non-blank). An
@@ -1640,6 +1669,15 @@ module Phlex
1640
1669
  record
1641
1670
  end
1642
1671
 
1672
+ # Issue #471: a click op aimed at the trigger. A hand-built chain may
1673
+ # carry Symbol names and keys, or no args Hash.
1674
+ def self_click?(ops)
1675
+ ops.ops.any? do |name, args|
1676
+ name.to_s == "click" && args.is_a?(Hash) &&
1677
+ (args["to"] || args[:to]) == Phlex::Reactive::JS::TRIGGER_SENTINEL
1678
+ end
1679
+ end
1680
+
1643
1681
  # Issue #442: validate on_client's within: — a non-empty CSS selector,
1644
1682
  # on an element-bound binding that can survive a miss.
1645
1683
  def client_within!(event, within, window:, outside:, shortcut:, once:)
@@ -145,6 +145,29 @@ module Phlex
145
145
  end
146
146
  end
147
147
 
148
+ # Ops the server never pushes (issue #471): click activates an element
149
+ # (follows a link, submits a form), so a reply or a broadcast that lands
150
+ # later must not carry it. Stricter than the broadcast-only refusal of
151
+ # focus/submit (Streamable::BROADCAST_REFUSED_OPS).
152
+ GESTURE_OPS = %w[click].freeze
153
+
154
+ # Raise when `list` (a JS chain or a raw [[op, args]] list) carries a
155
+ # gesture-only op. Called for every op the server pushes
156
+ # (Response.js_ops_json: reply.js, a settle's js and broadcast_to(js:)).
157
+ # A pushed dispatch("click") stays allowed (it may run an on(:action)
158
+ # click binding, as it always could), so it can reach a :click binding
159
+ # that holds js.click — the developer's wiring, like set_value's input.
160
+ def self.refuse_gesture_ops!(list)
161
+ pairs = list.is_a?(JS) ? list.ops : Array(list)
162
+ refused = pairs.filter_map { |op, _| op.to_s if GESTURE_OPS.include?(op.to_s) }.uniq
163
+ return if refused.empty?
164
+
165
+ raise ArgumentError,
166
+ "#{self}: a server-pushed op (reply.js, broadcast_to(js:)) refuses #{refused.join(", ")} — " \
167
+ "click activates an element (follows a link, submits a form), so the server never pushes " \
168
+ "it. Answer with reply.redirect for a visit, or bind js.click with on_client."
169
+ end
170
+
148
171
  # Raise when an op in `list` (a JS chain or a raw [[op, args]] list)
149
172
  # names @trigger (a target, from:, or dispatch's detail_from:, which
150
173
  # reads off it). Called for every op the server pushes
@@ -322,6 +345,34 @@ module Phlex
322
345
  append("blur", target_args(to, global:))
323
346
  end
324
347
 
348
+ # --- Click (issue #471) ---
349
+ #
350
+ # click(to = :trigger) — HTMLElement#click() on the FIRST match: the
351
+ # browser's own activation, as a user click would run it. A link follows
352
+ # its href (through Turbo Drive, with its own data-turbo-* attributes), a
353
+ # submit button submits its form, a checkbox toggles. The default target
354
+ # is the trigger, so a link that should also answer Space reads
355
+ # a(href: item_path(item), **on_client("keydown.space", js.click)) { item.name }
356
+ # (the binding prevents the keydown's default, so Space does not scroll).
357
+ #
358
+ # The synthetic click bubbles like a real one: a click binding on the
359
+ # target or an ancestor prevents its default (and so the activation)
360
+ # unless it was bound with prevent: false. on_client(:click, js.click) on
361
+ # its own trigger is refused at render for that reason.
362
+ #
363
+ # NEVER SERVER-PUSHED, stricter than focus: refused in every server-pushed
364
+ # op (reply.js, a settle's js, broadcast_to(js:)) — a reply that lands
365
+ # later would navigate without a gesture. on_client, a raw ["click", …] pair in a reducer's $ops and
366
+ # reactive_on_complete may carry it. The last two run on an input event,
367
+ # and a reply's set_value fires one too, so a reply can reach a click
368
+ # there — the same exposure submit has; so can a pushed
369
+ # dispatch("click") reaching a :click binding that holds it. A held key repeats its keydown,
370
+ # and each repeat clicks again.
371
+
372
+ def click(to = :trigger, global: false)
373
+ append("click", target_args(to, global:))
374
+ end
375
+
325
376
  # --- Modal dialogs (issue #365) ---
326
377
  #
327
378
  # show_modal(to) — HTMLDialogElement#showModal(): the top layer, a
@@ -304,12 +304,14 @@ data-reactive-ops="#{ERB::Util.html_escape(json)}"></turbo-stream>).html_safe
304
304
  # site), so fail loudly rather than emit an inert tag.
305
305
  # Every op the server pushes (reply.js, broadcast_to(js:)) passes here,
306
306
  # so this is where @trigger is refused for a chain too (issue #442): a
307
- # pushed op has no element whose binding fired.
307
+ # pushed op has no element whose binding fired. So is a gesture-only op
308
+ # (click, issue #471).
308
309
  def js_ops_json(ops)
309
310
  if ops.is_a?(Phlex::Reactive::JS)
310
311
  raise ArgumentError, "js(...) got no ops — a dead reactive:js stream" if ops.empty?
311
312
 
312
313
  Phlex::Reactive::JS.refuse_trigger!(ops)
314
+ Phlex::Reactive::JS.refuse_gesture_ops!(ops)
313
315
  ops.to_json
314
316
  else
315
317
  list = Array(ops)
@@ -319,6 +321,7 @@ data-reactive-ops="#{ERB::Util.html_escape(json)}"></turbo-stream>).html_safe
319
321
  # list skips that, so re-apply the allowlist here (defense in depth —
320
322
  # the client interpreter also refuses on*/URL/style attrs).
321
323
  Phlex::Reactive::JS.assert_ops_allowed!(list)
324
+ Phlex::Reactive::JS.refuse_gesture_ops!(list)
322
325
  list.to_json
323
326
  end
324
327
  end
@@ -44,14 +44,19 @@ module Phlex
44
44
  # and close_dialog (issue #365) would open or close a modal, and move
45
45
  # focus, on every screen at once; set_value (issue #374) would overwrite
46
46
  # every subscriber's field; preview_file (issue #375) would read every
47
- # subscriber's file input. They
47
+ # subscriber's file input; click (issue #471) would follow a link or
48
+ # submit a form on every subscriber's page. They
48
49
  # belong to the actor's own reply (reply.js) or gesture (on_client / a
49
- # reducer's $ops), never a broadcast. Names mirror Phlex::Reactive::JS's verbs.
50
+ # reducer's $ops), never a broadcast — except click, which reply.js
51
+ # refuses too (Phlex::Reactive::JS::GESTURE_OPS): bind it with on_client
52
+ # (or a raw ["click", …] pair in a reducer's $ops).
53
+ # Names mirror Phlex::Reactive::JS's verbs.
50
54
  BROADCAST_REFUSED_OPS = %w[
51
55
  focus focus_first blur submit paste_into persist_state persist_clear check_group presence
52
56
  show_modal close_dialog
53
57
  preview_file
54
58
  set_value
59
+ click
55
60
  ].freeze
56
61
  # Refused as a FLAG, on any op (issue #369): keep: records client state in
57
62
  # the tab that ran the op, so a broadcast carrying it would plant that
@@ -241,7 +246,9 @@ module Phlex
241
246
  "broadcasting show_modal or close_dialog opens or closes a modal (and moves focus) on " \
242
247
  "every screen — render the dialog open or closed, with data: { reactive_modal: true }, instead. " \
243
248
  "Broadcasting preview_file reads every subscriber's chosen file onto their page. " \
244
- "These are actor concerns (reply.js / on_client / $ops)."
249
+ "Broadcasting click follows a link or submits a form on every subscriber's page. " \
250
+ "These are actor concerns (reply.js / on_client / $ops); click is never server-pushed — " \
251
+ "reply.js refuses it too: bind it with on_client (or a raw [\"click\", …] pair in a reducer's $ops)."
245
252
  end
246
253
  refuse_kept_broadcast_ops!(pairs)
247
254
 
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phlex
4
+ module Reactive
5
+ module TestHelpers
6
+ module System
7
+ # Raised by wait_for_reactive when the busy window it waited on ended with
8
+ # failures (issue #464): the client's <html data-reactive-errors> list.
9
+ #
10
+ # reactive action "increment" failed (http 500) on #flaky-counter
11
+ #
12
+ # #errors is that list, each entry { action:, kind:, status:, root: }.
13
+ class ReactiveReplyError < StandardError
14
+ attr_reader :errors
15
+
16
+ def initialize(errors)
17
+ @errors = errors
18
+ super(errors.map { describe(it) }.join("; "))
19
+ end
20
+
21
+ private
22
+
23
+ def describe(error)
24
+ subject = error[:action] ? %(action "#{error[:action]}") : error[:kind].to_s
25
+ reason = [error[:kind], error[:status]].compact.join(" ")
26
+ "reactive #{subject} failed (#{reason})#{" on ##{error[:root]}" if error[:root]}"
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
@@ -42,6 +42,22 @@ module Phlex
42
42
  # gate (dev/test by default).
43
43
  REQUESTS_ATTR = "data-reactive-requests"
44
44
 
45
+ # The <html> attribute the client writes when a busy window ends with
46
+ # failures (issue #464): a JSON list of { action, kind, status, root },
47
+ # present from that idle edge until the next busy edge. Lockstep with
48
+ # runtime.js ERRORS_ATTR.
49
+ ERRORS_ATTR = "data-reactive-errors"
50
+
51
+ # The list in the attribute, each entry a Hash with Symbol keys. Anything
52
+ # but a JSON list (absent, garbled, Playwright's {} for a JS null) reads
53
+ # as no errors, and so does an entry that is not an object.
54
+ def self.parse_reactive_errors(raw)
55
+ parsed = raw.is_a?(::String) ? ::JSON.parse(raw, symbolize_names: true) : []
56
+ parsed.is_a?(::Array) ? parsed.grep(::Hash) : []
57
+ rescue ::JSON::ParserError
58
+ []
59
+ end
60
+
45
61
  # Parse the attribute value into { action:, defer: } Integers — zeros for
46
62
  # an absent or garbled value. Shared by the helpers and
47
63
  # ReactiveRequestsMatcher.
@@ -74,7 +90,13 @@ module Phlex
74
90
  # (a deferred render behind a real job). Returns nil; call it as a barrier
75
91
  # BEFORE asserting a settled value if you are not already using one of the
76
92
  # waiting matchers below.
77
- def wait_for_reactive(timeout: nil)
93
+ #
94
+ # The idle edge comes after the replies are drawn, and it records what
95
+ # failed in the window that just ended (issue #464). If anything did, this
96
+ # raises ReactiveReplyError naming each failed action, kind and status, so
97
+ # a 500 or a timeout fails here rather than one assertion later.
98
+ # `allow_error: true` only waits, for a test that expects the failure.
99
+ def wait_for_reactive(timeout: nil, allow_error: false)
78
100
  # Scope the check to <html> via the :xpath "/html" so the marker is read
79
101
  # on the document element the client writes it to — not a descendant.
80
102
  # assert_no_selector WAITS (retries) until the marker clears or the wait
@@ -83,6 +105,13 @@ module Phlex
83
105
  # session) so it works regardless of whether the example group mixed in
84
106
  # Capybara::DSL.
85
107
  page.assert_no_selector(:xpath, "/html[@#{ACTIVE_MARKER}]", **wait_option(timeout))
108
+ return if allow_error
109
+
110
+ errors = System.parse_reactive_errors(
111
+ page.evaluate_script("document.documentElement.getAttribute(#{ERRORS_ATTR.to_json})")
112
+ )
113
+ raise ReactiveReplyError, errors if errors.any?
114
+
86
115
  nil
87
116
  end
88
117
 
@@ -252,3 +281,4 @@ module Phlex
252
281
  end
253
282
 
254
283
  require "phlex/reactive/test_helpers/system/reactive_requests_matcher"
284
+ require "phlex/reactive/test_helpers/system/reactive_reply_error"
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Phlex
4
4
  module Reactive
5
- VERSION = "0.16.12"
5
+ VERSION = "0.16.14"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: phlex-reactive
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.16.12
4
+ version: 0.16.14
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson
@@ -262,6 +262,7 @@ files:
262
262
  - lib/phlex/reactive/test_helpers.rb
263
263
  - lib/phlex/reactive/test_helpers/matchers.rb
264
264
  - lib/phlex/reactive/test_helpers/system.rb
265
+ - lib/phlex/reactive/test_helpers/system/reactive_reply_error.rb
265
266
  - lib/phlex/reactive/test_helpers/system/reactive_requests_matcher.rb
266
267
  - lib/phlex/reactive/version.rb
267
268
  - lib/tasks/phlex_reactive.rake