chartjs-override.js TypeError on pie/doughnut charts and colour overwrite on non-election charts [3.x]
>>> [!note] Migrated issue
<!-- Drupal.org comment -->
<!-- Migrated from issue #3579223. -->
Reported by: [awearring](https://www.drupal.org/user/112933)
Related to !16
>>>
<p>This is the 3.x equivalent of <a href="https://www.drupal.org/project/localgov_elections/issues/3579222">#3579222</a>, which was raised and patched against the 2.x branch. The same two bugs are present in the 3.x codebase.</p>
<p><strong>Bug 1 — TypeError on pie/doughnut charts</strong></p>
<p><code>setChartColours()</code> unconditionally accesses <code>chartData.options.scales.x</code>. Pie and doughnut chart types have no axes, so <code>chartData.options.scales</code> is <code>undefined</code>, throwing:</p>
<p><code>Uncaught TypeError: can't access property "x", chartData.options.scales is undefined</code></p>
<p><strong>Bug 2 — Non-election charts have colours overwritten</strong></p>
<p><code>setChartColours()</code> runs against every <code>.charts-chartjs</code> element on the page. For any non-election chart, no party match is found and every label's colour is pushed as <code>#ffffff</code>, rendering the chart entirely white with no JavaScript error to indicate the cause.</p>
<p><strong>Steps to reproduce:</strong></p>
<ol>
<li>Enable <code>localgov_elections</code> on a site also using <code>drupal/charts</code></li>
<li>Place any non-election chart (e.g. a pie chart with colours defined in the Drupal Charts UI) on the same page as an election chart</li>
<li>Observe the non-election chart renders entirely white</li>
<li>Place a pie or doughnut chart type as an election chart</li>
<li>Observe the TypeError in the browser console</li>
</ol>
<p><strong>Suggested fix:</strong></p>
<p>Full details and suggested code fix are documented in the parent issue <a href="https://www.drupal.org/project/localgov_elections/issues/3579222">#3579222</a>. The same two changes are needed in the 3.x version of <code>js/chartjs-override.js</code>:</p>
<ol>
<li>Wrap <code>scales.x</code> and <code>scales.y</code> access in existence checks to prevent TypeError on axisless chart types</li>
<li>Pass the chart ID into <code>setChartColours()</code> and return early if the chart is not a known election chart ID, preventing <code>backgroundColor</code> being overwritten on unrelated <code>drupal/charts</code> instances</li>
</ol>
<p><strong>Related issues:</strong><br>
Parent issue (2.x): <a href="https://www.drupal.org/project/localgov_elections/issues/3579222">#3579222</a></p>
issue