Module: ReactOnRails::Helper

Includes:
FontHelper, ProHelper, Utils::Required
Included in:
ReactOnRailsHelper
Defined in:
lib/react_on_rails/helper.rb,
sig/react_on_rails/helper.rbs

Constant Summary collapse

COMPONENT_HTML_KEY =

Returns:

  • (String)
"componentHtml"
IMMEDIATE_HYDRATION_WARNING_MUTEX =
Mutex.new

Constants included from FontHelper

FontHelper::UNSAFE_TOKEN

Class Method Summary collapse

Instance Method Summary collapse

Methods included from FontHelper

ensure_safe!, fallback_font_face_rule, font_face_markup, font_face_rule, preload_link, #react_on_rails_font_face

Methods included from ProHelper

#generate_component_script, #generate_store_script, #generated_stylesheet_hrefs_json, #hydrate_on_data_attribute_value

Methods included from Utils::Required

#required

Class Method Details

.reset_removed_immediate_hydration_warnings!void

This method returns an undefined value.

:nodoc:



44
45
46
47
48
# File 'lib/react_on_rails/helper.rb', line 44

def reset_removed_immediate_hydration_warnings!
  IMMEDIATE_HYDRATION_WARNING_MUTEX.synchronize do
    @removed_immediate_hydration_warnings = {}
  end
end

.validate_redux_store_options!(rest) ⇒ Object

Validates the **rest kwargs accepted by both redux_store implementations (controller concern and view helper). Raises ArgumentError for unknown keywords and warns once if the removed :immediate_hydration option is passed.



53
54
55
56
57
58
59
60
61
62
# File 'lib/react_on_rails/helper.rb', line 53

def validate_redux_store_options!(rest)
  unknown_keys = rest.keys - [:immediate_hydration]
  if unknown_keys.any?
    plural = unknown_keys.one? ? "" : "s"
    unknown_options = unknown_keys.map { |key| ":#{key}" }.join(", ")
    raise ArgumentError, "unknown keyword#{plural}: #{unknown_options}"
  end

  warn_removed_immediate_hydration_option("redux_store") if rest.key?(:immediate_hydration)
end

.warn_removed_immediate_hydration_option(helper_name) ⇒ void

This method returns an undefined value.

Parameters:

  • helper_name (String)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/react_on_rails/helper.rb', line 28

def warn_removed_immediate_hydration_option(helper_name)
  should_warn = IMMEDIATE_HYDRATION_WARNING_MUTEX.synchronize do
    @removed_immediate_hydration_warnings ||= {}
    next false if @removed_immediate_hydration_warnings[helper_name]

    @removed_immediate_hydration_warnings[helper_name] = true
  end

  return unless should_warn

  Rails.logger.warn(
    "[React on Rails] `immediate_hydration:` is no longer supported on #{helper_name}. Remove this option."
  )
end

Instance Method Details

#add_csp_nonce_to_context(result) ⇒ Object



433
434
435
436
# File 'lib/react_on_rails/helper.rb', line 433

def add_csp_nonce_to_context(result)
  nonce = csp_nonce
  result[:cspNonce] = nonce if nonce.present?
end

#add_rsc_stream_observability_to_context(context) ⇒ Object

Set by ReactOnRailsPro::Stream#initialize_rsc_stream_observability_state. Keep this ivar name in sync with the Pro stream concern.



416
417
418
419
420
421
# File 'lib/react_on_rails/helper.rb', line 416

def add_rsc_stream_observability_to_context(context)
  return unless defined?(@react_on_rails_rsc_stream_observability) &&
                @react_on_rails_rsc_stream_observability

  context[:rscStreamObservability] = true
end

#add_rsc_stream_observability_to_render_options(render_options) ⇒ Object

Set by ReactOnRailsPro::Stream#initialize_rsc_stream_observability_state. Keep this ivar name in sync with the Pro stream concern.



425
426
427
428
429
430
431
# File 'lib/react_on_rails/helper.rb', line 425

def add_rsc_stream_observability_to_render_options(render_options)
  return unless render_options.streaming?
  return unless defined?(@react_on_rails_rsc_stream_observability) &&
                @react_on_rails_rsc_stream_observability

  render_options.set_option(:rsc_stream_observability, true)
end

#build_react_component_result_for_server_rendered_hash(server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options")) ⇒ Object



690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
# File 'lib/react_on_rails/helper.rb', line 690

def build_react_component_result_for_server_rendered_hash(
  server_rendered_html: required("server_rendered_html"),
  component_specification_tag: required("component_specification_tag"),
  console_script: required("console_script"),
  render_options: required("render_options")
)
   = render_options.html_options
  [:id] = render_options.dom_id

  unless server_rendered_html[COMPONENT_HTML_KEY]
    raise ReactOnRails::Error, "server_rendered_html hash expected to contain \"#{COMPONENT_HTML_KEY}\" key."
  end

  rendered_output = (:div,
                                server_rendered_html[COMPONENT_HTML_KEY].html_safe,
                                )

  result_console_script = render_options.replay_console ? wrap_console_script_with_nonce(console_script) : ""
  result = compose_react_component_html_with_spec_and_console(
    component_specification_tag, rendered_output, result_console_script
  )

  # Other HTML strings need to be marked as html_safe too:
  server_rendered_hash_except_component = server_rendered_html.except(COMPONENT_HTML_KEY)
  server_rendered_hash_except_component.each do |key, html_string|
    server_rendered_hash_except_component[key] = html_string.html_safe
  end

  result_with_rails_context = prepend_render_rails_context(result)
  { COMPONENT_HTML_KEY => result_with_rails_context }.merge(
    server_rendered_hash_except_component
  )
end

#build_react_component_result_for_server_rendered_string(server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options")) ⇒ Object



