billboard.js 4.0.3 → 4.1.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/README.md +82 -7
  2. package/dist/billboard.css +1 -1
  3. package/dist/billboard.js +1848 -494
  4. package/dist/billboard.min.css +1 -1
  5. package/dist/billboard.min.js +19 -24
  6. package/dist/billboard.pkgd.js +1844 -679
  7. package/dist/billboard.pkgd.min.js +24 -29
  8. package/dist/billboard.react.js +205 -0
  9. package/dist/billboard.react.min.js +9 -0
  10. package/dist/billboard.worker.js +10 -0
  11. package/dist/plugin/billboardjs-plugin-bubblecompare.js +5 -3
  12. package/dist/plugin/billboardjs-plugin-bubblecompare.min.js +2 -2
  13. package/dist/plugin/billboardjs-plugin-sparkline.js +6 -3
  14. package/dist/plugin/billboardjs-plugin-sparkline.min.js +3 -3
  15. package/dist/plugin/billboardjs-plugin-stanford.js +6 -3
  16. package/dist/plugin/billboardjs-plugin-stanford.min.js +3 -3
  17. package/dist/plugin/billboardjs-plugin-tableview.js +59 -27
  18. package/dist/plugin/billboardjs-plugin-tableview.min.js +5 -5
  19. package/dist/plugin/billboardjs-plugin-textoverlap.js +75 -55
  20. package/dist/plugin/billboardjs-plugin-textoverlap.min.js +2 -2
  21. package/dist/plugin/pkgd/billboardjs-plugin-bubblecompare.pkgd.js +5 -3
  22. package/dist/plugin/pkgd/billboardjs-plugin-bubblecompare.pkgd.min.js +2 -2
  23. package/dist/plugin/pkgd/billboardjs-plugin-sparkline.pkgd.js +6 -3
  24. package/dist/plugin/pkgd/billboardjs-plugin-sparkline.pkgd.min.js +3 -3
  25. package/dist/plugin/pkgd/billboardjs-plugin-stanford.pkgd.js +6 -3
  26. package/dist/plugin/pkgd/billboardjs-plugin-stanford.pkgd.min.js +2 -2
  27. package/dist/plugin/pkgd/billboardjs-plugin-tableview.pkgd.js +59 -27
  28. package/dist/plugin/pkgd/billboardjs-plugin-tableview.pkgd.min.js +11 -11
  29. package/dist/plugin/pkgd/billboardjs-plugin-textoverlap.pkgd.js +68 -3557
  30. package/dist/plugin/pkgd/billboardjs-plugin-textoverlap.pkgd.min.js +8 -8
  31. package/dist/theme/dark.css +1 -1
  32. package/dist/theme/dark.min.css +1 -1
  33. package/dist/theme/datalab.css +1 -1
  34. package/dist/theme/datalab.min.css +1 -1
  35. package/dist/theme/graph.css +1 -1
  36. package/dist/theme/graph.min.css +1 -1
  37. package/dist/theme/insight.css +1 -1
  38. package/dist/theme/insight.min.css +1 -1
  39. package/dist/theme/modern.css +1 -1
  40. package/dist/theme/modern.min.css +1 -1
  41. package/dist-esm/Chart/Chart.js +134 -152
  42. package/dist-esm/Chart/api/axis.js +217 -237
  43. package/dist-esm/Chart/api/category.js +54 -54
  44. package/dist-esm/Chart/api/chart.js +172 -215
  45. package/dist-esm/Chart/api/color.js +21 -21
  46. package/dist-esm/Chart/api/data.js +172 -173
  47. package/dist-esm/Chart/api/export.js +242 -262
  48. package/dist-esm/Chart/api/flow.js +198 -254
  49. package/dist-esm/Chart/api/focus.js +136 -143
  50. package/dist-esm/Chart/api/grid.js +191 -190
  51. package/dist-esm/Chart/api/group.js +31 -34
  52. package/dist-esm/Chart/api/legend.js +54 -63
  53. package/dist-esm/Chart/api/load.js +237 -257
  54. package/dist-esm/Chart/api/regions.js +148 -168
  55. package/dist-esm/Chart/api/selection.js +181 -139
  56. package/dist-esm/Chart/api/show.js +133 -147
  57. package/dist-esm/Chart/api/stubs.js +43 -42
  58. package/dist-esm/Chart/api/subchart.js +155 -172
  59. package/dist-esm/Chart/api/tooltip.js +132 -177
  60. package/dist-esm/Chart/api/x.js +67 -71
  61. package/dist-esm/Chart/api/zoom.js +183 -220
  62. package/dist-esm/ChartInternal/Axis/Axis.js +1059 -1266
  63. package/dist-esm/ChartInternal/Axis/AxisRenderer.js +408 -540
  64. package/dist-esm/ChartInternal/Axis/AxisRendererHelper.js +113 -149
  65. package/dist-esm/ChartInternal/ChartInternal.js +573 -749
  66. package/dist-esm/ChartInternal/data/convert.helper.js +133 -159
  67. package/dist-esm/ChartInternal/data/convert.js +200 -229
  68. package/dist-esm/ChartInternal/data/data.js +967 -1153
  69. package/dist-esm/ChartInternal/data/load.js +145 -197
  70. package/dist-esm/ChartInternal/interactions/drag.js +86 -122
  71. package/dist-esm/ChartInternal/interactions/eventrect.js +455 -621
  72. package/dist-esm/ChartInternal/interactions/flow.js +151 -215
  73. package/dist-esm/ChartInternal/interactions/interaction.js +214 -252
  74. package/dist-esm/ChartInternal/interactions/subchart.js +425 -300
  75. package/dist-esm/ChartInternal/interactions/zoom.js +321 -440
  76. package/dist-esm/ChartInternal/internals/category.js +18 -18
  77. package/dist-esm/ChartInternal/internals/class.js +89 -99
  78. package/dist-esm/ChartInternal/internals/clip.js +88 -119
  79. package/dist-esm/ChartInternal/internals/color.js +233 -288
  80. package/dist-esm/ChartInternal/internals/domain.js +452 -588
  81. package/dist-esm/ChartInternal/internals/format.js +64 -77
  82. package/dist-esm/ChartInternal/internals/grid.js +333 -457
  83. package/dist-esm/ChartInternal/internals/legend.js +675 -927
  84. package/dist-esm/ChartInternal/internals/redraw.js +200 -289
  85. package/dist-esm/ChartInternal/internals/region.js +106 -159
  86. package/dist-esm/ChartInternal/internals/scale.js +186 -215
  87. package/dist-esm/ChartInternal/internals/selection.js +132 -159
  88. package/dist-esm/ChartInternal/internals/size.axis.js +92 -139
  89. package/dist-esm/ChartInternal/internals/size.js +286 -394
  90. package/dist-esm/ChartInternal/internals/style.js +39 -41
  91. package/dist-esm/ChartInternal/internals/subchart.util.js +49 -0
  92. package/dist-esm/ChartInternal/internals/text.arc.js +155 -219
  93. package/dist-esm/ChartInternal/internals/text.js +368 -528
  94. package/dist-esm/ChartInternal/internals/text.util.js +179 -239
  95. package/dist-esm/ChartInternal/internals/title.js +96 -121
  96. package/dist-esm/ChartInternal/internals/tooltip.js +450 -586
  97. package/dist-esm/ChartInternal/internals/transform.js +79 -97
  98. package/dist-esm/ChartInternal/internals/type.js +285 -236
  99. package/dist-esm/ChartInternal/shape/arc.js +825 -1112
  100. package/dist-esm/ChartInternal/shape/area.js +73 -94
  101. package/dist-esm/ChartInternal/shape/bar.js +227 -288
  102. package/dist-esm/ChartInternal/shape/bubble.js +9 -8
  103. package/dist-esm/ChartInternal/shape/candlestick.js +110 -138
  104. package/dist-esm/ChartInternal/shape/core/barRadius.js +197 -133
  105. package/dist-esm/ChartInternal/shape/core/bubble.js +64 -73
  106. package/dist-esm/ChartInternal/shape/core/candlestick.js +93 -86
  107. package/dist-esm/ChartInternal/shape/core/dataRegion.js +68 -75
  108. package/dist-esm/ChartInternal/shape/core/geometry.js +112 -112
  109. package/dist-esm/ChartInternal/shape/core/path.js +142 -115
  110. package/dist-esm/ChartInternal/shape/core/point.js +105 -125
  111. package/dist-esm/ChartInternal/shape/core/treemap.js +83 -88
  112. package/dist-esm/ChartInternal/shape/funnel.js +310 -338
  113. package/dist-esm/ChartInternal/shape/gauge.js +71 -103
  114. package/dist-esm/ChartInternal/shape/line.js +208 -278
  115. package/dist-esm/ChartInternal/shape/point.js +310 -425
  116. package/dist-esm/ChartInternal/shape/polar.js +84 -109
  117. package/dist-esm/ChartInternal/shape/radar.js +228 -318
  118. package/dist-esm/ChartInternal/shape/shape.js +782 -843
  119. package/dist-esm/ChartInternal/shape/treemap.js +152 -190
  120. package/dist-esm/canvas/CanvasAxisRenderer.js +1180 -1328
  121. package/dist-esm/canvas/CanvasEngine.js +148 -166
  122. package/dist-esm/canvas/CanvasPainter.js +395 -411
  123. package/dist-esm/canvas/CanvasRenderer.js +1584 -1834
  124. package/dist-esm/canvas/CanvasTheme.js +899 -802
  125. package/dist-esm/canvas/HitDetector.js +394 -463
  126. package/dist-esm/canvas/axisTicks.js +672 -786
  127. package/dist-esm/canvas/classes.js +19 -17
  128. package/dist-esm/canvas/color.js +40 -59
  129. package/dist-esm/canvas/geometry.js +38 -38
  130. package/dist-esm/canvas/labels.js +318 -371
  131. package/dist-esm/canvas/pointPattern.js +578 -580
  132. package/dist-esm/canvas/util.js +242 -262
  133. package/dist-esm/config/Options/Options.js +29 -32
  134. package/dist-esm/config/Options/axis/axis.js +101 -101
  135. package/dist-esm/config/Options/axis/x.js +759 -755
  136. package/dist-esm/config/Options/axis/y.js +525 -522
  137. package/dist-esm/config/Options/axis/y2.js +501 -485
  138. package/dist-esm/config/Options/common/boost.js +93 -32
  139. package/dist-esm/config/Options/common/color.js +88 -87
  140. package/dist-esm/config/Options/common/grid.js +74 -73
  141. package/dist-esm/config/Options/common/legend.js +180 -179
  142. package/dist-esm/config/Options/common/main.js +474 -473
  143. package/dist-esm/config/Options/common/point.js +160 -159
  144. package/dist-esm/config/Options/common/title.js +47 -46
  145. package/dist-esm/config/Options/common/tooltip.js +253 -252
  146. package/dist-esm/config/Options/data/axis.js +173 -172
  147. package/dist-esm/config/Options/data/data.js +958 -957
  148. package/dist-esm/config/Options/data/selection.js +131 -130
  149. package/dist-esm/config/Options/interaction/interaction.js +53 -52
  150. package/dist-esm/config/Options/interaction/subchart.js +164 -73
  151. package/dist-esm/config/Options/interaction/zoom.js +86 -85
  152. package/dist-esm/config/Options/shape/arc.js +150 -149
  153. package/dist-esm/config/Options/shape/area.js +69 -68
  154. package/dist-esm/config/Options/shape/bar.js +147 -146
  155. package/dist-esm/config/Options/shape/bubble.js +35 -34
  156. package/dist-esm/config/Options/shape/candlestick.js +61 -60
  157. package/dist-esm/config/Options/shape/donut.js +181 -180
  158. package/dist-esm/config/Options/shape/funnel.js +49 -48
  159. package/dist-esm/config/Options/shape/gauge.js +237 -236
  160. package/dist-esm/config/Options/shape/line.js +58 -57
  161. package/dist-esm/config/Options/shape/pie.js +185 -184
  162. package/dist-esm/config/Options/shape/polar.js +167 -166
  163. package/dist-esm/config/Options/shape/radar.js +76 -75
  164. package/dist-esm/config/Options/shape/scatter.js +36 -36
  165. package/dist-esm/config/Options/shape/spline.js +46 -46
  166. package/dist-esm/config/Options/shape/treemap.js +80 -79
  167. package/dist-esm/config/Store/Element.js +64 -62
  168. package/dist-esm/config/Store/State.js +189 -200
  169. package/dist-esm/config/Store/Store.js +25 -26
  170. package/dist-esm/config/classes.js +157 -155
  171. package/dist-esm/config/config.js +26 -35
  172. package/dist-esm/config/const.js +120 -128
  173. package/dist-esm/config/resolver/axis.core.js +25 -25
  174. package/dist-esm/config/resolver/axis.js +26 -27
  175. package/dist-esm/config/resolver/canvas.js +2071 -2472
  176. package/dist-esm/config/resolver/canvasShape.js +201 -177
  177. package/dist-esm/config/resolver/category.js +26 -27
  178. package/dist-esm/config/resolver/export.js +24 -26
  179. package/dist-esm/config/resolver/flow.js +29 -31
  180. package/dist-esm/config/resolver/grid.js +34 -35
  181. package/dist-esm/config/resolver/interaction/selection.js +17 -17
  182. package/dist-esm/config/resolver/interaction/subchart.js +17 -17
  183. package/dist-esm/config/resolver/interaction/zoom.js +17 -17
  184. package/dist-esm/config/resolver/regions.js +30 -31
  185. package/dist-esm/config/resolver/shape/arc.helpers.js +19 -19
  186. package/dist-esm/config/resolver/shape/area.js +17 -17
  187. package/dist-esm/config/resolver/shape/axis.helpers.js +28 -25
  188. package/dist-esm/config/resolver/shape/bar.js +13 -13
  189. package/dist-esm/config/resolver/shape/bubble.js +18 -14
  190. package/dist-esm/config/resolver/shape/candlestick.js +13 -13
  191. package/dist-esm/config/resolver/shape/donut.js +11 -11
  192. package/dist-esm/config/resolver/shape/funnel.js +11 -11
  193. package/dist-esm/config/resolver/shape/gauge.js +12 -12
  194. package/dist-esm/config/resolver/shape/line.js +10 -10
  195. package/dist-esm/config/resolver/shape/pie.js +11 -11
  196. package/dist-esm/config/resolver/shape/polar.js +12 -12
  197. package/dist-esm/config/resolver/shape/radar.js +22 -14
  198. package/dist-esm/config/resolver/shape/scatter.js +13 -13
  199. package/dist-esm/config/resolver/shape/treemap.js +11 -11
  200. package/dist-esm/core.js +208 -211
  201. package/dist-esm/index.canvas.js +14 -13
  202. package/dist-esm/index.esm.js +25 -24
  203. package/dist-esm/module/Cache.js +117 -129
  204. package/dist-esm/module/browser.js +30 -35
  205. package/dist-esm/module/dsv.js +107 -127
  206. package/dist-esm/module/error.js +45 -52
  207. package/dist-esm/module/generator.js +75 -83
  208. package/dist-esm/module/sanitize.js +302 -399
  209. package/dist-esm/module/util/brush.js +27 -38
  210. package/dist-esm/module/util/dom.js +288 -348
  211. package/dist-esm/module/util/object.js +277 -341
  212. package/dist-esm/module/util/type-checks.js +21 -25
  213. package/dist-esm/module/worker.js +312 -130
  214. package/dist-esm/plugin/billboardjs-plugin-bubblecompare.js +185 -198
  215. package/dist-esm/plugin/billboardjs-plugin-sparkline.js +442 -450
  216. package/dist-esm/plugin/billboardjs-plugin-stanford.js +813 -950
  217. package/dist-esm/plugin/billboardjs-plugin-tableview.js +708 -788
  218. package/dist-esm/plugin/billboardjs-plugin-textoverlap.js +344 -301
  219. package/dist-esm/react/index.js +157 -0
  220. package/package.json +28 -8
  221. package/src/Chart/api/selection.ts +130 -5
  222. package/src/ChartInternal/Axis/Axis.ts +164 -65
  223. package/src/ChartInternal/Axis/AxisRenderer.ts +41 -8
  224. package/src/ChartInternal/Axis/AxisRendererHelper.ts +1 -1
  225. package/src/ChartInternal/ChartInternal.ts +1 -1
  226. package/src/ChartInternal/data/convert.ts +54 -4
  227. package/src/ChartInternal/data/data.ts +4 -1
  228. package/src/ChartInternal/interactions/eventrect.ts +8 -2
  229. package/src/ChartInternal/interactions/subchart.ts +437 -66
  230. package/src/ChartInternal/internals/color.ts +2 -2
  231. package/src/ChartInternal/internals/domain.ts +15 -3
  232. package/src/ChartInternal/internals/grid.ts +21 -1
  233. package/src/ChartInternal/internals/scale.ts +9 -2
  234. package/src/ChartInternal/internals/selection.ts +1 -1
  235. package/src/ChartInternal/internals/subchart.util.ts +55 -0
  236. package/src/ChartInternal/internals/text.arc.ts +3 -1
  237. package/src/ChartInternal/internals/text.ts +18 -5
  238. package/src/ChartInternal/internals/transform.ts +8 -2
  239. package/src/ChartInternal/internals/type.ts +105 -1
  240. package/src/ChartInternal/shape/IShape.ts +6 -3
  241. package/src/ChartInternal/shape/bar.ts +62 -31
  242. package/src/ChartInternal/shape/core/barRadius.ts +129 -0
  243. package/src/ChartInternal/shape/core/candlestick.ts +1 -1
  244. package/src/ChartInternal/shape/core/path.ts +76 -9
  245. package/src/ChartInternal/shape/funnel.ts +2 -3
  246. package/src/ChartInternal/shape/point.ts +2 -2
  247. package/src/ChartInternal/shape/shape.ts +149 -17
  248. package/src/Plugin/stanford/index.ts +0 -4
  249. package/src/Plugin/tableview/index.ts +85 -3
  250. package/src/Plugin/textoverlap/index.ts +9 -15
  251. package/src/canvas/CanvasAxisRenderer.ts +184 -36
  252. package/src/canvas/CanvasRenderer.ts +247 -160
  253. package/src/canvas/CanvasTheme.ts +212 -0
  254. package/src/canvas/axisTicks.ts +122 -40
  255. package/src/config/Options/axis/y2.ts +13 -0
  256. package/src/config/Options/common/boost.ts +64 -4
  257. package/src/config/Options/common/color.ts +2 -2
  258. package/src/config/Options/interaction/subchart.ts +98 -1
  259. package/src/config/Options/shape/gauge.ts +1 -1
  260. package/src/config/Options/shape/treemap.ts +2 -2
  261. package/src/config/Store/Element.ts +3 -1
  262. package/src/config/Store/State.ts +1 -0
  263. package/src/config/classes.ts +1 -0
  264. package/src/config/resolver/canvas.ts +92 -10
  265. package/src/module/util/type-checks.ts +3 -1
  266. package/src/module/voronoi.ts +119 -0
  267. package/src/module/worker.entry.ts +61 -0
  268. package/src/module/worker.ts +346 -63
  269. package/src/react/index.ts +193 -0
  270. package/types/options.d.ts +206 -3
  271. package/types/react/index.d.ts +27 -0
@@ -5,2659 +5,2258 @@
5
5
  * billboard.js, JavaScript chart library
6
6
  * https://naver.github.io/billboard.js/
7
7
  *
8
- * @version 4.0.3
8
+ * @version 4.1.0-next.2
9
9
  */
10
- import { select } from 'd3-selection';
11
- import CanvasAxisRenderer from '../../canvas/CanvasAxisRenderer.js';
12
- import CanvasEngine from '../../canvas/CanvasEngine.js';
13
- import CanvasRenderer from '../../canvas/CanvasRenderer.js';
14
- import CanvasTheme from '../../canvas/CanvasTheme.js';
15
- import { $CANVAS } from '../../canvas/classes.js';
16
- import HitDetector from '../../canvas/HitDetector.js';
17
- import { hasCanvasDrawableValue, isCanvasTargetSupported, isCanvasPointType, isCanvasBarType, isCanvasCandlestickType, isCanvasTreemapType, isCanvasScatterType, isCanvasBubbleType } from '../../canvas/util.js';
18
- import ChartInternal from '../../ChartInternal/ChartInternal.js';
19
- import { getRenderDataPoint } from '../../ChartInternal/shape/core/geometry.js';
20
- import { $LEGEND, $FOCUS } from '../classes.js';
21
- import { window as win } from '../../module/browser.js';
22
- import { KEY } from '../../module/Cache.js';
23
- import { extend, callFn, tplProcess, parseDate } from '../../module/util/object.js';
24
- import { getBoundingRect } from '../../module/util/dom.js';
25
- import { isFunction, isBoolean } from '../../module/util/type-checks.js';
26
- import { sanitize } from '../../module/sanitize.js';
27
-
10
+ import { window as win } from "../../module/browser.js";
11
+ import { isBoolean, isFunction } from "../../module/util/type-checks.js";
12
+ import { sanitize } from "../../module/sanitize.js";
13
+ import { callFn, extend, parseDate, tplProcess } from "../../module/util/object.js";
14
+ import { getBoundingRect } from "../../module/util/dom.js";
15
+ import { $FOCUS, $LEGEND } from "../classes.js";
16
+ import { KEY } from "../../module/Cache.js";
17
+ import ChartInternal from "../../ChartInternal/ChartInternal.js";
18
+ import { getRenderDataPoint } from "../../ChartInternal/shape/core/geometry.js";
19
+ import { getMainCoordFromSubchartCoord } from "../../ChartInternal/internals/subchart.util.js";
20
+ import { hasCanvasDrawableValue, isCanvasBarType, isCanvasBubbleType, isCanvasCandlestickType, isCanvasPointType, isCanvasScatterType, isCanvasTargetSupported, isCanvasTreemapType } from "../../canvas/util.js";
21
+ import CanvasAxisRenderer from "../../canvas/CanvasAxisRenderer.js";
22
+ import { $CANVAS } from "../../canvas/classes.js";
23
+ import CanvasEngine from "../../canvas/CanvasEngine.js";
24
+ import CanvasRenderer from "../../canvas/CanvasRenderer.js";
25
+ import CanvasTheme from "../../canvas/CanvasTheme.js";
26
+ import HitDetector from "../../canvas/HitDetector.js";
27
+ import { select } from "d3-selection";
28
+ //#region src/config/resolver/canvas.ts
28
29
  /**
29
- * Copyright (c) 2017 ~ present NAVER Corp.
30
- * billboard.js project is licensed under the MIT license
31
- */
30
+ * Copyright (c) 2017 ~ present NAVER Corp.
31
+ * billboard.js project is licensed under the MIT license
32
+ */
32
33
  const CANVAS_SELECTABLE_TYPE_FILTERS = [
33
- isCanvasPointType,
34
- isCanvasBarType,
35
- isCanvasCandlestickType,
36
- isCanvasTreemapType
34
+ isCanvasPointType,
35
+ isCanvasBarType,
36
+ isCanvasCandlestickType,
37
+ isCanvasTreemapType
37
38
  ];
38
39
  const CANVAS_LEGEND_TOUCH_TAP_THRESHOLD = 10;
39
40
  const CANVAS_LEGEND_TOUCH_CLICK_TIMEOUT = 750;
40
41
  const CANVAS_SUBCHART_HANDLE_SIZE = 6;
41
42
  const CANVAS_SUBCHART_CLICK_TOLERANCE = 2;
42
- const CANVAS_FLOW_ANIMATION_MAX_VALUES = 100000;
43
+ const CANVAS_FLOW_ANIMATION_MAX_VALUES = 1e5;
43
44
  const CANVAS_HTML_ATTR_ESCAPE = {
44
- "&": "&",
45
- "<": "&lt;",
46
- ">": "&gt;",
47
- "\"": "&quot;",
48
- "'": "&#39;"
45
+ "&": "&amp;",
46
+ "<": "&lt;",
47
+ ">": "&gt;",
48
+ "\"": "&quot;",
49
+ "'": "&#39;"
49
50
  };
50
- const canvasSelectionDragRows = new WeakMap();
51
+ const canvasSelectionDragRows = /* @__PURE__ */ new WeakMap();
51
52
  /**
52
- * Emit canvas v1 unsupported option warning.
53
- * @param {string} message Warning message
54
- * @private
55
- */
53
+ * Emit canvas v1 unsupported option warning.
54
+ * @param {string} message Warning message
55
+ * @private
56
+ */
56
57
  function warn(message) {
57
- win.console?.warn?.(`[billboard.js] ${message}`);
58
+ win.console?.warn?.(`[billboard.js] ${message}`);
58
59
  }
59
60
  /**
60
- * Get formatted legend text.
61
- * @param {object} $$ ChartInternal instance
62
- * @param {string} id Data id
63
- * @returns {string} Legend text
64
- * @private
65
- */
61
+ * Get formatted legend text.
62
+ * @param {object} $$ ChartInternal instance
63
+ * @param {string} id Data id
64
+ * @returns {string} Legend text
65
+ * @private
66
+ */
66
67
  function getLegendText($$, id) {
67
- const { config } = $$;
68
- const text = config.data_names[id] ?? id;
69
- return isFunction(config.legend_format) ?
70
- config.legend_format(text, id !== text ? id : undefined) :
71
- text;
68
+ const { config } = $$;
69
+ const text = config.data_names[id] ?? id;
70
+ return isFunction(config.legend_format) ? config.legend_format(text, id !== text ? id : void 0) : text;
72
71
  }
