reactive_component 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7f5fd3fc0f10d7fd47f43039a0ba4b58824915989d618d97e32c48b09397ceed
4
+ data.tar.gz: 4755871d523443f453f870939d01183bdd165e1f39f97092f7c87c0a367c89fe
5
+ SHA512:
6
+ metadata.gz: cc558b9d15841f9cab6c359450f3324c4f98a38078240437e951a60699e3eeb33cd58acd057622926b62c094fc9b1d68aa58b971fa70efa779a22d8bc83fbe81
7
+ data.tar.gz: 1a785c4e6d55be8b767d90b2a483eb5415d684da8513cf1a96c6abdb8811273a6bc5890bcd08f8ce65a6b4cd3043dfc0a8ed2f8e6e2c9d9f5a5522b23f1efd8f
data/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-03-15
4
+
5
+ ### Added
6
+ - Initial extraction of reactive component system
7
+ - Core `ReactiveComponent` concern with DSL: `subscribes_to`, `broadcasts`, `live_action`, `client_state`
8
+ - ERB-to-JavaScript compiler pipeline for client-side re-rendering
9
+ - ActionCable channel with configurable `filter_callback` for broadcast filtering
10
+ - Actions controller for secure server-side action invocation
11
+ - Stimulus controller and utilities for client-side rendering
12
+ - Rails Engine with automatic route mounting
13
+ - Multi-Rails version support (7.1, 7.2, 8.0)
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Przemyslaw Lusar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ReactiveComponent
4
+ class Channel < ActionCable::Channel::Base
5
+ mattr_accessor :compress, default: false
6
+
7
+ class_attribute :filter_callback, default: nil
8
+
9
+ def subscribed
10
+ stream_name = verified_stream_name
11
+ if stream_name
12
+ stream_from stream_name
13
+ else
14
+ reject
15
+ end
16
+ end
17
+
18
+ def unsubscribed
19
+ stop_all_streams
20
+ end
21
+
22
+ def request_update(data)
23
+ component_class = data["component"].constantize
24
+ params = data["params"] || {}
25
+
26
+ model_class = component_class.live_model_class
27
+ record_id = data["record_id"] || params.delete("record_id")
28
+ record = model_class.find_by(id: record_id)
29
+ return unless record
30
+
31
+ if data["record_id"].present?
32
+ if record_matches?(record, params)
33
+ transmit({"action" => "render", "data" => component_class.build_data(record)})
34
+ else
35
+ transmit({"action" => "remove", "dom_id" => data["dom_id"]})
36
+ end
37
+ else
38
+ result = component_class.build_data(record, **params.symbolize_keys)
39
+ transmit({"action" => "render", "data" => result})
40
+ end
41
+ end
42
+
43
+ private
44
+
45
+ def record_matches?(record, params)
46
+ return true unless self.class.filter_callback
47
+
48
+ self.class.filter_callback.call(record, params)
49
+ end
50
+
51
+ def verified_stream_name
52
+ Turbo::StreamsChannel.verified_stream_name(params[:signed_stream_name])
53
+ rescue
54
+ nil
55
+ end
56
+
57
+ class << self
58
+ def broadcast_data(streamables, action:, data:)
59
+ signed = Turbo::StreamsChannel.signed_stream_name(streamables)
60
+ stream_name = Turbo::StreamsChannel.verified_stream_name(signed)
61
+
62
+ payload = {action: action, data: data}
63
+
64
+ if compress
65
+ json = ActiveSupport::JSON.encode(payload)
66
+ ActionCable.server.broadcast(stream_name, {z: Base64.strict_encode64(ActiveSupport::Gzip.compress(json))})
67
+ else
68
+ ActionCable.server.broadcast(stream_name, payload)
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ReactiveComponent
4
+ class ActionsController < ActionController::Base
5
+ def create
6
+ payload = verify_token!.symbolize_keys
7
+ component_class = payload[:c].constantize
8
+ record = payload[:m].constantize.find(payload[:r])
9
+
10
+ component_class.execute_action(
11
+ params[:action_name],
12
+ record,
13
+ params.fetch(:params, {}).permit!.to_h
14
+ )
15
+
16
+ head :ok
17
+ end
18
+
19
+ private
20
+
21
+ def verify_token!
22
+ Rails.application.message_verifier(:reactive_component_action)
23
+ .verify(params[:token], purpose: :reactive_component_action)
24
+ rescue ActiveSupport::MessageVerifier::InvalidSignature
25
+ raise ActionController::RoutingError, "Not found"
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,224 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+ import { createConsumer } from "@rails/actioncable"
3
+ import { compileTemplate, decompress, morphElement, buildActionBody, routeMessage } from "reactive_component/lib/reactive_renderer_utils"
4
+
5
+ const consumer = createConsumer()
6
+ const log = (...args) => {
7
+ if (localStorage.getItem("devToolbar:debug") !== "false") {
8
+ console.log("[reactive-renderer]", ...args)
9
+ }
10
+ }
11
+
12
+ function findSubscription(streamValue) {
13
+ const identifier = JSON.stringify({ channel: "ReactiveComponent::Channel", signed_stream_name: streamValue })
14
+ return consumer.subscriptions.subscriptions.find(s => s.identifier === identifier)
15
+ }
16
+
17
+ function subscribe(streamValue, controller) {
18
+ let sub = findSubscription(streamValue)
19
+
20
+ if (!sub) {
21
+ sub = consumer.subscriptions.create(
22
+ { channel: "ReactiveComponent::Channel", signed_stream_name: streamValue },
23
+ {
24
+ received: async (message) => {
25
+ const decoded = message.z ? await decompress(message.z) : message
26
+ for (const handler of sub.handlers) {
27
+ handler.handleMessage(decoded)
28
+ }
29
+ }
30
+ }
31
+ )
32
+ sub.handlers = new Set()
33
+ }
34
+ sub.handlers.add(controller)
35
+ }
36
+
37
+ function unsubscribe(streamValue, controller) {
38
+ const sub = findSubscription(streamValue)
39
+ if (!sub) return
40
+
41
+ sub.handlers.delete(controller)
42
+ if (sub.handlers.size === 0) {
43
+ consumer.subscriptions.remove(sub)
44
+ }
45
+ }
46
+
47
+ export default class extends Controller {
48
+ static values = {
49
+ template: String,
50
+ templateId: String,
51
+ stream: String,
52
+ actionUrl: String,
53
+ actionToken: String,
54
+ state: { type: Object, default: {} },
55
+ data: { type: Object, default: {} },
56
+ strategy: { type: String, default: "push" },
57
+ component: { type: String, default: "" },
58
+ params: { type: Object, default: {} },
59
+ fieldMap: { type: Object, default: {} }
60
+ }
61
+
62
+ connect() {
63
+ this.clientState = { ...this.stateValue }
64
+ this.lastServerData = Object.keys(this.dataValue).length > 0 ? this.dataValue : null
65
+
66
+ const encoded = this.resolveTemplate()
67
+ this.renderFn = encoded ? compileTemplate(encoded) : null
68
+
69
+ if (!this.renderFn) {
70
+ if (!this.streamValue) return
71
+ }
72
+
73
+ if (!this.streamValue) return
74
+
75
+ subscribe(this.streamValue, this)
76
+ }
77
+
78
+ disconnect() {
79
+ if (this.streamValue) {
80
+ unsubscribe(this.streamValue, this)
81
+ }
82
+ }
83
+
84
+ resolveTemplate() {
85
+ if (this.hasTemplateValue) return this.templateValue
86
+
87
+ if (this.hasTemplateIdValue) {
88
+ const el = document.getElementById(this.templateIdValue)
89
+ if (el) return el.textContent
90
+ }
91
+
92
+ return null
93
+ }
94
+
95
+ handleMessage(message) {
96
+ const route = routeMessage(message, this.element.id, this.strategyValue)
97
+
98
+ switch (route.type) {
99
+ case "render":
100
+ log("render", this.element.id, route.data)
101
+ this.lastServerData = route.data
102
+ if (this.renderFn) this.render({ ...route.data, ...this.clientState })
103
+ break
104
+
105
+ case "request_update":
106
+ log("update", this.element.id, { action: message.action, strategy: "notify" })
107
+ this.requestUpdate()
108
+ break
109
+
110
+ case "update":
111
+ log("update", this.element.id, route.data)
112
+ this.lastServerData = route.data
113
+ if (this.renderFn) this.render({ ...route.data, ...this.clientState })
114
+ this.element.dispatchEvent(new CustomEvent("reactive-renderer:updated", {
115
+ bubbles: true,
116
+ detail: { data: route.data }
117
+ }))
118
+ break
119
+
120
+ case "remove":
121
+ case "destroy":
122
+ this.element.remove()
123
+ break
124
+ }
125
+ }
126
+
127
+ requestUpdate() {
128
+ if (this._updateTimer) clearTimeout(this._updateTimer)
129
+
130
+ this._updateTimer = setTimeout(() => {
131
+ this._updateTimer = null
132
+ const sub = findSubscription(this.streamValue)
133
+ if (!sub) return
134
+
135
+ sub.perform("request_update", {
136
+ component: this.componentValue,
137
+ record_id: this.dataValue?.id,
138
+ dom_id: this.element.id,
139
+ params: this.paramsValue
140
+ })
141
+ }, 50)
142
+ }
143
+
144
+ render(data) {
145
+ const newHtml = this.renderFn(data)
146
+ this.morph(newHtml)
147
+ }
148
+
149
+ performAction(event) {
150
+ event.preventDefault()
151
+ event.stopPropagation()
152
+
153
+ const actionName = event.params.action
154
+ if (!actionName || !this.hasActionUrlValue || !this.hasActionTokenValue) return
155
+
156
+ // --- Optimistic update ---
157
+ const optimisticExpr = event.params.optimistic
158
+ let rollbackData = null
159
+
160
+ if (optimisticExpr && this.lastServerData && this.renderFn && this.fieldMapValue) {
161
+ const dataKey = this.fieldMapValue[optimisticExpr]
162
+ if (dataKey && dataKey in this.lastServerData) {
163
+ rollbackData = { ...this.lastServerData }
164
+ this.lastServerData[dataKey] = !this.lastServerData[dataKey]
165
+ this.render({ ...this.lastServerData, ...this.clientState })
166
+ }
167
+ }
168
+ // --- End optimistic ---
169
+
170
+ const formData = event.type === "submit" ? new FormData(event.target) : null
171
+ const { body, redirect } = buildActionBody(actionName, this.actionTokenValue, event.params, formData)
172
+
173
+ fetch(this.actionUrlValue, {
174
+ method: "POST",
175
+ headers: {
176
+ "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content,
177
+ },
178
+ body
179
+ }).then(response => {
180
+ if (!response.ok && rollbackData) {
181
+ this.lastServerData = rollbackData
182
+ this.render({ ...this.lastServerData, ...this.clientState })
183
+ }
184
+ if (redirect && response.ok) {
185
+ Turbo.visit(redirect)
186
+ } else if (response.ok && response.headers.get("content-type")?.includes("text/html")) {
187
+ return response.text()
188
+ }
189
+ }).then(html => {
190
+ if (html) this.morph(html)
191
+ }).catch(() => {
192
+ if (rollbackData) {
193
+ this.lastServerData = rollbackData
194
+ this.render({ ...this.lastServerData, ...this.clientState })
195
+ }
196
+ })
197
+ }
198
+
199
+ setState(event) {
200
+ const updates = { ...event.params }
201
+ delete updates.action
202
+
203
+ if (updates.exclusive) {
204
+ delete updates.exclusive
205
+ const container = this.element.parentElement
206
+ if (container) {
207
+ container.querySelectorAll(`:scope > [data-controller~="reactive-renderer"]`).forEach(el => {
208
+ if (el === this.element) return
209
+ const ctrl = this.application.getControllerForElementAndIdentifier(el, "reactive-renderer")
210
+ if (!ctrl?.clientState) return
211
+ for (const key of Object.keys(updates)) {
212
+ if (ctrl.clientState[key]) ctrl.clientState[key] = false
213
+ }
214
+ })
215
+ }
216
+ }
217
+
218
+ Object.assign(this.clientState, updates)
219
+ }
220
+
221
+ morph(newHtml) {
222
+ morphElement(this.element, newHtml)
223
+ }
224
+ }
@@ -0,0 +1,99 @@
1
+ const templateCache = new Map()
2
+
3
+ export function isBase64(str) {
4
+ return /^[A-Za-z0-9+/\n]+=*$/.test(str.trim())
5
+ }
6
+
7
+ export function compileTemplate(source) {
8
+ if (templateCache.has(source)) return templateCache.get(source)
9
+
10
+ try {
11
+ const body = isBase64(source) ? atob(source) : source
12
+ const fn = new Function("data", body)
13
+ templateCache.set(source, fn)
14
+ return fn
15
+ } catch (e) {
16
+ console.log("[reactive-renderer] ERROR compiling template:", e)
17
+ return null
18
+ }
19
+ }
20
+
21
+ export function clearTemplateCache() {
22
+ templateCache.clear()
23
+ }
24
+
25
+ export async function decompress(base64) {
26
+ const bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0))
27
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"))
28
+ return new Response(stream).json()
29
+ }
30
+
31
+ export function morphElement(element, newHtml) {
32
+ const parser = new DOMParser()
33
+ const doc = parser.parseFromString(`<div>${newHtml}</div>`, "text/html")
34
+ const newContent = doc.body.firstChild
35
+
36
+ if (typeof Idiomorph !== "undefined") {
37
+ Idiomorph.morph(element, newContent, {
38
+ morphStyle: "innerHTML",
39
+ ignoreActiveValue: true
40
+ })
41
+ } else {
42
+ element.innerHTML = newContent.innerHTML
43
+ }
44
+
45
+ element.classList.remove("reactive-morph-flash")
46
+ void element.offsetWidth
47
+ element.classList.add("reactive-morph-flash")
48
+ }
49
+
50
+ export function buildActionBody(actionName, actionToken, stimulusParams, formData) {
51
+ const body = new URLSearchParams({
52
+ token: actionToken,
53
+ action_name: actionName
54
+ })
55
+
56
+ const params = { ...stimulusParams }
57
+ delete params.action
58
+ const redirect = params.redirect
59
+ delete params.redirect
60
+
61
+ for (const [key, value] of Object.entries(params)) {
62
+ const snakeKey = key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
63
+ body.append(`params[${snakeKey}]`, value)
64
+ }
65
+
66
+ if (formData) {
67
+ for (const [key, value] of formData.entries()) {
68
+ body.append(`params[${key}]`, value)
69
+ }
70
+ }
71
+
72
+ return { body, redirect }
73
+ }
74
+
75
+ export function routeMessage(message, elementId, strategy) {
76
+ const { action, data } = message
77
+
78
+ if (action === "render" && data?.dom_id === elementId) {
79
+ return { type: "render", data }
80
+ }
81
+
82
+ if (strategy === "notify" && (action === "update" || action === "destroy")) {
83
+ return { type: "request_update" }
84
+ }
85
+
86
+ if (action === "update" && data?.dom_id === elementId) {
87
+ return { type: "update", data }
88
+ }
89
+
90
+ if (action === "remove" && (message.dom_id || data?.dom_id) === elementId) {
91
+ return { type: "remove" }
92
+ }
93
+
94
+ if (action === "destroy" && data?.dom_id === elementId) {
95
+ return { type: "destroy" }
96
+ }
97
+
98
+ return { type: "ignore" }
99
+ }
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ pin_all_from ReactiveComponent::Engine.root.join("app/javascript/reactive_component"),
4
+ under: "reactive_component"
data/config/routes.rb ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ ReactiveComponent::Engine.routes.draw do
4
+ post "actions", to: "actions#create", as: :reactive_component_actions
5
+ end