view_component 4.19.0 → 4.21.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 (38) 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 +144 -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 +127 -101
  20. data/lib/view_component/cache_digest/dependency_tracking.rb +9 -1
  21. data/lib/view_component/cache_digest/digestor_lookup.rb +3 -1
  22. data/lib/view_component/cache_digest/resolver.rb +131 -52
  23. data/lib/view_component/cache_digest.rb +286 -48
  24. data/lib/view_component/cacheable.rb +16 -18
  25. data/lib/view_component/collection.rb +4 -9
  26. data/lib/view_component/compile_cache.rb +59 -2
  27. data/lib/view_component/compiler.rb +76 -13
  28. data/lib/view_component/config.rb +114 -8
  29. data/lib/view_component/engine.rb +10 -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 +12 -0
  33. data/lib/view_component/slotable.rb +32 -8
  34. data/lib/view_component/template.rb +33 -15
  35. data/lib/view_component/test_helpers.rb +38 -16
  36. data/lib/view_component/translatable.rb +35 -1
  37. data/lib/view_component/version.rb +1 -1
  38. metadata +17 -1
@@ -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.
@@ -38,23 +40,18 @@ 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
+ private_constant :COMPILED_SOURCES
55
47
 
56
48
  # Rails' escape hatch for dependencies static analysis can't see.
57
49
  EXPLICIT_DEPENDENCY = /#\s*Template Dependency:\s*(\S+)/
50
+
51
+ # A constant path made only of constants, such as `Foo` or `::Foo::Bar`,
52
+ # rather than one hanging off an expression, such as `self.class::Bar`.
53
+ CONSTANT_NAME = /\A(?:::)?[A-Z]\w*(?:::[A-Z]\w*)*\z/
54
+
58
55
  class << self
59
56
  # Virtual paths of components, mapped to their class names.
60
57
  #
@@ -102,46 +99,104 @@ module ViewComponent
102
99
  constantize_component(name)
103
100
  end
104
101
 
105
- # Scan a template's source for renders of components.
102
+ # Compile a template to Ruby with its own handler, so ERB, Haml, Slim and
103
+ # any other template language can be analyzed the same way. Reuses the
104
+ # Ruby compiled at boot, when there is some.
106
105
  #
107
- # @return [Array<String>] synthetic virtual paths
108
- def dependencies_in(template)
109
- component_paths_in(template.source)
106
+ # @return [String] Ruby source
107
+ def compiled_source(template)
108
+ source = template.source
109
+ Thread.current[COMPILED_SOURCES]&.dig(template.handler, source) || template.handler.call(template, source)
110
110
  end
111
111
 
112
- # Scan arbitrary source (a template or a component's Ruby file) for
113
- # renders of components.
112
+ # Skip literal templates and ERB markup before compiling Ruby for analysis.
113
+ # Other handlers keep a conservative check because their code syntax varies.
114
114
  #
115
- # @return [Array<String>] synthetic virtual paths
116
- def component_paths_in(source)
117
- return [] unless source.is_a?(String) && source.include?("render")
118
-
119
- source.scan(RENDER_CALL).flatten.uniq.filter_map do |constant_name|
120
- registered_path_for(constantize_component(constant_name))
115
+ # @param source [String]
116
+ # @param handler [#call]
117
+ #
118
+ # @return [Boolean]
119
+ def template_dependencies?(source, handler)
120
+ return false unless source.match?(/render|[A-Z]/)
121
+
122
+ case handler
123
+ when ActionView::Template::Handlers::Raw, ActionView::Template::Handlers::Html
124
+ false
125
+ when ActionView::Template::Handlers::ERB
126
+ # Never restart the search at another opener after an unterminated tag.
127
+ scanner = StringScanner.new(source)
128
+ while scanner.skip_until(/<%/)
129
+ code = scanner.scan_until(/%>/)
130
+ return false unless code
131
+ next if code.start_with?("#", "%")
132
+
133
+ return true if code.match?(/render|[A-Z]/)
134
+ end
135
+ false
136
+ else
137
+ true
121
138
  end
122
139
  end
123
140
 
124
- # Scan a component's Ruby source for partials referenced by string path,
125
- # such as `render "posts/byline"` inside a `#call` method.
141
+ # Find the components Ruby source references and the partials it
142
+ # renders.
143
+ #
144
+ # Every constant that names a component counts, not only one passed
145
+ # straight to `render`: a component can also be rendered from a method
146
+ # that builds it, from a local variable, or from a slot declared with its
147
+ # class. A component referenced without being rendered only makes the
148
+ # digest change more often than it needs to.
126
149
  #
