]> git.ipfire.org Git - thirdparty/Chart.js.git/commitdiff
Trigger legend onLeave when the mouse leaves the canvas (#10301)
authorEvert Timberg <evert.timberg@gmail.com>
Fri, 15 Apr 2022 23:36:42 +0000 (19:36 -0400)
committerGitHub <noreply@github.com>
Fri, 15 Apr 2022 23:36:42 +0000 (19:36 -0400)
src/plugins/plugin.legend.js
test/specs/plugin.legend.tests.js

index 7388bc714f11dc4c8ffc33d93d8d44320ccb847d..02fa12ae1a87924d81b1f22dc9cfc9f07864dc7d 100644 (file)
@@ -524,7 +524,7 @@ export class Legend extends Element {
     // Chart event already has relative position in it
     const hoveredItem = this._getLegendItemAt(e.x, e.y);
 
-    if (e.type === 'mousemove') {
+    if (e.type === 'mousemove' || e.type === 'mouseout') {
       const previous = this._hoveredItem;
       const sameItem = itemsEqual(previous, hoveredItem);
       if (previous && !sameItem) {
@@ -543,7 +543,7 @@ export class Legend extends Element {
 }
 
 function isListened(type, opts) {
-  if (type === 'mousemove' && (opts.onHover || opts.onLeave)) {
+  if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {
     return true;
   }
   if (opts.onClick && (type === 'click' || type === 'mouseup')) {
index b8d1fba6d84407caab4fc06c932b4bf7b522eec2..9c7f340f13e5968af4db3589d93d002f676fb551 100644 (file)
@@ -997,6 +997,46 @@ describe('Legend block tests', function() {
       expect(leaveItem).toBe(chart.legend.legendItems[0]);
     });
 
+    it('should call onLeave when the mouse leaves the canvas', async function() {
+      var hoverItem = null;
+      var leaveItem = null;
+
+      var chart = acquireChart({
+        type: 'line',
+        data: {
+          labels: ['A', 'B', 'C', 'D'],
+          datasets: [{
+            data: [10, 20, 30, 100]
+          }]
+        },
+        options: {
+          plugins: {
+            legend: {
+              onHover: function(_, item) {
+                hoverItem = item;
+              },
+              onLeave: function(_, item) {
+                leaveItem = item;
+              }
+            }
+          }
+        }
+      });
+
+      var hb = chart.legend.legendHitBoxes[0];
+      var el = {
+        x: hb.left + (hb.width / 2),
+        y: hb.top + (hb.height / 2)
+      };
+
+      await jasmine.triggerMouseEvent(chart, 'mousemove', el);
+      expect(hoverItem).toBe(chart.legend.legendItems[0]);
+
+      await jasmine.triggerMouseEvent(chart, 'mouseout');
+      expect(leaveItem).toBe(chart.legend.legendItems[0]);
+    });
+
+
     it('should call onClick for the correct item when in RTL mode', async function() {
       var clickItem = null;