73
72
  /**
74
- * Escape a value for safe HTML attribute interpolation.
75
- * @param {string} value Attribute value
76
- * @returns {string} Escaped value
77
- * @private
78
- */
73
+ * Escape a value for safe HTML attribute interpolation.
74
+ * @param {string} value Attribute value
75
+ * @returns {string} Escaped value
76
+ * @private
77
+ */
79
78
  function escapeHtmlAttr(value) {
80
- return `${value}`.replace(/[&<>"']/g, char => CANVAS_HTML_ATTR_ESCAPE[char]);
79
+ return `${value}`.replace(/[&<>"']/g, (char) => CANVAS_HTML_ATTR_ESCAPE[char]);
81
80
  }
82
81
  /**
83
- * Get the point pattern assigned to a legend item.
84
- * @param {object} $$ ChartInternal instance
85
- * @param {string} id Data id
86
- * @returns {string} Point pattern
87
- * @private
88
- */
82
+ * Get the point pattern assigned to a legend item.
83
+ * @param {object} $$ ChartInternal instance
84
+ * @param {string} id Data id
85
+ * @returns {string} Point pattern
86
+ * @private
87
+ */
89
88
  function getCanvasLegendPointPattern($$, id) {
90
- const { config } = $$;
91
- const targetIds = $$.mapToIds?.($$.data.targets) || [];
92
- const pattern = $$.getValidPointPattern?.() || (Array.isArray(config.point_pattern) && config.point_pattern.length ?
93
- config.point_pattern :
94
- [config.point_type]);
95
- const index = Math.max(0, targetIds.indexOf(id));
96
- return pattern[index % pattern.length] || "circle";
89
+ const { config } = $$;
90
+ const targetIds = $$.mapToIds?.($$.data.targets) || [];
91
+ const pattern = $$.getValidPointPattern?.() || (Array.isArray(config.point_pattern) && config.point_pattern.length ? config.point_pattern : [config.point_type]);
92
+ return pattern[Math.max(0, targetIds.indexOf(id)) % pattern.length] || "circle";
97
93
  }
98
94
  /**
99
- * Build inline SVG markup for a canvas HTML legend point tile.
100
- * @param {object} $$ ChartInternal instance
101
- * @param {string} id Data id
102
- * @returns {string} SVG markup
103
- * @private
104
- */
95
+ * Build inline SVG markup for a canvas HTML legend point tile.
96
+ * @param {object} $$ ChartInternal instance
97
+ * @param {string} id Data id
98
+ * @returns {string} SVG markup
99
+ * @private
100
+ */
105
101
  function getCanvasLegendPointIcon($$, id) {
106
- const color = escapeHtmlAttr($$.color(id));
107
- const pattern = getCanvasLegendPointPattern($$, id);
108
- const svgAttrs = "viewBox=\"0 0 8 8\" aria-hidden=\"true\" focusable=\"false\" " +
109
- "style=\"display:block;width:100%;height:100%;overflow:visible;pointer-events:none\"";
110
- const paintAttrs = `fill="${color}" stroke="${color}"`;
111
- if (/^rect(angle)?$/i.test(pattern)) {
112
- return `<svg ${svgAttrs}><rect x="1" y="1" width="6" height="6" ${paintAttrs}></rect></svg>`;
113
- }
114
- if (/^circle$/i.test(pattern)) {
115
- return `<svg ${svgAttrs}><circle cx="4" cy="4" r="3" ${paintAttrs}></circle></svg>`;
116
- }
117
- return `<svg ${svgAttrs}><g ${paintAttrs}>${sanitize(pattern)}</g></svg>`;
102
+ const color = escapeHtmlAttr($$.color(id));
103
+ const pattern = getCanvasLegendPointPattern($$, id);
104
+ const svgAttrs = "viewBox=\"0 0 8 8\" aria-hidden=\"true\" focusable=\"false\" style=\"display:block;width:100%;height:100%;overflow:visible;pointer-events:none\"";
105
+ const paintAttrs = `fill="${color}" stroke="${color}"`;
106
+ if (/^rect(angle)?$/i.test(pattern)) return `<svg ${svgAttrs}><rect x="1" y="1" width="6" height="6" ${paintAttrs}></rect></svg>`;
107
+ if (!pattern || /^circle$/i.test(pattern)) return `<svg ${svgAttrs}><circle cx="4" cy="4" r="3" ${paintAttrs}></circle></svg>`;
108
+ return `<svg ${svgAttrs}><g ${paintAttrs}>${sanitize(pattern)}</g></svg>`;
118
109
  }
119
110
  /**
120
- * Update legend item lookup cache for canvas HTML legends.
121
- * @param {object} $$ ChartInternal instance
122
- * @param {object} item Legend item selection
123
- * @private
124
- */
111
+ * Update legend item lookup cache for canvas HTML legends.
112
+ * @param {object} $$ ChartInternal instance
113
+ * @param {object} item Legend item selection
114
+ * @private
115
+ */
125
116
  function updateCanvasLegendItemMap($$, item) {
126
- const itemMap = new Map();
127
- item.each(function (id) {
128
- itemMap.set(id, this);
129
- });
130
- $$.cache.add(KEY.legendItemMap, itemMap);
117
+ const itemMap = /* @__PURE__ */ new Map();
118
+ item.each(function(id) {
119
+ itemMap.set(id, this);
120
+ });
121
+ $$.cache.add(KEY.legendItemMap, itemMap);
131
122
  }
132
123
  /**
133
- * Apply shared canvas HTML legend classes and state.
134
- * @param {object} $$ ChartInternal instance
135
- * @param {object} item Legend item selection
136
- * @private
137
- */
124
+ * Apply shared canvas HTML legend classes and state.
125
+ * @param {object} $$ ChartInternal instance
126
+ * @param {object} item Legend item selection
127
+ * @private
128
+ */
138
129
  function setCanvasHtmlLegendItem($$, item) {
139
- const { config } = $$;
140
- item
141
- .attr("class", function (id) {
142
- const current = select(this).attr("class") || "";
143
- const next = `${current} ${$$.generateClass($LEGEND.legendItem, id)}`;
144
- return Array.from(new Set(next.trim().split(/\s+/).filter(Boolean))).join(" ");
145
- })
146
- .style("visibility", id => ($$.isLegendToShow(id) ? null : "hidden"))
147
- .classed($LEGEND.legendItemHidden, id => !$$.isTargetToShow(id))
148
- .classed($CANVAS.legendItemInteractive, !!config.interaction_enabled);
149
- updateCanvasLegendItemMap($$, item);
130
+ const { config } = $$;
131
+ item.attr("class", function(id) {
132
+ const next = `${select(this).attr("class") || ""} ${$$.generateClass($LEGEND.legendItem, id)}`;
133
+ return Array.from(new Set(next.trim().split(/\s+/).filter(Boolean))).join(" ");
134
+ }).style("visibility", (id) => $$.isLegendToShow(id) ? null : "hidden").classed($LEGEND.legendItemHidden, (id) => !$$.isTargetToShow(id)).classed($CANVAS.legendItemInteractive, !!config.interaction_enabled);
135
+ updateCanvasLegendItemMap($$, item);
150
136
  }
151
137
  /**
152
- * Apply SVG-compatible legend focus styling to canvas HTML legend items.
153
- * @param {object} $$ ChartInternal instance
154
- * @param {string} id Focused data id
155
- * @private
156
- */
138
+ * Apply SVG-compatible legend focus styling to canvas HTML legend items.
139
+ * @param {object} $$ ChartInternal instance
140
+ * @param {string} id Focused data id
141
+ * @private
142
+ */
157
143
  function setCanvasHtmlLegendFocus($$, id) {
158
- const { legend } = $$.$el;
159
- const targetIds = $$.mapToTargetIds?.([id]) || [id];
160
- legend?.selectAll(`.${$LEGEND.legendItem}`)
161
- .classed($FOCUS.legendItemFocused, (d) => targetIds.indexOf(d) >= 0)
162
- .style("opacity", function (d) {
163
- return targetIds.indexOf(d) >= 0 ?
164
- null :
165
- $$.opacityForUnfocusedLegend.call($$, select(this));
166
- });
144
+ const { legend } = $$.$el;
145
+ const targetIds = $$.mapToTargetIds?.([id]) || [id];
146
+ legend?.selectAll(`.${$LEGEND.legendItem}`).classed($FOCUS.legendItemFocused, (d) => targetIds.indexOf(d) >= 0).style("opacity", function(d) {
147
+ return targetIds.indexOf(d) >= 0 ? null : $$.opacityForUnfocusedLegend.call($$, select(this));
148
+ });
167
149
  }
168
150
  /**
169
- * Revert canvas HTML legend focus styling.
170
- * @param {object} $$ ChartInternal instance
171
- * @private
172
- */
151
+ * Revert canvas HTML legend focus styling.
152
+ * @param {object} $$ ChartInternal instance
153
+ * @private
154
+ */
173
155
  function revertCanvasHtmlLegendFocus($$) {
174
- const { legend } = $$.$el;
175
- legend?.selectAll(`.${$LEGEND.legendItem}`)
176
- .classed($FOCUS.legendItemFocused, false)
177
- .style("opacity", null);
156
+ const { legend } = $$.$el;
157
+ legend?.selectAll(`.${$LEGEND.legendItem}`).classed($FOCUS.legendItemFocused, false).style("opacity", null);
178
158
  }
179
159
  /**
180
- * Apply SVG-compatible target focus state for canvas redraw.
181
- * @param {object} $$ ChartInternal instance
182
- * @param {string} id Focused data id
183
- * @private
184
- */
160
+ * Apply SVG-compatible target focus state for canvas redraw.
161
+ * @param {object} $$ ChartInternal instance
162
+ * @param {string} id Focused data id
163
+ * @private
164
+ */
185
165
  function setCanvasLegendTargetFocus($$, id) {
186
- const { state } = $$;
187
- const targetIds = $$.mapToTargetIds?.([id]) || [id];
188
- const focusedIds = targetIds.filter($$.isTargetToShow, $$);
189
- const focusedSet = new Set(focusedIds);
190
- const defocusedIds = ($$.mapToTargetIds?.() || [])
191
- .filter(targetId => !focusedSet.has(targetId) && $$.isTargetToShow(targetId));
192
- state.focusedTargetIds = focusedSet;
193
- state.defocusedTargetIds = new Set(defocusedIds);
194
- $$.renderCanvasFrame?.(undefined, null, false);
166
+ const { state } = $$;
167
+ const focusedIds = ($$.mapToTargetIds?.([id]) || [id]).filter($$.isTargetToShow, $$);
168
+ const focusedSet = new Set(focusedIds);
169
+ const defocusedIds = ($$.mapToTargetIds?.() || []).filter((targetId) => !focusedSet.has(targetId) && $$.isTargetToShow(targetId));
170
+ state.focusedTargetIds = focusedSet;
171
+ state.defocusedTargetIds = new Set(defocusedIds);
172
+ $$.renderCanvasFrame?.(void 0, null, false);
195
173
  }
196
174
  /**
197
- * Revert canvas target focus state.
198
- * @param {object} $$ ChartInternal instance
199
- * @private
200
- */
175
+ * Revert canvas target focus state.
176
+ * @param {object} $$ ChartInternal instance
177
+ * @private
178
+ */
201
179
  function revertCanvasLegendTargetFocus($$) {
202
- const { state } = $$;
203
- const changed = !!state.focusedTargetIds?.size || !!state.defocusedTargetIds?.size;
204
- state.focusedTargetIds = new Set();
205
- state.defocusedTargetIds = new Set();
206
- changed && $$.renderCanvasFrame?.(undefined, null, false);
180
+ const { state } = $$;
181
+ const changed = !!state.focusedTargetIds?.size || !!state.defocusedTargetIds?.size;
182
+ state.focusedTargetIds = /* @__PURE__ */ new Set();
183
+ state.defocusedTargetIds = /* @__PURE__ */ new Set();
184
+ changed && $$.renderCanvasFrame?.(void 0, null, false);
207
185
  }
208
186
  /**
209
- * Get touch point from a canvas legend touch event.
210
- * @param {TouchEvent} event Touch event
211
- * @returns {Touch | undefined} Touch point
212
- * @private
213
- */
187
+ * Get touch point from a canvas legend touch event.
188
+ * @param {TouchEvent} event Touch event
189
+ * @returns {Touch | undefined} Touch point
190
+ * @private
191
+ */
214
192
  function getCanvasLegendTouchPoint(event) {
215
- return event.changedTouches?.[0] || event.touches?.[0];
193
+ return event.changedTouches?.[0] || event.touches?.[0];
216
194
  }
217
195
  /**
218
- * Store the touch start position for canvas legend tap detection.
219
- * @param {object} $$ ChartInternal instance
220
- * @param {string} id Legend data id
221
- * @param {TouchEvent} event Touch event
222
- * @private
223
- */
196
+ * Store the touch start position for canvas legend tap detection.
197
+ * @param {object} $$ ChartInternal instance
198
+ * @param {string} id Legend data id
199
+ * @param {TouchEvent} event Touch event
200
+ * @private
201
+ */
224
202
  function setCanvasLegendTouchStart($$, id, event) {
225
- const touch = getCanvasLegendTouchPoint(event);
226
- $$.state.canvasLegendTouch = touch ?
227
- {
228
- id,
229
- x: touch.clientX,
230
- y: touch.clientY,
231
- moved: false
232
- } :
233
- null;
203
+ const touch = getCanvasLegendTouchPoint(event);
204
+ $$.state.canvasLegendTouch = touch ? {
205
+ id,
206
+ x: touch.clientX,
207
+ y: touch.clientY,
208
+ moved: false
209
+ } : null;
234
210
  }
235
211
  /**
236
- * Update whether the current canvas legend touch moved beyond tap tolerance.
237
- * @param {object} $$ ChartInternal instance
238
- * @param {TouchEvent} event Touch event
239
- * @private
240
- */
212
+ * Update whether the current canvas legend touch moved beyond tap tolerance.
213
+ * @param {object} $$ ChartInternal instance
214
+ * @param {TouchEvent} event Touch event
215
+ * @private
216
+ */
241
217
  function updateCanvasLegendTouchMove($$, event) {
242
- const start = $$.state.canvasLegendTouch;
243
- const touch = start && getCanvasLegendTouchPoint(event);
244
- if (touch) {
245
- start.moved = start.moved ||
246
- Math.abs(touch.clientX - start.x) > CANVAS_LEGEND_TOUCH_TAP_THRESHOLD ||
247
- Math.abs(touch.clientY - start.y) > CANVAS_LEGEND_TOUCH_TAP_THRESHOLD;
248
- }
218
+ const start = $$.state.canvasLegendTouch;
219
+ const touch = start && getCanvasLegendTouchPoint(event);
220
+ if (touch) start.moved = start.moved || Math.abs(touch.clientX - start.x) > CANVAS_LEGEND_TOUCH_TAP_THRESHOLD || Math.abs(touch.clientY - start.y) > CANVAS_LEGEND_TOUCH_TAP_THRESHOLD;
249
221
  }
250
222
  /**
251
- * Determine whether a touch sequence is a canvas legend tap.
252
- * @param {object} $$ ChartInternal instance
253
- * @param {string} id Legend data id
254
- * @param {TouchEvent} event Touch event
255
- * @returns {boolean} Whether the touch sequence is a tap
256
- * @private
257
- */
223
+ * Determine whether a touch sequence is a canvas legend tap.
224
+ * @param {object} $$ ChartInternal instance
225
+ * @param {string} id Legend data id
226
+ * @param {TouchEvent} event Touch event
227
+ * @returns {boolean} Whether the touch sequence is a tap
228
+ * @private
229
+ */
258
230
  function isCanvasLegendTouchTap($$, id, event) {
259
- updateCanvasLegendTouchMove($$, event);
260
- const start = $$.state.canvasLegendTouch;
261
- $$.state.canvasLegendTouch = null;
262
- return !!start && start.id === id && !start.moved;
231
+ updateCanvasLegendTouchMove($$, event);
232
+ const start = $$.state.canvasLegendTouch;
233
+ $$.state.canvasLegendTouch = null;
234
+ return !!start && start.id === id && !start.moved;
263
235
  }
264
236
  /**
265
- * Mark a canvas legend touch tap so the following compatibility click can be skipped.
266
- * @param {object} $$ ChartInternal instance
267
- * @param {string} id Legend data id
268
- * @private
269
- */
237
+ * Mark a canvas legend touch tap so the following compatibility click can be skipped.
238
+ * @param {object} $$ ChartInternal instance
239
+ * @param {string} id Legend data id
240
+ * @private
241
+ */
270
242
  function markCanvasLegendTouchClick($$, id) {
271
- $$.state.canvasLegendLastTouchClickId = id;
272
- $$.state.canvasLegendLastTouchClickTime = Date.now();
243
+ $$.state.canvasLegendLastTouchClickId = id;
244
+ $$.state.canvasLegendLastTouchClickTime = Date.now();
273
245
  }
274
246
  /**
275
- * Check if a canvas legend click duplicates a recent touch tap.
276
- * @param {object} $$ ChartInternal instance
277
- * @param {string} id Legend data id
278
- * @returns {boolean} Whether the click is duplicate
279
- * @private
280
- */
247
+ * Check if a canvas legend click duplicates a recent touch tap.
248
+ * @param {object} $$ ChartInternal instance
249
+ * @param {string} id Legend data id
250
+ * @returns {boolean} Whether the click is duplicate
251
+ * @private
252
+ */
281
253
  function isDuplicateCanvasLegendTouchClick($$, id) {
282
- const { state } = $$;
283
- const duplicate = state.canvasLegendLastTouchClickId === id &&
284
- Date.now() - (state.canvasLegendLastTouchClickTime || 0) <
285
- CANVAS_LEGEND_TOUCH_CLICK_TIMEOUT;
286
- if (duplicate) {
287
- state.canvasLegendLastTouchClickId = null;
288
- state.canvasLegendLastTouchClickTime = 0;
289
- }
290
- return duplicate;
254
+ const { state } = $$;
255
+ const duplicate = state.canvasLegendLastTouchClickId === id && Date.now() - (state.canvasLegendLastTouchClickTime || 0) < CANVAS_LEGEND_TOUCH_CLICK_TIMEOUT;
256
+ if (duplicate) {
257
+ state.canvasLegendLastTouchClickId = null;
258
+ state.canvasLegendLastTouchClickTime = 0;
259
+ }
260
+ return duplicate;
291
261
  }
292
262
  /**
293
- * Bind canvas HTML legend interactions without invoking SVG focus paths.
294
- * @param {object} $$ ChartInternal instance
295
- * @param {object} item Legend item selection
296
- * @private
297
- */
263
+ * Bind canvas HTML legend interactions without invoking SVG focus paths.
264
+ * @param {object} $$ ChartInternal instance
265
+ * @param {object} item Legend item selection
266
+ * @private
267
+ */
298
268
  function bindCanvasHtmlLegendInteractions($$, item) {
299
- const { api, config, state } = $$;
300
- item.on("click dblclick mouseover mouseout touchstart touchmove touchend", null);
301
- if (!config.interaction_enabled) {
302
- return;
303
- }
304
- const interaction = config.legend_item_interaction;
305
- const eventType = typeof interaction === "object" && interaction?.dblclick ?
306
- "dblclick" :
307
- "click";
308
- const isTouch = state.inputType === "touch";
309
- const hasClickInteraction = interaction || isFunction(config.legend_item_onclick);
310
- const touchOption = isTouch ? getCanvasTouchListenerOption(config) : undefined;
311
- const handleCanvasLegendToggle = function (event, id) {
312
- if (!callFn(config.legend_item_onclick, api, id, !state.hiddenTargetIds.has(id))) {
313
- const selected = select(this);
314
- if (event.type === "dblclick" || event.altKey) {
315
- if (state.hiddenTargetIds.size &&
316
- !selected.classed($LEGEND.legendItemHidden)) {
317
- api.show();
318
- }
319
- else {
320
- api.hide();
321
- api.show(id);
322
- }
323
- }
324
- else {
325
- api.toggle(id);
326
- selected.classed($FOCUS.legendItemFocused, false);
327
- }
328
- revertCanvasLegendTargetFocus($$);
329
- }
330
- isTouch && $$.hideTooltip?.();
331
- };
332
- item.on(eventType, hasClickInteraction ?
333
- function (event, id) {
334
- if (isTouch && event.type === "click" &&
335
- isDuplicateCanvasLegendTouchClick($$, id)) {
336
- return;
337
- }
338
- handleCanvasLegendToggle.call(this, event, id);
339
- } :
340
- null);
341
- isTouch && eventType === "click" && hasClickInteraction && item
342
- .on("touchstart", function (event, id) {
343
- setCanvasLegendTouchStart($$, id, event);
344
- }, touchOption)
345
- .on("touchmove", event => {
346
- updateCanvasLegendTouchMove($$, event);
347
- }, touchOption)
348
- .on("touchend", function (event, id) {
349
- if (isCanvasLegendTouchTap($$, id, event)) {
350
- markCanvasLegendTouchClick($$, id);
351
- handleCanvasLegendToggle.call(this, event, id);
352
- }
353
- }, touchOption);
354
- !isTouch && item
355
- .on("mouseover", interaction || isFunction(config.legend_item_onover) ?
356
- function (event, id) {
357
- if (!callFn(config.legend_item_onover, api, id, !state.hiddenTargetIds.has(id))) {
358
- // hidden data's legend shouldn't react on hover (mirrors SVG focus guard)
359
- if (!state.transiting && $$.isTargetToShow(id)) {
360
- setCanvasHtmlLegendFocus($$, id);
361
- setCanvasLegendTargetFocus($$, id);
362
- }
363
- }
364
- } :
365
- null)
366
- .on("mouseout", interaction || isFunction(config.legend_item_onout) ?
367
- function (event, id) {
368
- if (!callFn(config.legend_item_onout, api, id, !state.hiddenTargetIds.has(id))) {
369
- revertCanvasHtmlLegendFocus($$);
370
- revertCanvasLegendTargetFocus($$);
371
- }
372
- } :
373
- null);
269
+ const { api, config, state } = $$;
270
+ item.on("click dblclick mouseover mouseout touchstart touchmove touchend", null);
271
+ if (!config.interaction_enabled) return;
272
+ const interaction = config.legend_item_interaction;
273
+ const eventType = typeof interaction === "object" && interaction?.dblclick ? "dblclick" : "click";
274
+ const isTouch = state.inputType === "touch";
275
+ const hasClickInteraction = interaction || isFunction(config.legend_item_onclick);
276
+ const touchOption = isTouch ? getCanvasTouchListenerOption(config) : void 0;
277
+ const handleCanvasLegendToggle = function(event, id) {
278
+ if (!callFn(config.legend_item_onclick, api, id, !state.hiddenTargetIds.has(id))) {
279
+ const selected = select(this);
280
+ if (event.type === "dblclick" || event.altKey) if (state.hiddenTargetIds.size && !selected.classed($LEGEND.legendItemHidden)) api.show();
281
+ else {
282
+ api.hide();
283
+ api.show(id);
284
+ }
285
+ else {
286
+ api.toggle(id);
287
+ selected.classed($FOCUS.legendItemFocused, false);
288
+ }
289
+ revertCanvasLegendTargetFocus($$);
290
+ }
291
+ isTouch && $$.hideTooltip?.();
292
+ };
293
+ item.on(eventType, hasClickInteraction ? function(event, id) {
294
+ if (isTouch && event.type === "click" && isDuplicateCanvasLegendTouchClick($$, id)) return;
295
+ handleCanvasLegendToggle.call(this, event, id);
296
+ } : null);
297
+ isTouch && eventType === "click" && hasClickInteraction && item.on("touchstart", function(event, id) {
298
+ setCanvasLegendTouchStart($$, id, event);
299
+ }, touchOption).on("touchmove", (event) => {
300
+ updateCanvasLegendTouchMove($$, event);
301
+ }, touchOption).on("touchend", function(event, id) {
302
+ if (isCanvasLegendTouchTap($$, id, event)) {
303
+ markCanvasLegendTouchClick($$, id);
304
+ handleCanvasLegendToggle.call(this, event, id);
305
+ }
306
+ }, touchOption);
307
+ !isTouch && item.on("mouseover", interaction || isFunction(config.legend_item_onover) ? function(event, id) {
308
+ if (!callFn(config.legend_item_onover, api, id, !state.hiddenTargetIds.has(id))) {
309
+ if (!state.transiting && $$.isTargetToShow(id)) {
310
+ setCanvasHtmlLegendFocus($$, id);
311
+ setCanvasLegendTargetFocus($$, id);
312
+ }
313
+ }
314
+ } : null).on("mouseout", interaction || isFunction(config.legend_item_onout) ? function(event, id) {
315
+ if (!callFn(config.legend_item_onout, api, id, !state.hiddenTargetIds.has(id))) {
316
+ revertCanvasHtmlLegendFocus($$);
317
+ revertCanvasLegendTargetFocus($$);
318
+ }
319
+ } : null);
374
320
  }
375
321
  /**
376
- * Measure a legend text with the same SVG structure used by the default renderer.
377
- * @param {object} $$ ChartInternal instance
378
- * @param {string} text Legend text
379
- * @returns {object|null} Text bounding rect
380
- * @private
381
- */
322
+ * Measure a legend text with the same SVG structure used by the default renderer.
323
+ * @param {object} $$ ChartInternal instance
324
+ * @param {string} text Legend text
325
+ * @returns {object|null} Text bounding rect
326
+ * @private
327
+ */
382
328
  function measureSvgLegendText($$, text) {
383
- const chart = $$.$el.chart?.node?.();
384
- const doc = chart?.ownerDocument;
385
- if (!chart || !doc) {
386
- return null;
387
- }
388
- const svg = doc.createElementNS("http://www.w3.org/2000/svg", "svg");
389
- const group = doc.createElementNS("http://www.w3.org/2000/svg", "g");
390
- const textElement = doc.createElementNS("http://www.w3.org/2000/svg", "text");
391
- svg.style.cssText = "position:absolute;visibility:hidden;left:-10000px;top:-10000px;";
392
- group.setAttribute("class", $LEGEND.legendItem);
393
- textElement.textContent = text;
394
- group.appendChild(textElement);
395
- svg.appendChild(group);
396
- chart.appendChild(svg);
397
- const rect = getBoundingRect(textElement);
398
- svg.remove();
399
- return rect;
329
+ const chart = $$.$el.chart?.node?.();
330
+ const doc = chart?.ownerDocument;
331
+ if (!chart || !doc) return null;
332
+ const svg = doc.createElementNS("http://www.w3.org/2000/svg", "svg");
333
+ const group = doc.createElementNS("http://www.w3.org/2000/svg", "g");
334
+ const textElement = doc.createElementNS("http://www.w3.org/2000/svg", "text");
335
+ svg.style.cssText = "position:absolute;visibility:hidden;left:-10000px;top:-10000px;";
336
+ group.setAttribute("class", $LEGEND.legendItem);
337
+ textElement.textContent = text;
338
+ group.appendChild(textElement);
339
+ svg.appendChild(group);
340
+ chart.appendChild(svg);
341
+ const rect = getBoundingRect(textElement);
342
+ svg.remove();
343
+ return rect;
400
344
  }
401
345
  /**
402
- * Check if canvas can render the configured x axis type.
403
- * @param {string} type X axis type
404
- * @returns {boolean} Whether type is supported
405
- * @private
406
- */
346
+ * Check if canvas can render the configured x axis type.
347
+ * @param {string} type X axis type
348
+ * @returns {boolean} Whether type is supported
349
+ * @private
350
+ */
407
351
  function isSupportedCanvasXType(type) {
408
- return /^(indexed|category|log|timeseries)$/.test(type);
352
+ return /^(indexed|category|log|timeseries)$/.test(type);
409
353
  }
410
354
  /**
411
- * Check if canvas can render the configured y/y2 axis type.
412
- * @param {string} type Y axis type
413
- * @returns {boolean} Whether type is supported
414
- * @private
415
- */
355
+ * Check if canvas can render the configured y/y2 axis type.
356
+ * @param {string} type Y axis type
357
+ * @returns {boolean} Whether type is supported
358
+ * @private
359
+ */
416
360
  function isSupportedCanvasYType(type) {
417
- return /^(indexed|log|timeseries)$/.test(type);
361
+ return /^(indexed|log|timeseries)$/.test(type);
418
362
  }
419
363
  /**
420
- * Get client position from mouse, pointer or touch event.
421
- * @param {Event} event Input event
422
- * @returns {object|null} Client position
423
- * @private
424
- */
364
+ * Get client position from mouse, pointer or touch event.
365
+ * @param {Event} event Input event
366
+ * @returns {object|null} Client position
367
+ * @private
368
+ */
425
369
  function getCanvasEventClientPoint(event) {
426
- const touchEvent = event;
427
- const touch = touchEvent.changedTouches?.[0] || touchEvent.touches?.[0];
428
- return touch || ("clientX" in event ? event : null);
370
+ const touchEvent = event;
371
+ return touchEvent.changedTouches?.[0] || touchEvent.touches?.[0] || ("clientX" in event ? event : null);
429
372
  }
430
373
  /**
431
- * Get data row under a canvas pointer event.
432
- * @param {object} $$ ChartInternal instance
433
- * @param {Event} event Input event
434
- * @param {boolean} shapeOnly Whether to skip grouped x-index fallback
435
- * @returns {object|null} Hit data row
436
- * @private
437
- */
374
+ * Get data row under a canvas pointer event.
375
+ * @param {object} $$ ChartInternal instance
376
+ * @param {Event} event Input event
377
+ * @param {boolean} shapeOnly Whether to skip grouped x-index fallback
378
+ * @returns {object|null} Hit data row
379
+ * @private
380
+ */
438
381
  function getCanvasEventDatum($$, event, shapeOnly = false) {
439
- const point = getCanvasEventPoint($$, event);
440
- return point ?
441
- (shapeOnly ?
442
- $$.hitDetector.findNearestShape?.(point[0], point[1]) :
443
- $$.hitDetector.findNearest(point[0], point[1])) :
444
- null;
382
+ const point = getCanvasEventPoint($$, event);
383
+ return point ? shapeOnly ? $$.hitDetector.findNearestShape?.(point[0], point[1]) : $$.hitDetector.findNearest(point[0], point[1]) : null;
445
384
  }
446
385
  /**
447
- * Check whether a canvas pointer coordinate can select the grouped x index.
448
- * @param {object} $$ ChartInternal instance
449
- * @param {Array} point Canvas-local coordinates
450
- * @returns {boolean} Whether x-index hover is allowed
451
- * @private
452
- */
386
+ * Check whether a canvas pointer coordinate can select the grouped x index.
387
+ * @param {object} $$ ChartInternal instance
388
+ * @param {Array} point Canvas-local coordinates
389
+ * @returns {boolean} Whether x-index hover is allowed
390
+ * @private
391
+ */
453
392
  function isCanvasXIndexHoverArea($$, point) {
454
- const { config, state } = $$;
455
- const { height, margin, width, xAxisHeight } = state;
456
- const [x, y] = point;
457
- const left = margin.left;
458
- const right = margin.left + width;
459
- const top = margin.top;
460
- const bottom = margin.top + height;
461
- const axisBand = config.axis_x_show ? Math.max(xAxisHeight || 0, 24) : 0;
462
- if ($$.isMultipleX?.() || state.hasTreemap) {
463
- return false;
464
- }
465
- return config.axis_rotated ?
466
- y >= top && y <= bottom && x >= left - axisBand && x <= right :
467
- x >= left && x <= right && y >= top && y <= bottom + axisBand;
393
+ const { config, state } = $$;
394
+ const { height, margin, width, xAxisHeight } = state;
395
+ const [x, y] = point;
396
+ const left = margin.left;
397
+ const right = margin.left + width;
398
+ const top = margin.top;
399
+ const bottom = margin.top + height;
400
+ const axisBand = config.axis_x_show ? Math.max(xAxisHeight || 0, 24) : 0;
401
+ if ($$.isMultipleX?.() || state.hasTreemap) return false;
402
+ return config.axis_rotated ? y >= top && y <= bottom && x >= left - axisBand && x <= right : x >= left && x <= right && y >= top && y <= bottom + axisBand;
468
403
  }
469
404
  /**
470
- * Check whether a canvas pointer coordinate is inside the main plot area.
471
- * @param {object} $$ ChartInternal instance
472
- * @param {Array} point Canvas-local coordinates
473
- * @returns {boolean} Whether axis tooltip can be shown
474
- * @private
475
- */
405
+ * Check whether a canvas pointer coordinate is inside the main plot area.
406
+ * @param {object} $$ ChartInternal instance
407
+ * @param {Array} point Canvas-local coordinates
408
+ * @returns {boolean} Whether axis tooltip can be shown
409
+ * @private
410
+ */
476
411
  function isCanvasAxisTooltipArea($$, point) {
477
- const { state: { height, margin, width } } = $$;
478
- const [x, y] = point;
479
- return x >= margin.left &&
480
- x <= margin.left + width &&
481
- y >= margin.top &&
482
- y <= margin.top + height;
412
+ const { state: { height, margin, width } } = $$;
413
+ const [x, y] = point;
414
+ return x >= margin.left && x <= margin.left + width && y >= margin.top && y <= margin.top + height;
483
415
  }
484
416
  /**
485
- * Get data row for hover from a canvas-local coordinate.
486
- * @param {object} $$ ChartInternal instance
487
- * @param {Array} point Canvas-local coordinates
488
- * @returns {object|null} Hover data row
489
- * @private
490
- */
417
+ * Get data row for hover from a canvas-local coordinate.
418
+ * @param {object} $$ ChartInternal instance
419
+ * @param {Array} point Canvas-local coordinates
420
+ * @returns {object|null} Hover data row
421
+ * @private
422
+ */
491
423
  function getCanvasHoverDatumFromPoint($$, point) {
492
- return $$.hitDetector.findNearest(point[0], point[1]) ||
493
- (isCanvasXIndexHoverArea($$, point) ?
494
- $$.hitDetector.findNearestIndexByCoord?.(point[0], point[1]) :
495
- null);
424
+ return $$.hitDetector.findNearest(point[0], point[1]) || (isCanvasXIndexHoverArea($$, point) ? $$.hitDetector.findNearestIndexByCoord?.(point[0], point[1]) : null);
496
425
  }
497
426
  /**
498
- * Get visible canvas data rows for a tooltip target.
499
- * @param {object} $$ ChartInternal instance
500
- * @param {object} d Base data row
501
- * @returns {Array} Tooltip data rows
502
- * @private
503
- */
427
+ * Get visible canvas data rows for a tooltip target.
428
+ * @param {object} $$ ChartInternal instance
429
+ * @param {object} d Base data row
430
+ * @returns {Array} Tooltip data rows
431
+ * @private
432
+ */
504
433
  function getCanvasTooltipData($$, d) {
505
- const { config, state } = $$;
506
- const targetsToShow = $$.filterTargetsToShow($$.data.targets);
507
- const pointBased = isCanvasPointBasedInteraction($$, d);
508
- const sameXData = config.tooltip_grouped &&
509
- !state.hasTreemap &&
510
- !pointBased ?
511
- $$.filterByX?.(targetsToShow, d.x) :
512
- null;
513
- return (state.hasTreemap ?
514
- [d] :
515
- (pointBased ?
516
- [d] :
517
- (config.tooltip_grouped ?
518
- (sameXData?.length ?
519
- sameXData :
520
- targetsToShow.map(target => target.values[d.index]).filter(Boolean)) :
521
- [d])))
522
- .map(v => $$.addName?.(v) || v);
434
+ const { config, state } = $$;
435
+ const targetsToShow = $$.filterTargetsToShow($$.data.targets);
436
+ const pointBased = isCanvasPointBasedInteraction($$, d);
437
+ const sameXData = config.tooltip_grouped && !state.hasTreemap && !pointBased ? $$.filterByX?.(targetsToShow, d.x) : null;
438
+ return (state.hasTreemap ? [d] : pointBased ? [d] : config.tooltip_grouped ? sameXData?.length ? sameXData : targetsToShow.map((target) => target.values[d.index]).filter(Boolean) : [d]).map((v) => $$.addName?.(v) || v);
523
439
  }
524
440
  /**
525
- * Get data rows for canvas focus rendering.
526
- * @param {object} $$ ChartInternal instance
527
- * @param {object} d Hover data row
528
- * @param {Array} selectedData Tooltip data rows
529
- * @returns {Array} Focus data rows
530
- * @private
531
- */
441
+ * Get data rows for canvas focus rendering.
442
+ * @param {object} $$ ChartInternal instance
443
+ * @param {object} d Hover data row
444
+ * @param {Array} selectedData Tooltip data rows
445
+ * @returns {Array} Focus data rows
446
+ * @private
447
+ */
532
448
  function getCanvasFocusData($$, d, selectedData) {
533
- return $$.isMultipleX?.() && !isCanvasPointBasedInteraction($$, d) ?
534
- [$$.addName?.(d) || d] :
535
- selectedData;
449
+ return $$.isMultipleX?.() && !isCanvasPointBasedInteraction($$, d) ? [$$.addName?.(d) || d] : selectedData;
536
450
  }
537
451
  /**
538
- * Get canvas-local coordinates from mouse, pointer or touch event.
539
- * @param {object} $$ ChartInternal instance
540
- * @param {Event} event Input event
541
- * @returns {Array|null} Canvas-local coordinates
542
- * @private
543
- */
452
+ * Get canvas-local coordinates from mouse, pointer or touch event.
453
+ * @param {object} $$ ChartInternal instance
454
+ * @param {Event} event Input event
455
+ * @returns {Array|null} Canvas-local coordinates
456
+ * @private
457
+ */
544
458
  function getCanvasEventPoint($$, event) {
545
- const point = getCanvasEventClientPoint(event);
546
- if (!point) {
547
- return null;
548
- }
549
- const canvas = $$.$el.canvas.node();
550
- const rect = getBoundingRect(canvas, true);
551
- return [point.clientX - rect.left, point.clientY - rect.top];
459
+ const point = getCanvasEventClientPoint(event);
460
+ if (!point) return null;
461
+ const rect = getBoundingRect($$.$el.canvas.node(), true);
462
+ return [point.clientX - rect.left, point.clientY - rect.top];
552
463
  }
553
464
  /**
554
- * Normalize a subchart domain range for the current x axis type.
555
- * @param {object} $$ ChartInternal instance
556
- * @param {Array} domain Domain range
557
- * @returns {Array} Normalized domain range
558
- * @private
559
- */
465
+ * Normalize a subchart domain range for the current x axis type.
466
+ * @param {object} $$ ChartInternal instance
467
+ * @param {Array} domain Domain range
468
+ * @returns {Array} Normalized domain range
469
+ * @private
470
+ */
560
471
  function normalizeCanvasSubchartDomain($$, domain) {
561
- if (!Array.isArray(domain) || domain.length < 2) {
562
- return null;
563
- }
564
- const values = domain.slice(0, 2);
565
- return $$.axis?.isTimeSeries?.() ? values.map(value => parseDate.call($$, value)) : values;
472
+ if (!Array.isArray(domain) || domain.length < 2) return null;
473
+ const values = domain.slice(0, 2);
474
+ return $$.axis?.isTimeSeries?.() ? values.map((value) => parseDate.call($$, value)) : values;
566
475
  }
567
476
  /**
568
- * Get the canvas-space rectangle occupied by the subchart plot.
569
- * @param {object} $$ ChartInternal instance
570
- * @returns {object|null} Subchart rectangle
571
- * @private
572
- */
477
+ * Get the canvas-space rectangle occupied by the subchart plot.
478
+ * @param {object} $$ ChartInternal instance
479
+ * @returns {object|null} Subchart rectangle
480
+ * @private
481
+ */
573
482
  function getCanvasSubchartRect($$) {
574
- const { config, state } = $$;
575
- if (!config.subchart_show || !state.hasAxis || state.width2 <= 0 || state.height2 <= 0) {
576
- return null;
577
- }
578
- return {
579
- x: state.margin2.left,
580
- y: state.margin2.top,
581
- w: state.width2,
582
- h: state.height2
583
- };
483
+ const { config, state } = $$;
484
+ if (!config.subchart_show || !state.hasAxis || state.width2 <= 0 || state.height2 <= 0) return null;
485
+ return {
486
+ x: state.margin2.left,
487
+ y: state.margin2.top,
488
+ w: state.width2,
489
+ h: state.height2
490
+ };
584
491
  }
585
492
  /**
586
- * Check whether a canvas point is inside the subchart plot area.
587
- * @param {object} $$ ChartInternal instance
588
- * @param {Array} point Canvas-local point
589
- * @returns {boolean} Whether point is in the subchart
590
- * @private
591
- */
493
+ * Check whether a canvas point is inside the subchart plot area.
494
+ * @param {object} $$ ChartInternal instance
495
+ * @param {Array} point Canvas-local point
496
+ * @returns {boolean} Whether point is in the subchart
497
+ * @private
498
+ */
592
499
  function isCanvasSubchartPoint($$, point) {
593
- const rect = getCanvasSubchartRect($$);
594
- return !!rect &&
595
- point[0] >= rect.x &&
596
- point[0] <= rect.x + rect.w &&
597
- point[1] >= rect.y &&
598
- point[1] <= rect.y + rect.h;
500
+ const rect = getCanvasSubchartRect($$);
501
+ return !!rect && point[0] >= rect.x && point[0] <= rect.x + rect.w && point[1] >= rect.y && point[1] <= rect.y + rect.h;
502
+ }
503
+ /**
504
+ * Convert a canvas subchart point to the equivalent main plot point.
505
+ * @param {object} $$ ChartInternal instance
506
+ * @param {Array} point Canvas-local point
507
+ * @returns {Array|null} Main plot point or null when not applicable
508
+ * @private
509
+ */
510
+ function getCanvasMainPointFromSubchart($$, point) {
511
+ const { config, state } = $$;
512
+ const rect = getCanvasSubchartRect($$);
513
+ if (config.subchart_brush_enabled !== false || !rect || !isCanvasSubchartPoint($$, point)) return null;
514
+ const mainCoord = getMainCoordFromSubchartCoord($$, config.axis_rotated ? point[1] - rect.y : point[0] - rect.x);
515
+ if (mainCoord === null) return null;
516
+ return config.axis_rotated ? [state.margin.left + state.width / 2, state.margin.top + mainCoord] : [state.margin.left + mainCoord, state.margin.top + state.height / 2];
599
517
  }
600
518
  /**
601
- * Get the allowed local brush coordinate extent for canvas subchart interactions.
602
- * @param {object} $$ ChartInternal instance
603
- * @returns {Array} Brush extent in subchart-local pixels
604
- * @private
605
- */
519
+ * Get the allowed local brush coordinate extent for canvas subchart interactions.
520
+ * @param {object} $$ ChartInternal instance
521
+ * @returns {Array} Brush extent in subchart-local pixels
522
+ * @private
523
+ */
606
524
  function getCanvasSubchartBrushExtent($$) {
607
- const rect = getCanvasSubchartRect($$);
608
- const axisLength = rect ? ($$.config.axis_rotated ? rect.h : rect.w) : 0;
609
- const extent = $$.axis?.getExtent?.();
610
- const values = Array.isArray(extent) ? extent.slice(0, 2) : [];
611
- if (values.length === 2 && values.every(Number.isFinite)) {
612
- const start = Math.max(0, Math.min(axisLength, values[0]));
613
- const end = Math.max(0, Math.min(axisLength, values[1]));
614
- return [Math.min(start, end), Math.max(start, end)];
615
- }
616
- return [0, axisLength];
525
+ const rect = getCanvasSubchartRect($$);
526
+ const axisLength = rect ? $$.config.axis_rotated ? rect.h : rect.w : 0;
527
+ const extent = $$.axis?.getExtent?.();
528
+ const values = Array.isArray(extent) ? extent.slice(0, 2) : [];
529
+ if (values.length === 2 && values.every(Number.isFinite)) {
530
+ const start = Math.max(0, Math.min(axisLength, values[0]));
531
+ const end = Math.max(0, Math.min(axisLength, values[1]));
532
+ return [Math.min(start, end), Math.max(start, end)];
533
+ }
534
+ return [0, axisLength];
617
535
  }
618
536
  /**
619
- * Get the local brush coordinate from a canvas subchart pointer event.
620
- * @param {object} $$ ChartInternal instance
621
- * @param {Event} event Input event
622
- * @param {boolean} clampToExtent Whether to clamp pointer outside brush extent
623
- * @returns {number|null} Brush coordinate
624
- * @private
625
- */
537
+ * Get the local brush coordinate from a canvas subchart pointer event.
538
+ * @param {object} $$ ChartInternal instance
539
+ * @param {Event} event Input event
540
+ * @param {boolean} clampToExtent Whether to clamp pointer outside brush extent
541
+ * @returns {number|null} Brush coordinate
542
+ * @private
543
+ */
626
544
  function getCanvasSubchartBrushCoord($$, event, clampToExtent = false) {
627
- const point = getCanvasEventPoint($$, event);
628
- const rect = point && getCanvasSubchartRect($$);
629
- if (!point || !rect || !isCanvasSubchartPoint($$, point)) {
630
- return null;
631
- }
632
- const raw = $$.config.axis_rotated ? point[1] - rect.y : point[0] - rect.x;
633
- const [min, max] = getCanvasSubchartBrushExtent($$);
634
- if (!clampToExtent && (raw < min || raw > max)) {
635
- return null;
636
- }
637
- return Math.max(min, Math.min(max, raw));
545
+ const point = getCanvasEventPoint($$, event);
546
+ const rect = point && getCanvasSubchartRect($$);
547
+ if (!point || !rect || !isCanvasSubchartPoint($$, point)) return null;
548
+ const raw = $$.config.axis_rotated ? point[1] - rect.y : point[0] - rect.x;
549
+ const [min, max] = getCanvasSubchartBrushExtent($$);
550
+ if (!clampToExtent && (raw < min || raw > max)) return null;
551
+ return Math.max(min, Math.min(max, raw));
638
552
  }
639
553
  /**
640
- * Build a scale domain from two subchart brush coordinates.
641
- * @param {object} $$ ChartInternal instance
642
- * @param {number} start Brush start coordinate
643
- * @param {number} end Brush end coordinate
644
- * @returns {Array} Domain range
645
- * @private
646
- */
554
+ * Build a scale domain from two subchart brush coordinates.
555
+ * @param {object} $$ ChartInternal instance
556
+ * @param {number} start Brush start coordinate
557
+ * @param {number} end Brush end coordinate
558
+ * @returns {Array} Domain range
559
+ * @private
560
+ */
647
561
  function getCanvasSubchartDomainFromCoords($$, start, end) {
648
- const coordStart = Math.min(start, end);
649
- const coordEnd = Math.max(start, end);
650
- return [
651
- $$.scale.subX.invert(coordStart),
652
- $$.scale.subX.invert(coordEnd)
653
- ];
562
+ const coordStart = Math.min(start, end);
563
+ const coordEnd = Math.max(start, end);
564
+ return [$$.scale.subX.invert(coordStart), $$.scale.subX.invert(coordEnd)];
654
565
  }
655
566
  /**
656
- * Get current canvas subchart brush selection in local subchart pixels.
657
- * @param {object} $$ ChartInternal instance
658
- * @returns {Array|null} Brush selection pixels
659
- * @private
660
- */
567
+ * Get current canvas subchart brush selection in local subchart pixels.
568
+ * @param {object} $$ ChartInternal instance
569
+ * @returns {Array|null} Brush selection pixels
570
+ * @private
571
+ */
661
572
  function getCanvasSubchartBrushSelection($$) {
662
- const { scale, state } = $$;
663
- const domain = state.domain;
664
- if (!domain?.length || !scale.subX) {
665
- return null;
666
- }
667
- const rect = getCanvasSubchartRect($$);
668
- const p0 = scale.subX(domain[0]);
669
- const p1 = scale.subX(domain[1]);
670
- if (!rect || !Number.isFinite(p0) || !Number.isFinite(p1)) {
671
- return null;
672
- }
673
- const [min, max] = getCanvasSubchartBrushExtent($$);
674
- return [
675
- Math.max(min, Math.min(max, Math.min(p0, p1))),
676
- Math.max(min, Math.min(max, Math.max(p0, p1)))
677
- ];
573
+ const { scale, state } = $$;
574
+ const domain = state.domain;
575
+ if (!domain?.length || !scale.subX) return null;
576
+ const rect = getCanvasSubchartRect($$);
577
+ const p0 = scale.subX(domain[0]);
578
+ const p1 = scale.subX(domain[1]);
579
+ if (!rect || !Number.isFinite(p0) || !Number.isFinite(p1)) return null;
580
+ const [min, max] = getCanvasSubchartBrushExtent($$);
581
+ return [Math.max(min, Math.min(max, Math.min(p0, p1))), Math.max(min, Math.min(max, Math.max(p0, p1)))];
678
582
  }
679
583
  /**
680
- * Get the subchart brush mode at a local brush coordinate.
681
- * @param {object} $$ ChartInternal instance
682
- * @param {number} coord Brush coordinate
683
- * @returns {string} Brush mode
684
- * @private
685
- */
584
+ * Get the subchart brush mode at a local brush coordinate.
585
+ * @param {object} $$ ChartInternal instance
586
+ * @param {number} coord Brush coordinate
587
+ * @returns {string} Brush mode
588
+ * @private
589
+ */
686
590
  function getCanvasSubchartBrushMode($$, coord) {
687
- const selection = getCanvasSubchartBrushSelection($$);
688
- if (!selection) {
689
- return "select";
690
- }
691
- const [start, end] = selection;
692
- if (Math.abs(coord - start) <= CANVAS_SUBCHART_HANDLE_SIZE) {
693
- return "resize-start";
694
- }
695
- if (Math.abs(coord - end) <= CANVAS_SUBCHART_HANDLE_SIZE) {
696
- return "resize-end";
697
- }
698
- return coord > start && coord < end ? "move" : "select";
591
+ const selection = getCanvasSubchartBrushSelection($$);
592
+ if (!selection) return "select";
593
+ const [start, end] = selection;
594
+ if (Math.abs(coord - start) <= CANVAS_SUBCHART_HANDLE_SIZE) return "resize-start";
595
+ if (Math.abs(coord - end) <= CANVAS_SUBCHART_HANDLE_SIZE) return "resize-end";
596
+ return coord > start && coord < end ? "move" : "select";
699
597
  }
700
598
  /**
701
- * Clamp a subchart brush selection to the subchart extent.
702
- * @param {object} $$ ChartInternal instance
703
- * @param {number} start Selection start pixel
704
- * @param {number} end Selection end pixel
705
- * @returns {Array} Clamped selection pixels
706
- * @private
707
- */
599
+ * Clamp a subchart brush selection to the subchart extent.
600
+ * @param {object} $$ ChartInternal instance
601
+ * @param {number} start Selection start pixel
602
+ * @param {number} end Selection end pixel
603
+ * @returns {Array} Clamped selection pixels
604
+ * @private
605
+ */
708
606
  function clampCanvasSubchartSelection($$, start, end) {
709
- const [min, max] = getCanvasSubchartBrushExtent($$);
710
- return [
711
- Math.max(min, Math.min(max, start)),
712
- Math.max(min, Math.min(max, end))
713
- ];
607
+ const [min, max] = getCanvasSubchartBrushExtent($$);
608
+ return [Math.max(min, Math.min(max, start)), Math.max(min, Math.min(max, end))];
714
609
  }
715
610
  /**
716
- * Get cursor for a canvas subchart brush mode.
717
- * @param {object} $$ ChartInternal instance
718
- * @param {string} mode Brush mode
719
- * @returns {string} CSS cursor
720
- * @private
721
- */
611
+ * Get cursor for a canvas subchart brush mode.
612
+ * @param {object} $$ ChartInternal instance
613
+ * @param {string} mode Brush mode
614
+ * @returns {string} CSS cursor
615
+ * @private
616
+ */
722
617
  function getCanvasSubchartCursor($$, mode) {
723
- if (/^resize/.test(mode)) {
724
- return $$.config.axis_rotated ? "ns-resize" : "ew-resize";
725
- }
726
- return mode === "move" ? "move" : "crosshair";
618
+ if (/^resize/.test(mode)) return $$.config.axis_rotated ? "ns-resize" : "ew-resize";
619
+ return mode === "move" ? "move" : "crosshair";
727
620
  }
728
621
  /**
729
- * Get stable key for canvas data callbacks.
730
- * @param {object} d Data row
731
- * @returns {string|null} Data key
732
- * @private
733
- */
622
+ * Get stable key for canvas data callbacks.
623
+ * @param {object} d Data row
624
+ * @returns {string|null} Data key
625
+ * @private
626
+ */
734
627
  function getCanvasDataKey(d) {
735
- return d ? `${d.id}:${d.index}` : null;
628
+ return d ? `${d.id}:${d.index}` : null;
736
629
  }
737
630
  /**
738
- * Get canvas drag selection delta rows from current and previous hit rows.
739
- * @param {object} $$ ChartInternal instance
740
- * @param {Array} dataRows Current drag hit rows
741
- * @returns {object} Current included keys and rows to toggle
742
- * @private
743
- */
631
+ * Get canvas drag selection delta rows from current and previous hit rows.
632
+ * @param {object} $$ ChartInternal instance
633
+ * @param {Array} dataRows Current drag hit rows
634
+ * @returns {object} Current included keys and rows to toggle
635
+ * @private
636
+ */
744
637
  function getCanvasSelectionDragDelta($$, dataRows) {
745
- const previousKeys = $$.state.canvasSelectionDragIncluded;
746
- const previousRows = canvasSelectionDragRows.get($$) || new Map();
747
- const currentRows = new Map();
748
- const included = new Set();
749
- const rows = [];
750
- dataRows
751
- .filter(d => isCanvasSelectableData($$, d))
752
- .forEach(d => {
753
- const key = getCanvasDataKey(d);
754
- if (key) {
755
- included.add(key);
756
- !currentRows.has(key) && currentRows.set(key, d);
757
- }
758
- });
759
- currentRows.forEach((d, key) => {
760
- !previousKeys.has(key) && rows.push(d);
761
- });
762
- previousRows.forEach((d, key) => {
763
- !included.has(key) && rows.push(d);
764
- });
765
- canvasSelectionDragRows.set($$, currentRows);
766
- return { included, rows };
638
+ const previousKeys = $$.state.canvasSelectionDragIncluded;
639
+ const previousRows = canvasSelectionDragRows.get($$) || /* @__PURE__ */ new Map();
640
+ const currentRows = /* @__PURE__ */ new Map();
641
+ const included = /* @__PURE__ */ new Set();
642
+ const rows = [];
643
+ dataRows.filter((d) => isCanvasSelectableData($$, d)).forEach((d) => {
644
+ const key = getCanvasDataKey(d);
645
+ if (key) {
646
+ included.add(key);
647
+ !currentRows.has(key) && currentRows.set(key, d);
648
+ }
649
+ });
650
+ currentRows.forEach((d, key) => {
651
+ !previousKeys.has(key) && rows.push(d);
652
+ });
653
+ previousRows.forEach((d, key) => {
654
+ !included.has(key) && rows.push(d);
655
+ });
656
+ canvasSelectionDragRows.set($$, currentRows);
657
+ return {
658
+ included,
659
+ rows
660
+ };
767
661
  }
768
662
  /**
769
- * Normalize a data id or id list.
770
- * @param {string|Array} ids Data ids
771
- * @returns {Array|null} Normalized ids
772
- * @private
773
- */
663
+ * Normalize a data id or id list.
664
+ * @param {string|Array} ids Data ids
665
+ * @returns {Array|null} Normalized ids
666
+ * @private
667
+ */
774
668
  function getCanvasSelectionIds(ids) {
775
- return ids ? (Array.isArray(ids) ? ids : [ids]) : null;
669
+ return ids ? Array.isArray(ids) ? ids : [ids] : null;
776
670
  }
777
671
  /**
778
- * Check whether a canvas data row participates in selection.
779
- * @param {object} $$ ChartInternal instance
780
- * @param {object} d Data row
781
- * @returns {boolean} Whether the row can be selected
782
- * @private
783
- */
672
+ * Check whether a canvas data row participates in selection.
673
+ * @param {object} $$ ChartInternal instance
674
+ * @param {object} d Data row
675
+ * @returns {boolean} Whether the row can be selected
676
+ * @private
677
+ */
784
678
  function isCanvasSelectableData($$, d) {
785
- return d &&
786
- hasCanvasDrawableValue($$, d) &&
787
- isCanvasTargetSupported($$, d, CANVAS_SELECTABLE_TYPE_FILTERS) &&
788
- CANVAS_SELECTABLE_TYPE_FILTERS.some(filter => filter($$, d)) &&
789
- $$.config.data_selection_isselectable.bind($$.api)(d);
679
+ return d && hasCanvasDrawableValue($$, d) && isCanvasTargetSupported($$, d, CANVAS_SELECTABLE_TYPE_FILTERS) && CANVAS_SELECTABLE_TYPE_FILTERS.some((filter) => filter($$, d)) && $$.config.data_selection_isselectable.bind($$.api)(d);
790
680
  }
791
681
  /**
792
- * Iterate selectable canvas rows.
793
- * @param {object} $$ ChartInternal instance
794
- * @param {function} callback Row callback
795
- * @private
796
- */
682
+ * Iterate selectable canvas rows.
683
+ * @param {object} $$ ChartInternal instance
684
+ * @param {function} callback Row callback
685
+ * @private
686
+ */
797
687
  function eachCanvasSelectableData($$, callback) {
798
- $$.filterTargetsToShow($$.data.targets)
799
- .filter(target => isCanvasTargetSupported($$, target, CANVAS_SELECTABLE_TYPE_FILTERS))
800
- .forEach(target => {
801
- target.values.forEach(d => {
802
- isCanvasSelectableData($$, d) && callback(d);
803
- });
804
- });
688
+ $$.filterTargetsToShow($$.data.targets).filter((target) => isCanvasTargetSupported($$, target, CANVAS_SELECTABLE_TYPE_FILTERS)).forEach((target) => {
689
+ target.values.forEach((d) => {
690
+ isCanvasSelectableData($$, d) && callback(d);
691
+ });
692
+ });
805
693
  }
806
694
  /**
807
- * Check whether a canvas data row should interact as a single point.
808
- * @param {object} $$ ChartInternal instance
809
- * @param {object} d Data row
810
- * @returns {boolean} Whether the row should stay ungrouped
811
- * @private
812
- */
695
+ * Check whether a canvas data row should interact as a single point.
696
+ * @param {object} $$ ChartInternal instance
697
+ * @param {object} d Data row
698
+ * @returns {boolean} Whether the row should stay ungrouped
699
+ * @private
700
+ */
813
701
  function isCanvasPointBasedInteraction($$, d) {
814
- return !($$.config.axis_x_forceAsSingle && $$.config.tooltip_grouped) &&
815
- (isCanvasScatterType($$, d) || isCanvasBubbleType($$, d));
702
+ return !($$.config.axis_x_forceAsSingle && $$.config.tooltip_grouped) && (isCanvasScatterType($$, d) || isCanvasBubbleType($$, d));
816
703
  }
817
704
  /**
818
- * Check if touch input is enabled by option.
819
- * @param {object} config Config object
820
- * @returns {boolean} Whether touch is enabled
821
- * @private
822
- */
705
+ * Check if touch input is enabled by option.
706
+ * @param {object} config Config object
707
+ * @returns {boolean} Whether touch is enabled
708
+ * @private
709
+ */
823
710
  function isCanvasTouchEnabled(config) {
824
- return config.interaction_inputType_touch !== false;
711
+ return config.interaction_inputType_touch !== false;
825
712
  }
826
713
  /**
827
- * Get touch listener passive option following interaction.inputType.touch.preventDefault.
828
- * @param {object} config Config object
829
- * @returns {object} Event listener options
830
- * @private
831
- */
714
+ * Get touch listener passive option following interaction.inputType.touch.preventDefault.
715
+ * @param {object} config Config object
716
+ * @returns {object} Event listener options
717
+ * @private
718
+ */
832
719
  function getCanvasTouchListenerOption(config) {
833
- const preventDefault = config.interaction_inputType_touch?.preventDefault;
834
- const isPrevented = (isBoolean(preventDefault) && preventDefault) || false;
835
- const preventThreshold = (!isNaN(preventDefault) && preventDefault) || null;
836
- return {
837
- passive: !isPrevented && preventThreshold === null
838
- };
720
+ const preventDefault = config.interaction_inputType_touch?.preventDefault;
721
+ return { passive: !(isBoolean(preventDefault) && preventDefault || false) && (!isNaN(preventDefault) && preventDefault || null) === null };
839
722
  }
840
723
  /**
841
- * Create touch preventDefault handler following interaction.inputType.touch.preventDefault.
842
- * @param {object} config Config object
843
- * @returns {function} Touch preventer
844
- * @private
845
- */
724
+ * Create touch preventDefault handler following interaction.inputType.touch.preventDefault.
725
+ * @param {object} config Config object
726
+ * @returns {function} Touch preventer
727
+ * @private
728
+ */
846
729
  function getCanvasTouchPreventer(config) {
847
- const preventDefault = config.interaction_inputType_touch?.preventDefault;
848
- const isPrevented = (isBoolean(preventDefault) && preventDefault) || false;
849
- const preventThreshold = (!isNaN(preventDefault) && preventDefault) || null;
850
- let startPx;
851
- return event => {
852
- const touch = event.changedTouches?.[0] || event.touches?.[0];
853
- if (!touch) {
854
- return;
855
- }
856
- const currentXY = touch[`client${config.axis_rotated ? "Y" : "X"}`];
857
- if (event.type === "touchstart") {
858
- if (isPrevented) {
859
- event.preventDefault();
860
- }
861
- else if (preventThreshold !== null) {
862
- startPx = currentXY;
863
- }
864
- }
865
- else if (event.type === "touchmove" &&
866
- (isPrevented ||
867
- startPx === true ||
868
- (preventThreshold !== null &&
869
- Math.abs(startPx - currentXY) >= preventThreshold))) {
870
- startPx = true;
871
- event.preventDefault();
872
- }
873
- };
730
+ const preventDefault = config.interaction_inputType_touch?.preventDefault;
731
+ const isPrevented = isBoolean(preventDefault) && preventDefault || false;
732
+ const preventThreshold = !isNaN(preventDefault) && preventDefault || null;
733
+ let startPx;
734
+ return (event) => {
735
+ const touch = event.changedTouches?.[0] || event.touches?.[0];
736
+ if (!touch) return;
737
+ const currentXY = touch[`client${config.axis_rotated ? "Y" : "X"}`];
738
+ if (event.type === "touchstart") {
739
+ if (isPrevented) event.preventDefault();
740
+ else if (preventThreshold !== null) startPx = currentXY;
741
+ } else if (event.type === "touchmove" && (isPrevented || startPx === true || preventThreshold !== null && Math.abs(startPx - currentXY) >= preventThreshold)) {
742
+ startPx = true;
743
+ event.preventDefault();
744
+ }
745
+ };
874
746
  }
875
747
  /**
876
- * Check whether a pointer event should be handled by canvas pointer path.
877
- * @param {object} $$ ChartInternal instance
878
- * @param {PointerEvent} event Pointer event
879
- * @returns {boolean} Whether event should be handled
880
- * @private
881
- */
748
+ * Check whether a pointer event should be handled by canvas pointer path.
749
+ * @param {object} $$ ChartInternal instance
750
+ * @param {PointerEvent} event Pointer event
751
+ * @returns {boolean} Whether event should be handled
752
+ * @private
753
+ */
882
754
  function shouldHandleCanvasPointerEvent($$, event) {
883
- return event.pointerType !== "mouse" && $$.state.inputType !== "touch";
755
+ return event.pointerType !== "mouse" && $$.state.inputType !== "touch";
884
756
  }
885
757
  /**
886
- * Check if click event duplicates a recent touch/pointer data click.
887
- * @param {object} $$ ChartInternal instance
888
- * @param {object} d Data row
889
- * @returns {boolean} Whether the click should skip data callback
890
- * @private
891
- */
758
+ * Check if click event duplicates a recent touch/pointer data click.
759
+ * @param {object} $$ ChartInternal instance
760
+ * @param {object} d Data row
761
+ * @returns {boolean} Whether the click should skip data callback
762
+ * @private
763
+ */
892
764
  function isDuplicateCanvasInputClick($$, d) {
893
- const { state } = $$;
894
- const key = getCanvasDataKey(d);
895
- const duplicate = key &&
896
- state.canvasLastInputClickKey === key &&
897
- Date.now() - (state.canvasLastInputClickTime || 0) < 750;
898
- if (duplicate) {
899
- state.canvasLastInputClickKey = null;
900
- state.canvasLastInputClickTime = 0;
901
- }
902
- return Boolean(duplicate);
765
+ const { state } = $$;
766
+ const key = getCanvasDataKey(d);
767
+ const duplicate = key && state.canvasLastInputClickKey === key && Date.now() - (state.canvasLastInputClickTime || 0) < 750;
768
+ if (duplicate) {
769
+ state.canvasLastInputClickKey = null;
770
+ state.canvasLastInputClickTime = 0;
771
+ }
772
+ return Boolean(duplicate);
903
773
  }
904
774
  /**
905
- * Mark a touch/pointer data click so the following compatibility click can be ignored.
906
- * @param {object} $$ ChartInternal instance
907
- * @param {object} d Data row
908
- * @private
909
- */
775
+ * Mark a touch/pointer data click so the following compatibility click can be ignored.
776
+ * @param {object} $$ ChartInternal instance
777
+ * @param {object} d Data row
778
+ * @private
779
+ */
910
780
  function markCanvasInputClick($$, d) {
911
- $$.state.canvasLastInputClickKey = getCanvasDataKey(d);
912
- $$.state.canvasLastInputClickTime = Date.now();
781
+ $$.state.canvasLastInputClickKey = getCanvasDataKey(d);
782
+ $$.state.canvasLastInputClickTime = Date.now();
913
783
  }
914
784
  /**
915
- * Get current animation timestamp.
916
- * @returns {number} Timestamp
917
- * @private
918
- */
785
+ * Get current animation timestamp.
786
+ * @returns {number} Timestamp
787
+ * @private
788
+ */
919
789
  function getCanvasAnimationTime() {
920
- return win.performance?.now?.() ?? Date.now();
790
+ return win.performance?.now?.() ?? Date.now();
921
791
  }
922
792
  /**
923
- * Check whether a domain can be interpolated for canvas flow.
924
- * @param {Array} domain Domain values
925
- * @param {boolean} isLog Whether the domain is in log scale
926
- * @returns {boolean} Whether domain is numeric/date-like
927
- * @private
928
- */
793
+ * Check whether a domain can be interpolated for canvas flow.
794
+ * @param {Array} domain Domain values
795
+ * @param {boolean} isLog Whether the domain is in log scale
796
+ * @returns {boolean} Whether domain is numeric/date-like
797
+ * @private
798
+ */
929
799
  function isCanvasFlowDomain(domain, isLog = false) {
930
- return Array.isArray(domain) &&
931
- domain.length >= 2 &&
932
- domain.every(v => Number.isFinite(+v) && (!isLog || +v > 0));
800
+ return Array.isArray(domain) && domain.length >= 2 && domain.every((v) => Number.isFinite(+v) && (!isLog || +v > 0));
933
801
  }
934
802
  /**
935
- * Interpolate numeric/date domain values.
936
- * @param {Array} start Start domain
937
- * @param {Array} end End domain
938
- * @param {number} ratio Interpolation ratio
939
- * @param {boolean} isLog Whether to interpolate in log space
940
- * @returns {Array} Interpolated domain
941
- * @private
942
- */
803
+ * Interpolate numeric/date domain values.
804
+ * @param {Array} start Start domain
805
+ * @param {Array} end End domain
806
+ * @param {number} ratio Interpolation ratio
807
+ * @param {boolean} isLog Whether to interpolate in log space
808
+ * @returns {Array} Interpolated domain
809
+ * @private
810
+ */
943
811
  function interpolateCanvasFlowDomain(start, end, ratio, isLog = false) {
944
- return start.slice(0, 2).map((value, index) => {
945
- const next = isLog ?
946
- Math.exp(Math.log(+value) + ((Math.log(+end[index]) - Math.log(+value)) * ratio)) :
947
- +value + ((+end[index] - +value) * ratio);
948
- return value instanceof Date || end[index] instanceof Date ? new Date(next) : next;
949
- });
812
+ return start.slice(0, 2).map((value, index) => {
813
+ const next = isLog ? Math.exp(Math.log(+value) + (Math.log(+end[index]) - Math.log(+value)) * ratio) : +value + (+end[index] - +value) * ratio;
814
+ return value instanceof Date || end[index] instanceof Date ? new Date(next) : next;
815
+ });
950
816
  }
951
817
  /**
952
- * Count current canvas flow values.
953
- * @param {object} $$ ChartInternal instance
954
- * @returns {number} Total values
955
- * @private
956
- */
818
+ * Count current canvas flow values.
819
+ * @param {object} $$ ChartInternal instance
820
+ * @returns {number} Total values
821
+ * @private
822
+ */
957
823
  function getCanvasFlowValueCount($$) {
958
- return $$.data.targets.reduce((sum, target) => sum + target.values.length, 0);
824
+ return $$.data.targets.reduce((sum, target) => sum + target.values.length, 0);
959
825
  }
960
826
  /**
961
- * Sync y/y2 domains for canvas flow frames after data has been appended.
962
- * @param {object} $$ ChartInternal instance
963
- * @private
964
- */
827
+ * Sync y/y2 domains for canvas flow frames after data has been appended.
828
+ * @param {object} $$ ChartInternal instance
829
+ * @private
830
+ */
965
831
  function syncCanvasFlowYDomains($$) {
966
- const { scale } = $$;
967
- const targetsToShow = $$.filterTargetsToShow($$.data.targets);
968
- ["y", "y2"].forEach(key => {
969
- scale[key]?.domain($$.getYDomain(targetsToShow, key));
970
- });
971
- scale.subY?.domain($$.getYDomain(targetsToShow, "y"));
972
- scale.subY2?.domain($$.getYDomain(targetsToShow, "y2"));
832
+ const { scale } = $$;
833
+ const targetsToShow = $$.filterTargetsToShow($$.data.targets);
834
+ ["y", "y2"].forEach((key) => {
835
+ scale[key]?.domain($$.getYDomain(targetsToShow, key));
836
+ });
837
+ $$.withSubchartTypeContext(() => {
838
+ scale.subY?.domain($$.getYDomain(targetsToShow, "y"));
839
+ scale.subY2?.domain($$.getYDomain(targetsToShow, "y2"));
840
+ });
973
841
  }
974
842
  const canvasInternal = {
975
- /**
976
- * Normalize unsupported options before initializing canvas mode.
977
- * @private
978
- */
979
- prepareCanvasConfig() {
980
- const { config, state } = this;
981
- this.warnUnsupportedCanvasOptions();
982
- if (state.orgConfig?.transition &&
983
- Object.prototype.hasOwnProperty.call(state.orgConfig.transition, "duration") &&
984
- state.orgConfig.transition.duration) {
985
- warn("canvas mode: transition.duration is ignored; canvas redraws synchronously.");
986
- }
987
- config.transition_duration = 0;
988
- if (!isSupportedCanvasXType(config.axis_x_type)) {
989
- config.axis_x_type = "indexed";
990
- }
991
- if (!isSupportedCanvasYType(config.axis_y_type)) {
992
- config.axis_y_type = "indexed";
993
- }
994
- if (!isSupportedCanvasYType(config.axis_y2_type)) {
995
- config.axis_y2_type = "indexed";
996
- }
997
- if (this.hasType?.("bubble")) {
998
- config.point_show = true;
999
- config.point_type = "circle";
1000
- }
1001
- },
1002
- /**
1003
- * Apply the current canvas subchart selection to the main x domain.
1004
- * @private
1005
- */
1006
- applyCanvasSubchartDomain() {
1007
- const $$ = this;
1008
- const { axis, config, scale, state } = $$;
1009
- if (!config.subchart_show || !state.hasAxis || !scale.subX) {
1010
- return;
1011
- }
1012
- if (!state.rendered && !state.domain && config.subchart_init_range) {
1013
- state.domain = normalizeCanvasSubchartDomain($$, config.subchart_init_range);
1014
- }
1015
- const domain = normalizeCanvasSubchartDomain($$, state.domain);
1016
- if (!domain ||
1017
- !$$.withinRange(domain, $$.getZoomDomain("subX", true), $$.getZoomDomain("subX"))) {
1018
- return;
1019
- }
1020
- state.domain = domain;
1021
- scale.x.domain(domain);
1022
- axis.x.scale(scale.x);
1023
- },
1024
- /**
1025
- * Set the canvas subchart selection domain and redraw the main chart.
1026
- * @param {Array} domain Domain range
1027
- * @param {boolean} redraw Whether to redraw immediately
1028
- * @param {boolean} callCallback Whether to call subchart.onbrush
1029
- * @returns {Array|undefined} Applied domain range
1030
- * @private
1031
- */
1032
- setCanvasSubchartDomain(domain, redraw = true, callCallback = false) {
1033
- const $$ = this;
1034
- const { config, scale, state } = $$;
1035
- const nextDomain = normalizeCanvasSubchartDomain($$, domain);
1036
- if (!config.subchart_show ||
1037
- !nextDomain ||
1038
- !$$.withinRange(nextDomain, $$.getZoomDomain("subX", true), $$.getZoomDomain("subX"))) {
1039
- return undefined;
1040
- }
1041
- state.domain = nextDomain;
1042
- scale.zoom = null;
1043
- if (redraw) {
1044
- $$.redraw({
1045
- withTransition: false,
1046
- withY: config.zoom_rescale,
1047
- withSubchart: false,
1048
- withEventRect: false,
1049
- withDimension: false
1050
- });
1051
- }
1052
- callCallback && config.subchart_onbrush.bind($$.api)(state.domain);
1053
- return state.domain;
1054
- },
1055
- /**
1056
- * Clear the canvas subchart brush selection and restore the full x domain.
1057
- * @param {boolean} redraw Whether to redraw immediately
1058
- * @param {boolean} callCallback Whether to call subchart.onbrush
1059
- * @private
1060
- */
1061
- clearCanvasSubchartDomain(redraw = true, callCallback = false) {
1062
- const $$ = this;
1063
- const { axis, config, org, scale, state } = $$;
1064
- if (!config.subchart_show) {
1065
- return;
1066
- }
1067
- state.domain = undefined;
1068
- scale.zoom = null;
1069
- if (org.xDomain?.length) {
1070
- scale.x.domain(org.xDomain);
1071
- axis.x.scale(scale.x);
1072
- }
1073
- if (redraw) {
1074
- $$.redraw({
1075
- withTransition: false,
1076
- withUpdateXDomain: true,
1077
- withUpdateOrgXDomain: false,
1078
- withY: config.zoom_rescale,
1079
- withSubchart: false,
1080
- withEventRect: false,
1081
- withDimension: false
1082
- });
1083
- }
1084
- callCallback && config.subchart_onbrush.bind($$.api)(scale.x.orgDomain());
1085
- },
1086
- /**
1087
- * Finish a pending canvas flow animation before accepting another flow mutation.
1088
- * @private
1089
- */
1090
- flushCanvasFlow() {
1091
- const { state } = this;
1092
- if (!state.canvasFlowFinish) {
1093
- return;
1094
- }
1095
- state.canvasFlowFrame !== null &&
1096
- win.cancelAnimationFrame?.(state.canvasFlowFrame);
1097
- state.canvasFlowFrame = null;
1098
- state.canvasFlowFinish();
1099
- },
1100
- /**
1101
- * Animate canvas flow by interpolating the x domain, then commit the final data window.
1102
- * @param {object} flow Flow metadata
1103
- * @returns {boolean} Whether animation was started
1104
- * @private
1105
- */
1106
- animateCanvasFlow(flow) {
1107
- const $$ = this;
1108
- const { axis, data, org, scale, state } = $$;
1109
- const { done = () => { }, duration, length, orgDataCount } = flow;
1110
- const requestFrame = win.requestAnimationFrame?.bind(win);
1111
- const isLog = !!axis.isLog?.("x");
1112
- if (!requestFrame ||
1113
- !duration ||
1114
- !length ||
1115
- !orgDataCount ||
1116
- getCanvasFlowValueCount($$) > CANVAS_FLOW_ANIMATION_MAX_VALUES) {
1117
- return false;
1118
- }
1119
- const startDomain = scale.x.domain().slice(0, 2);
1120
- const startOrgDomain = org.xDomain?.slice?.();
1121
- const startSubXDomain = scale.subX?.domain?.().slice?.();
1122
- if (!isCanvasFlowDomain(startDomain, isLog)) {
1123
- return false;
1124
- }
1125
- const removed = data.targets.map(target => target.values.splice(0, length));
1126
- $$.updateXDomain($$.filterTargetsToShow(data.targets), true, true);
1127
- const endDomain = scale.x.domain().slice(0, 2);
1128
- const endOrgDomain = org.xDomain?.slice?.();
1129
- data.targets.forEach((target, index) => {
1130
- target.values.unshift(...removed[index]);
1131
- });
1132
- if (!isCanvasFlowDomain(endDomain, isLog)) {
1133
- startOrgDomain && (org.xDomain = startOrgDomain);
1134
- scale.x.domain(startDomain);
1135
- startSubXDomain && scale.subX.domain(startSubXDomain);
1136
- axis.x.scale(scale.x);
1137
- return false;
1138
- }
1139
- syncCanvasFlowYDomains($$);
1140
- let finished = false;
1141
- const started = getCanvasAnimationTime();
1142
- const finish = () => {
1143
- if (finished) {
1144
- return;
1145
- }
1146
- finished = true;
1147
- data.targets.forEach(target => {
1148
- target.values.splice(0, length);
1149
- });
1150
- endOrgDomain && (org.xDomain = endOrgDomain);
1151
- scale.x.domain(endDomain);
1152
- scale.subX?.domain?.(endOrgDomain ?? endDomain);
1153
- axis.x.scale(scale.x);
1154
- state.dirty.data = true;
1155
- state._eventRectFingerprint = null;
1156
- state.canvasShape = null;
1157
- state._cachedDrawShape = null;
1158
- $$.redraw({
1159
- withLegend: true,
1160
- withTransition: false,
1161
- withTrimXDomain: false,
1162
- withUpdateOrgXDomain: true,
1163
- withUpdateXAxis: true,
1164
- withUpdateXDomain: true
1165
- });
1166
- $$.updateTypesElements();
1167
- state.canvasFlowFrame = null;
1168
- state.canvasFlowFinish = null;
1169
- state.flowing = false;
1170
- done.call($$.api);
1171
- };
1172
- const render = (timestamp) => {
1173
- const ratio = Math.min(1, Math.max(0, (timestamp - started) / duration));
1174
- const domain = interpolateCanvasFlowDomain(startDomain, endDomain, ratio, isLog);
1175
- scale.x.domain(domain);
1176
- axis.x.scale(scale.x);
1177
- state.canvasShape = null;
1178
- state._cachedDrawShape = null;
1179
- state._canvasVisibleRangeCache = null;
1180
- state._canvasXTickValuesCache = null;
1181
- $$.renderCanvasFrame(undefined, null, false);
1182
- if (ratio < 1) {
1183
- state.canvasFlowFrame = requestFrame(render);
1184
- }
1185
- else {
1186
- finish();
1187
- }
1188
- };
1189
- startOrgDomain && (org.xDomain = startOrgDomain);
1190
- scale.x.domain(startDomain);
1191
- startSubXDomain && scale.subX.domain(startSubXDomain);
1192
- axis.x.scale(scale.x);
1193
- state.flowing = true;
1194
- state.cancelClick = true;
1195
- $$.hideTooltip?.();
1196
- state.canvasFlowFinish = finish;
1197
- state.canvasFlowFrame = requestFrame(render);
1198
- return true;
1199
- },
1200
- /**
1201
- * Initialize canvas renderers, theme, hit detector and event bindings.
1202
- * @private
1203
- */
1204
- initCanvas() {
1205
- const $$ = this;
1206
- const { config, state, $el } = $$;
1207
- const container = $el.chart.node();
1208
- state.isCanvasMode = true;
1209
- state.canvasInlineStyle.minHeight = container.style.minHeight;
1210
- if (win.getComputedStyle(container).position === "static") {
1211
- $el.chart.style("position", "relative");
1212
- }
1213
- $el.chart.style("min-height", `${state.current.height}px`);
1214
- $$.canvasEngine = new CanvasEngine();
1215
- $$.canvasEngine.init(container, state.current.width, $$.getCanvasSurfaceHeight());
1216
- $el.canvas = select($$.canvasEngine.canvas);
1217
- $$.canvasTheme = new CanvasTheme();
1218
- $$.canvasTheme.load(container, config.canvas_theme);
1219
- $$.canvasAxisRenderer = new CanvasAxisRenderer($$.canvasEngine, $$.canvasTheme);
1220
- $$.canvasRenderer = new CanvasRenderer($$.canvasEngine, $$.canvasTheme);
1221
- $$.hitDetector = new HitDetector();
1222
- $$.bindCanvasEvents();
1223
- config.zoom_enabled && $$.bindZoomEvent?.();
1224
- },
1225
- /**
1226
- * Warn about options that canvas mode does not support yet.
1227
- * @private
1228
- */
1229
- warnUnsupportedCanvasOptions() {
1230
- const { config } = this;
1231
- const unsupported = [
1232
- [
1233
- !isSupportedCanvasXType(config.axis_x_type),
1234
- "axis.x.type other than indexed/category/log/timeseries"
1235
- ],
1236
- [
1237
- !isSupportedCanvasYType(config.axis_y_type),
1238
- "axis.y.type other than indexed/log/timeseries"
1239
- ],
1240
- [
1241
- !isSupportedCanvasYType(config.axis_y2_type),
1242
- "axis.y2.type other than indexed/log/timeseries"
1243
- ],
1244
- [config.boost_useCssRule, "boost.useCssRule"],
1245
- [this.hasArcType?.(), "arc charts"],
1246
- [this.hasType?.("radar"), "radar chart"],
1247
- [this.hasType?.("polar"), "polar chart"],
1248
- [this.hasType?.("funnel"), "funnel chart"]
1249
- ];
1250
- unsupported.forEach(([condition, name]) => {
1251
- condition && warn(`canvas mode: ${name} is not yet supported.`);
1252
- });
1253
- },
1254
- /**
1255
- * Bind pointer and click handlers to the canvas surface.
1256
- * @private
1257
- */
1258
- bindCanvasEvents() {
1259
- const $$ = this;
1260
- const { config, state, $el } = $$;
1261
- const canvas = $el.canvas.node();
1262
- const preventTouchEvent = getCanvasTouchPreventer(config);
1263
- const touchOption = getCanvasTouchListenerOption(config);
1264
- canvas.addEventListener("mousemove", $$.onCanvasMouseMove.bind($$));
1265
- canvas.addEventListener("mouseenter", event => {
1266
- state.event = event;
1267
- config.onover?.bind($$.api)(event);
1268
- });
1269
- canvas.addEventListener("mouseout", $$.onCanvasMouseOut.bind($$));
1270
- canvas.addEventListener("mouseleave", event => {
1271
- state.event = event;
1272
- config.onout?.bind($$.api)(event);
1273
- });
1274
- canvas.addEventListener("mousedown", event => {
1275
- if ($$.onCanvasSubchartBrushStart?.(event)) {
1276
- return;
1277
- }
1278
- $$.onCanvasSelectionDragStart(event);
1279
- });
1280
- canvas.addEventListener("click", $$.onCanvasClick.bind($$));
1281
- canvas.addEventListener("pointerdown", $$.onCanvasPointerDown.bind($$));
1282
- canvas.addEventListener("pointerenter", $$.onCanvasPointerEnter.bind($$));
1283
- canvas.addEventListener("pointermove", $$.onCanvasPointerMove.bind($$));
1284
- canvas.addEventListener("pointerup", $$.onCanvasPointerUp.bind($$));
1285
- canvas.addEventListener("pointerleave", $$.onCanvasPointerOut.bind($$));
1286
- canvas.addEventListener("pointercancel", $$.onCanvasPointerCancel.bind($$));
1287
- if (isCanvasTouchEnabled(config)) {
1288
- canvas.addEventListener("touchstart", event => {
1289
- preventTouchEvent(event);
1290
- $$.onCanvasTouchStart(event);
1291
- }, touchOption);
1292
- canvas.addEventListener("touchmove", event => {
1293
- preventTouchEvent(event);
1294
- $$.onCanvasTouchMove(event);
1295
- }, touchOption);
1296
- canvas.addEventListener("touchend", $$.onCanvasTouchEnd.bind($$), touchOption);
1297
- canvas.addEventListener("touchcancel", $$.onCanvasTouchCancel.bind($$), touchOption);
1298
- }
1299
- },
1300
- /**
1301
- * Render and update the HTML legend used by canvas mode.
1302
- * @private
1303
- */
1304
- updateHtmlLegend() {
1305
- const $$ = this;
1306
- const { config, state, $el } = $$;
1307
- const chart = $el.chart.node();
1308
- if (!config.legend_show || state.hasTreemap) {
1309
- if (state.hasTreemap) {
1310
- $el.legend?.remove();
1311
- $el.legend = null;
1312
- }
1313
- else {
1314
- $el.legend?.style("visibility", "hidden");
1315
- }
1316
- state.legendItemWidth = 0;
1317
- state.legendItemHeight = 0;
1318
- state.legendStep = 0;
1319
- return;
1320
- }
1321
- const targetIds = $$.mapToIds($$.data.targets)
1322
- .filter(id => config.data_names[id] !== null);
1323
- if (config.legend_contents_bindto && config.legend_contents_template) {
1324
- if ($$.updateHtmlLegendTemplate(targetIds)) {
1325
- state.legendItemWidth = 0;
1326
- state.legendItemHeight = 0;
1327
- state.legendStep = 0;
1328
- state.legendHasRendered = true;
1329
- }
1330
- else {
1331
- state.legendItemWidth = 0;
1332
- state.legendItemHeight = 0;
1333
- state.legendStep = 0;
1334
- }
1335
- return;
1336
- }
1337
- if (!$el.legend) {
1338
- $el.legend = select(chart)
1339
- .append("div")
1340
- .classed($LEGEND.legend, true)
1341
- .classed($CANVAS.legend, true);
1342
- }
1343
- $el.legend.style("visibility", null);
1344
- const legendItems = $el.legend
1345
- .selectAll(`button.${$LEGEND.legendItem}`)
1346
- .data(targetIds, (id) => id);
1347
- legendItems.exit().remove();
1348
- const enter = legendItems.enter()
1349
- .append("button")
1350
- .attr("type", "button")
1351
- .attr("data-id", id => id);
1352
- enter.append("span")
1353
- .classed($LEGEND.legendItemTile, true);
1354
- enter.append("span")
1355
- .classed($CANVAS.legendItemTitle, true);
1356
- const item = enter.merge(legendItems)
1357
- .attr("class", id => $$.generateClass($LEGEND.legendItem, id).trim());
1358
- setCanvasHtmlLegendItem($$, item);
1359
- item.select(`.${$LEGEND.legendItemTile}`)
1360
- .classed($CANVAS.legendItemTileCircle, !config.legend_usePoint && config.legend_item_tile_type === "circle")
1361
- .style("background-color", id => (config.legend_usePoint ? null : $$.color(id)))
1362
- .html(id => (config.legend_usePoint ? getCanvasLegendPointIcon($$, id) : ""));
1363
- item.select(`.${$CANVAS.legendItemTitle}`)
1364
- .text(id => getLegendText($$, id));
1365
- if (config.legend_tooltip) {
1366
- item.attr("title", id => getLegendText($$, id));
1367
- }
1368
- bindCanvasHtmlLegendInteractions($$, item);
1369
- $$.updateHtmlLegendSize(targetIds);
1370
- $$.positionHtmlLegend();
1371
- state.legendHasRendered = true;
1372
- },
1373
- /**
1374
- * Render canvas mode legend into custom HTML template container.
1375
- * @param {Array} targetIds Legend target ids
1376
- * @returns {boolean} Whether template legend was rendered
1377
- * @private
1378
- */
1379
- updateHtmlLegendTemplate(targetIds) {
1380
- const $$ = this;
1381
- const { api, config, $el } = $$;
1382
- const wrapper = select(config.legend_contents_bindto);
1383
- const template = config.legend_contents_template;
1384
- const ids = [];
1385
- let html = "";
1386
- if (wrapper.empty()) {
1387
- return false;
1388
- }
1389
- targetIds.forEach(id => {
1390
- const content = isFunction(template) ?
1391
- sanitize(template.call(api, id, $$.color(id), api.data(id)[0].values)) :
1392
- tplProcess(template, {
1393
- COLOR: $$.color(id),
1394
- TITLE: id
1395
- });
1396
- if (content) {
1397
- ids.push(id);
1398
- html += content;
1399
- }
1400
- });
1401
- const legendItem = wrapper
1402
- .html(html)
1403
- .classed($LEGEND.legend, true)
1404
- .classed($CANVAS.legend, false)
1405
- .style("visibility", null)
1406
- .selectAll(function () {
1407
- return this.children;
1408
- })
1409
- .data(ids);
1410
- setCanvasHtmlLegendItem($$, legendItem);
1411
- bindCanvasHtmlLegendInteractions($$, legendItem);
1412
- $el.legend = wrapper;
1413
- return true;
1414
- },
1415
- /**
1416
- * Measure HTML legend items and update legend layout state.
1417
- * @param {Array} targetIds Visible legend target ids
1418
- * @private
1419
- */
1420
- updateHtmlLegendSize(targetIds) {
1421
- const $$ = this;
1422
- const { config, state, $el } = $$;
1423
- const itemSizes = [];
1424
- const itemLayouts = {};
1425
- let maxWidth = 0;
1426
- let maxHeight = 0;
1427
- let legendStep = 0;
1428
- const useTemplateLegend = config.legend_contents_bindto && config.legend_contents_template;
1429
- if (useTemplateLegend) {
1430
- $el.legend.selectAll(`.${$LEGEND.legendItem}`)
1431
- .each(function (id) {
1432
- const rect = getBoundingRect(this, true);
1433
- const text = `${getLegendText($$, id)}`;
1434
- const fallbackWidth = Math.max(32, text.length * 7 + 24);
1435
- const fallbackHeight = 20;
1436
- const width = Math.ceil(rect.width || fallbackWidth);
1437
- const height = Math.ceil(rect.height || fallbackHeight);
1438
- itemSizes.push(width);
1439
- maxWidth = Math.max(maxWidth, width);
1440
- maxHeight = Math.max(maxHeight, height);
1441
- });
1442
- }
1443
- else if (targetIds.length) {
1444
- const isRightOrInset = state.isLegendRight || state.isLegendInset;
1445
- const isRectangle = config.legend_item_tile_type !== "circle";
1446
- const itemTileSize = {
1447
- width: isRectangle ? config.legend_item_tile_width : config.legend_item_tile_r * 2,
1448
- height: isRectangle ? config.legend_item_tile_height : config.legend_item_tile_r * 2
1449
- };
1450
- const dimension = {
1451
- padding: {
1452
- top: 4,
1453
- right: 10
1454
- },
1455
- max: {
1456
- width: 0,
1457
- height: 0
1458
- },
1459
- posMin: 10,
1460
- step: 0,
1461
- tileWidth: itemTileSize.width + 5,
1462
- totalLength: 0
1463
- };
1464
- const sizes = {
1465
- offsets: {},
1466
- widths: {},
1467
- heights: {},
1468
- margins: [0],
1469
- steps: {}
1470
- };
1471
- const measured = targetIds.map((id, index) => {
1472
- const text = `${getLegendText($$, id)}`;
1473
- const rect = measureSvgLegendText($$, text);
1474
- const fallbackWidth = Math.max(32, text.length * 7);
1475
- const fallbackHeight = 12;
1476
- const isLast = index === targetIds.length - 1;
1477
- const hidden = config.legend_show && !$$.isLegendToShow(id);
1478
- const width = hidden ? 0 : ((rect?.width || fallbackWidth) +
1479
- dimension.tileWidth +
1480
- (isLast && !isRightOrInset ? 0 : dimension.padding.right) +
1481
- config.legend_padding);
1482
- const height = hidden ? 0 : (rect?.height || fallbackHeight) +
1483
- dimension.padding.top;
1484
- dimension.max.width = Math.max(dimension.max.width, width);
1485
- dimension.max.height = Math.max(dimension.max.height, height);
1486
- return {
1487
- id,
1488
- hidden,
1489
- width,
1490
- height
1491
- };
1492
- });
1493
- const areaLength = isRightOrInset ? $$.getLegendHeight() : $$.getLegendWidth();
1494
- const updateValues = (id, itemLength, withoutStep = false) => {
1495
- let margin;
1496
- if (!withoutStep) {
1497
- margin = (areaLength - dimension.totalLength - itemLength) / 2;
1498
- if (margin < dimension.posMin) {
1499
- margin = (areaLength - itemLength) / 2;
1500
- dimension.totalLength = 0;
1501
- dimension.step++;
1502
- }
1503
- }
1504
- sizes.steps[id] = dimension.step;
1505
- sizes.margins[dimension.step] = state.isLegendInset ? 10 : margin;
1506
- sizes.offsets[id] = dimension.totalLength;
1507
- dimension.totalLength += itemLength;
1508
- };
1509
- if (state.isLegendInset) {
1510
- dimension.step = config.legend_inset_step ?
1511
- config.legend_inset_step :
1512
- targetIds.length;
1513
- state.legendStep = dimension.step;
1514
- }
1515
- measured.forEach(({ id, hidden, width, height }) => {
1516
- const itemWidth = config.legend_equally && !hidden ? dimension.max.width : width;
1517
- const itemHeight = config.legend_equally && !hidden ? dimension.max.height : height;
1518
- const itemLength = isRightOrInset ? itemHeight : itemWidth;
1519
- sizes.widths[id] = itemWidth;
1520
- sizes.heights[id] = itemHeight;
1521
- itemSizes.push(itemWidth);
1522
- maxWidth = Math.max(maxWidth, itemWidth);
1523
- maxHeight = Math.max(maxHeight, itemHeight);
1524
- if (hidden) {
1525
- sizes.steps[id] = 0;
1526
- sizes.offsets[id] = 0;
1527
- return;
1528
- }
1529
- updateValues(id, itemLength);
1530
- });
1531
- const xForLegend = state.isLegendRight ?
1532
- (id) => dimension.max.width * sizes.steps[id] :
1533
- state.isLegendInset ?
1534
- (id) => dimension.max.width * sizes.steps[id] + 10 :
1535
- (id) => sizes.margins[sizes.steps[id]] + sizes.offsets[id];
1536
- const yForLegend = state.isLegendRight || state.isLegendInset ?
1537
- (id) => sizes.margins[sizes.steps[id]] + sizes.offsets[id] :
1538
- (id) => dimension.max.height * sizes.steps[id];
1539
- const titleX = 4 + itemTileSize.width;
1540
- const tileCenterY = 9;
1541
- measured.forEach(({ id, hidden }) => {
1542
- const x = hidden ? 0 : xForLegend(id);
1543
- const y = hidden ? 0 : yForLegend(id);
1544
- itemLayouts[id] = {
1545
- item: {
1546
- x,
1547
- y: y - 5,
1548
- width: sizes.widths[id],
1549
- height: sizes.heights[id]
1550
- },
1551
- title: {
1552
- x: titleX,
1553
- y: 0,
1554
- height: sizes.heights[id]
1555
- },
1556
- tile: {
1557
- x: -2,
1558
- y: tileCenterY - (itemTileSize.height / 2),
1559
- width: itemTileSize.width,
1560
- height: itemTileSize.height
1561
- }
1562
- };
1563
- });
1564
- legendStep = dimension.step;
1565
- }
1566
- if (!targetIds.length) {
1567
- state.legendItemWidth = 0;
1568
- state.legendItemHeight = 0;
1569
- state.legendStep = 0;
1570
- return;
1571
- }
1572
- if (useTemplateLegend) {
1573
- const availableWidth = Math.max(1, state.current.width);
1574
- const rowGap = 10;
1575
- let rows = 1;
1576
- let rowWidth = 0;
1577
- itemSizes.forEach(width => {
1578
- if (rowWidth && rowWidth + rowGap + width > availableWidth) {
1579
- rows++;
1580
- rowWidth = width;
1581
- }
1582
- else {
1583
- rowWidth += (rowWidth ? rowGap : 0) + width;
1584
- }
1585
- });
1586
- state.legendStep = Math.max(0, rows - 1);
1587
- }
1588
- else {
1589
- state.legendStep = legendStep;
1590
- }
1591
- state.legendItemWidth = maxWidth;
1592
- state.legendItemHeight = Math.max(12, maxHeight);
1593
- if (!useTemplateLegend) {
1594
- $el.legend.selectAll(`button.${$LEGEND.legendItem}`)
1595
- .each(function (id) {
1596
- const layout = itemLayouts[id];
1597
- const item = select(this);
1598
- if (!layout) {
1599
- return;
1600
- }
1601
- item
1602
- .style("left", `${layout.item.x}px`)
1603
- .style("top", `${layout.item.y}px`)
1604
- .style("width", `${layout.item.width}px`)
1605
- .style("height", `${layout.item.height}px`);
1606
- item.select(`.${$CANVAS.legendItemTitle}`)
1607
- .style("left", `${layout.title.x}px`)
1608
- .style("top", `${layout.title.y}px`)
1609
- .style("height", `${layout.title.height}px`)
1610
- .style("line-height", `${layout.title.height}px`);
1611
- item.select(`.${$LEGEND.legendItemTile}`)
1612
- .style("left", `${layout.tile.x}px`)
1613
- .style("top", `${layout.tile.y}px`)
1614
- .style("width", `${layout.tile.width}px`)
1615
- .style("height", `${layout.tile.height}px`);
1616
- });
1617
- }
1618
- },
1619
- /**
1620
- * Get bottom legend block height separated from the canvas drawing surface.
1621
- * @returns {number} Legend block height
1622
- * @private
1623
- */
1624
- getCanvasBottomLegendHeight() {
1625
- const $$ = this;
1626
- const { config, state, $el } = $$;
1627
- if (!config.legend_show ||
1628
- state.isLegendRight ||
1629
- state.isLegendInset ||
1630
- state.hasTreemap ||
1631
- !$el.legend ||
1632
- !state.legendItemHeight) {
1633
- return 0;
1634
- }
1635
- const rectHeight = getBoundingRect($el.legend.node(), true).height;
1636
- const rowHeight = state.legendItemHeight * (state.legendStep + 1);
1637
- return Math.ceil(Math.max($$.getLegendHeight?.() || 0, rectHeight || rowHeight));
1638
- },
1639
- /**
1640
- * Get canvas drawing surface height excluding separately rendered bottom legend DOM.
1641
- * @returns {number} Canvas drawing surface height
1642
- * @private
1643
- */
1644
- getCanvasSurfaceHeight() {
1645
- const $$ = this;
1646
- return Math.max(0, $$.state.current.height - $$.getCanvasBottomLegendHeight());
1647
- },
1648
- /**
1649
- * Position the HTML legend around or inside the canvas chart.
1650
- * @private
1651
- */
1652
- positionHtmlLegend() {
1653
- const $$ = this;
1654
- const { config, state, $el } = $$;
1655
- const legend = $el.legend;
1656
- legend
1657
- .classed($CANVAS.legendBottom, !state.isLegendRight && !state.isLegendInset)
1658
- .classed($CANVAS.legendRight, state.isLegendRight)
1659
- .classed($CANVAS.legendInset, state.isLegendInset)
1660
- .style("top", null)
1661
- .style("right", null)
1662
- .style("bottom", null)
1663
- .style("left", null)
1664
- .style("width", null)
1665
- .style("height", null)
1666
- .style("min-height", null);
1667
- if (state.isLegendRight) {
1668
- legend
1669
- .style("top", `${state.margin3.top}px`)
1670
- .style("right", "0")
1671
- .style("bottom", `${state.margin3.bottom}px`)
1672
- .style("width", `${Math.max(0, $$.getLegendWidth())}px`);
1673
- }
1674
- else if (!state.isLegendInset) {
1675
- const legendHeight = $$.getLegendHeight?.() || 0;
1676
- legend
1677
- .style("top", `${Math.max(0, state.current.height - legendHeight)}px`)
1678
- .style("right", "0")
1679
- .style("bottom", "auto")
1680
- .style("left", "0");
1681
- }
1682
- else if (state.isLegendInset) {
1683
- const isTop = state.isLegendTop;
1684
- const isLeft = state.isLegendLeft;
1685
- legend
1686
- .style(isTop ? "top" : "bottom", `${config.legend_inset_y}px`)
1687
- .style(isLeft ? "left" : "right", `${config.legend_inset_x}px`)
1688
- .style("width", `${Math.max(0, state.legendItemWidth * (state.legendStep + 1) + 20)}px`);
1689
- }
1690
- },
1691
- /**
1692
- * Get selected canvas data rows.
1693
- * @param {string} targetId Target id
1694
- * @returns {Array} Selected rows
1695
- * @private
1696
- */
1697
- getCanvasSelectedData(targetId) {
1698
- const $$ = this;
1699
- const selected = $$.state.canvasSelection;
1700
- const data = [];
1701
- if (!$$.config.data_selection_enabled || !selected?.size) {
1702
- return data;
1703
- }
1704
- eachCanvasSelectableData($$, d => {
1705
- (!targetId || d.id === targetId) &&
1706
- selected.has(getCanvasDataKey(d)) &&
1707
- data.push(d);
1708
- });
1709
- return data;
1710
- },
1711
- /**
1712
- * Select or unselect canvas data rows.
1713
- * @param {boolean} isSelection Whether to select
1714
- * @param {string|Array} ids Target ids
1715
- * @param {Array} indices Target indices
1716
- * @param {boolean} resetOther Whether to reset unrelated selections
1717
- * @private
1718
- */
1719
- setCanvasSelection(isSelection = false, ids, indices, resetOther) {
1720
- const $$ = this;
1721
- const { config, state } = $$;
1722
- const selected = state.canvasSelection;
1723
- const selectionGrouped = config.data_selection_grouped;
1724
- const targetIds = getCanvasSelectionIds(ids);
1725
- let changed = false;
1726
- if (!config.data_selection_enabled) {
1727
- return;
1728
- }
1729
- eachCanvasSelectableData($$, d => {
1730
- const key = getCanvasDataKey(d);
1731
- const isTargetId = selectionGrouped || !targetIds || targetIds.indexOf(d.id) >= 0;
1732
- const isTargetIndex = !indices || indices.indexOf(d.index) >= 0;
1733
- const isSelected = selected.has(key);
1734
- if (isSelection) {
1735
- if (isTargetId && isTargetIndex && !isSelected) {
1736
- selected.add(key);
1737
- callFn(config.data_onselected, $$.api, d, $$.canvasEngine.canvas);
1738
- changed = true;
1739
- }
1740
- else if (resetOther && isSelected) {
1741
- selected.delete(key);
1742
- callFn(config.data_onunselected, $$.api, d, $$.canvasEngine.canvas);
1743
- changed = true;
1744
- }
1745
- }
1746
- else if (isTargetId && isTargetIndex && isSelected) {
1747
- selected.delete(key);
1748
- callFn(config.data_onunselected, $$.api, d, $$.canvasEngine.canvas);
1749
- changed = true;
1750
- }
1751
- });
1752
- changed && $$.renderCanvasFrame?.(undefined, null, false);
1753
- },
1754
- /**
1755
- * Toggle canvas data selection from a click.
1756
- * @param {Array} dataRows Data rows to toggle
1757
- * @private
1758
- */
1759
- toggleCanvasSelection(dataRows) {
1760
- const $$ = this;
1761
- const { config, state } = $$;
1762
- const selected = state.canvasSelection;
1763
- let changed = false;
1764
- if (!config.data_selection_enabled) {
1765
- return;
1766
- }
1767
- dataRows
1768
- .filter(d => isCanvasSelectableData($$, d))
1769
- .forEach(d => {
1770
- const key = getCanvasDataKey(d);
1771
- const isSelected = selected.has(key);
1772
- if (!config.data_selection_multiple) {
1773
- eachCanvasSelectableData($$, selectedData => {
1774
- const selectedKey = getCanvasDataKey(selectedData);
1775
- const shouldReset = config.data_selection_grouped ?
1776
- selectedData.id === d.id :
1777
- selectedKey !== key;
1778
- if (shouldReset && selected.has(selectedKey)) {
1779
- selected.delete(selectedKey);
1780
- callFn(config.data_onunselected, $$.api, selectedData, $$.canvasEngine.canvas);
1781
- changed = true;
1782
- }
1783
- });
1784
- }
1785
- if (isSelected && selected.has(key)) {
1786
- selected.delete(key);
1787
- callFn(config.data_onunselected, $$.api, d, $$.canvasEngine.canvas);
1788
- }
1789
- else {
1790
- selected.add(key);
1791
- callFn(config.data_onselected, $$.api, d, $$.canvasEngine.canvas);
1792
- }
1793
- changed = true;
1794
- });
1795
- changed && $$.renderCanvasFrame?.(undefined, null, false);
1796
- },
1797
- /**
1798
- * Check whether canvas draggable selection can start.
1799
- * @param {MouseEvent|TouchEvent} event Input event
1800
- * @returns {boolean} Whether drag selection can start
1801
- * @private
1802
- */
1803
- canStartCanvasSelectionDrag(event) {
1804
- const $$ = this;
1805
- const { config } = $$;
1806
- const mouse = event;
1807
- return Boolean(config.interaction_enabled &&
1808
- config.data_selection_enabled &&
1809
- config.data_selection_draggable &&
1810
- config.data_selection_multiple &&
1811
- !config.zoom_enabled &&
1812
- (mouse.button === undefined || mouse.button === 0));
1813
- },
1814
- /**
1815
- * Get the selected data rows inside the current canvas drag rectangle.
1816
- * @param {object} rect Canvas rectangle
1817
- * @returns {Array} Included rows
1818
- * @private
1819
- */
1820
- getCanvasSelectionDragData(rect) {
1821
- const $$ = this;
1822
- const { config } = $$;
1823
- const data = $$.hitDetector.findInRect(rect, config.data_selection_grouped);
1824
- if (!config.data_selection_grouped) {
1825
- return data;
1826
- }
1827
- const indices = new Set(data.map(d => d.index));
1828
- return $$.filterTargetsToShow($$.data.targets)
1829
- .flatMap(target => target.values.filter(d => indices.has(d.index)));
1830
- },
1831
- /**
1832
- * Start canvas draggable selection.
1833
- * @param {MouseEvent|TouchEvent} event Input event
1834
- * @returns {boolean} Whether drag started
1835
- * @private
1836
- */
1837
- startCanvasSelectionDrag(event) {
1838
- const $$ = this;
1839
- const { state } = $$;
1840
- const point = getCanvasEventPoint($$, event);
1841
- if (!point || !$$.canStartCanvasSelectionDrag(event)) {
1842
- return false;
1843
- }
1844
- state.dragStart = point;
1845
- state.canvasSelectionDragStart = point;
1846
- state.canvasSelectionDragIncluded = new Set();
1847
- state.canvasSelectionDragging = true;
1848
- state.canvasSelectionDragMoved = false;
1849
- canvasSelectionDragRows.set($$, new Map());
1850
- $$.setDragStatus(true);
1851
- $$.hideTooltip?.();
1852
- event.preventDefault?.();
1853
- return true;
1854
- },
1855
- /**
1856
- * Update canvas draggable selection.
1857
- * @param {MouseEvent|TouchEvent} event Input event
1858
- * @returns {boolean} Whether drag was handled
1859
- * @private
1860
- */
1861
- updateCanvasSelectionDrag(event) {
1862
- const $$ = this;
1863
- const { config, state } = $$;
1864
- const start = state.canvasSelectionDragStart;
1865
- const point = getCanvasEventPoint($$, event);
1866
- if (!state.canvasSelectionDragging || !start || !point) {
1867
- return false;
1868
- }
1869
- const [sx, sy] = start;
1870
- const [mx, my] = point;
1871
- const minX = Math.min(sx, mx);
1872
- const maxX = Math.max(sx, mx);
1873
- const minY = config.data_selection_grouped ? state.margin.top : Math.min(sy, my);
1874
- const maxY = config.data_selection_grouped ?
1875
- state.margin.top + state.height :
1876
- Math.max(sy, my);
1877
- const rect = {
1878
- x: minX,
1879
- y: minY,
1880
- w: maxX - minX,
1881
- h: maxY - minY
1882
- };
1883
- const moved = Math.abs(mx - sx) > 4 || Math.abs(my - sy) > 4;
1884
- state.canvasSelectionDragMoved = state.canvasSelectionDragMoved || moved;
1885
- if (moved) {
1886
- const { included, rows } = getCanvasSelectionDragDelta($$, $$.getCanvasSelectionDragData(rect));
1887
- rows.length && $$.toggleCanvasSelection(rows);
1888
- state.canvasSelectionDragIncluded = included;
1889
- state.cancelClick = true;
1890
- }
1891
- $$.renderCanvasSelectionDrag(rect);
1892
- event.preventDefault?.();
1893
- return true;
1894
- },
1895
- /**
1896
- * End canvas draggable selection.
1897
- * @param {MouseEvent|TouchEvent} event Input event
1898
- * @returns {boolean} Whether drag ended
1899
- * @private
1900
- */
1901
- endCanvasSelectionDrag(event) {
1902
- const $$ = this;
1903
- const { state } = $$;
1904
- if (!state.canvasSelectionDragging) {
1905
- return false;
1906
- }
1907
- $$.updateCanvasSelectionDrag(event);
1908
- state.cancelClick = state.cancelClick || state.canvasSelectionDragMoved;
1909
- state.dragStart = null;
1910
- state.canvasSelectionDragStart = null;
1911
- state.canvasSelectionDragIncluded = new Set();
1912
- state.canvasSelectionDragging = false;
1913
- state.canvasSelectionDragMoved = false;
1914
- canvasSelectionDragRows.delete($$);
1915
- $$.setDragStatus(false);
1916
- $$.clearCanvasFocus();
1917
- event.preventDefault?.();
1918
- return true;
1919
- },
1920
- /**
1921
- * Dispatch canvas data.onout callback for the current hovered row.
1922
- * @param {HTMLCanvasElement} canvas Canvas element
1923
- * @private
1924
- */
1925
- dispatchCanvasDataOut(canvas) {
1926
- const $$ = this;
1927
- const { config, state } = $$;
1928
- const d = state.canvasDataHover;
1929
- if (!d) {
1930
- return;
1931
- }
1932
- state.canvasDataHover = null;
1933
- state.canvasDataHoverKey = null;
1934
- config.interaction_enabled && callFn(config.data_onout, $$.api, d, canvas);
1935
- },
1936
- /**
1937
- * Dispatch canvas data.onover callback when the hovered row changes.
1938
- * @param {object} d Data row
1939
- * @param {HTMLCanvasElement} canvas Canvas element
1940
- * @private
1941
- */
1942
- dispatchCanvasDataOver(d, canvas) {
1943
- const $$ = this;
1944
- const { config, state } = $$;
1945
- const key = getCanvasDataKey(d);
1946
- if (state.canvasDataHoverKey === key) {
1947
- return;
1948
- }
1949
- $$.dispatchCanvasDataOut(canvas);
1950
- state.canvasDataHover = d;
1951
- state.canvasDataHoverKey = key;
1952
- config.interaction_enabled && d && callFn(config.data_onover, $$.api, d, canvas);
1953
- },
1954
- /**
1955
- * Dispatch canvas data.onclick callback for a pointer position.
1956
- * @param {Event} event Input event
1957
- * @param {boolean} markInputClick Whether to suppress following compatibility click
1958
- * @returns {object|null} Clicked data row
1959
- * @private
1960
- */
1961
- dispatchCanvasDataClick(event, markInputClick = false) {
1962
- const $$ = this;
1963
- const { config, $el } = $$;
1964
- const canvas = $el.canvas.node();
1965
- const d = getCanvasEventDatum($$, event, true);
1966
- if (!d || isDuplicateCanvasInputClick($$, d)) {
1967
- return d;
1968
- }
1969
- if (config.interaction_enabled) {
1970
- const dataRows = config.data_selection_grouped ?
1971
- $$.filterTargetsToShow($$.data.targets)
1972
- .map(target => target.values[d.index])
1973
- .filter(Boolean) :
1974
- [d];
1975
- $$.toggleCanvasSelection?.(dataRows);
1976
- dataRows.forEach(row => callFn(config.data_onclick, $$.api, row, canvas));
1977
- markInputClick && markCanvasInputClick($$, d);
1978
- }
1979
- return d;
1980
- },
1981
- /**
1982
- * Update canvas subchart brush domain from an input event.
1983
- * @param {Event} event Input event
1984
- * @returns {boolean} Whether the brush was updated
1985
- * @private
1986
- */
1987
- updateCanvasSubchartBrush(event) {
1988
- const $$ = this;
1989
- const { state } = $$;
1990
- const start = state.canvasSubchartBrushStart;
1991
- const origin = state.canvasSubchartBrushOrigin;
1992
- const mode = state.canvasSubchartBrushMode;
1993
- const coord = getCanvasSubchartBrushCoord($$, event, true);
1994
- if (!state.canvasSubchartBrushDragging || start === null || coord === null || !mode) {
1995
- return false;
1996
- }
1997
- const delta = coord - start;
1998
- if (Math.abs(delta) > CANVAS_SUBCHART_CLICK_TOLERANCE) {
1999
- state.canvasSubchartBrushMoved = true;
2000
- }
2001
- if (!state.canvasSubchartBrushMoved) {
2002
- event.preventDefault?.();
2003
- return true;
2004
- }
2005
- let selection;
2006
- if (mode === "move" && origin) {
2007
- const [extentStart, extentEnd] = getCanvasSubchartBrushExtent($$);
2008
- const size = origin[1] - origin[0];
2009
- let nextStart = origin[0] + delta;
2010
- let nextEnd = origin[1] + delta;
2011
- if (nextStart < extentStart) {
2012
- nextEnd += extentStart - nextStart;
2013
- nextStart = extentStart;
2014
- }
2015
- if (nextEnd > extentEnd) {
2016
- nextStart -= nextEnd - extentEnd;
2017
- nextEnd = extentEnd;
2018
- }
2019
- selection = [
2020
- Math.max(extentStart, Math.min(extentEnd - size, nextStart)),
2021
- Math.min(extentEnd, Math.max(extentStart + size, nextEnd))
2022
- ];
2023
- }
2024
- else if (mode === "resize-start" && origin) {
2025
- selection = clampCanvasSubchartSelection($$, coord, origin[1]);
2026
- }
2027
- else if (mode === "resize-end" && origin) {
2028
- selection = clampCanvasSubchartSelection($$, origin[0], coord);
2029
- }
2030
- else {
2031
- selection = clampCanvasSubchartSelection($$, start, coord);
2032
- }
2033
- const domain = getCanvasSubchartDomainFromCoords($$, selection[0], selection[1]);
2034
- $$.setCanvasSubchartDomain(domain, true);
2035
- state.cancelClick = true;
2036
- event.preventDefault?.();
2037
- return true;
2038
- },
2039
- /**
2040
- * Update cursor while hovering over the canvas subchart brush area.
2041
- * @param {Event} event Input event
2042
- * @returns {boolean} Whether the pointer is over the subchart
2043
- * @private
2044
- */
2045
- updateCanvasSubchartCursor(event) {
2046
- const $$ = this;
2047
- const canvas = $$.$el.canvas.node();
2048
- const coord = getCanvasSubchartBrushCoord($$, event);
2049
- if (coord === null) {
2050
- canvas.style.cursor = "";
2051
- return false;
2052
- }
2053
- const mode = getCanvasSubchartBrushMode($$, coord);
2054
- canvas.style.cursor = getCanvasSubchartCursor($$, mode);
2055
- return true;
2056
- },
2057
- /**
2058
- * Start a canvas subchart brush gesture.
2059
- * @param {Event} event Mouse, pointer or touch event
2060
- * @returns {boolean} Whether brushing started
2061
- * @private
2062
- */
2063
- startCanvasSubchartBrush(event) {
2064
- const $$ = this;
2065
- const { state } = $$;
2066
- const coord = getCanvasSubchartBrushCoord($$, event);
2067
- if (coord === null) {
2068
- return false;
2069
- }
2070
- const mode = getCanvasSubchartBrushMode($$, coord);
2071
- state.event = event;
2072
- state.canvasSubchartBrushDragging = true;
2073
- state.canvasSubchartBrushMode = mode;
2074
- state.canvasSubchartBrushStart = coord;
2075
- state.canvasSubchartBrushOrigin = getCanvasSubchartBrushSelection($$);
2076
- state.canvasSubchartBrushMoved = false;
2077
- state.cancelClick = true;
2078
- $$.setDragStatus(true);
2079
- event.preventDefault?.();
2080
- return true;
2081
- },
2082
- /**
2083
- * End a canvas subchart brush gesture.
2084
- * @param {Event} event Mouse, pointer or touch event
2085
- * @returns {boolean} Whether brushing ended
2086
- * @private
2087
- */
2088
- endCanvasSubchartBrush(event) {
2089
- const $$ = this;
2090
- const { state } = $$;
2091
- if (!state.canvasSubchartBrushDragging) {
2092
- return false;
2093
- }
2094
- $$.updateCanvasSubchartBrush(event);
2095
- const shouldClear = state.canvasSubchartBrushMode === "select" &&
2096
- !state.canvasSubchartBrushMoved;
2097
- const shouldCallback = state.canvasSubchartBrushMoved || shouldClear;
2098
- if (shouldClear) {
2099
- $$.clearCanvasSubchartDomain?.(true, true);
2100
- }
2101
- else if (shouldCallback) {
2102
- $$.config.subchart_onbrush.bind($$.api)(state.domain ?? $$.scale.x.orgDomain());
2103
- }
2104
- state.canvasSubchartBrushDragging = false;
2105
- state.canvasSubchartBrushMode = null;
2106
- state.canvasSubchartBrushStart = null;
2107
- state.canvasSubchartBrushOrigin = null;
2108
- state.canvasSubchartBrushMoved = false;
2109
- $$.setDragStatus(false);
2110
- event.preventDefault?.();
2111
- return true;
2112
- },
2113
- /**
2114
- * Cancel a canvas subchart brush gesture without applying callbacks.
2115
- * @param {Event} event Mouse, pointer or touch event
2116
- * @returns {boolean} Whether brushing was cancelled
2117
- * @private
2118
- */
2119
- cancelCanvasSubchartBrush(event) {
2120
- const $$ = this;
2121
- const { state } = $$;
2122
- if (!state.canvasSubchartBrushDragging) {
2123
- return false;
2124
- }
2125
- state.canvasSubchartBrushDragging = false;
2126
- state.canvasSubchartBrushMode = null;
2127
- state.canvasSubchartBrushStart = null;
2128
- state.canvasSubchartBrushOrigin = null;
2129
- state.canvasSubchartBrushMoved = false;
2130
- $$.setDragStatus(false);
2131
- event.preventDefault?.();
2132
- return true;
2133
- },
2134
- /**
2135
- * Start mouse-driven canvas subchart brushing.
2136
- * @param {MouseEvent} event Mouse event
2137
- * @returns {boolean} Whether brushing started
2138
- * @private
2139
- */
2140
- onCanvasSubchartBrushStart(event) {
2141
- const $$ = this;
2142
- if (!$$.startCanvasSubchartBrush(event)) {
2143
- return false;
2144
- }
2145
- const move = (event) => {
2146
- $$.updateCanvasSubchartBrush(event);
2147
- };
2148
- const end = (event) => {
2149
- $$.endCanvasSubchartBrush(event);
2150
- win.removeEventListener("mousemove", move);
2151
- win.removeEventListener("mouseup", end);
2152
- };
2153
- win.addEventListener("mousemove", move);
2154
- win.addEventListener("mouseup", end);
2155
- return true;
2156
- },
2157
- /**
2158
- * Handle canvas click and dispatch shape-level data onclick.
2159
- * @param {MouseEvent} event Mouse click event
2160
- * @private
2161
- */
2162
- onCanvasClick(event) {
2163
- const $$ = this;
2164
- const { config, state } = $$;
2165
- state.event = event;
2166
- if (state.flowing || state.cancelClick) {
2167
- state.cancelClick = false;
2168
- return;
2169
- }
2170
- $$.dispatchCanvasDataClick(event);
2171
- config.onclick?.bind($$.api)(event);
2172
- },
2173
- /**
2174
- * Start mouse-driven canvas draggable selection.
2175
- * @param {MouseEvent} event Mouse event
2176
- * @private
2177
- */
2178
- onCanvasSelectionDragStart(event) {
2179
- const $$ = this;
2180
- const { state } = $$;
2181
- if (!$$.startCanvasSelectionDrag(event)) {
2182
- return;
2183
- }
2184
- const move = (event) => {
2185
- $$.updateCanvasSelectionDrag(event);
2186
- };
2187
- const end = (event) => {
2188
- $$.endCanvasSelectionDrag(event);
2189
- win.removeEventListener("mousemove", move);
2190
- win.removeEventListener("mouseup", end);
2191
- state.canvasSelectionDragMoveHandler = null;
2192
- state.canvasSelectionDragEndHandler = null;
2193
- };
2194
- state.canvasSelectionDragMoveHandler = move;
2195
- state.canvasSelectionDragEndHandler = end;
2196
- win.addEventListener("mousemove", move);
2197
- win.addEventListener("mouseup", end);
2198
- },
2199
- /**
2200
- * Start non-mouse pointer-driven canvas subchart brushing.
2201
- * @param {PointerEvent} event Pointer event
2202
- * @private
2203
- */
2204
- onCanvasPointerDown(event) {
2205
- if (!shouldHandleCanvasPointerEvent(this, event)) {
2206
- return;
2207
- }
2208
- const $$ = this;
2209
- const canvas = $$.$el.canvas.node();
2210
- if (!$$.startCanvasSubchartBrush(event)) {
2211
- return;
2212
- }
2213
- const pointerId = event.pointerId;
2214
- const matchesPointer = (event) => event.pointerId === pointerId;
2215
- const move = (event) => {
2216
- matchesPointer(event) && $$.updateCanvasSubchartBrush(event);
2217
- };
2218
- const end = (event) => {
2219
- if (matchesPointer(event)) {
2220
- $$.endCanvasSubchartBrush(event);
2221
- cleanup();
2222
- }
2223
- };
2224
- const cancel = (event) => {
2225
- if (matchesPointer(event)) {
2226
- $$.cancelCanvasSubchartBrush(event);
2227
- cleanup();
2228
- }
2229
- };
2230
- /**
2231
- * Remove temporary pointer brush listeners.
2232
- * @private
2233
- */
2234
- function cleanup() {
2235
- win.removeEventListener("pointermove", move);
2236
- win.removeEventListener("pointerup", end);
2237
- win.removeEventListener("pointercancel", cancel);
2238
- try {
2239
- canvas.releasePointerCapture?.(pointerId);
2240
- }
2241
- catch {
2242
- // Synthetic pointer events used by tests may not be capturable.
2243
- }
2244
- }
2245
- try {
2246
- canvas.setPointerCapture?.(pointerId);
2247
- }
2248
- catch {
2249
- // Synthetic pointer events used by tests may not be capturable.
2250
- }
2251
- win.addEventListener("pointermove", move);
2252
- win.addEventListener("pointerup", end);
2253
- win.addEventListener("pointercancel", cancel);
2254
- },
2255
- /**
2256
- * Handle non-mouse pointer entering the canvas.
2257
- * @param {PointerEvent} event Pointer event
2258
- * @private
2259
- */
2260
- onCanvasPointerEnter(event) {
2261
- if (!shouldHandleCanvasPointerEvent(this, event)) {
2262
- return;
2263
- }
2264
- this.state.event = event;
2265
- this.config.onover?.bind(this.api)(event);
2266
- },
2267
- /**
2268
- * Handle non-mouse pointer movement over the canvas.
2269
- * @param {PointerEvent} event Pointer event
2270
- * @private
2271
- */
2272
- onCanvasPointerMove(event) {
2273
- if (!shouldHandleCanvasPointerEvent(this, event)) {
2274
- return;
2275
- }
2276
- if (this.updateCanvasSubchartBrush(event)) {
2277
- return;
2278
- }
2279
- this.onCanvasMouseMove(event);
2280
- },
2281
- /**
2282
- * Handle non-mouse pointer click.
2283
- * @param {PointerEvent} event Pointer event
2284
- * @private
2285
- */
2286
- onCanvasPointerUp(event) {
2287
- if (!shouldHandleCanvasPointerEvent(this, event)) {
2288
- return;
2289
- }
2290
- this.state.event = event;
2291
- if (this.endCanvasSubchartBrush(event)) {
2292
- this.config.onout?.bind(this.api)(event);
2293
- return;
2294
- }
2295
- this.dispatchCanvasDataClick(event, true);
2296
- this.dispatchCanvasDataOut(this.$el.canvas.node());
2297
- },
2298
- /**
2299
- * Handle non-mouse pointer leaving the canvas.
2300
- * @param {PointerEvent} event Pointer event
2301
- * @private
2302
- */
2303
- onCanvasPointerOut(event) {
2304
- if (!shouldHandleCanvasPointerEvent(this, event)) {
2305
- return;
2306
- }
2307
- if (this.state.canvasSubchartBrushDragging) {
2308
- return;
2309
- }
2310
- this.state.event = event;
2311
- this.onCanvasMouseOut();
2312
- this.config.onout?.bind(this.api)(event);
2313
- },
2314
- /**
2315
- * Handle non-mouse pointer cancellation.
2316
- * @param {PointerEvent} event Pointer event
2317
- * @private
2318
- */
2319
- onCanvasPointerCancel(event) {
2320
- if (!shouldHandleCanvasPointerEvent(this, event)) {
2321
- return;
2322
- }
2323
- this.state.event = event;
2324
- if (this.cancelCanvasSubchartBrush(event)) {
2325
- this.config.onout?.bind(this.api)(event);
2326
- return;
2327
- }
2328
- this.onCanvasPointerOut(event);
2329
- },
2330
- /**
2331
- * Handle touch start over the canvas.
2332
- * @param {TouchEvent} event Touch event
2333
- * @private
2334
- */
2335
- onCanvasTouchStart(event) {
2336
- if (event.touches.length > 1) {
2337
- return;
2338
- }
2339
- this.state.event = event;
2340
- if (this.startCanvasSubchartBrush(event)) {
2341
- return;
2342
- }
2343
- if (this.startCanvasSelectionDrag(event)) {
2344
- return;
2345
- }
2346
- this.config.onover?.bind(this.api)(event);
2347
- this.onCanvasMouseMove(event);
2348
- },
2349
- /**
2350
- * Handle touch move over the canvas.
2351
- * @param {TouchEvent} event Touch event
2352
- * @private
2353
- */
2354
- onCanvasTouchMove(event) {
2355
- if (event.touches.length > 1) {
2356
- return;
2357
- }
2358
- if (this.updateCanvasSubchartBrush(event)) {
2359
- return;
2360
- }
2361
- if (this.updateCanvasSelectionDrag(event)) {
2362
- return;
2363
- }
2364
- this.onCanvasMouseMove(event);
2365
- },
2366
- /**
2367
- * Handle touch end over the canvas.
2368
- * @param {TouchEvent} event Touch event
2369
- * @private
2370
- */
2371
- onCanvasTouchEnd(event) {
2372
- this.state.event = event;
2373
- if (this.endCanvasSubchartBrush(event)) {
2374
- this.config.onout?.bind(this.api)(event);
2375
- return;
2376
- }
2377
- if (this.endCanvasSelectionDrag(event)) {
2378
- this.config.onout?.bind(this.api)(event);
2379
- return;
2380
- }
2381
- this.dispatchCanvasDataClick(event, true);
2382
- this.dispatchCanvasDataOut(this.$el.canvas.node());
2383
- this.config.onout?.bind(this.api)(event);
2384
- },
2385
- /**
2386
- * Handle touch cancellation.
2387
- * @param {TouchEvent} event Touch event
2388
- * @private
2389
- */
2390
- onCanvasTouchCancel(event) {
2391
- this.state.event = event;
2392
- this.cancelCanvasSubchartBrush(event);
2393
- this.endCanvasSelectionDrag(event);
2394
- this.onCanvasMouseOut();
2395
- this.config.onout?.bind(this.api)(event);
2396
- },
2397
- /**
2398
- * Update canvas focus state and tooltip on pointer movement.
2399
- * @param {Event} event Mouse, pointer or touch move event
2400
- * @private
2401
- */
2402
- onCanvasMouseMove(event) {
2403
- const $$ = this;
2404
- const { config, state, $el } = $$;
2405
- const canvas = $el.canvas.node();
2406
- state.event = event;
2407
- if (state.flowing) {
2408
- return;
2409
- }
2410
- if (state.canvasSelectionDragging) {
2411
- return;
2412
- }
2413
- if ($$.updateCanvasSubchartCursor?.(event)) {
2414
- $$.dispatchCanvasDataOut(canvas);
2415
- if (state.canvasFocusKey) {
2416
- state.canvasFocusKey = null;
2417
- $$.clearCanvasFocus();
2418
- }
2419
- $$.hideTooltip?.();
2420
- return;
2421
- }
2422
- const point = getCanvasEventPoint($$, event);
2423
- const d = point ? getCanvasHoverDatumFromPoint($$, point) : null;
2424
- if (!d) {
2425
- $$.dispatchCanvasDataOut(canvas);
2426
- if (state.canvasFocusKey) {
2427
- state.canvasFocusKey = null;
2428
- $$.clearCanvasFocus();
2429
- }
2430
- if (point && config.axis_tooltip && isCanvasAxisTooltipArea($$, point)) {
2431
- $$.renderCanvasAxisTooltip(point);
2432
- $$.hideTooltip?.();
2433
- return;
2434
- }
2435
- $$.hideTooltip?.();
2436
- return;
2437
- }
2438
- $$.dispatchCanvasDataOver(d, canvas);
2439
- const selectedData = getCanvasTooltipData($$, d);
2440
- const focusData = getCanvasFocusData($$, d, selectedData);
2441
- const focusKey = focusData.map(v => `${v.id}:${v.index}`).join("|");
2442
- if (state.canvasFocusKey !== focusKey || config.axis_tooltip) {
2443
- state.canvasFocusKey = focusKey;
2444
- $$.renderCanvasFocus(focusData, point);
2445
- }
2446
- $$.showTooltip?.(selectedData, canvas);
2447
- },
2448
- /**
2449
- * Clear focus and tooltip state when the pointer leaves the canvas.
2450
- * @private
2451
- */
2452
- onCanvasMouseOut() {
2453
- const canvas = this.$el.canvas.node();
2454
- canvas.style.cursor = "";
2455
- this.dispatchCanvasDataOut(canvas);
2456
- if (this.state.canvasFocusKey) {
2457
- this.state.canvasFocusKey = null;
2458
- this.clearCanvasFocus();
2459
- }
2460
- else if (this.config.axis_tooltip) {
2461
- this.clearCanvasFocus();
2462
- }
2463
- this.hideTooltip?.();
2464
- },
2465
- /**
2466
- * Show canvas tooltip from linked tooltip propagation.
2467
- * @param {number} index Data index
2468
- * @returns {boolean} Whether linked tooltip was shown
2469
- * @private
2470
- */
2471
- showCanvasLinkedTooltip(index) {
2472
- const $$ = this;
2473
- const { $el, state } = $$;
2474
- const canvas = $el.canvas?.node();
2475
- const targetsToShow = $$.filterTargetsToShow($$.data.targets);
2476
- const d = targetsToShow.map(target => target.values[index]).find(Boolean);
2477
- if (!canvas || !d) {
2478
- $$.hideTooltip?.();
2479
- return false;
2480
- }
2481
- const selectedData = getCanvasTooltipData($$, d);
2482
- const focus = selectedData.find(v => v && hasCanvasDrawableValue($$, v)) ||
2483
- selectedData[0];
2484
- if (!selectedData.length || !focus) {
2485
- $$.hideTooltip?.();
2486
- return false;
2487
- }
2488
- const { left, top } = getBoundingRect(canvas, true);
2489
- const point = getRenderDataPoint($$, focus);
2490
- const eventPoint = [
2491
- state.margin.left + point.x,
2492
- state.margin.top + point.y
2493
- ];
2494
- state.event = {
2495
- clientX: left + eventPoint[0],
2496
- clientY: top + eventPoint[1],
2497
- currentTarget: canvas,
2498
- target: canvas
2499
- };
2500
- state.canvasFocusKey = selectedData.map(v => `${v.id}:${v.index}`).join("|");
2501
- $$.renderCanvasFocus(selectedData, eventPoint);
2502
- $$.showTooltip?.(selectedData, canvas);
2503
- return true;
2504
- },
2505
- /**
2506
- * Draw drag-zoom brush overlay on the cached canvas frame.
2507
- * @param {number} start Start coordinate
2508
- * @param {number} end End coordinate
2509
- * @private
2510
- */
2511
- renderCanvasZoomBrush(start, end) {
2512
- const $$ = this;
2513
- $$.canvasEngine.withOverlay(ctx => {
2514
- $$.canvasRenderer.withContext(ctx, () => {
2515
- $$.canvasRenderer.drawZoomBrush($$, start, end);
2516
- });
2517
- });
2518
- },
2519
- /**
2520
- * Clear drag-zoom brush overlay.
2521
- * @private
2522
- */
2523
- clearCanvasZoomBrush() {
2524
- this.canvasEngine.clearOverlay();
2525
- },
2526
- /**
2527
- * Draw selection drag overlay on the cached canvas frame.
2528
- * @param {object} rect Selection rectangle
2529
- * @private
2530
- */
2531
- renderCanvasSelectionDrag(rect) {
2532
- const $$ = this;
2533
- $$.canvasEngine.withOverlay(ctx => {
2534
- $$.canvasRenderer.withContext(ctx, () => {
2535
- $$.canvasRenderer.drawSelectionDragArea($$, rect);
2536
- });
2537
- });
2538
- },
2539
- /**
2540
- * Draw a complete canvas frame and optionally rebuild hit indexes.
2541
- * @param {object} shape Cached draw shape object
2542
- * @param {Array} focusData Focused data rows
2543
- * @param {boolean} rebuildHit Whether to rebuild hit indexes
2544
- * @private
2545
- */
2546
- renderCanvasFrame(shape, focusData, rebuildHit = false) {
2547
- const $$ = this;
2548
- const { state } = $$;
2549
- const drawShape = shape || state.canvasShape || $$.getDrawShape();
2550
- state.canvasShape = drawShape;
2551
- state._canvasVisibleRangeCache = null;
2552
- state._canvasXTickValuesCache = null;
2553
- $$.canvasEngine.beginFrame(state.current.width, $$.getCanvasSurfaceHeight());
2554
- try {
2555
- // user callbacks (tick format, data label format, etc.) run within:
2556
- // guard so a throwing formatter can't leak the saved context state
2557
- $$.canvasRenderer.drawBackground($$);
2558
- $$.canvasAxisRenderer.drawTitle($$);
2559
- state.hasAxis && $$.canvasAxisRenderer.draw($$);
2560
- $$.canvasRenderer.draw($$, drawShape);
2561
- state.hasAxis && $$.config.grid_lines_front &&
2562
- $$.canvasAxisRenderer.drawGridLines($$);
2563
- $$.canvasRenderer.drawSubchart($$, drawShape);
2564
- state.hasAxis && $$.canvasAxisRenderer.drawSubXAxis($$);
2565
- $$.canvasRenderer.drawEmptyLabel($$);
2566
- rebuildHit && $$.hitDetector.rebuild($$, drawShape);
2567
- }
2568
- finally {
2569
- $$.canvasEngine.endFrame();
2570
- }
2571
- $$.canvasEngine.clearOverlay();
2572
- state.canvasFocusMainRedraw = false;
2573
- focusData && $$.renderCanvasFocus(focusData);
2574
- },
2575
- /**
2576
- * Restore the cached frame and draw focus overlays.
2577
- * @param {Array} focusData Focused data rows
2578
- * @param {Array} point Canvas-local pointer coordinate
2579
- * @private
2580
- */
2581
- renderCanvasFocus(focusData, point) {
2582
- const $$ = this;
2583
- const { state } = $$;
2584
- const withMainRedraw = $$.canvasRenderer.hasExpandedShapeFocus?.($$, focusData);
2585
- if (withMainRedraw) {
2586
- const drawShape = state.canvasShape || $$.getDrawShape();
2587
- $$.canvasEngine.beginFrame(state.current.width, $$.getCanvasSurfaceHeight());
2588
- try {
2589
- $$.canvasRenderer.drawBackground($$);
2590
- $$.canvasAxisRenderer.drawTitle($$);
2591
- state.hasAxis && $$.canvasAxisRenderer.draw($$);
2592
- $$.canvasRenderer.draw($$, drawShape, focusData);
2593
- state.hasAxis && $$.config.grid_lines_front &&
2594
- $$.canvasAxisRenderer.drawGridLines($$);
2595
- $$.canvasRenderer.drawSubchart($$, drawShape);
2596
- state.hasAxis && $$.canvasAxisRenderer.drawSubXAxis($$);
2597
- $$.canvasRenderer.drawEmptyLabel($$);
2598
- }
2599
- finally {
2600
- $$.canvasEngine.endFrame();
2601
- }
2602
- }
2603
- state.canvasFocusMainRedraw = !!withMainRedraw;
2604
- $$.canvasEngine.withOverlay(ctx => {
2605
- $$.canvasRenderer.withContext(ctx, () => {
2606
- $$.canvasRenderer.drawFocus($$, focusData);
2607
- });
2608
- $$.canvasAxisRenderer.withContext(ctx, () => {
2609
- $$.canvasAxisRenderer.drawFocusedXAxisTick($$, focusData);
2610
- point && $$.canvasAxisRenderer.drawAxisTooltip($$, point);
2611
- });
2612
- });
2613
- },
2614
- /**
2615
- * Draw only the canvas axis tooltip overlay.
2616
- * @param {Array} point Canvas-local pointer coordinate
2617
- * @private
2618
- */
2619
- renderCanvasAxisTooltip(point) {
2620
- const $$ = this;
2621
- $$.canvasEngine.withOverlay(ctx => {
2622
- $$.canvasAxisRenderer.withContext(ctx, () => {
2623
- $$.canvasAxisRenderer.drawAxisTooltip($$, point);
2624
- });
2625
- });
2626
- },
2627
- /**
2628
- * Restore the cached canvas frame without focus overlays.
2629
- * @private
2630
- */
2631
- clearCanvasFocus() {
2632
- const $$ = this;
2633
- if ($$.state.canvasFocusMainRedraw) {
2634
- $$.state.canvasFocusMainRedraw = false;
2635
- $$.renderCanvasFrame(undefined, null, false);
2636
- }
2637
- else {
2638
- $$.canvasEngine?.clearOverlay();
2639
- }
2640
- },
2641
- /**
2642
- * Resize canvas surfaces and reload canvas theme values.
2643
- * @private
2644
- */
2645
- resizeCanvas() {
2646
- const $$ = this;
2647
- const { config, state, $el } = $$;
2648
- const container = $el.chart.node();
2649
- $el.chart.style("min-height", `${state.current.height}px`);
2650
- $$.canvasEngine?.resize(state.current.width, $$.getCanvasSurfaceHeight());
2651
- $$.canvasTheme?.reload(container, config.canvas_theme);
2652
- }
843
+ /**
844
+ * Normalize unsupported options before initializing canvas mode.
845
+ * @private
846
+ */
847
+ prepareCanvasConfig() {
848
+ const { config, state } = this;
849
+ this.warnUnsupportedCanvasOptions();
850
+ if (state.orgConfig?.transition && Object.prototype.hasOwnProperty.call(state.orgConfig.transition, "duration") && state.orgConfig.transition.duration) warn("canvas mode: transition.duration is ignored; canvas redraws synchronously.");
851
+ config.transition_duration = 0;
852
+ if (!isSupportedCanvasXType(config.axis_x_type)) config.axis_x_type = "indexed";
853
+ if (!isSupportedCanvasYType(config.axis_y_type)) config.axis_y_type = "indexed";
854
+ if (!isSupportedCanvasYType(config.axis_y2_type)) config.axis_y2_type = "indexed";
855
+ if (this.hasType?.("bubble")) {
856
+ config.point_show = true;
857
+ config.point_type = "circle";
858
+ }
859
+ },
860
+ /**
861
+ * Apply the current canvas subchart selection to the main x domain.
862
+ * @private
863
+ */
864
+ applyCanvasSubchartDomain() {
865
+ const $$ = this;
866
+ const { axis, config, scale, state } = $$;
867
+ if (!config.subchart_show || !state.hasAxis || !scale.subX) return;
868
+ if (!state.rendered && !state.domain && config.subchart_init_range) state.domain = normalizeCanvasSubchartDomain($$, config.subchart_init_range);
869
+ const domain = normalizeCanvasSubchartDomain($$, state.domain);
870
+ if (!domain || !$$.withinRange(domain, $$.getZoomDomain("subX", true), $$.getZoomDomain("subX"))) return;
871
+ state.domain = domain;
872
+ scale.x.domain(domain);
873
+ axis.x.scale(scale.x);
874
+ },
875
+ /**
876
+ * Set the canvas subchart selection domain and redraw the main chart.
877
+ * @param {Array} domain Domain range
878
+ * @param {boolean} redraw Whether to redraw immediately
879
+ * @param {boolean} callCallback Whether to call subchart.onbrush
880
+ * @returns {Array|undefined} Applied domain range
881
+ * @private
882
+ */
883
+ setCanvasSubchartDomain(domain, redraw = true, callCallback = false) {
884
+ const $$ = this;
885
+ const { config, scale, state } = $$;
886
+ const nextDomain = normalizeCanvasSubchartDomain($$, domain);
887
+ if (!config.subchart_show || !nextDomain || !$$.withinRange(nextDomain, $$.getZoomDomain("subX", true), $$.getZoomDomain("subX"))) return;
888
+ state.domain = nextDomain;
889
+ scale.zoom = null;
890
+ if (redraw) $$.redraw({
891
+ withTransition: false,
892
+ withY: config.zoom_rescale,
893
+ withSubchart: false,
894
+ withEventRect: false,
895
+ withDimension: false
896
+ });
897
+ callCallback && config.subchart_onbrush.bind($$.api)(state.domain);
898
+ return state.domain;
899
+ },
900
+ /**
901
+ * Clear the canvas subchart brush selection and restore the full x domain.
902
+ * @param {boolean} redraw Whether to redraw immediately
903
+ * @param {boolean} callCallback Whether to call subchart.onbrush
904
+ * @private
905
+ */
906
+ clearCanvasSubchartDomain(redraw = true, callCallback = false) {
907
+ const $$ = this;
908
+ const { axis, config, org, scale, state } = $$;
909
+ if (!config.subchart_show) return;
910
+ state.domain = void 0;
911
+ scale.zoom = null;
912
+ if (org.xDomain?.length) {
913
+ scale.x.domain(org.xDomain);
914
+ axis.x.scale(scale.x);
915
+ }
916
+ if (redraw) $$.redraw({
917
+ withTransition: false,
918
+ withUpdateXDomain: true,
919
+ withUpdateOrgXDomain: false,
920
+ withY: config.zoom_rescale,
921
+ withSubchart: false,
922
+ withEventRect: false,
923
+ withDimension: false
924
+ });
925
+ callCallback && config.subchart_onbrush.bind($$.api)(scale.x.orgDomain());
926
+ },
927
+ /**
928
+ * Finish a pending canvas flow animation before accepting another flow mutation.
929
+ * @private
930
+ */
931
+ flushCanvasFlow() {
932
+ const { state } = this;
933
+ if (!state.canvasFlowFinish) return;
934
+ state.canvasFlowFrame !== null && win.cancelAnimationFrame?.(state.canvasFlowFrame);
935
+ state.canvasFlowFrame = null;
936
+ state.canvasFlowFinish();
937
+ },
938
+ /**
939
+ * Animate canvas flow by interpolating the x domain, then commit the final data window.
940
+ * @param {object} flow Flow metadata
941
+ * @returns {boolean} Whether animation was started
942
+ * @private
943
+ */
944
+ animateCanvasFlow(flow) {
945
+ const $$ = this;
946
+ const { axis, data, org, scale, state } = $$;
947
+ const { done = () => {}, duration, length, orgDataCount } = flow;
948
+ const requestFrame = win.requestAnimationFrame?.bind(win);
949
+ const isLog = !!axis.isLog?.("x");
950
+ if (!requestFrame || !duration || !length || !orgDataCount || getCanvasFlowValueCount($$) > CANVAS_FLOW_ANIMATION_MAX_VALUES) return false;
951
+ const startDomain = scale.x.domain().slice(0, 2);
952
+ const startOrgDomain = org.xDomain?.slice?.();
953
+ const startSubXDomain = scale.subX?.domain?.().slice?.();
954
+ if (!isCanvasFlowDomain(startDomain, isLog)) return false;
955
+ const removed = data.targets.map((target) => target.values.splice(0, length));
956
+ $$.updateXDomain($$.filterTargetsToShow(data.targets), true, true);
957
+ const endDomain = scale.x.domain().slice(0, 2);
958
+ const endOrgDomain = org.xDomain?.slice?.();
959
+ data.targets.forEach((target, index) => {
960
+ target.values.unshift(...removed[index]);
961
+ });
962
+ if (!isCanvasFlowDomain(endDomain, isLog)) {
963
+ startOrgDomain && (org.xDomain = startOrgDomain);
964
+ scale.x.domain(startDomain);
965
+ startSubXDomain && scale.subX.domain(startSubXDomain);
966
+ axis.x.scale(scale.x);
967
+ return false;
968
+ }
969
+ syncCanvasFlowYDomains($$);
970
+ let finished = false;
971
+ const started = getCanvasAnimationTime();
972
+ const finish = () => {
973
+ if (finished) return;
974
+ finished = true;
975
+ data.targets.forEach((target) => {
976
+ target.values.splice(0, length);
977
+ });
978
+ endOrgDomain && (org.xDomain = endOrgDomain);
979
+ scale.x.domain(endDomain);
980
+ scale.subX?.domain?.(endOrgDomain ?? endDomain);
981
+ axis.x.scale(scale.x);
982
+ state.dirty.data = true;
983
+ state._eventRectFingerprint = null;
984
+ state.canvasShape = null;
985
+ state._cachedDrawShape = null;
986
+ $$.redraw({
987
+ withLegend: true,
988
+ withTransition: false,
989
+ withTrimXDomain: false,
990
+ withUpdateOrgXDomain: true,
991
+ withUpdateXAxis: true,
992
+ withUpdateXDomain: true
993
+ });
994
+ $$.updateTypesElements();
995
+ state.canvasFlowFrame = null;
996
+ state.canvasFlowFinish = null;
997
+ state.flowing = false;
998
+ done.call($$.api);
999
+ };
1000
+ const render = (timestamp) => {
1001
+ const ratio = Math.min(1, Math.max(0, (timestamp - started) / duration));
1002
+ const domain = interpolateCanvasFlowDomain(startDomain, endDomain, ratio, isLog);
1003
+ scale.x.domain(domain);
1004
+ axis.x.scale(scale.x);
1005
+ state.canvasShape = null;
1006
+ state._cachedDrawShape = null;
1007
+ state._canvasVisibleRangeCache = null;
1008
+ state._canvasXTickValuesCache = null;
1009
+ $$.renderCanvasFrame(void 0, null, false);
1010
+ if (ratio < 1) state.canvasFlowFrame = requestFrame(render);
1011
+ else finish();
1012
+ };
1013
+ startOrgDomain && (org.xDomain = startOrgDomain);
1014
+ scale.x.domain(startDomain);
1015
+ startSubXDomain && scale.subX.domain(startSubXDomain);
1016
+ axis.x.scale(scale.x);
1017
+ state.flowing = true;
1018
+ state.cancelClick = true;
1019
+ $$.hideTooltip?.();
1020
+ state.canvasFlowFinish = finish;
1021
+ state.canvasFlowFrame = requestFrame(render);
1022
+ return true;
1023
+ },
1024
+ /**
1025
+ * Initialize canvas renderers, theme, hit detector and event bindings.
1026
+ * @private
1027
+ */
1028
+ initCanvas() {
1029
+ const $$ = this;
1030
+ const { config, state, $el } = $$;
1031
+ const container = $el.chart.node();
1032
+ state.isCanvasMode = true;
1033
+ state.canvasInlineStyle.minHeight = container.style.minHeight;
1034
+ if (win.getComputedStyle(container).position === "static") $el.chart.style("position", "relative");
1035
+ $el.chart.style("min-height", `${state.current.height}px`);
1036
+ $$.canvasEngine = new CanvasEngine();
1037
+ $$.canvasEngine.init(container, state.current.width, $$.getCanvasSurfaceHeight());
1038
+ $el.canvas = select($$.canvasEngine.canvas);
1039
+ $$.canvasTheme = new CanvasTheme();
1040
+ $$.canvasTheme.load(container, config.canvas_theme);
1041
+ $$.canvasAxisRenderer = new CanvasAxisRenderer($$.canvasEngine, $$.canvasTheme);
1042
+ $$.canvasRenderer = new CanvasRenderer($$.canvasEngine, $$.canvasTheme);
1043
+ $$.hitDetector = new HitDetector();
1044
+ $$.bindCanvasEvents();
1045
+ config.zoom_enabled && $$.bindZoomEvent?.();
1046
+ },
1047
+ /**
1048
+ * Warn about options that canvas mode does not support yet.
1049
+ * @private
1050
+ */
1051
+ warnUnsupportedCanvasOptions() {
1052
+ const { config } = this;
1053
+ [
1054
+ [!isSupportedCanvasXType(config.axis_x_type), "axis.x.type other than indexed/category/log/timeseries"],
1055
+ [!isSupportedCanvasYType(config.axis_y_type), "axis.y.type other than indexed/log/timeseries"],
1056
+ [!isSupportedCanvasYType(config.axis_y2_type), "axis.y2.type other than indexed/log/timeseries"],
1057
+ [config.boost_useCssRule, "boost.useCssRule"],
1058
+ [this.hasArcType?.(), "arc charts"],
1059
+ [this.hasType?.("radar"), "radar chart"],
1060
+ [this.hasType?.("polar"), "polar chart"],
1061
+ [this.hasType?.("funnel"), "funnel chart"]
1062
+ ].forEach(([condition, name]) => {
1063
+ condition && warn(`canvas mode: ${name} is not yet supported.`);
1064
+ });
1065
+ },
1066
+ /**
1067
+ * Bind pointer and click handlers to the canvas surface.
1068
+ * @private
1069
+ */
1070
+ bindCanvasEvents() {
1071
+ const $$ = this;
1072
+ const { config, state, $el } = $$;
1073
+ const canvas = $el.canvas.node();
1074
+ const preventTouchEvent = getCanvasTouchPreventer(config);
1075
+ const touchOption = getCanvasTouchListenerOption(config);
1076
+ canvas.addEventListener("mousemove", $$.onCanvasMouseMove.bind($$));
1077
+ canvas.addEventListener("mouseenter", (event) => {
1078
+ state.event = event;
1079
+ config.onover?.bind($$.api)(event);
1080
+ });
1081
+ canvas.addEventListener("mouseout", $$.onCanvasMouseOut.bind($$));
1082
+ canvas.addEventListener("mouseleave", (event) => {
1083
+ state.event = event;
1084
+ config.onout?.bind($$.api)(event);
1085
+ });
1086
+ canvas.addEventListener("mousedown", (event) => {
1087
+ if ($$.onCanvasSubchartBrushStart?.(event)) return;
1088
+ $$.onCanvasSelectionDragStart(event);
1089
+ });
1090
+ canvas.addEventListener("click", $$.onCanvasClick.bind($$));
1091
+ canvas.addEventListener("pointerdown", $$.onCanvasPointerDown.bind($$));
1092
+ canvas.addEventListener("pointerenter", $$.onCanvasPointerEnter.bind($$));
1093
+ canvas.addEventListener("pointermove", $$.onCanvasPointerMove.bind($$));
1094
+ canvas.addEventListener("pointerup", $$.onCanvasPointerUp.bind($$));
1095
+ canvas.addEventListener("pointerleave", $$.onCanvasPointerOut.bind($$));
1096
+ canvas.addEventListener("pointercancel", $$.onCanvasPointerCancel.bind($$));
1097
+ if (isCanvasTouchEnabled(config)) {
1098
+ canvas.addEventListener("touchstart", (event) => {
1099
+ preventTouchEvent(event);
1100
+ $$.onCanvasTouchStart(event);
1101
+ }, touchOption);
1102
+ canvas.addEventListener("touchmove", (event) => {
1103
+ preventTouchEvent(event);
1104
+ $$.onCanvasTouchMove(event);
1105
+ }, touchOption);
1106
+ canvas.addEventListener("touchend", $$.onCanvasTouchEnd.bind($$), touchOption);
1107
+ canvas.addEventListener("touchcancel", $$.onCanvasTouchCancel.bind($$), touchOption);
1108
+ }
1109
+ },
1110
+ /**
1111
+ * Render and update the HTML legend used by canvas mode.
1112
+ * @private
1113
+ */
1114
+ updateHtmlLegend() {
1115
+ const $$ = this;
1116
+ const { config, state, $el } = $$;
1117
+ const chart = $el.chart.node();
1118
+ if (!config.legend_show || state.hasTreemap) {
1119
+ if (state.hasTreemap) {
1120
+ $el.legend?.remove();
1121
+ $el.legend = null;
1122
+ } else $el.legend?.style("visibility", "hidden");
1123
+ state.legendItemWidth = 0;
1124
+ state.legendItemHeight = 0;
1125
+ state.legendStep = 0;
1126
+ return;
1127
+ }
1128
+ const targetIds = $$.mapToIds($$.data.targets).filter((id) => config.data_names[id] !== null);
1129
+ if (config.legend_contents_bindto && config.legend_contents_template) {
1130
+ if ($$.updateHtmlLegendTemplate(targetIds)) {
1131
+ state.legendItemWidth = 0;
1132
+ state.legendItemHeight = 0;
1133
+ state.legendStep = 0;
1134
+ state.legendHasRendered = true;
1135
+ } else {
1136
+ state.legendItemWidth = 0;
1137
+ state.legendItemHeight = 0;
1138
+ state.legendStep = 0;
1139
+ }
1140
+ return;
1141
+ }
1142
+ if (!$el.legend) $el.legend = select(chart).append("div").classed($LEGEND.legend, true).classed($CANVAS.legend, true);
1143
+ $el.legend.style("visibility", null);
1144
+ const legendItems = $el.legend.selectAll(`button.${$LEGEND.legendItem}`).data(targetIds, (id) => id);
1145
+ legendItems.exit().remove();
1146
+ const enter = legendItems.enter().append("button").attr("type", "button").attr("data-id", (id) => id);
1147
+ enter.append("span").classed($LEGEND.legendItemTile, true);
1148
+ enter.append("span").classed($CANVAS.legendItemTitle, true);
1149
+ const item = enter.merge(legendItems).attr("class", (id) => $$.generateClass($LEGEND.legendItem, id).trim());
1150
+ setCanvasHtmlLegendItem($$, item);
1151
+ item.select(`.${$LEGEND.legendItemTile}`).classed($CANVAS.legendItemTileCircle, !config.legend_usePoint && config.legend_item_tile_type === "circle").style("background-color", (id) => config.legend_usePoint ? null : $$.color(id)).html((id) => config.legend_usePoint ? getCanvasLegendPointIcon($$, id) : "");
1152
+ item.select(`.${$CANVAS.legendItemTitle}`).text((id) => getLegendText($$, id));
1153
+ if (config.legend_tooltip) item.attr("title", (id) => getLegendText($$, id));
1154
+ bindCanvasHtmlLegendInteractions($$, item);
1155
+ $$.updateHtmlLegendSize(targetIds);
1156
+ $$.positionHtmlLegend();
1157
+ state.legendHasRendered = true;
1158
+ },
1159
+ /**
1160
+ * Render canvas mode legend into custom HTML template container.
1161
+ * @param {Array} targetIds Legend target ids
1162
+ * @returns {boolean} Whether template legend was rendered
1163
+ * @private
1164
+ */
1165
+ updateHtmlLegendTemplate(targetIds) {
1166
+ const $$ = this;
1167
+ const { api, config, $el } = $$;
1168
+ const wrapper = select(config.legend_contents_bindto);
1169
+ const template = config.legend_contents_template;
1170
+ const ids = [];
1171
+ let html = "";
1172
+ if (wrapper.empty()) return false;
1173
+ targetIds.forEach((id) => {
1174
+ const content = isFunction(template) ? sanitize(template.call(api, id, $$.color(id), api.data(id)[0].values)) : tplProcess(template, {
1175
+ COLOR: $$.color(id),
1176
+ TITLE: id
1177
+ });
1178
+ if (content) {
1179
+ ids.push(id);
1180
+ html += content;
1181
+ }
1182
+ });
1183
+ const legendItem = wrapper.html(html).classed($LEGEND.legend, true).classed($CANVAS.legend, false).style("visibility", null).selectAll(function() {
1184
+ return this.children;
1185
+ }).data(ids);
1186
+ setCanvasHtmlLegendItem($$, legendItem);
1187
+ bindCanvasHtmlLegendInteractions($$, legendItem);
1188
+ $el.legend = wrapper;
1189
+ return true;
1190
+ },
1191
+ /**
1192
+ * Measure HTML legend items and update legend layout state.
1193
+ * @param {Array} targetIds Visible legend target ids
1194
+ * @private
1195
+ */
1196
+ updateHtmlLegendSize(targetIds) {
1197
+ const $$ = this;
1198
+ const { config, state, $el } = $$;
1199
+ const itemSizes = [];
1200
+ const itemLayouts = {};
1201
+ let maxWidth = 0;
1202
+ let maxHeight = 0;
1203
+ let legendStep = 0;
1204
+ const useTemplateLegend = config.legend_contents_bindto && config.legend_contents_template;
1205
+ if (useTemplateLegend) $el.legend.selectAll(`.${$LEGEND.legendItem}`).each(function(id) {
1206
+ const rect = getBoundingRect(this, true);
1207
+ const text = `${getLegendText($$, id)}`;
1208
+ const fallbackWidth = Math.max(32, text.length * 7 + 24);
1209
+ const fallbackHeight = 20;
1210
+ const width = Math.ceil(rect.width || fallbackWidth);
1211
+ const height = Math.ceil(rect.height || fallbackHeight);
1212
+ itemSizes.push(width);
1213
+ maxWidth = Math.max(maxWidth, width);
1214
+ maxHeight = Math.max(maxHeight, height);
1215
+ });
1216
+ else if (targetIds.length) {
1217
+ const isRightOrInset = state.isLegendRight || state.isLegendInset;
1218
+ const isRectangle = config.legend_item_tile_type !== "circle";
1219
+ const itemTileSize = {
1220
+ width: isRectangle ? config.legend_item_tile_width : config.legend_item_tile_r * 2,
1221
+ height: isRectangle ? config.legend_item_tile_height : config.legend_item_tile_r * 2
1222
+ };
1223
+ const dimension = {
1224
+ padding: {
1225
+ top: 4,
1226
+ right: 10
1227
+ },
1228
+ max: {
1229
+ width: 0,
1230
+ height: 0
1231
+ },
1232
+ posMin: 10,
1233
+ step: 0,
1234
+ tileWidth: itemTileSize.width + 5,
1235
+ totalLength: 0
1236
+ };
1237
+ const sizes = {
1238
+ offsets: {},
1239
+ widths: {},
1240
+ heights: {},
1241
+ margins: [0],
1242
+ steps: {}
1243
+ };
1244
+ const measured = targetIds.map((id, index) => {
1245
+ const text = `${getLegendText($$, id)}`;
1246
+ const rect = measureSvgLegendText($$, text);
1247
+ const fallbackWidth = Math.max(32, text.length * 7);
1248
+ const fallbackHeight = 12;
1249
+ const isLast = index === targetIds.length - 1;
1250
+ const hidden = config.legend_show && !$$.isLegendToShow(id);
1251
+ const width = hidden ? 0 : (rect?.width || fallbackWidth) + dimension.tileWidth + (isLast && !isRightOrInset ? 0 : dimension.padding.right) + config.legend_padding;
1252
+ const height = hidden ? 0 : (rect?.height || fallbackHeight) + dimension.padding.top;
1253
+ dimension.max.width = Math.max(dimension.max.width, width);
1254
+ dimension.max.height = Math.max(dimension.max.height, height);
1255
+ return {
1256
+ id,
1257
+ hidden,
1258
+ width,
1259
+ height
1260
+ };
1261
+ });
1262
+ const areaLength = isRightOrInset ? $$.getLegendHeight() : $$.getLegendWidth();
1263
+ const updateValues = (id, itemLength, withoutStep = false) => {
1264
+ let margin;
1265
+ if (!withoutStep) {
1266
+ margin = (areaLength - dimension.totalLength - itemLength) / 2;
1267
+ if (margin < dimension.posMin) {
1268
+ margin = (areaLength - itemLength) / 2;
1269
+ dimension.totalLength = 0;
1270
+ dimension.step++;
1271
+ }
1272
+ }
1273
+ sizes.steps[id] = dimension.step;
1274
+ sizes.margins[dimension.step] = state.isLegendInset ? 10 : margin;
1275
+ sizes.offsets[id] = dimension.totalLength;
1276
+ dimension.totalLength += itemLength;
1277
+ };
1278
+ if (state.isLegendInset) {
1279
+ dimension.step = config.legend_inset_step ? config.legend_inset_step : targetIds.length;
1280
+ state.legendStep = dimension.step;
1281
+ }
1282
+ measured.forEach(({ id, hidden, width, height }) => {
1283
+ const itemWidth = config.legend_equally && !hidden ? dimension.max.width : width;
1284
+ const itemHeight = config.legend_equally && !hidden ? dimension.max.height : height;
1285
+ const itemLength = isRightOrInset ? itemHeight : itemWidth;
1286
+ sizes.widths[id] = itemWidth;
1287
+ sizes.heights[id] = itemHeight;
1288
+ itemSizes.push(itemWidth);
1289
+ maxWidth = Math.max(maxWidth, itemWidth);
1290
+ maxHeight = Math.max(maxHeight, itemHeight);
1291
+ if (hidden) {
1292
+ sizes.steps[id] = 0;
1293
+ sizes.offsets[id] = 0;
1294
+ return;
1295
+ }
1296
+ updateValues(id, itemLength);
1297
+ });
1298
+ const xForLegend = state.isLegendRight ? (id) => dimension.max.width * sizes.steps[id] : state.isLegendInset ? (id) => dimension.max.width * sizes.steps[id] + 10 : (id) => sizes.margins[sizes.steps[id]] + sizes.offsets[id];
1299
+ const yForLegend = state.isLegendRight || state.isLegendInset ? (id) => sizes.margins[sizes.steps[id]] + sizes.offsets[id] : (id) => dimension.max.height * sizes.steps[id];
1300
+ const titleX = 4 + itemTileSize.width;
1301
+ const tileCenterY = 9;
1302
+ measured.forEach(({ id, hidden }) => {
1303
+ const x = hidden ? 0 : xForLegend(id);
1304
+ const y = hidden ? 0 : yForLegend(id);
1305
+ itemLayouts[id] = {
1306
+ item: {
1307
+ x,
1308
+ y: y - 5,
1309
+ width: sizes.widths[id],
1310
+ height: sizes.heights[id]
1311
+ },
1312
+ title: {
1313
+ x: titleX,
1314
+ y: 0,
1315
+ height: sizes.heights[id]
1316
+ },
1317
+ tile: {
1318
+ x: -2,
1319
+ y: tileCenterY - itemTileSize.height / 2,
1320
+ width: itemTileSize.width,
1321
+ height: itemTileSize.height
1322
+ }
1323
+ };
1324
+ });
1325
+ legendStep = dimension.step;
1326
+ }
1327
+ if (!targetIds.length) {
1328
+ state.legendItemWidth = 0;
1329
+ state.legendItemHeight = 0;
1330
+ state.legendStep = 0;
1331
+ return;
1332
+ }
1333
+ if (useTemplateLegend) {
1334
+ const availableWidth = Math.max(1, state.current.width);
1335
+ const rowGap = 10;
1336
+ let rows = 1;
1337
+ let rowWidth = 0;
1338
+ itemSizes.forEach((width) => {
1339
+ if (rowWidth && rowWidth + rowGap + width > availableWidth) {
1340
+ rows++;
1341
+ rowWidth = width;
1342
+ } else rowWidth += (rowWidth ? rowGap : 0) + width;
1343
+ });
1344
+ state.legendStep = Math.max(0, rows - 1);
1345
+ } else state.legendStep = legendStep;
1346
+ state.legendItemWidth = maxWidth;
1347
+ state.legendItemHeight = Math.max(12, maxHeight);
1348
+ if (!useTemplateLegend) $el.legend.selectAll(`button.${$LEGEND.legendItem}`).each(function(id) {
1349
+ const layout = itemLayouts[id];
1350
+ const item = select(this);
1351
+ if (!layout) return;
1352
+ item.style("left", `${layout.item.x}px`).style("top", `${layout.item.y}px`).style("width", `${layout.item.width}px`).style("height", `${layout.item.height}px`);
1353
+ item.select(`.${$CANVAS.legendItemTitle}`).style("left", `${layout.title.x}px`).style("top", `${layout.title.y}px`).style("height", `${layout.title.height}px`).style("line-height", `${layout.title.height}px`);
1354
+ item.select(`.${$LEGEND.legendItemTile}`).style("left", `${layout.tile.x}px`).style("top", `${layout.tile.y}px`).style("width", `${layout.tile.width}px`).style("height", `${layout.tile.height}px`);
1355
+ });
1356
+ },
1357
+ /**
1358
+ * Get bottom legend block height separated from the canvas drawing surface.
1359
+ * @returns {number} Legend block height
1360
+ * @private
1361
+ */
1362
+ getCanvasBottomLegendHeight() {
1363
+ const $$ = this;
1364
+ const { config, state, $el } = $$;
1365
+ if (!config.legend_show || state.isLegendRight || state.isLegendInset || state.hasTreemap || !$el.legend || !state.legendItemHeight) return 0;
1366
+ const rectHeight = getBoundingRect($el.legend.node(), true).height;
1367
+ const rowHeight = state.legendItemHeight * (state.legendStep + 1);
1368
+ return Math.ceil(Math.max($$.getLegendHeight?.() || 0, rectHeight || rowHeight));
1369
+ },
1370
+ /**
1371
+ * Get canvas drawing surface height excluding separately rendered bottom legend DOM.
1372
+ * @returns {number} Canvas drawing surface height
1373
+ * @private
1374
+ */
1375
+ getCanvasSurfaceHeight() {
1376
+ const $$ = this;
1377
+ return Math.max(0, $$.state.current.height - $$.getCanvasBottomLegendHeight());
1378
+ },
1379
+ /**
1380
+ * Position the HTML legend around or inside the canvas chart.
1381
+ * @private
1382
+ */
1383
+ positionHtmlLegend() {
1384
+ const $$ = this;
1385
+ const { config, state, $el } = $$;
1386
+ const legend = $el.legend;
1387
+ legend.classed($CANVAS.legendBottom, !state.isLegendRight && !state.isLegendInset).classed($CANVAS.legendRight, state.isLegendRight).classed($CANVAS.legendInset, state.isLegendInset).style("top", null).style("right", null).style("bottom", null).style("left", null).style("width", null).style("height", null).style("min-height", null);
1388
+ if (state.isLegendRight) legend.style("top", `${state.margin3.top}px`).style("right", "0").style("bottom", `${state.margin3.bottom}px`).style("width", `${Math.max(0, $$.getLegendWidth())}px`);
1389
+ else if (!state.isLegendInset) {
1390
+ const legendHeight = $$.getLegendHeight?.() || 0;
1391
+ legend.style("top", `${Math.max(0, state.current.height - legendHeight)}px`).style("right", "0").style("bottom", "auto").style("left", "0");
1392
+ } else if (state.isLegendInset) {
1393
+ const isTop = state.isLegendTop;
1394
+ const isLeft = state.isLegendLeft;
1395
+ legend.style(isTop ? "top" : "bottom", `${config.legend_inset_y}px`).style(isLeft ? "left" : "right", `${config.legend_inset_x}px`).style("width", `${Math.max(0, state.legendItemWidth * (state.legendStep + 1) + 20)}px`);
1396
+ }
1397
+ },
1398
+ /**
1399
+ * Get selected canvas data rows.
1400
+ * @param {string} targetId Target id
1401
+ * @returns {Array} Selected rows
1402
+ * @private
1403
+ */
1404
+ getCanvasSelectedData(targetId) {
1405
+ const $$ = this;
1406
+ const selected = $$.state.canvasSelection;
1407
+ const data = [];
1408
+ if (!$$.config.data_selection_enabled || !selected?.size) return data;
1409
+ eachCanvasSelectableData($$, (d) => {
1410
+ (!targetId || d.id === targetId) && selected.has(getCanvasDataKey(d)) && data.push(d);
1411
+ });
1412
+ return data;
1413
+ },
1414
+ /**
1415
+ * Select or unselect canvas data rows.
1416
+ * @param {boolean} isSelection Whether to select
1417
+ * @param {string|Array} ids Target ids
1418
+ * @param {Array} indices Target indices
1419
+ * @param {boolean} resetOther Whether to reset unrelated selections
1420
+ * @private
1421
+ */
1422
+ setCanvasSelection(isSelection = false, ids, indices, resetOther) {
1423
+ const $$ = this;
1424
+ const { config, state } = $$;
1425
+ const selected = state.canvasSelection;
1426
+ const selectionGrouped = config.data_selection_grouped;
1427
+ let targetIds = getCanvasSelectionIds(ids);
1428
+ let changed = false;
1429
+ const singleSelection = isSelection && !config.data_selection_multiple;
1430
+ let resetDone = !singleSelection;
1431
+ if (!config.data_selection_enabled) return;
1432
+ if (singleSelection) {
1433
+ indices = indices?.length ? [indices[0]] : [0];
1434
+ if (!selectionGrouped) if (targetIds) targetIds = targetIds.slice(0, 1);
1435
+ else {
1436
+ const [firstTarget] = $$.filterTargetsToShow($$.data.targets);
1437
+ targetIds = firstTarget ? [firstTarget.id] : [];
1438
+ }
1439
+ }
1440
+ eachCanvasSelectableData($$, (d) => {
1441
+ const key = getCanvasDataKey(d);
1442
+ const isTargetId = selectionGrouped || !targetIds || targetIds.indexOf(d.id) >= 0;
1443
+ const isTargetIndex = !indices || indices.indexOf(d.index) >= 0;
1444
+ const isSelected = selected.has(key);
1445
+ if (isSelection) {
1446
+ if (isTargetId && isTargetIndex && (!isSelected || singleSelection)) {
1447
+ if (!resetDone) {
1448
+ $$.setCanvasSelection(false);
1449
+ resetDone = true;
1450
+ }
1451
+ if (selected.has(key)) return;
1452
+ selected.add(key);
1453
+ callFn(config.data_onselected, $$.api, d, $$.canvasEngine.canvas);
1454
+ changed = true;
1455
+ } else if ((!singleSelection || resetDone) && resetOther && isSelected) {
1456
+ selected.delete(key);
1457
+ callFn(config.data_onunselected, $$.api, d, $$.canvasEngine.canvas);
1458
+ changed = true;
1459
+ }
1460
+ } else if (isTargetId && isTargetIndex && isSelected) {
1461
+ selected.delete(key);
1462
+ callFn(config.data_onunselected, $$.api, d, $$.canvasEngine.canvas);
1463
+ changed = true;
1464
+ }
1465
+ });
1466
+ changed && $$.renderCanvasFrame?.(void 0, null, false);
1467
+ },
1468
+ /**
1469
+ * Toggle canvas data selection from a click.
1470
+ * @param {Array} dataRows Data rows to toggle
1471
+ * @private
1472
+ */
1473
+ toggleCanvasSelection(dataRows) {
1474
+ const $$ = this;
1475
+ const { config, state } = $$;
1476
+ const selected = state.canvasSelection;
1477
+ let changed = false;
1478
+ if (!config.data_selection_enabled) return;
1479
+ dataRows.filter((d) => isCanvasSelectableData($$, d)).forEach((d) => {
1480
+ const key = getCanvasDataKey(d);
1481
+ const isSelected = selected.has(key);
1482
+ if (!config.data_selection_multiple) eachCanvasSelectableData($$, (selectedData) => {
1483
+ const selectedKey = getCanvasDataKey(selectedData);
1484
+ if ((config.data_selection_grouped ? selectedData.id === d.id : selectedKey !== key) && selected.has(selectedKey)) {
1485
+ selected.delete(selectedKey);
1486
+ callFn(config.data_onunselected, $$.api, selectedData, $$.canvasEngine.canvas);
1487
+ changed = true;
1488
+ }
1489
+ });
1490
+ if (isSelected && selected.has(key)) {
1491
+ selected.delete(key);
1492
+ callFn(config.data_onunselected, $$.api, d, $$.canvasEngine.canvas);
1493
+ } else {
1494
+ selected.add(key);
1495
+ callFn(config.data_onselected, $$.api, d, $$.canvasEngine.canvas);
1496
+ }
1497
+ changed = true;
1498
+ });
1499
+ changed && $$.renderCanvasFrame?.(void 0, null, false);
1500
+ },
1501
+ /**
1502
+ * Check whether canvas draggable selection can start.
1503
+ * @param {MouseEvent|TouchEvent} event Input event
1504
+ * @returns {boolean} Whether drag selection can start
1505
+ * @private
1506
+ */
1507
+ canStartCanvasSelectionDrag(event) {
1508
+ const { config } = this;
1509
+ const mouse = event;
1510
+ return Boolean(config.interaction_enabled && config.data_selection_enabled && config.data_selection_draggable && config.data_selection_multiple && !config.zoom_enabled && (mouse.button === void 0 || mouse.button === 0));
1511
+ },
1512
+ /**
1513
+ * Get the selected data rows inside the current canvas drag rectangle.
1514
+ * @param {object} rect Canvas rectangle
1515
+ * @returns {Array} Included rows
1516
+ * @private
1517
+ */
1518
+ getCanvasSelectionDragData(rect) {
1519
+ const $$ = this;
1520
+ const { config } = $$;
1521
+ const data = $$.hitDetector.findInRect(rect, config.data_selection_grouped);
1522
+ if (!config.data_selection_grouped) return data;
1523
+ const indices = new Set(data.map((d) => d.index));
1524
+ return $$.filterTargetsToShow($$.data.targets).flatMap((target) => target.values.filter((d) => indices.has(d.index)));
1525
+ },
1526
+ /**
1527
+ * Start canvas draggable selection.
1528
+ * @param {MouseEvent|TouchEvent} event Input event
1529
+ * @returns {boolean} Whether drag started
1530
+ * @private
1531
+ */
1532
+ startCanvasSelectionDrag(event) {
1533
+ const $$ = this;
1534
+ const { state } = $$;
1535
+ const point = getCanvasEventPoint($$, event);
1536
+ if (!point || !$$.canStartCanvasSelectionDrag(event)) return false;
1537
+ state.dragStart = point;
1538
+ state.canvasSelectionDragStart = point;
1539
+ state.canvasSelectionDragIncluded = /* @__PURE__ */ new Set();
1540
+ state.canvasSelectionDragging = true;
1541
+ state.canvasSelectionDragMoved = false;
1542
+ canvasSelectionDragRows.set($$, /* @__PURE__ */ new Map());
1543
+ $$.setDragStatus(true);
1544
+ $$.hideTooltip?.();
1545
+ event.preventDefault?.();
1546
+ return true;
1547
+ },
1548
+ /**
1549
+ * Update canvas draggable selection.
1550
+ * @param {MouseEvent|TouchEvent} event Input event
1551
+ * @returns {boolean} Whether drag was handled
1552
+ * @private
1553
+ */
1554
+ updateCanvasSelectionDrag(event) {
1555
+ const $$ = this;
1556
+ const { config, state } = $$;
1557
+ const start = state.canvasSelectionDragStart;
1558
+ const point = getCanvasEventPoint($$, event);
1559
+ if (!state.canvasSelectionDragging || !start || !point) return false;
1560
+ const [sx, sy] = start;
1561
+ const [mx, my] = point;
1562
+ const minX = Math.min(sx, mx);
1563
+ const maxX = Math.max(sx, mx);
1564
+ const minY = config.data_selection_grouped ? state.margin.top : Math.min(sy, my);
1565
+ const maxY = config.data_selection_grouped ? state.margin.top + state.height : Math.max(sy, my);
1566
+ const rect = {
1567
+ x: minX,
1568
+ y: minY,
1569
+ w: maxX - minX,
1570
+ h: maxY - minY
1571
+ };
1572
+ const moved = Math.abs(mx - sx) > 4 || Math.abs(my - sy) > 4;
1573
+ state.canvasSelectionDragMoved = state.canvasSelectionDragMoved || moved;
1574
+ if (moved) {
1575
+ const { included, rows } = getCanvasSelectionDragDelta($$, $$.getCanvasSelectionDragData(rect));
1576
+ rows.length && $$.toggleCanvasSelection(rows);
1577
+ state.canvasSelectionDragIncluded = included;
1578
+ state.cancelClick = true;
1579
+ }
1580
+ $$.renderCanvasSelectionDrag(rect);
1581
+ event.preventDefault?.();
1582
+ return true;
1583
+ },
1584
+ /**
1585
+ * End canvas draggable selection.
1586
+ * @param {MouseEvent|TouchEvent} event Input event
1587
+ * @returns {boolean} Whether drag ended
1588
+ * @private
1589
+ */
1590
+ endCanvasSelectionDrag(event) {
1591
+ const $$ = this;
1592
+ const { state } = $$;
1593
+ if (!state.canvasSelectionDragging) return false;
1594
+ $$.updateCanvasSelectionDrag(event);
1595
+ state.cancelClick = state.cancelClick || state.canvasSelectionDragMoved;
1596
+ state.dragStart = null;
1597
+ state.canvasSelectionDragStart = null;
1598
+ state.canvasSelectionDragIncluded = /* @__PURE__ */ new Set();
1599
+ state.canvasSelectionDragging = false;
1600
+ state.canvasSelectionDragMoved = false;
1601
+ canvasSelectionDragRows.delete($$);
1602
+ $$.setDragStatus(false);
1603
+ $$.clearCanvasFocus();
1604
+ event.preventDefault?.();
1605
+ return true;
1606
+ },
1607
+ /**
1608
+ * Dispatch canvas data.onout callback for the current hovered row.
1609
+ * @param {HTMLCanvasElement} canvas Canvas element
1610
+ * @private
1611
+ */
1612
+ dispatchCanvasDataOut(canvas) {
1613
+ const $$ = this;
1614
+ const { config, state } = $$;
1615
+ const d = state.canvasDataHover;
1616
+ if (!d) return;
1617
+ state.canvasDataHover = null;
1618
+ state.canvasDataHoverKey = null;
1619
+ config.interaction_enabled && callFn(config.data_onout, $$.api, d, canvas);
1620
+ },
1621
+ /**
1622
+ * Dispatch canvas data.onover callback when the hovered row changes.
1623
+ * @param {object} d Data row
1624
+ * @param {HTMLCanvasElement} canvas Canvas element
1625
+ * @private
1626
+ */
1627
+ dispatchCanvasDataOver(d, canvas) {
1628
+ const $$ = this;
1629
+ const { config, state } = $$;
1630
+ const key = getCanvasDataKey(d);
1631
+ if (state.canvasDataHoverKey === key) return;
1632
+ $$.dispatchCanvasDataOut(canvas);
1633
+ state.canvasDataHover = d;
1634
+ state.canvasDataHoverKey = key;
1635
+ config.interaction_enabled && d && callFn(config.data_onover, $$.api, d, canvas);
1636
+ },
1637
+ /**
1638
+ * Dispatch canvas data.onclick callback for a pointer position.
1639
+ * @param {Event} event Input event
1640
+ * @param {boolean} markInputClick Whether to suppress following compatibility click
1641
+ * @returns {object|null} Clicked data row
1642
+ * @private
1643
+ */
1644
+ dispatchCanvasDataClick(event, markInputClick = false) {
1645
+ const $$ = this;
1646
+ const { config, $el } = $$;
1647
+ const canvas = $el.canvas.node();
1648
+ const d = getCanvasEventDatum($$, event, true);
1649
+ if (!d || isDuplicateCanvasInputClick($$, d)) return d;
1650
+ if (config.interaction_enabled) {
1651
+ const dataRows = config.data_selection_grouped ? $$.filterTargetsToShow($$.data.targets).map((target) => target.values[d.index]).filter(Boolean) : [d];
1652
+ $$.toggleCanvasSelection?.(dataRows);
1653
+ dataRows.forEach((row) => callFn(config.data_onclick, $$.api, row, canvas));
1654
+ markInputClick && markCanvasInputClick($$, d);
1655
+ }
1656
+ return d;
1657
+ },
1658
+ /**
1659
+ * Update canvas subchart brush domain from an input event.
1660
+ * @param {Event} event Input event
1661
+ * @returns {boolean} Whether the brush was updated
1662
+ * @private
1663
+ */
1664
+ updateCanvasSubchartBrush(event) {
1665
+ const $$ = this;
1666
+ const { config, state } = $$;
1667
+ const start = state.canvasSubchartBrushStart;
1668
+ const origin = state.canvasSubchartBrushOrigin;
1669
+ const mode = state.canvasSubchartBrushMode;
1670
+ const coord = getCanvasSubchartBrushCoord($$, event, true);
1671
+ if (config.subchart_brush_enabled === false || !state.canvasSubchartBrushDragging || start === null || coord === null || !mode) return false;
1672
+ const delta = coord - start;
1673
+ if (Math.abs(delta) > CANVAS_SUBCHART_CLICK_TOLERANCE) state.canvasSubchartBrushMoved = true;
1674
+ if (!state.canvasSubchartBrushMoved) {
1675
+ event.preventDefault?.();
1676
+ return true;
1677
+ }
1678
+ let selection;
1679
+ if (mode === "move" && origin) {
1680
+ const [extentStart, extentEnd] = getCanvasSubchartBrushExtent($$);
1681
+ const size = origin[1] - origin[0];
1682
+ let nextStart = origin[0] + delta;
1683
+ let nextEnd = origin[1] + delta;
1684
+ if (nextStart < extentStart) {
1685
+ nextEnd += extentStart - nextStart;
1686
+ nextStart = extentStart;
1687
+ }
1688
+ if (nextEnd > extentEnd) {
1689
+ nextStart -= nextEnd - extentEnd;
1690
+ nextEnd = extentEnd;
1691
+ }
1692
+ selection = [Math.max(extentStart, Math.min(extentEnd - size, nextStart)), Math.min(extentEnd, Math.max(extentStart + size, nextEnd))];
1693
+ } else if (mode === "resize-start" && origin) selection = clampCanvasSubchartSelection($$, coord, origin[1]);
1694
+ else if (mode === "resize-end" && origin) selection = clampCanvasSubchartSelection($$, origin[0], coord);
1695
+ else selection = clampCanvasSubchartSelection($$, start, coord);
1696
+ const domain = getCanvasSubchartDomainFromCoords($$, selection[0], selection[1]);
1697
+ $$.setCanvasSubchartDomain(domain, true);
1698
+ state.cancelClick = true;
1699
+ event.preventDefault?.();
1700
+ return true;
1701
+ },
1702
+ /**
1703
+ * Update cursor while hovering over the canvas subchart brush area.
1704
+ * @param {Event} event Input event
1705
+ * @returns {boolean} Whether the pointer is over the subchart
1706
+ * @private
1707
+ */
1708
+ updateCanvasSubchartCursor(event) {
1709
+ const $$ = this;
1710
+ const canvas = $$.$el.canvas.node();
1711
+ if ($$.config.subchart_brush_enabled === false) {
1712
+ canvas.style.cursor = "";
1713
+ return false;
1714
+ }
1715
+ const coord = getCanvasSubchartBrushCoord($$, event);
1716
+ if (coord === null) {
1717
+ canvas.style.cursor = "";
1718
+ return false;
1719
+ }
1720
+ const mode = getCanvasSubchartBrushMode($$, coord);
1721
+ canvas.style.cursor = getCanvasSubchartCursor($$, mode);
1722
+ return true;
1723
+ },
1724
+ /**
1725
+ * Start a canvas subchart brush gesture.
1726
+ * @param {Event} event Mouse, pointer or touch event
1727
+ * @returns {boolean} Whether brushing started
1728
+ * @private
1729
+ */
1730
+ startCanvasSubchartBrush(event) {
1731
+ const $$ = this;
1732
+ const { state } = $$;
1733
+ if ($$.config.subchart_brush_enabled === false) return false;
1734
+ const coord = getCanvasSubchartBrushCoord($$, event);
1735
+ if (coord === null) return false;
1736
+ const mode = getCanvasSubchartBrushMode($$, coord);
1737
+ state.event = event;
1738
+ state.canvasSubchartBrushDragging = true;
1739
+ state.canvasSubchartBrushMode = mode;
1740
+ state.canvasSubchartBrushStart = coord;
1741
+ state.canvasSubchartBrushOrigin = getCanvasSubchartBrushSelection($$);
1742
+ state.canvasSubchartBrushMoved = false;
1743
+ state.cancelClick = true;
1744
+ $$.setDragStatus(true);
1745
+ event.preventDefault?.();
1746
+ return true;
1747
+ },
1748
+ /**
1749
+ * End a canvas subchart brush gesture.
1750
+ * @param {Event} event Mouse, pointer or touch event
1751
+ * @returns {boolean} Whether brushing ended
1752
+ * @private
1753
+ */
1754
+ endCanvasSubchartBrush(event) {
1755
+ const $$ = this;
1756
+ const { state } = $$;
1757
+ if (!state.canvasSubchartBrushDragging) return false;
1758
+ $$.updateCanvasSubchartBrush(event);
1759
+ const shouldClear = state.canvasSubchartBrushMode === "select" && !state.canvasSubchartBrushMoved;
1760
+ const shouldCallback = state.canvasSubchartBrushMoved || shouldClear;
1761
+ if (shouldClear) $$.clearCanvasSubchartDomain?.(true, true);
1762
+ else if (shouldCallback) $$.config.subchart_onbrush.bind($$.api)(state.domain ?? $$.scale.x.orgDomain());
1763
+ state.canvasSubchartBrushDragging = false;
1764
+ state.canvasSubchartBrushMode = null;
1765
+ state.canvasSubchartBrushStart = null;
1766
+ state.canvasSubchartBrushOrigin = null;
1767
+ state.canvasSubchartBrushMoved = false;
1768
+ $$.setDragStatus(false);
1769
+ event.preventDefault?.();
1770
+ return true;
1771
+ },
1772
+ /**
1773
+ * Cancel a canvas subchart brush gesture without applying callbacks.
1774
+ * @param {Event} event Mouse, pointer or touch event
1775
+ * @returns {boolean} Whether brushing was cancelled
1776
+ * @private
1777
+ */
1778
+ cancelCanvasSubchartBrush(event) {
1779
+ const $$ = this;
1780
+ const { state } = $$;
1781
+ if (!state.canvasSubchartBrushDragging) return false;
1782
+ state.canvasSubchartBrushDragging = false;
1783
+ state.canvasSubchartBrushMode = null;
1784
+ state.canvasSubchartBrushStart = null;
1785
+ state.canvasSubchartBrushOrigin = null;
1786
+ state.canvasSubchartBrushMoved = false;
1787
+ $$.setDragStatus(false);
1788
+ event.preventDefault?.();
1789
+ return true;
1790
+ },
1791
+ /**
1792
+ * Start mouse-driven canvas subchart brushing.
1793
+ * @param {MouseEvent} event Mouse event
1794
+ * @returns {boolean} Whether brushing started
1795
+ * @private
1796
+ */
1797
+ onCanvasSubchartBrushStart(event) {
1798
+ const $$ = this;
1799
+ if (!$$.startCanvasSubchartBrush(event)) return false;
1800
+ const move = (event) => {
1801
+ $$.updateCanvasSubchartBrush(event);
1802
+ };
1803
+ const end = (event) => {
1804
+ $$.endCanvasSubchartBrush(event);
1805
+ win.removeEventListener("mousemove", move);
1806
+ win.removeEventListener("mouseup", end);
1807
+ };
1808
+ win.addEventListener("mousemove", move);
1809
+ win.addEventListener("mouseup", end);
1810
+ return true;
1811
+ },
1812
+ /**
1813
+ * Handle canvas click and dispatch shape-level data onclick.
1814
+ * @param {MouseEvent} event Mouse click event
1815
+ * @private
1816
+ */
1817
+ onCanvasClick(event) {
1818
+ const $$ = this;
1819
+ const { config, state } = $$;
1820
+ state.event = event;
1821
+ if (state.flowing || state.cancelClick) {
1822
+ state.cancelClick = false;
1823
+ return;
1824
+ }
1825
+ $$.dispatchCanvasDataClick(event);
1826
+ config.onclick?.bind($$.api)(event);
1827
+ },
1828
+ /**
1829
+ * Start mouse-driven canvas draggable selection.
1830
+ * @param {MouseEvent} event Mouse event
1831
+ * @private
1832
+ */
1833
+ onCanvasSelectionDragStart(event) {
1834
+ const $$ = this;
1835
+ const { state } = $$;
1836
+ if (!$$.startCanvasSelectionDrag(event)) return;
1837
+ const move = (event) => {
1838
+ $$.updateCanvasSelectionDrag(event);
1839
+ };
1840
+ const end = (event) => {
1841
+ $$.endCanvasSelectionDrag(event);
1842
+ win.removeEventListener("mousemove", move);
1843
+ win.removeEventListener("mouseup", end);
1844
+ state.canvasSelectionDragMoveHandler = null;
1845
+ state.canvasSelectionDragEndHandler = null;
1846
+ };
1847
+ state.canvasSelectionDragMoveHandler = move;
1848
+ state.canvasSelectionDragEndHandler = end;
1849
+ win.addEventListener("mousemove", move);
1850
+ win.addEventListener("mouseup", end);
1851
+ },
1852
+ /**
1853
+ * Start non-mouse pointer-driven canvas subchart brushing.
1854
+ * @param {PointerEvent} event Pointer event
1855
+ * @private
1856
+ */
1857
+ onCanvasPointerDown(event) {
1858
+ if (!shouldHandleCanvasPointerEvent(this, event)) return;
1859
+ const $$ = this;
1860
+ const canvas = $$.$el.canvas.node();
1861
+ if (!$$.startCanvasSubchartBrush(event)) return;
1862
+ const pointerId = event.pointerId;
1863
+ const matchesPointer = (event) => event.pointerId === pointerId;
1864
+ const move = (event) => {
1865
+ matchesPointer(event) && $$.updateCanvasSubchartBrush(event);
1866
+ };
1867
+ const end = (event) => {
1868
+ if (matchesPointer(event)) {
1869
+ $$.endCanvasSubchartBrush(event);
1870
+ cleanup();
1871
+ }
1872
+ };
1873
+ const cancel = (event) => {
1874
+ if (matchesPointer(event)) {
1875
+ $$.cancelCanvasSubchartBrush(event);
1876
+ cleanup();
1877
+ }
1878
+ };
1879
+ /**
1880
+ * Remove temporary pointer brush listeners.
1881
+ * @private
1882
+ */
1883
+ function cleanup() {
1884
+ win.removeEventListener("pointermove", move);
1885
+ win.removeEventListener("pointerup", end);
1886
+ win.removeEventListener("pointercancel", cancel);
1887
+ try {
1888
+ canvas.releasePointerCapture?.(pointerId);
1889
+ } catch {}
1890
+ }
1891
+ try {
1892
+ canvas.setPointerCapture?.(pointerId);
1893
+ } catch {}
1894
+ win.addEventListener("pointermove", move);
1895
+ win.addEventListener("pointerup", end);
1896
+ win.addEventListener("pointercancel", cancel);
1897
+ },
1898
+ /**
1899
+ * Handle non-mouse pointer entering the canvas.
1900
+ * @param {PointerEvent} event Pointer event
1901
+ * @private
1902
+ */
1903
+ onCanvasPointerEnter(event) {
1904
+ if (!shouldHandleCanvasPointerEvent(this, event)) return;
1905
+ this.state.event = event;
1906
+ this.config.onover?.bind(this.api)(event);
1907
+ },
1908
+ /**
1909
+ * Handle non-mouse pointer movement over the canvas.
1910
+ * @param {PointerEvent} event Pointer event
1911
+ * @private
1912
+ */
1913
+ onCanvasPointerMove(event) {
1914
+ if (!shouldHandleCanvasPointerEvent(this, event)) return;
1915
+ if (this.updateCanvasSubchartBrush(event)) return;
1916
+ this.onCanvasMouseMove(event);
1917
+ },
1918
+ /**
1919
+ * Handle non-mouse pointer click.
1920
+ * @param {PointerEvent} event Pointer event
1921
+ * @private
1922
+ */
1923
+ onCanvasPointerUp(event) {
1924
+ if (!shouldHandleCanvasPointerEvent(this, event)) return;
1925
+ this.state.event = event;
1926
+ if (this.endCanvasSubchartBrush(event)) {
1927
+ this.config.onout?.bind(this.api)(event);
1928
+ return;
1929
+ }
1930
+ this.dispatchCanvasDataClick(event, true);
1931
+ this.dispatchCanvasDataOut(this.$el.canvas.node());
1932
+ },
1933
+ /**
1934
+ * Handle non-mouse pointer leaving the canvas.
1935
+ * @param {PointerEvent} event Pointer event
1936
+ * @private
1937
+ */
1938
+ onCanvasPointerOut(event) {
1939
+ if (!shouldHandleCanvasPointerEvent(this, event)) return;
1940
+ if (this.state.canvasSubchartBrushDragging) return;
1941
+ this.state.event = event;
1942
+ this.onCanvasMouseOut();
1943
+ this.config.onout?.bind(this.api)(event);
1944
+ },
1945
+ /**
1946
+ * Handle non-mouse pointer cancellation.
1947
+ * @param {PointerEvent} event Pointer event
1948
+ * @private
1949
+ */
1950
+ onCanvasPointerCancel(event) {
1951
+ if (!shouldHandleCanvasPointerEvent(this, event)) return;
1952
+ this.state.event = event;
1953
+ if (this.cancelCanvasSubchartBrush(event)) {
1954
+ this.config.onout?.bind(this.api)(event);
1955
+ return;
1956
+ }
1957
+ this.onCanvasPointerOut(event);
1958
+ },
1959
+ /**
1960
+ * Handle touch start over the canvas.
1961
+ * @param {TouchEvent} event Touch event
1962
+ * @private
1963
+ */
1964
+ onCanvasTouchStart(event) {
1965
+ if (event.touches.length > 1) return;
1966
+ this.state.event = event;
1967
+ if (this.startCanvasSubchartBrush(event)) return;
1968
+ if (this.startCanvasSelectionDrag(event)) return;
1969
+ this.config.onover?.bind(this.api)(event);
1970
+ this.onCanvasMouseMove(event);
1971
+ },
1972
+ /**
1973
+ * Handle touch move over the canvas.
1974
+ * @param {TouchEvent} event Touch event
1975
+ * @private
1976
+ */
1977
+ onCanvasTouchMove(event) {
1978
+ if (event.touches.length > 1) return;
1979
+ if (this.updateCanvasSubchartBrush(event)) return;
1980
+ if (this.updateCanvasSelectionDrag(event)) return;
1981
+ this.onCanvasMouseMove(event);
1982
+ },
1983
+ /**
1984
+ * Handle touch end over the canvas.
1985
+ * @param {TouchEvent} event Touch event
1986
+ * @private
1987
+ */
1988
+ onCanvasTouchEnd(event) {
1989
+ this.state.event = event;
1990
+ if (this.endCanvasSubchartBrush(event)) {
1991
+ this.config.onout?.bind(this.api)(event);
1992
+ return;
1993
+ }
1994
+ if (this.endCanvasSelectionDrag(event)) {
1995
+ this.config.onout?.bind(this.api)(event);
1996
+ return;
1997
+ }
1998
+ this.dispatchCanvasDataClick(event, true);
1999
+ this.dispatchCanvasDataOut(this.$el.canvas.node());
2000
+ this.config.onout?.bind(this.api)(event);
2001
+ },
2002
+ /**
2003
+ * Handle touch cancellation.
2004
+ * @param {TouchEvent} event Touch event
2005
+ * @private
2006
+ */
2007
+ onCanvasTouchCancel(event) {
2008
+ this.state.event = event;
2009
+ this.cancelCanvasSubchartBrush(event);
2010
+ this.endCanvasSelectionDrag(event);
2011
+ this.onCanvasMouseOut();
2012
+ this.config.onout?.bind(this.api)(event);
2013
+ },
2014
+ /**
2015
+ * Update canvas focus state and tooltip on pointer movement.
2016
+ * @param {Event} event Mouse, pointer or touch move event
2017
+ * @private
2018
+ */
2019
+ onCanvasMouseMove(event) {
2020
+ const $$ = this;
2021
+ const { config, state, $el } = $$;
2022
+ const canvas = $el.canvas.node();
2023
+ state.event = event;
2024
+ if (state.flowing) return;
2025
+ if (state.canvasSelectionDragging) return;
2026
+ if ($$.updateCanvasSubchartCursor?.(event)) {
2027
+ $$.dispatchCanvasDataOut(canvas);
2028
+ if (state.canvasFocusKey) {
2029
+ state.canvasFocusKey = null;
2030
+ $$.clearCanvasFocus();
2031
+ }
2032
+ $$.hideTooltip?.();
2033
+ return;
2034
+ }
2035
+ const rawPoint = getCanvasEventPoint($$, event);
2036
+ const point = rawPoint && (getCanvasMainPointFromSubchart($$, rawPoint) || rawPoint);
2037
+ const d = point ? getCanvasHoverDatumFromPoint($$, point) : null;
2038
+ if (!d) {
2039
+ $$.dispatchCanvasDataOut(canvas);
2040
+ if (state.canvasFocusKey) {
2041
+ state.canvasFocusKey = null;
2042
+ $$.clearCanvasFocus();
2043
+ }
2044
+ if (rawPoint && config.axis_tooltip && isCanvasAxisTooltipArea($$, rawPoint)) {
2045
+ $$.renderCanvasAxisTooltip(rawPoint);
2046
+ $$.hideTooltip?.();
2047
+ return;
2048
+ }
2049
+ $$.hideTooltip?.();
2050
+ return;
2051
+ }
2052
+ $$.dispatchCanvasDataOver(d, canvas);
2053
+ const selectedData = getCanvasTooltipData($$, d);
2054
+ const focusData = getCanvasFocusData($$, d, selectedData);
2055
+ const focusKey = focusData.map((v) => `${v.id}:${v.index}`).join("|");
2056
+ if (state.canvasFocusKey !== focusKey || config.axis_tooltip) {
2057
+ state.canvasFocusKey = focusKey;
2058
+ $$.renderCanvasFocus(focusData, point);
2059
+ }
2060
+ $$.showTooltip?.(selectedData, canvas);
2061
+ },
2062
+ /**
2063
+ * Clear focus and tooltip state when the pointer leaves the canvas.
2064
+ * @private
2065
+ */
2066
+ onCanvasMouseOut() {
2067
+ const canvas = this.$el.canvas.node();
2068
+ canvas.style.cursor = "";
2069
+ this.dispatchCanvasDataOut(canvas);
2070
+ if (this.state.canvasFocusKey) {
2071
+ this.state.canvasFocusKey = null;
2072
+ this.clearCanvasFocus();
2073
+ } else if (this.config.axis_tooltip) this.clearCanvasFocus();
2074
+ this.hideTooltip?.();
2075
+ },
2076
+ /**
2077
+ * Show canvas tooltip from linked tooltip propagation.
2078
+ * @param {number} index Data index
2079
+ * @returns {boolean} Whether linked tooltip was shown
2080
+ * @private
2081
+ */
2082
+ showCanvasLinkedTooltip(index) {
2083
+ const $$ = this;
2084
+ const { $el, state } = $$;
2085
+ const canvas = $el.canvas?.node();
2086
+ const d = $$.filterTargetsToShow($$.data.targets).map((target) => target.values[index]).find(Boolean);
2087
+ if (!canvas || !d) {
2088
+ $$.hideTooltip?.();
2089
+ return false;
2090
+ }
2091
+ const selectedData = getCanvasTooltipData($$, d);
2092
+ const focus = selectedData.find((v) => v && hasCanvasDrawableValue($$, v)) || selectedData[0];
2093
+ if (!selectedData.length || !focus) {
2094
+ $$.hideTooltip?.();
2095
+ return false;
2096
+ }
2097
+ const { left, top } = getBoundingRect(canvas, true);
2098
+ const point = getRenderDataPoint($$, focus);
2099
+ const eventPoint = [state.margin.left + point.x, state.margin.top + point.y];
2100
+ state.event = {
2101
+ clientX: left + eventPoint[0],
2102
+ clientY: top + eventPoint[1],
2103
+ currentTarget: canvas,
2104
+ target: canvas
2105
+ };
2106
+ state.canvasFocusKey = selectedData.map((v) => `${v.id}:${v.index}`).join("|");
2107
+ $$.renderCanvasFocus(selectedData, eventPoint);
2108
+ $$.showTooltip?.(selectedData, canvas);
2109
+ return true;
2110
+ },
2111
+ /**
2112
+ * Draw drag-zoom brush overlay on the cached canvas frame.
2113
+ * @param {number} start Start coordinate
2114
+ * @param {number} end End coordinate
2115
+ * @private
2116
+ */
2117
+ renderCanvasZoomBrush(start, end) {
2118
+ const $$ = this;
2119
+ $$.canvasEngine.withOverlay((ctx) => {
2120
+ $$.canvasRenderer.withContext(ctx, () => {
2121
+ $$.canvasRenderer.drawZoomBrush($$, start, end);
2122
+ });
2123
+ });
2124
+ },
2125
+ /**
2126
+ * Clear drag-zoom brush overlay.
2127
+ * @private
2128
+ */
2129
+ clearCanvasZoomBrush() {
2130
+ this.canvasEngine.clearOverlay();
2131
+ },
2132
+ /**
2133
+ * Draw selection drag overlay on the cached canvas frame.
2134
+ * @param {object} rect Selection rectangle
2135
+ * @private
2136
+ */
2137
+ renderCanvasSelectionDrag(rect) {
2138
+ const $$ = this;
2139
+ $$.canvasEngine.withOverlay((ctx) => {
2140
+ $$.canvasRenderer.withContext(ctx, () => {
2141
+ $$.canvasRenderer.drawSelectionDragArea($$, rect);
2142
+ });
2143
+ });
2144
+ },
2145
+ /**
2146
+ * Draw a complete canvas frame and optionally rebuild hit indexes.
2147
+ * @param {object} shape Cached draw shape object
2148
+ * @param {Array} focusData Focused data rows
2149
+ * @param {boolean} rebuildHit Whether to rebuild hit indexes
2150
+ * @private
2151
+ */
2152
+ renderCanvasFrame(shape, focusData, rebuildHit = false) {
2153
+ const $$ = this;
2154
+ const { state } = $$;
2155
+ const drawShape = shape || state.canvasShape || $$.getDrawShape();
2156
+ state.canvasShape = drawShape;
2157
+ state._canvasVisibleRangeCache = null;
2158
+ state._canvasXTickValuesCache = null;
2159
+ $$.canvasEngine.beginFrame(state.current.width, $$.getCanvasSurfaceHeight());
2160
+ try {
2161
+ $$.canvasRenderer.drawBackground($$);
2162
+ $$.canvasAxisRenderer.drawTitle($$);
2163
+ state.hasAxis && $$.canvasAxisRenderer.draw($$);
2164
+ $$.canvasRenderer.draw($$, drawShape);
2165
+ state.hasAxis && $$.config.grid_lines_front && $$.canvasAxisRenderer.drawGridLines($$);
2166
+ $$.canvasRenderer.drawSubchart($$, drawShape);
2167
+ state.hasAxis && $$.canvasAxisRenderer.drawSubXAxis($$);
2168
+ state.hasAxis && $$.canvasAxisRenderer.drawSubYAxes($$);
2169
+ $$.canvasRenderer.drawEmptyLabel($$);
2170
+ rebuildHit && $$.hitDetector.rebuild($$, drawShape);
2171
+ } finally {
2172
+ $$.canvasEngine.endFrame();
2173
+ }
2174
+ $$.canvasEngine.clearOverlay();
2175
+ state.canvasFocusMainRedraw = false;
2176
+ focusData && $$.renderCanvasFocus(focusData);
2177
+ },
2178
+ /**
2179
+ * Restore the cached frame and draw focus overlays.
2180
+ * @param {Array} focusData Focused data rows
2181
+ * @param {Array} point Canvas-local pointer coordinate
2182
+ * @private
2183
+ */
2184
+ renderCanvasFocus(focusData, point) {
2185
+ const $$ = this;
2186
+ const { state } = $$;
2187
+ const withMainRedraw = $$.canvasRenderer.hasExpandedShapeFocus?.($$, focusData);
2188
+ if (withMainRedraw) {
2189
+ const drawShape = state.canvasShape || $$.getDrawShape();
2190
+ $$.canvasEngine.beginFrame(state.current.width, $$.getCanvasSurfaceHeight());
2191
+ try {
2192
+ $$.canvasRenderer.drawBackground($$);
2193
+ $$.canvasAxisRenderer.drawTitle($$);
2194
+ state.hasAxis && $$.canvasAxisRenderer.draw($$);
2195
+ $$.canvasRenderer.draw($$, drawShape, focusData);
2196
+ state.hasAxis && $$.config.grid_lines_front && $$.canvasAxisRenderer.drawGridLines($$);
2197
+ $$.canvasRenderer.drawSubchart($$, drawShape);
2198
+ state.hasAxis && $$.canvasAxisRenderer.drawSubXAxis($$);
2199
+ state.hasAxis && $$.canvasAxisRenderer.drawSubYAxes($$);
2200
+ $$.canvasRenderer.drawEmptyLabel($$);
2201
+ } finally {
2202
+ $$.canvasEngine.endFrame();
2203
+ }
2204
+ }
2205
+ state.canvasFocusMainRedraw = !!withMainRedraw;
2206
+ $$.canvasEngine.withOverlay((ctx) => {
2207
+ $$.canvasRenderer.withContext(ctx, () => {
2208
+ $$.canvasRenderer.drawFocus($$, focusData);
2209
+ });
2210
+ $$.canvasAxisRenderer.withContext(ctx, () => {
2211
+ $$.canvasAxisRenderer.drawFocusedXAxisTick($$, focusData);
2212
+ point && $$.canvasAxisRenderer.drawAxisTooltip($$, point);
2213
+ });
2214
+ });
2215
+ },
2216
+ /**
2217
+ * Draw only the canvas axis tooltip overlay.
2218
+ * @param {Array} point Canvas-local pointer coordinate
2219
+ * @private
2220
+ */
2221
+ renderCanvasAxisTooltip(point) {
2222
+ const $$ = this;
2223
+ $$.canvasEngine.withOverlay((ctx) => {
2224
+ $$.canvasAxisRenderer.withContext(ctx, () => {
2225
+ $$.canvasAxisRenderer.drawAxisTooltip($$, point);
2226
+ });
2227
+ });
2228
+ },
2229
+ /**
2230
+ * Restore the cached canvas frame without focus overlays.
2231
+ * @private
2232
+ */
2233
+ clearCanvasFocus() {
2234
+ const $$ = this;
2235
+ if ($$.state.canvasFocusMainRedraw) {
2236
+ $$.state.canvasFocusMainRedraw = false;
2237
+ $$.renderCanvasFrame(void 0, null, false);
2238
+ } else $$.canvasEngine?.clearOverlay();
2239
+ },
2240
+ /**
2241
+ * Resize canvas surfaces and reload canvas theme values.
2242
+ * @private
2243
+ */
2244
+ resizeCanvas() {
2245
+ const $$ = this;
2246
+ const { config, state, $el } = $$;
2247
+ const container = $el.chart.node();
2248
+ $el.chart.style("min-height", `${state.current.height}px`);
2249
+ $$.canvasEngine?.resize(state.current.width, $$.getCanvasSurfaceHeight());
2250
+ $$.canvasTheme?.reload(container, config.canvas_theme);
2251
+ }
2653
2252
  };
2654
2253
  /**
2655
- * Register canvas rendering modules and return canvas render mode.
2656
- * @returns {string} Canvas render mode
2657
- */
2254
+ * Register canvas rendering modules and return canvas render mode.
2255
+ * @returns {string} Canvas render mode
2256
+ */
2658
2257
  let canvas = () => {
2659
- extend(ChartInternal.prototype, canvasInternal);
2660
- return (canvas = () => "canvas")();
2258
+ extend(ChartInternal.prototype, canvasInternal);
2259
+ return (canvas = () => "canvas")();
2661
2260
  };
2662
-
2261
+ //#endregion
2663
2262
  export { canvas };