view_component 4.20.0 → 4.22.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 (35) hide show
  1. checksums.yaml +4 -4
  2. data/docs/CHANGELOG.md +120 -0
  3. data/lib/generators/view_component/abstract_generator.rb +24 -4
  4. data/lib/generators/view_component/component/component_generator.rb +8 -6
  5. data/lib/generators/view_component/component/templates/component.rb.tt +1 -1
  6. data/lib/generators/view_component/erb/erb_generator.rb +2 -2
  7. data/lib/generators/view_component/haml/haml_generator.rb +1 -1
  8. data/lib/generators/view_component/locale/locale_generator.rb +2 -6
  9. data/lib/generators/view_component/preview/preview_generator.rb +9 -6
  10. data/lib/generators/view_component/preview/templates/component_preview.rb.tt +2 -2
  11. data/lib/generators/view_component/rspec/rspec_generator.rb +1 -1
  12. data/lib/generators/view_component/rspec/templates/component_spec.rb.tt +1 -1
  13. data/lib/generators/view_component/slim/slim_generator.rb +1 -1
  14. data/lib/generators/view_component/stimulus/stimulus_generator.rb +3 -7
  15. data/lib/generators/view_component/test_unit/templates/component_test.rb.tt +2 -2
  16. data/lib/generators/view_component/test_unit/test_unit_generator.rb +8 -7
  17. data/lib/view_component/base.rb +110 -102
  18. data/lib/view_component/cache_digest/dependency_tracking.rb +25 -19
  19. data/lib/view_component/cache_digest/digestor_lookup.rb +47 -1
  20. data/lib/view_component/cache_digest/resolver.rb +73 -41
  21. data/lib/view_component/cache_digest.rb +221 -61
  22. data/lib/view_component/cacheable.rb +16 -18
  23. data/lib/view_component/collection.rb +4 -9
  24. data/lib/view_component/compile_cache.rb +51 -9
  25. data/lib/view_component/compiler.rb +50 -2
  26. data/lib/view_component/config.rb +114 -8
  27. data/lib/view_component/engine.rb +1 -2
  28. data/lib/view_component/errors.rb +16 -0
  29. data/lib/view_component/slot.rb +12 -0
  30. data/lib/view_component/slotable.rb +28 -4
  31. data/lib/view_component/template.rb +16 -3
  32. data/lib/view_component/test_helpers.rb +38 -16
  33. data/lib/view_component/translatable.rb +34 -0
  34. data/lib/view_component/version.rb +1 -1
  35. metadata +1 -1
@@ -4,6 +4,7 @@ require "active_support/dependencies/autoload"
4
4
  require "action_view/digestor"
5
5
  require "action_view/render_parser"
6
6
  require "prism"
7
+ require "strscan"
7
8
 
8
9
  module ViewComponent
9
10
  # Integrates ViewComponents into Rails' template digest tree.
@@ -42,11 +43,8 @@ module ViewComponent
42
43
  RENDER_METHODS = %i[render render_to_string].freeze
43
44
 
44
45
  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]/
46
+ MEMO = :view_component_cache_digest_memo
47
+ private_constant :COMPILED_SOURCES, :MEMO
50
48
 
51
49
  # Rails' escape hatch for dependencies static analysis can't see.
52
50
  EXPLICIT_DEPENDENCY = /#\s*Template Dependency:\s*(\S+)/
@@ -112,6 +110,35 @@ module ViewComponent
112
110
  Thread.current[COMPILED_SOURCES]&.dig(template.handler, source) || template.handler.call(template, source)
113
111
  end
114
112
 
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]
118
+ #
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
141
+
115
142
  # Find the components Ruby source references and the partials it
116
143
  # renders.
117
144
  #
@@ -126,42 +153,40 @@ module ViewComponent
126
153
  #
127
154
  # @param source [String] Ruby source
128
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
129
158
  # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
130
159
  # 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
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]
141
167
  end
142
-
143
- components = names.uniq.filter_map { |constant_name| constantize_component(constant_name) }
144
- [component_paths(components), partials_rendered_by(other_calls, name)]
145
168
  end
146
169
 
147
- # Find the components Ruby source renders, along with the partials Action
148
- # View infers from them.
170
+ # Find the components Ruby source renders, along with partial guesses
171
+ # Action View should discard.
149
172
  #
150
173
  # Action View reads `render FooComponent.new` as a dynamic render of a
