michelson / lazy_high_charts

Make highcharts a la ruby , works in rails 5.X / 4.X / 3.X, and other ruby web frameworks
http://www.suipit.com
MIT License
1.05k stars 242 forks source link

Does not work with Turbo gem #258

Closed redhoodie closed 3 years ago

redhoodie commented 3 years ago

Does not generate Turbolinks like JavaScript event handler when using the Turbo gem.

See line 109 of layout_helper.rb https://github.com/michelson/lazy_high_charts/blob/master/lib/lazy_high_charts/layout_helper.rb#L109

As with Turbolinks gem document.addEventListener("turbolinks:load", function() {

We need to use an event listener like so: document.addEventListener("turbo:load", function() {

duffyjp commented 2 years ago

I must be doing something wrong... Updating from Turbolinks to Turbo (and the latest lazy_high_charts) I'm getting this result in my charts which of course only actually loads the charts if you do a full page reload. 🤔

window.addEventListener('load', function() {

I'm using the stock high_chart helper. A possible complication is I'm using the as needed loading DHH outlines in his Turbo video.

View

<%= content_for(:head) { javascript_import_module_tag 'application/highcharts' } %>

Layout

<head>
...
<%= yield :head %>
</head>

app/javascript/application/highcharts.js


import Highcharts from 'https://code.highcharts.com/es-modules/masters/highcharts.src.js';
window.Highcharts = Highcharts;
import 'https://code.highcharts.com/es-modules/masters/highcharts-more.src.js';
import 'https://code.highcharts.com/es-modules/masters/modules/sankey.src.js';

Highcharts.setOptions({ global: { useUTC: false } });

duffyjp commented 2 years ago

It looks like the issue is with encapsulate_js thinking Turbo is undefined... I tried copying the entire lib/lazy_high_charts/layout_helper.rb into my config/initializers and monkeypatched it to just always use the turbo:load option and everything works.

If I can figure out why it's not finding Turbo I'll send in a PR.

    def encapsulate_js(core_js)
      js_output = js_event_function(core_js, 'turbo:load')
      js_output = "(function() {\n  #{js_output}\n})()"

      if defined?(javascript_tag)
        javascript_tag js_output, nonce: true
      else
        "<script type='text/javascript'>#{js_output}</script>"
      end
    end