phlex-reactive 0.16.13 → 0.17.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.
Files changed (31) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +99 -16
  3. data/README.md +60 -3
  4. data/app/javascript/phlex/reactive/core.js +1 -0
  5. data/app/javascript/phlex/reactive/core.min.js +4 -4
  6. data/app/javascript/phlex/reactive/core.min.js.map +4 -4
  7. data/app/javascript/phlex/reactive/features/presence.js +37 -3
  8. data/app/javascript/phlex/reactive/features/presence.min.js +2 -2
  9. data/app/javascript/phlex/reactive/features/presence.min.js.map +3 -3
  10. data/app/javascript/phlex/reactive/features/subscribe.js +143 -0
  11. data/app/javascript/phlex/reactive/features/subscribe.min.js +4 -0
  12. data/app/javascript/phlex/reactive/features/subscribe.min.js.map +10 -0
  13. data/app/javascript/phlex/reactive/reactive_controller.js +2 -0
  14. data/app/javascript/phlex/reactive/reactive_controller.min.js +4 -4
  15. data/app/javascript/phlex/reactive/reactive_controller.min.js.map +7 -6
  16. data/app/javascript/phlex/reactive/runtime.js +37 -2
  17. data/lib/phlex/reactive/component/dsl.rb +3 -0
  18. data/lib/phlex/reactive/component/editable.rb +3 -0
  19. data/lib/phlex/reactive/component/helpers.rb +26 -0
  20. data/lib/phlex/reactive/component/presence_declaration.rb +2 -1
  21. data/lib/phlex/reactive/component/registry.rb +5 -2
  22. data/lib/phlex/reactive/component/subscribe_declaration.rb +132 -0
  23. data/lib/phlex/reactive/component.rb +1 -0
  24. data/lib/phlex/reactive/doctor.rb +51 -4
  25. data/lib/phlex/reactive/engine.rb +3 -3
  26. data/lib/phlex/reactive/js.rb +51 -0
  27. data/lib/phlex/reactive/response.rb +4 -1
  28. data/lib/phlex/reactive/streamable.rb +10 -3
  29. data/lib/phlex/reactive/subscribe.rb +125 -0
  30. data/lib/phlex/reactive/version.rb +1 -1
  31. metadata +6 -1
@@ -38,6 +38,7 @@ import * as deferFeature from "phlex/reactive/features/defer"
38
38
  import * as sortableFeature from "phlex/reactive/features/sortable"
39
39
  import * as dragFeature from "phlex/reactive/features/drag"
40
40
  import * as presenceFeature from "phlex/reactive/features/presence"
41
+ import * as subscribeFeature from "phlex/reactive/features/subscribe"
41
42
  import * as countdownFeature from "phlex/reactive/features/countdown"
42
43
 
43
44
  // phlex/reactive/runtime — the reactive controller WITHOUT its feature