663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'lib/react_on_rails/helper.rb', line 663

def build_react_component_result_for_server_rendered_string(
  server_rendered_html: required("server_rendered_html"),
  component_specification_tag: required("component_specification_tag"),
  console_script: required("console_script"),
  render_options: required("render_options")
)
   = render_options.html_options
  if .key?(:tag)
     = [:tag]
    .delete(:tag)
  else
     = "div"
  end
  [:id] = render_options.dom_id

  rendered_output = (.to_sym,
                                server_rendered_html.html_safe,
                                )

  result_console_script = render_options.replay_console ? wrap_console_script_with_nonce(console_script) : ""
  result = compose_react_component_html_with_spec_and_console(
    component_specification_tag, rendered_output, result_console_script
  )

  prepend_render_rails_context(result)
end

#client_prop_target_key(props, key) ⇒ Object



879
880
881
882
883
884
885
# File 'lib/react_on_rails/helper.rb', line 879

def client_prop_target_key(props, key)
  string_key = key.to_s
  symbol_key = string_key.to_sym
  # Preserve an existing symbol key when clientProps arrives from JSON with string keys,
  # otherwise we would create duplicate entries that serialize to the same JSON key.
  props.key?(symbol_key) && !props.key?(string_key) ? symbol_key : string_key
end

#compose_react_component_html_with_spec_and_console(component_specification_tag, rendered_output, console_script) ⇒ Object



754
755
756
757
758
759
760
761
# File 'lib/react_on_rails/helper.rb', line 754

def compose_react_component_html_with_spec_and_console(component_specification_tag, rendered_output,
                                                       console_script)
  # IMPORTANT: Ensure that we mark string as html_safe to avoid escaping.
  added_html = "#{component_specification_tag}\n#{console_script}".strip
  added_html = added_html.present? ? "\n#{added_html}" : ""

  "#{rendered_output}#{added_html}".html_safe
end

#create_render_options(react_component_name, options) ⇒ Object



499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/react_on_rails/helper.rb', line 499

def create_render_options(react_component_name, options)
  options = options.dup
  # If no store dependencies are passed, default to all registered stores up till now
  unless options.key?(:store_dependencies)
    store_dependencies = registered_stores_including_deferred.map { |store| store[:store_name] }
    options = options.merge(store_dependencies: store_dependencies.presence)
  end
  render_options = ReactOnRails::ReactComponent::RenderOptions.new(react_component_name:,
                                                                   options:)
  add_rsc_stream_observability_to_render_options(render_options)
  render_options
end

#csp_nonceObject

Returns the CSP script nonce for the current request, or nil if CSP is not enabled. Rails 5.2-6.0 use content_security_policy_nonce with no arguments. Rails 6.1+ accept an optional directive argument.



727
728
729
730
731
732
733
734
735
736
# File 'lib/react_on_rails/helper.rb', line 727

def csp_nonce
  return unless respond_to?(:content_security_policy_nonce)

  begin
    content_security_policy_nonce(:script)
  rescue ArgumentError
    # Fallback for Rails versions that don't accept arguments
    content_security_policy_nonce
  end
end

#current_shakapacker_instanceObject



559
560
561
# File 'lib/react_on_rails/helper.rb', line 559

def current_shakapacker_instance
  ::Shakapacker.instance
end

#generated_component_pack_name(component_name) ⇒ Object



520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/react_on_rails/helper.rb', line 520

def generated_component_pack_name(component_name)
  component_name = component_name.to_s
  component_name = component_name.delete_prefix("generated/")

  unless component_name.match?(/\A[A-Za-z0-9_]+\z/)
    raise ArgumentError,
          "react_on_rails_preload_links component names must use PascalCase, camelCase, or snake_case " \
          "without hyphens: #{component_name.inspect}"
  end

  "generated/#{component_name.camelize}"
end

#generated_components_pack_path(component_name) ⇒ Object



512
513
514
# File 'lib/react_on_rails/helper.rb', line 512

def generated_components_pack_path(component_name)
  "#{ReactOnRails::PackerUtils.packer_source_entry_path}/generated/#{component_name}.js"
end

#generated_stores_pack_path(store_name) ⇒ Object



516
517
518
# File 'lib/react_on_rails/helper.rb', line 516

def generated_stores_pack_path(store_name)
  "#{ReactOnRails::PackerUtils.packer_source_entry_path}/generated/#{store_name}.js"
end

#in_mailer?Boolean

Returns:

  • (Boolean)


1047
1048
1049
1050
1051
1052
# File 'lib/react_on_rails/helper.rb', line 1047

def in_mailer?
  return false unless defined?(controller)
  return false unless defined?(ActionMailer::Base)

  controller.is_a?(ActionMailer::Base)
end

#initialize_redux_stores(render_options) ⇒ Object



1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
# File 'lib/react_on_rails/helper.rb', line 1021