151
174
  # partial named after the last method, inferring `news/new`. Partials also
152
- # rendered some other way aren't returned.
175
+ # rendered some other way aren't returned. Unresolved guesses from other
176
+ # dynamic renders are discarded when view paths are available.
153
177
  #
154
178
  # @param source [String] Ruby source
155
179
  # @param name [String] virtual path the source is being digested under
180
+ # @param view_paths [ActionView::PathSet, nil] paths to check dynamic partial guesses against
156
181
  # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
157
182
  # 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?
183
+ def template_renders_in(source, name, view_paths: nil)
184
+ components, component_calls, other_calls = partition_render_calls(Prism.parse(source).value)
161
185
 
162
186
  [
163
- component_paths(components.values),
164
- partials_rendered_by(components.keys, name) - partials_rendered_by(other_calls, name)
187
+ component_paths(components),
188
+ (partials_rendered_by(component_calls, name) - partials_rendered_by(other_calls, name)) |
189
+ unresolved_partials_rendered_by(other_calls, name, view_paths)
165
190
  ]
166
191
  end
167
192
 
@@ -213,24 +238,28 @@ module ViewComponent
213
238
  # Compute the digest of a component using Rails' digest tree.
214
239
  #
215
240
  # @param component [Class] a component class
216
- # @param finder [ActionView::LookupContext]
241
+ # @param finder [ActionView::LookupContext, nil]
217
242
  # @param format [Symbol]
243
+ #
218
244
  # @return [String]
219
- def digest(component, finder: default_finder, format: :html)
245
+ def digest(component, finder: nil, format: :html)
220
246
  register(component)
221
247
  virtual_path = virtual_path_for(component)
222
248
  return "" unless virtual_path
223
249
 
250
+ finder ||= default_finder(format: format)
224
251
  ActionView::Digestor.digest(name: virtual_path, format: format, finder: finder)
225
252
  end
226
253
 
227
254
  # A lookup context for digesting components outside a request, where no
228
255
  # view context (and therefore no finder) exists.
229
256
  #
257
+ # @param format [Symbol]
258
+ #
230
259
  # @return [ActionView::LookupContext]
231
- def default_finder
260
+ def default_finder(format: :html)
232
261
  # Not memoized across reloads: view paths change when the app reloads.
233
- ActionView::LookupContext.new(ActionController::Base.view_paths)
262
+ ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [format])
234
263
  end
235
264
 
236
265
  # Wire the tracker and resolver into Action View.
@@ -256,6 +285,40 @@ module ViewComponent
256
285
  Thread.current[COMPILED_SOURCES] = nil
257
286
  end
258
287
 
288
+ # Share synthetic templates between every lookup in the block.
289
+ #
290
+ # The Digestor looks a template up once per edge of the tree, before it
291
+ # checks whether it has seen the template already. Action View's own
292
+ # resolvers cache their templates, but building a synthetic one reads and
293
+ # parses the component's sources, so a component rendered from many
294
+ # places was rebuilt once per place. Kept for one digest computation
295
+ # only, so a source edited between requests is still seen.
296
+ #
297
+ # @private
298
+ def memoizing
299
+ return yield if Thread.current[MEMO]
300
+
301
+ begin
302
+ Thread.current[MEMO] = {}
303
+ yield
304
+ ensure
305
+ Thread.current[MEMO] = nil
306
+ end
307
+ end
308
+
309
+ # @private
310
+ def memo
311
+ Thread.current[MEMO]
312
+ end
313
+
314
+ # @private
315
+ def memoize(key)
316
+ memo = Thread.current[MEMO]
317
+ return yield unless memo
318
+
319
+ memo.fetch(key) { memo[key] = yield }
320
+ end
321
+
259
322
  # @private
260
323
  def compiled(handler, source, compiled_source)
261
324
  sources = Thread.current[COMPILED_SOURCES]
@@ -276,53 +339,74 @@ module ViewComponent
276
339
  # digest, so registering midway would discard digests already warmed.
277
340
  components.each { |component| register(component) }
278
341
 
279
- components.each do |component|
280
- component.__vc_cache_digest_source = Resolver.instance.source_for(component).freeze
281
- end
342
+ memoizing do
343
+ components.each do |component|
344
+ component.__vc_cache_digest_source = Resolver.instance.source_for(component).freeze
345
+ end
282
346
 
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)
347
+ # Warms the same digest cache requests read, since a lookup context's
348
+ # cache is shared by every context with the same details.
349
+ components.each do |component|
350
+ component.__vc_template_formats.each do |format|
351
+ finder = ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [format])
352
+ component.cache_digest(finder: finder, format: format)
353
+ end
289
354
  end
