view_component 4.17.0 → 4.24.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/app/views/test_mailer/test_multipart_email.html.erb +1 -0
  3. data/app/views/test_mailer/test_multipart_email.text.erb +1 -0
  4. data/docs/CHANGELOG.md +234 -0
  5. data/lib/generators/view_component/abstract_generator.rb +24 -4
  6. data/lib/generators/view_component/component/component_generator.rb +8 -6
  7. data/lib/generators/view_component/component/templates/component.rb.tt +1 -1
  8. data/lib/generators/view_component/erb/erb_generator.rb +2 -2
  9. data/lib/generators/view_component/haml/haml_generator.rb +1 -1
  10. data/lib/generators/view_component/locale/locale_generator.rb +2 -6
  11. data/lib/generators/view_component/preview/preview_generator.rb +9 -6
  12. data/lib/generators/view_component/preview/templates/component_preview.rb.tt +2 -2
  13. data/lib/generators/view_component/rspec/rspec_generator.rb +1 -1
  14. data/lib/generators/view_component/rspec/templates/component_spec.rb.tt +1 -1
  15. data/lib/generators/view_component/slim/slim_generator.rb +1 -1
  16. data/lib/generators/view_component/stimulus/stimulus_generator.rb +3 -7
  17. data/lib/generators/view_component/test_unit/templates/component_test.rb.tt +2 -2
  18. data/lib/generators/view_component/test_unit/test_unit_generator.rb +8 -7
  19. data/lib/view_component/base.rb +169 -94
  20. data/lib/view_component/cache_digest/dependency_tracking.rb +43 -11
  21. data/lib/view_component/cache_digest/digestor_lookup.rb +77 -0
  22. data/lib/view_component/cache_digest/resolver.rb +163 -65
  23. data/lib/view_component/cache_digest.rb +384 -75
  24. data/lib/view_component/{experimentally_cacheable.rb → cacheable.rb} +50 -127
  25. data/lib/view_component/collection.rb +4 -9
  26. data/lib/view_component/compile_cache.rb +63 -3
  27. data/lib/view_component/compiler.rb +86 -15
  28. data/lib/view_component/config.rb +114 -8
  29. data/lib/view_component/engine.rb +18 -6
  30. data/lib/view_component/errors.rb +16 -0
  31. data/lib/view_component/request_details.rb +5 -10
  32. data/lib/view_component/slot.rb +17 -0
  33. data/lib/view_component/slotable.rb +32 -8
  34. data/lib/view_component/template.rb +38 -16
  35. data/lib/view_component/test_helpers.rb +39 -15
  36. data/lib/view_component/translatable.rb +35 -1
  37. data/lib/view_component/version.rb +1 -1
  38. data/lib/view_component.rb +1 -1
  39. metadata +10 -7
@@ -3,6 +3,8 @@
3
3
  require "active_support/dependencies/autoload"
4
4
  require "action_view/digestor"
5
5
  require "action_view/render_parser"
6
+ require "prism"
7
+ require "strscan"
6
8
 
7
9
  module ViewComponent
8
10
  # Integrates ViewComponents into Rails' template digest tree.
@@ -21,15 +23,15 @@ module ViewComponent
21
23
  # not just its template.
22
24
  #
23
25
  # 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.
26
+ # reimplementing static analysis. Every discovered component is tracked
27
+ # automatically, independently of output caching.
27
28
  #
28
29
  # @private
29
30
  module CacheDigest
30
31
  extend ActiveSupport::Autoload
31
32
 
32
33
  autoload :DependencyTracking
34
+ autoload :DigestorLookup
33
35
  autoload :Resolver
34
36
 
35
37
  # Prefix for the synthetic virtual paths components are digested under.
@@ -38,26 +40,21 @@ module ViewComponent
38
40
  # application partial.
39
41
  VIRTUAL_PATH_PREFIX = "view_component/cache_digest"
40
42
 
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
43
+ RENDER_METHODS = %i[render render_to_string].freeze
44
+
45
+ COMPILED_SOURCES = :view_component_cache_digest_compiled_sources
46
+ MEMO = :view_component_cache_digest_memo
47
+ private_constant :COMPILED_SOURCES, :MEMO
55
48
 
56
49
  # Rails' escape hatch for dependencies static analysis can't see.
57
50
  EXPLICIT_DEPENDENCY = /#\s*Template Dependency:\s*(\S+)/
