Module: ReactOnRails::Helper

Includes:
Utils::Required, ScoutApm::Tracer
Included in:
ReactOnRailsHelper
Defined in:
lib/react_on_rails/helper.rb

Constant Summary collapse

COMPONENT_HTML_KEY =
"componentHtml"

Instance Method Summary collapse

Methods included from Utils::Required

#required

Instance Method Details

#json_safe_and_pretty(hash_or_string) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/react_on_rails/helper.rb', line 244

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



316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/react_on_rails/helper.rb', line 316

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

  ReactOnRails::WebpackerUtils.raise_nested_entries_disabled unless ReactOnRails::WebpackerUtils.nested_entries?
  if Rails.env.development?
    is_component_pack_present = File.exist?(generated_components_pack_path(react_component_name))
    raise_missing_autoloaded_bundle(react_component_name) unless is_component_pack_present
  end
  append_javascript_pack_tag("generated/#{react_component_name}",
                             defer: ReactOnRails.configuration.defer_generated_component_packs)
  append_stylesheet_pack_tag("generated/#{react_component_name}")
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



262
263
264
265
266
267
268
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
# File 'lib/react_on_rails/helper.rb', line 262

def rails_context(server_side: true)
  # ALERT: Keep in sync with node_package/src/types/index.ts for the properties of RailsContext
  @rails_context ||= begin
    result = {
      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
      rorPro: ReactOnRails::Utils.react_on_rails_pro?
    }
    if ReactOnRails::Utils.react_on_rails_pro?
      result[:rorProVersion] = ReactOnRails::Utils.react_on_rails_pro_version
    end

    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.present? ? "?#{uri.query}" : ''}",
        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

  @rails_context.merge(serverSide: server_side)
end

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

react_component_name: can be a React function or class component or a “Render-Function”. “Render-Functions” differ from a React function in that they take two parameters, the

props and the railsContext, like this:

let MyReactComponentApp = (props, railsContext) => <MyReactComponent {...props}/>;

Alternately, you can define the Render-Function with an additional property
`.renderFunction = true`:

let MyReactComponentApp = (props) => <MyReactComponent {...props}/>;
MyReactComponent.renderFunction = true;

Exposing the react_component_name is necessary to both a plain ReactComponent as well as
  a generator:
See README.md for how to "register" your react components.
See spec/dummy/client/app/packs/server-bundle.js and
  spec/dummy/client/app/packs/client-bundle.js for examples of this.

options:

props: Ruby Hash or JSON string which contains the properties to pass to the react object. Do
   not pass any props if you are separately initializing the store by the `redux_store` helper.
prerender: <true/false> set to false when debugging!
id: You can optionally set the id, or else a unique one is automatically generated.
html_options: You can set other html attributes that will go on this component
trace: <true/false> set to true to print additional debugging information in the browser
       default is true for development, off otherwise
replay_console: <true/false> Default is true. False will disable echoing server rendering
                logs to browser. While this can make troubleshooting server rendering difficult,
                so long as you have the default configuration of logging_on_server set to
                true, you'll still see the errors on the server.
raise_on_prerender_error: <true/false> Default to false. True will raise exception on server
   if the JS code throws

Any other options are passed to the content tag, including the id. random_dom_id can be set to override the default from the config/initializers. That’s only used if you have multiple instance of the same component on the Rails view.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/react_on_rails/helper.rb', line 56

def react_component(component_name, options = {})
  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
    build_react_component_result_for_server_rendered_string(
      server_rendered_html: server_rendered_html,
      component_specification_tag: internal_result[:tag],
      console_script: console_script,
      render_options: render_options
    )
  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/master/spec/dummy/client/app/startup/ReactHelmetServerApp.jsx
      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/master/spec/dummy/client/app/startup/ReactHelmetServerApp.jsx
      for an example of the JavaScript code.
    MSG
    raise ReactOnRails::Error, msg
  end
end

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

react_component_hash is used to return multiple HTML strings for server rendering, such as for adding meta-tags to a page. It is exactly like react_component except for the following:

  1. prerender: true is automatically added, as this method doesn’t make sense for client only rendering.

  2. Your JavaScript Render-Function for server rendering must return an Object rather than a React component.

  3. Your view code must expect an object and not a string.

Here is an example of the view code:

<% react_helmet_app = react_component_hash("ReactHelmetApp", prerender: true,
                                           props: { helloWorldData: { name: "Mr. Server Side Rendering"}},
                                           id: "react-helmet-0", trace: true) %>
<% content_for :title do %>
  <%= react_helmet_app['title'] %>
<% end %>
<%= react_helmet_app["componentHtml"] %>


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
# File 'lib/react_on_rails/helper.rb', line 111

def react_component_hash(component_name, options = {})
  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: server_rendered_html,
      component_specification_tag: internal_result[:tag],
      console_script: console_script,
      render_options: 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/master/spec/dummy/client/app/startup/ReactHelmetServerApp.jsx
      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

#redux_store(store_name, props: {}, defer: false) ⇒ Object

Separate initialization of store from react_component allows multiple react_component calls to use the same Redux store.

NOTE: This technique not recommended as it prevents dynamic code splitting for performance. Instead, you should use the standard react_component view helper.

store_name: name of the store, corresponding to your call to ReactOnRails.registerStores in your

JavaScript code.

props: Ruby Hash or JSON string which contains the properties to pass to the redux store. Options

defer: false -- pass as true if you wish to render this below your component.


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/react_on_rails/helper.rb', line 152

def redux_store(store_name, props: {}, defer: false)
  redux_store_data = { store_name: store_name,
                       props: props }
  if defer
    @registered_stores_defer_render ||= []
    @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 ||= []
    @registered_stores << redux_store_data
    result = render_redux_store_data(redux_store_data)
    prepend_render_rails_context(result)
  end
end

#redux_store_hydration_dataObject

Place this view helper (no parameters) at the end of your shared layout. This tell ReactOnRails where to client render the redux store hydration data. Since we’re going to be setting up the stores in the controllers, we need to know where on the view to put the client side rendering of this hydration data, which is a hidden div with a matching class that contains a data props.



173
174
175
176
177
178
179
# File 'lib/react_on_rails/helper.rb', line 173

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

#sanitized_props_string(props) ⇒ Object



181
182
183
# File 'lib/react_on_rails/helper.rb', line 181

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

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

Helper method to take javascript expression and returns the output from evaluating it. If you have more than one line that needs to be executed, wrap it in an IIFE. JS exceptions are caught and console messages are handled properly. Options include:{ prerender:, trace:, raise_on_prerender_error:, throw_js_errors: }



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/react_on_rails/helper.rb', line 189

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

  js_code = <<-JS.strip_heredoc
  (function() {
    var htmlResult = '';
    var consoleReplayScript = '';
    var hasErrors = false;
    var renderingError = null;
    var renderingErrorObject = {};

    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;
      renderingErrorObject = {
        message: renderingError.message,
        stack: renderingError.stack,
      }
    }

    consoleReplayScript = ReactOnRails.buildConsoleReplay();

    return JSON.stringify({
        html: htmlResult,
        consoleReplayScript: consoleReplayScript,
        hasErrors: hasErrors,
        renderingError: renderingErrorObject
    });

  })()
  JS

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

  html = result["html"]
  console_log_script = result["consoleLogScript"]
  raw("#{html}#{render_options.replay_console ? console_log_script : ''}")
rescue ExecJS::ProgramError => err
  raise ReactOnRails::PrerenderError.new(component_name: "N/A (server_render_js called)",
                                         err: err,
                                         js_code: js_code)
end