127
- # Uses Rails' own render parser — the same one `RubyTracker` runs over
128
- # compiled templates — rather than a second implementation of the same
129
- # analysis. Its results are then narrowed to paths that appear verbatim in
130
- # the source, which keeps string literals and discards the speculative
131
- # `things/_thing` entries the parser infers from dynamic renders like
132
- # `render @thing` or `render FooComponent.new`. Those would resolve to
133
- # nothing and only add log noise; components rendered from Ruby are
134
- # already found precisely by `component_paths_in`.
150
+ # Action View's render parser only sees the calls that don't render a
151
+ # component, so it can't infer partials from them.
135
152
  #
136
153
  # @param source [String] Ruby source
137
154
  # @param name [String] virtual path the source is being digested under
138
- # @return [Array<String>] partial virtual paths
139
- def partial_paths_in(source, name)
140
- return [] unless source.is_a?(String) && source.include?("render")
155
+ # @param view_paths [ActionView::PathSet, nil] paths to check dynamic partial guesses against
156
+ # @param nesting [Array<Module>] lexical scope of compiled template source
157
+ # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
158
+ # components and partial virtual paths
159
+ def renders_in(source, name, view_paths: nil, nesting: [])
160
+ components, _component_calls, other_calls = partition_render_calls(Prism.parse(source).value, nesting)
161
+ partials = partials_rendered_by(other_calls, name) - unresolved_partials_rendered_by(other_calls, name, view_paths)
162
+ [component_paths(components), partials]
163
+ end
141
164
 
142
- RENDER_PARSER.new(name, source).render_calls.uniq.select do |path|
143
- source.include?(path) || source.include?(path.sub(%r{(\A|/)_}, '\1'))
144
- end
165
+ # Find the components Ruby source renders, along with partial guesses
166
+ # Action View should discard.
167
+ #
168
+ # Action View reads `render FooComponent.new` as a dynamic render of a
169
+ # partial named after the last method, inferring `news/new`. Partials also
170
+ # rendered some other way aren't returned. Unresolved guesses from other
171
+ # dynamic renders are discarded when view paths are available.
172
+ #
173
+ # @param source [String] Ruby source
174
+ # @param name [String] virtual path the source is being digested under
175
+ # @param view_paths [ActionView::PathSet, nil] paths to check dynamic partial guesses against
176
+ # @return [Array(Array<String>, Array<String>)] synthetic virtual paths of
177
+ # components and inferred partial virtual paths
178
+ def template_renders_in(source, name, view_paths: nil)
179
+ components, component_calls, other_calls = partition_render_calls(Prism.parse(source).value)
180
+
181
+ [
182
+ component_paths(components),
183
+ (partials_rendered_by(component_calls, name) - partials_rendered_by(other_calls, name)) |
184
+ unresolved_partials_rendered_by(other_calls, name, view_paths)
185
+ ]
186
+ end
187
+
188
+ # Find the components a component's slots render, from the class each
189
+ # slot was declared with: `renders_one :header, HeaderComponent` or
190
+ # `renders_many :items, "ItemComponent"`. Read from the slot definitions
191
+ # rather than from source, since a class named by a string, or by a name
192
+ # relative to the component, resolves against the component at runtime.
193
+ #
194
+ # @param component [Class]
195
+ # @return [Array<String>] synthetic virtual paths of components
196
+ def slot_renders_of(component)
197
+ definitions = component.registered_slots.values.flat_map { |slot| slot[:renderable_hash]&.values || [slot] }
198
+
199
+ component_paths(definitions.filter_map { |slot| slot_component(component, slot) })
145
200
  end
146
201
 
147
202
  # Action View has shipped its render parser as a class (Rails 7.1, and
@@ -178,24 +233,28 @@ module ViewComponent
178
233
  # Compute the digest of a component using Rails' digest tree.
179
234
  #
180
235
  # @param component [Class] a component class
181
- # @param finder [ActionView::LookupContext]
236
+ # @param finder [ActionView::LookupContext, nil]
182
237
  # @param format [Symbol]
238
+ #
183
239
  # @return [String]
