FIX: theme JS should only run when needed global objects exist (#6098)

This commit is contained in:
OsamaSayegh 2018-07-18 08:13:47 +03:00 committed by Sam
parent 0c159f17b7
commit 281538ae61
2 changed files with 18 additions and 8 deletions

View File

@ -44,10 +44,12 @@ class ThemeField < ActiveRecord::Base
def transpile(es6_source, version) def transpile(es6_source, version)
template = Tilt::ES6ModuleTranspilerTemplate.new {} template = Tilt::ES6ModuleTranspilerTemplate.new {}
wrapped = <<PLUGIN_API_JS wrapped = <<PLUGIN_API_JS
if ('Discourse' in window) {
Discourse._registerPluginCode('#{version}', api => { Discourse._registerPluginCode('#{version}', api => {
#{settings(es6_source)} #{settings(es6_source)}
#{es6_source} #{es6_source}
}); });
}
PLUGIN_API_JS PLUGIN_API_JS
template.babel_transpile(wrapped) template.babel_transpile(wrapped)
@ -73,7 +75,9 @@ PLUGIN_API_JS
node.replace <<COMPILED node.replace <<COMPILED
<script> <script>
(function() { (function() {
if ('Discourse' in window) {
Discourse.RAW_TEMPLATES[#{name.sub(/\.raw$/, '').inspect}] = #{template}; Discourse.RAW_TEMPLATES[#{name.sub(/\.raw$/, '').inspect}] = #{template};
}
})(); })();
</script> </script>
COMPILED COMPILED
@ -82,7 +86,9 @@ COMPILED
node.replace <<COMPILED node.replace <<COMPILED
<script> <script>
(function() { (function() {
if ('Em' in window) {
Ember.TEMPLATES[#{name.inspect}] = #{template}; Ember.TEMPLATES[#{name.inspect}] = #{template};
}
})(); })();
</script> </script>
COMPILED COMPILED

View File

@ -233,10 +233,12 @@ HTML
theme.save! theme.save!
transpiled = <<~HTML transpiled = <<~HTML
<script>Discourse._registerPluginCode('1.0', function (api) { <script>if ('Discourse' in window) {
Discourse._registerPluginCode('1.0', function (api) {
var settings = { "name": "bob" }; var settings = { "name": "bob" };
alert(settings.name);var a = function a() {}; alert(settings.name);var a = function a() {};
});</script> });
}</script>
HTML HTML
expect(Theme.lookup_field(theme.id, :desktop, :after_header)).to eq(transpiled.strip) expect(Theme.lookup_field(theme.id, :desktop, :after_header)).to eq(transpiled.strip)
@ -245,10 +247,12 @@ HTML
setting.value = 'bill' setting.value = 'bill'
transpiled = <<~HTML transpiled = <<~HTML
<script>Discourse._registerPluginCode('1.0', function (api) { <script>if ('Discourse' in window) {
Discourse._registerPluginCode('1.0', function (api) {
var settings = { "name": "bill" }; var settings = { "name": "bill" };
alert(settings.name);var a = function a() {}; alert(settings.name);var a = function a() {};
});</script> });
}</script>
HTML HTML
expect(Theme.lookup_field(theme.id, :desktop, :after_header)).to eq(transpiled.strip) expect(Theme.lookup_field(theme.id, :desktop, :after_header)).to eq(transpiled.strip)