view_component 4.19.0 → 4.23.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 +180 -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 +27 -11
  21. data/lib/view_component/cache_digest/digestor_lookup.rb +47 -1
  22. data/lib/view_component/cache_digest/resolver.rb +146 -52
  23. data/lib/view_component/cache_digest.rb +346 -56
  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 +62 -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 +40 -16
  36. data/lib/view_component/translatable.rb +35 -1
  37. data/lib/view_component/version.rb +1 -1
  38. metadata +17 -1
@@ -32,6 +32,9 @@ end
32
32
 
33
33
  module ViewComponent
34
34
  class Base
35
+ EMPTY_OUTPUT = "".html_safe.freeze
36
+ private_constant :EMPTY_OUTPUT
37
+
35
38
  class << self
36
39
  # A digest of the component's source, ancestors, and rendered dependencies.
37
40
  #
@@ -42,7 +45,7 @@ module ViewComponent
42
45
  def cache_digest(finder: nil, format: :html)
43
46
  ViewComponent::CacheDigest.digest(
44
47
  self,
45
- finder: finder || ViewComponent::CacheDigest.default_finder,
48
+ finder: finder,
46
49
  format: format
47
50
  )
48
51
  end
@@ -121,86 +124,14 @@ module ViewComponent
121
124
  # @return [String]
122
125
  def render_in(view_context, **, &block)
123
126
  self.class.__vc_compile(raise_errors: true) unless self.class.__vc_compiled?
124
-
125
- if self.class.__vc_cache_output && !@__vc_cache_bypassed
126
- return __vc_render_cached(view_context, block)
127
- end
128
-
129
127
  __vc_check_reused_instance!
130
- __vc_reset_render_state!
131
-
132
- @view_context = view_context
133
- @old_virtual_path = view_context.instance_variable_get(:@virtual_path)
134
- self.__vc_original_view_context = view_context
135
-
136
- @output_buffer = view_context.output_buffer
137
-
138
- @lookup_context = view_context.lookup_context
139
-
140
- # For content_for
141
- @view_flow = view_context.view_flow
142
-
143
- # For i18n
144
- @virtual_path ||= virtual_path
145
-
146
- # Describes the inferred request constraints (locales, formats, variants)
147
- @__vc_requested_details = @lookup_context.vc_requested_details
148
-
149
- # For caching, such as #cache_if
150
- @current_template = nil unless defined?(@current_template)
151
- old_current_template = @current_template
152
-
153
- if block && defined?(@__vc_content_set_by_with_content)
154
- raise DuplicateContentError.new(self.class.name)
155
- end
156
-
157
- @__vc_content_evaluated = false
158
- remove_instance_variable(:@__vc_content) if defined?(@__vc_content)
159
- @__vc_render_in_block = block
160
- @view_context.instance_variable_set(:@virtual_path, virtual_path)
161
-
162
- before_render
163
-
164
- if render?
165
- value = nil
166
-
167
- @output_buffer.with_buffer do
168
- inner_rendered_template = nil
169
- around_rendered_template = around_render do
170
- inner_rendered_template = render_template_for(@__vc_requested_details).to_s
171
- end
172
-
173
- # If `around_render` returned the same object the block yielded, the inner
174
- # template's escaping is authoritative and we can trust the result. If the
175
- # user replaced/wrapped the value, re-check HTML safety to prevent
176
- # bypassing the escaping applied to normal `#call` return values
177
- # (GHSA-97jw-64cj-jc58).
178
- rendered_template = if around_rendered_template.equal?(inner_rendered_template)
179
- around_rendered_template
180
- else
181
- __vc_safe_around_render_output(around_rendered_template)
182
- end
183
128
 
