view_component 4.15.0 → 4.20.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.
@@ -18,6 +18,10 @@ module ViewComponent
18
18
  # Extensions whose contents are hashed into the synthetic source.
19
19
  SIDECAR_EXTENSIONS = %w[yml yaml].freeze
20
20
 
21
+ # Where ViewComponent's own modules, such as the ones it includes into
22
+ # every component, are defined.
23
+ VIEW_COMPONENT_LIB = "#{::File.expand_path("..", __dir__)}/".freeze
24
+
21
25
  class << self
22
26
  def instance
23
27
  INSTANCE
@@ -30,11 +34,6 @@ module ViewComponent
30
34
  return [] unless component
31
35
 
32
36
  [build_template(component, virtual_path, details)]
33
- rescue
34
- # Never let digest resolution break rendering. Returning no template
35
- # makes the Digestor treat this as a missing node, which degrades to
36
- # the behavior components have without this feature.
37
- []
38
37
  end
39
38
 
40
39
  def to_s
@@ -47,52 +46,58 @@ module ViewComponent
47
46
  end
48
47
  alias_method :==, :eql?
49
48
 
50
- private
51
-
52
- def build_template(component, virtual_path, details)
53
- ActionView::Template.new(
54
- source_for(component),
55
- "view_component cache digest for #{component.name}",
56
- ActionView::Template.handler_for_extension(:erb),
57
- locals: [],
58
- format: Array(details[:formats]).first || :html,
59
- virtual_path: virtual_path
60
- )
61
- end
62
-
63
49
  # The synthetic source. Every section exists to change this string when
64
50
  # something the component renders from changes.
51
+ #
52
+ # @param component [Class]
53
+ # @return [String]
65
54
  def source_for(component)
66
55
  parts = []
56
+ templates = template_sources(component)
67
57
 
68
58
  # Safety net: this template should never be rendered, only digested.
69
59
  parts << "<% raise ViewComponent::CacheDigestTemplateError.new(#{component.name.inspect}) %>"
70
60
 
71
61
  # Content hashes of the Ruby files and sidecar files backing the
72
- # component and its component superclasses. Hashing rather than
73
- # inlining keeps the source small and avoids embedding Ruby that a
74
- # tracker might misread as a render call.
62
+ # component, its component superclasses, and the modules they include.
63
+ # Hashing rather than inlining keeps the source small and avoids
64
+ # embedding Ruby that a tracker might misread as a render call.
75
65
  source_files(component).each do |path|
76
66
  parts << "<%# Resolved Dependency: #{path} #{file_digest(path)} %>"
77
67
  end
78
68
 
79
- # Everything the component renders from Ruby rather than from a
80
- # template: `# Template Dependency:` declarations, components rendered
81
- # from `#call` methods, and partials referenced by string path.
82
- # Re-emitted so the Digestor resolves them as tree nodes.
83
- ruby_dependencies(component).each do |dependency|
69
+ # Everything the component renders: `# Template Dependency:`
70
+ # declarations, the components its slots are declared with, and the
71
+ # components and partials referenced from its templates, in any
72
+ # language, and from its Ruby. Emitted as declarations so the Digestor
73
+ # resolves them as tree nodes without trackers having to find them in
74
+ # the template sources, where they'd also infer partials from component
75
+ # renders.
76
+ dependencies(component, templates).each do |dependency|
84
77
  parts << "<%# Template Dependency: #{dependency} %>"
85
78
  end
86
79
 
87
- # Template sources verbatim, so trackers can discover the partials and
88
- # components they render.
89
- template_sources(component).each do |source|
90
- parts << source
80
+ # Content hashes of the templates, including inline ones.
81
+ templates.each do |source, _extension|
82
+ parts << "<%# Template Digest: #{ActiveSupport::Digest.hexdigest(source)} %>"
91
83
  end
92
84
 
93
85
  parts.join("\n")
94
86
  end
95
87
 
88
+ private
89
+
90
+ def build_template(component, virtual_path, details)
91
+ ActionView::Template.new(
92
+ component.__vc_cache_digest_source || source_for(component),
93
+ "view_component cache digest for #{component.name}",
94
+ ActionView::Template.handler_for_extension(:erb),
95
+ locals: [],
96
+ format: Array(details[:formats]).first || :html,
97
+ virtual_path: virtual_path
98
+ )
99
+ end
100
+
96
101
  # The component and any component superclasses, nearest first. Including