290
355
  end
291
356
  end
292
357
 
293
358
  private
294
359
 
295
- # Receiverless `render` and `render_to_string` calls, split into those
296
- # that render a component and the rest.
360
+ # Component references and receiverless render calls, split into those
361
+ # that render a component directly and the rest.
297
362
  #
298
- # @return [Array(Hash{Prism::CallNode => Class}, Array<Prism::CallNode>)]
299
- def partition_render_calls(program)
300
- components = {}
363
+ # @return [Array(Array<Class>, Array<Prism::CallNode>, Array<Prism::CallNode>)]
364
+ def partition_render_calls(program, nesting = [])
365
+ names = []
366
+ component_calls = []
301
367
  other_calls = []
302
368
 
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
369
+ each_node(program, nesting) do |node, scope|
370
+ if node.is_a?(Prism::ConstantReadNode) || node.is_a?(Prism::ConstantPathNode)
371
+ name = node.slice
372
+ names << [name, scope] if CONSTANT_NAME.match?(name)
373
+ elsif render_call?(node)
374
+ if rendered_component(node, scope)
375
+ component_calls << node
376
+ else
377
+ other_calls << node
378
+ end
310
379
  end
311
380
  end
312
381
 
313
- [components, other_calls]
382
+ components = names.uniq.filter_map { |constant_name, scope| constantize_component(constant_name, scope) }
383
+ [components, component_calls, other_calls]
314
384
  end
315
385
 
316
386
  def render_call?(node)
317
387
  node.is_a?(Prism::CallNode) && node.receiver.nil? && RENDER_METHODS.include?(node.name)
318
388
  end
319
389
 
320
- # Visit every node of a Prism tree, in source order.
321
- def each_node(program)
322
- nodes = [program]
390
+ # Class/module bodies add one lexical scope, even for qualified names:
391
+ # `class UI::Card` adds Card, not UI, to Module.nesting.
392
+ def each_node(program, nesting = [])
393
+ # Keep scopes and nodes in one stack rather than allocating a pair per node.
394
+ nodes = [nesting, program]
323
395
  while (node = nodes.pop)
324
- yield node
325
- nodes.concat(node.compact_child_nodes.reverse!)
396
+ scope = nodes.pop
397
+ yield node, scope
398
+
399
+ body = nil
400
+ body_scope = scope
401
+ if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
402
+ body = node.body
403
+ namespace = resolve_constant(node.constant_path.slice, scope)
404
+ body_scope = [namespace, *scope] if namespace.is_a?(Module)
405
+ end
406
+
407
+ node.compact_child_nodes.reverse_each do |child|
408
+ nodes.push(child.equal?(body) ? body_scope : scope, child)
409
+ end
326
410
  end
327
411
  end
328
412
 
@@ -331,13 +415,13 @@ module ViewComponent
331
415
  # `FooComponent.with_collection(...)`, and so on.
332
416
  #
333
417
  # @return [Class, nil]
334
- def rendered_component(call)
418
+ def rendered_component(call, nesting = [])
335
419
  node = call.arguments&.arguments&.first
336
420
  node = node.receiver while node.is_a?(Prism::CallNode) && node.receiver
337
421
 
338
422
  case node
339
423
  when Prism::ConstantReadNode, Prism::ConstantPathNode
340
- constantize_component(node.slice)
424
+ constantize_component(node.slice, nesting)
341
425
  end
342
426
  end
343
427
 
@@ -363,11 +447,68 @@ module ViewComponent
363
447
  return [] if calls.empty?
364
448
 
365
449
  source = calls.map { |call| "#{call.name}(#{call.arguments&.slice})" }.join("\n")
450
+ partial_paths_in(source, name)
451
+ end
452
+
453
+ def partial_paths_in(source, name)
366
454
  RENDER_PARSER.new(name, source).render_calls
367
455
  .map { |path| path.gsub(%r{/_}, "/") }
368
456
  .uniq
369
457
  end
370
458
 