184
- # Avoid allocating new string when output_preamble and output_postamble are blank
185
- value = if output_preamble.blank? && output_postamble.blank?
186
- rendered_template
187
- else
188
- __vc_safe_output_preamble + rendered_template + __vc_safe_output_postamble
189
- end
190
- end
191
-
192
- if ActionView::Base.annotate_rendered_view_with_filenames && current_template.inline_call? && request&.format == :html
193
- identifier = defined?(Rails.root) ? self.class.identifier.sub("#{Rails.root}/", "") : self.class.identifier
194
- value = "<!-- BEGIN #{identifier} -->".html_safe + value + "<!-- END #{identifier} -->".html_safe
195
- end
196
-
197
- value
129
+ if self.class.__vc_cache_output
130
+ __vc_render_cached(view_context, block)
198
131
  else
199
- "".html_safe
132
+ __vc_render_uncached(view_context, &block)
200
133
  end
201
134
  ensure
202
- view_context.instance_variable_set(:@virtual_path, @old_virtual_path)
203
- @current_template = old_current_template
204
135
  @__vc_rendered = true
205
136
  end
206
137
 
@@ -232,14 +163,21 @@ module ViewComponent
232
163
  # When rendering the parent inside an .erb template, use `#render_parent` instead.
233
164
  def render_parent_to_string
234
165
  @__vc_parent_render_level ||= 0 # ensure a good starting value
166
+ old_current_template = @current_template
235
167
 
236
168
  begin
237
169
  target_render = self.class.instance_variable_get(:@__vc_ancestor_calls)[@__vc_parent_render_level]
238
170
  @__vc_parent_render_level += 1
239
171
 
172
+ unless target_render.owner.__vc_compiled?
173
+ target_render.owner.__vc_compile(raise_errors: true)
174
+ target_render = target_render.owner.instance_method(:render_template_for)
175
+ end
176
+
240
177
  target_render.bind_call(self, @__vc_requested_details)
241
178
  ensure
242
179
  @__vc_parent_render_level -= 1
180
+ @current_template = old_current_template
243
181
  end
244
182
  end
245
183
 
@@ -247,14 +185,14 @@ module ViewComponent
247
185
  #
248
186
  # @return [String]
249
187
  def output_preamble
250
- @@default_output_preamble ||= "".html_safe
188
+ EMPTY_OUTPUT
251
189
  end
252
190
 
253
191
  # Optional content to be returned after the rendered template.
254
192
  #
255
193
  # @return [String]
256
194
  def output_postamble
257
- @@default_output_postamble ||= "".html_safe
195
+ EMPTY_OUTPUT
258
196
  end
259
197
 
260
198
  # Called before rendering the component. Override to perform operations that
@@ -289,7 +227,7 @@ module ViewComponent
289
227
  #
290
228
  # @private
291
229
  def render(options = {}, args = {}, &block)
292
- if options.respond_to?(:set_original_view_context)
230
+ if options.is_a?(ViewComponent::Base) || options.respond_to?(:set_original_view_context)
293
231
  options.set_original_view_context(__vc_original_view_context)
294
232
 
295
233
  # We assume options is a component, so there's no need to evaluate the
@@ -448,20 +386,99 @@ module ViewComponent
448
386
  # @private
449
387
  def digest_path_from_template(template)
450
388
  component_path = self.class.virtual_path
451
- return super unless component_path && template.virtual_path == component_path
389
+ return super unless component_path && template.is_a?(ViewComponent::Template)
452
390
 
453
391
  digest = self.class.cache_digest(
454
392
  finder: lookup_context,
455
393
  format: template.format || lookup_context.formats.first || :html
456
394
  )
457
395
 
458
- digest.present? ? "#{component_path}:#{digest}" : component_path
396
+ digest.present? ? "#{template.virtual_path}:#{digest}" : template.virtual_path
459
397
  end
460
398
 
461
399
  private
462
400
 
463
401
  attr_reader :view_context
464
402
 