97
102
  # ancestors means editing `ApplicationComponent` invalidates every
98
103
  # component that inherits from it.
@@ -104,34 +109,55 @@ module ViewComponent
104
109
  end
105
110
  end
106
111
 
112
+ # Modules the component and its component superclasses include, such as
113
+ # a module of helpers that render other components. Modules included
114
+ # into `ViewComponent::Base` and above are left out, as superclasses
115
+ # are, and so are the modules ViewComponent adds to every component.
116
+ #
117
+ # @return [Array<String>] the files the modules are defined in
118
+ def module_files(component)
119
+ component.ancestors.take_while { |ancestor| ancestor != ViewComponent::Base }.filter_map { |ancestor|
120
+ next if ancestor.is_a?(Class) || ancestor.name.nil?
121
+
122
+ path, _line = Object.const_source_location(ancestor.name)
123
+ path unless path.nil? || path.start_with?(VIEW_COMPONENT_LIB)
124
+ }.uniq
125
+ end
126
+
107
127
  def source_files(component)
108
- component_ancestors(component).flat_map { |ancestor|
109
- [ancestor.identifier, *ancestor.sidecar_files(SIDECAR_EXTENSIONS)]
110
- }.compact.uniq.select { |path| ::File.exist?(path) }
128
+ sidecars = component_ancestors(component).flat_map { |ancestor| ancestor.__vc_sidecar_files(SIDECAR_EXTENSIONS) }
129
+ (ruby_files(component) + sidecars).uniq.select { |path| ::File.exist?(path) }
130
+ end
131
+
132
+ def ruby_files(component)
133
+ component_ancestors(component).map(&:identifier).concat(module_files(component))
134
+ .compact.uniq.select { |path| ::File.exist?(path) }
111
135
  end
112
136
 
113
137
  def template_files(component)
114
138
  component_ancestors(component)
115
- .flat_map { |ancestor| ancestor.sidecar_files(ActionView::Template::Handlers.extensions) }
139
+ .flat_map { |ancestor| ancestor.__vc_sidecar_files(ActionView::Template::Handlers.extensions) }
116
140
  .uniq
117
141
  .select { |path| ::File.exist?(path) }
118
142
  end
119
143
 
120
144
  # Sidecar template files plus inline templates, which live in the Ruby
121
145
  # file and so are invisible to Action View's trackers.
146
+ #
147
+ # @return [Array<Array(String, String)>] pairs of source and extension
122
148
  def template_sources(component)
123
- sources = template_files(component).map { |path| ::File.read(path) }
149
+ sources = template_files(component).map { |path| [::File.read(path), ::File.extname(path).delete_prefix(".")] }
124
150
 
125
151
  component_ancestors(component).each do |ancestor|
126
152
  inline_template = ancestor.__vc_inline_template
127
- sources << inline_template.source if inline_template
153
+ sources << [inline_template.source, inline_template.language.to_s] if inline_template
128
154
  end
129
155
 
130
156
  sources.uniq
131
157
  end
132
158
 
