rage-pulse 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.
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Pulse::Cable::ViewChannel < Rage::Cable::Channel
4
+ def subscribed
5
+ Fiber[:__pulse_state] = Pulse::State.new(->(payload) { transmit(payload) })
6
+ end
7
+
8
+ def unsubscribed
9
+ Pulse.__state.reload
10
+ end
11
+
12
+ # Single client -> server entrypoint. `type` distinguishes a page navigation from an
13
+ # event dispatched to a specific component.
14
+ def receive(data)
15
+ case data["type"]
16
+ when "navigate"
17
+ update_page(data)
18
+ navigate(data)
19
+ when "event"
20
+ handle_event(data)
21
+ when "page"
22
+ update_page(data)
23
+ end
24
+ end
25
+
26
+ private
27
+
28
+ # Dispatch an event to the component.
29
+ def handle_event(data)
30
+ pulse_id, event, event_data = data["id"].to_i, data["event"].to_sym, data["data"]
31
+ component = Pulse.__state.interactive_components[pulse_id]
32
+
33
+ unless component
34
+ Rage.logger.debug("Couldn't find a component to handle event", component_id: pulse_id, event:)
35
+ return
36
+ end
37
+
38
+ Pulse.__state.server_events.with_batched_events do
39
+ component.__handle_event(event, event_data)
40
+ end
41
+ end
42
+
43
+ # Render a root component replacing the whole page.
44
+ def navigate(data)
45
+ Pulse.__state.reload
46
+
47
+ env = build_request(data)
48
+ _, response_headers, response_body = app.call(env)
49
+
50
+ if (location_url = response_headers["location"])
51
+ transmit(action: "navigate", url: location_url)
52
+ else
53
+ transmit(action: "update", html: response_body[0])
54
+ end
55
+ end
56
+
57
+ def update_page(data)
58
+ state = Pulse.__state
59
+
60
+ if (local_storage_snapshot = data["local_storage"])
61
+ state.local_storage_snapshot = local_storage_snapshot
62
+ end
63
+
64
+ if (query_snapshot = data["query"])
65
+ state.query_snapshot = query_snapshot
66
+ end
67
+
68
+ if (url = data["url"])
69
+ state.url = url
70
+ end
71
+ end
72
+
73
+ def app
74
+ @app ||= Rage.application
75
+ end
76
+
77
+ # Build the Rack env hash representing the request
78
+ def build_request(data)
79
+ request_env = env.dup
80
+ request_env["rack.upgrade?"] = request_env["rack.upgrade"] = request_env["rage.request_id"] = nil
81
+
82
+ request_env["PATH_INFO"] = data["url"]
83
+ request_env["REQUEST_METHOD"] = data["method"] || "GET"
84
+ request_env["QUERY_STRING"] = data["query"] || ""
85
+
86
+ if (body = data["body"])
87
+ request_env["rack.input"] = StringIO.new(body)
88
+ request_env["IODINE_HAS_BODY"] = true
89
+ request_env["CONTENT_TYPE"] = data["contentType"]
90
+ request_env["CONTENT_LENGTH"] = body.bytesize.to_s
91
+ end
92
+
93
+ request_env
94
+ end
95
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Pulse::Component < Phlex::HTML
4
+ include Pulse::Scripts
5
+ include Pulse::Watching
6
+ include Pulse::Fingerprint
7
+ include Pulse::Marker
8
+
9
+ # @private
10
+ def self.__event_handlers
11
+ @__event_handlers ||= Set.new(public_instance_methods(false) - [:view_template])
12
+ end
13
+
14
+ # @private
15
+ # @param event [Symbol]
16
+ # @param data [Hash, nil] the event data (input value, key, form fields)
17
+ def __handle_event(event, data)
18
+ unless self.class.__event_handlers.include?(event)
19
+ Rage.logger.debug("Unknown event received", event:)
20
+ return
21
+ end
22
+
23
+ @_streamed = false
24
+
25
+ if method(event).arity == 1
26
+ event_payload = Pulse::Event.new(data || {})
27
+ public_send(event, event_payload)
28
+ else
29
+ public_send(event)
30
+ end
31
+
32
+ replace unless @_streamed
33
+ ensure
34
+ @_streamed = false
35
+ end
36
+
37
+ # Re-render this component and morph it in place on the client.
38
+ def replace
39
+ @_streamed = true
40
+ Pulse.__state.server_events.replace_component(self)
41
+ end
42
+
43
+ # Render this component and append it to the element matching a CSS selector.
44
+ def append(to:)
45
+ @_streamed = true
46
+ Pulse.__state.server_events.append_component(self, to)
47
+ end
48
+
49
+ # Render this component and prepend it to the element matching a CSS selector.
50
+ def prepend(to:)
51
+ @_streamed = true
52
+ Pulse.__state.server_events.prepend_component(self, to)
53
+ end
54
+
55
+ # Remove this component's element from the client and drop it from the registry.
56
+ def remove
57
+ @_streamed = true
58
+ __cleanup_subscriptions
59
+ @__parent&.__children&.delete(@__identity)
60
+ Pulse.__state.server_events.remove_component(pulse_id)
61
+ end
62
+
63
+ def page
64
+ Pulse.__state.page
65
+ end
66
+
67
+ def __pulse_dump(is_replace = false)
68
+ # Phlex normally refuses to render an instance more than once
69
+ @_state = nil
70
+ @__is_replace = is_replace
71
+ call { div(data_pulse_stub: true) }
72
+ ensure
73
+ @__is_replace = false
74
+ end
75
+
76
+ protected
77
+
78
+ attr_accessor :__parent, :__children, :__cached_fingerprint, :__identity
79
+
80
+ class << self
81
+ attr_accessor :__root_validated
82
+ end
83
+
84
+ def pulse_id
85
+ @pulse_id ||= object_id.to_s
86
+ end
87
+
88
+ def render(component, key: nil, &block)
89
+ return super(component, &block) unless Pulse.__state.live? && component.is_a?(Pulse::Component)
90
+
91
+ identity = [component.class, key]
92
+ existing_child = @__children&.dig(identity)
93
+
94
+ unless existing_child
95
+ store_child_component(component, identity)
96
+ return super(component, &block)
97
+ end
98
+
99
+ if existing_child.__cached_fingerprint == component.fingerprint
100
+ existing_child.__mark
101
+ div(id: existing_child.pulse_id, data_pulse_stub: true)
102
+
103
+ if block
104
+ # send blocks as distinct patches
105
+ @__pending_pulse_id = true
106
+ Pulse.__state.server_events.replace_html(capture(&block))
107
+ end
108
+ else
109
+ existing_child.__cleanup_subscriptions
110
+ store_child_component(component, identity)
111
+
112
+ component.__children = existing_child.__children
113
+ existing_child.__children = nil
114
+
115
+ super(component, &block)
116
+ end
117
+ end
118
+
119
+ def around_template
120
+ validate_root_element
121
+ @__pending_pulse_id = true
122
+ super
123
+ __activate_subscriptions
124
+ cleanup_child_components
125
+ ensure
126
+ @__cached_fingerprint = fingerprint
127
+ end
128
+
129
+ def validate_root_element
130
+ if (Rage.env.development? || Rage.env.test?) && !self.class.__root_validated
131
+ Pulse::ComponentRootValidator.validate!(self.class)
132
+ self.class.__root_validated = true
133
+ end
134
+ end
135
+
136
+ def store_child_component(component, identity)
137
+ (@__children ||= {})[identity] = component.tap(&:__mark)
138
+ component.__identity = identity
139
+ component.__parent = self
140
+ end
141
+
142
+ def cleanup_child_components
143
+ @__children&.delete_if do |_, component|
144
+ unless component.__marked?
145
+ should_delete = true
146
+ component.__cleanup_subscriptions
147
+ end
148
+ component.__unmark
149
+
150
+ should_delete
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,240 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "phlex"
4
+ require "prism"
5
+
6
+ class Pulse::ComponentRootValidator < Prism::Visitor
7
+ PHLEX_TAG_METHODS = Set.new(
8
+ Phlex::HTML::StandardElements.instance_methods(false) +
9
+ Phlex::HTML::VoidElements.instance_methods(false) +
10
+ [:tag]
11
+ ).freeze
12
+ NON_ROOT_TAG_METHODS = Set.new(%i[head meta title style script]).freeze
13
+ ROOT_TAG_METHODS = (PHLEX_TAG_METHODS - NON_ROOT_TAG_METHODS).freeze
14
+ OUTPUT_METHODS = (PHLEX_TAG_METHODS + %i[comment doctype plain raw render whitespace]).freeze
15
+
16
+ Diagnostic = Data.define(:path, :line, :scope, :roots, :unwrapped_output, :early_returns) do
17
+ def message
18
+ "#{path}:#{line}: #{problem}"
19
+ end
20
+
21
+ private
22
+
23
+ def problem
24
+ [root_problem, early_return_problem].compact.join(" ")
25
+ end
26
+
27
+ def root_problem
28
+ if roots.one?
29
+ return if unwrapped_output.empty?
30
+
31
+ root = roots.first
32
+ "#{describe(unwrapped_output)} #{verb(unwrapped_output)} rendered outside " \
33
+ "the root #{describe(roots)} in #{scope_name}; move #{unwrapped_output.one? ? "it" : "them"} " \
34
+ "inside the `#{root.name}`."
35
+ elsif roots.any?
36
+ both = (roots.length == 2) ? "both" : "all"
37
+ outside = unwrapped_output.any? ? ", and #{describe(unwrapped_output)} #{verb(unwrapped_output)} also rendered outside them" : ""
38
+
39
+ "#{describe(roots)} are #{both} top-level in #{scope_name}#{outside}; wrap them in one element."
40
+ elsif unwrapped_output.any?
41
+ "#{scope_name.capitalize} has no root element wrapping #{describe(unwrapped_output)}; " \
42
+ "render one element at the top level and put all output inside it."
43
+ else
44
+ "#{scope_name.capitalize} renders no root element; render one element that wraps all of its content."
45
+ end
46
+ end
47
+
48
+ def early_return_problem
49
+ return if early_returns.empty?
50
+
51
+ "#{describe(early_returns)} can exit #{scope_name} before its root #{describe(roots)}; " \
52
+ "move the conditional inside the root."
53
+ end
54
+
55
+ def verb(nodes)
56
+ nodes.one? ? "is" : "are"
57
+ end
58
+
59
+ def scope_name
60
+ (scope == "view_template") ? "`view_template`" : "this render block"
61
+ end
62
+
63
+ def describe(nodes)
64
+ descriptions = nodes.map do |node|
65
+ name = case node
66
+ when Prism::ReturnNode then "return"
67
+ when Prism::YieldNode then "yield"
68
+ else node.name
69
+ end
70
+ "`#{name}` (line #{node.location.start_line})"
71
+ end
72
+
73
+ return descriptions.first if descriptions.one?
74
+
75
+ "#{descriptions[0...-1].join(", ")} and #{descriptions.last}"
76
+ end
77
+ end
78
+
79
+ class ReturnCollector < Prism::Visitor
80
+ attr_reader :returns
81
+
82
+ def initialize
83
+ @returns = []
84
+ super
85
+ end
86
+
87
+ def visit_def_node(_node)
88
+ # A return in a nested method cannot exit the component template.
89
+ end
90
+
91
+ def visit_lambda_node(_node)
92
+ # A return in a lambda exits the lambda, not the component template.
93
+ end
94
+
95
+ def visit_return_node(node)
96
+ @returns << node
97
+ end
98
+ end
99
+
100
+ class OutputCollector < Prism::Visitor
101
+ attr_reader :output
102
+
103
+ def initialize
104
+ @output = []
105
+ super
106
+ end
107
+
108
+ def visit_call_node(node)
109
+ if output?(node)
110
+ @output << node
111
+ return
112
+ end
113
+
114
+ super
115
+ end
116
+
117
+ def visit_yield_node(node)
118
+ @output << node
119
+ end
120
+
121
+ private
122
+
123
+ def output?(node)
124
+ phlex_call?(node) && OUTPUT_METHODS.include?(node.name)
125
+ end
126
+
127
+ def phlex_call?(node)
128
+ node.receiver.nil? || node.receiver.is_a?(Prism::SelfNode)
129
+ end
130
+ end
131
+
132
+ def self.call(components)
133
+ locations = components.map do |klass|
134
+ location, _ = Object.const_source_location(klass.name)
135
+ location
136
+ end
137
+
138
+ locations.sort.flat_map do |location|
139
+ result = Prism.parse_file(location)
140
+ next [] unless result.success?
141
+
142
+ validator = new(Pathname.new(location).relative_path_from(Rage.root))
143
+ result.value.accept(validator)
144
+ validator.diagnostics
145
+ end
146
+ end
147
+
148
+ def self.validate(*components)
149
+ diagnostics = call(components)
150
+ return if diagnostics.empty?
151
+
152
+ message = diagnostics.map { |diagnostic| " - #{diagnostic.message}" }.join("\n")
153
+
154
+ "Every Pulse component and `render` block must wrap its output in exactly one root element. " \
155
+ "Found #{diagnostics.length} #{diagnostics.one? ? "problem" : "problems"}:\n#{message}"
156
+ end
157
+
158
+ def self.validate!(*components)
159
+ error_message = validate(*components)
160
+ raise Pulse::InvalidComponentRootError, error_message if error_message
161
+ end
162
+
163
+ attr_reader :diagnostics
164
+
165
+ def initialize(path)
166
+ @path = path
167
+ @diagnostics = []
168
+ super()
169
+ end
170
+
171
+ def visit_def_node(node)
172
+ validate_scope(node.body, node.location.start_line, "view_template") if node.name == :view_template
173
+ super
174
+ end
175
+
176
+ def visit_call_node(node)
177
+ if node.name == :render && node.block && phlex_call?(node)
178
+ validate_scope(node.block.body, node.location.start_line, "render block")
179
+ end
180
+
181
+ super
182
+ end
183
+
184
+ private
185
+
186
+ def validate_scope(node, line, scope)
187
+ statements = node.is_a?(Prism::StatementsNode) ? node.body : Array(node)
188
+ roots = statements.select { |statement| root?(statement) }
189
+ unwrapped_output = statements.flat_map do |statement|
190
+ next [] if roots.include?(statement)
191
+ next [] if allowed_document_output?(statement, roots)
192
+
193
+ collector = OutputCollector.new
194
+ statement.accept(collector)
195
+ collector.output
196
+ end
197
+ early_returns = early_returns(statements, roots)
198
+
199
+ return if roots.one? && unwrapped_output.empty? && early_returns.empty?
200
+
201
+ @diagnostics << Diagnostic.new(
202
+ path: @path,
203
+ line:,
204
+ scope:,
205
+ roots:,
206
+ unwrapped_output:,
207
+ early_returns:
208
+ )
209
+ end
210
+
211
+ def early_returns(statements, roots)
212
+ return [] unless roots.one?
213
+
214
+ collector = ReturnCollector.new
215
+ statements.take_while { |statement| statement != roots.first }.each do |statement|
216
+ statement.accept(collector)
217
+ end
218
+ collector.returns
219
+ end
220
+
221
+ def root?(node)
222
+ return false unless node.is_a?(Prism::CallNode) && phlex_call?(node)
223
+
224
+ ROOT_TAG_METHODS.include?(node.name) || (node.name == :render && node.block)
225
+ end
226
+
227
+ def allowed_document_output?(node, roots)
228
+ return false unless node.is_a?(Prism::CallNode) && phlex_call?(node) && roots.one?
229
+
230
+ root_name = roots.first.name
231
+ (node.name == :doctype && %i[body html].include?(root_name)) ||
232
+ (node.name == :head && root_name == :body)
233
+ end
234
+
235
+ def phlex_call?(node)
236
+ node.receiver.nil? || node.receiver.is_a?(Prism::SelfNode)
237
+ end
238
+
239
+ private_constant :NON_ROOT_TAG_METHODS, :OUTPUT_METHODS, :PHLEX_TAG_METHODS, :ROOT_TAG_METHODS
240
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Pulse::Event
4
+ def initialize(data)
5
+ @data = data
6
+ end
7
+
8
+ def value
9
+ @data["value"]
10
+ end
11
+
12
+ def checked?
13
+ @data["checked"]
14
+ end
15
+
16
+ def form_data
17
+ return @form_data if @form_data
18
+
19
+ form = @data["form"]
20
+ return unless form
21
+
22
+ @form_data = Rage::ParamsParser.prepare({
23
+ "IODINE_HAS_BODY" => true,
24
+ "QUERY_STRING" => "",
25
+ "CONTENT_TYPE" => "application/x-www-form-urlencoded",
26
+ "rack.input" => StringIO.new(form)
27
+ }, {})
28
+ end
29
+ end
@@ -0,0 +1,51 @@
1
+ module Pulse::Fingerprint
2
+ def self.included(klass)
3
+ klass.extend ClassMethods
4
+ end
5
+
6
+ module ClassMethods
7
+ def new(*args, **kwargs, &)
8
+ instance = super
9
+ instance.__record_pulse_inputs(args:, kwargs:)
10
+ instance
11
+ end
12
+ end
13
+
14
+ # @private
15
+ def __record_pulse_inputs(args:, kwargs:)
16
+ @__inputs = if args.any? && kwargs.any?
17
+ args + kwargs.to_a
18
+ elsif args.any?
19
+ args
20
+ else
21
+ kwargs
22
+ end
23
+ end
24
+
25
+ # Returns a content-based fingerprint for change detection.
26
+ #
27
+ # Used to determine if a component's inputs have changed since the last render.
28
+ # If the fingerprint matches the stored fingerprint, re-rendering can be skipped.
29
+ def fingerprint
30
+ @__inputs.map { |input| calculate_fingerprint(input) }
31
+ end
32
+
33
+ private
34
+
35
+ # Calculate fingerprint for different input types.
36
+ # `hash` is used as a cheaper alternative to duplication in order to support in-place edits.
37
+ # Active Record's dirty edits are not supported - it would require calling `changed?` or
38
+ # `attributes`, which are very slow - doing this for every single component render
39
+ # to support the minority of cases is not viable.
40
+ def calculate_fingerprint(value)
41
+ if value.is_a?(ActiveRecord::Base)
42
+ value[:updated_at].nil? ? value.attributes.hash : [value.hash, value.updated_at]
43
+ elsif value.is_a?(Hash)
44
+ calculate_fingerprint(value.to_a)
45
+ elsif value.is_a?(Array)
46
+ value.map { |v| calculate_fingerprint(v) }
47
+ else
48
+ value.hash
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Pulse::InvalidComponentRootError < StandardError
4
+ end
@@ -0,0 +1,13 @@
1
+ module Pulse::Marker
2
+ def __mark
3
+ @__marked = true
4
+ end
5
+
6
+ def __unmark
7
+ @__marked = false
8
+ end
9
+
10
+ def __marked?
11
+ @__marked
12
+ end
13
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Pulse::ModelCache
4
+ class << self
5
+ def store
6
+ @store ||= {}
7
+ end
8
+
9
+ def fetch(gid)
10
+ store.fetch(gid) do
11
+ model = begin
12
+ GlobalID::Locator.locate(gid)
13
+ rescue ActiveRecord::RecordNotFound
14
+ end
15
+
16
+ Fiber.schedule do
17
+ sleep 0
18
+ store.delete(gid)
19
+ end
20
+
21
+ store[gid] = model
22
+ end
23
+ end
24
+ end
25
+ end