@@ -1416,6 +1417,12 @@ const CLIENT_OPS = Object.freeze({
1416
1417
  show_modal: (el) => showModal(el),
1417
1418
  close_dialog: (el) => closeDialog(el),
1418
1419
 
1420
+ // Click op (issue #471): HTMLElement#click(), the browser's own activation
1421
+ // (a link visit through Turbo Drive, a form submit, a checkbox toggle).
1422
+ // FIRST match only (FIRST_MATCH_OPS). Gesture-only: the server refuses it in
1423
+ // every pushed op (JS::GESTURE_OPS).
1424
+ click: (el) => el.click?.(),
1425
+
1419
1426
  // Text op (issue #159): set textContent — XSS-safe by construction (never
1420
1427
  // innerHTML), strictly less powerful than set_attr. Change-guarded like
1421
1428
  // #mirrorText. With global: true it is the cross-root text escape: paint a
@@ -2114,6 +2121,10 @@ function bindingsAlreadyRan(event, controller) {
2114
2121
  return false
2115
2122
  }
2116
2123
 
2124
+ // Ops that act on the first match only (issue #471): clicking every match
2125
+ // would follow several links or submit several forms.
2126
+ const FIRST_MATCH_OPS = new Set(["click"])
2127
+
2117
2128
  // Interpret a [[name, args], ...] op list against the frozen CLIENT_OPS
2118
2129
  // whitelist (issues #95/#96/#97). `resolveTargets(args)` returns the element(s)
2119
2130
  // an op applies to — the controller scopes to its root (excluding nested
@@ -2130,8 +2141,9 @@ function applyOps(list, resolveTargets, onZeroTargets) {
2130
2141
  console.warn(`[phlex-reactive] unknown client op ${JSON.stringify(name)} — skipped`)
2131
2142
  continue
2132
2143
  }
2133
- const targets = resolveTargets(args)
2144
+ let targets = resolveTargets(args)
2134
2145
  if (targets.length === 0 && onZeroTargets) onZeroTargets(name, args)
2146
+ if (targets.length > 1 && FIRST_MATCH_OPS.has(name)) targets = targets.slice(0, 1)
2135
2147
  if (targets.length > 0) args = readArgs(name, args, resolveTargets, onZeroTargets)
2136
2148
  if (!args) continue
2137
2149
  for (const el of targets) {
@@ -2403,6 +2415,11 @@ function presenceNeeded(root) {
2403
2415
  return root.getAttribute?.("data-reactive-presence") != null
2404
2416
  }
2405
2417
 
2418
+ // Subscribe (issue #474): the root subscribes to its own broadcast stream.
2419
+ function subscribeNeeded(root) {
2420
+ return root.getAttribute?.("data-reactive-subscribe") != null
2421
+ }
2422
+
2406
2423
  // Countdowns (issue #400): the root is, or holds, a reactive_countdown.
2407
2424
  function countdownNeeded(root) {
2408
2425
  return Boolean(root.matches?.("[data-reactive-countdown]") || root.querySelector?.("[data-reactive-countdown]"))
@@ -2425,6 +2442,9 @@ const PRODUCTION_FEATURES = [
2425
2442
  // Its announce is a request of its own; nothing it does at connect is read
2426
2443
  // by another request: it never gates.
2427
2444
  ["presence", [presenceNeeded, null]],
2445
+ // Its source is a connection of its own; nothing it does at connect is read
2446
+ // by a request: it never gates.
2447
+ ["subscribe", [subscribeNeeded, null]],
2428
2448
  // A countdown writes only its own text and visibility: it never gates.
2429
2449
  ["countdown", [countdownNeeded, null]],
2430
2450
  [
@@ -2590,7 +2610,7 @@ function featureTimeoutMs() {
2590
2610
  export function reactiveFeatureNames() {
2591
2611
  return __SPLIT__
2592
2612
  ? [...FEATURES.keys()]
2593
- : ["persist", "defer", "form", "bindings", "compute", "sortable", "drag", "presence", "countdown", "effects", "hints", "devtools"]
2613
+ : ["persist", "defer", "form", "bindings", "compute", "sortable", "drag", "presence", "subscribe", "countdown", "effects", "hints", "devtools"]
2594
2614
  }
2595
2615
 
2596
2616
  export function __setReactiveFeatureForTest(name, needs, load, waiting, gates) {
@@ -2615,6 +2635,7 @@ export function __loadReactiveFeatureForTest(name) {
2615
2635
  sortable: sortableFeature,
2616
2636
  drag: dragFeature,
2617
2637
  presence: presenceFeature,
2638
+ subscribe: subscribeFeature,
2618
2639
  countdown: countdownFeature,
2619
2640
  effects: effectsFeature,
2620
2641
  hints: hintsFeature,
@@ -2679,6 +2700,7 @@ const SORTABLE = 32
2679
2700
  const PRESENCE = 64
2680
2701
  const COUNTDOWN = 128
2681
2702
  const DRAG = 256
2703
+ const SUBSCRIBE = 512
2682
2704
 
2683
2705
  // The default entry's features are part of this file: install them now, as
2684
2706
  // the opt-in entry does when one arrives.
@@ -3011,6 +3033,7 @@ export default class extends Controller {
3011
3033
  this.#connectFeatureNow(SORTABLE, "sortable", sortableNeeded, (core) => sortableFeature.connect(this, core))
3012
3034
  this.#connectFeatureNow(DRAG, "drag", dragNeeded, (core) => dragFeature.connect(this, core))
3013
3035
  this.#connectFeatureNow(PRESENCE, "presence", presenceNeeded, (core) => presenceFeature.connect(this, core))
3036
+ this.#connectFeatureNow(SUBSCRIBE, "subscribe", subscribeNeeded, () => subscribeFeature.connect(this))
3014
3037
  this.#connectFeatureNow(COUNTDOWN, "countdown", countdownNeeded, (core) => countdownFeature.connect(this, core))
3015
3038
  }
3016
3039
  }
@@ -3051,6 +3074,7 @@ export default class extends Controller {
3051
3074
  if (on & SORTABLE) this.#disconnectFeatureNow("sortable", () => sortableFeature.disconnect(this, core))
3052
3075
  if (on & DRAG) this.#disconnectFeatureNow("drag", () => dragFeature.disconnect(this, core))
3053
3076
  if (on & PRESENCE) this.#disconnectFeatureNow("presence", () => presenceFeature.disconnect(this, core))
3077
+ if (on & SUBSCRIBE) this.#disconnectFeatureNow("subscribe", () => subscribeFeature.disconnect(this))
3054
3078
  if (on & COUNTDOWN) this.#disconnectFeatureNow("countdown", () => countdownFeature.disconnect(this, core))
3055
3079
  }
3056
3080
  }
@@ -5232,7 +5256,18 @@ export default class extends Controller {
5232
5256
  // when not present (e.g. no pgbus, or no active subscription) — the header
5233
5257
  // is then simply omitted.
5234
5258
  #connectionId() {
5259
+ // A subscribing root (issue #474) sends its own stream's connection, so
5260
+ // exclude: reactive_connection_id on a broadcast to that stream skips the
5261
+ // actor — whatever source comes first on the page.
5262
+ const src = this.element.getAttribute?.("data-reactive-subscribe")
5263
+ let own
5264
+ if (src) {
5265
+ for (const source of document.querySelectorAll("pgbus-stream-source[data-reactive-subscribe-source][connection-id]")) {
5266
+ if (source.getAttribute("src") === src) own = source.getAttribute("connection-id")
5267
+ }
5268
+ }
5235
5269
  return (
5270
+ own ||
5236
5271
  document.querySelector("pgbus-stream-source[connection-id]")?.getAttribute("connection-id") ||
5237
5272
  document.querySelector('meta[name="pgbus-connection-id"]')?.content ||
5238
5273
  null
@@ -372,6 +372,9 @@ module Phlex
372
372
  # A ClientBindings-only class has no presence declaration to refuse.
373
373
  refuse_dormant_presence! if dormant && respond_to?(:reactive_presence_declaration) &&
374
374
  reactive_presence_declaration
375
+ # Issue #474: nor subscribe to its stream.
376
+ refuse_dormant_subscribe! if dormant && respond_to?(:reactive_subscribe_declaration) &&
377
+ reactive_subscribe_declaration
375
378
 
376
379
  Phlex::Reactive::Dormant.reject_visible_lazy!(self) if dormant
377
380
 
@@ -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
 
@@ -111,6 +111,10 @@ module Phlex
111
111
  # The lazy SHELL (not the real render) of an on: :visible component
112
112
  # can never wake — refuse it rather than ship a dead placeholder.
113
113
  Phlex::Reactive::Dormant.reject_visible_lazy!(self.class) unless Phlex::Reactive::Defer.real_render?
114
+ # Nor a per-render dormant root that subscribes (issue #474) or
115
+ # is a presence roster: it never connects, so it never would.
116
+ self.class.send(:refuse_dormant_subscribe!) if respond_to?(:reactive_subscribe_data)
117
+ self.class.send(:refuse_dormant_presence!) if respond_to?(:reactive_presence_data)
114
118
  { reactive_dormant: "reactive" }
115
119
  else
116
120
  { controller: "reactive" }
@@ -155,6 +159,10 @@ module Phlex
155
159
  # stream, from which the client mints its subscription. Only a class
156
160
  # that declares reactive_presence has the method.
157
161
  data.merge!(reactive_presence_data) if respond_to?(:reactive_presence_data)
162
+ # Subscribe (issue #474): the signed src of the component's own
163
+ # broadcast stream. Only a class that declares reactive_subscribe has
164
+ # the method.
165
+ data.merge!(reactive_subscribe_data) if respond_to?(:reactive_subscribe_data)
158
166
  { data: }
159
167
  end
160
168
 
@@ -547,6 +555,15 @@ module Phlex
547
555
  "submit event this trigger is bound to. Bind the submit op to another event " \
548
556
  "(change/input), or gate it behind a reducer's $ops / reactive_on_complete."
549
557
  end
558
+ # Issue #471: el.click() dispatches the very click this trigger is
559
+ # bound to, and the binding prevents its default — the activation
560
+ # would be lost.
561
+ if event == "click" && self_click?(ops)
562
+ raise ArgumentError,
563
+ "on_client(:click, js.click) on its own trigger cancels itself — the synthetic click " \
564
+ "re-enters this binding, which prevents its default. Bind it to another event " \
565
+ "(\"keydown.space\"), or click another element (js.click(\"#target\"))."
566
+ end
550
567
  shortcut = client_shortcut!(event, shortcut, window:, outside:)
551
568
  keeps_default!("on_client(#{event.inspect})", prevent, shortcut) unless prevent == true
552
569
  window_bound = window || outside || !shortcut.nil?
@@ -1660,6 +1677,15 @@ module Phlex
1660
1677
  record
1661
1678
  end
1662
1679
 
1680
+ # Issue #471: a click op aimed at the trigger. A hand-built chain may
1681
+ # carry Symbol names and keys, or no args Hash.
1682
+ def self_click?(ops)
1683
+ ops.ops.any? do |name, args|
1684
+ name.to_s == "click" && args.is_a?(Hash) &&
1685
+ (args["to"] || args[:to]) == Phlex::Reactive::JS::TRIGGER_SENTINEL
1686
+ end
1687
+ end
1688
+
1663
1689
  # Issue #442: validate on_client's within: — a non-empty CSS selector,
1664
1690
  # on an element-bound binding that can survive a miss.
1665
1691
  def client_within!(event, within, window:, outside:, shortcut:, once:)
@@ -109,7 +109,8 @@ module Phlex
109
109
  def refuse_dormant_presence!
110
110
  raise ArgumentError,
111
111
  "#{name}: reactive_presence cannot be dormant — a dormant root never connects, so its tab " \
112
- "would never join the stream. Drop reactive_dormant on this component."
112
+ "would never join the stream. Drop reactive_dormant (or reactive_root(dormant: true)) on this " \
113
+ "component."
113
114
  end
114
115
  end
115
116
 
@@ -68,7 +68,9 @@ module Phlex
68
68
  skip_all: :@reactive_own_skip_all,
69
69
  skip_actions: :@reactive_own_skip_actions,
70
70
  # Presence roster — reactive_presence (issue #358).
71
- presence: :@reactive_own_presence
71
+ presence: :@reactive_own_presence,
72
+ # Own broadcast stream — reactive_subscribe (issue #474).
73
+ subscribe: :@reactive_own_subscribe
72
74
  }.freeze
73
75
 
74
76
  # The identity-side hot-path memos swept by bump! (see the contract
@@ -92,7 +94,8 @@ module Phlex
92
94
  effects: :reactive_effects_config,
93
95
  skip_all: :reactive_skip_all_authorization?,
94
96
  skip_actions: :reactive_skip_authorization_actions,
95
- presence: :reactive_presence_declaration
97
+ presence: :reactive_presence_declaration,
98
+ subscribe: :reactive_subscribe_declaration
96
99
  }.freeze
97
100
 
98
101
  # The per-class memos the render path reads (Identity's token memos,
@@ -0,0 +1,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phlex
4
+ module Reactive
5
+ module Component
6
+ # The reactive_subscribe macro (issue #474). Not named `Subscribe`: this
7
+ # module is in every reactive component's constant lookup, where a bare
8
+ # noun would shadow a host app's kit component of that name (the #233
9
+ # rule). The behaviour it adds lives in Phlex::Reactive::Subscribe.
10
+ module SubscribeDeclaration
11
+ extend ActiveSupport::Concern
12
+
13
+ # A subscribe name is the stream name's last part: one identifier, no
14
+ # colon (the stream-name separator), no spaces.
15
+ SUBSCRIBE_NAME = /\A[a-z][a-z0-9_]*\z/
16
+
17
+ class_methods do
18
+ # Subscribe every rendered root of this component to a broadcast
19
+ # stream, for as long as the root is on the page:
20
+ #
21
+ # reactive_record :item
22
+ # reactive_subscribe :widget # [item, :widget]
23
+ # reactive_subscribe key: -> { [@item.list, :items] } # parts, run on the component
24
+ # reactive_subscribe key: [:lobby, :feed] # parts, fixed
25
+ #
26
+ # A name or key:, not both. One stream per component (a subclass may
27
+ # declare its own). broadcast_self broadcasts to it.
28
+ def reactive_subscribe(name = nil, key: nil)
29
+ declaration = build_subscribe_declaration(name, key)
30
+ refuse_dormant_subscribe! if reactive_dormant?
31
+ Registry.write_scalar(self, :subscribe, declaration)
32
+ include Phlex::Reactive::Subscribe::ComponentMethods
33
+
34
+ declaration
35
+ end
36
+
37
+ # The Phlex::Reactive::Subscribe::Declaration, or nil.
38
+ def reactive_subscribe_declaration
39
+ Registry.resolve_scalar(self, :subscribe, :reactive_subscribe_declaration)
40
+ end
41
+
42
+ # broadcast_to on the declared stream, so the broadcaster need not
43
+ # repeat the key:
44
+ #
45
+ # Widget.broadcast_self(replace: item) # the key from the Widget built for item
46
+ # Widget.broadcast_self(item, js: js.add_class(...)) # js: has no component: name its subject
47
+ #
48
+ # The key resolves on a component of this class: `subject` (a record,
49
+ # an init-kwargs Hash or a built component), else the verb's payload
50
+ # (built once: the same component is what gets rendered). Every other
51
+ # keyword is broadcast_to's, except each: (the stream is the
52
+ # declared one).
53
+ def broadcast_self(subject = nil, **opts)
54
+ unless reactive_subscribe_declaration
55
+ raise ArgumentError, "#{name}.broadcast_self needs a reactive_subscribe declaration"
56
+ end
57
+ if opts.key?(:each)
58
+ raise ArgumentError, "#{name}.broadcast_self broadcasts to the declared stream: it takes no each: " \
59
+ "(use broadcast_to(each: ...) to fan out)"
60
+ end
61
+
62
+ # Exactly one verb, or broadcast_to's own error before a component
63
+ # is built for nothing.
64
+ verb, = send(:extract_broadcast_verb, opts.slice(*Phlex::Reactive::Streamable::BROADCAST_VERBS.keys))
65
+ # No subject: the verb's payload is it — built here, and handed on
66
+ # built, so broadcast_to does not build it a second time.
67
+ if subject.nil? && verb != :js
68
+ component = subscribe_component(opts[verb])
69
+ opts = opts.merge(verb => component)
70
+ else
71
+ component = subscribe_component(subject, javascript: verb == :js && subject.nil?)
72
+ end
73
+
74
+ broadcast_to(*component.reactive_subscribe_parts, **opts)
75
+ end
76
+
77
+ private
78
+
79
+ def subscribe_component(subject, javascript: false)
80
+ if javascript
81
+ raise ArgumentError,
82
+ "#{name}.broadcast_self(js: ...) has no component to read the stream key from: pass its " \
83
+ "subject first, e.g. broadcast_self(record, js: ...)"
84
+ end
85
+
86
+ component = subject.is_a?(::Phlex::SGML) ? subject : send(:coerce_broadcast_payload, subject)
87
+ return component if component.is_a?(self)
88
+
89
+ raise ArgumentError,
90
+ "#{name}.broadcast_self reads the stream key from a #{name}, got a #{component.class.name}: " \
91
+ "pass the subject first, e.g. broadcast_self(record, replace: other_component)"
92
+ end
93
+
94
+ def build_subscribe_declaration(name, key)
95
+ if name.nil? == key.nil?
96
+ raise ArgumentError, "#{self.name}: reactive_subscribe takes a stream name or key:, exactly one"
97
+ end
98
+ return Phlex::Reactive::Subscribe::Declaration.new(name: nil, key: subscribe_key(key)) if key
99
+
100
+ name = name.to_s
101
+ unless SUBSCRIBE_NAME.match?(name)
102
+ raise ArgumentError,
103
+ "#{self.name}: reactive_subscribe name must be a lowercase identifier (it ends the stream " \
104
+ "name), got #{name.inspect}"
105
+ end
106
+
107
+ Phlex::Reactive::Subscribe::Declaration.new(name: name.to_sym, key: nil)
108
+ end
109
+
110
+ def subscribe_key(key)
111
+ return key if key.respond_to?(:call)
112
+ return key.dup.freeze if key.is_a?(Array) && !key.empty?
113
+
114
+ raise ArgumentError,
115
+ "#{name}: reactive_subscribe key: must be the stream's parts (a non-empty Array) or a " \
116
+ "callable that returns them, got #{key.inspect}"
117
+ end
118
+
119
+ def refuse_dormant_subscribe!
120
+ raise ArgumentError,
121
+ "#{name}: reactive_subscribe cannot be dormant — a dormant root never connects, so it would " \
122
+ "never subscribe. Drop reactive_dormant (or reactive_root(dormant: true)) on this component."
123
+ end
124
+ end
125
+
126
+ # ActiveSupport::Concern's bookkeeping on this module, sealed now that
127
+ # the body has loaded (zoolutions/phlex-reactive#364).
128
+ Phlex::Reactive::Shareable.seal_concern(self)
129
+ end
130
+ end
131
+ end
132
+ end
@@ -147,6 +147,7 @@ module Phlex
147
147
  include Identity
148
148
  include Lazy
149
149
  include PresenceDeclaration
150
+ include SubscribeDeclaration
150
151
 
151
152
  # ActiveSupport::Concern's bookkeeping on this module, sealed now that
152
153
  # the body has loaded (zoolutions/phlex-reactive#364).
@@ -85,6 +85,7 @@ module Phlex
85
85
  id_check(components),
86
86
  authorization_check(components),
87
87
  dormant_check(components),
88
+ subscribe_check(components),
88
89
  *early_pin_check(components)
89
90
  ].compact
90
91
  end
@@ -286,6 +287,32 @@ module Phlex
286
287
  "your entrypoint, before any controller loads:\n import \"phlex/reactive/early\"")
287
288
  end
288
289
 
290
+ # Subscribing components (issue #474): reactive_subscribe needs pgbus with
291
+ # reactive Streams (a hard failure: the root raises at render without it)
292
+ # and pgbus's client element on the page — nothing else imports
293
+ # pgbus/stream_source_element when no view renders pgbus_stream_from. The
294
+ # client half is ADVISORY: the import may live in a file not scanned. No
295
+ # line at all when nothing subscribes.
296
+ def subscribe_check(components, capable: Phlex::Reactive::Subscribe.capable?, client: imports_pgbus_client?)
297
+ subscribing = components.select do
298
+ it.respond_to?(:reactive_subscribe_declaration) && it.reactive_subscribe_declaration
299
+ end
300
+ return if subscribing.empty?
301
+
302
+ label = "#{subscribing.size} subscribing #{subscribing.one? ? "component" : "components"} " \
303
+ "(#{subscribing.map(&:name).join(", ")})"
304
+ unless capable
305
+ return Check.new(:fail, "#{label}, but pgbus with reactive Streams is not loaded", name: :subscribe,
306
+ fix: "reactive_subscribe needs pgbus (its roots raise at render without it). Add pgbus, or drop the " \
307
+ "declaration and render turbo_stream_from with the same key next to the component.")
308
+ end
309
+ return Check.new(:ok, "#{label}; pgbus's client is imported", name: :subscribe) if client
310
+
311
+ Check.new(:unknown, "#{label}, but no import of pgbus/stream_source_element was found", name: :subscribe,
312
+ fix: "A subscribing root mints a <pgbus-stream-source>, which connects only once pgbus's client " \
313
+ "element is defined. Add to your entrypoint:\n import \"pgbus/stream_source_element\"")
314
+ end
315
+
289
316
  # Every import map the app registers must pin phlex/reactive/early when a
290
317
  # dormant root exists (issue #307): a map without the pin cannot resolve
291
318
  # the specifier, so the import fails on the pages that map serves. One
@@ -334,18 +361,28 @@ module Phlex
334
361
  app/javascript/application.js
335
362
  ].freeze
336
363
  EARLY_IMPORT = %r{import\s+["']phlex/reactive/early["']}
364
+ # pgbus's client element, imported (statically or dynamically), or a
365
+ # helper that emits the import (issue #474). A bare mention (an import
366
+ # map pin) is not an import.
367
+ PGBUS_CLIENT = %r{\bimport\b[^;\n]*?["']pgbus/stream_source_element["']|\b(?:pgbus|turbo)_stream_from\b}
337
368
  # Closed comments, which may span lines: HTML, JS block and ERB.
338
369
  BLOCK_COMMENT = %r{<!--.*?-->|/\*.*?\*/|<%#.*?%>}m
339
370
  # What precedes the import on its line when it is commented out: a //
340
- # (not the one in a URL), an unclosed /*, or a block-comment's leading *.
341
- COMMENT_BEFORE = %r{(?<!:)//|/\*|\A\s*\*}
371
+ # (not the one in a URL: after a scheme's colon, or a protocol-relative
372
+ # one opening a quoted value), an unclosed /*, or a block-comment's
373
+ # leading *.
374
+ COMMENT_BEFORE = %r{(?<![:"'=])//|/\*|\A\s*\*}
342
375
 
343
376
  # Is there an `import "phlex/reactive/early"` in `source` that actually
344
377
  # runs? Closed comments are dropped first, then each line is read, so a
345
378
  # commented-out import doesn't count.
346
- def self.imports_early_source?(source)
379
+ def self.imports_early_source?(source) = imports_source?(source, EARLY_IMPORT)
380
+
381
+ # Is there a match for `pattern` in `source` that is not commented out?
382
+ # Closed comments are dropped first, then each line is read.
383
+ def self.imports_source?(source, pattern)
347
384
  source.gsub(BLOCK_COMMENT, "").each_line.any? do
348
- (match = EARLY_IMPORT.match(it)) && !match.pre_match.match?(COMMENT_BEFORE)
385
+ (match = pattern.match(it)) && !match.pre_match.match?(COMMENT_BEFORE)
349
386
  end
350
387
  end
351
388
 
@@ -502,6 +539,16 @@ module Phlex
502
539
  " (#{early})"
503
540
  end
504
541
 
542
+ # Does any app JavaScript, view or component import pgbus's client
543
+ # element (or render a helper that emits that import)?
544
+ def imports_pgbus_client?
545
+ (stimulus_registration_files | early_import_candidates).any? do
546
+ Doctor.imports_source?(early_source(it), PGBUS_CLIENT)
547
+ rescue StandardError
548
+ false
549
+ end
550
+ end
551
+
505
552
  def dormant_components(components)
506
553
  components.select { it.respond_to?(:reactive_dormant?) && it.reactive_dormant? }
507
554
  end
@@ -21,11 +21,11 @@ module Phlex
21
21
  # default entry name the same features —
22
22
  # spec/phlex/engine_client_pin_spec.rb fails when they disagree.
23
23
  CLIENT_FEATURES = %w[
24
- persist defer form bindings compute sortable drag presence countdown effects hints devtools
24
+ persist defer form bindings compute sortable drag presence subscribe countdown effects hints devtools
25
25
  ].freeze
26
- # (Gzipped, bun zlib level 9, KB = 1,024 B: the default file 39.5 KB; the core 17.9 KB;
26
+ # (Gzipped, bun zlib level 9, KB = 1,024 B: the default file 42.4 KB; the core 19.6 KB;
27
27
  # persist 3.2, defer 2.9, form 1.2, bindings 8.0, compute 2.0, sortable
28
- # 3.1, drag 3.5, presence 1.3, countdown 0.9, effects 1.7, hints 0.9, devtools 1.5 KB. spec/javascript/bundle_budget.test.js
28
+ # 3.1, drag 3.5, presence 1.5, subscribe 0.9, countdown 0.9, effects 1.7, hints 0.9, devtools 1.5 KB. spec/javascript/bundle_budget.test.js
29
29
  # is the source of truth and holds a ratchet on each.)
30
30
 
31
31
  # Mount POST /reactive/actions -> Phlex::Reactive::ActionsController#create
@@ -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