51
+
52
+ # A constant path made only of constants, such as `Foo` or `::Foo::Bar`,
53
+ # rather than one hanging off an expression, such as `self.class::Bar`.
54
+ CONSTANT_NAME = /\A(?:::)?[A-Z]\w*(?:::[A-Z]\w*)*\z/
55
+
58
56
  class << self
59
- # Virtual paths of components that have opted into caching, mapped to
60
- # their class names.
57
+ # Virtual paths of components, mapped to their class names.
61
58
  #
62
59
  # Class *names* rather than class objects so the registry survives
63
60
  # autoloader reloads without pinning stale constants in memory.
@@ -67,11 +64,6 @@ module ViewComponent
67
64
  @registry ||= {}
68
65
  end
69
66
 
70
- # @return [Boolean] whether any component has opted in.
71
- def enabled?
72
- !registry.empty?
73
- end
74
-
75
67
  # @private
76
68
  def register(component)
77
69
  return unless component.virtual_path && component.name
@@ -108,52 +100,110 @@ module ViewComponent
108
100
  constantize_component(name)
109
101
  end
110
102
 
111
- # Scan a template's source for renders of cacheable components.
103
+ # Compile a template to Ruby with its own handler, so ERB, Haml, Slim and
104
+ # any other template language can be analyzed the same way. Reuses the
105
+ # Ruby compiled at boot, when there is some.
112
106
  #
113
- # Called for every template Rails digests, so it exits early when the
114
- # feature is unused.
115
- #
116
- # @return [Array<String>] synthetic virtual paths
117
- def dependencies_in(template)
118
- return [] unless enabled?
119
-
120
- component_paths_in(template.source)
107
+ # @return [String] Ruby source
108
+ def compiled_source(template)
109
+ source = template.source
110
+ Thread.current[COMPILED_SOURCES]&.dig(template.handler, source) || template.handler.call(template, source)
121
111
  end
122
112
 
123
- # Scan arbitrary source (a template or a component's Ruby file) for
124
- # renders of cacheable components.
113
+ # Skip literal templates and ERB markup before compiling Ruby for analysis.
114
+ # Other handlers keep a conservative check because their code syntax varies.
115
+ #
116
+ # @param source [String]
117
+ # @param handler [#call]
125
118
  #
126
- # @return [Array<String>] synthetic virtual paths
127
- def component_paths_in(source)
128
- return [] unless source.is_a?(String) && source.include?("render")
119
+ # @return [Boolean]
120
+ def template_dependencies?(source, handler)
121
+ return false unless source.match?(/render|[A-Z]/)
122
+
123
+ case handler
124
+ when ActionView::Template::Handlers::Raw, ActionView::Template::Handlers::Html
125
+ false
126
+ when ActionView::Template::Handlers::ERB
127
+ # Never restart the search at another opener after an unterminated tag.
128
+ scanner = StringScanner.new(source)
129
+ while scanner.skip_until(/<%/)
130
+ code = scanner.scan_until(/%>/)
131
+ return false unless code
132
+ next if code.start_with?("#", "%")
133
+
134
+ return true if code.match?(/render|[A-Z]/)
135
+ end
136
+ false
137
+ else
138
+ true
139
+ end
140
+ end
129
141
 
130
- source.scan(RENDER_CALL).flatten.uniq.filter_map do |constant_name|
131
- component = constantize_component(constant_name)
132
- virtual_path_for(component) if component
142
+ # Find the components Ruby source references and the partials it
143
+ # renders.
144
+ #
145
+ # Every constant that names a component counts, not only one passed
146
+ # straight to `render`: a component can also be rendered from a method
147
+ # that builds it, from a local variable, or from a slot declared with its
148
+ # class. A component referenced without being rendered only makes the
149
+ # digest change more often than it needs to.
150
+ #
151
+ # Action View's render parser only sees the calls that don't render a
152
+ # component, so it can't infer partials from them.
153
+ #
154
+ # @param source [String] Ruby source
155
+ # @param name [String] virtual path the source is being digested under
156
+ # @param view_paths [ActionView::PathSet, nil] paths to check dynamic partial guesses against
157
+ # @param nesting [Array<Module>] lexical scope of compiled template source
158
+ # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
159
+ # components and partial virtual paths
160
+ def renders_in(source, name, view_paths: nil, nesting: [])
161
+ # Shared by every component that includes a module or inherits from
162
+ # the same superclass, so it's scanned once per digest computation.
163
+ memoize([:renders_in, source, name, view_paths, nesting]) do
164
+ components, _component_calls, other_calls = partition_render_calls(Prism.parse(source).value, nesting)
165
+ partials = partials_rendered_by(other_calls, name) - unresolved_partials_rendered_by(other_calls, name, view_paths)
166
+ [component_paths(components), partials]
133
167
  end
