Module: Phlex::Reactive

Defined in:
lib/phlex/reactive.rb,
lib/phlex/reactive/engine.rb,
lib/phlex/reactive/version.rb,
lib/phlex/reactive/response.rb,
lib/phlex/reactive/component.rb,
lib/phlex/reactive/streamable.rb,
app/controllers/phlex/reactive/actions_controller.rb,
lib/generators/phlex/reactive/install/install_generator.rb,
lib/generators/phlex/reactive/component/component_generator.rb

Overview

phlex-reactive: reactive Phlex components for Rails.

Two cooperating mixins, one client runtime, one endpoint:

* Phlex::Reactive::Streamable — gives a component a stable `id` and class
  methods to render itself as a Turbo Stream (`.replace`, `.append`, ...)
  and to broadcast itself (`.broadcast_replace_to`, ...). The server->client
  half (controller responses + background broadcasts).

* Phlex::Reactive::Component — declares client-invokable `action`s and
  emits a signed identity token + the wiring the generic `reactive`
  Stimulus controller needs. The client->server half (clicks, form input).

Both halves converge on ONE re-render unit: the component, targeted by its ‘id`. See the README for the mental model and examples.

Defined Under Namespace

Modules: Component, Generators, Streamable Classes: ActionsController, Engine, Error, InvalidToken, Response

Constant Summary collapse

IDENTITY_PURPOSE =

Purpose string bound into every identity token’s signature so a token minted for phlex-reactive can’t be replayed against another verifier use.

"phlex-reactive/identity"
ACTIONS_CONTROLLER =

The controller a correctly-mounted action path resolves to. Used by the route guard below.

"phlex/reactive/actions"
VERSION =
"0.2.9"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.action_pathObject



69
70
71
# File 'lib/phlex/reactive.rb', line 69

def action_path
  @action_path ||= "/reactive/actions"
end

.authorization_errorsObject

Exception classes the action endpoint renders as 403. Append your authorization library’s error (Pundit::NotAuthorizedError, ActionPolicy::Unauthorized, …).



61
62
63
# File 'lib/phlex/reactive.rb', line 61

def authorization_errors
  @authorization_errors
end

.base_controller_nameObject



101
102
103
# File 'lib/phlex/reactive.rb', line 101

def base_controller_name
  @base_controller_name ||= "ActionController::Base"
end

.flash_targetObject

DOM id of the host-app container a Response#flash appends into. Default “flash”; override to match your layout’s flash region.



83
84
85
# File 'lib/phlex/reactive.rb', line 83

def flash_target
  @flash_target ||= "flash"
end

.rendererObject



77
78
79
# File 'lib/phlex/reactive.rb', line 77

def renderer
  @renderer ||= defined?(::ActionController::Base) ? ::ActionController::Base : nil
end

.verifierObject



73
74
75
# File 'lib/phlex/reactive.rb', line 73

def verifier
  @verifier ||= default_verifier
end

Class Method Details

.action_route_ok?(path = action_path) ⇒ Boolean

True when a POST to ‘path` resolves to the gem’s ActionsController. A host catch-all route (match “*path”, …) appended above the engine’s route SHADOWS it, so every reactive POST 404s and none of the controller runs —the opaque “is the endpoint even mounted?” failure (issue #26). A false here is the signal. Returns false (not raise) when nothing matches.

Returns:

  • (Boolean)


145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/phlex/reactive.rb', line 145

def action_route_ok?(path = action_path)
  return false unless defined?(::Rails) && ::Rails.application

  # At after_initialize (when the boot guard runs) the host's routes may not
  # be drawn yet, so recognize_path would see an incomplete set and report a
  # false shadow. Force-load routes first (idempotent — no-op if already
  # loaded), so the check is correct whether it runs at boot or at runtime.
  ensure_routes_loaded
  recognized = ::Rails.application.routes.recognize_path(path, method: :post)
  recognized[:controller] == ACTIONS_CONTROLLER
rescue ActionController::RoutingError, ActiveRecord::RecordNotFound
  false
end

.base_controllerObject



105
106
107
# File 'lib/phlex/reactive.rb', line 105

def base_controller
  base_controller_name.constantize
end

.current_connection_idObject

The acting client’s SSE connection id during an action, or nil. Set by the ActionsController from the X-Pgbus-Connection header. A component action passes ‘exclude: Phlex::Reactive.current_connection_id` (or the `reactive_connection_id` helper) to suppress the actor’s own broadcast echo.



124
125
126
# File 'lib/phlex/reactive.rb', line 124

def current_connection_id
  Thread.current[:phlex_reactive_connection_id]
end

.flash_builderObject

A Turbo::Streams::TagBuilder bound to an off-request view context, used to build standalone streams (e.g. a Response flash append) not tied to a specific component’s id.



97
98
99
# File 'lib/phlex/reactive.rb', line 97

def flash_builder
  ::Turbo::Streams::TagBuilder.new(renderer.new.view_context)
end

.render(component) ⇒ Object

Render a Phlex component to HTML with a full (off-request) view context.



90
91
92
# File 'lib/phlex/reactive.rb', line 90

def render(component)
  renderer.render(component, layout: false)
end

.sign(payload) ⇒ Object

Signs a payload hash into an identity token.



115
116
117
# File 'lib/phlex/reactive.rb', line 115

def sign(payload)
  verifier.generate(payload, purpose: IDENTITY_PURPOSE)
end

.verify(token) ⇒ Object

Returns the verified payload hash, or nil if the token is invalid.



110
111
112
# File 'lib/phlex/reactive.rb', line 110

def verify(token)
  verifier.verified(token, purpose: IDENTITY_PURPOSE)
end

.warn_unless_action_route_mounted!(path: action_path, logger: default_logger) ⇒ Object

Log a clear warning (once, at boot) when the action path doesn’t resolve to the gem controller — pointing at the catch-all shadow rather than leaving an adopter to guess. Called from the engine’s after_initialize.



162
163
164
165
166
167
168
169
170
171
172
# File 'lib/phlex/reactive.rb', line 162

def warn_unless_action_route_mounted!(path: action_path, logger: default_logger)
  return if action_route_ok?(path)
  return unless logger

  logger.warn(
    "[phlex-reactive] POST #{path} does not resolve to #{ACTIONS_CONTROLLER}. " \
    "A host catch-all route (e.g. match \"*path\", ...) likely shadows it, so reactive " \
    "actions will 404. Exempt #{path.sub(%r{\A/}, "")} from the catch-all, or set " \
    "Phlex::Reactive.action_path to an unshadowed path. See the README integration section."
  )
end

.with_connection_id(connection_id) ⇒ Object



128
129
130
131
132
133
134
# File 'lib/phlex/reactive.rb', line 128

def with_connection_id(connection_id)
  previous = Thread.current[:phlex_reactive_connection_id]
  Thread.current[:phlex_reactive_connection_id] = connection_id.presence
  yield
ensure
  Thread.current[:phlex_reactive_connection_id] = previous
end