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
@@ -4,45 +4,312 @@
4
4
  */
5
5
  import {window} from "./browser";
6
6
 
7
+ /**
8
+ * The worker source constant (declared in config/globals.d.ts) is pre-bundled from
9
+ * `src/module/worker.entry.ts` and injected at build time by config/worker-src.js.
10
+ * Never name that constant outside the single reference in getWorkerSrc(): the
11
+ * rolldown injection is textual, so a mention in a comment would inline the whole
12
+ * source string a second time.
13
+ *
14
+ * Offloaded work is addressed by op name and the worker code is built
15
+ * independently of the application bundle, so no application function is ever
16
+ * stringified. Host toolchains that rewrite function bodies - coverage
17
+ * instrumentation, babel helpers, bundler-hoisted module scope - cannot break
18
+ * the worker anymore.
19
+ */
7
20
  // Store worker cache in memory
8
- const cache: {[key: string]: {src: string, worker: Worker | null}} = {};
21
+ const cache: {[key: string]: {revoke: boolean, src: string, worker: Worker | null}} = {};
22
+ const disabledKeys = new Set<string>();
23
+
24
+ /**
25
+ * Parity self-test state, keyed as `${key}:${op}`: the in-flight check while it runs,
26
+ * `true` once the worker agreed with the main thread.
27
+ * @private
28
+ */
29
+ const verifiedOps = new Map<string, true | Promise<boolean>>();
30
+
31
+ const DEFAULT_WORKER_TIMEOUT = 5000;
32
+
33
+ /**
34
+ * Number of leading entries kept when sampling arguments for the parity self-test.
35
+ * @private
36
+ */
37
+ const VERIFY_SAMPLE_SIZE = 3;
9
38
 
10
39
  // Correlation id for worker request/response matching
11
40
  let messageId = 0;
12
41
 