def initialize_redux_stores(render_options)
  result = +<<-JS
  ReactOnRails.clearHydratedStores();
  JS

  store_dependencies = render_options.store_dependencies
  return result unless store_dependencies.present?

  declarations = +"var reduxProps, store, storeGenerator;\n"
  store_objects = registered_stores_including_deferred.select do |store|
    store_dependencies.include?(store[:store_name])
  end

  result << store_objects.each_with_object(declarations) do |redux_store_data, memo|
    store_name = redux_store_data[:store_name]
    props = props_string(redux_store_data[:props])
    memo << <<~JS
      reduxProps = #{props};
      storeGenerator = ReactOnRails.getStoreGenerator(#{store_name.to_json});
      store = storeGenerator(reduxProps, railsContext);
      ReactOnRails.setStore(#{store_name.to_json}, store);
    JS
  end
  result
end

#internal_react_component(react_component_name, options = {}) ⇒ Object



796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
# File 'lib/react_on_rails/helper.rb', line 796

def internal_react_component(react_component_name, options = {})
  # Create the JavaScript and HTML to allow either client or server rendering of the
  # react_component.
  #
  # Create the JavaScript setup of the global to initialize the client rendering
  # (re-hydrate the data). This enables react rendered on the client to see that the
  # server has already rendered the HTML.

  render_options = create_render_options(react_component_name, options)

  load_pack_for_generated_component(react_component_name, render_options)
  # Create the HTML rendering part
  result = server_rendered_react_component(render_options)

  # clientProps are only expected on successful SSR hashes. Current error hashes do not
  # include that key, so non-SSR/error paths skip this merge entirely.
  merge_server_rendered_client_props!(render_options, result) if result.is_a?(Hash)

  # Setup the page_loaded_js, which is the same regardless of prerendering or not!
  # The reason is that React is smart about not doing extra work if the server rendering did its job.
  component_specification_tag = generate_component_script(render_options)

  {
    render_options:,
    tag: component_specification_tag,
    result:
  }
end

#json_safe_and_pretty(hash_or_string) ⇒ Object



330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/react_on_rails/helper.rb', line 330

def json_safe_and_pretty(hash_or_string)
  return "{}" if hash_or_string.nil?

  unless hash_or_string.is_a?(String) || hash_or_string.is_a?(Hash)
    raise ReactOnRails::Error, "#{__method__} only accepts String or Hash as argument " \
                               "(#{hash_or_string.class} given)."
  end

  json_value = hash_or_string.is_a?(String) ? hash_or_string : hash_or_string.to_json

  ReactOnRails::JsonOutput.escape(json_value)
end

#load_pack_for_generated_component(_react_component_name, render_options) ⇒ Object



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/react_on_rails/helper.rb', line 438

def load_pack_for_generated_component(_react_component_name, render_options)
  return unless render_options.auto_load_bundle

  ReactOnRails::PackerUtils.raise_nested_entries_disabled unless ReactOnRails::PackerUtils.nested_entries?
  generated_component_name = render_options.react_component_name
  if Rails.env.development?
    is_component_pack_present = File.exist?(generated_components_pack_path(generated_component_name))
    raise_missing_autoloaded_bundle(generated_component_name) unless is_component_pack_present
  end

  options = { defer: ReactOnRails.configuration.generated_component_packs_loading_strategy == :defer }
  # Old versions of Shakapacker don't support async script tags.
  # ReactOnRails.configure already validates if async loading is supported by the installed Shakapacker version.
  # Therefore, we only need to pass the async option if the loading strategy is explicitly set to :async
  options[:async] = true if ReactOnRails.configuration.generated_component_packs_loading_strategy == :async
  append_javascript_pack_tag("generated/#{generated_component_name}", **options)
  append_stylesheet_pack_tag("generated/#{generated_component_name}")
end

#load_pack_for_generated_store(store_name, explicit_auto_load: false) ⇒ Object



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/react_on_rails/helper.rb', line 457

def load_pack_for_generated_store(store_name, explicit_auto_load: false)
  unless ReactOnRails.configuration.stores_subdirectory.present?
    if explicit_auto_load
      raise ReactOnRails::SmartError.new(
        error_type: :configuration_error,
        details: "auto_load_bundle is enabled for store " \
                 "'#{store_name}', but " \
                 "stores_subdirectory is not configured. " \
                 "Set config.stores_subdirectory (e.g., " \
                 "'ror_stores') in your ReactOnRails " \
                 "configuration so that store packs can " \
                 "be generated and loaded."
      )
    end
    return
  end

  ReactOnRails::PackerUtils.raise_nested_entries_disabled unless ReactOnRails::PackerUtils.nested_entries?
  if Rails.env.development?
    is_store_pack_present = File.exist?(generated_stores_pack_path(store_name))
    raise_missing_autoloaded_store_bundle(store_name) unless is_store_pack_present
  end

  options = { defer: ReactOnRails.configuration.generated_component_packs_loading_strategy == :defer }
  options[:async] = true if ReactOnRails.configuration.generated_component_packs_loading_strategy == :async
  append_javascript_pack_tag("generated/#{store_name}", **options)
end

#merge_client_props(existing_props, client_props) ⇒ Object



860
861
862
863
864
865
866
867
# File 'lib/react_on_rails/helper.rb', line 860

def merge_client_props(existing_props, client_props)
  merged_props = existing_props.dup
  client_props.each do |key, value|
    raise_if_duplicate_client_prop_key_types!(merged_props, key)
    merged_props[client_prop_target_key(merged_props, key)] = value
  end
  merged_props
end

#merge_server_rendered_client_props!(render_options, result) ⇒ Object



825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/react_on_rails/helper.rb', line 825

def merge_server_rendered_client_props!(render_options, result)
  client_props = result["clientProps"]
  return if client_props.nil?

  unless client_props.is_a?(Hash)
    raise ReactOnRails::Error, "Expected result[\"clientProps\"] to be a Hash, got #{client_props.class.name}."
  end

  return if client_props.empty?

  raw_existing_props = render_options.props
  existing_props = if raw_existing_props.nil?
                     {}
                   elsif raw_existing_props.is_a?(String)
                     begin
                       JSON.parse(raw_existing_props)
                     rescue JSON::ParserError
                       raise ReactOnRails::Error,
                             "Cannot merge result[\"clientProps\"] into props: failed to parse props JSON " \
                             "string. Ensure props is a Ruby Hash or a JSON string representing an object."
                     end
                   else
                     raw_existing_props
                   end

  unless existing_props.is_a?(Hash)
    class_name = existing_props.class.name
    raise ReactOnRails::Error,
          "Cannot merge result[\"clientProps\"] into non-Hash props. " \
          "Pass props as a Hash, not #{class_name}."
  end

  render_options.set_option(:props, merge_client_props(existing_props, client_props))
end

#modulepreload_source?(source) ⇒ Boolean

Returns:

  • (Boolean)


637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/react_on_rails/helper.rb', line 637

def modulepreload_source?(source)
  # Priority order: explicit module metadata, rel/type metadata, then the .mjs extension heuristic.
  module_value = preload_manifest_value(source, "module")
  return true if module_value == true
  return false if module_value == false

  return true if preload_manifest_value(source, "rel").to_s == "modulepreload"
  return true if preload_manifest_value(source, "type").to_s == "module"

  source_path = preload_manifest_source(source).to_s.split(/[?#]/, 2).first
  File.extname(source_path) == ".mjs"
end

#normalize_js_stack_lines(stack) ⇒ Object

V8 stack strings begin with a "TypeError: ..." header line — and chained-exception stacks add further non-frame headers mid-stack (e.g. Caused by: ...) — none of which match Ruby's file:line:in 'method' backtrace format. Keep only the at <frame> lines so backtrace cleaners and APM tools that ship the array raw don't choke on unparseable strings. Frames are also .strip-ed to drop V8's leading indentation, which Ruby backtraces never carry.

When the stack has no at <frame> lines (e.g. a header-only or non-V8 string) this returns [], leaving the backtrace nil rather than seeding it with unparseable header lines.



932
933
934
935
936
937
938
939
# File 'lib/react_on_rails/helper.rb', line 932

def normalize_js_stack_lines(stack)
  # Only V8 string stacks are parseable here. A non-String stack (e.g. an array of frames
  # from a non-V8 serializer) would otherwise be `to_s`-ed into Ruby array syntax and yield
  # no usable frames — guard explicitly so the no-backtrace path is intentional, not garbage.
  return [] unless stack.is_a?(String)

  stack.lines.map { |line| line.chomp.strip }.select { |line| line.start_with?("at ") }
end

#preload_crossoriginObject



625
626
627
628
# File 'lib/react_on_rails/helper.rb', line 625

def preload_crossorigin
  cross_origin = shakapacker_integrity_config[:cross_origin]
  cross_origin.nil? ? "anonymous" : cross_origin
end


599
600
601
602
603
604
605
606
# File 'lib/react_on_rails/helper.rb', line 599

def preload_link_attributes(source, href:)
  attributes = { href: }
  integrity = preload_source_integrity(source)
  return attributes unless integrity.present?

  cross_origin = shakapacker_integrity_config[:cross_origin]
  attributes.merge(integrity:, crossorigin: cross_origin.nil? ? preload_crossorigin : cross_origin)
end


585
586
587
588
589
590
591
592
593
# File 'lib/react_on_rails/helper.rb', line 585

def preload_link_for_javascript_source(source, href:)
  attributes = preload_link_attributes(source, href:)
  if modulepreload_source?(source)
    attributes[:crossorigin] = preload_crossorigin if attributes[:crossorigin].nil?
    tag.link(**attributes.merge(rel: "modulepreload"))
  else
    tag.link(**attributes.merge(rel: "preload", as: "script"))
  end
end


574
575
576
577
578
579
580
581
582
583
# File 'lib/react_on_rails/helper.rb', line 574

def preload_link_for_source(source)
  case source.fetch(:source_type)
  when :javascript
    preload_link_for_javascript_source(source.fetch(:source), href: source.fetch(:href))
  when :stylesheet
    preload_link_for_stylesheet_source(source.fetch(:source), href: source.fetch(:href))
  else
    raise ArgumentError, "Unexpected preload source type: #{source.fetch(:source_type).inspect}"
  end
end


595
596
597
# File 'lib/react_on_rails/helper.rb', line 595

def preload_link_for_stylesheet_source(source, href:)
  tag.link(**preload_link_attributes(source, href:).merge(rel: "preload", as: "style"))
end

#preload_manifest_key?(source, key) ⇒ Boolean

Returns:

  • (Boolean)


659
660
661
# File 'lib/react_on_rails/helper.rb', line 659

def preload_manifest_key?(source, key)
  source.respond_to?(:key?) && source.key?(key)
end

#preload_manifest_source(source) ⇒ Object

Raises:

  • (ArgumentError)


612
613
614
615
616
617
# File 'lib/react_on_rails/helper.rb', line 612

def preload_manifest_source(source)
  return source if source.is_a?(String)
  return preload_manifest_value(source, "src") if preload_manifest_key?(source, "src")

  raise ArgumentError, "Unexpected Shakapacker manifest source without src: #{source.inspect}"
end

#preload_manifest_value(source, key) ⇒ Object



650
651
652
653
654
655
656
657
# File 'lib/react_on_rails/helper.rb', line 650

def preload_manifest_value(source, key)
  return if source.is_a?(String) || !source.respond_to?(:[])

  return source[key] if preload_manifest_key?(source, key)
  return source[key.to_sym] if preload_manifest_key?(source, key.to_sym)

  nil
end

#preload_source_integrity(source) ⇒ Object



619
620
621
622
623
# File 'lib/react_on_rails/helper.rb', line 619

def preload_source_integrity(source)
  return unless shakapacker_integrity_config[:enabled]

  preload_manifest_value(source, "integrity")
end

#preload_source_path(source) ⇒ Object



608
609
610
# File 'lib/react_on_rails/helper.rb', line 608

def preload_source_path(source)
  path_to_asset(preload_manifest_source(source), skip_pipeline: true)
end

#preload_sources_for_generated_pack(pack_name) ⇒ Object



533
534
535
# File 'lib/react_on_rails/helper.rb', line 533

def preload_sources_for_generated_pack(pack_name)
  preload_sources_for_javascript_pack(pack_name) + preload_sources_for_stylesheet_pack(pack_name)
end

#preload_sources_for_javascript_pack(pack_name) ⇒ Object



537
538
539
540
541
# File 'lib/react_on_rails/helper.rb', line 537

def preload_sources_for_javascript_pack(pack_name)
  preload_sources_for_pack(pack_name, type: :javascript, required: true).map do |source|
    { source:, source_type: :javascript }
  end
end

#preload_sources_for_pack(pack_name, type:, required:) ⇒ Object



549
550
551
552
553
554
555
556
557
# File 'lib/react_on_rails/helper.rb', line 549

def preload_sources_for_pack(pack_name, type:, required:)
  manifest = current_shakapacker_instance.manifest
  sources = if required
              manifest.lookup_pack_with_chunks!(pack_name, type:)
            else
              manifest.lookup_pack_with_chunks(pack_name, type:)
            end
  Array(sources).compact
end

#preload_sources_for_stylesheet_pack(pack_name) ⇒ Object



543
544
545
546
547
# File 'lib/react_on_rails/helper.rb', line 543

def preload_sources_for_stylesheet_pack(pack_name)
  preload_sources_for_pack(pack_name, type: :stylesheet, required: false).map do |source|
    { source:, source_type: :stylesheet }
  end
end

#prepend_render_rails_context(render_value) ⇒ safe_buffer

prepend the rails_context if not yet applied

Parameters:

  • result (String)

Returns:

  • (safe_buffer)


790
791
792
793
794
# File 'lib/react_on_rails/helper.rb', line 790

def prepend_render_rails_context(render_value)
  rails_context_content = rails_context_if_not_already_rendered
  rails_context_content = rails_context_content.present? ? "#{rails_context_content}\n" : ""
  "#{rails_context_content}#{render_value}".html_safe
end

#props_string(props) ⇒ Object



893
894
895
# File 'lib/react_on_rails/helper.rb', line 893

def props_string(props)
  props.is_a?(String) ? props : props.to_json
end

#rails_context(server_side: true) ⇒ Object

This is the definitive list of the default values used for the rails_context, which is the second parameter passed to both component and store Render-Functions. This method can be called from views and from the controller, as helpers.rails_context

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/react_on_rails/helper.rb', line 348

def rails_context(server_side: true)
  # ALERT: Keep in sync with packages/react-on-rails/src/types/index.ts for the properties of RailsContext
  @rails_context ||= begin
    result = {
      componentRegistryTimeout: ReactOnRails.configuration.component_registry_timeout,
      railsEnv: Rails.env,
      inMailer: in_mailer?,
      # Locale settings
      i18nLocale: I18n.locale,
      i18nDefaultLocale: I18n.default_locale,
      rorVersion: ReactOnRails::VERSION,
      # TODO: v13 just use the version if existing
      # Pro gem availability signal (not license-valid state).
      rorPro: ReactOnRails::Utils.react_on_rails_pro?
    }

    if ReactOnRails::Utils.react_on_rails_pro?
      result[:rorProVersion] = ReactOnRails::Utils.react_on_rails_pro_version

      if ReactOnRails::Utils.rsc_support_enabled?
        rsc_payload_url = ReactOnRailsPro.configuration.rsc_payload_generation_url_path
        result[:rscPayloadGenerationUrlPath] = rsc_payload_url
      end
    end

    add_csp_nonce_to_context(result)

    if defined?(request) && request.present?
      # Check for encoding of the request's original_url and try to force-encoding the
      # URLs as UTF-8. This situation can occur in browsers that do not encode the
      # entire URL as UTF-8 already, mostly on the Windows platform (IE11 and lower).
      original_url_normalized = request.original_url
      if original_url_normalized.encoding == Encoding::BINARY
        original_url_normalized = original_url_normalized.force_encoding(Encoding::ISO_8859_1)
                                                         .encode(Encoding::UTF_8)
      end

      # Using Addressable instead of standard URI to better deal with
      # non-ASCII characters (see https://github.com/shakacode/react_on_rails/pull/405)
      uri = Addressable::URI.parse(original_url_normalized)
      # uri = Addressable::URI.parse("http://foo.com:3000/posts?id=30&limit=5#time=1305298413")

      result.merge!(
        # URL settings
        href: uri.to_s,
        location: "#{uri.path}#{"?#{uri.query}" if uri.query.present?}",
        scheme: uri.scheme, # http
        host: uri.host, # foo.com
        port: uri.port,
        pathname: uri.path, # /posts
        search: uri.query, # id=30&limit=5
        httpAcceptLanguage: request.env["HTTP_ACCEPT_LANGUAGE"]
      )
    end
    if ReactOnRails.configuration.rendering_extension
      custom_context = ReactOnRails.configuration.rendering_extension.custom_context(self)
      result.merge!(custom_context) if custom_context
    end
    result
  end

  context = @rails_context.merge(serverSide: server_side)
  add_rsc_stream_observability_to_context(context)
  context
end

#rails_context_if_not_already_renderedObject



763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# File 'lib/react_on_rails/helper.rb', line 763

def rails_context_if_not_already_rendered
  return "" if @rendered_rails_context

  data = rails_context(server_side: false)

  @rendered_rails_context = true

  attribution_comment = react_on_rails_attribution_comment
  script_tag = (:script,
                           json_safe_and_pretty(data).html_safe,
                           type: "application/json",
                           id: "js-react-on-rails-context")

  "#{attribution_comment}\n#{script_tag}".html_safe
end

#raise_if_duplicate_client_prop_key_types!(props, key) ⇒ Object



869
870
871
872
873
874
875
876
877
# File 'lib/react_on_rails/helper.rb', line 869

def raise_if_duplicate_client_prop_key_types!(props, key)
  string_key = key.to_s
  symbol_key = string_key.to_sym
  return unless props.key?(string_key) && props.key?(symbol_key)

  raise ReactOnRails::Error,
        "Cannot merge result[\"clientProps\"] when props contains both string and symbol versions of " \
        "#{string_key.inspect}. Normalize props keys before calling react_component."
end

#raise_missing_autoloaded_bundle(react_component_name) ⇒ Object



1054
1055
1056
1057
1058
1059
1060
# File 'lib/react_on_rails/helper.rb', line 1054

def raise_missing_autoloaded_bundle(react_component_name)
  raise ReactOnRails::SmartError.new(
    error_type: :missing_auto_loaded_bundle,
    component_name: react_component_name,
    expected_path: generated_components_pack_path(react_component_name)
  )
end

#raise_missing_autoloaded_store_bundle(store_name) ⇒ Object



1062
1063
1064
1065
1066
1067
1068
# File 'lib/react_on_rails/helper.rb', line 1062

def raise_missing_autoloaded_store_bundle(store_name)
  raise ReactOnRails::SmartError.new(
    error_type: :missing_auto_loaded_store_bundle,
    component_name: store_name,
    expected_path: generated_stores_pack_path(store_name)
  )
end

#raise_prerender_error(json_result, react_component_name, props, js_code) ⇒ Object



897
898
899
900
901
902
903
904
905
# File 'lib/react_on_rails/helper.rb', line 897

def raise_prerender_error(json_result, react_component_name, props, js_code)
  raise ReactOnRails::PrerenderError.new(
    component_name: react_component_name,
    props: sanitized_props_string(props),
    err: rendering_error_from_result(json_result),
    js_code:,
    console_messages: json_result["consoleReplayScript"]
  )
end

#react_component(component_name, options = {}) ⇒ Object

Main helper methods Returns html_safe string (ActiveSupport::SafeBuffer)



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/react_on_rails/helper.rb', line 100

def react_component(component_name, options = {})
  if options.key?(:immediate_hydration)
    ReactOnRails::Helper.warn_removed_immediate_hydration_option("react_component")
    options.delete(:immediate_hydration)
  end

  internal_result = internal_react_component(component_name, options)
  server_rendered_html = internal_result[:result]["html"]
  console_script = internal_result[:result]["consoleReplayScript"]
  render_options = internal_result[:render_options]

  case server_rendered_html
  when String
    html = build_react_component_result_for_server_rendered_string(
      server_rendered_html:,
      component_specification_tag: internal_result[:tag],
      console_script:,
      render_options:
    )
    html.html_safe
  when Hash
    msg = <<~MSG
      Use react_component_hash (not react_component) to return a Hash to your ruby view code. See
      https://github.com/shakacode/react_on_rails/blob/main/react_on_rails/spec/dummy/client/app/startup/ReactHelmetApp.server.tsx
      for an example of the necessary javascript configuration.
    MSG
    raise ReactOnRails::Error, msg
  else
    class_name = server_rendered_html.class.name
    msg = <<~MSG
      ReactOnRails: server_rendered_html is expected to be a String or Hash for #{component_name}.
      Type is #{class_name}
      Value:
      #{server_rendered_html}

      If you're trying to use a Render-Function to return a Hash to your ruby view code, then use
      react_component_hash instead of react_component and see
      https://github.com/shakacode/react_on_rails/blob/main/react_on_rails/spec/dummy/client/app/startup/ReactHelmetApp.server.tsx
      for an example of the JavaScript code.
    MSG
    raise ReactOnRails::Error, msg
  end
end

#react_component_hash(component_name, options = {}) ⇒ Object

Returns hash with html_safe strings (ActiveSupport::SafeBuffer)



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/react_on_rails/helper.rb', line 161

def react_component_hash(component_name, options = {})
  if options.key?(:immediate_hydration)
    ReactOnRails::Helper.warn_removed_immediate_hydration_option("react_component_hash")
    options.delete(:immediate_hydration)
  end

  options[:prerender] = true

  internal_result = internal_react_component(component_name, options)
  server_rendered_html = internal_result[:result]["html"]
  console_script = internal_result[:result]["consoleReplayScript"]
  render_options = internal_result[:render_options]

  if server_rendered_html.is_a?(String) && internal_result[:result]["hasErrors"]
    server_rendered_html = { COMPONENT_HTML_KEY => internal_result[:result]["html"] }
  end

  if server_rendered_html.is_a?(Hash)
    build_react_component_result_for_server_rendered_hash(
      server_rendered_html:,
      component_specification_tag: internal_result[:tag],
      console_script:,
      render_options:
    )

  else
    msg = <<~MSG
      Render-Function used by react_component_hash for #{component_name} is expected to return
      an Object. See https://github.com/shakacode/react_on_rails/blob/main/react_on_rails/spec/dummy/client/app/startup/ReactHelmetApp.server.tsx
      for an example of the JavaScript code.
      Note, your Render-Function must either take 2 params or have the property
      `.renderFunction = true` added to it to distinguish it from a React Function Component.
    MSG
    raise ReactOnRails::Error, msg
  end
end

#react_on_rails_attribution_commentObject

Generates the HTML attribution comment Pro version calls ReactOnRailsPro::Utils for license-specific details



781
782
783
784
785
786
787
# File 'lib/react_on_rails/helper.rb', line 781

def react_on_rails_attribution_comment
  if ReactOnRails::Utils.react_on_rails_pro?
    ReactOnRailsPro::Utils.pro_attribution_comment
  else
    "<!-- Powered by React on Rails (c) ShakaCode | Open Source -->"
  end
end

Returns html_safe string (ActiveSupport::SafeBuffer)

Parameters:

  • component_names (Object)

Returns:

  • (safe_buffer)


36
37
38
39
40
41
42
43
44
45
46
# File 'sig/react_on_rails/helper.rbs', line 36

def react_on_rails_preload_links(*component_names)
  ReactOnRails::PackerUtils.raise_nested_entries_disabled unless ReactOnRails::PackerUtils.nested_entries?

  pack_names = component_names.flatten.compact.map do |component_name|
    generated_component_pack_name(component_name)
  end

  sources = pack_names.flat_map { |pack_name| preload_sources_for_generated_pack(pack_name) }
  links = unique_preload_sources_by_href(sources).map { |source| preload_link_for_source(source) }
  safe_join(links, "\n")
end

#redux_store(store_name, props: {}, defer: false, auto_load_bundle: nil, **rest) ⇒ Object

Returns html_safe string (ActiveSupport::SafeBuffer)



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/react_on_rails/helper.rb', line 216

def redux_store(store_name, props: {}, defer: false, auto_load_bundle: nil, **rest)
  ReactOnRails::Helper.validate_redux_store_options!(rest)

  # Auto-load store pack if configured
  should_auto_load = auto_load_bundle.nil? ? ReactOnRails.configuration.auto_load_bundle : auto_load_bundle
  load_pack_for_generated_store(store_name, explicit_auto_load: auto_load_bundle == true) if should_auto_load

  redux_store_data = { store_name:,
                       props: }
  if defer
    registered_stores_defer_render << redux_store_data
    "YOU SHOULD NOT SEE THIS ON YOUR VIEW -- Uses as a code block, like <% redux_store %> " \
      "and not <%= redux store %>"
  else
    registered_stores << redux_store_data
    result = render_redux_store_data(redux_store_data)
    prepend_render_rails_context(result).html_safe
  end
end

#redux_store_hydration_datasafe_buffer

Returns html_safe string (ActiveSupport::SafeBuffer)

Returns:

  • (safe_buffer)


241
242
243
244
245
246
247
# File 'lib/react_on_rails/helper.rb', line 241

def redux_store_hydration_data
  return if registered_stores_defer_render.blank?

  registered_stores_defer_render.reduce(+"") do |accum, redux_store_data|
    accum << render_redux_store_data(redux_store_data)
  end.html_safe
end

#registered_storesObject

rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity



487
488
489
# File 'lib/react_on_rails/helper.rb', line 487

def registered_stores
  @registered_stores ||= []
end

#registered_stores_defer_renderObject



491
492
493
# File 'lib/react_on_rails/helper.rb', line 491

def registered_stores_defer_render
  @registered_stores_defer_render ||= []
end

#registered_stores_including_deferredObject



495
496
497
# File 'lib/react_on_rails/helper.rb', line 495

def registered_stores_including_deferred
  registered_stores + registered_stores_defer_render
end

#render_redux_store_data(redux_store_data) ⇒ Object



887
888
889
890
891
# File 'lib/react_on_rails/helper.rb', line 887

def render_redux_store_data(redux_store_data)
  store_hydration_data = generate_store_script(redux_store_data)

  prepend_render_rails_context(store_hydration_data)
end

#rendering_error_from_result(json_result) ⇒ Object



907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
# File 'lib/react_on_rails/helper.rb', line 907

def rendering_error_from_result(json_result)
  rendering_error = json_result["renderingError"]
  return unless rendering_error.is_a?(Hash)

  stack = rendering_error["stack"]
  # Mirror the JS `buildRSCStreamDiagnosticError` fallback: a renderingError that carries only
  # a stack (no message) should still surface a diagnostic rather than be silently dropped.
  message = rendering_error["message"].presence ||
            (stack.present? ? "RSC stream metadata reported a rendering error" : nil)
  return if message.nil?

  error = StandardError.new(message)
  frames = normalize_js_stack_lines(stack)
  error.set_backtrace(frames) unless frames.empty?
  error
end

#sanitized_props_string(props) ⇒ String

Parameters:

  • props (Hash[Symbol, untyped], String)

Returns:

  • (String)


261
262
263
# File 'lib/react_on_rails/helper.rb', line 261

def sanitized_props_string(props)
  ReactOnRails::JsonOutput.escape(props.is_a?(String) ? props : props.to_json)
end

#server_render_js(js_expression, options = {}) ⇒ Object

Returns html_safe string (ActiveSupport::SafeBuffer)



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/react_on_rails/helper.rb', line 269

def server_render_js(js_expression, options = {})
  render_options = ReactOnRails::ReactComponent::RenderOptions
                   .new(react_component_name: "generic-js", options:)

  js_code = <<~JS
    (function() {
      var htmlResult = '';
      var hasErrors = false;
      var renderingError = null;
      var renderingErrorObject = null;

      try {
        htmlResult =
          (function() {
            return #{js_expression};
          })();
      } catch(e) {
        renderingError = e;
        if (#{render_options.throw_js_errors}) {
          throw e;
        }
        htmlResult = ReactOnRails.handleError({e: e, name: null,
          jsCode: '#{escape_javascript(js_expression)}', serverSide: true});
        hasErrors = true;
        var errorMessage = String(renderingError);
        var errorStack = null;
        // Guard against non-Error throws (e.g., throw null / throw "string").
        // Boxed primitives (for example new Boolean(false)) are objects too.
        if (renderingError && typeof renderingError === 'object') {
          if ('message' in renderingError) {
            errorMessage = String(renderingError.message);
          }
          // Use != (not !==) to guard both null and undefined stack values.
          if ('stack' in renderingError && renderingError.stack != null) {
            errorStack = String(renderingError.stack);
          }
        }
        renderingErrorObject = {
          message: errorMessage,
          stack: errorStack,
        };
      }

      var consoleReplayScript = ReactOnRails.getConsoleReplayScript();
      return ReactOnRails.prepareRenderResult(htmlResult, consoleReplayScript, hasErrors, renderingErrorObject);
    })()
  JS

  result = ReactOnRails::ServerRenderingPool
           .server_render_js_with_console_logging(js_code, render_options)

  html = result["html"]
  console_script = result["consoleReplayScript"]
  console_script_tag = wrap_console_script_with_nonce(console_script) if render_options.replay_console
  raw("#{html}#{console_script_tag}")
rescue ExecJS::ProgramError => err
  raise ReactOnRails::PrerenderError.new(component_name: "N/A (server_render_js called)",
                                         err:,
                                         js_code:)
end

#server_rendered_react_component(render_options) ⇒ Object

Returns object with values that are NOT html_safe!



951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
# File 'lib/react_on_rails/helper.rb', line 951

def server_rendered_react_component(render_options)
  return { "html" => "", "consoleReplayScript" => "" } unless render_options.prerender

  react_component_name = render_options.react_component_name
  props = render_options.props

  # On server `location` option is added (`location = request.fullpath`)
  # React Router needs this to match the current route

  # Make sure that we use up-to-date bundle file used for server rendering, which is defined
  # by config file value for config.server_bundle_js_file
  ReactOnRails::ServerRenderingPool.reset_pool_if_server_bundle_was_modified

  # Since this code is not inserted on a web page, we don't need to escape props
  #
  # However, as JSON (returned from `props_string(props)`) isn't JavaScript,
  # but we want treat it as such, we need to compensate for the difference.
  #
  # \u2028 and \u2029 are valid characters in strings in JSON, but are treated
  # as newline separators in JavaScript. As no newlines are allowed in
  # strings in JavaScript, this causes an exception.
  #
  # We fix this by replacing these unicode characters with their escaped versions.
  # This should be safe, as the only place they can appear is in strings anyway.
  #
  # Read more here: http://timelessrepo.com/json-isnt-a-javascript-subset

  js_code = ReactOnRails::ServerRenderingJsCode.server_rendering_component_js_code(
    props_string: props_string(props).gsub("\u2028", '\u2028').gsub("\u2029", '\u2029'),
    rails_context: rails_context(server_side: true).to_json,
    redux_stores: initialize_redux_stores(render_options),
    react_component_name:,
    render_options:
  )

  begin
    result = ReactOnRails::ServerRenderingPool.server_render_js_with_console_logging(js_code, render_options)
  rescue StandardError => err
    # This error came from the renderer
    raise ReactOnRails::PrerenderError.new(component_name: react_component_name,
                                           # Sanitize as this might be browser logged
                                           props: sanitized_props_string(props),
                                           err:,
                                           js_code:)
  end

  if render_options.streaming?
    result.transform do |chunk_json_result|
      if should_raise_streaming_prerender_error?(chunk_json_result, render_options)
        raise_prerender_error(chunk_json_result, react_component_name, props, js_code)
      end
      # It doesn't make any transformation, it listens and raises error if a chunk has errors
      chunk_json_result
    end

    result.rescue do |err|
      # This error came from the renderer
      raise ReactOnRails::PrerenderError.new(component_name: react_component_name,
                                             # Sanitize as this might be browser logged
                                             props: sanitized_props_string(props),
                                             err:,
                                             js_code:)
    end
  elsif result["hasErrors"] && render_options.raise_on_prerender_error
    raise_prerender_error(result, react_component_name, props, js_code)
  end

  result
end

#shakapacker_integrity_configObject



630
631
632
633
634
635
# File 'lib/react_on_rails/helper.rb', line 630

def shakapacker_integrity_config
  config = current_shakapacker_instance.config
  return {} unless config.respond_to?(:integrity)

  config.integrity || {}
end

#should_raise_streaming_prerender_error?(chunk_json_result, render_options) ⇒ Boolean

Returns:

  • (Boolean)


941
942
943
944
945
946
947
948
# File 'lib/react_on_rails/helper.rb', line 941

def should_raise_streaming_prerender_error?(chunk_json_result, render_options)
  chunk_json_result["hasErrors"] &&
    (if chunk_json_result["isShellReady"]
       render_options.raise_non_shell_server_rendering_errors
     else
       render_options.raise_on_prerender_error
     end)
end

#unique_preload_sources_by_href(sources) ⇒ Object



563
564
565
566
567
568
569
570
571
572
# File 'lib/react_on_rails/helper.rb', line 563

def unique_preload_sources_by_href(sources)
  seen_hrefs = {}
  sources.filter_map do |source|
    href = preload_source_path(source.fetch(:source))
    next if seen_hrefs.key?(href)

    seen_hrefs[href] = true
    source.merge(href:)
  end
end

#wrap_console_script_with_nonce(console_script_code) ⇒ Object

Wraps console replay JavaScript code in a script tag with CSP nonce if available. The console_script_code is already sanitized by scriptSanitizedVal() in the JavaScript layer, so using html_safe here is secure.



741
742
743
744
745
746
747
748
749
750
751
752
# File 'lib/react_on_rails/helper.rb', line 741

def wrap_console_script_with_nonce(console_script_code)
  return "" if console_script_code.blank?

  nonce = csp_nonce

  # Build the script tag with nonce if available
  script_options = { id: "consoleReplayLog" }
  script_options[:nonce] = nonce if nonce.present?

  # Safe to use html_safe because content is pre-sanitized via scriptSanitizedVal()
  (:script, console_script_code.html_safe, script_options)
end