134
168
  end
135
169
 
136
- # Scan a component's Ruby source for partials referenced by string path,
137
- # such as `render "posts/byline"` inside a `#call` method.
170
+ # Find the components Ruby source renders, along with partial guesses
171
+ # Action View should discard.
138
172
  #
139
- # Uses Rails' own render parser — the same one `RubyTracker` runs over
140
- # compiled templates — rather than a second implementation of the same
141
- # analysis. Its results are then narrowed to paths that appear verbatim in
142
- # the source, which keeps string literals and discards the speculative
143
- # `things/_thing` entries the parser infers from dynamic renders like
144
- # `render @thing` or `render FooComponent.new`. Those would resolve to
145
- # nothing and only add log noise; components rendered from Ruby are
146
- # already found precisely by `component_paths_in`.
173
+ # Action View reads `render FooComponent.new` as a dynamic render of a
174
+ # partial named after the last method, inferring `news/new`. Partials also
175
+ # rendered some other way aren't returned. Unresolved guesses from other
176
+ # dynamic renders are discarded when view paths are available.
147
177
  #
148
178
  # @param source [String] Ruby source
149
179
  # @param name [String] virtual path the source is being digested under
150
- # @return [Array<String>] partial virtual paths
151
- def partial_paths_in(source, name)
152
- return [] unless source.is_a?(String) && source.include?("render")
180
+ # @param view_paths [ActionView::PathSet, nil] paths to check dynamic partial guesses against
181
+ # @yieldparam calls [Array<String>] Ruby render calls to track with the template's tracker
182
+ # @yieldreturn [Array<String>] partial paths inferred by that tracker
183
+ # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
184
+ # components and inferred partial virtual paths
185
+ def template_renders_in(source, name, view_paths: nil, &tracker)
186
+ components, component_calls, other_calls = partition_render_calls(Prism.parse(source).value)
187
+
188
+ [
189
+ component_paths(components),
190
+ (partials_rendered_by(component_calls, name, &tracker) - partials_rendered_by(other_calls, name, &tracker)) |
191
+ unresolved_partials_rendered_by(other_calls, name, view_paths)
192
+ ]
193
+ end
153
194
 
154
- RENDER_PARSER.new(name, source).render_calls.uniq.select do |path|
155
- source.include?(path) || source.include?(path.sub(%r{(\A|/)_}, '\1'))
156
- end
195
+ # Find the components a component's slots render, from the class each
196
+ # slot was declared with: `renders_one :header, HeaderComponent` or
197
+ # `renders_many :items, "ItemComponent"`. Read from the slot definitions
198
+ # rather than from source, since a class named by a string, or by a name
199
+ # relative to the component, resolves against the component at runtime.
200
+ #
201
+ # @param component [Class]
202
+ # @return [Array<String>] synthetic virtual paths of components
203
+ def slot_renders_of(component)
204
+ definitions = component.registered_slots.values.flat_map { |slot| slot[:renderable_hash]&.values || [slot] }
205
+
206
+ component_paths(definitions.filter_map { |slot| slot_component(component, slot) })
157
207
  end
158
208
 
159
209
  # Action View has shipped its render parser as a class (Rails 7.1, and
@@ -182,52 +232,293 @@ module ViewComponent
182
232
  next unless /\A(?:::)?[A-Z]/.match?(declared)
183
233
 
184
234
  component = constantize_component(declared)
185
- [declared, virtual_path_for(component)] if component
235
+ virtual_path = registered_path_for(component)
236
+ [declared, virtual_path] if virtual_path
186
237
  end
187
238
  end
188
239
 
189
240
  # Compute the digest of a component using Rails' digest tree.
190
241
  #
191
- # @param component [Class] a component that includes `ExperimentallyCacheable`
192
- # @param finder [ActionView::LookupContext]
242
+ # @param component [Class] a component class
243
+ # @param finder [ActionView::LookupContext, nil]
193
244
  # @param format [Symbol]
245
+ #
194
246
  # @return [String]
195
- def digest(component, finder: default_finder, format: :html)
247
+ def digest(component, finder: nil, format: :html)
248
+ register(component)
196
249
  virtual_path = virtual_path_for(component)
197
250
  return "" unless virtual_path
198
251
 
252
+ finder ||= default_finder(format: format)
199
253
  ActionView::Digestor.digest(name: virtual_path, format: format, finder: finder)