403
+ def __vc_render_uncached(view_context, &block)
404
+ old_virtual_path = view_context.instance_variable_get(:@virtual_path)
405
+ __vc_reset_render_state!
406
+
407
+ @view_context = view_context
408
+ @old_virtual_path = old_virtual_path
409
+ self.__vc_original_view_context = view_context
410
+
411
+ @output_buffer = view_context.output_buffer
412
+
413
+ @lookup_context = view_context.lookup_context
414
+
415
+ # For content_for
416
+ @view_flow = view_context.view_flow
417
+
418
+ # For i18n
419
+ component_virtual_path = virtual_path
420
+ @virtual_path ||= component_virtual_path
421
+
422
+ # Describes the inferred request constraints (locales, formats, variants)
423
+ @__vc_requested_details = @lookup_context.vc_requested_details
424
+
425
+ # For caching, such as #cache_if
426
+ @current_template = nil unless defined?(@current_template)
427
+ old_current_template = @current_template
428
+
429
+ if block && defined?(@__vc_content_set_by_with_content)
430
+ raise DuplicateContentError.new(self.class.name)
431
+ end
432
+
433
+ @__vc_content_evaluated = false
434
+ remove_instance_variable(:@__vc_content) if defined?(@__vc_content)
435
+ @__vc_render_in_block = block
436
+ @view_context.instance_variable_set(:@virtual_path, component_virtual_path)
437
+
438
+ before_render
439
+
440
+ if render?
441
+ value = nil
442
+
443
+ @output_buffer.with_buffer do
444
+ inner_rendered_template = nil
445
+ around_rendered_template = around_render do
446
+ inner_rendered_template = render_template_for(@__vc_requested_details).to_s
447
+ end
448
+
449
+ # If `around_render` returned the same object the block yielded, the inner
450
+ # template's escaping is authoritative and we can trust the result. If the
451
+ # user replaced/wrapped the value, re-check HTML safety to prevent
452
+ # bypassing the escaping applied to normal `#call` return values
453
+ # (GHSA-97jw-64cj-jc58).
454
+ rendered_template = if around_rendered_template.equal?(inner_rendered_template)
455
+ around_rendered_template
456
+ else
457
+ __vc_safe_around_render_output(around_rendered_template)
458
+ end
459
+
460
+ # Avoid allocating new string when output_preamble and output_postamble are blank
461
+ value = if output_preamble.blank? && output_postamble.blank?
462
+ rendered_template
463
+ else
464
+ __vc_safe_output_preamble + rendered_template + __vc_safe_output_postamble
465
+ end
466
+ end
467
+
468
+ if ActionView::Base.annotate_rendered_view_with_filenames && current_template.inline_call? && request&.format == :html
469
+ identifier = defined?(Rails.root) ? self.class.identifier.sub("#{Rails.root}/", "") : self.class.identifier
470
+ value = "<!-- BEGIN #{identifier} -->".html_safe + value + "<!-- END #{identifier} -->".html_safe
471
+ end
472
+
473
+ value
474
+ else
475
+ "".html_safe
476
+ end
477
+ ensure
478
+ view_context.instance_variable_set(:@virtual_path, old_virtual_path)
479
+ @current_template = old_current_template
480
+ end
481
+
465
482
  def __vc_render_in_block_provided?
466
483
  defined?(@view_context) && @view_context && @__vc_render_in_block
467
484
  end
@@ -471,15 +488,12 @@ module ViewComponent
471
488
  end
472
489
 
473
490
  def __vc_maybe_escape_html(text)
491
+ return text if text.html_safe?
474
492
  return text if @current_template && !@current_template.html?
475
493
  return text if text.blank?
476
494
 
477
- if text.html_safe?
478
- text
479
- else
480
- yield
481
- html_escape(text)
482
- end
495
+ yield
496
+ html_escape(text)
483
497
  end
484
498
 
485
499
  def __vc_safe_output_preamble
@@ -508,16 +522,10 @@ module ViewComponent
508
522
  # slot setters or `with_content`); reuse of an instance that has slot or
509
523
  # `with_content` state is guarded against separately by
510
524
  # `__vc_check_reused_instance!`.
511
- RENDER_STATE_IVARS = %i[
512
- @__vc_controller
513
- @__vc_helpers
514
- @__vc_request
515
- ].freeze
516
-
517
525
  def __vc_reset_render_state!