184
- def digest(component, finder: default_finder, format: :html)
240
+ def digest(component, finder: nil, format: :html)
185
241
  register(component)
186
242
  virtual_path = virtual_path_for(component)
187
243
  return "" unless virtual_path
188
244
 
245
+ finder ||= default_finder(format: format)
189
246
  ActionView::Digestor.digest(name: virtual_path, format: format, finder: finder)
190
247
  end
191
248
 
192
249
  # A lookup context for digesting components outside a request, where no
193
250
  # view context (and therefore no finder) exists.
194
251
  #
252
+ # @param format [Symbol]
253
+ #
195
254
  # @return [ActionView::LookupContext]
196
- def default_finder
255
+ def default_finder(format: :html)
197
256
  # Not memoized across reloads: view paths change when the app reloads.
198
- ActionView::LookupContext.new(ActionController::Base.view_paths)
257
+ ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [format])
199
258
  end
200
259
 
201
260
  # Wire the tracker and resolver into Action View.
@@ -208,6 +267,25 @@ module ViewComponent
208
267
  DigestorLookup.install!
209
268
  end
210
269
 
270
+ # Keep the Ruby that templates compile to while the block runs, so
271
+ # `precompute!` can analyze templates components just compiled without
272
+ # compiling them again. Kept in a thread local rather than on the module,
273
+ # which isn't writable from other Ractors.
274
+ #
275
+ # @private
276
+ def retaining_compiled_sources
277
+ Thread.current[COMPILED_SOURCES] = {}
278
+ yield
279
+ ensure
280
+ Thread.current[COMPILED_SOURCES] = nil
281
+ end
282
+
283
+ # @private
284
+ def compiled(handler, source, compiled_source)
285
+ sources = Thread.current[COMPILED_SOURCES]
286
+ (sources[handler] ||= {})[source] = compiled_source if sources
287
+ end
288
+
211
289
  # Compute component digests at boot, so requests read them from memory
212
290
  # instead of reading and scanning source files.
213
291
  #
@@ -238,6 +316,147 @@ module ViewComponent
238
316
 
239
317
  private
240
318
 