200
254
  end
201
255
 
202
256
  # A lookup context for digesting components outside a request, where no
203
257
  # view context (and therefore no finder) exists.
204
258
  #
259
+ # @param format [Symbol]
260
+ #
205
261
  # @return [ActionView::LookupContext]
206
- def default_finder
262
+ def default_finder(format: :html)
207
263
  # Not memoized across reloads: view paths change when the app reloads.
208
- ActionView::LookupContext.new(ActionController::Base.view_paths)
264
+ ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [format])
209
265
  end
210
266
 
211
267
  # Wire the tracker and resolver into Action View.
212
268
  #
213
- # Called each time a component includes `ExperimentallyCacheable`. Both
214
- # steps below are individually idempotent, so no "already installed" flag
215
- # is kept. Both hooks short-circuit while the registry is empty, so
216
- # applications that never opt in are unaffected.
269
+ # Installed during engine initialization. Both steps are idempotent.
217
270
  #
218
271
  # @private
219
272
  def install!
220
273
  DependencyTracking.install!
274
+ DigestorLookup.install!
275
+ end
276
+
277
+ # Keep the Ruby that templates compile to while the block runs, so
278
+ # `precompute!` can analyze templates components just compiled without
279
+ # compiling them again. Kept in a thread local rather than on the module,
280
+ # which isn't writable from other Ractors.
281
+ #
282
+ # @private
283
+ def retaining_compiled_sources
284
+ Thread.current[COMPILED_SOURCES] = {}
285
+ yield
286
+ ensure
287
+ Thread.current[COMPILED_SOURCES] = nil
288
+ end
221
289
 
222
- ActiveSupport.on_load(:action_controller_base) do
223
- resolver = ViewComponent::CacheDigest::Resolver.instance
290
+ # Share synthetic templates between every lookup in the block.
291
+ #
292
+ # The Digestor looks a template up once per edge of the tree, before it
293
+ # checks whether it has seen the template already. Action View's own
294
+ # resolvers cache their templates, but building a synthetic one reads and
295
+ # parses the component's sources, so a component rendered from many
296
+ # places was rebuilt once per place. Kept for one digest computation
297
+ # only, so a source edited between requests is still seen.
298
+ #
299
+ # @private
300
+ def memoizing
301
+ return yield if Thread.current[MEMO]
302
+
303
+ begin
304
+ Thread.current[MEMO] = {}
305
+ yield
306
+ ensure
307
+ Thread.current[MEMO] = nil
308
+ end
309
+ end
224
310
 
225
- append_view_path(resolver) unless view_paths.include?(resolver)
311
+ # @private
312
+ def memo
313
+ Thread.current[MEMO]
314
+ end
315
+
316
+ # @private
317
+ def memoize(key)
318
+ memo = Thread.current[MEMO]
319
+ return yield unless memo
320
+
321
+ memo.fetch(key) { memo[key] = yield }
322
+ end
323
+
324
+ # @private
325
+ def compiled(handler, source, compiled_source)
326
+ sources = Thread.current[COMPILED_SOURCES]
327
+ (sources[handler] ||= {})[source] = compiled_source if sources
328
+ end
329
+
330
+ # Compute component digests at boot, so requests read them from memory
331
+ # instead of reading and scanning source files.
332
+ #
333
+ # Only safe when templates are cached at boot: the precomputed sources are
334
+ # never refreshed.
335
+ #
336
+ # @param components [Array<Class>]
337
+ # @return [void]
338
+ # @private
339
+ def precompute!(components)
340
+ # Register everything first: a registration expires every memoized
341
+ # digest, so registering midway would discard digests already warmed.
342
+ components.each { |component| register(component) }
343
+
344
+ memoizing do
345
+ components.each do |component|
346
+ component.__vc_cache_digest_source = Resolver.instance.source_for(component).freeze
347
+ end
348
+
349
+ # Warms the same digest cache requests read, since a lookup context's
350
+ # cache is shared by every context with the same details.
351
+ components.each do |component|
352
+ component.__vc_template_formats.each do |format|
353
+ finder = ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [format])
354
+ component.cache_digest(finder: finder, format: format)
355
+ end
356
+ end
226
357
  end
227
358
  end
228
359
 
229
360
  private
230
361
 
