ankane / chartkick

Create beautiful JavaScript charts with one line of Ruby
https://chartkick.com
MIT License
6.33k stars 565 forks source link

Chartkick doesn't refresh with Turbo morphing #625

Open anquinn opened 1 month ago

anquinn commented 1 month ago

Using chartkick with Turbo 8's new morphing doesn't update the chart.

To reproduce Add any chartkick chart to a page, and update the data source via a morph. Ex:

<%= bar_chart @vote_chart %>

class Results < ApplicationRecord
  broadcasts_refreshes

  @vote_chart = ...
end

HTML generated by Chartkick

  <div id="chart-1" style="height: 300px; width: 100%; text-align: center; color: #999; line-height: 300px; font-size: 14px; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif;"><canvas style="display: block; box-sizing: border-box; height: 300px; width: 1168px;" width="2336" height="600"></canvas></div>
  <script>
  (function() {
    if (document.documentElement.hasAttribute("data-turbolinks-preview")) return;
    if (document.documentElement.hasAttribute("data-turbo-preview")) return;

    var createChart = function() { new Chartkick["ColumnChart"]("chart-1", [["Candidate 1",4],["Candidate 2",1],["Candidate 3",1],["Candidate 4",0],["Candidate 5",0],["Candidate 6",0]], {}); };
    if ("Chartkick" in window) {
      createChart();
    } else {
      window.addEventListener("chartkick:load", createChart, true);
    }
  })();
  </script>

After the turbo refresh happens, the page data is correct, but the chartkick chart shows "Loading".

I've attempted to monkey patch the helper similar to https://github.com/ankane/chartkick/issues/608 and add in a listener for "turbo:morph" but that doesn't seem to work. Refreshing the page in the browser renders the chart as intended.