518
- RENDER_STATE_IVARS.each do |ivar|
519
- remove_instance_variable(ivar) if instance_variable_defined?(ivar)
520
- end
526
+ remove_instance_variable(:@__vc_controller) if defined?(@__vc_controller)
527
+ remove_instance_variable(:@__vc_helpers) if defined?(@__vc_helpers)
528
+ remove_instance_variable(:@__vc_request) if defined?(@__vc_request)
521
529
  end
522
530
 
523
531
  # Raises when a component instance is rendered more than once.
@@ -624,7 +632,10 @@ module ViewComponent
624
632
  return [] unless identifier
625
633
  return [] unless name
626
634
 
627
- extensions = extensions.join(",")
635
+ # One glob per directory, filtered by extension, rather than a brace
636
+ # pattern per extension: Dir expands braces into one directory listing
637
+ # per extension.
638
+ extensions = extensions.map(&:to_s)
628
639
 
629
640
  # view files in a directory named like the component
630
641
  directory = File.dirname(identifier)
@@ -643,19 +654,29 @@ module ViewComponent
643
654
  # Without this, `MyOtherComponent` will not look for `my_component/my_other_component.html.erb`
644
655
  nested_component_files =
645
656
  if name.include?("::") && component_name != filename
646
- Dir["#{directory}/#{filename}/#{component_name}.*{#{extensions}}"]
657
+ __vc_files_ending_with(extensions, "#{directory}/#{filename}/#{component_name}.*")
647
658
  else
648
659
  []
649
660
  end
650
661
 
651
662
  # view files in the same directory as the component
652
- sidecar_files = Dir["#{directory}/#{component_name}.*{#{extensions}}"]
663
+ sidecar_files = __vc_files_ending_with(extensions, "#{directory}/#{component_name}.*")
653
664
 
654
- sidecar_directory_files = Dir["#{directory}/#{component_name}/#{filename}.*{#{extensions}}"]
665
+ sidecar_directory_files = __vc_files_ending_with(extensions, "#{directory}/#{component_name}/#{filename}.*")
655
666
 
656
667
  (sidecar_files - [identifier] + sidecar_directory_files + nested_component_files).uniq
657
668
  end
658
669
 
670
+ # `sidecar_files`, looked up once per component during eager loading or a
671
+ # digest computation: every component looks up its superclasses' templates
672
+ # and translations too, when it compiles, loads its translations, and
673
+ # computes its cache digest.
674
+ #
675
+ # @private
676
+ def __vc_sidecar_files(extensions)
677
+ CompileCache.sidecar_files_for(self, extensions) { sidecar_files(extensions) }
678
+ end
679
+
659
680
  # Render a component for each element in a collection ([documentation](/guide/collections)):
660
681
  #
661
682
  # ```ruby
@@ -720,7 +741,7 @@ module ViewComponent
720
741
 
721
742
  # @private
722
743
  def __vc_compiled?
723
- __vc_compiler.compiled?
744
+ CompileCache.compiled?(self)
724
745
  end
725
746
 
726
747
  # Hook called by the compiler after a component is compiled.
@@ -901,6 +922,11 @@ module ViewComponent
901
922
  signatures
902
923
  end
903
924
 
925
+ def __vc_files_ending_with(extensions, pattern)
926
+ paths = CompileCache.sidecar_files_matching(pattern)
927
+ extensions.flat_map { |extension| paths.select { |path| path.end_with?(extension) } }
928
+ end
929
+
904
930
  attr_reader :__vc_provided_collection_parameter
905
931
  end
906
932
 
@@ -14,19 +14,35 @@ module ViewComponent
14
14
  #
15
15
  # @private
16
16
  module DependencyTracking
17
+ # Templates are memoized during a digest, so a template reached along
18
+ # many edges of the tree is scanned once.
17
19
  def find_dependencies(name, template, view_paths = nil)