362
+ # Component references and receiverless render calls, split into those
363
+ # that render a component directly and the rest.
364
+ #
365
+ # @return [Array(Array<Class>, Array<Prism::CallNode>, Array<Prism::CallNode>)]
366
+ def partition_render_calls(program, nesting = [])
367
+ names = []
368
+ component_calls = []
369
+ other_calls = []
370
+
371
+ each_node(program, nesting) do |node, scope|
372
+ if node.is_a?(Prism::ConstantReadNode) || node.is_a?(Prism::ConstantPathNode)
373
+ name = node.slice
374
+ names << [name, scope] if CONSTANT_NAME.match?(name)
375
+ elsif render_call?(node)
376
+ if rendered_component(node, scope)
377
+ component_calls << node
378
+ else
379
+ other_calls << node
380
+ end
381
+ end
382
+ end
383
+
384
+ components = names.uniq.filter_map { |constant_name, scope| constantize_component(constant_name, scope) }
385
+ [components, component_calls, other_calls]
386
+ end
387
+
388
+ def render_call?(node)
389
+ node.is_a?(Prism::CallNode) && node.receiver.nil? && RENDER_METHODS.include?(node.name)
390
+ end
391
+
392
+ # Class/module bodies add one lexical scope, even for qualified names:
393
+ # `class UI::Card` adds Card, not UI, to Module.nesting.
394
+ def each_node(program, nesting = [])
395
+ # Keep scopes and nodes in one stack rather than allocating a pair per node.
396
+ nodes = [nesting, program]
397
+ while (node = nodes.pop)
398
+ scope = nodes.pop
399
+ yield node, scope
400
+
401
+ body = nil
402
+ body_scope = scope
403
+ if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
404
+ body = node.body
405
+ namespace = resolve_constant(node.constant_path.slice, scope)
406
+ body_scope = [namespace, *scope] if namespace.is_a?(Module)
407
+ end
408
+
409
+ node.compact_child_nodes.reverse_each do |child|
410
+ nodes.push(child.equal?(body) ? body_scope : scope, child)
411
+ end
412
+ end
413
+ end
414
+
415
+ # The component a render call renders, from the constant at the root of
416
+ # its first argument: `FooComponent`, `FooComponent.new(...)`,
417
+ # `FooComponent.with_collection(...)`, and so on.
418
+ #
419
+ # @return [Class, nil]
420
+ def rendered_component(call, nesting = [])
421
+ node = call.arguments&.arguments&.first
422
+ node = node.receiver while node.is_a?(Prism::CallNode) && node.receiver
423
+
424
+ case node
425
+ when Prism::ConstantReadNode, Prism::ConstantPathNode
426
+ constantize_component(node.slice, nesting)
427
+ end
428
+ end
429
+
430
+ def component_paths(components)
431
+ components.uniq.filter_map { |component| registered_path_for(component) }
432
+ end
433
+
434
+ # The component a slot renders, resolving a class name the way the slot
435
+ # does when it's set. A name that doesn't resolve is left to fail there.
436
+ def slot_component(component, slot)
437
+ renderable = slot[:renderable]
438
+ name = slot[:renderable_class_name]
439
+ renderable ||= component.const_get(name) if name && component.const_defined?(name)
440
+
441
+ renderable if renderable.is_a?(Class) && renderable < ViewComponent::Base
442
+ end
443
+
444
+ # Partials the given tracker, or Action View's render parser, finds in
445
+ # the given calls. Calls are tracked together rather than once per call.
446
+ # Blocks are left out, as any renders inside them are calls of their own.
447
+ def partials_rendered_by(calls, name)
448
+ return [] if calls.empty?
449
+
450
+ sources = calls.map { |call| "#{call.name}(#{call.arguments&.slice})" }
451
+ block_given? ? yield(sources) : partial_paths_in(sources.join("\n"), name)
452
+ end
453
+
454
+ def partial_paths_in(source, name)
455
+ RENDER_PARSER.new(name, source).render_calls
456
+ .map { |path| path.gsub(%r{/_}, "/") }
457
+ .uniq
458
+ end
459
+
460
+ # Dynamic renders can return components without naming their classes,
461
+ # such as `render UI.button`. Keep Action View's guess only if it resolves,
462
+ # without executing application methods to discover what they return.
463
+ # Interpolated paths are discarded if Rails cannot expand their wildcards.
464
+ def unresolved_partials_rendered_by(calls, name, view_paths)
465
+ targets = calls.flat_map { |call| render_targets(call) }
466
+ literal, dynamic = targets.partition do |target|
467
+ target.is_a?(Prism::StringNode) || target.is_a?(Prism::InterpolatedStringNode)
468
+ end
469
+ interpolated = literal.grep(Prism::InterpolatedStringNode)
470
+ unresolved = []
471
+ if interpolated.any?
472
+ paths = partial_paths_in(interpolated.map { |target| "render(#{target.slice})" }.join("\n"), name)
473
+ # Rails expands only directory wildcards with a literal prefix.
474
+ # Older parsers can return truncated paths without any wildcard.
475
+ unresolved = paths.reject { |path| path.match?(%r{\A[^*]+/\*\z}) }
476
+ static = literal.grep(Prism::StringNode)
477
+ unresolved -= partial_paths_in(static.map { |target| "render(#{target.slice})" }.join("\n"), name)
478
+ end
479
+ return unresolved unless view_paths && dynamic.any?
480
+
481
+ inferred = partial_paths_in(dynamic.map { |target| "render(#{target.slice})" }.join("\n"), name)
482
+ declared = partial_paths_in(literal.map { |target| "render(#{target.slice})" }.join("\n"), name)
483
+ finder = ActionView::LookupContext.new(view_paths, variants: :any, locale: I18n.available_locales)
484
+
485
+ unresolved | inferred.reject do |path|
486
+ declared.include?(path) || finder.exists?(path, [], true)
487
+ end
488
+ end
489
+
490
+ def render_targets(call)
491
+ arguments = call.arguments&.arguments || []
492
+ targets = arguments.flat_map do |argument|
493
+ if argument.is_a?(Prism::KeywordHashNode) || argument.is_a?(Prism::HashNode)
494
+ argument.elements.filter_map do |element|
495
+ next unless element.is_a?(Prism::AssocNode) && element.key.is_a?(Prism::SymbolNode)
496
+ next unless %w[partial template layout spacer_template].include?(element.key.unescaped)
497
+
498
+ element.value
499
+ end
500
+ elsif argument.equal?(arguments.first)
501
+ argument
502
+ end
503
+ end.compact
504
+
505
+ targets.map do |target|
506
+ while target.is_a?(Prism::ParenthesesNode) && target.body.is_a?(Prism::StatementsNode) && target.body.body.one?
507
+ target = target.body.body.first
508
+ end
509
+ target
510
+ end
511
+ end
512
+
513
+ # Record the actual class name rather than trying to reverse a virtual
514
+ # path, which may contain acronyms or be overridden by the component.
515
+ def registered_path_for(component)
516
+ return unless component
517
+
518
+ register(component)
519
+ virtual_path_for(component)
520
+ end
521
+
231
522
  # Drop Action View's memoized template digests, leaving its resolver