319
+ # Component references and receiverless render calls, split into those
320
+ # that render a component directly and the rest.
321
+ #
322
+ # @return [Array(Array<Class>, Array<Prism::CallNode>, Array<Prism::CallNode>)]
323
+ def partition_render_calls(program, nesting = [])
324
+ names = []
325
+ component_calls = []
326
+ other_calls = []
327
+
328
+ each_node(program, nesting) do |node, scope|
329
+ if node.is_a?(Prism::ConstantReadNode) || node.is_a?(Prism::ConstantPathNode)
330
+ names << [node.slice, scope] if CONSTANT_NAME.match?(node.slice)
331
+ elsif render_call?(node)
332
+ if rendered_component(node, scope)
333
+ component_calls << node
334
+ else
335
+ other_calls << node
336
+ end
337
+ end
338
+ end
339
+
340
+ components = names.uniq.filter_map { |constant_name, scope| constantize_component(constant_name, scope) }
341
+ [components, component_calls, other_calls]
342
+ end
343
+
344
+ def render_call?(node)
345
+ node.is_a?(Prism::CallNode) && node.receiver.nil? && RENDER_METHODS.include?(node.name)
346
+ end
347
+
348
+ # Class/module bodies add one lexical scope, even for qualified names:
349
+ # `class UI::Card` adds Card, not UI, to Module.nesting.
350
+ def each_node(program, nesting = [])
351
+ nodes = [[program, nesting]]
352
+ while (entry = nodes.pop)
353
+ node, scope = entry
354
+ yield node, scope
355
+
356
+ body = nil
357
+ body_scope = scope
358
+ if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
359
+ body = node.body
360
+ namespace = resolve_constant(node.constant_path.slice, scope)
361
+ body_scope = [namespace, *scope] if namespace.is_a?(Module)
362
+ end
363
+
364
+ node.compact_child_nodes.reverse_each do |child|
365
+ nodes << [child, child.equal?(body) ? body_scope : scope]
366
+ end
367
+ end
368
+ end
369
+
370
+ # The component a render call renders, from the constant at the root of
371
+ # its first argument: `FooComponent`, `FooComponent.new(...)`,
372
+ # `FooComponent.with_collection(...)`, and so on.
373
+ #
374
+ # @return [Class, nil]
375
+ def rendered_component(call, nesting = [])
376
+ node = call.arguments&.arguments&.first
377
+ node = node.receiver while node.is_a?(Prism::CallNode) && node.receiver
378
+
379
+ case node
380
+ when Prism::ConstantReadNode, Prism::ConstantPathNode
381
+ constantize_component(node.slice, nesting)
382
+ end
383
+ end
384
+
385
+ def component_paths(components)
386
+ components.uniq.filter_map { |component| registered_path_for(component) }
387
+ end
388
+
389
+ # The component a slot renders, resolving a class name the way the slot
390
+ # does when it's set. A name that doesn't resolve is left to fail there.
391
+ def slot_component(component, slot)
392
+ renderable = slot[:renderable]
393
+ name = slot[:renderable_class_name]
394
+ renderable ||= component.const_get(name) if name && component.const_defined?(name)
395
+
396
+ renderable if renderable.is_a?(Class) && renderable < ViewComponent::Base
397
+ end
398
+
399
+ # Partials Action View's render parser finds in the given calls,
400
+ # normalized to the form its trackers report. The calls are parsed
401
+ # together, so the parser runs once rather than once per call. Blocks are
402
+ # left out, as any renders inside them are calls of their own.
403
+ def partials_rendered_by(calls, name)
404
+ return [] if calls.empty?
405
+
406
+ source = calls.map { |call| "#{call.name}(#{call.arguments&.slice})" }.join("\n")
407
+ partial_paths_in(source, name)
408
+ end
409
+
410
+ def partial_paths_in(source, name)
411
+ RENDER_PARSER.new(name, source).render_calls
412
+ .map { |path| path.gsub(%r{/_}, "/") }
413
+ .uniq
414
+ end
415
+
416
+ # Dynamic renders can return components without naming their classes,
417
+ # such as `render UI.button`. Keep Action View's guess only if it resolves,
418
+ # without executing application methods to discover what they return.
419
+ def unresolved_partials_rendered_by(calls, name, view_paths)
420
+ return [] unless view_paths
421
+
422
+ targets = calls.flat_map { |call| render_targets(call) }
423
+ literal, dynamic = targets.partition do |target|
424
+ target.is_a?(Prism::StringNode) || target.is_a?(Prism::InterpolatedStringNode)
425
+ end
426
+ return [] if dynamic.empty?
427
+
428
+ inferred = partial_paths_in(dynamic.map { |target| "render(#{target.slice})" }.join("\n"), name)
429
+ declared = partial_paths_in(literal.map { |target| "render(#{target.slice})" }.join("\n"), name)
430
+ finder = ActionView::LookupContext.new(view_paths, variants: :any, locale: I18n.available_locales)
431
+
432
+ inferred.reject do |path|
433
+ declared.include?(path) || finder.exists?(path, [], true)
434
+ end
435
+ end
436
+
437
+ def render_targets(call)
438
+ arguments = call.arguments&.arguments || []
439
+ targets = arguments.flat_map do |argument|
440
+ if argument.is_a?(Prism::KeywordHashNode) || argument.is_a?(Prism::HashNode)
441
+ argument.elements.filter_map do |element|
442
+ next unless element.is_a?(Prism::AssocNode) && element.key.is_a?(Prism::SymbolNode)
443
+ next unless %w[partial template layout spacer_template].include?(element.key.unescaped)
444
+
445
+ element.value
446
+ end
447
+ elsif argument.equal?(arguments.first)
448
+ argument
449
+ end
450
+ end.compact
451
+
452
+ targets.map do |target|
453
+ while target.is_a?(Prism::ParenthesesNode) && target.body.is_a?(Prism::StatementsNode) && target.body.body.one?
454
+ target = target.body.body.first
455
+ end
456
+ target
457
+ end
458
+ end
459
+
241
460
  # Record the actual class name rather than trying to reverse a virtual
242
461
  # path, which may contain acronyms or be overridden by the component.
243
462
  def registered_path_for(component)
@@ -259,12 +478,31 @@ module ViewComponent
259
478
  # Returns nil for anything else, including constants that don't exist.
260
479
  # Autoloading here is safe: the template is about to render this constant
261
480
  # anyway.
262
- def constantize_component(constant_name)
263
- component = constant_name.safe_constantize
481
+ def constantize_component(constant_name, nesting = [])
482
+ component = resolve_constant(constant_name, nesting)
264
483
  return unless component.is_a?(Class) && component < ViewComponent::Base
