@trismegisto/charts 3.3.14 → 4.0.0

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 (297) hide show
  1. package/LICENSE +56 -56
  2. package/MIGRATION.md +831 -0
  3. package/NOTICE +8 -13
  4. package/README.md +53 -32
  5. package/dist/core/bar-chart.d.ts +32 -0
  6. package/dist/core/bar-chart.js +108 -0
  7. package/dist/core/bar-chart.js.map +1 -0
  8. package/dist/core/boxplot-chart.d.ts +15 -0
  9. package/dist/core/boxplot-chart.js +44 -0
  10. package/dist/core/boxplot-chart.js.map +1 -0
  11. package/dist/core/bullet-chart.d.ts +29 -0
  12. package/dist/core/bullet-chart.js +93 -0
  13. package/dist/core/bullet-chart.js.map +1 -0
  14. package/dist/core/calendar-heatmap.d.ts +20 -0
  15. package/dist/core/calendar-heatmap.js +78 -0
  16. package/dist/core/calendar-heatmap.js.map +1 -0
  17. package/dist/core/category-range.d.ts +15 -0
  18. package/dist/core/category-range.js +35 -0
  19. package/dist/core/category-range.js.map +1 -0
  20. package/dist/core/chart-host.d.ts +36 -0
  21. package/dist/core/chart-host.js +209 -0
  22. package/dist/core/chart-host.js.map +1 -0
  23. package/dist/core/charts-i18n.d.ts +25 -0
  24. package/dist/core/charts-i18n.js +33 -0
  25. package/dist/core/charts-i18n.js.map +1 -0
  26. package/dist/core/charts-messages.d.ts +143 -0
  27. package/dist/core/charts-messages.en.d.ts +2 -0
  28. package/dist/core/charts-messages.en.js +143 -0
  29. package/dist/core/charts-messages.en.js.map +1 -0
  30. package/dist/core/charts-messages.es.d.ts +2 -0
  31. package/dist/core/charts-messages.es.js +143 -0
  32. package/dist/core/charts-messages.es.js.map +1 -0
  33. package/dist/core/charts-messages.js +143 -0
  34. package/dist/core/charts-messages.js.map +1 -0
  35. package/dist/core/colors.d.ts +27 -0
  36. package/dist/core/colors.js +76 -0
  37. package/dist/core/colors.js.map +1 -0
  38. package/dist/core/context.d.ts +42 -0
  39. package/dist/core/context.js +36 -0
  40. package/dist/core/context.js.map +1 -0
  41. package/dist/core/engine-locale.d.ts +4 -0
  42. package/dist/core/engine-locale.js +38 -0
  43. package/dist/core/engine-locale.js.map +1 -0
  44. package/dist/core/format.d.ts +13 -0
  45. package/dist/core/format.js +64 -0
  46. package/dist/core/format.js.map +1 -0
  47. package/dist/core/frame.d.ts +31 -0
  48. package/dist/core/frame.js +64 -0
  49. package/dist/core/frame.js.map +1 -0
  50. package/dist/core/funnel-chart.d.ts +8 -0
  51. package/dist/core/funnel-chart.js +30 -0
  52. package/dist/core/funnel-chart.js.map +1 -0
  53. package/dist/core/gauge-chart.d.ts +44 -0
  54. package/dist/core/gauge-chart.js +186 -0
  55. package/dist/core/gauge-chart.js.map +1 -0
  56. package/dist/core/gauge-layout.d.ts +67 -0
  57. package/dist/core/gauge-layout.js +140 -0
  58. package/dist/core/gauge-layout.js.map +1 -0
  59. package/dist/core/heatmap-chart.d.ts +22 -0
  60. package/dist/core/heatmap-chart.js +62 -0
  61. package/dist/core/heatmap-chart.js.map +1 -0
  62. package/dist/core/index.d.ts +46 -0
  63. package/dist/core/index.js +52 -0
  64. package/dist/core/index.js.map +1 -0
  65. package/dist/core/line-chart.d.ts +43 -0
  66. package/dist/core/line-chart.js +99 -0
  67. package/dist/core/line-chart.js.map +1 -0
  68. package/dist/core/line-extras.d.ts +20 -0
  69. package/dist/core/line-extras.js +49 -0
  70. package/dist/core/line-extras.js.map +1 -0
  71. package/dist/core/linear-gauge.d.ts +64 -0
  72. package/dist/core/linear-gauge.js +78 -0
  73. package/dist/core/linear-gauge.js.map +1 -0
  74. package/dist/core/live-session.d.ts +58 -0
  75. package/dist/core/live-session.js +200 -0
  76. package/dist/core/live-session.js.map +1 -0
  77. package/dist/core/live.d.ts +78 -0
  78. package/dist/core/live.js +245 -0
  79. package/dist/core/live.js.map +1 -0
  80. package/dist/core/navigation.d.ts +20 -0
  81. package/dist/core/navigation.js +62 -0
  82. package/dist/core/navigation.js.map +1 -0
  83. package/dist/core/normalize.d.ts +19 -0
  84. package/dist/core/normalize.js +51 -0
  85. package/dist/core/normalize.js.map +1 -0
  86. package/dist/core/observe.d.ts +28 -0
  87. package/dist/core/observe.js +151 -0
  88. package/dist/core/observe.js.map +1 -0
  89. package/dist/core/options.d.ts +29 -0
  90. package/dist/core/options.js +69 -0
  91. package/dist/core/options.js.map +1 -0
  92. package/dist/core/pie-chart.d.ts +25 -0
  93. package/dist/core/pie-chart.js +99 -0
  94. package/dist/core/pie-chart.js.map +1 -0
  95. package/dist/core/radar-chart.d.ts +18 -0
  96. package/dist/core/radar-chart.js +34 -0
  97. package/dist/core/radar-chart.js.map +1 -0
  98. package/dist/core/range-interaction.d.ts +62 -0
  99. package/dist/core/range-interaction.js +196 -0
  100. package/dist/core/range-interaction.js.map +1 -0
  101. package/dist/core/range.d.ts +83 -0
  102. package/dist/core/range.js +200 -0
  103. package/dist/core/range.js.map +1 -0
  104. package/dist/core/references.d.ts +25 -0
  105. package/dist/core/references.js +71 -0
  106. package/dist/core/references.js.map +1 -0
  107. package/dist/core/sankey-chart.d.ts +15 -0
  108. package/dist/core/sankey-chart.js +28 -0
  109. package/dist/core/sankey-chart.js.map +1 -0
  110. package/dist/core/scale-legend.d.ts +10 -0
  111. package/dist/core/scale-legend.js +16 -0
  112. package/dist/core/scale-legend.js.map +1 -0
  113. package/dist/core/scatter-chart.d.ts +38 -0
  114. package/dist/core/scatter-chart.js +74 -0
  115. package/dist/core/scatter-chart.js.map +1 -0
  116. package/dist/core/scope-cache.d.ts +6 -0
  117. package/dist/core/scope-cache.js +49 -0
  118. package/dist/core/scope-cache.js.map +1 -0
  119. package/dist/core/series-extras.d.ts +46 -0
  120. package/dist/core/series-extras.js +125 -0
  121. package/dist/core/series-extras.js.map +1 -0
  122. package/dist/core/sparkline-chart.d.ts +31 -0
  123. package/dist/core/sparkline-chart.js +69 -0
  124. package/dist/core/sparkline-chart.js.map +1 -0
  125. package/dist/core/stats.d.ts +12 -0
  126. package/dist/core/stats.js +23 -0
  127. package/dist/core/stats.js.map +1 -0
  128. package/dist/core/theme.d.ts +9 -0
  129. package/dist/core/theme.js +138 -0
  130. package/dist/core/theme.js.map +1 -0
  131. package/dist/core/time-series-chart.d.ts +91 -0
  132. package/dist/core/time-series-chart.js +390 -0
  133. package/dist/core/time-series-chart.js.map +1 -0
  134. package/dist/core/treemap-chart.d.ts +21 -0
  135. package/dist/core/treemap-chart.js +41 -0
  136. package/dist/core/treemap-chart.js.map +1 -0
  137. package/dist/core/types.d.ts +67 -0
  138. package/dist/core/types.js +2 -0
  139. package/dist/core/types.js.map +1 -0
  140. package/dist/core/view.d.ts +95 -0
  141. package/dist/core/view.js +2 -0
  142. package/dist/core/view.js.map +1 -0
  143. package/dist/core/warn.d.ts +5 -0
  144. package/dist/core/warn.js +22 -0
  145. package/dist/core/warn.js.map +1 -0
  146. package/dist/core/waterfall-chart.d.ts +32 -0
  147. package/dist/core/waterfall-chart.js +114 -0
  148. package/dist/core/waterfall-chart.js.map +1 -0
  149. package/dist/engine/aria.d.ts +3 -0
  150. package/dist/engine/aria.js +18 -0
  151. package/dist/engine/aria.js.map +1 -0
  152. package/dist/engine/component/legend.d.ts +11 -0
  153. package/dist/engine/component/legend.js +348 -0
  154. package/dist/engine/component/legend.js.map +1 -0
  155. package/dist/engine/component/reference-marks.d.ts +46 -0
  156. package/dist/engine/component/reference-marks.js +197 -0
  157. package/dist/engine/component/reference-marks.js.map +1 -0
  158. package/dist/engine/component/text-style.d.ts +6 -0
  159. package/dist/engine/component/text-style.js +26 -0
  160. package/dist/engine/component/text-style.js.map +1 -0
  161. package/dist/engine/component/title.d.ts +2 -0
  162. package/dist/engine/component/title.js +90 -0
  163. package/dist/engine/component/title.js.map +1 -0
  164. package/dist/engine/component/tooltip.d.ts +40 -0
  165. package/dist/engine/component/tooltip.js +394 -0
  166. package/dist/engine/component/tooltip.js.map +1 -0
  167. package/dist/engine/component/view-window.d.ts +29 -0
  168. package/dist/engine/component/view-window.js +39 -0
  169. package/dist/engine/component/view-window.js.map +1 -0
  170. package/dist/engine/component/visual-map.d.ts +9 -0
  171. package/dist/engine/component/visual-map.js +381 -0
  172. package/dist/engine/component/visual-map.js.map +1 -0
  173. package/dist/engine/contract.d.ts +469 -0
  174. package/dist/engine/contract.js +9 -0
  175. package/dist/engine/contract.js.map +1 -0
  176. package/dist/engine/coord/axis.d.ts +55 -0
  177. package/dist/engine/coord/axis.js +358 -0
  178. package/dist/engine/coord/axis.js.map +1 -0
  179. package/dist/engine/coord/calendar.d.ts +44 -0
  180. package/dist/engine/coord/calendar.js +282 -0
  181. package/dist/engine/coord/calendar.js.map +1 -0
  182. package/dist/engine/coord/cartesian.d.ts +22 -0
  183. package/dist/engine/coord/cartesian.js +481 -0
  184. package/dist/engine/coord/cartesian.js.map +1 -0
  185. package/dist/engine/coord/polar.d.ts +24 -0
  186. package/dist/engine/coord/polar.js +232 -0
  187. package/dist/engine/coord/polar.js.map +1 -0
  188. package/dist/engine/coord/radar.d.ts +90 -0
  189. package/dist/engine/coord/radar.js +288 -0
  190. package/dist/engine/coord/radar.js.map +1 -0
  191. package/dist/engine/index.d.ts +3 -0
  192. package/dist/engine/index.js +5 -0
  193. package/dist/engine/index.js.map +1 -0
  194. package/dist/engine/instance.d.ts +101 -0
  195. package/dist/engine/instance.js +993 -0
  196. package/dist/engine/instance.js.map +1 -0
  197. package/dist/engine/label-layout.d.ts +3 -0
  198. package/dist/engine/label-layout.js +35 -0
  199. package/dist/engine/label-layout.js.map +1 -0
  200. package/dist/engine/locale.d.ts +6 -0
  201. package/dist/engine/locale.js +100 -0
  202. package/dist/engine/locale.js.map +1 -0
  203. package/dist/engine/model.d.ts +21 -0
  204. package/dist/engine/model.js +160 -0
  205. package/dist/engine/model.js.map +1 -0
  206. package/dist/engine/option/axis.d.ts +167 -0
  207. package/dist/engine/option/axis.js +2 -0
  208. package/dist/engine/option/axis.js.map +1 -0
  209. package/dist/engine/option/components.d.ts +434 -0
  210. package/dist/engine/option/components.js +2 -0
  211. package/dist/engine/option/components.js.map +1 -0
  212. package/dist/engine/registry.d.ts +7 -0
  213. package/dist/engine/registry.js +40 -0
  214. package/dist/engine/registry.js.map +1 -0
  215. package/dist/engine/render/path.d.ts +25 -0
  216. package/dist/engine/render/path.js +378 -0
  217. package/dist/engine/render/path.js.map +1 -0
  218. package/dist/engine/render/svg.d.ts +60 -0
  219. package/dist/engine/render/svg.js +651 -0
  220. package/dist/engine/render/svg.js.map +1 -0
  221. package/dist/engine/render/text.d.ts +13 -0
  222. package/dist/engine/render/text.js +144 -0
  223. package/dist/engine/render/text.js.map +1 -0
  224. package/dist/engine/scale.d.ts +48 -0
  225. package/dist/engine/scale.js +238 -0
  226. package/dist/engine/scale.js.map +1 -0
  227. package/dist/engine/series/bar.d.ts +67 -0
  228. package/dist/engine/series/bar.js +428 -0
  229. package/dist/engine/series/bar.js.map +1 -0
  230. package/dist/engine/series/boxplot.d.ts +31 -0
  231. package/dist/engine/series/boxplot.js +125 -0
  232. package/dist/engine/series/boxplot.js.map +1 -0
  233. package/dist/engine/series/cartesian-data.d.ts +38 -0
  234. package/dist/engine/series/cartesian-data.js +159 -0
  235. package/dist/engine/series/cartesian-data.js.map +1 -0
  236. package/dist/engine/series/circular-common.d.ts +50 -0
  237. package/dist/engine/series/circular-common.js +178 -0
  238. package/dist/engine/series/circular-common.js.map +1 -0
  239. package/dist/engine/series/circular-options.d.ts +151 -0
  240. package/dist/engine/series/circular-options.js +2 -0
  241. package/dist/engine/series/circular-options.js.map +1 -0
  242. package/dist/engine/series/common.d.ts +48 -0
  243. package/dist/engine/series/common.js +198 -0
  244. package/dist/engine/series/common.js.map +1 -0
  245. package/dist/engine/series/funnel.d.ts +37 -0
  246. package/dist/engine/series/funnel.js +204 -0
  247. package/dist/engine/series/funnel.js.map +1 -0
  248. package/dist/engine/series/gauge.d.ts +106 -0
  249. package/dist/engine/series/gauge.js +349 -0
  250. package/dist/engine/series/gauge.js.map +1 -0
  251. package/dist/engine/series/heatmap.d.ts +31 -0
  252. package/dist/engine/series/heatmap.js +222 -0
  253. package/dist/engine/series/heatmap.js.map +1 -0
  254. package/dist/engine/series/label-fit.d.ts +7 -0
  255. package/dist/engine/series/label-fit.js +48 -0
  256. package/dist/engine/series/label-fit.js.map +1 -0
  257. package/dist/engine/series/line.d.ts +65 -0
  258. package/dist/engine/series/line.js +354 -0
  259. package/dist/engine/series/line.js.map +1 -0
  260. package/dist/engine/series/mark-point.d.ts +4 -0
  261. package/dist/engine/series/mark-point.js +196 -0
  262. package/dist/engine/series/mark-point.js.map +1 -0
  263. package/dist/engine/series/pie.d.ts +64 -0
  264. package/dist/engine/series/pie.js +402 -0
  265. package/dist/engine/series/pie.js.map +1 -0
  266. package/dist/engine/series/radar.d.ts +34 -0
  267. package/dist/engine/series/radar.js +168 -0
  268. package/dist/engine/series/radar.js.map +1 -0
  269. package/dist/engine/series/sankey.d.ts +64 -0
  270. package/dist/engine/series/sankey.js +486 -0
  271. package/dist/engine/series/sankey.js.map +1 -0
  272. package/dist/engine/series/scatter.d.ts +40 -0
  273. package/dist/engine/series/scatter.js +167 -0
  274. package/dist/engine/series/scatter.js.map +1 -0
  275. package/dist/engine/series/treemap.d.ts +77 -0
  276. package/dist/engine/series/treemap.js +493 -0
  277. package/dist/engine/series/treemap.js.map +1 -0
  278. package/dist/engine/spec/compile.d.ts +9 -0
  279. package/dist/engine/spec/compile.js +593 -0
  280. package/dist/engine/spec/compile.js.map +1 -0
  281. package/dist/engine/spec/theme.d.ts +5 -0
  282. package/dist/engine/spec/theme.js +83 -0
  283. package/dist/engine/spec/theme.js.map +1 -0
  284. package/dist/engine/spec/types.d.ts +564 -0
  285. package/dist/engine/spec/types.js +3 -0
  286. package/dist/engine/spec/types.js.map +1 -0
  287. package/dist/engine/theme.d.ts +8 -0
  288. package/dist/engine/theme.js +85 -0
  289. package/dist/engine/theme.js.map +1 -0
  290. package/dist/engine/util.d.ts +73 -0
  291. package/dist/engine/util.js +285 -0
  292. package/dist/engine/util.js.map +1 -0
  293. package/package.json +43 -31
  294. package/fesm2022/trismegisto-charts.mjs +0 -12428
  295. package/fesm2022/trismegisto-charts.mjs.map +0 -1
  296. package/types/trismegisto-charts.d.ts +0 -1970
  297. package/types/trismegisto-charts.d.ts.map +0 -1