459
+ # Dynamic renders can return components without naming their classes,
460
+ # such as `render UI.button`. Keep Action View's guess only if it resolves,
461
+ # without executing application methods to discover what they return.
462
+ # Interpolated paths are discarded if Rails cannot expand their wildcards.
463
+ def unresolved_partials_rendered_by(calls, name, view_paths)
464
+ targets = calls.flat_map { |call| render_targets(call) }
465
+ literal, dynamic = targets.partition do |target|
466
+ target.is_a?(Prism::StringNode) || target.is_a?(Prism::InterpolatedStringNode)
467
+ end
468
+ interpolated = literal.grep(Prism::InterpolatedStringNode)
469
+ unresolved = []
470
+ if interpolated.any?
471
+ paths = partial_paths_in(interpolated.map { |target| "render(#{target.slice})" }.join("\n"), name)
472
+ # Rails expands only directory wildcards with a literal prefix.
473
+ # Older parsers can return truncated paths without any wildcard.
474
+ unresolved = paths.reject { |path| path.match?(%r{\A[^*]+/\*\z}) }
475
+ static = literal.grep(Prism::StringNode)
476
+ unresolved -= partial_paths_in(static.map { |target| "render(#{target.slice})" }.join("\n"), name)
477
+ end
478
+ return unresolved unless view_paths && dynamic.any?
479
+
480
+ inferred = partial_paths_in(dynamic.map { |target| "render(#{target.slice})" }.join("\n"), name)
481
+ declared = partial_paths_in(literal.map { |target| "render(#{target.slice})" }.join("\n"), name)
482
+ finder = ActionView::LookupContext.new(view_paths, variants: :any, locale: I18n.available_locales)
483
+
484
+ unresolved | inferred.reject do |path|
485
+ declared.include?(path) || finder.exists?(path, [], true)
486
+ end
487
+ end
488
+
489
+ def render_targets(call)
490
+ arguments = call.arguments&.arguments || []
491
+ targets = arguments.flat_map do |argument|
492
+ if argument.is_a?(Prism::KeywordHashNode) || argument.is_a?(Prism::HashNode)
493
+ argument.elements.filter_map do |element|
494
+ next unless element.is_a?(Prism::AssocNode) && element.key.is_a?(Prism::SymbolNode)
495
+ next unless %w[partial template layout spacer_template].include?(element.key.unescaped)
496
+
497
+ element.value
498
+ end
499
+ elsif argument.equal?(arguments.first)
500
+ argument
501
+ end
502
+ end.compact
503
+
504
+ targets.map do |target|
505
+ while target.is_a?(Prism::ParenthesesNode) && target.body.is_a?(Prism::StatementsNode) && target.body.body.one?
506
+ target = target.body.body.first
507
+ end
508
+ target
509
+ end
510
+ end
511
+
371
512
  # Record the actual class name rather than trying to reverse a virtual
372
513
  # path, which may contain acronyms or be overridden by the component.
373
514
  def registered_path_for(component)
@@ -389,12 +530,31 @@ module ViewComponent
389
530
  # Returns nil for anything else, including constants that don't exist.
390
531
  # Autoloading here is safe: the template is about to render this constant
391
532
  # anyway.
392
- def constantize_component(constant_name)
393
- component = constant_name.safe_constantize
533
+ def constantize_component(constant_name, nesting = [])
534
+ component = resolve_constant(constant_name, nesting)
394
535
  return unless component.is_a?(Class) && component < ViewComponent::Base
395
536
 
396
537
  component
397
538
  end
539
+
540
+ def resolve_constant(name, nesting)
541
+ return unless CONSTANT_NAME.match?(name)
542
+ return name.safe_constantize if nesting.empty? || name.start_with?("::")
543
+
544
+ first, *rest = name.split("::")
545
+ # Lexical constants precede inherited constants. Once a name resolves,
546
+ # do not fall back to a top-level component if it names something else.
547
+ owner = nesting.find { |namespace| namespace.const_defined?(first, false) }
548
+ owner ||= nesting.first if nesting.first.const_defined?(first)
549
+ owner ||= Object if Object.const_defined?(first)
550
+ return unless owner
551
+
552
+ constant = owner.const_get(first)
553
+ return constant if rest.empty?
554
+ return unless constant.is_a?(Module) && constant.name
555
+
556
+ "#{constant.name}::#{rest.join("::")}".safe_constantize
557
+ end
398
558
  end
399
559
 
400
560
  # Resolved once at load time rather than memoized, so no class-level state