18
- dependencies = super
19
- source = template.source
20
-
21
- # `# Template Dependency: SomeComponent` names a class, which Rails
22
- # would resolve as a template path and never find. Swap it for the path
23
- # the component is digested under, so the declaration resolves instead
24
- # of becoming a missing node.
25
- CacheDigest.explicit_component_dependencies(source).each do |declared, virtual_path|
26
- dependencies = dependencies - [declared] + [virtual_path]
27
- end
20
+ CacheDigest.memoize([:dependencies, name, template, view_paths]) do
21
+ dependencies = super
22
+ source = template.source
23
+
24
+ # Synthetic templates already declare every dependency found in their
25
+ # sources, as paths.
26
+ next dependencies if name.start_with?("#{CacheDigest::VIRTUAL_PATH_PREFIX}/")
27
+
28
+ # `# Template Dependency: SomeComponent` names a class, which Rails
29
+ # would resolve as a template path and never find. Swap it for the path
30
+ # the component is digested under, so the declaration resolves instead
31
+ # of becoming a missing node.
32
+ CacheDigest.explicit_component_dependencies(source).each do |declared, virtual_path|
33
+ dependencies = dependencies - [declared] + [virtual_path]
34
+ end
28
35
 
29
- dependencies + CacheDigest.dependencies_in(template)
36
+ next dependencies unless CacheDigest.template_dependencies?(source, template.handler)
37
+
38
+ component_paths, inferred_partials =
39
+ CacheDigest.template_renders_in(CacheDigest.compiled_source(template), name, view_paths: view_paths)
40
+ # Older ERB trackers omit the underscore on unqualified partial paths.
41
+ inferred_partials |= inferred_partials.map { |path| path.delete_prefix("_") }
42
+ declared = source.scan(CacheDigest::EXPLICIT_DEPENDENCY).flatten
43
+
44
+ (dependencies - (inferred_partials - declared) + component_paths).uniq
45
+ end
30
46
  end
31
47
 
32
48
  # @private
@@ -21,10 +21,56 @@ module ViewComponent
21
21
  digestor.prepend(self)
22
22
  end
23
23
 
24
+ def digest(finder:, **)
25
+ CacheDigest.memoizing do
26
+ previous = CacheDigest.memo[:pruned]
27
+ loop do
28
+ pruned = CacheDigest.memo[:pruned] = {}
29
+ digest = super
30
+
31
+ # A component that registered while the tree was built expired the
32
+ # digests the pruned nodes stood in for, so this one, and the
33
+ # digests computed for them since, are missing their dependencies.
34
+ break digest if pruned.all? { |name, cached| finder.digest_cache[name].equal?(cached) }
35
+
36
+ finder.digest_cache.clear
37
+ end
38
+ ensure
39
+ CacheDigest.memo[:pruned] = previous
40
+ end
41
+ end
42
+
43
+ # A dependency whose digest is cached already becomes a leaf:
44
+ # `Node#dependency_digest` reads the cache and never walks its children.
45
+ # Without this, every component digested at boot rebuilds the tree of
46
+ # everything it renders, which for components rendering a shared helper
47
+ # module is most of the application.
48
+ def tree(name, finder, partial = false, seen = {})
49
+ CompileCache.with_sidecar_files_cache do
50
+ pruned = CacheDigest.memo&.fetch(:pruned, nil)
51
+ cached = finder.digest_cache[name] if pruned && partial
52
+ next super unless cached
53
+
54
+ path = ActionView::TemplatePath.parse(name)
55
+ template = find_template(finder, path.name, [path.prefix], partial, [])
56
+ next super unless template
57
+
58
+ pruned[name] = cached
59
+ seen[template.identifier] ||= ActionView::Digestor::Node.create(name, name.gsub(%r{/_}, "/"), template, partial)
60
+ end
61
+ end
62
+
24
63
  private
25
64
 
26
65
  def find_template(finder, name, prefixes, partial, keys)
27
- Resolver.instance.find_templates(name, prefixes.first, partial, {formats: finder.formats}).first || super
66
+ key = [:template, name, prefixes.first, partial, finder.formats, finder.view_paths]
67
+ template = CacheDigest.memoize(key) do
68
+ Resolver.instance.find_templates(
69
+ name, prefixes.first, partial, {formats: finder.formats}, view_paths: finder.view_paths
70
+ ).first
71
+ end
72
+
73
+ template || super
28
74
  end
29
75
  end
30
76
  end