@@ -0,0 +1,993 @@
1
+ import { compileSpec } from './spec/compile';
2
+ import { themePlan } from './spec/theme';
3
+ import { decalFor } from './aria';
4
+ import { nextLegendSelection, scrollLegend } from './component/legend';
5
+ import { TooltipController } from './component/tooltip';
6
+ import { createVisualResolver, toggleVisualPiece } from './component/visual-map';
7
+ import { layoutLabels } from './label-layout';
8
+ import { markPointNodes } from './series/mark-point';
9
+ import { referenceMarkNodes } from './component/reference-marks';
10
+ import { sweepNodes, viewWindowOf } from './component/view-window';
11
+ import { createLocale, languageOf } from './locale';
12
+ import { dataCount, normalizeOption } from './model';
13
+ import { COMPONENT_TYPES, COORDINATE_TYPES, SERIES_TYPES } from './registry';
14
+ import { SvgRenderer } from './render/svg';
15
+ import { measureText } from './render/text';
16
+ import { buildTheme } from './theme';
17
+ import { isPlainObject, isUnnamed, toArray } from './util';
18
+ const EASINGS = ['linear', 'cubicOut', 'cubicInOut', 'quadraticOut', 'elasticOut', 'backOut', 'exponentialOut'];
19
+ const FALLBACK_WIDTH = 600;
20
+ const FALLBACK_HEIGHT = 400;
21
+ /** De onde o evento veio, no vocabulário do contrato. */
22
+ function partOf(componentType) {
23
+ switch (componentType) {
24
+ case 'series':
25
+ return 'series';
26
+ case 'legend':
27
+ return 'legend';
28
+ case 'blank':
29
+ return 'plane';
30
+ case 'sweepSelect':
31
+ return 'sweep';
32
+ default:
33
+ return 'chart';
34
+ }
35
+ }
36
+ const coordKey = (type, index) => `${type}:${index}`;
37
+ function easingOf(value, fallback) {
38
+ return EASINGS.includes(value) ? value : fallback;
39
+ }
40
+ function prefersReducedMotion() {
41
+ try {
42
+ return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ export class Chart {
49
+ dom;
50
+ raw = {};
51
+ theme;
52
+ locale;
53
+ renderer;
54
+ tooltip;
55
+ plotWidth;
56
+ plotHeight;
57
+ fixedWidth;
58
+ fixedHeight;
59
+ legendSelected = {};
60
+ legendInit = false;
61
+ highlights = new Map();
62
+ hover = null;
63
+ pointer = null;
64
+ componentState = new Map();
65
+ listeners = [];
66
+ frame = null;
67
+ renderTicket = 0;
68
+ animateNext = true;
69
+ gone = false;
70
+ current = null;
71
+ /** A opção nova ainda não desenhou: a translação de `slide` vale nesse quadro só. */
72
+ slidePending = false;
73
+ /** Faixa temporária da seleção por arrasto (`sweepSelect`), enquanto o botão está apertado. */
74
+ sweep = null;
75
+ domListeners = [];
76
+ constructor(dom, opts = {}) {
77
+ this.dom = dom;
78
+ this.theme = buildTheme(themePlan(opts.theme));
79
+ this.locale = createLocale(opts.locale ?? null, languageOf(dom));
80
+ this.fixedWidth = opts.width;
81
+ this.fixedHeight = opts.height;
82
+ this.plotWidth = this.measureWidth();
83
+ this.plotHeight = this.measureHeight();
84
+ if (!opts.positioned && getComputedStyleSafe(dom, 'position') === 'static')
85
+ dom.style.position = 'relative';
86
+ this.renderer = new SvgRenderer(dom, {
87
+ onPointer: (item, x, y, e) => this.onPointer(item, x, y, e),
88
+ onClick: (item, x, y, e) => this.onClick(item, x, y, e),
89
+ onLeave: (e) => this.onLeave(e),
90
+ });
91
+ this.renderer.onFinished = () => this.emit('settled', { componentType: 'chart' });
92
+ this.listenSweep();
93
+ this.renderer.setSize(this.plotWidth, this.plotHeight);
94
+ this.tooltip = new TooltipController(dom, () => this.currentCtx(), {
95
+ paramsOf: (model, dataIndex) => SERIES_TYPES.get(model.type)?.tooltipParams(model, dataIndex, this.currentCtx()) ?? null,
96
+ itemsAtAxisValue: (model, axisDim, value) => SERIES_TYPES.get(model.type)?.itemsAtAxisValue?.(model, axisDim, value, this.currentCtx()) ?? [],
97
+ });
98
+ }
99
+ // ---------------------------------------------------------------- tamanho
100
+ measureWidth() {
101
+ return this.fixedWidth ?? (this.dom.clientWidth || FALLBACK_WIDTH);
102
+ }
103
+ measureHeight() {
104
+ return this.fixedHeight ?? (this.dom.clientHeight || FALLBACK_HEIGHT);
105
+ }
106
+ get width() {
107
+ return this.plotWidth;
108
+ }
109
+ get height() {
110
+ return this.plotHeight;
111
+ }
112
+ get element() {
113
+ return this.dom;
114
+ }
115
+ get disposed() {
116
+ return this.gone;
117
+ }
118
+ get spec() {
119
+ return this.current;
120
+ }
121
+ resize(size = {}) {
122
+ if (this.gone)
123
+ return;
124
+ this.plotWidth = typeof size.width === 'number' ? size.width : this.dom.clientWidth || this.fixedWidth || this.plotWidth;
125
+ this.plotHeight = typeof size.height === 'number' ? size.height : this.dom.clientHeight || this.fixedHeight || this.plotHeight;
126
+ this.renderer.setSize(this.plotWidth, this.plotHeight);
127
+ this.animateNext = !!size.animate;
128
+ this.draw();
129
+ this.emit('resize', { componentType: 'chart' });
130
+ }
131
+ // ---------------------------------------------------------------- opção
132
+ render(spec) {
133
+ if (this.gone || !spec || !Array.isArray(spec.series))
134
+ return;
135
+ this.current = spec;
136
+ this.apply(compileSpec(spec));
137
+ }
138
+ /** Troca o plano interno inteiro (sem mesclar com o anterior). */
139
+ apply(plan) {
140
+ this.raw = plan;
141
+ this.highlights.clear();
142
+ this.pointer = null;
143
+ if (!this.legendInit)
144
+ this.legendSelected = {};
145
+ this.legendInit = true;
146
+ this.animateNext = true;
147
+ this.slidePending = true;
148
+ this.draw();
149
+ }
150
+ /** Plano interno normalizado (padrões aplicados) do quadro atual: só para os testes do motor. */
151
+ normalizedPlan() {
152
+ const frame = this.frame ?? this.build();
153
+ return frame.normalized.option;
154
+ }
155
+ setTheme(theme) {
156
+ this.theme = buildTheme(themePlan(theme));
157
+ this.animateNext = false;
158
+ this.draw();
159
+ }
160
+ clear() {
161
+ this.raw = {};
162
+ this.current = null;
163
+ this.highlights.clear();
164
+ this.hover = null;
165
+ this.pointer = null;
166
+ this.tooltip.hide();
167
+ this.draw();
168
+ }
169
+ dispose() {
170
+ if (this.gone)
171
+ return;
172
+ this.gone = true;
173
+ for (const [type, fn, opts] of this.domListeners)
174
+ this.dom.removeEventListener(type, fn, opts);
175
+ this.domListeners.length = 0;
176
+ this.tooltip.dispose();
177
+ this.renderer.dispose();
178
+ this.listeners.length = 0;
179
+ instances.delete(this.dom);
180
+ }
181
+ // ---------------------------------------------------------------- quadro
182
+ requestRender() {
183
+ const ticket = ++this.renderTicket;
184
+ const run = () => {
185
+ if (ticket === this.renderTicket && !this.gone)
186
+ this.draw();
187
+ };
188
+ if (typeof requestAnimationFrame === 'function')
189
+ requestAnimationFrame(run);
190
+ else
191
+ setTimeout(run, 0);
192
+ }
193
+ currentCtx() {
194
+ return (this.frame ?? this.build()).ctx;
195
+ }
196
+ /** Monta o contexto, os modelos e os sistemas de coordenadas do quadro (sem desenhar). */
197
+ build() {
198
+ const normalized = normalizeOption(this.raw, this.theme, { series: SERIES_TYPES, components: COMPONENT_TYPES });
199
+ const option = normalized.option;
200
+ const models = normalized.models;
201
+ const palette = option['color'].filter((c) => typeof c === 'string');
202
+ const aria = option['aria'][0] ?? {};
203
+ const animationOn = option['animation'] !== false && !prefersReducedMotion() && dataCount(models) <= Number(option['animationThreshold'] ?? 2000);
204
+ const delayOpt = option['animationDelay'];
205
+ const coords = new Map();
206
+ const legendSelected = (name) => this.legendSelected[name] !== false;
207
+ const visible = models.filter((m) => {
208
+ const type = SERIES_TYPES.get(m.type);
209
+ // Séries que dão a legenda por item (pizza, funil) filtram os itens; as outras somem inteiras.
210
+ return type?.legendEntries ? true : legendSelected(m.name);
211
+ });
212
+ const ctx = {
213
+ width: this.plotWidth,
214
+ height: this.plotHeight,
215
+ theme: this.theme,
216
+ locale: this.locale,
217
+ option,
218
+ models: visible,
219
+ measureText,
220
+ paletteColor: (i) => palette[((i % palette.length) + palette.length) % palette.length] ?? '#5470c6',
221
+ decal: (i) => (aria['decal']?.['show'] ? decalFor(i, toArray(aria['decal']?.['decals'])[i]) : null),
222
+ coordinateSystem: (type, index) => coords.get(coordKey(type, index)),
223
+ state: (si, di) => this.stateOf(si, di, models),
224
+ legendSelected,
225
+ visual: () => undefined,
226
+ animation: {
227
+ enabled: animationOn,
228
+ duration: typeof option['animationDuration'] === 'number' ? option['animationDuration'] : 1000,
229
+ easing: easingOf(option['animationEasing'], 'cubicOut'),
230
+ durationUpdate: typeof option['animationDurationUpdate'] === 'number' ? option['animationDurationUpdate'] : 300,
231
+ delay: (i) => (typeof delayOpt === 'function' ? Number(delayOpt(i)) || 0 : Number(delayOpt) || 0),
232
+ },
233
+ formatNumber: (v) => this.locale.number(v),
234
+ componentState: this.componentState,
235
+ requestRender: () => this.requestRender(),
236
+ };
237
+ ctx.visual = createVisualResolver(option, visible, this.componentState, ctx);
238
+ const frame = { normalized, visible, coords, ctx };
239
+ this.frame = frame;
240
+ // Sistemas de coordenadas: um por componente usado pelas séries (as visíveis dão as extensões).
241
+ for (const [type, coordType] of COORDINATE_TYPES) {
242
+ const users = models.filter((m) => m.coordinateSystem === type);
243
+ const declared = type === 'cartesian2d' ? option['xAxis'] || option['grid'] : type === 'polar' ? option['polar'] : type === 'radar' ? option['radar'] : option['calendar'];
244
+ if (!users.length && !declared)
245
+ continue;
246
+ try {
247
+ for (const coord of coordType.create(option, visible.filter((m) => m.coordinateSystem === type), ctx))
248
+ coords.set(coordKey(type, coord.index), coord);
249
+ }
250
+ catch (error) {
251
+ logError(`coordenadas ${type}`, error);
252
+ }
253
+ }
254
+ return frame;
255
+ }
256
+ draw() {
257
+ if (this.gone)
258
+ return;
259
+ ++this.renderTicket;
260
+ const frame = this.build();
261
+ const { normalized, visible, coords, ctx } = frame;
262
+ const option = normalized.option;
263
+ const nodes = [];
264
+ const labels = [];
265
+ // Tempo real: as séries vão num grupo interno que desliza pelo intervalo novo (o recorte do grupo de fora fica parado).
266
+ const slideOption = isPlainObject(option['slide']) ? option['slide'] : null;
267
+ const slide = slideOption && this.slidePending ? { dx: Number(slideOption.dx) || 0, duration: Number(slideOption.duration) || 0 } : null;
268
+ this.slidePending = false;
269
+ for (const [key, coord] of coords) {
270
+ try {
271
+ nodes.push({ kind: 'group', key: `coord/${key}`, z: 0, children: coord.render(ctx) });
272
+ }
273
+ catch (error) {
274
+ logError(`coordenadas ${key}`, error);
275
+ }
276
+ }
277
+ if (this.pointer) {
278
+ const coord = coords.get(this.pointer.coordKey);
279
+ const axis = coord?.axes[this.pointer.axisDim];
280
+ const tip = option['tooltip'][0] ?? {};
281
+ const kind = (tip['axisPointer']?.['type'] ?? 'line');
282
+ if (coord?.renderAxisPointer && axis && kind !== 'none') {
283
+ nodes.push({ kind: 'group', key: 'axis-pointer', z: kind === 'shadow' ? 1 : 5, silent: true, children: coord.renderAxisPointer(axis, this.pointer.value, kind, ctx) });
284
+ }
285
+ }
286
+ // Marcas de referência: faixas atrás das séries, linhas na frente delas e atrás dos rótulos.
287
+ if (option['referenceMarks']?.length) {
288
+ try {
289
+ const refs = referenceMarkNodes(ctx);
290
+ if (refs.bands.length)
291
+ nodes.push({ kind: 'group', key: 'reference-bands', z: 1.5, silent: true, children: refs.bands });
292
+ if (refs.lines.length)
293
+ nodes.push({ kind: 'group', key: 'reference-lines', z: 2.9, silent: true, children: refs.lines });
294
+ }
295
+ catch (error) {
296
+ logError('marcas de referência', error);
297
+ }
298
+ }
299
+ for (const model of visible) {
300
+ const type = SERIES_TYPES.get(model.type);
301
+ if (!type)
302
+ continue;
303
+ try {
304
+ const result = type.render(model, ctx);
305
+ // Com janela de dados no grid, a série é recortada na largura do plano (o ponto logo fora leva a linha à borda).
306
+ let clip;
307
+ if (model.coordinateSystem === 'cartesian2d' && viewWindowOf(option, model.coordinateIndex)) {
308
+ const rect = coords.get(coordKey('cartesian2d', model.coordinateIndex))?.rect;
309
+ if (rect)
310
+ clip = { x: rect.x, y: 0, width: rect.width, height: this.plotHeight };
311
+ }
312
+ const children = slideOption ? [{ kind: 'group', key: `series/${model.index}/slide`, children: result.nodes, ...(slide ? { slide } : {}) }] : result.nodes;
313
+ nodes.push({ kind: 'group', key: `series/${model.index}`, z: 2 + Number(model.option['z'] ?? 0) / 100, children, ...(clip ? { clip } : {}) });
314
+ if (result.labels)
315
+ labels.push(...result.labels);
316
+ }
317
+ catch (error) {
318
+ logError(`série ${model.type}`, error);
319
+ }
320
+ }
321
+ if (labels.length)
322
+ nodes.push({ kind: 'group', key: 'labels', z: 3, children: layoutLabels(labels, measureText) });
323
+ // markPoint: acima das séries e dos rótulos delas, fora da disposição (o selo não some por sobreposição).
324
+ const marks = [];
325
+ for (const model of visible) {
326
+ if (!model.option['markPoint'] || !ctx.legendSelected(model.name))
327
+ continue;
328
+ try {
329
+ const children = markPointNodes(model, ctx);
330
+ if (children.length) {
331
+ const group = { kind: 'group', key: `markPoint/${model.index}`, z: 3.5, silent: true, children };
332
+ nodes.push(group);
333
+ marks.push(group);
334
+ }
335
+ }
336
+ catch (error) {
337
+ logError(`markPoint da série ${model.index}`, error);
338
+ }
339
+ }
340
+ stackOverlappingBadges(marks);
341
+ if (this.sweep)
342
+ nodes.push({ kind: 'group', key: 'sweep', z: 4.5, silent: true, children: sweepNodes(this.sweep, ctx) });
343
+ // Componentes: a legenda recebe as entradas das séries.
344
+ const entries = this.legendEntries(normalized.models, ctx);
345
+ for (const [key, type] of COMPONENT_TYPES) {
346
+ if (!type.render)
347
+ continue;
348
+ option[key]?.forEach((componentOption, index) => {
349
+ const opt = key === 'legend' ? { ...componentOption, __entries: entries } : componentOption;
350
+ try {
351
+ nodes.push({ kind: 'group', key: `component/${key}/${index}`, z: 4, children: type.render(opt, index, ctx) });
352
+ }
353
+ catch (error) {
354
+ logError(`componente ${key}`, error);
355
+ }
356
+ });
357
+ }
358
+ this.renderer.setSize(this.plotWidth, this.plotHeight);
359
+ this.renderer.setBackground(typeof option['backgroundColor'] === 'string' ? option['backgroundColor'] : undefined);
360
+ this.renderer.setLabel(null);
361
+ this.renderer.render(nodes, {
362
+ animate: ctx.animation.enabled && this.animateNext,
363
+ duration: ctx.animation.duration,
364
+ durationUpdate: ctx.animation.durationUpdate,
365
+ easing: ctx.animation.easing,
366
+ easingUpdate: easingOf(option['animationEasingUpdate'], 'cubicInOut'),
367
+ });
368
+ this.animateNext = true;
369
+ this.emit('rendered', { componentType: 'chart' });
370
+ }
371
+ /** Entradas da legenda: as que cada série dá (pizza por item) ou uma por série com nome. */
372
+ legendEntries(models, ctx) {
373
+ const out = [];
374
+ const seen = new Set();
375
+ for (const model of models) {
376
+ const type = SERIES_TYPES.get(model.type);
377
+ const list = type?.legendEntries
378
+ ? type.legendEntries(model, ctx)
379
+ : isUnnamed(model.name)
380
+ ? []
381
+ : [{ name: model.name, color: model.color, icon: model.type === 'line' ? 'line' : 'rounded-square', seriesIndex: model.index, decal: model.decal, lineStyle: undefined }];
382
+ for (const entry of list) {
383
+ if (seen.has(entry.name))
384
+ continue;
385
+ seen.add(entry.name);
386
+ out.push(entry);
387
+ }
388
+ }
389
+ return out;
390
+ }
391
+ // ---------------------------------------------------------------- destaque
392
+ stateOf(si, di, models) {
393
+ const active = [];
394
+ for (const [s, set] of this.highlights) {
395
+ if (set === 'all')
396
+ active.push({ si: s, di: 'all' });
397
+ else
398
+ for (const d of set)
399
+ active.push({ si: s, di: d });
400
+ }
401
+ if (this.hover?.componentType === 'series' && this.hover.seriesIndex !== undefined) {
402
+ active.push({ si: this.hover.seriesIndex, di: this.hover.dataIndex ?? 'all' });
403
+ }
404
+ if (!active.length)
405
+ return 'normal';
406
+ let blur = false;
407
+ for (const a of active) {
408
+ const focus = models[a.si]?.option['emphasis']?.['focus'] ?? 'none';
409
+ if (a.si === si && (a.di === 'all' || a.di === di || di === undefined || focus === 'series'))
410
+ return 'emphasis';
411
+ if (focus === 'series' && a.si !== si)
412
+ blur = true;
413
+ if (focus === 'self')
414
+ blur = true;
415
+ }
416
+ return blur ? 'blur' : 'normal';
417
+ }
418
+ sameItem(a, b) {
419
+ if (!a || !b)
420
+ return a === b;
421
+ return a.componentType === b.componentType && a.seriesIndex === b.seriesIndex && a.dataIndex === b.dataIndex && a.name === b.name && a.dataType === b.dataType;
422
+ }
423
+ // ---------------------------------------------------------------- mouse
424
+ tooltipOption() {
425
+ const frame = this.frame ?? this.build();
426
+ return frame.normalized.option['tooltip'][0] ?? { show: false };
427
+ }
428
+ onPointer(item, x, y, event) {
429
+ // Arrastando a seleção: sem tooltip nem destaque.
430
+ if (this.sweep)
431
+ return;
432
+ const frame = this.frame ?? this.build();
433
+ const tip = this.tooltipOption();
434
+ const tipOn = !!frame.normalized.option['tooltip'].length && tip['show'] !== false && tip['showContent'] !== false && String(tip['triggerOn'] ?? 'mousemove').includes('mousemove');
435
+ let needsRender = false;
436
+ const seriesItem = item?.componentType === 'series' ? item : null;
437
+ if (!this.sameItem(this.hover, seriesItem)) {
438
+ if (this.hover)
439
+ this.emit('pointerleave', { ...this.hover, event });
440
+ this.hover = seriesItem;
441
+ if (seriesItem)
442
+ this.emit('pointerenter', { ...this.fillItem(seriesItem, frame), event });
443
+ needsRender = true;
444
+ }
445
+ if (tipOn && tip['trigger'] === 'axis') {
446
+ const found = this.axisAt(x, y, frame);
447
+ const next = found ? { coordKey: found.key, axisDim: found.axis.dim, value: found.value } : null;
448
+ if (JSON.stringify(next) !== JSON.stringify(this.pointer)) {
449
+ this.pointer = next;
450
+ needsRender = true;
451
+ }
452
+ if (found)
453
+ this.tooltip.showAxis(found.coord, found.axis, found.value, x, y);
454
+ else
455
+ this.tooltip.hide();
456
+ }
457
+ else if (tipOn && tip['trigger'] !== 'none') {
458
+ const model = seriesItem?.seriesIndex !== undefined ? frame.normalized.models[seriesItem.seriesIndex] : undefined;
459
+ if (model && seriesItem?.dataIndex !== undefined)
460
+ this.tooltip.showItem(model, seriesItem.dataIndex, x, y);
461
+ else
462
+ this.tooltip.hide();
463
+ }
464
+ if (needsRender) {
465
+ this.animateNext = true;
466
+ this.draw();
467
+ }
468
+ }
469
+ axisAt(x, y, frame) {
470
+ for (const [key, coord] of frame.coords) {
471
+ if (!coord.pointerAt)
472
+ continue;
473
+ const hit = coord.pointerAt(x, y);
474
+ if (hit)
475
+ return { key, coord, axis: hit.axis, value: hit.value };
476
+ }
477
+ return null;
478
+ }
479
+ onLeave(event) {
480
+ const tip = this.tooltipOption();
481
+ if (!tip['alwaysShowContent'])
482
+ this.tooltip.hide();
483
+ const changed = !!this.hover || !!this.pointer;
484
+ if (this.hover)
485
+ this.emit('pointerleave', { ...this.hover, event });
486
+ this.hover = null;
487
+ this.pointer = null;
488
+ if (changed)
489
+ this.draw();
490
+ }
491
+ onClick(item, x, y, event) {
492
+ const frame = this.frame ?? this.build();
493
+ if (!item) {
494
+ this.emit('click', { componentType: 'blank', event });
495
+ return;
496
+ }
497
+ if (item.componentType === 'legend' && item.name !== undefined) {
498
+ this.toggleLegend(String(item.name), item.componentIndex ?? 0);
499
+ return;
500
+ }
501
+ if (item.componentType === 'legendScroll') {
502
+ const delta = Number(item.data?.delta ?? 0);
503
+ scrollLegend(frame.ctx, item.componentIndex ?? 0, delta);
504
+ return;
505
+ }
506
+ if (item.componentType === 'visualMap') {
507
+ const piece = item.data?.pieceIndex;
508
+ if (piece !== undefined)
509
+ toggleVisualPiece(frame.ctx, item.componentIndex ?? 0, piece);
510
+ return;
511
+ }
512
+ const full = this.fillItem(item, frame);
513
+ this.emit('click', { ...full, event });
514
+ if (item.componentType === 'series' && item.seriesIndex !== undefined) {
515
+ const model = frame.normalized.models[item.seriesIndex];
516
+ const type = model ? SERIES_TYPES.get(model.type) : undefined;
517
+ if (model && type?.onClick?.(model, item, frame.ctx))
518
+ this.draw();
519
+ const tip = this.tooltipOption();
520
+ if (String(tip['triggerOn'] ?? '').includes('click') && tip['trigger'] !== 'axis' && model && item.dataIndex !== undefined)
521
+ this.tooltip.showItem(model, item.dataIndex, x, y);
522
+ }
523
+ }
524
+ /** Completa o item do evento com o que o modelo sabe (nome, valor, dado, tipo e nome da série). */
525
+ fillItem(item, frame) {
526
+ if (item.componentType !== 'series' || item.seriesIndex === undefined)
527
+ return item;
528
+ const model = frame.normalized.models[item.seriesIndex];
529
+ if (!model)
530
+ return item;
531
+ const data = item.dataIndex !== undefined ? model.data[item.dataIndex] : undefined;
532
+ let name = item.name || data?.name || '';
533
+ // Sem nome no item: a categoria do eixo.
534
+ if (!name && item.dataIndex !== undefined && model.coordinateSystem !== 'none') {
535
+ const coord = frame.coords.get(coordKey(model.coordinateSystem, model.coordinateIndex));
536
+ const base = coord && Object.values(coord.axes).find((a) => a.type === 'category');
537
+ name = base?.categories[item.dataIndex] ?? '';
538
+ }
539
+ return {
540
+ ...item,
541
+ seriesType: item.seriesType ?? model.type,
542
+ seriesName: item.seriesName ?? model.name,
543
+ name,
544
+ value: item.value ?? data?.value,
545
+ data: item.data ?? data?.raw,
546
+ };
547
+ }
548
+ // ---------------------------------------------------------------- legenda
549
+ legendNames(frame) {
550
+ return this.legendEntries(frame.normalized.models, frame.ctx).map((e) => e.name);
551
+ }
552
+ toggleLegend(name, index) {
553
+ const frame = this.frame ?? this.build();
554
+ const legendOpt = (frame.normalized.option['legend'] ?? [])[index] ?? {};
555
+ this.legendSelected = nextLegendSelection(legendOpt, this.legendSelected, name, this.legendNames(frame));
556
+ this.afterLegendChange(name, 'legendtoggle');
557
+ }
558
+ afterLegendChange(name, type) {
559
+ const frame = this.frame ?? this.build();
560
+ const selected = {};
561
+ for (const n of this.legendNames(frame))
562
+ selected[n] = this.legendSelected[n] !== false;
563
+ this.animateNext = true;
564
+ this.draw();
565
+ this.emit(type, { componentType: 'legend', name, selected });
566
+ }
567
+ // ---------------------------------------------------------------- destaque e tooltip (contrato)
568
+ highlight(target) {
569
+ this.act({ type: 'highlight', seriesIndex: target.series, dataIndex: target.point });
570
+ }
571
+ clearHighlight(target) {
572
+ this.act(target ? { type: 'downplay', seriesIndex: target.series, dataIndex: target.point } : { type: 'downplay' });
573
+ }
574
+ showTooltip(target) {
575
+ this.act({ type: 'showTip', seriesIndex: target.series, dataIndex: target.point, axisValue: target.axisValue });
576
+ }
577
+ hideTooltip() {
578
+ this.act({ type: 'hideTip' });
579
+ }
580
+ // ---------------------------------------------------------------- ações internas
581
+ act(action) {
582
+ if (this.gone || !isPlainObject(action))
583
+ return;
584
+ const frame = this.frame ?? this.build();
585
+ const models = frame.normalized.models;
586
+ const type = String(action['type']);
587
+ const seriesOf = () => {
588
+ if (action['seriesIndex'] !== undefined)
589
+ return toArray(action['seriesIndex']).map((i) => models[i]).filter(Boolean);
590
+ if (action['seriesName'] !== undefined) {
591
+ const names = toArray(action['seriesName']);
592
+ return models.filter((m) => names.includes(m.name));
593
+ }
594
+ if (action['seriesId'] !== undefined) {
595
+ const ids = toArray(action['seriesId']);
596
+ return models.filter((m) => ids.includes(m.option['id']));
597
+ }
598
+ return [];
599
+ };
600
+ const indicesOf = (model) => {
601
+ if (action['dataIndex'] !== undefined)
602
+ return toArray(action['dataIndex']);
603
+ if (action['name'] !== undefined) {
604
+ const names = toArray(action['name']).map(String);
605
+ return model.data.map((d, i) => (d.name !== undefined && names.includes(d.name) ? i : -1)).filter((i) => i >= 0);
606
+ }
607
+ return 'all';
608
+ };
609
+ switch (type) {
610
+ case 'highlight':
611
+ case 'downplay': {
612
+ const list = seriesOf();
613
+ if (type === 'downplay' && !list.length && action['dataIndex'] === undefined && action['name'] === undefined)
614
+ this.highlights.clear();
615
+ // Sem série: pelo nome, em qualquer série (pizza e legenda chamam assim).
616
+ const targets = list.length ? list : action['name'] !== undefined ? models : [];
617
+ for (const model of targets) {
618
+ const idx = indicesOf(model);
619
+ if (type === 'highlight') {
620
+ if (idx === 'all')
621
+ this.highlights.set(model.index, 'all');
622
+ else if (idx.length) {
623
+ const cur = this.highlights.get(model.index);
624
+ const set = cur instanceof Set ? cur : new Set();
625
+ idx.forEach((i) => set.add(i));
626
+ this.highlights.set(model.index, set);
627
+ }
628
+ }
629
+ else {
630
+ const cur = this.highlights.get(model.index);
631
+ if (idx === 'all' || cur === 'all')
632
+ this.highlights.delete(model.index);
633
+ else if (cur) {
634
+ idx.forEach((i) => cur.delete(i));
635
+ if (!cur.size)
636
+ this.highlights.delete(model.index);
637
+ }
638
+ }
639
+ }
640
+ this.animateNext = true;
641
+ this.draw();
642
+ this.emit(type === 'highlight' ? 'highlight' : 'clearhighlight', { componentType: 'series', seriesIndex: action['seriesIndex'], dataIndex: action['dataIndex'], name: action['name'] });
643
+ return;
644
+ }
645
+ case 'showTip': {
646
+ const pos = Array.isArray(action['position']) ? action['position'] : undefined;
647
+ const x = pos?.[0] ?? (typeof action['x'] === 'number' ? action['x'] : this.plotWidth / 2);
648
+ const y = pos?.[1] ?? (typeof action['y'] === 'number' ? action['y'] : this.plotHeight / 2);
649
+ const model = seriesOf()[0];
650
+ // Valor no eixo-base (instante): o tooltip de eixo nesse valor, com o ponteiro de eixo.
651
+ if (action['axisValue'] !== undefined) {
652
+ const target = model ?? models.find((m) => m.coordinateSystem === 'cartesian2d');
653
+ const coord = target ? frame.coords.get(coordKey(target.coordinateSystem, target.coordinateIndex)) : undefined;
654
+ const base = coord && (Object.values(coord.axes).find((a) => a.type === 'category') ?? coord.axes['x']);
655
+ if (coord && base) {
656
+ const value = Number(action['axisValue']);
657
+ this.pointer = { coordKey: coordKey(target.coordinateSystem, target.coordinateIndex), axisDim: base.dim, value };
658
+ const px = base.toPixel(value);
659
+ const pos = base.dim === 'x' ? [px, coord.rect.y + coord.rect.height / 2] : [coord.rect.x + coord.rect.width / 2, px];
660
+ this.tooltip.showAxis(coord, base, value, pos[0], pos[1]);
661
+ this.draw();
662
+ }
663
+ return;
664
+ }
665
+ if (model) {
666
+ const idx = indicesOf(model);
667
+ const dataIndex = idx === 'all' ? 0 : idx[0];
668
+ if (dataIndex === undefined)
669
+ return;
670
+ const tip = this.tooltipOption();
671
+ if (tip['trigger'] === 'axis' && model.coordinateSystem !== 'none') {
672
+ const coord = frame.coords.get(coordKey(model.coordinateSystem, model.coordinateIndex));
673
+ const base = coord && Object.values(coord.axes).find((a) => a.type === 'category');
674
+ if (coord && base) {
675
+ const value = base.categories[dataIndex] ?? dataIndex;
676
+ this.pointer = { coordKey: coordKey(model.coordinateSystem, model.coordinateIndex), axisDim: base.dim, value: dataIndex };
677
+ this.tooltip.showAxis(coord, base, dataIndex, x, y);
678
+ void value;
679
+ this.draw();
680
+ return;
681
+ }
682
+ }
683
+ this.tooltip.showItem(model, dataIndex, x, y);
684
+ return;
685
+ }
686
+ if (typeof action['x'] === 'number' && typeof action['y'] === 'number') {
687
+ const found = this.axisAt(action['x'], action['y'], frame);
688
+ if (found) {
689
+ this.pointer = { coordKey: found.key, axisDim: found.axis.dim, value: found.value };
690
+ this.tooltip.showAxis(found.coord, found.axis, found.value, action['x'], action['y']);
691
+ this.draw();
692
+ }
693
+ }
694
+ return;
695
+ }
696
+ case 'hideTip':
697
+ this.tooltip.hide();
698
+ if (this.pointer) {
699
+ this.pointer = null;
700
+ this.draw();
701
+ }
702
+ return;
703
+ }
704
+ }
705
+ // ---------------------------------------------------------------- seleção por arrasto, Ctrl + roda, duplo clique
706
+ sweepOption() {
707
+ const frame = this.frame ?? this.build();
708
+ return toArray(frame.normalized.option['sweepSelect'])[0] ?? null;
709
+ }
710
+ /** Grid, eixo X e posição local do ponteiro, quando ele está dentro do plano do grid do componente. */
711
+ sweepTarget(e) {
712
+ const option = this.sweepOption();
713
+ if (!option)
714
+ return null;
715
+ const grid = option.gridIndex ?? 0;
716
+ const coord = (this.frame ?? this.build()).coords.get(coordKey('cartesian2d', grid));
717
+ const axis = coord?.xAxes[0];
718
+ if (!coord || !axis)
719
+ return null;
720
+ const box = this.renderer.svg.getBoundingClientRect();
721
+ const x = e.clientX - box.left;
722
+ const y = e.clientY - box.top;
723
+ const r = coord.rect;
724
+ if (x < r.x || x > r.x + r.width || y < r.y || y > r.y + r.height)
725
+ return null;
726
+ return { grid, axis, x };
727
+ }
728
+ listenSweep() {
729
+ const on = (type, fn, opts) => {
730
+ this.dom.addEventListener(type, fn, opts);
731
+ this.domListeners.push([type, fn, opts]);
732
+ };
733
+ const valueAt = (axis, px) => (axis.type === 'category' ? Math.round(axis.fromPixel(px)) : axis.fromPixel(px));
734
+ on('pointerdown', (e) => {
735
+ // Um dedo continua rolando a página: arrasto de seleção só com mouse ou caneta.
736
+ if (e.button !== 0 || e.pointerType === 'touch' || !this.sweepOption() || this.sweepOption()?.drag === false)
737
+ return;
738
+ const target = this.sweepTarget(e);
739
+ if (!target)
740
+ return;
741
+ this.sweep = { gridIndex: target.grid, from: target.x, to: target.x };
742
+ try {
743
+ this.dom.setPointerCapture?.(e.pointerId);
744
+ }
745
+ catch {
746
+ // ponteiro sintético (testes): sem captura
747
+ }
748
+ });
749
+ on('pointermove', (e) => {
750
+ if (!this.sweep)
751
+ return;
752
+ const coord = (this.frame ?? this.build()).coords.get(coordKey('cartesian2d', this.sweep.gridIndex));
753
+ if (!coord)
754
+ return;
755
+ const box = this.renderer.svg.getBoundingClientRect();
756
+ const x = Math.max(coord.rect.x, Math.min(coord.rect.x + coord.rect.width, e.clientX - box.left));
757
+ if (x === this.sweep.to)
758
+ return;
759
+ this.sweep = { ...this.sweep, to: x };
760
+ this.tooltip.hide();
761
+ this.pointer = null;
762
+ this.animateNext = false;
763
+ this.draw();
764
+ this.emit('sweepmove', { componentType: 'sweepSelect' });
765
+ });
766
+ const finish = (e, cancel) => {
767
+ const sweep = this.sweep;
768
+ if (!sweep)
769
+ return;
770
+ this.sweep = null;
771
+ try {
772
+ this.dom.releasePointerCapture?.(e.pointerId);
773
+ }
774
+ catch {
775
+ // idem
776
+ }
777
+ this.animateNext = false;
778
+ this.draw();
779
+ const coord = (this.frame ?? this.build()).coords.get(coordKey('cartesian2d', sweep.gridIndex));
780
+ const axis = coord?.xAxes[0];
781
+ if (cancel || !axis || Math.abs(sweep.to - sweep.from) < 4)
782
+ return;
783
+ const a = valueAt(axis, Math.min(sweep.from, sweep.to));
784
+ const b = valueAt(axis, Math.max(sweep.from, sweep.to));
785
+ this.emit('sweepselect', { componentType: 'sweepSelect', data: { start: Math.min(a, b), end: Math.max(a, b) } });
786
+ };
787
+ on('pointerup', (e) => finish(e, false));
788
+ on('pointercancel', (e) => finish(e, true));
789
+ on('keydown', (e) => {
790
+ if (e.key !== 'Escape' || !this.sweep)
791
+ return;
792
+ this.sweep = null;
793
+ this.animateNext = false;
794
+ this.draw();
795
+ this.emit('sweepcancel', { componentType: 'sweepSelect' });
796
+ });
797
+ // Roda só com Ctrl (ou a pinça do touchpad): a roda sozinha rola a página, nunca é presa.
798
+ on('wheel', (e) => {
799
+ if (!e.ctrlKey)
800
+ return;
801
+ const target = this.sweepTarget(e);
802
+ if (!target)
803
+ return;
804
+ e.preventDefault();
805
+ this.emit('sweepzoom', { componentType: 'sweepSelect', data: { center: target.axis.fromPixel(target.x), factor: e.deltaY < 0 ? 0.8 : 1.25 } });
806
+ }, { passive: false });
807
+ on('dblclick', (e) => {
808
+ if (this.sweepTarget(e))
809
+ this.emit('sweepreset', { componentType: 'sweepSelect' });
810
+ });
811
+ }
812
+ // ---------------------------------------------------------------- eventos
813
+ listen(type, handler) {
814
+ const entry = { event: type.toLowerCase(), handler };
815
+ this.listeners.push(entry);
816
+ return () => {
817
+ const at = this.listeners.indexOf(entry);
818
+ if (at >= 0)
819
+ this.listeners.splice(at, 1);
820
+ };
821
+ }
822
+ emit(type, params) {
823
+ if (!this.listeners.length)
824
+ return;
825
+ const model = params.seriesIndex !== undefined ? this.frame?.normalized.models[params.seriesIndex] : undefined;
826
+ const event = {
827
+ type,
828
+ part: partOf(params.componentType),
829
+ seriesIndex: params.seriesIndex,
830
+ seriesId: model?.option['id'],
831
+ seriesName: params.seriesName ?? (model && !isUnnamed(model.name) ? model.name : undefined),
832
+ pointIndex: params.dataIndex,
833
+ name: params.name,
834
+ value: params.value,
835
+ detail: params.data,
836
+ selected: params.selected,
837
+ native: params.event,
838
+ };
839
+ for (const key of Object.keys(event))
840
+ if (event[key] === undefined)
841
+ delete event[key];
842
+ for (const l of [...this.listeners]) {
843
+ if (l.event !== type)
844
+ continue;
845
+ try {
846
+ l.handler(event);
847
+ }
848
+ catch (error) {
849
+ logError(`evento ${type}`, error);
850
+ }
851
+ }
852
+ }
853
+ // ---------------------------------------------------------------- conversão de coordenadas
854
+ coordFor(target) {
855
+ const frame = this.frame ?? this.build();
856
+ const f = 'series' in target ? { seriesIndex: target.series } : { gridIndex: target.plane };
857
+ const get = (type, index) => frame.coords.get(coordKey(type, index));
858
+ if (f['seriesIndex'] !== undefined) {
859
+ const model = frame.normalized.models[f['seriesIndex']];
860
+ if (!model)
861
+ return undefined;
862
+ const coord = get(model.coordinateSystem, model.coordinateIndex);
863
+ return coord ? { coord } : undefined;
864
+ }
865
+ if (f['gridIndex'] !== undefined) {
866
+ const coord = get('cartesian2d', f['gridIndex']);
867
+ return coord ? { coord } : undefined;
868
+ }
869
+ return undefined;
870
+ }
871
+ toPixel(target, value) {
872
+ const found = this.coordFor(target);
873
+ if (!found)
874
+ return undefined;
875
+ if (found.axisDim) {
876
+ const axis = found.coord.axes[found.axisDim];
877
+ return axis ? axis.toPixel(Array.isArray(value) ? value[0] : value) : undefined;
878
+ }
879
+ return found.coord.dataToPoint(Array.isArray(value) ? [...value] : [value]);
880
+ }
881
+ fromPixel(target, value) {
882
+ const found = this.coordFor(target);
883
+ if (!found)
884
+ return undefined;
885
+ if (found.axisDim) {
886
+ const axis = found.coord.axes[found.axisDim];
887
+ const pixel = found.axisDim === 'x' ? value[0] : (value[1] ?? value[0]);
888
+ return axis ? axis.fromPixel(pixel) : undefined;
889
+ }
890
+ const x = found.coord.axes['x'];
891
+ const y = found.coord.axes['y'];
892
+ if (x && y)
893
+ return [x.fromPixel(value[0]), y.fromPixel(value[1])];
894
+ return undefined;
895
+ }
896
+ containsPixel(target, value) {
897
+ const found = this.coordFor(target);
898
+ if (!found)
899
+ return false;
900
+ if (found.coord.contains)
901
+ return found.coord.contains(value[0], value[1]);
902
+ const r = found.coord.rect;
903
+ return value[0] >= r.x && value[0] <= r.x + r.width && value[1] >= r.y && value[1] <= r.y + r.height;
904
+ }
905
+ // ---------------------------------------------------------------- exportar
906
+ toSVG() {
907
+ return this.renderer.toString();
908
+ }
909
+ toDataURL(options = {}) {
910
+ let svg = this.toSVG();
911
+ if (options.background)
912
+ svg = svg.replace(/<svg([^>]*?)style="/, `<svg$1style="background-color:${options.background};`);
913
+ return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`;
914
+ }
915
+ }
916
+ // ---------------------------------------------------------------- auxiliares
917
+ /**
918
+ * Selos com `stackOverlap` (último valor de cada série) que colidem sobem acima do anterior, na ordem em que vieram:
919
+ * nenhum some e nenhum esconde o outro.
920
+ */
921
+ export function stackOverlappingBadges(groups) {
922
+ const badges = [];
923
+ const collect = (node) => {
924
+ if (node.kind === 'group')
925
+ node.children.forEach(collect);
926
+ else if (node.kind === 'text' && node.stackOverlap)
927
+ badges.push(node);
928
+ };
929
+ groups.forEach(collect);
930
+ if (badges.length < 2)
931
+ return;
932
+ const placed = [];
933
+ const boxOf = (n) => {
934
+ const m = measureText(n.text, n.style);
935
+ const [pt, pr, pb, pl] = paddingOf(n.style.padding);
936
+ const w = m.width + pl + pr;
937
+ const h = m.height + pt + pb;
938
+ const align = n.style.align ?? 'left';
939
+ const valign = n.style.verticalAlign ?? 'top';
940
+ const x = align === 'center' ? n.x - w / 2 : align === 'right' ? n.x - w : n.x;
941
+ const y = valign === 'middle' ? n.y - h / 2 : valign === 'bottom' ? n.y - h : n.y;
942
+ return { x, y, w, h };
943
+ };
944
+ for (const badge of badges) {
945
+ let box = boxOf(badge);
946
+ for (let guard = 0; guard < badges.length; guard++) {
947
+ const hit = placed.find((p) => box.x < p.x + p.w && p.x < box.x + box.w && box.y < p.y + p.h && p.y < box.y + box.h);
948
+ if (!hit)
949
+ break;
950
+ const shift = box.y + box.h - hit.y + 2;
951
+ badge.y -= shift;
952
+ box = { ...box, y: box.y - shift };
953
+ }
954
+ placed.push(box);
955
+ }
956
+ }
957
+ function paddingOf(padding) {
958
+ if (padding === undefined)
959
+ return [0, 0, 0, 0];
960
+ if (typeof padding === 'number')
961
+ return [padding, padding, padding, padding];
962
+ const [a = 0, b = a, c = a, d = b] = padding;
963
+ return [a, b, c, d];
964
+ }
965
+ function getComputedStyleSafe(el, prop) {
966
+ try {
967
+ return el.ownerDocument.defaultView?.getComputedStyle(el).getPropertyValue(prop) ?? '';
968
+ }
969
+ catch {
970
+ return '';
971
+ }
972
+ }
973
+ function logError(where, error) {
974
+ // Um pedaço que falha não derruba o gráfico inteiro; o erro vai para o console.
975
+ console.error(`[hermes-charts] ${where}:`, error);
976
+ }
977
+ // ---------------------------------------------------------------- registro por elemento
978
+ const instances = new WeakMap();
979
+ /** Cria o gráfico no elemento (um por elemento: criar de novo descarta o anterior). Desenho sempre em SVG. */
980
+ export function createChart(element, options) {
981
+ const existing = instances.get(element);
982
+ if (existing && !existing.disposed)
983
+ existing.dispose();
984
+ const chart = new Chart(element, options);
985
+ instances.set(element, chart);
986
+ return chart;
987
+ }
988
+ /** O gráfico vivo no elemento, se houver. */
989
+ export function chartOf(element) {
990
+ const chart = instances.get(element);
991
+ return chart && !chart.disposed ? chart : undefined;
992
+ }
993
+ //# sourceMappingURL=instance.js.map