@@ -117,25 +117,32 @@ module ViewComponent
117
117
  # The cache key for this rendering of the component.
118
118
  #
119
119
  # Combines the component's identity, its source digest, the requested
120
- # format and variant, the current locale, and the values declared with
121
- # `cache_on`. Override for full control.
120
+ # ordered formats, variants and partial lookup prefixes, the current locale,
121
+ # and the values declared with `cache_on`. Override for full control.
122
122
  #
123
123
  # @param view_context [ActionView::Base]
124
124
  # @return [String]
125
125
  def cache_key(view_context = nil)
126
126
  lookup_context = view_context&.lookup_context
127
- format = __vc_cache_format(lookup_context)
127
+ formats = Array(lookup_context&.formats).presence || [:html]
128
+ values = __vc_cache_on_values.map do |value|
129
+ value.nil? ? nil : ActiveSupport::Cache.expand_cache_key(value)
130
+ end
128
131
 
129
132
  parts = [
130
133
  "view_component",
131
134
  self.class.virtual_path,
132
- self.class.cache_digest(finder: lookup_context, format: format),
135
+ self.class.cache_digest(finder: lookup_context, format: formats.first),
133
136
  # Included in its own right, not just as a digest input: components that
134
137
  # render every format from one template have the same digest for each.
135
- format,
136
- __vc_cache_variant(lookup_context),
138
+ # Encode each list to keep format and variant boundaries distinct.
139
+ formats.to_json,
140
+ __vc_cache_variants(lookup_context).to_json,
141
+ Array(lookup_context&.prefixes).to_json,
137
142
  I18n.locale,
138
- *__vc_cache_on_values
143
+ # Expand records using Rails' versioned keys, then preserve the boundaries
144
+ # between declared values, including nils and strings containing slashes.
145
+ values.to_json
139
146
  ]
140
147
 
141
148
  # Positions are significant, so nils are substituted rather than removed.
@@ -175,11 +182,6 @@ module ViewComponent
175
182
  end
176
183
  end
177
184
 
178
- def __vc_render_uncached(view_context)
179
- @__vc_cache_bypassed = true
180
- render_in(view_context)
181
- end
182
-
183
185
  # Slots set by the caller via `with_*`. Checked before rendering, so slots
184
186
  # a component fills in for itself with a `default_*` method — which resolve
185
187
  # lazily during the render — aren't counted.
@@ -227,12 +229,8 @@ module ViewComponent
227
229
  end
228
230
  end
229
231
 
230
- def __vc_cache_format(lookup_context)
231
- Array(lookup_context&.formats).first || :html
232
- end
233
-
234
- def __vc_cache_variant(lookup_context)
235
- Array(lookup_context&.variants).first
232
+ def __vc_cache_variants(lookup_context)
233
+ Array(lookup_context&.variants)
236
234
  end
237
235
  end
238
236
  end
@@ -41,12 +41,12 @@ module ViewComponent
41
41
  def components
42
42
  component.__vc_validate_collection_parameter!(validate_default: true)
43
43
 
44
- iterator = ActionView::PartialIteration.new(@collection.size)
45
44
  collection_param = component.__vc_collection_parameter
46
45
  counter_present = component.__vc_counter_argument_present?
47
46
  counter_param = component.__vc_collection_counter_parameter if counter_present
48
47
  iteration_present = component.__vc_iteration_argument_present?
49
48
  iteration_param = component.__vc_collection_iteration_parameter if iteration_present
49
+ iterator = ActionView::PartialIteration.new(@collection.size) if counter_present || iteration_present
50
50
  item_options = @options.dup
51
51
 
52
52
  @collection.map do |item|
@@ -54,7 +54,7 @@ module ViewComponent
54
54
  item_options[counter_param] = iterator.index if counter_present
55
55
  item_options[iteration_param] = iterator.dup if iteration_present
56
56
  instance = component.new(**item_options)
57
- iterator.iterate!
57
+ iterator&.iterate!
58
58
  instance
59
59
  end
60
60
  end
@@ -74,16 +74,11 @@ module ViewComponent
74
74
  end
75
75
  end
76
76
 
77
- # Render the spacer through a fresh `dup` so a collection rendered multiple
78
- # times does not reuse (and trip the single-render guard on) the spacer
79
- # instance passed by the caller.
77
+ # Keep the caller's spacer unrendered, including its nested slot components.
80
78
  def rendered_spacer(view_context)