42
+ type TWorkerOptions = {timeout?: number, workerUrl?: string};
43
+
44
+ /**
45
+ * Get the build-injected worker source.
46
+ * @returns {string} Worker source, or empty string when it wasn't injected
47
+ * @private
48
+ */
49
+ function getWorkerSrc(): string {
50
+ try {
51
+ // referenced exactly once: each occurrence inlines the whole source string
52
+ return __WORKER_SRC__;
53
+ } catch {
54
+ // not injected (e.g. consuming src/*.ts directly) - stay on the main thread
55
+ return "";
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Get Web Worker related browser APIs when all required primitives are available.
61
+ * @returns {object|null} Worker API handles
62
+ * @private
63
+ */
64
+ function getWorkerAPI():
65
+ | {Blob: typeof Blob, Worker: typeof Worker, URL: typeof URL}
66
+ | null {
67
+ const {Blob, Worker, URL} = window;
68
+
69
+ return Worker && Blob && URL?.createObjectURL && URL?.revokeObjectURL ?
70
+ {Blob, Worker, URL} :
71
+ null;
72
+ }
73
+
74
+ /**
75
+ * Get Worker constructor when available.
76
+ * @returns {function|null} Worker constructor
77
+ * @private
78
+ */
79
+ function getWorkerConstructor(): typeof Worker | null {
80
+ return window.Worker || null;
81
+ }
82
+
83
+ /**
84
+ * Normalize worker options while preserving the legacy numeric timeout argument.
85
+ * @param {number|object} options Worker timeout or options
86
+ * @returns {object} Normalized worker options
87
+ * @private
88
+ */
89
+ function normalizeWorkerOptions(options?: number | TWorkerOptions): Required<TWorkerOptions> {
90
+ return typeof options === "number" ? {timeout: options, workerUrl: ""} : {
91
+ timeout: options?.timeout ?? DEFAULT_WORKER_TIMEOUT,
92
+ workerUrl: options?.workerUrl ?? ""
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Release cached worker resources and optionally disable this worker for the session.
98
+ * @param {string} key Cache key
99
+ * @param {boolean} disable Whether to disable future worker attempts
100
+ * @private
101
+ */
102
+ function releaseWorker(key: string, disable = false): void {
103
+ const cached = cache[key];
104
+
105
+ if (disable) {
106
+ disabledKeys.add(key);
107
+ }
108
+
109
+ if (cached) {
110
+ cached.worker?.terminate();
111
+ cached.revoke && getWorkerAPI()?.URL.revokeObjectURL(cached.src);
112
+ delete cache[key];
113
+ }
114
+
115
+ // entries are stored per op as `${key}:${op}`, so a bare key never matches:
116
+ // drop every op verified against the worker being released
117
+ for (const verified of verifiedOps.keys()) {
118
+ if (verified.startsWith(`${key}:`)) {
119
+ verifiedOps.delete(verified);
120
+ }
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Compare worker and main-thread results for the parity self-test.
126
+ * @param {unknown} actual Worker result
127
+ * @param {unknown} expected Main-thread result
128
+ * @returns {boolean} Whether results match
129
+ * @private
130
+ */
131
+ function isSameResult(actual, expected): boolean {
132
+ if (actual === expected) {
133
+ return true;
134
+ }
135
+
136
+ try {
137
+ return JSON.stringify(actual) === JSON.stringify(expected);
138
+ } catch {
139
+ // Structured-cloned worker results should normally be serializable. If a custom
140
+ // worker returns an exotic value, don't disable the worker on an unverifiable result.
141
+ return true;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Truncate conversion arguments to a small payload of the same shape.
147
+ *
148
+ * `args[0]` is the data array for every op: an array of series for `columns`, of rows
149
+ * for `rows`, of records for `json`. Keeping a few leading entries - and, where those
150
+ * entries are themselves arrays, a few leading cells of each - stays a valid payload
151
+ * for all three while costing a fixed amount regardless of the real data size.
152
+ * Anything that isn't an array is passed through untouched.
153
+ * @param {Array} args Conversion arguments
154
+ * @returns {Array} Sampled arguments
155
+ * @private
156
+ */
157
+ function getVerifySample(args: unknown[]): unknown[] {
158
+ const [data, ...rest] = args;
159
+
160
+ if (!Array.isArray(data)) {
161
+ return args;
162
+ }
163
+
164
+ return [
165
+ data.slice(0, VERIFY_SAMPLE_SIZE).map(entry =>
166
+ // +1: a column/row entry leads with its name, which the values follow
167
+ Array.isArray(entry) ? entry.slice(0, VERIFY_SAMPLE_SIZE + 1) : entry
168
+ ),
169
+ ...rest
170
+ ];
171
+ }
172
+
173
+ /**
174
+ * Post a single request to the worker and resolve with its result.
175
+ * @param {Worker} worker Worker instance
176
+ * @param {string} op Worker op name
177
+ * @param {Array} args Arguments to hand over
178
+ * @param {number} timeout Response timeout in milliseconds
179
+ * @returns {Promise} Worker result
180
+ * @private
181
+ */
182
+ function request(worker: Worker, op: string, args: unknown[], timeout: number): Promise<unknown> {
183
+ // workers are cached and shared: match the response by id so concurrent callers
184
+ // don't steal each other's result
185
+ const id = ++messageId;
186
+ let settled = false;
187
+ let cleanup: () => void;
188
+
189
+ const promise = new Promise((resolve, reject) => {
190
+ const settle = (fn: Function, value: unknown) => {
191
+ if (!settled) {
192
+ settled = true;
193
+ cleanup();
194
+ fn(value);
195
+ }
196
+ };
197
+ const handler = function(e: MessageEvent) {
198
+ if (e.data?.id === id) {
199
+ e.data.error ?
200
+ settle(reject, new Error(e.data.error)) :
201
+ settle(resolve, e.data.result);
202
+ }
203
+ };
204
+ const errorHandler = function() {
205
+ settle(reject, new Error("worker error"));
206
+ };
207
+ const timer = setTimeout(() => settle(reject, new Error("worker timeout")), timeout);
208
+
209
+ cleanup = () => {
210
+ clearTimeout(timer);
211
+ worker.removeEventListener("message", handler);
212
+ worker.removeEventListener("error", errorHandler);
213
+ };
214
+
215
+ worker.addEventListener("message", handler);
216
+ worker.addEventListener("error", errorHandler);
217
+ });
218
+
219
+ // Thrown synchronously, not turned into a rejection: a worker that cannot even
220
+ // accept a message must fall back on the main thread synchronously, so that
221
+ // `bb.generate()` stays as synchronous as it is with `useWorker: false`.
222
+ try {
223
+ worker.postMessage({args, id, op});
224
+ } catch (error) {
225
+ settled = true;
226
+ cleanup!();
227
+ throw error;
228
+ }
229
+
230
+ return promise;
231
+ }
232
+
233
+ /**
234
+ * Start the parity self-test for an op, on a sampled payload rather than the real one.
235
+ *
236
+ * The check answers "does this worker implement this op the way the main thread does",
237
+ * which the sample settles just as well as the full dataset - and at a cost that does
238
+ * not grow with it. Re-parsing the real payload here would hand back the very
239
+ * main-thread work the offload was meant to avoid.
240
+ * @param {Worker} worker Worker instance
241
+ * @param {string} verifyKey Cache key as `${key}:${op}`
242
+ * @param {string} op Worker op name
243
+ * @param {function} fn Equivalent main-thread function
244
+ * @param {Array} args Conversion arguments to sample from
245
+ * @param {number} timeout Response timeout in milliseconds
246
+ * @returns {Promise} Whether the worker matched the main thread
247
+ * @private
248
+ */
249
+ function startVerify(
250
+ worker: Worker,
251
+ verifyKey: string,
252
+ op: string,
253
+ fn: Function,
254
+ args: unknown[],
255
+ timeout: number
256
+ ): Promise<boolean> {
257
+ const sample = getVerifySample(args);
258
+ const check = request(worker, op, sample, timeout)
259
+ // a worker that errors or times out on the sample is handled by the real
260
+ // request's own fallback: report it as unverified and let that path run
261
+ .then(result => isSameResult(result, fn(...sample)), () => false)
262
+ .then(matched => {
263
+ matched ? verifiedOps.set(verifyKey, true) : verifiedOps.delete(verifyKey);
264
+
265
+ return matched;
266
+ });
267
+
268
+ verifiedOps.set(verifyKey, check);
269
+
270
+ return check;
271
+ }
272
+
13
273
  /**
14
274
  * Get or create cached worker resources (Object URL, Worker)
15
- * @param {function} fn Function to be executed in worker
16
- * @param {Array} depsFn Dependency functions to run given function(fn).
275
+ * @param {string} op Worker op name
276
+ * @param {string} workerUrl Custom worker script URL.
17
277
  * @returns {{key: string, src: string}} Cache key and Object URL
18
278
  * @private
19
279
  */
20
- function getOrCreateWorkerResources(fn: Function, depsFn?: Function[]):
280
+ function getOrCreateWorkerResources(op: string, workerUrl = ""):
21
281
  | {key: string, src: string}
22
282
  | null {
23
- const fnString = fn.toString();
24
- // Include depsFn in cache key to handle different dependencies
25
- const depsString = depsFn?.map(String).join(";") ?? "";
26
- const key = (fnString + depsString).replace(/(function|[\s\W\n])/g, "").substring(0, 30);
283
+ const hasWorker = !!getWorkerConstructor();
284
+ const api = workerUrl ? null : getWorkerAPI();
285
+ const src = workerUrl ? "" : getWorkerSrc();
286
+ // one worker per source: ops share a single cached worker per script
287
+ const key = workerUrl || "blob";
288
+
289
+ if (!hasWorker || (!workerUrl && (!api || !src)) || disabledKeys.has(key)) {
290
+ return null;
291
+ }
27
292
 
28
293
  if (!(key in cache)) {
29
294
  try {
30
- // Create Blob and Object URL for Web Worker
31
- const blob = new window.Blob([
32
- `${depsString}
33
-
34
- self.onmessage=function({data}) {
35
- const result = (${fnString}).apply(null, data.args);
36
- self.postMessage({id: data.id, result});
37
- };`
38
- ], {
39
- type: "text/javascript"
40
- });
41
-
42
- cache[key] = {
43
- src: window.URL.createObjectURL(blob),
44
- worker: null
45
- };
295
+ if (workerUrl) {
296
+ cache[key] = {
297
+ revoke: false,
298
+ src: workerUrl,
299
+ worker: null
300
+ };
301
+ } else if (api) {
302
+ // Create Blob and Object URL for Web Worker
303
+ const blob = new api.Blob([src], {
304
+ type: "text/javascript"
305
+ });
306
+
307
+ cache[key] = {
308
+ revoke: true,
309
+ src: api.URL.createObjectURL(blob),
310
+ worker: null
311
+ };
312
+ }
46
313
  } catch {
47
314
  return null;
48
315
  }
@@ -60,26 +327,20 @@ function getOrCreateWorkerResources(fn: Function, depsFn?: Function[]):
60
327
  */
61
328
  export function getWorker(key: string, src: string): Worker | null {
62
329
  const cached = cache[key];
330
+ const Worker = getWorkerConstructor();
63
331
 
64
332
  // Return null if cache entry doesn't exist
65
- if (!cached) {
333
+ if (!cached || !Worker || disabledKeys.has(key)) {
66
334
  return null;
67
335
  }
68
336
 
69
337
  if (!cached.worker) {
70
338
  try {
71
- cached.worker = new window.Worker(src);
339
+ cached.worker = new Worker(src);
72
340
  } catch {
341
+ releaseWorker(key, true);
73
342
  return null;
74
343
  }
75
-
76
- // handle error
77
- if (cached.worker) {
78
- cached.worker.onerror = function(e: ErrorEvent) {
79
- // eslint-disable-next-line no-console
80
- console.error ? console.error(e) : console.log(e);
81
- };
82
- }
83
344
  }
84
345
 
85
346
  return cached.worker;
@@ -88,57 +349,74 @@ export function getWorker(key: string, src: string): Worker | null {
88
349
  /**
89
350
  * Create and run on Web Worker
90
351
  * @param {boolean} useWorker Use Web Worker
91
- * @param {function} fn Function to be executed in worker
352
+ * @param {string} op Op name registered in src/module/worker.entry.ts
353
+ * @param {function} fn Equivalent main-thread function, used for fallback and for the
354
+ * sampled parity self-test
92
355
  * @param {function} callback Callback function to receive result from worker
93
- * @param {Array} depsFn Dependency functions to run given function(fn).
356
+ * @param {number|object} options Worker response timeout or options.
94
357
  * @returns {function}
95
358
  * @example
96
- * const worker = runWorker(function(arg) {
97
- * // do some tasks...
98
- * console.log("param:", A(arg));
99
- *
100
- * return 1234;
101
- * }, function(data) {
359
+ * const worker = runWorker(true, "rows", rows, function(data) {
102
360
  * // callback after worker is done
103
361
  * console.log("result:", data);
104
- * },
105
- * [function A(){}]
106
- * );
362
+ * });
107
363
  *
108
364
  * worker(11111);
109
365
  * @private
110
366
  */
111
367
  export function runWorker(
112
368
  useWorker = true,
369
+ op: string,
113
370
  fn: Function,
114
371
  callback: Function,
115
- depsFn?: Function[]
372
+ options?: number | TWorkerOptions
116
373
  ): Function {
117
- let runFn = function(...args: unknown[]) {
374
+ const {timeout, workerUrl} = normalizeWorkerOptions(options);
375
+ const runSync = function(...args: unknown[]) {
118
376
  const res = fn(...args);
119
377
 
120
378
  callback(res);
121
379
  };
380
+ let runFn = runSync;
381
+
382
+ if (useWorker) {
383
+ const workerResources = getOrCreateWorkerResources(op, workerUrl);
384
+ const worker = workerResources ? getWorker(workerResources.key, workerResources.src) : null;
122
385
 
123
- if (window.Worker && useWorker) {
124
- const workerResources = getOrCreateWorkerResources(fn, depsFn);
125
- const worker = workerResources && getWorker(workerResources.key, workerResources.src);
386
+ if (worker && workerResources) {
387
+ const {key} = workerResources;
126
388
 
127
- if (worker) {
128
389
  runFn = function(...args: unknown[]) {
129
- // workers are cached and shared: match the response by id so concurrent
130
- // callers don't steal each other's result
131
- const id = ++messageId;
132
-
133
- const handler = function(e: MessageEvent) {
134
- if (e.data?.id === id) {
135
- worker.removeEventListener("message", handler);
136
- callback(e.data.result);
137
- }
390
+ // any failure - worker error, {error} reply, timeout, postMessage throw,
391
+ // parity mismatch - gives up on this worker for the session and redoes the
392
+ // work on the main thread
393
+ const fallback = () => {
394
+ releaseWorker(key, true);
395
+ runFn = runSync;
396
+ runSync(...args);
138
397
  };
139
398
 
140
- worker.addEventListener("message", handler);
141
- worker.postMessage({id, args});
399
+ try {
400
+ const verifyKey = `${key}:${op}`;
401
+ // Started before the real request is posted: the worker processes
402
+ // messages in order, so the sampled result comes back first and the
403
+ // check overlaps the real conversion instead of following it.
404
+ const verified = verifiedOps.get(verifyKey) ??
405
+ startVerify(worker, verifyKey, op, fn, args, timeout);
406
+
407
+ request(worker, op, args, timeout).then(result => {
408
+ // already verified: hand the result over without touching the
409
+ // main-thread converter at all
410
+ if (verified === true) {
411
+ callback(result);
412
+ } else {
413
+ verified.then(matched => (matched ? callback(result) : fallback()));
414
+ }
415
+ }, fallback);
416
+ } catch {
417
+ // postMessage refused the payload outright - stay synchronous
418
+ fallback();
419
+ }
142
420
  };
143
421
  }
144
422
  }
@@ -151,6 +429,8 @@ export function runWorker(
151
429
  * @private
152
430
  */
153
431
  export function cleanupWorkers(): void {
432
+ const api = getWorkerAPI();
433
+
154
434
  for (const key in cache) {
155
435
  const cached = cache[key];
156
436
 
@@ -159,9 +439,12 @@ export function cleanupWorkers(): void {
159
439
  }
160
440
 
161
441
  if (cached.src) {
162
- window.URL.revokeObjectURL(cached.src);
442
+ cached.revoke && api?.URL.revokeObjectURL(cached.src);
163
443
  }
164
444
 
165
445
  delete cache[key];
166
446
  }
447
+
448
+ disabledKeys.clear();
449
+ verifiedOps.clear();
167
450
  }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Copyright (c) 2017 ~ present NAVER Corp.
3
+ * billboard.js project is licensed under the MIT license
4
+ */
5
+ import type {HTMLProps} from "react";
6
+ import {createElement, forwardRef, useEffect, useImperativeHandle, useRef} from "react";
7
+ import type {bb, Chart as BillboardChart, ChartOptions} from "../../types";
8
+ import type {ChartTypes} from "../../types/types";
9
+
10
+ export type {ChartOptions as IChartOptions};
11
+
12
+ export type ChartTypeResolver = () => ChartTypes;
13
+ export type ChartModuleResolver = () => unknown;
14
+
15
+ export interface IProp extends Pick<HTMLProps<HTMLDivElement>, "className" | "style"> {
16
+ bb: typeof bb;
17
+ options: ChartOptions;
18
+ type?: ChartTypes | ChartTypeResolver;
19
+ modules?: ChartModuleResolver[];
20
+ }
21
+
22
+ export interface IChart {
23
+ instance: BillboardChart;
24
+ }
25
+
26
+ /**
27
+ * Resolve chart type from a direct string or resolver function.
28
+ * @param {string|function} [type] Chart type value or resolver
29
+ * @returns {string|undefined} Chart type string
30
+ * @private
31
+ */
32
+ function resolveType(type?: IProp["type"]): ChartTypes | undefined {
33
+ return typeof type === "function" ? type() : type;
34
+ }
35
+
36
+ /**
37
+ * Clone options and apply the optional chart type helper.
38
+ * @param {object} options Chart options
39
+ * @param {string|function} [type] Chart type value or resolver
40
+ * @returns {object} Chart options with resolved type
41
+ * @private
42
+ */
43
+ function getOptions(options: ChartOptions, type?: IProp["type"]): ChartOptions {
44
+ const resolvedType = resolveType(type);
45
+
46
+ return {
47
+ ...options,
48
+ ...(resolvedType ?
49
+ {
50
+ data: {
51
+ ...options.data,
52
+ type: resolvedType
53
+ }
54
+ } :
55
+ {})
56
+ };
57
+ }
58
+
59
+ /**
60
+ * React component wrapper for billboard.js.
61
+ * @module billboard.js/react
62
+ * @description
63
+ * Use the `billboard.js/react` subpath to render billboard.js charts in React.
64
+ * The component preserves the existing `ChartOptions` API and receives the
65
+ * billboard namespace through the `bb` prop, so importing this React subpath
66
+ * does not pull the root billboard.js bundle into non-React user bundles.
67
+ * @example
68
+ * import bb, {line} from "billboard.js";
69
+ * import BillboardJS from "billboard.js/react";
70
+ *
71
+ * <BillboardJS
72
+ * bb={bb}
73
+ * options={{
74
+ * data: {
75
+ * columns: [["data1", 30, 120, 80]],
76
+ * type: line()
77
+ * }
78
+ * }}
79
+ * />;
80
+ * @example
81
+ * import bb, {canvas, line} from "billboard.js/canvas";
82
+ * import BillboardJS from "billboard.js/react";
83
+ *
84
+ * <BillboardJS
85
+ * bb={bb}
86
+ * type={line}
87
+ * modules={[canvas]}
88
+ * style={{
89
+ * width: "480px",
90
+ * height: "320px"
91
+ * }}
92
+ * options={{
93
+ * render: {
94
+ * mode: "canvas"
95
+ * },
96
+ * size: {
97
+ * width: 480,
98
+ * height: 320
99
+ * },
100
+ * data: {
101
+ * columns: [["data1", 30, 120, 80]]
102
+ * }
103
+ * }}
104
+ * />;
105
+ * @example
106
+ * import bb, {line, zoom} from "billboard.js";
107
+ * import {Chart} from "billboard.js/react";
108
+ *
109
+ * <Chart
110
+ * bb={bb}
111
+ * type={line}
112
+ * modules={[zoom]}
113
+ * options={{
114
+ * data: {
115
+ * columns: [["data1", 30, 120, 80]]
116
+ * },
117
+ * zoom: {
118
+ * enabled: true
119
+ * }
120
+ * }}
121
+ * />;
122
+ * @example
123
+ * // UMD: 'dist/billboard.react.js' exposes the 'BillboardReact' global, holding
124
+ * // the same component as both '.Chart' and '.default'. React is expected on the
125
+ * // page as the 'React' global, so this path needs a UMD build of React - React
126
+ * // 18 and below ship one, React 19 does not.
127
+ * <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
128
+ * <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
129
+ *
130
+ * <link rel="stylesheet" href="$YOUR_PATH/billboard.css">
131
+ * <script src="$YOUR_PATH/billboard.pkgd.js"></script>
132
+ * <script src="$YOUR_PATH/billboard.react.js"></script>
133
+ *
134
+ * <div id="root"></div>
135
+ * <script>
136
+ * const {Chart} = BillboardReact;
137
+ *
138
+ * ReactDOM.createRoot(document.getElementById("root")).render(
139
+ * React.createElement(Chart, {
140
+ * bb,
141
+ * options: {
142
+ * data: {
143
+ * columns: [["data1", 30, 120, 80]],
144
+ * type: "line"
145
+ * }
146
+ * }
147
+ * })
148
+ * );
149
+ * </script>
150
+ */
151
+ const Chart = forwardRef<IChart, IProp>((props, ref) => {
152
+ const container = useRef<HTMLDivElement>(null);
153
+ const instance = useRef<BillboardChart | null>(null);
154
+ const {bb: billboard, options, type, modules, ...htmlDivProps} = props;
155
+
156
+ useEffect(() => {
157
+ if (!billboard || !options) {
158
+ // eslint-disable-next-line no-console
159
+ console.warn("Required props('bb' or 'options') are not defined.");
160
+ return;
161
+ }
162
+
163
+ modules?.forEach(register => register());
164
+
165
+ const chartOptions = getOptions(options, type);
166
+
167
+ chartOptions.bindto = container.current;
168
+ instance.current = billboard.generate(chartOptions);
169
+
170
+ return () => {
171
+ instance.current?.destroy();
172
+ instance.current = null;
173
+ };
174
+ }, []);
175
+
176
+ useImperativeHandle(
177
+ ref,
178
+ () => ({
179
+ get instance() {
180
+ return instance.current as BillboardChart;
181
+ }
182
+ }),
183
+ []
184
+ );
185
+
186
+ return createElement("div", {
187
+ ...htmlDivProps,
188
+ ref: container
189
+ });
190
+ });
191
+
192
+ export {Chart};
193
+ export default Chart;