133
- def explicit_dependencies(component)
134
- ruby_sources(component).flat_map { |source|
159
+ def explicit_dependencies(sources)
160
+ sources.flat_map { |source|
135
161
  declared = source.scan(CacheDigest::EXPLICIT_DEPENDENCY).flatten
136
162
 
137
163
  # Component class names are translated to the path they're digested
@@ -144,34 +170,65 @@ module ViewComponent
144
170
  }.uniq
145
171
  end
146
172
 
147
- # Everything a component renders from Ruby code rather than from a
148
- # template. Action View's trackers only read templates, so a `#call`
149
- # method that renders another component or a partial would otherwise go
150
- # unnoticed.
151
- def ruby_dependencies(component)
173
+ # Everything but the component and its superclasses, which a component
174
+ # references in its own source but are digested as part of it already.
175
+ def dependencies(component, templates)
152
176
  virtual_path = CacheDigest.virtual_path_for(component)
177
+ ruby = ruby_sources(component)
178
+ own_paths = component_ancestors(component).filter_map { |ancestor| CacheDigest.virtual_path_for(ancestor) }
153
179
 
154
- explicit_dependencies(component) |
155
- ruby_sources(component).flat_map { |source|
156
- CacheDigest.component_paths_in(source) |
157
- CacheDigest.partial_paths_in(source, virtual_path)
158
- }.uniq
180
+ dependencies = explicit_dependencies(ruby + templates.map(&:first)) |
181
+ ruby.flat_map { |source| ruby_dependencies(source, virtual_path) } |
182
+ CacheDigest.slot_renders_of(component) |
183
+ templates.flat_map { |source, extension| template_dependencies(component, source, extension, virtual_path) }
184
+
185
+ dependencies - own_paths
186
+ end
187
+
188
+ # Components and partials rendered from Ruby, such as a `#call` method.
189
+ # Partials are narrowed to paths that appear in the source, discarding
190
+ # the speculative `things/thing` Action View infers from dynamic renders
191
+ # like `render @thing`, which would resolve to nothing.
192
+ def ruby_dependencies(source, virtual_path)
193
+ components, partials = CacheDigest.renders_in(source, virtual_path)
194
+
195
+ components | partials.select { |path|
196
+ source.include?(path) || source.include?(path.sub(%r{[^/]+\z}, '_\0'))
197
+ }
198
+ end
199
+
200
+ def template_dependencies(component, source, extension, virtual_path)
201
+ return [] unless source.include?("render")
202
+
203
+ template = ActionView::Template.new(
204
+ source,
205
+ "view_component cache digest for #{component.name}",
206
+ ActionView::Template.handler_for_extension(extension),
207
+ locals: [],
208
+ format: nil,
209
+ virtual_path: virtual_path
210
+ )
211
+ CacheDigest.renders_in(CacheDigest.compiled_source(template), virtual_path).flatten
159
212
  end
160
213
 
214
+ # Components loaded from encrypted files, as some commercial gems ship
215
+ # them, have binary identifiers that can't be scanned. They're still
216
+ # hashed by `file_digest`.
161
217
  def ruby_sources(component)
162
- component_ancestors(component).filter_map { |ancestor|
163
- path = ancestor.identifier
164
- ::File.read(path) if path && ::File.exist?(path)
218
+ ruby_files(component).filter_map { |path|
219
+ source = ::File.read(path)
220
+ source if source.valid_encoding?
165
221
  }
166
222
  end
167
223
 
168
224
  def file_digest(path)
169
- ActiveSupport::Digest.hexdigest(::File.read(path))
225
+ ActiveSupport::Digest.hexdigest(::File.binread(path))
170
226
  end
171
227
 
172
228
  # Built once at load time rather than memoized, so no class-level state
173
- # is written after boot. The resolver is stateless: it reads from disk on
174
- # every call so it can't go stale when a component changes.
229
+ # is written after boot. Unless sources were precomputed at boot, the
230
+ # resolver reads from disk on every call so it can't go stale when a
231
+ # component changes.
175
232
  INSTANCE = new
176
233
  end
177
234
  end
@@ -3,6 +3,7 @@
3
3
  require "active_support/dependencies/autoload"
4
4
  require "action_view/digestor"
5
5
  require "action_view/render_parser"
6
+ require "prism"
6
7
 
7
8
  module ViewComponent
8
9
  # Integrates ViewComponents into Rails' template digest tree.
@@ -21,15 +22,15 @@ module ViewComponent
21
22
  # not just its template.
22
23
  #
23
24
  # This module fixes both, reusing Rails' own `ActionView::Digestor` rather than
24
- # reimplementing static analysis. Components opt in individually by including
25
- # `ViewComponent::ExperimentallyCacheable`; until at least one component does,
26
- # every hook here short-circuits.
25
+ # reimplementing static analysis. Every discovered component is tracked
26
+ # automatically, independently of output caching.
27
27
  #
28
28
  # @private
29
29
  module CacheDigest
30
30
  extend ActiveSupport::Autoload
31
31
 
32
32
  autoload :DependencyTracking
33
+ autoload :DigestorLookup
33
34
  autoload :Resolver
34
35
 
35
36
  # Prefix for the synthetic virtual paths components are digested under.
@@ -38,26 +39,24 @@ module ViewComponent
38
39
  # application partial.
39
40
  VIRTUAL_PATH_PREFIX = "view_component/cache_digest"
40
41
 
41
- # Matches `render FooComponent`, `render(Foo::BarComponent.new(...))`,
42
- # `render FooComponent.with_collection(...)`, etc.
43
- #
44
- # Deliberately a plain source scan rather than a tracker-specific hook: it
45
- # behaves identically for the ERB tracker, the Prism-based Ruby tracker, and
46
- # third-party Haml/Slim trackers.
47
- RENDER_CALL = /
48
- \brender(?:_to_string)?\b # render or render_to_string
49
- \s*\(?\s* # optional opening paren
50
- (?<const>
51
- (?:::)?[A-Z]\w* # a constant
52
- (?:::[A-Z]\w*)* # optionally namespaced
53
- )
54
- /x
42
+ RENDER_METHODS = %i[render render_to_string].freeze
43
+
44
+ COMPILED_SOURCES = :view_component_cache_digest_compiled_sources
45
+ private_constant :COMPILED_SOURCES
46
+
47
+ # A render call whose first argument starts with a constant, such as
48
+ # `render FooComponent.new` or `render(Foo::Bar.with_collection(...))`.
49
+ CONSTANT_RENDER = /\brender(?:_to_string)?[\s(]*(?:::)?[A-Z]/
55
50
 
56
51
  # Rails' escape hatch for dependencies static analysis can't see.
57
52
  EXPLICIT_DEPENDENCY = /#\s*Template Dependency:\s*(\S+)/
53
+
54
+ # A constant path made only of constants, such as `Foo` or `::Foo::Bar`,
55
+ # rather than one hanging off an expression, such as `self.class::Bar`.
56
+ CONSTANT_NAME = /\A(?:::)?[A-Z]\w*(?:::[A-Z]\w*)*\z/
57
+
58
58
  class << self
59
- # Virtual paths of components that have opted into caching, mapped to
60
- # their class names.
59
+ # Virtual paths of components, mapped to their class names.
61
60
  #
62
61
  # Class *names* rather than class objects so the registry survives
63
62
  # autoloader reloads without pinning stale constants in memory.
@@ -67,16 +66,19 @@ module ViewComponent
67
66
  @registry ||= {}
68
67
  end
69
68
 
70
- # @return [Boolean] whether any component has opted in.
71
- def enabled?
72
- !registry.empty?
73
- end
74
-
75
69
  # @private
76
70
  def register(component)
77
71
  return unless component.virtual_path && component.name
72
+ return if registry[component.virtual_path] == component.name
78
73
 
79
74
  registry[component.virtual_path] = component.name
75
+
76
+ # Components register as they load, and under lazy loading that happens
77
+ # after Action View has already digested and memoized some templates.
78
+ # Those digests were computed without this component's dependencies and
79
+ # would otherwise be served for the rest of the process, making the
80
+ # digest a function of load order rather than of source.
81
+ expire_digests
80
82
  end
81
83
 
82
84
  # The synthetic virtual path a component is digested under.
@@ -100,55 +102,81 @@ module ViewComponent
100
102
  constantize_component(name)
101
103
  end
102
104
 
103
- # Scan a template's source for renders of cacheable components.
105
+ # Compile a template to Ruby with its own handler, so ERB, Haml, Slim and
106
+ # any other template language can be analyzed the same way. Reuses the
107
+ # Ruby compiled at boot, when there is some.
104
108
  #
105
- # Called for every template Rails digests, so it exits early when the
106
- # feature is unused.
107
- #
108
- # @return [Array<String>] synthetic virtual paths
109
- def dependencies_in(template)
110
- return [] unless enabled?
111
-
112
- component_paths_in(template.source)
109
+ # @return [String] Ruby source
110
+ def compiled_source(template)
111
+ source = template.source
112
+ Thread.current[COMPILED_SOURCES]&.dig(template.handler, source) || template.handler.call(template, source)
113
113
  end
114
114
 
115
- # Scan arbitrary source (a template or a component's Ruby file) for
116
- # renders of cacheable components.
115
+ # Find the components Ruby source references and the partials it
116
+ # renders.
117
117
  #
118
- # @return [Array<String>] synthetic virtual paths
119
- def component_paths_in(source)
120
- return [] unless source.is_a?(String) && source.include?("render")
121
-
122
- source.scan(RENDER_CALL).flatten.uniq.filter_map do |constant_name|
123
- component = constantize_component(constant_name)
124
- virtual_path_for(component) if component
118
+ # Every constant that names a component counts, not only one passed
119
+ # straight to `render`: a component can also be rendered from a method
120
+ # that builds it, from a local variable, or from a slot declared with its
121
+ # class. A component referenced without being rendered only makes the
122
+ # digest change more often than it needs to.
123
+ #
124
+ # Action View's render parser only sees the calls that don't render a
125
+ # component, so it can't infer partials from them.
126
+ #
127
+ # @param source [String] Ruby source
128
+ # @param name [String] virtual path the source is being digested under
129
+ # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
130
+ # components and partial virtual paths
131
+ def renders_in(source, name)
132
+ names = []
133
+ other_calls = []
134
+
135
+ each_node(Prism.parse(source).value) do |node|
136
+ if node.is_a?(Prism::ConstantReadNode) || node.is_a?(Prism::ConstantPathNode)
137
+ names << node.slice if CONSTANT_NAME.match?(node.slice)
138
+ elsif render_call?(node) && !rendered_component(node)
139
+ other_calls << node
140
+ end
125
141
  end
142
+
143
+ components = names.uniq.filter_map { |constant_name| constantize_component(constant_name) }
144
+ [component_paths(components), partials_rendered_by(other_calls, name)]
126
145
  end
127
146
 
128
- # Scan a component's Ruby source for partials referenced by string path,
129
- # such as `render "posts/byline"` inside a `#call` method.
147
+ # Find the components Ruby source renders, along with the partials Action
148
+ # View infers from them.
130
149
  #
131
- # Uses Rails' own render parser — the same one `RubyTracker` runs over
132
- # compiled templates — rather than a second implementation of the same
133
- # analysis. Its results are then narrowed to paths that appear verbatim in
134
- # the source, which keeps string literals and discards the speculative
135
- # `things/_thing` entries the parser infers from dynamic renders like
136
- # `render @thing` or `render FooComponent.new`. Those would resolve to
137
- # nothing and only add log noise; components rendered from Ruby are
138
- # already found precisely by `component_paths_in`.
150
+ # Action View reads `render FooComponent.new` as a dynamic render of a
151
+ # partial named after the last method, inferring `news/new`. Partials also
152
+ # rendered some other way aren't returned.
139
153
  #
140
154
  # @param source [String] Ruby source
141
155
  # @param name [String] virtual path the source is being digested under
142
- # @return [Array<String>] partial virtual paths
143
- def partial_paths_in(source, name)
144
- return [] unless source.is_a?(String) && source.include?("render")
156
+ # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
157
+ # components and inferred partial virtual paths
158
+ def component_renders_in(source, name)
159
+ components, other_calls = partition_render_calls(Prism.parse(source).value)
160
+ return [[], []] if components.empty?
161
+
162
+ [
163
+ component_paths(components.values),
164
+ partials_rendered_by(components.keys, name) - partials_rendered_by(other_calls, name)
165
+ ]
166
+ end
145
167
 
146
- RENDER_PARSER.new(name, source).render_calls.uniq.select do |path|
147
- source.include?(path) || source.include?(path.sub(%r{(\A|/)_}, '\1'))
148
- end
149
- rescue
150
- # Never let digest computation break rendering.
151
- []
168
+ # Find the components a component's slots render, from the class each
169
+ # slot was declared with: `renders_one :header, HeaderComponent` or
170
+ # `renders_many :items, "ItemComponent"`. Read from the slot definitions
171
+ # rather than from source, since a class named by a string, or by a name
172
+ # relative to the component, resolves against the component at runtime.
173
+ #
174
+ # @param component [Class]
175
+ # @return [Array<String>] synthetic virtual paths of components
176
+ def slot_renders_of(component)
177
+ definitions = component.registered_slots.values.flat_map { |slot| slot[:renderable_hash]&.values || [slot] }
178
+
179
+ component_paths(definitions.filter_map { |slot| slot_component(component, slot) })
152
180
  end
153
181
 
154
182
  # Action View has shipped its render parser as a class (Rails 7.1, and
@@ -177,17 +205,19 @@ module ViewComponent
177
205
  next unless /\A(?:::)?[A-Z]/.match?(declared)
178
206
 
179
207
  component = constantize_component(declared)
180
- [declared, virtual_path_for(component)] if component
208
+ virtual_path = registered_path_for(component)
209
+ [declared, virtual_path] if virtual_path
181
210
  end
182
211
  end
183
212
 
184
213
  # Compute the digest of a component using Rails' digest tree.
185
214
  #
186
- # @param component [Class] a component that includes `ExperimentallyCacheable`
215
+ # @param component [Class] a component class
187
216
  # @param finder [ActionView::LookupContext]
188
217
  # @param format [Symbol]
189
218
  # @return [String]
190
219
  def digest(component, finder: default_finder, format: :html)
220
+ register(component)
191
221
  virtual_path = virtual_path_for(component)
192
222
  return "" unless virtual_path
193
223
 
@@ -205,38 +235,165 @@ module ViewComponent
205
235
 
206
236
  # Wire the tracker and resolver into Action View.
207
237
  #
208
- # Called each time a component includes `ExperimentallyCacheable`. Both
209
- # steps below are individually idempotent, so no "already installed" flag
210
- # is kept. Both hooks short-circuit while the registry is empty, so
211
- # applications that never opt in are unaffected.
238
+ # Installed during engine initialization. Both steps are idempotent.
212
239
  #
213
240
  # @private
214
241
  def install!
215
242
  DependencyTracking.install!
243
+ DigestorLookup.install!
244
+ end
216
245
 
217
- ActiveSupport.on_load(:action_controller_base) do
218
- resolver = ViewComponent::CacheDigest::Resolver.instance
246
+ # Keep the Ruby that templates compile to while the block runs, so
247
+ # `precompute!` can analyze templates components just compiled without
248
+ # compiling them again. Kept in a thread local rather than on the module,
249
+ # which isn't writable from other Ractors.
250
+ #
251
+ # @private
252
+ def retaining_compiled_sources
253
+ Thread.current[COMPILED_SOURCES] = {}
254
+ yield
255
+ ensure
256
+ Thread.current[COMPILED_SOURCES] = nil
257
+ end
258
+
259
+ # @private
260
+ def compiled(handler, source, compiled_source)
261
+ sources = Thread.current[COMPILED_SOURCES]
262
+ (sources[handler] ||= {})[source] = compiled_source if sources
263
+ end
264
+
265
+ # Compute component digests at boot, so requests read them from memory
266
+ # instead of reading and scanning source files.
267
+ #
268
+ # Only safe when templates are cached at boot: the precomputed sources are
269
+ # never refreshed.
270
+ #
271
+ # @param components [Array<Class>]
272
+ # @return [void]
273
+ # @private
274
+ def precompute!(components)
275
+ # Register everything first: a registration expires every memoized
276
+ # digest, so registering midway would discard digests already warmed.
277
+ components.each { |component| register(component) }
219
278
 
220
- append_view_path(resolver) unless view_paths.include?(resolver)
279
+ components.each do |component|
280
+ component.__vc_cache_digest_source = Resolver.instance.source_for(component).freeze
281
+ end
282
+
283
+ # Warms the same digest cache requests read, since a lookup context's
284
+ # cache is shared by every context with the same details.
285
+ components.each do |component|
286
+ component.__vc_template_formats.each do |format|
287
+ finder = ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [format])
288
+ component.cache_digest(finder: finder, format: format)
289
+ end
221
290
  end
222
291
  end
223
292
 
224
293
  private
225
294
 
226
- # Resolve a constant name to a component that opted into caching.
295
+ # Receiverless `render` and `render_to_string` calls, split into those
296
+ # that render a component and the rest.
297
+ #
298
+ # @return [Array(Hash{Prism::CallNode => Class}, Array<Prism::CallNode>)]
299
+ def partition_render_calls(program)
300
+ components = {}
301
+ other_calls = []
302
+
303
+ each_node(program) do |node|
304
+ next unless render_call?(node)
305
+
306
+ if (component = rendered_component(node))
307
+ components[node] = component
308
+ else
309
+ other_calls << node
310
+ end
311
+ end
312
+
313
+ [components, other_calls]
314
+ end
315
+
316
+ def render_call?(node)
317
+ node.is_a?(Prism::CallNode) && node.receiver.nil? && RENDER_METHODS.include?(node.name)
318
+ end
319
+
320
+ # Visit every node of a Prism tree, in source order.
321
+ def each_node(program)
322
+ nodes = [program]
323
+ while (node = nodes.pop)
324
+ yield node
325
+ nodes.concat(node.compact_child_nodes.reverse!)
326
+ end
327
+ end
328
+
329
+ # The component a render call renders, from the constant at the root of
330
+ # its first argument: `FooComponent`, `FooComponent.new(...)`,
331
+ # `FooComponent.with_collection(...)`, and so on.
332
+ #
333
+ # @return [Class, nil]
334
+ def rendered_component(call)
335
+ node = call.arguments&.arguments&.first
336
+ node = node.receiver while node.is_a?(Prism::CallNode) && node.receiver
337
+
338
+ case node
339
+ when Prism::ConstantReadNode, Prism::ConstantPathNode
340
+ constantize_component(node.slice)
341
+ end
342
+ end
343
+
344
+ def component_paths(components)
345
+ components.uniq.filter_map { |component| registered_path_for(component) }
346
+ end
347
+
348
+ # The component a slot renders, resolving a class name the way the slot
349
+ # does when it's set. A name that doesn't resolve is left to fail there.
350
+ def slot_component(component, slot)
351
+ renderable = slot[:renderable]
352
+ name = slot[:renderable_class_name]
353
+ renderable ||= component.const_get(name) if name && component.const_defined?(name)
354
+
355
+ renderable if renderable.is_a?(Class) && renderable < ViewComponent::Base
356
+ end
357
+
358
+ # Partials Action View's render parser finds in the given calls,
359
+ # normalized to the form its trackers report. The calls are parsed
360
+ # together, so the parser runs once rather than once per call. Blocks are
361
+ # left out, as any renders inside them are calls of their own.
362
+ def partials_rendered_by(calls, name)
363
+ return [] if calls.empty?
364
+
365
+ source = calls.map { |call| "#{call.name}(#{call.arguments&.slice})" }.join("\n")
366
+ RENDER_PARSER.new(name, source).render_calls
367
+ .map { |path| path.gsub(%r{/_}, "/") }
368
+ .uniq
369
+ end
370
+
371
+ # Record the actual class name rather than trying to reverse a virtual
372
+ # path, which may contain acronyms or be overridden by the component.
373
+ def registered_path_for(component)
374
+ return unless component
375
+
376
+ register(component)
377
+ virtual_path_for(component)
378
+ end
379
+
380
+ # Drop Action View's memoized template digests, leaving its resolver
381
+ # caches alone: no template changed, only the set of dependencies the
382
+ # Digestor can see.
383
+ def expire_digests
384
+ ActionView::LookupContext::DetailsKey.digest_caches.each(&:clear)
385
+ end
386
+
387
+ # Resolve a constant name to any ViewComponent.
227
388
  #
228
389
  # Returns nil for anything else, including constants that don't exist.
229
390
  # Autoloading here is safe: the template is about to render this constant
230
391
  # anyway.
231
392
  def constantize_component(constant_name)
232
393
  component = constant_name.safe_constantize
233
- return unless component.is_a?(Class)
234
- return unless component.respond_to?(:__vc_cacheable?) && component.__vc_cacheable?
394
+ return unless component.is_a?(Class) && component < ViewComponent::Base
235
395
 
236
396
  component
237
- rescue
238
- # Never let digest computation break rendering.
239
- nil
240
397
  end
241
398
  end
242
399