19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
93
94
95
96
97
98
99
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
|
# File 'lib/isomorfeus/react_view_helper.rb', line 19
def mount_component(component_name, props = {}, asset = 'web_ssr.js', static = false)
@ssr_response_status = nil
@ssr_styles = nil
thread_id_asset = "#{Thread.current.object_id}#{asset}"
render_result = if static
'<div>'
else
"<div data-iso-env=\"#{Isomorfeus.env}\" data-iso-root=\"#{component_name}\" data-iso-props='#{Oj.dump(props, mode: :strict)}'"
end
if Isomorfeus.server_side_rendering
if Isomorfeus.development?
if Isomorfeus.ssr_contexts.key?(thread_id_asset)
uuid = Isomorfeus.ssr_contexts[thread_id_asset].instance_variable_get(:@uuid)
runtime = Isomorfeus.ssr_contexts[thread_id_asset].instance_variable_get(:@runtime)
runtime.vm.delete_context(uuid)
end
asset_path = "#{Isomorfeus.ssr_hot_asset_url}#{asset}"
begin
asset = Net::HTTP.get(URI(asset_path))
rescue Exception => e
Isomorfeus.raise_error(message: "Server Side Rendering: Failed loading asset #{asset_path} from webpack dev server. Error: #{e.message}", stack: e.backtrace )
end
if asset.strip.start_with?('<')
Isomorfeus.raise_error(message: "Server Side Rendering: Failed loading asset #{asset_path} from webpack dev server, asset is not javascript. Did the webpack build succeed?")
end
begin
Isomorfeus.ssr_contexts[thread_id_asset] = ExecJS.permissive_compile(asset)
rescue Exception => e
Isomorfeus.raise_error(message: "Server Side Rendering: Failed creating context for #{asset_path}. Error: #{e.message}", stack: e.backtrace)
end
else
unless Isomorfeus.ssr_contexts.key?(thread_id_asset)
asset_file_name = OpalWebpackLoader::Manifest.lookup_path_for(asset)
Isomorfeus.raise_error(message: "Server Side Rendering: Build asset file not found for #{asset}. Has it been build?") unless asset_file_name
asset_path = File.join('public', asset_file_name)
Isomorfeus.ssr_contexts[thread_id_asset] = ExecJS.permissive_compile(File.read(asset_path))
end
end
javascript = " global.Opal.React.render_buffer = [];\n global.Opal.React.active_components = [];\n global.Opal.React.active_redux_components = [];\n global.FirstPassFinished = false;\n global.Exception = false;\n global.IsomorfeusSessionId = '\#{Thread.current[:isomorfeus_session_id]}';\n global.Opal.Isomorfeus['$env=']('\#{Isomorfeus.env}');\n if (typeof global.Opal.Isomorfeus.$negotiated_locale === 'function') {\n global.Opal.Isomorfeus[\"$negotiated_locale=\"]('\#{props[:locale]}');\n }\n global.Opal.Isomorfeus['$force_init!']();\n global.Opal.Isomorfeus['$ssr_response_status='](200);\n global.Opal.Isomorfeus.TopLevel['$ssr_route_path=']('\#{props[:location]}');\n JAVASCRIPT\n\n # if location_host and scheme are given and if Transport is loaded, connect and then render,\n # otherwise do not render because only one pass is required\n ws_scheme = props[:location_scheme] == 'https:' ? 'wss:' : 'ws:'\n location_host = props[:location_host] ? props[:location_host] : 'localhost'\n api_ws_path = Isomorfeus.respond_to?(:api_websocket_path) ? Isomorfeus.api_websocket_path : ''\n transport_ws_url = ws_scheme + location_host + api_ws_path\n javascript << <<~JAVASCRIPT\n let api_ws_path = '\#{api_ws_path}';\n let exception;\n if (typeof global.Opal.Isomorfeus.Transport !== 'undefined' && api_ws_path !== '') {\n global.Opal.Isomorfeus.TopLevel[\"$transport_ws_url=\"](\"\#{transport_ws_url}\");\n global.Opal.send(global.Opal.Isomorfeus.Transport.$promise_connect(), 'then', [], ($$1 = function(){\n try {\n if (\#{static}) { global.Opal.Isomorfeus.TopLevel.$render_component_to_static_markup('\#{component_name}', \#{Oj.dump(props, mode: :strict)}); }\n else { global.Opal.Isomorfeus.TopLevel.$render_component_to_string('\#{component_name}', \#{Oj.dump(props, mode: :strict)}); }\n global.FirstPassFinished = 'transport';\n } catch (e) {\n global.Exception = e;\n global.FirstPassFinished = 'transport';\n }\n }, $$1.$$s = this, $$1.$$arity = 0, $$1))\n } else { return global.FirstPassFinished = true; };\n JAVASCRIPT\n\n # execute first render pass\n first_pass_skipped = Isomorfeus.ssr_contexts[thread_id_asset].exec(javascript)\n\n # wait for first pass to finish\n unless first_pass_skipped\n first_pass_finished, exception = Isomorfeus.ssr_contexts[thread_id_asset].exec('return [global.FirstPassFinished, global.Exception ? { message: global.Exception.message, stack: global.Exception.stack } : false ]')\n Isomorfeus.raise_error(message: \"Server Side Rendering: \#{exception['message']}\", stack: exception['stack']) if exception\n unless first_pass_finished\n start_time = Time.now\n while !first_pass_finished\n break if (Time.now - start_time) > 10\n sleep 0.01\n first_pass_finished = Isomorfeus.ssr_contexts[thread_id_asset].exec('return global.FirstPassFinished')\n end\n end\n\n # wait for transport requests to finish\n if first_pass_finished == 'transport'\n transport_busy = Isomorfeus.ssr_contexts[thread_id_asset].exec('return global.Opal.Isomorfeus.Transport[\"$busy?\"]()')\n if transport_busy\n start_time = Time.now\n while transport_busy\n break if (Time.now - start_time) > 10\n sleep 0.01\n transport_busy = Isomorfeus.ssr_contexts[thread_id_asset].exec('return global.Opal.Isomorfeus.Transport[\"$busy?\"]()')\n end\n end\n end\n end\n\n # build javascript for second render pass\n # guard against leaks from first pass, maybe because of a exception\n javascript = <<~JAVASCRIPT\n global.Opal.React.render_buffer = [];\n global.Opal.React.active_components = [];\n global.Opal.React.active_redux_components = [];\n global.Exception = false;\n let rendered_tree;\n let ssr_styles;\n let component;\n if (typeof global.Opal.global.MuiStyles !== 'undefined' && typeof global.Opal.global.MuiStyles.ServerStyleSheets !== 'undefined') {\n component = '\#{component_name}'.split(\".\").reduce(function(o, x) {\n return (o !== null && typeof o[x] !== \"undefined\" && o[x] !== null) ? o[x] : null;\n }, global.Opal.global)\n if (!component) { component = global.Opal.Isomorfeus.$cached_component_class('\#{component_name}'); }\n try {\n let sheets = new global.Opal.global.MuiStyles.ServerStyleSheets();\n let app = global.Opal.React.$create_element(component, global.Opal.Hash.$new(\#{Oj.dump(props, mode: :strict)}));\n if (\#{static}) { rendered_tree = global.Opal.global.ReactDOMServer.renderToStaticMarkup(sheets.collect(app)); }\n else { rendered_tree = global.Opal.global.ReactDOMServer.renderToString(sheets.collect(app)); }\n ssr_styles = sheets.toString();\n } catch (e) {\n global.Exception = e;\n }\n } else if (typeof global.Opal.global.ReactJSS !== 'undefined' && typeof global.Opal.global.ReactJSS.SheetsRegistry !== 'undefined') {\n component = '\#{component_name}'.split(\".\").reduce(function(o, x) {\n return (o !== null && typeof o[x] !== \"undefined\" && o[x] !== null) ? o[x] : null;\n }, global.Opal.global)\n if (!component) { component = global.Opal.Isomorfeus.$cached_component_class('\#{component_name}'); }\n try {\n let sheets = new global.Opal.global.ReactJSS.SheetsRegistry();\n let generate_id = global.Opal.global.ReactJSS.createGenerateId();\n let app = global.Opal.React.$create_element(component, global.Opal.Hash.$new(\#{Oj.dump(props, mode: :strict)}));\n let element = global.Opal.global.React.createElement(global.Opal.global.ReactJSS.JssProvider, { registry: sheets, generateId: generate_id }, app);\n if (\#{static}) { rendered_tree = global.Opal.global.ReactDOMServer.renderToStaticMarkup(element); }\n else { rendered_tree = global.Opal.global.ReactDOMServer.renderToString(element); }\n ssr_styles = sheets.toString();\n } catch (e) {\n global.Exception = e;\n }\n } else {\n try {\n if (\#{static}) { rendered_tree = global.Opal.Isomorfeus.TopLevel.$render_component_to_static_markup('\#{component_name}', \#{Oj.dump(props, mode: :strict)}); } \n else { rendered_tree = global.Opal.Isomorfeus.TopLevel.$render_component_to_string('\#{component_name}', \#{Oj.dump(props, mode: :strict)}); }\n } catch (e) {\n global.Exception = e;\n }\n }\n let application_state = global.Opal.Isomorfeus.store.native.getState();\n if (typeof global.Opal.Isomorfeus.Transport !== 'undefined') { global.Opal.Isomorfeus.Transport.$disconnect(); }\n return [rendered_tree, application_state, ssr_styles, global.Opal.Isomorfeus['$ssr_response_status'](), global.Exception ? { message: global.Exception.message, stack: global.Exception.stack } : false];\n JAVASCRIPT\n\n # execute second render pass\n rendered_tree, application_state, @ssr_styles, @ssr_response_status, exception = Isomorfeus.ssr_contexts[thread_id_asset].exec(javascript)\n Isomorfeus.raise_error(message: exception['message'], stack: exception['stack']) if exception\n\n # build result\n unless static\n render_result << \" data-iso-hydrated='true'\" if rendered_tree\n if Isomorfeus.respond_to?(:current_user) && Isomorfeus.current_user && !Isomorfeus.current_user.anonymous?\n render_result << \" data-iso-usid=\#{Oj.dump(Isomorfeus.current_user.to_sid, mode: :strict)}\"\n end\n render_result << \" data-iso-nloc='\#{props[:locale]}'>\"\n end\n render_result << (rendered_tree ? rendered_tree : \"SSR didn't work\")\n else\n if Isomorfeus.respond_to?(:current_user) && Isomorfeus.current_user && !Isomorfeus.current_user.anonymous?\n render_result << \" data-iso-usid=\#{Oj.dump(Isomorfeus.current_user.to_sid, mode: :strict)}\"\n end\n render_result << \" data-iso-nloc='\#{props[:locale]}'>\" unless static\n end\n render_result << '</div>'\n if Isomorfeus.server_side_rendering && !static\n render_result = \"<script type='application/javascript'>\\nServerSideRenderingStateJSON = \#{Oj.dump(application_state, mode: :strict)}\\n</script>\\n\" << render_result\n end\n render_result\nend\n"
|