81
79
  return EMPTY_SPACER unless @spacer_component
82
80
 
83
- spacer = @spacer_component.dup
84
- if spacer.instance_variable_defined?(:@__vc_rendered)
85
- spacer.remove_instance_variable(:@__vc_rendered)
86
- end
81
+ spacer = @spacer_component.is_a?(Base) ? @spacer_component.__vc_dup_for_render : @spacer_component.dup
87
82
  spacer.render_in(view_context)
88
83
  end
89
84
  end
@@ -15,7 +15,7 @@ module ViewComponent
15
15
  end
16
16
 
17
17
  def compiled?(klass)
18
- cache.include? klass
18
+ @@cache.include? klass
19
19
  end
20
20
 
21
21
  def invalidate_class!(klass)
@@ -26,14 +26,36 @@ module ViewComponent
26
26
  cache.clear
27
27
  end
28
28
 
29
- # Sidecar files can't change while the application eager loads: within the
30
- # block, each component's are looked up once. Fiber storage rather than
31
- # module state, so the cache is gone once boot is done.
29
+ # Share directory listings, sidecar lookups, and file contents within one
30
+ # eager load or digest computation, but never across reloads.
32
31
  def with_sidecar_files_cache
33
- Fiber[:__vc_sidecar_files] = {}
34
- yield
35
- ensure
36
- Fiber[:__vc_sidecar_files] = nil
32
+ return yield if Fiber[:__vc_sidecar_files]
33
+
34
+ begin
35
+ Fiber[:__vc_sidecar_files] = {}
36
+ Fiber[:__vc_sidecar_directories] = {}
37
+ Fiber[:__vc_source_files] = {}
38
+ Fiber[:__vc_path_parser] = ActionView::Resolver::PathParser.new
39
+ yield
40
+ ensure
41
+ Fiber[:__vc_sidecar_files] = nil
42
+ Fiber[:__vc_sidecar_directories] = nil
43
+ Fiber[:__vc_source_files] = nil
44
+ Fiber[:__vc_path_parser] = nil
45
+ end
46
+ end
47
+
48
+ def path_parser
49
+ # Its regular expression depends on registered handlers, formats and locales.
50
+ # Reuse it during eager loading or a digest computation, but not across reloads.
51
+ Fiber[:__vc_path_parser] || ActionView::Resolver::PathParser.new
52
+ end
53
+
54
+ def read_file(path)
55
+ files = Fiber[:__vc_source_files]
56
+ return File.read(path) unless files
57
+
58
+ (files[path] ||= File.read(path).freeze).dup
37
59
  end
38
60
 
39
61
  def sidecar_files_for(klass, extensions)
@@ -44,13 +66,33 @@ module ViewComponent
44
66
  sidecar_files[extensions] ||= yield.freeze
45
67
  end
46
68
 
69
+ def sidecar_files_matching(pattern)
70
+ directories = Fiber[:__vc_sidecar_directories]
71
+ return Dir[pattern] unless directories
72
+
73
+ filename = File.basename(pattern)
74
+ prefix = filename.delete_suffix(".*")
75
+ return Dir[pattern] if prefix.match?(/[*?{}\[\]\\]/)
76
+
77
+ directory = File.dirname(pattern)
78
+ # Index the shared directory by component name instead of scanning all
79
+ # its entries again for every component and extension.
80
+ entries = directories[directory] ||= Dir.glob("#{directory}/*", File::FNM_DOTMATCH)
81
+ .group_by { |path| File.basename(path).split(".", 2).first }
82
+ candidates = entries.fetch(prefix.split(".", 2).first, [])
83
+ candidates.select { |path| File.fnmatch?(filename, File.basename(path)) }
84
+ end
85
+
47
86
  # Invalidates the cache when a template or a translation file is added,
48
87
  # changed, or removed. Changes to Ruby files reload the application instead.
49
88
  def template_watcher(file_watcher)
50
89
  extensions = ActionView::Template::Handlers.extensions.map(&:to_s) + %w[yml yaml]
51
90
  directories = ActiveSupport::Dependencies.autoload_paths.map(&:to_s).index_with(extensions)
52
91
 
53
- file_watcher.new([], directories) { invalidate! }
92
+ file_watcher.new([], directories) do
93
+ invalidate!
94
+ ActionView::LookupContext::DetailsKey.clear
95
+ end
54
96
  end
55
97
  end
56
98
  end