265
484
 
266
485
  component
267
486
  end
487
+
488
+ def resolve_constant(name, nesting)
489
+ return unless CONSTANT_NAME.match?(name)
490
+ return name.safe_constantize if nesting.empty? || name.start_with?("::")
491
+
492
+ first, *rest = name.split("::")
493
+ # Lexical constants precede inherited constants. Once a name resolves,
494
+ # do not fall back to a top-level component if it names something else.
495
+ owner = nesting.find { |namespace| namespace.const_defined?(first, false) }
496
+ owner ||= nesting.first if nesting.first.const_defined?(first)
497
+ owner ||= Object if Object.const_defined?(first)
498
+ return unless owner
499
+
500
+ constant = owner.const_get(first)
501
+ return constant if rest.empty?
502
+ return unless constant.is_a?(Module) && constant.name
503
+
504
+ "#{constant.name}::#{rest.join("::")}".safe_constantize
505
+ end
268
506
  end
269
507
 
270
508
  # 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,13 +26,70 @@ module ViewComponent
26
26
  cache.clear
27
27
  end
28
28
 
29
+ # Source files can't change while the application eager loads: share
30
+ # directory listings, sidecar lookups, and file contents within the block.
31
+ # Fiber storage keeps the caches from surviving boot.
32
+ def with_sidecar_files_cache
33
+ Fiber[:__vc_sidecar_files] = {}
34
+ Fiber[:__vc_sidecar_directories] = {}
35
+ Fiber[:__vc_source_files] = {}
36
+ Fiber[:__vc_path_parser] = ActionView::Resolver::PathParser.new
37
+ yield
38
+ ensure
39
+ Fiber[:__vc_sidecar_files] = nil
40
+ Fiber[:__vc_sidecar_directories] = nil
41
+ Fiber[:__vc_source_files] = nil
42
+ Fiber[:__vc_path_parser] = nil
43
+ end
44
+
45
+ def path_parser
46
+ # Its regular expression depends on registered handlers, formats and locales.
47
+ # Reuse it during eager loading, but not across reloads.
48
+ Fiber[:__vc_path_parser] || ActionView::Resolver::PathParser.new
49
+ end
50
+
51
+ def read_file(path)
52
+ files = Fiber[:__vc_source_files]
53
+ return File.read(path) unless files
54
+
55
+ (files[path] ||= File.read(path).freeze).dup
56
+ end
57
+
58
+ def sidecar_files_for(klass, extensions)
59
+ sidecar_files_by_component = Fiber[:__vc_sidecar_files]
60
+ return yield unless sidecar_files_by_component
61
+
62
+ sidecar_files = sidecar_files_by_component[klass] ||= {}
63
+ sidecar_files[extensions] ||= yield.freeze
64
+ end
65
+
66
+ def sidecar_files_matching(pattern)
67
+ directories = Fiber[:__vc_sidecar_directories]
68
+ return Dir[pattern] unless directories
69
+
70
+ filename = File.basename(pattern)
71
+ prefix = filename.delete_suffix(".*")
72
+ return Dir[pattern] if prefix.match?(/[*?{}\[\]\\]/)
73
+
74
+ directory = File.dirname(pattern)
75
+ # Index the shared directory by component name instead of scanning all
76
+ # its entries again for every component and extension.
77
+ entries = directories[directory] ||= Dir.glob("#{directory}/*", File::FNM_DOTMATCH)
78
+ .group_by { |path| File.basename(path).split(".", 2).first }
79
+ candidates = entries.fetch(prefix.split(".", 2).first, [])
80
+ candidates.select { |path| File.fnmatch?(filename, File.basename(path)) }
81
+ end
82
+
29
83
  # Invalidates the cache when a template or a translation file is added,
30
84
  # changed, or removed. Changes to Ruby files reload the application instead.
31
85
  def template_watcher(file_watcher)
32
86
  extensions = ActionView::Template::Handlers.extensions.map(&:to_s) + %w[yml yaml]
33
87
  directories = ActiveSupport::Dependencies.autoload_paths.map(&:to_s).index_with(extensions)
34
88
 
35
- file_watcher.new([], directories) { invalidate! }
89
+ file_watcher.new([], directories) do
90
+ invalidate!
91
+ ActionView::LookupContext::DetailsKey.clear
92
+ end
36
93
  end
37
94
  end
38
95
  end