A platform for community discussion. Free, open, simple.
FIX: theme JS should only run when needed global objects exist (#6098)
OsamaSayegh281538ae61d6
diff --git a/app/models/theme_field.rb b/app/models/theme_field.rbindex da1ab9d2a29..92d7fd2d172 100644--- a/app/models/theme_field.rb+++ b/app/models/theme_field.rb@@ -44,10 +44,12 @@ class ThemeField < ActiveRecord::Basedef transpile(es6_source, version)template = Tilt::ES6ModuleTranspilerTemplate.new {}wrapped = <<PLUGIN_API_JS+if ('Discourse' in window) {Discourse._registerPluginCode('#{version}', api => {#{settings(es6_source)}#{es6_source}});+}PLUGIN_API_JStemplate.babel_transpile(wrapped)@@ -73,7 +75,9 @@ PLUGIN_API_JSnode.replace <<COMPILED<script>(function() {+ if ('Discourse' in window) {Discourse.RAW_TEMPLATES[#{name.sub(/\.raw$/, '').inspect}] = #{template};+ }})();</script>COMPILED@@ -82,7 +86,9 @@ COMPILEDnode.replace <<COMPILED<script>(function() {+ if ('Em' in window) {Ember.TEMPLATES[#{name.inspect}] = #{template};+ }})();</script>COMPILEDdiff --git a/spec/models/theme_spec.rb b/spec/models/theme_spec.rbindex 5802de76120..d12e0fd10a0 100644--- a/spec/models/theme_spec.rb+++ b/spec/models/theme_spec.rb@@ -233,10 +233,12 @@ HTMLtheme.save!transpiled = <<~HTML- <script>Discourse._registerPluginCode('1.0', function (api) {- var settings = { "name": "bob" };- alert(settings.name);var a = function a() {};- });</script>+ <script>if ('Discourse' in window) {+ Discourse._registerPluginCode('1.0', function (api) {+ var settings = { "name": "bob" };+ alert(settings.name);var a = function a() {};+ });+ }</script>HTMLexpect(Theme.lookup_field(theme.id, :desktop, :after_header)).to eq(transpiled.strip)@@ -245,10 +247,12 @@ HTMLsetting.value = 'bill'transpiled = <<~HTML- <script>Discourse._registerPluginCode('1.0', function (api) {- var settings = { "name": "bill" };- alert(settings.name);var a = function a() {};- });</script>+ <script>if ('Discourse' in window) {+ Discourse._registerPluginCode('1.0', function (api) {+ var settings = { "name": "bill" };+ alert(settings.name);var a = function a() {};+ });+ }</script>HTMLexpect(Theme.lookup_field(theme.id, :desktop, :after_header)).to eq(transpiled.strip)