232
523
  # caches alone: no template changed, only the set of dependencies the
233
524
  # Digestor can see.
@@ -235,18 +526,36 @@ module ViewComponent
235
526
  ActionView::LookupContext::DetailsKey.digest_caches.each(&:clear)
236
527
  end
237
528
 
238
- # Resolve a constant name to a component that opted into caching.
529
+ # Resolve a constant name to any ViewComponent.
239
530
  #
240
531
  # Returns nil for anything else, including constants that don't exist.
241
532
  # Autoloading here is safe: the template is about to render this constant
242
533
  # anyway.
243
- def constantize_component(constant_name)
244
- component = constant_name.safe_constantize
245
- return unless component.is_a?(Class)
246
- return unless component.respond_to?(:__vc_cacheable?) && component.__vc_cacheable?
534
+ def constantize_component(constant_name, nesting = [])
535
+ component = resolve_constant(constant_name, nesting)
536
+ return unless component.is_a?(Class) && component < ViewComponent::Base
247
537
 
248
538
  component
249
539
  end
540
+
541
+ def resolve_constant(name, nesting)
542
+ return unless CONSTANT_NAME.match?(name)
543
+ return name.safe_constantize if nesting.empty? || name.start_with?("::")
544
+
545
+ first, *rest = name.split("::")
546
+ # Lexical constants precede inherited constants. Once a name resolves,
547
+ # do not fall back to a top-level component if it names something else.
548
+ owner = nesting.find { |namespace| namespace.const_defined?(first, false) }
549
+ owner ||= nesting.first if nesting.first.const_defined?(first)
550
+ owner ||= Object if Object.const_defined?(first)
551
+ return unless owner
552
+
553
+ constant = owner.const_get(first)
554
+ return constant if rest.empty?
555
+ return unless constant.is_a?(Module) && constant.name
556
+
557
+ "#{constant.name}::#{rest.join("::")}".safe_constantize
558
+ end
250
559
  end
251
560
 
252
561
  # Resolved once at load time rather than memoized, so no class-level state