@kepler.gl/utils 3.3.0-alpha.2 → 3.3.0-alpha.21

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 (264) hide show
  1. package/dist/application-config.d.ts +180 -1
  2. package/dist/arrow-data-container.d.ts +55 -2
  3. package/dist/camera-tour.d.ts +11 -0
  4. package/dist/camera-utils.d.ts +7 -0
  5. package/dist/cjs/aggregation.js +84 -0
  6. package/dist/cjs/aggregation.js.map +1 -0
  7. package/dist/cjs/application-config-types.js +6 -0
  8. package/dist/cjs/application-config-types.js.map +1 -0
  9. package/dist/cjs/application-config.js +178 -0
  10. package/dist/cjs/application-config.js.map +1 -0
  11. package/dist/cjs/arrow-data-container.js +1152 -0
  12. package/dist/cjs/arrow-data-container.js.map +1 -0
  13. package/dist/cjs/browser-utils.js +17 -0
  14. package/dist/cjs/browser-utils.js.map +1 -0
  15. package/dist/cjs/camera-tour.js +99 -0
  16. package/dist/cjs/camera-tour.js.map +1 -0
  17. package/dist/cjs/camera-utils.js +81 -0
  18. package/dist/cjs/camera-utils.js.map +1 -0
  19. package/dist/cjs/color-utils.js +462 -0
  20. package/dist/cjs/color-utils.js.map +1 -0
  21. package/dist/cjs/column-statistics.js +115 -0
  22. package/dist/cjs/column-statistics.js.map +1 -0
  23. package/dist/cjs/data-container-interface.js +6 -0
  24. package/dist/cjs/data-container-interface.js.map +1 -0
  25. package/dist/cjs/data-container-utils.js +76 -0
  26. package/dist/cjs/data-container-utils.js.map +1 -0
  27. package/dist/cjs/data-row.js +110 -0
  28. package/dist/cjs/data-row.js.map +1 -0
  29. package/dist/cjs/data-scale-utils.js +634 -0
  30. package/dist/cjs/data-scale-utils.js.map +1 -0
  31. package/dist/cjs/data-utils.js +538 -0
  32. package/dist/cjs/data-utils.js.map +1 -0
  33. package/dist/cjs/dataset-utils.js +361 -0
  34. package/dist/cjs/dataset-utils.js.map +1 -0
  35. package/dist/cjs/dom-to-image.js +433 -0
  36. package/dist/cjs/dom-to-image.js.map +1 -0
  37. package/dist/cjs/dom-utils.js +349 -0
  38. package/dist/cjs/dom-utils.js.map +1 -0
  39. package/dist/cjs/editor-feature-utils.js +177 -0
  40. package/dist/cjs/editor-feature-utils.js.map +1 -0
  41. package/dist/cjs/effect-utils.js +340 -0
  42. package/dist/cjs/effect-utils.js.map +1 -0
  43. package/dist/cjs/export-map-html.js +112 -0
  44. package/dist/cjs/export-map-html.js.map +1 -0
  45. package/dist/cjs/export-utils.js +318 -0
  46. package/dist/cjs/export-utils.js.map +1 -0
  47. package/dist/cjs/extract-dataset-utils.js +218 -0
  48. package/dist/cjs/extract-dataset-utils.js.map +1 -0
  49. package/dist/cjs/filter-utils.js +1762 -0
  50. package/dist/cjs/filter-utils.js.map +1 -0
  51. package/dist/cjs/format.js +38 -0
  52. package/dist/cjs/format.js.map +1 -0
  53. package/dist/cjs/gl-utils.js +118 -0
  54. package/dist/cjs/gl-utils.js.map +1 -0
  55. package/dist/{index.js → cjs/index.js} +391 -10
  56. package/dist/cjs/index.js.map +1 -0
  57. package/dist/cjs/indexed-data-container.js +214 -0
  58. package/dist/cjs/indexed-data-container.js.map +1 -0
  59. package/dist/cjs/jenks.js +156 -0
  60. package/dist/cjs/jenks.js.map +1 -0
  61. package/dist/cjs/locale-utils.js +39 -0
  62. package/dist/cjs/locale-utils.js.map +1 -0
  63. package/dist/cjs/map-info-utils.js +41 -0
  64. package/dist/cjs/map-info-utils.js.map +1 -0
  65. package/dist/cjs/map-style-utils/mapbox-gl-style-editor.js +198 -0
  66. package/dist/cjs/map-style-utils/mapbox-gl-style-editor.js.map +1 -0
  67. package/dist/cjs/map-style-utils/mapbox-utils.js +155 -0
  68. package/dist/cjs/map-style-utils/mapbox-utils.js.map +1 -0
  69. package/dist/cjs/map-utils.js +76 -0
  70. package/dist/cjs/map-utils.js.map +1 -0
  71. package/dist/cjs/mapbox-utils.js +19 -0
  72. package/dist/cjs/mapbox-utils.js.map +1 -0
  73. package/dist/cjs/notifications-utils.js +69 -0
  74. package/dist/cjs/notifications-utils.js.map +1 -0
  75. package/dist/cjs/observe-dimensions.js +136 -0
  76. package/dist/cjs/observe-dimensions.js.map +1 -0
  77. package/dist/cjs/plot.js +1502 -0
  78. package/dist/cjs/plot.js.map +1 -0
  79. package/dist/cjs/position-utils.js +29 -0
  80. package/dist/cjs/position-utils.js.map +1 -0
  81. package/dist/cjs/projection-utils.js +141 -0
  82. package/dist/cjs/projection-utils.js.map +1 -0
  83. package/dist/cjs/quick-insertion-sort.js +132 -0
  84. package/dist/cjs/quick-insertion-sort.js.map +1 -0
  85. package/dist/cjs/row-data-container.js +291 -0
  86. package/dist/cjs/row-data-container.js.map +1 -0
  87. package/dist/cjs/slider-scale-utils.js +138 -0
  88. package/dist/cjs/slider-scale-utils.js.map +1 -0
  89. package/dist/cjs/split-map-utils.js +117 -0
  90. package/dist/cjs/split-map-utils.js.map +1 -0
  91. package/dist/cjs/strings.js +16 -0
  92. package/dist/cjs/strings.js.map +1 -0
  93. package/dist/cjs/theme-utils.js +46 -0
  94. package/dist/cjs/theme-utils.js.map +1 -0
  95. package/dist/cjs/time.js +321 -0
  96. package/dist/cjs/time.js.map +1 -0
  97. package/dist/cjs/types.js +6 -0
  98. package/dist/cjs/types.js.map +1 -0
  99. package/dist/cjs/utils.js +224 -0
  100. package/dist/cjs/utils.js.map +1 -0
  101. package/dist/column-statistics.d.ts +54 -0
  102. package/dist/data-container-interface.d.ts +16 -1
  103. package/dist/data-container-utils.d.ts +2 -1
  104. package/dist/data-scale-utils.d.ts +5 -0
  105. package/dist/data-utils.d.ts +3 -3
  106. package/dist/dataset-utils.d.ts +11 -28
  107. package/dist/editor-feature-utils.d.ts +30 -0
  108. package/dist/esm/aggregation.js +75 -0
  109. package/dist/esm/aggregation.js.map +1 -0
  110. package/dist/esm/application-config-types.js +3 -0
  111. package/dist/esm/application-config-types.js.map +1 -0
  112. package/dist/esm/application-config.js +167 -0
  113. package/dist/esm/application-config.js.map +1 -0
  114. package/dist/esm/arrow-data-container.js +1136 -0
  115. package/dist/esm/arrow-data-container.js.map +1 -0
  116. package/dist/esm/browser-utils.js +11 -0
  117. package/dist/esm/browser-utils.js.map +1 -0
  118. package/dist/esm/camera-tour.js +92 -0
  119. package/dist/esm/camera-tour.js.map +1 -0
  120. package/dist/esm/camera-utils.js +74 -0
  121. package/dist/esm/camera-utils.js.map +1 -0
  122. package/dist/esm/color-utils.js +435 -0
  123. package/dist/esm/color-utils.js.map +1 -0
  124. package/dist/esm/column-statistics.js +105 -0
  125. package/dist/esm/column-statistics.js.map +1 -0
  126. package/dist/esm/data-container-interface.js +3 -0
  127. package/dist/esm/data-container-interface.js.map +1 -0
  128. package/dist/esm/data-container-utils.js +68 -0
  129. package/dist/esm/data-container-utils.js.map +1 -0
  130. package/dist/esm/data-row.js +106 -0
  131. package/dist/esm/data-row.js.map +1 -0
  132. package/dist/esm/data-scale-utils.js +602 -0
  133. package/dist/esm/data-scale-utils.js.map +1 -0
  134. package/dist/esm/data-utils.js +504 -0
  135. package/dist/esm/data-utils.js.map +1 -0
  136. package/dist/esm/dataset-utils.js +352 -0
  137. package/dist/esm/dataset-utils.js.map +1 -0
  138. package/dist/esm/dom-to-image.js +426 -0
  139. package/dist/esm/dom-to-image.js.map +1 -0
  140. package/dist/esm/dom-utils.js +323 -0
  141. package/dist/esm/dom-utils.js.map +1 -0
  142. package/dist/esm/editor-feature-utils.js +164 -0
  143. package/dist/esm/editor-feature-utils.js.map +1 -0
  144. package/dist/esm/effect-utils.js +333 -0
  145. package/dist/esm/effect-utils.js.map +1 -0
  146. package/dist/esm/export-map-html.js +107 -0
  147. package/dist/esm/export-map-html.js.map +1 -0
  148. package/dist/esm/export-utils.js +297 -0
  149. package/dist/esm/export-utils.js.map +1 -0
  150. package/dist/esm/extract-dataset-utils.js +206 -0
  151. package/dist/esm/extract-dataset-utils.js.map +1 -0
  152. package/dist/esm/filter-utils.js +1701 -0
  153. package/dist/esm/filter-utils.js.map +1 -0
  154. package/dist/esm/format.js +31 -0
  155. package/dist/esm/format.js.map +1 -0
  156. package/dist/esm/gl-utils.js +113 -0
  157. package/dist/esm/gl-utils.js.map +1 -0
  158. package/dist/esm/index.js +55 -0
  159. package/dist/esm/index.js.map +1 -0
  160. package/dist/esm/indexed-data-container.js +210 -0
  161. package/dist/esm/indexed-data-container.js.map +1 -0
  162. package/dist/esm/jenks.js +149 -0
  163. package/dist/esm/jenks.js.map +1 -0
  164. package/dist/esm/locale-utils.js +36 -0
  165. package/dist/esm/locale-utils.js.map +1 -0
  166. package/dist/esm/map-info-utils.js +35 -0
  167. package/dist/esm/map-info-utils.js.map +1 -0
  168. package/dist/esm/map-style-utils/mapbox-gl-style-editor.js +188 -0
  169. package/dist/esm/map-style-utils/mapbox-gl-style-editor.js.map +1 -0
  170. package/dist/esm/map-style-utils/mapbox-utils.js +144 -0
  171. package/dist/esm/map-style-utils/mapbox-utils.js.map +1 -0
  172. package/dist/esm/map-utils.js +72 -0
  173. package/dist/esm/map-utils.js.map +1 -0
  174. package/dist/esm/mapbox-utils.js +13 -0
  175. package/dist/esm/mapbox-utils.js.map +1 -0
  176. package/dist/esm/notifications-utils.js +63 -0
  177. package/dist/esm/notifications-utils.js.map +1 -0
  178. package/dist/esm/observe-dimensions.js +128 -0
  179. package/dist/esm/observe-dimensions.js.map +1 -0
  180. package/dist/esm/plot.js +1460 -0
  181. package/dist/esm/plot.js.map +1 -0
  182. package/dist/esm/position-utils.js +22 -0
  183. package/dist/esm/position-utils.js.map +1 -0
  184. package/dist/esm/projection-utils.js +131 -0
  185. package/dist/esm/projection-utils.js.map +1 -0
  186. package/dist/esm/quick-insertion-sort.js +125 -0
  187. package/dist/esm/quick-insertion-sort.js.map +1 -0
  188. package/dist/esm/row-data-container.js +286 -0
  189. package/dist/esm/row-data-container.js.map +1 -0
  190. package/dist/esm/slider-scale-utils.js +129 -0
  191. package/dist/esm/slider-scale-utils.js.map +1 -0
  192. package/dist/esm/split-map-utils.js +109 -0
  193. package/dist/esm/split-map-utils.js.map +1 -0
  194. package/dist/esm/strings.js +10 -0
  195. package/dist/esm/strings.js.map +1 -0
  196. package/dist/esm/theme-utils.js +38 -0
  197. package/dist/esm/theme-utils.js.map +1 -0
  198. package/dist/esm/time.js +308 -0
  199. package/dist/esm/time.js.map +1 -0
  200. package/dist/esm/types.js +3 -0
  201. package/dist/esm/types.js.map +1 -0
  202. package/dist/esm/utils.js +203 -0
  203. package/dist/esm/utils.js.map +1 -0
  204. package/dist/export-map-html.d.ts +5 -0
  205. package/dist/export-utils.d.ts +31 -3
  206. package/dist/extract-dataset-utils.d.ts +79 -0
  207. package/dist/filter-utils.d.ts +56 -7
  208. package/dist/index.d.ts +20 -9
  209. package/dist/jenks.d.ts +5 -0
  210. package/dist/map-info-utils.d.ts +11 -1
  211. package/dist/map-style-utils/mapbox-gl-style-editor.d.ts +11 -10
  212. package/dist/map-style-utils/mapbox-utils.d.ts +29 -1
  213. package/dist/plot.d.ts +187 -21
  214. package/dist/projection-utils.d.ts +6 -4
  215. package/dist/row-data-container.d.ts +19 -0
  216. package/dist/split-map-utils.d.ts +7 -0
  217. package/dist/theme-utils.d.ts +8 -0
  218. package/dist/time.d.ts +3 -3
  219. package/dist/types.d.ts +2 -0
  220. package/package.json +33 -26
  221. package/dist/aggregation.js +0 -84
  222. package/dist/application-config-types.js +0 -6
  223. package/dist/application-config.js +0 -113
  224. package/dist/arrow-data-container.js +0 -398
  225. package/dist/browser-utils.js +0 -17
  226. package/dist/color-utils.js +0 -462
  227. package/dist/data-container-interface.js +0 -6
  228. package/dist/data-container-utils.js +0 -75
  229. package/dist/data-row.js +0 -110
  230. package/dist/data-scale-utils.js +0 -620
  231. package/dist/data-utils.js +0 -532
  232. package/dist/dataset-utils.js +0 -330
  233. package/dist/dom-to-image.js +0 -433
  234. package/dist/dom-utils.js +0 -349
  235. package/dist/effect-utils.js +0 -318
  236. package/dist/export-map-html.js +0 -38
  237. package/dist/export-utils.js +0 -203
  238. package/dist/filter-utils.js +0 -1274
  239. package/dist/format.js +0 -38
  240. package/dist/gl-utils.js +0 -118
  241. package/dist/indexed-data-container.js +0 -214
  242. package/dist/locale-utils.js +0 -39
  243. package/dist/map-info-utils.js +0 -14
  244. package/dist/map-style-utils/mapbox-gl-style-editor.js +0 -194
  245. package/dist/map-style-utils/mapbox-utils.js +0 -107
  246. package/dist/map-utils.js +0 -72
  247. package/dist/mapbox-utils.js +0 -19
  248. package/dist/noop.d.ts +0 -1
  249. package/dist/noop.js +0 -13
  250. package/dist/notifications-utils.js +0 -69
  251. package/dist/observe-dimensions.js +0 -136
  252. package/dist/plot.js +0 -637
  253. package/dist/position-utils.js +0 -26
  254. package/dist/projection-utils.js +0 -91
  255. package/dist/quick-insertion-sort.js +0 -132
  256. package/dist/row-data-container.js +0 -206
  257. package/dist/searcher-utils.d.ts +0 -1
  258. package/dist/searcher-utils.js +0 -25
  259. package/dist/slider-scale-utils.js +0 -138
  260. package/dist/split-map-utils.js +0 -99
  261. package/dist/strings.js +0 -16
  262. package/dist/time.js +0 -325
  263. package/dist/types.js +0 -6
  264. package/dist/utils.js +0 -224
@@ -0,0 +1,1460 @@
1
+ import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
2
+ import _typeof from "@babel/runtime/helpers/esm/typeof";
3
+ import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
4
+ import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
5
+ import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
6
+ var _excluded = ["numericInterval"];
7
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
8
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
9
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
10
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
11
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
12
+ // SPDX-License-Identifier: MIT
13
+ // Copyright contributors to the kepler.gl project
14
+
15
+ import { bisectCenter, bisectLeft, bisectRight, extent, histogram as d3Histogram, ticks } from 'd3-array';
16
+ import isEqual from 'es-toolkit/compat/isEqual';
17
+ import { getFilterMappedValue, getInitialInterval, getIntervalByTicks, intervalToFunction } from './time';
18
+ import { notNullorUndefined, toArray } from '@kepler.gl/common-utils';
19
+ import { ANIMATION_WINDOW, BINS, BINS_LARGE, FILTER_TYPES, TIME_AGGREGATION, AGGREGATION_TYPES, PLOT_TYPES, KEPLER_COLOR_PALETTES, colorPaletteToColorRange, DEFAULT_COLOR_UI, DEFAULT_CUSTOM_PALETTE } from '@kepler.gl/constants';
20
+ import { isNumber, roundValToStep } from './data-utils';
21
+ import { aggregate, AGGREGATION_NAME } from './aggregation';
22
+ import { capitalizeFirstLetter } from './strings';
23
+ import { getDefaultTimeFormat } from './format';
24
+ import { rgbToHex } from './color-utils';
25
+
26
+ // TODO kepler-table module isn't accessible from utils. Add compatible interface to types
27
+
28
+ /**
29
+ * Merge per-layer polygon-filtered indices into a dataset-level index.
30
+ * When any layers are polygon-filtered, take the union of their indices (a row is kept if it
31
+ * is visible on at least one targeted layer), then intersect with the base index.
32
+ * Used for filtered export and filter plots/histograms.
33
+ */
34
+ export function mergePolygonLayerIndexes(baseIndex) {
35
+ var filteredIndexByLayer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
36
+ var layerIndexes = Object.values(filteredIndexByLayer);
37
+ if (!layerIndexes.length) {
38
+ return baseIndex;
39
+ }
40
+ var union = new Set();
41
+ for (var _i = 0, _layerIndexes = layerIndexes; _i < _layerIndexes.length; _i++) {
42
+ var indexes = _layerIndexes[_i];
43
+ var _iterator = _createForOfIteratorHelper(indexes),
44
+ _step;
45
+ try {
46
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
47
+ var idx = _step.value;
48
+ union.add(idx);
49
+ }
50
+ } catch (err) {
51
+ _iterator.e(err);
52
+ } finally {
53
+ _iterator.f();
54
+ }
55
+ }
56
+ return baseIndex.filter(function (i) {
57
+ return union.has(i);
58
+ });
59
+ }
60
+
61
+ /**
62
+ *
63
+ * @param thresholds
64
+ * @param values
65
+ * @param indexes
66
+ */
67
+ export function histogramFromThreshold(thresholds, values, valueAccessor) {
68
+ var filterEmptyBins = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
69
+ var getBins = d3Histogram().domain([thresholds[0], thresholds[thresholds.length - 1]]).thresholds(thresholds);
70
+ if (valueAccessor) {
71
+ getBins.value(valueAccessor);
72
+ }
73
+
74
+ // @ts-ignore
75
+ var bins = getBins(values).map(function (bin) {
76
+ return {
77
+ count: bin.length,
78
+ indexes: bin,
79
+ x0: bin.x0,
80
+ x1: bin.x1
81
+ };
82
+ });
83
+
84
+ // d3-histogram ignores threshold values outside the domain
85
+ // The first bin.x0 is always equal to the minimum domain value, and the last bin.x1 is always equal to the maximum domain value.
86
+
87
+ // bins[0].x0 = thresholds[0];
88
+ // bins[bins.length - 1].x1 = thresholds[thresholds.length - 1];
89
+
90
+ // @ts-ignore
91
+ return filterEmptyBins ? bins.filter(function (b) {
92
+ return b.count > 0;
93
+ }) : bins;
94
+ }
95
+
96
+ /**
97
+ *
98
+ * @param values
99
+ * @param numBins
100
+ * @param valueAccessor
101
+ */
102
+ export function histogramFromValues(values, numBins, valueAccessor) {
103
+ var getBins = d3Histogram().thresholds(numBins);
104
+ if (valueAccessor) {
105
+ getBins.value(valueAccessor);
106
+ }
107
+
108
+ // @ts-ignore d3-array types doesn't match
109
+ return getBins(values).map(function (bin) {
110
+ return {
111
+ count: bin.length,
112
+ indexes: bin,
113
+ x0: bin.x0,
114
+ x1: bin.x1
115
+ };
116
+ }).filter(function (b) {
117
+ var x0 = b.x0,
118
+ x1 = b.x1;
119
+ return isNumber(x0) && isNumber(x1);
120
+ });
121
+ }
122
+ export function histogramFromOrdinal(domain, values, valueAccessor) {
123
+ // @ts-expect-error to typed to expect strings
124
+ var getBins = d3Histogram().thresholds(domain);
125
+ if (valueAccessor) {
126
+ // @ts-expect-error to typed to expect strings
127
+ getBins.value(valueAccessor);
128
+ }
129
+
130
+ // @ts-expect-error null values aren't expected
131
+ var bins = getBins(values);
132
+
133
+ // @ts-ignore d3-array types doesn't match
134
+ return bins.map(function (bin) {
135
+ return {
136
+ count: bin.length,
137
+ indexes: bin,
138
+ x0: bin.x0,
139
+ x1: bin.x0
140
+ };
141
+ });
142
+ }
143
+
144
+ /**
145
+ * Bin rows by time interval overlap: a feature [start, end] is counted in every
146
+ * bin whose range intersects that span. Null/undefined end is treated as still
147
+ * active through the last threshold (open-ended).
148
+ */
149
+ export function histogramFromTimeIntervals(thresholds, indexes, startAccessor, endAccessor) {
150
+ if (!thresholds || thresholds.length < 2) {
151
+ return [];
152
+ }
153
+ var nBins = thresholds.length - 1;
154
+ var bins = [];
155
+ for (var i = 0; i < nBins; i++) {
156
+ bins.push({
157
+ count: 0,
158
+ indexes: [],
159
+ x0: thresholds[i],
160
+ x1: thresholds[i + 1]
161
+ });
162
+ }
163
+ var lastThreshold = thresholds[nBins];
164
+ var _iterator2 = _createForOfIteratorHelper(indexes),
165
+ _step2;
166
+ try {
167
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
168
+ var idx = _step2.value;
169
+ var start = startAccessor(idx);
170
+ if (!notNullorUndefined(start) || Number.isNaN(start)) {
171
+ continue;
172
+ }
173
+ var rawEnd = endAccessor(idx);
174
+ if (notNullorUndefined(rawEnd) && !Number.isNaN(rawEnd) && rawEnd < start) {
175
+ continue;
176
+ }
177
+ var end = notNullorUndefined(rawEnd) && !Number.isNaN(rawEnd) ? rawEnd : lastThreshold;
178
+ var startBin = bisectRight(thresholds, start) - 1;
179
+ var endBin = bisectRight(thresholds, end) - 1;
180
+ if (startBin < 0) startBin = 0;
181
+ if (startBin >= nBins && start === lastThreshold) startBin = nBins - 1;
182
+ if (endBin >= nBins) endBin = nBins - 1;
183
+ if (endBin < 0 || startBin >= nBins || endBin < startBin) {
184
+ continue;
185
+ }
186
+ for (var _i2 = startBin; _i2 <= endBin; _i2++) {
187
+ bins[_i2].indexes.push(idx);
188
+ bins[_i2].count += 1;
189
+ }
190
+ }
191
+ } catch (err) {
192
+ _iterator2.e(err);
193
+ } finally {
194
+ _iterator2.f();
195
+ }
196
+ return bins.filter(function (b) {
197
+ return b.count > 0;
198
+ });
199
+ }
200
+ function getEndMappedValue(dataset, filter) {
201
+ var _filter$endMappedValu, _field$filterProps;
202
+ var datasetIdx = toArray(filter.dataId).indexOf(dataset.id);
203
+ var fromFilter = (_filter$endMappedValu = filter.endMappedValue) === null || _filter$endMappedValu === void 0 ? void 0 : _filter$endMappedValu[datasetIdx];
204
+ if (Array.isArray(fromFilter)) {
205
+ return fromFilter;
206
+ }
207
+ var endName = toArray(filter.endName)[datasetIdx];
208
+ if (!endName || typeof dataset.getColumnField !== 'function') {
209
+ return null;
210
+ }
211
+ var field = dataset.getColumnField(endName);
212
+ return (field === null || field === void 0 || (_field$filterProps = field.filterProps) === null || _field$filterProps === void 0 ? void 0 : _field$filterProps.mappedValue) || null;
213
+ }
214
+
215
+ /**
216
+ * @param domain
217
+ * @param values
218
+ * @param numBins
219
+ * @param valueAccessor
220
+ */
221
+ export function histogramFromDomain(domain, values, numBins, valueAccessor) {
222
+ var getBins = d3Histogram().thresholds(ticks(domain[0], domain[1], numBins)).domain(domain);
223
+ if (valueAccessor) {
224
+ getBins.value(valueAccessor);
225
+ }
226
+
227
+ // @ts-ignore d3-array types doesn't match
228
+ return getBins(values).map(function (bin) {
229
+ return {
230
+ count: bin.length,
231
+ indexes: bin,
232
+ x0: bin.x0,
233
+ x1: bin.x1
234
+ };
235
+ });
236
+ }
237
+ var timeBinDomains = new WeakMap();
238
+
239
+ /**
240
+ * @param filter
241
+ * @param datasets
242
+ * @param interval
243
+ */
244
+ export function getTimeBins(filter, datasets, interval, plotBaseIndexByDataId) {
245
+ interval = getTimeBinConfig(interval, filter.domain).interval;
246
+ var cachedDomain = filter.timeBins && timeBinDomains.get(filter.timeBins);
247
+ // Preserve caller-supplied caches; invalidate a domain change once it is known.
248
+ var bins = cachedDomain && !isEqual(cachedDomain, filter.domain) ? {} : filter.timeBins || {};
249
+ filter.dataId.forEach(function (dataId) {
250
+ // reuse bins if filterData did not change
251
+ if (bins[dataId] && bins[dataId][interval]) {
252
+ return;
253
+ }
254
+ var dataset = datasets[dataId];
255
+
256
+ // do not apply current filter
257
+ var indexes = runGpuFilterForPlot(dataset, filter, undefined, plotBaseIndexByDataId === null || plotBaseIndexByDataId === void 0 ? void 0 : plotBaseIndexByDataId[dataId]);
258
+ bins = _objectSpread(_objectSpread({}, bins), {}, _defineProperty({}, dataId, _objectSpread(_objectSpread({}, bins[dataId]), {}, _defineProperty({}, interval, binByTime(indexes, dataset, interval, filter)))));
259
+ });
260
+ timeBinDomains.set(bins, Array.isArray(filter.domain) ? filter.domain.slice(0, 2) : []);
261
+ return bins;
262
+ }
263
+ export function binByTime(indexes, dataset, interval, filter) {
264
+ // gpuFilters need to be apply to filteredIndex
265
+ var mappedValue = getFilterMappedValue(dataset, filter);
266
+ if (!mappedValue) {
267
+ return null;
268
+ }
269
+ var intervalBins = getBinThresholds(interval, filter.domain);
270
+ var endMapped = getEndMappedValue(dataset, filter);
271
+ if (Array.isArray(endMapped)) {
272
+ return histogramFromTimeIntervals(intervalBins, indexes, function (idx) {
273
+ return mappedValue[idx];
274
+ }, function (idx) {
275
+ return endMapped[idx];
276
+ });
277
+ }
278
+ var valueAccessor = function valueAccessor(idx) {
279
+ return mappedValue[idx];
280
+ };
281
+ var bins = histogramFromThreshold(intervalBins, indexes, valueAccessor);
282
+ return bins;
283
+ }
284
+ export function getBinThresholds(interval, domain) {
285
+ return getTimeBinConfig(interval, domain).thresholds.slice();
286
+ }
287
+ var MAX_TIME_BINS = 2048;
288
+ // Weak keys keep validation local to live domains without retaining old filters.
289
+ var timeBinConfigs = new WeakMap();
290
+
291
+ /** Resolve the interval and its complete domain together, never truncating a plot. */
292
+ function getTimeBinConfig(interval, domain) {
293
+ if (!Array.isArray(domain) || domain.length !== 2 || !domain.every(function (value) {
294
+ return Number.isFinite(value) && Number.isFinite(new Date(value).getTime());
295
+ }) || domain[1] < domain[0]) {
296
+ return {
297
+ interval: interval,
298
+ thresholds: []
299
+ };
300
+ }
301
+ var cached = timeBinConfigs.get(domain);
302
+ if (cached && isEqual(cached.domain, domain) && (cached.requestedInterval === interval || cached.result.interval === interval)) {
303
+ return cached.result;
304
+ }
305
+ var build = function build(id) {
306
+ var match = /^(\d+)-(millisecond|second|minute|hour|day|week|month|year)$/.exec(id);
307
+ var step = Number(match === null || match === void 0 ? void 0 : match[1]);
308
+ if (!match || !Number.isSafeInteger(step) || step <= 0) return null;
309
+ var timeInterval = intervalToFunction(id);
310
+ if (!timeInterval) return null;
311
+ // Filtered D3 intervals can loop internally after Date overflow. Near the
312
+ // Date limits, walk at most one field cycle using the unfiltered interval.
313
+ var period = {
314
+ second: 60,
315
+ minute: 60,
316
+ hour: 24,
317
+ day: 31,
318
+ month: 12
319
+ }[match[2]];
320
+ if (step > 1 && period) {
321
+ var base = intervalToFunction("1-".concat(match[2]));
322
+ if (!Number.isFinite(Number(base.offset(domain[0], -period))) || !Number.isFinite(Number(base.offset(domain[1], period)))) {
323
+ var field = {
324
+ second: function second(date) {
325
+ return date.getUTCSeconds();
326
+ },
327
+ minute: function minute(date) {
328
+ return date.getUTCMinutes();
329
+ },
330
+ hour: function hour(date) {
331
+ return date.getUTCHours();
332
+ },
333
+ day: function day(date) {
334
+ return date.getUTCDate() - 1;
335
+ },
336
+ month: function month(date) {
337
+ return date.getUTCMonth();
338
+ }
339
+ }[match[2]];
340
+ if (!field) return null;
341
+ var walk = function walk(value, direction) {
342
+ var includeCurrent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
343
+ var date = base.floor(value);
344
+ for (var index = 0; index < period; index++) {
345
+ if (!includeCurrent || index) date = base.offset(date, direction);
346
+ if (!Number.isFinite(Number(date))) return date;
347
+ if (field(date) % step === 0) return date;
348
+ }
349
+ return new Date(NaN);
350
+ };
351
+ timeInterval = {
352
+ floor: function floor(value) {
353
+ return walk(value, -1, true);
354
+ },
355
+ offset: function offset(value) {
356
+ return walk(value, 1);
357
+ }
358
+ };
359
+ }
360
+ }
361
+ if (match[2] === 'week' && step > 1) {
362
+ // D3's filtered week.offset walks every intervening week. Use the same
363
+ // epoch alignment without an unbounded scan for large configured steps.
364
+ var week = intervalToFunction('1-week');
365
+ timeInterval = {
366
+ floor: function floor(value) {
367
+ var floor = week.floor(value);
368
+ var remainder = (week.count(0, floor) % step + step) % step;
369
+ return week.offset(floor, -remainder);
370
+ },
371
+ offset: function offset(value) {
372
+ return week.offset(value, step);
373
+ }
374
+ };
375
+ }
376
+ var boundary = Number(timeInterval.floor(domain[0]));
377
+ var thresholds = [];
378
+ // Include the first boundary strictly after max, even when max is aligned.
379
+ // This preserves the existing inclusive maximum bin and calendar padding.
380
+ for (var index = 0; index <= MAX_TIME_BINS; index++) {
381
+ if (!Number.isFinite(boundary)) return null;
382
+ thresholds.push(boundary);
383
+ if (boundary > domain[1]) return thresholds;
384
+ var next = Number(timeInterval.floor(timeInterval.offset(boundary)));
385
+ if (!(next > boundary)) return null;
386
+ boundary = next;
387
+ }
388
+ return null;
389
+ };
390
+ var requestedInterval = interval;
391
+ var thresholds = build(interval);
392
+ // Domain-only fallback avoids copying/sorting every timestamp on refresh.
393
+ // Retry fewer ticks when the nearest interval still exceeds the cap.
394
+ for (var target = BINS_LARGE; !thresholds && target >= 1; target /= 10) {
395
+ interval = getIntervalByTicks(target, domain[0], domain[1]);
396
+ thresholds = build(interval);
397
+ }
398
+ var result = {
399
+ interval: interval,
400
+ thresholds: thresholds || []
401
+ };
402
+ timeBinConfigs.set(domain, {
403
+ requestedInterval: requestedInterval,
404
+ domain: domain.slice(),
405
+ result: result
406
+ });
407
+ return result;
408
+ }
409
+ function normalizeTimePlotType(plotType, domain) {
410
+ var _getTimeBinConfig = getTimeBinConfig(plotType.interval, domain),
411
+ interval = _getTimeBinConfig.interval;
412
+ return interval === plotType.interval ? plotType : _objectSpread(_objectSpread({}, plotType), {}, {
413
+ interval: interval,
414
+ defaultTimeFormat: getDefaultTimeFormat(interval)
415
+ });
416
+ }
417
+ var MAX_NUMERIC_BINS = 2048;
418
+ function getNumericBinCount(domain, interval) {
419
+ var _domain = _slicedToArray(domain, 2),
420
+ start = _domain[0],
421
+ end = _domain[1];
422
+ var rawCount = (end - start) / interval;
423
+ var roundedCount = Math.round(rawCount);
424
+ return Math.abs(rawCount - roundedCount) <= Number.EPSILON * Math.max(1, Math.abs(rawCount)) * 16 ? roundedCount : Math.ceil(rawCount);
425
+ }
426
+ function normalizeNumericInterval(domain, interval) {
427
+ if (!Number.isFinite(interval) || !(Number(interval) > 0)) {
428
+ return undefined;
429
+ }
430
+ if (Array.isArray(domain) && domain.length >= 2 && domain.every(Number.isFinite) && domain[1] > domain[0] && getNumericBinCount(domain, Number(interval)) > MAX_NUMERIC_BINS) {
431
+ return undefined;
432
+ }
433
+ return Number(interval);
434
+ }
435
+
436
+ /**
437
+ * Build histogram thresholds in the numeric field's own units.
438
+ * Unlike time intervals, numeric intervals are anchored to the filter domain
439
+ * and never pass through calendar conversion.
440
+ */
441
+ export function getNumericBinThresholds(domain, interval) {
442
+ var numBins = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : BINS;
443
+ if (!Array.isArray(domain) || domain.length < 2 || !domain.every(Number.isFinite)) {
444
+ return [];
445
+ }
446
+ var _domain2 = _slicedToArray(domain, 2),
447
+ start = _domain2[0],
448
+ end = _domain2[1];
449
+ if (!(end > start)) {
450
+ return [start, end];
451
+ }
452
+ if (!Number.isFinite(interval) || !(Number(interval) > 0)) {
453
+ var numericTicks = ticks(start, end, numBins).filter(function (value) {
454
+ return value > start && value < end;
455
+ });
456
+ return [start].concat(_toConsumableArray(numericTicks), [end]);
457
+ }
458
+ var width = Number(interval);
459
+ var count = getNumericBinCount(domain, width);
460
+ if (count > MAX_NUMERIC_BINS) {
461
+ return getNumericBinThresholds(domain, undefined, numBins);
462
+ }
463
+ var thresholds = [start];
464
+ for (var index = 1; index < count; index++) {
465
+ var boundary = start + index * width;
466
+ if (boundary > thresholds[thresholds.length - 1] && boundary < end) {
467
+ thresholds.push(boundary);
468
+ }
469
+ }
470
+ if (end > thresholds[thresholds.length - 1]) {
471
+ thresholds.push(end);
472
+ }
473
+ return thresholds;
474
+ }
475
+ var float64View = new DataView(new ArrayBuffer(8));
476
+ function adjacentFloat(value, direction) {
477
+ if (Number.isNaN(value) || value === direction * Infinity) {
478
+ return value;
479
+ }
480
+ if (value === 0) {
481
+ return direction > 0 ? Number.MIN_VALUE : -Number.MIN_VALUE;
482
+ }
483
+ float64View.setFloat64(0, value, false);
484
+ var high = float64View.getUint32(0, false);
485
+ var low = float64View.getUint32(4, false);
486
+ var incrementBits = value > 0 === direction > 0;
487
+ if (incrementBits) {
488
+ low = low + 1 >>> 0;
489
+ if (low === 0) {
490
+ high = high + 1 >>> 0;
491
+ }
492
+ } else if (low === 0) {
493
+ low = 0xffffffff;
494
+ high = high - 1 >>> 0;
495
+ } else {
496
+ low = low - 1 >>> 0;
497
+ }
498
+ float64View.setUint32(0, high, false);
499
+ float64View.setUint32(4, low, false);
500
+ return float64View.getFloat64(0, false);
501
+ }
502
+
503
+ /** Return the next representable IEEE-754 number above value. */
504
+ export function nextUp(value) {
505
+ return adjacentFloat(value, 1);
506
+ }
507
+
508
+ /** Return the next representable IEEE-754 number below value. */
509
+ export function nextDown(value) {
510
+ return adjacentFloat(value, -1);
511
+ }
512
+
513
+ /**
514
+ * Smallest useful range width across a numeric domain. It is large enough to
515
+ * move either endpoint by one representable value and never exceeds the span.
516
+ */
517
+ export function getNumericRangeMinimum(domain) {
518
+ if (!Array.isArray(domain) || domain.length < 2 || !domain.every(Number.isFinite)) {
519
+ return 0;
520
+ }
521
+ var _domain3 = _slicedToArray(domain, 2),
522
+ start = _domain3[0],
523
+ end = _domain3[1];
524
+ var span = end - start;
525
+ if (!(span > 0)) {
526
+ return 0;
527
+ }
528
+ var startResolution = nextUp(start) - start;
529
+ var endResolution = end - nextDown(end);
530
+ return Math.min(span, Math.max(startResolution, endResolution));
531
+ }
532
+
533
+ /** Infer the regular numeric bin width, ignoring tiny padded edge bins. */
534
+ export function getNumericPlotInterval(filter) {
535
+ var _filter$plotType, _filter$domain, _filter$domain2;
536
+ if (Number.isFinite((_filter$plotType = filter.plotType) === null || _filter$plotType === void 0 ? void 0 : _filter$plotType.numericInterval) && filter.plotType.numericInterval > 0) {
537
+ return filter.plotType.numericInterval;
538
+ }
539
+ var bins = Object.values(filter.bins || {}).find(function (value) {
540
+ return value === null || value === void 0 ? void 0 : value.length;
541
+ });
542
+ var binWidths = (bins || []).map(function (bin) {
543
+ return bin.x1 - bin.x0;
544
+ }).filter(function (width) {
545
+ return Number.isFinite(width) && width > 0;
546
+ }).sort(function (a, b) {
547
+ return a - b;
548
+ });
549
+ var binWidth = binWidths.length ? binWidths[Math.floor(binWidths.length / 2)] : 0;
550
+ if (binWidth > 0) {
551
+ return Number(binWidth.toPrecision(10));
552
+ }
553
+ var span = ((_filter$domain = filter.domain) === null || _filter$domain === void 0 ? void 0 : _filter$domain[1]) - ((_filter$domain2 = filter.domain) === null || _filter$domain2 === void 0 ? void 0 : _filter$domain2[0]);
554
+ return span > 0 ? Number((span / BINS).toPrecision(10)) : filter.step;
555
+ }
556
+
557
+ /** Return the plotted bin boundaries for either a time or numeric range filter. */
558
+ export function getFilterBinThresholds(filter) {
559
+ var _filter$plotType3;
560
+ if (filter.type === FILTER_TYPES.timeRange) {
561
+ var _filter$plotType2;
562
+ return getBinThresholds((_filter$plotType2 = filter.plotType) === null || _filter$plotType2 === void 0 ? void 0 : _filter$plotType2.interval, filter.domain);
563
+ }
564
+ var firstBins = Object.values(filter.bins || {}).find(Boolean) || [];
565
+ if (firstBins.length) {
566
+ return [].concat(_toConsumableArray(firstBins.map(function (bin) {
567
+ return bin.x0;
568
+ })), [firstBins[firstBins.length - 1].x1]);
569
+ }
570
+ return getNumericBinThresholds(filter.domain, (_filter$plotType3 = filter.plotType) === null || _filter$plotType3 === void 0 ? void 0 : _filter$plotType3.numericInterval);
571
+ }
572
+
573
+ /**
574
+ * Run GPU filter on current filter result to generate indexes for ploting chart
575
+ * Skip ruuning for the same field
576
+ * @param dataset
577
+ * @param filter Histogram filter whose dataId-paired column should be skipped
578
+ * @param skipFieldNames Extra GPU field names to skip (charts cross-filter). Histogram callers omit this.
579
+ * @param baseIndex CPU base that excludes the plotted filter and already includes polygon filters.
580
+ */
581
+ export function runGpuFilterForPlot(dataset, filter, skipFieldNames, baseIndex) {
582
+ var skipIndexes = getSkipIndexes(dataset, filter, skipFieldNames);
583
+ var _dataset$gpuFilter = dataset.gpuFilter,
584
+ filterValueUpdateTriggers = _dataset$gpuFilter.filterValueUpdateTriggers,
585
+ filterRange = _dataset$gpuFilter.filterRange,
586
+ filterValueAccessor = _dataset$gpuFilter.filterValueAccessor,
587
+ filteredIndex = dataset.filteredIndex,
588
+ filteredIndexByLayer = dataset.filteredIndexByLayer;
589
+ // Cached polygon indexes were built after the current CPU filter. When that
590
+ // filter is omitted, use the polygon-filtered base reconstructed by the caller.
591
+ var plotFilteredIndex = baseIndex !== null && baseIndex !== void 0 ? baseIndex : mergePolygonLayerIndexes(filteredIndex, filteredIndexByLayer);
592
+ var getFilterValue = filterValueAccessor(dataset.dataContainer)();
593
+ var allChannels = Object.keys(filterValueUpdateTriggers).map(function (_, i) {
594
+ return i;
595
+ }).filter(function (i) {
596
+ return Object.values(filterValueUpdateTriggers)[i];
597
+ });
598
+ var skipAll = !allChannels.filter(function (i) {
599
+ return !skipIndexes.includes(i);
600
+ }).length;
601
+ if (skipAll) {
602
+ return plotFilteredIndex;
603
+ }
604
+ var filterData = getFilterDataFunc(filterRange, getFilterValue, dataset.dataContainer, skipIndexes);
605
+ return plotFilteredIndex.filter(filterData);
606
+ }
607
+ function getSkipIndexes(dataset, filter, skipFieldNames) {
608
+ var _filter$endName;
609
+ // array of gpu filter names
610
+ var gpuFilters = Object.values(dataset.gpuFilter.filterValueUpdateTriggers);
611
+
612
+ // Charts pass extra field names so a cross-filter does not hide its own bins.
613
+ // Histogram plots never pass this list and keep the original dataId pairing.
614
+ if (skipFieldNames !== null && skipFieldNames !== void 0 && skipFieldNames.length) {
615
+ var skipNames = new Set(skipFieldNames.filter(function (name) {
616
+ return Boolean(name);
617
+ }));
618
+ return gpuFilters.reduce(function (accu, item, idx) {
619
+ if (item && skipNames.has(item.name)) {
620
+ accu.push(idx);
621
+ }
622
+ return accu;
623
+ }, []);
624
+ }
625
+ if (!filter) {
626
+ return [];
627
+ }
628
+ var valueIndex = filter.dataId.findIndex(function (id) {
629
+ return id === dataset.id;
630
+ });
631
+ // Channels identify the plotted GPU filter precisely when another filter uses the same field.
632
+ if (filter.gpu && valueIndex >= 0) {
633
+ var _filter$gpuChannel, _filter$gpuEndChannel;
634
+ var assignedChannels = [(_filter$gpuChannel = filter.gpuChannel) === null || _filter$gpuChannel === void 0 ? void 0 : _filter$gpuChannel[valueIndex], (_filter$gpuEndChannel = filter.gpuEndChannel) === null || _filter$gpuEndChannel === void 0 ? void 0 : _filter$gpuEndChannel[valueIndex]].filter(Number.isFinite);
635
+ if (assignedChannels.length) {
636
+ return assignedChannels;
637
+ }
638
+ }
639
+ // CPU filters are already omitted from baseIndex, so every GPU channel remains applicable.
640
+ if (filter.gpu === false && valueIndex >= 0) {
641
+ return [];
642
+ }
643
+ var filterColumn = filter.name[valueIndex];
644
+ var filterEndColumn = (_filter$endName = filter.endName) === null || _filter$endName === void 0 ? void 0 : _filter$endName[valueIndex];
645
+ return gpuFilters.reduce(function (accu, item, idx) {
646
+ if (item && (filterColumn === item.name || filterEndColumn === item.name)) {
647
+ accu.push(idx);
648
+ }
649
+ return accu;
650
+ }, []);
651
+ }
652
+ export function getFilterDataFunc(filterRange, getFilterValue, dataContainer, skips) {
653
+ return function (index) {
654
+ return getFilterValue({
655
+ index: index
656
+ }).every(function (val, i) {
657
+ return skips.includes(i) || val >= filterRange[i][0] && val <= filterRange[i][1];
658
+ });
659
+ };
660
+ }
661
+ export function validBin(b) {
662
+ return b.x0 !== undefined && b.x1 !== undefined;
663
+ }
664
+
665
+ /**
666
+ * Turn a histogram brush or slider position into one bin.
667
+ * Interval playback steps by bin, and the filter comparison is inclusive.
668
+ * Time bins preserve their millisecond offset. Numeric bins use the immediate
669
+ * representable predecessor of the next mark so their membership matches D3's
670
+ * half-open bins; only the final numeric bin includes its upper boundary.
671
+ */
672
+ export function intervalBinFromMarks(marks, value) {
673
+ var endOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
674
+ if (!marks.length || !Number.isFinite(value)) {
675
+ return [value, value];
676
+ }
677
+ if (marks.length === 1) {
678
+ return [marks[0], marks[0]];
679
+ }
680
+ var idx = bisectCenter(marks, value);
681
+ if (idx < 0) {
682
+ idx = 0;
683
+ }
684
+ // The last mark closes the final bin. Keep a drag there on that bin.
685
+ var lastBin = marks.length - 2;
686
+ if (idx > lastBin) {
687
+ idx = lastBin;
688
+ }
689
+ var start = marks[idx];
690
+ var end = marks[idx + 1];
691
+ if (endOffset === 0) {
692
+ return [start, idx === lastBin ? end : Math.max(start, nextDown(end))];
693
+ }
694
+ var offset = Number.isFinite(endOffset) && endOffset > 0 ? Math.min(endOffset, end - start) : 0;
695
+ return [start, Math.max(start, end - offset)];
696
+ }
697
+ export function snapToMarks(value, marks) {
698
+ // always use bin x0
699
+ if (!marks.length) {
700
+ // @ts-expect-error looking at the usage null return value isn't expected and requires extra handling in a lot of places
701
+ return null;
702
+ }
703
+ var i = bisectLeft(marks, value);
704
+ if (i === 0) {
705
+ return marks[i];
706
+ } else if (i === marks.length) {
707
+ return marks[i - 1];
708
+ }
709
+ var idx = marks[i] - value < value - marks[i - 1] ? i : i - 1;
710
+ return marks[idx];
711
+ }
712
+ export function normalizeValue(val, minValue, step, marks) {
713
+ if (marks && marks.length) {
714
+ return snapToMarks(val, marks);
715
+ }
716
+ return roundValToStep(minValue, step, val);
717
+ }
718
+ export function isPercentField(field) {
719
+ return field.metadata && field.metadata.numerator && field.metadata.denominator;
720
+ }
721
+ export function updateAggregationByField(field, aggregation) {
722
+ // shouldn't apply sum to percent fiele type
723
+ // default aggregation is average
724
+ return field && isPercentField(field) ? AGGREGATION_TYPES.average : aggregation || AGGREGATION_TYPES.average;
725
+ }
726
+ var getAgregationType = function getAgregationType(field, aggregation) {
727
+ if (isPercentField(field)) {
728
+ return 'mean_of_percent';
729
+ }
730
+ return aggregation;
731
+ };
732
+ var getAggregationAccessor = function getAggregationAccessor(field, fields) {
733
+ if (isPercentField(field)) {
734
+ var numeratorIdx = fields.findIndex(function (f) {
735
+ return f.name === field.metadata.numerator;
736
+ });
737
+ var denominatorIdx = fields.findIndex(function (f) {
738
+ return f.name === field.metadata.denominator;
739
+ });
740
+ return {
741
+ getNumerator: function getNumerator(i) {
742
+ return fields[numeratorIdx].valueAccessor({
743
+ index: i
744
+ });
745
+ },
746
+ getDenominator: function getDenominator(i) {
747
+ return fields[denominatorIdx].valueAccessor({
748
+ index: i
749
+ });
750
+ }
751
+ };
752
+ }
753
+ return function (i) {
754
+ return field.valueAccessor({
755
+ index: i
756
+ });
757
+ };
758
+ };
759
+ export var getValueAggrFunc = function getValueAggrFunc(field, aggregation, dataset) {
760
+ var fields = dataset.fields;
761
+
762
+ // The passed-in field might not have all the fields set (e.g. valueAccessor)
763
+ var datasetField = fields.find(function (f) {
764
+ return field && (f.name === field || f.name === field.name);
765
+ });
766
+ return datasetField && aggregation ? function (bin) {
767
+ return aggregate(bin.indexes, getAgregationType(datasetField, aggregation),
768
+ // @ts-expect-error can return {getNumerator, getDenominator}
769
+ getAggregationAccessor(datasetField, fields));
770
+ } : function (bin) {
771
+ return bin.count;
772
+ };
773
+ };
774
+ export var getAggregationOptiosnBasedOnField = function getAggregationOptiosnBasedOnField(field) {
775
+ if (isPercentField(field)) {
776
+ // don't show sum
777
+ return TIME_AGGREGATION.filter(function (_ref) {
778
+ var id = _ref.id;
779
+ return id !== AGGREGATION_TYPES.sum;
780
+ });
781
+ }
782
+ return TIME_AGGREGATION;
783
+ };
784
+ function getDelta(bins, y, _interval) {
785
+ // if (WOW[interval]) return getWow(bins, y, interval);
786
+ var lastBin = bins[bins.length - 1];
787
+ return {
788
+ delta: 'last',
789
+ pct: lastBin ? getPctChange(y, lastBin.y) : null
790
+ };
791
+ }
792
+ export function getPctChange(y, y0) {
793
+ if (Number.isFinite(y) && Number.isFinite(y0) && y0 !== 0) {
794
+ return (y - y0) / y0;
795
+ }
796
+ return null;
797
+ }
798
+ export var PLOT_GROUP_OTHERS_NAME = 'Others';
799
+ export var PLOT_NUM_GROUPS_ALL = 'ALL';
800
+ export var DEFAULT_PLOT_NUM_GROUPS = 10;
801
+ /** Qualitative palettes stop at 20. All uses this cap instead of one series per value. */
802
+ export var MAX_PLOT_NUM_GROUPS = 20;
803
+ export var PLOT_NUM_GROUPS_OPTIONS = [1, 3, 5, 7, 10, MAX_PLOT_NUM_GROUPS];
804
+ var DEFAULT_PLOT_GROUP_PALETTE = 'Uber Viz Qualitative';
805
+ var FALLBACK_SERIES_COLORS = ['#12939A', '#DDB27C', '#88572C', '#FF991F', '#F15C17', '#223F9A'];
806
+ export function plotGroupColorSteps(numGroups) {
807
+ if (numGroups === PLOT_NUM_GROUPS_ALL || typeof numGroups !== 'number' || numGroups < 1) {
808
+ return MAX_PLOT_NUM_GROUPS;
809
+ }
810
+ return Math.max(2, Math.min(numGroups, MAX_PLOT_NUM_GROUPS));
811
+ }
812
+ export function defaultPlotGroupColorRange(numGroups) {
813
+ var steps = plotGroupColorSteps(numGroups);
814
+ var palette = KEPLER_COLOR_PALETTES.find(function (item) {
815
+ return item.name === DEFAULT_PLOT_GROUP_PALETTE;
816
+ });
817
+ if (!palette) {
818
+ return {
819
+ name: DEFAULT_PLOT_GROUP_PALETTE,
820
+ type: 'qualitative',
821
+ category: 'Uber',
822
+ colors: FALLBACK_SERIES_COLORS
823
+ };
824
+ }
825
+ return colorPaletteToColorRange(palette, {
826
+ reversed: false,
827
+ steps: steps
828
+ });
829
+ }
830
+ function defaultPlotGroupColorUI(numGroups, colorRange) {
831
+ return _objectSpread(_objectSpread({}, DEFAULT_COLOR_UI), {}, {
832
+ colorRangeConfig: _objectSpread(_objectSpread({}, DEFAULT_COLOR_UI.colorRangeConfig), {}, {
833
+ type: 'qualitative',
834
+ steps: plotGroupColorSteps(numGroups)
835
+ }),
836
+ customPalette: _objectSpread(_objectSpread({}, DEFAULT_CUSTOM_PALETTE), {}, {
837
+ colors: colorRange.colors || []
838
+ })
839
+ });
840
+ }
841
+ function mergeGroupColorUI(prev, next, numGroups, colorRange) {
842
+ var base = prev !== null && prev !== void 0 ? prev : defaultPlotGroupColorUI(numGroups, colorRange);
843
+ if (!next) {
844
+ return base;
845
+ }
846
+ return _objectSpread(_objectSpread(_objectSpread({}, base), next), {}, {
847
+ colorRangeConfig: _objectSpread(_objectSpread({}, base.colorRangeConfig), next.colorRangeConfig || {}),
848
+ customPalette: next.customPalette ? _objectSpread(_objectSpread({}, base.customPalette), next.customPalette) : base.customPalette
849
+ });
850
+ }
851
+
852
+ /**
853
+ * Merge a partial timeline group-by onto the previous one.
854
+ * `null` clears grouping. Missing fields keep the previous value, then defaults.
855
+ */
856
+ export function mergePlotGroupBy(prev, next) {
857
+ var _ref2, _source$numGroups, _ref3, _source$colorRange;
858
+ if (next === null) {
859
+ return null;
860
+ }
861
+ if (!next && !prev) {
862
+ return null;
863
+ }
864
+ var source = next || {};
865
+ var numGroups = (_ref2 = (_source$numGroups = source.numGroups) !== null && _source$numGroups !== void 0 ? _source$numGroups : prev === null || prev === void 0 ? void 0 : prev.numGroups) !== null && _ref2 !== void 0 ? _ref2 : DEFAULT_PLOT_NUM_GROUPS;
866
+ var colorRange = (_ref3 = (_source$colorRange = source.colorRange) !== null && _source$colorRange !== void 0 ? _source$colorRange : prev === null || prev === void 0 ? void 0 : prev.colorRange) !== null && _ref3 !== void 0 ? _ref3 : defaultPlotGroupColorRange(numGroups);
867
+ return {
868
+ fieldName: source.fieldName !== undefined ? source.fieldName : prev === null || prev === void 0 ? void 0 : prev.fieldName,
869
+ numGroups: numGroups,
870
+ groupOthers: Boolean(source.groupOthers !== undefined ? source.groupOthers : prev === null || prev === void 0 ? void 0 : prev.groupOthers),
871
+ colorRange: colorRange,
872
+ colorUI: mergeGroupColorUI(prev === null || prev === void 0 ? void 0 : prev.colorUI, source.colorUI, numGroups, colorRange)
873
+ };
874
+ }
875
+ function groupByCacheValue(plotType) {
876
+ var _groupBy$numGroups, _groupBy$colorRange$c, _groupBy$colorRange, _groupBy$colorRange$c2, _groupBy$colorRange2;
877
+ var groupBy = plotType === null || plotType === void 0 ? void 0 : plotType.groupBy;
878
+ if (!(groupBy !== null && groupBy !== void 0 && groupBy.fieldName)) {
879
+ return null;
880
+ }
881
+ return {
882
+ fieldName: groupBy.fieldName,
883
+ numGroups: (_groupBy$numGroups = groupBy.numGroups) !== null && _groupBy$numGroups !== void 0 ? _groupBy$numGroups : DEFAULT_PLOT_NUM_GROUPS,
884
+ groupOthers: Boolean(groupBy.groupOthers),
885
+ colors: (_groupBy$colorRange$c = (_groupBy$colorRange = groupBy.colorRange) === null || _groupBy$colorRange === void 0 ? void 0 : _groupBy$colorRange.colors) !== null && _groupBy$colorRange$c !== void 0 ? _groupBy$colorRange$c : null,
886
+ colorMap: (_groupBy$colorRange$c2 = (_groupBy$colorRange2 = groupBy.colorRange) === null || _groupBy$colorRange2 === void 0 ? void 0 : _groupBy$colorRange2.colorMap) !== null && _groupBy$colorRange$c2 !== void 0 ? _groupBy$colorRange$c2 : null
887
+ };
888
+ }
889
+ function toGroupKey(value) {
890
+ if (value === null || value === undefined || value === '') {
891
+ return null;
892
+ }
893
+ return String(value);
894
+ }
895
+ function mappedSeriesColor(colorRange, key) {
896
+ var colorMap = colorRange === null || colorRange === void 0 ? void 0 : colorRange.colorMap;
897
+ if (!Array.isArray(colorMap)) {
898
+ return null;
899
+ }
900
+ var _iterator3 = _createForOfIteratorHelper(colorMap),
901
+ _step3;
902
+ try {
903
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
904
+ var entry = _step3.value;
905
+ var domain = entry === null || entry === void 0 ? void 0 : entry[0];
906
+ var color = entry === null || entry === void 0 ? void 0 : entry[1];
907
+ if (!color) {
908
+ continue;
909
+ }
910
+ if (Array.isArray(domain)) {
911
+ if (domain.map(function (item) {
912
+ return String(item);
913
+ }).includes(key)) {
914
+ return color;
915
+ }
916
+ } else if (domain !== null && domain !== undefined && String(domain) === key) {
917
+ return color;
918
+ }
919
+ }
920
+ } catch (err) {
921
+ _iterator3.e(err);
922
+ } finally {
923
+ _iterator3.f();
924
+ }
925
+ return null;
926
+ }
927
+ function seriesColor(colorRange, key, index) {
928
+ var mapped = mappedSeriesColor(colorRange, key);
929
+ if (mapped) {
930
+ return mapped;
931
+ }
932
+ var colors = colorRange === null || colorRange === void 0 ? void 0 : colorRange.colors;
933
+ if (colors !== null && colors !== void 0 && colors.length) {
934
+ return colors[index % colors.length];
935
+ }
936
+ return FALLBACK_SERIES_COLORS[index % FALLBACK_SERIES_COLORS.length];
937
+ }
938
+ var OTHERS_SERIES_COLOR = '#A0A7B4';
939
+ function defaultQualitativeColors() {
940
+ var palette = KEPLER_COLOR_PALETTES.find(function (item) {
941
+ return item.name === DEFAULT_PLOT_GROUP_PALETTE;
942
+ });
943
+ if ((palette === null || palette === void 0 ? void 0 : palette.type) === 'qualitative') {
944
+ return palette.colors(palette.maxStep);
945
+ }
946
+ return FALLBACK_SERIES_COLORS;
947
+ }
948
+
949
+ /** Others must not wrap onto a color already used by a kept group. */
950
+ function othersSeriesColor(colorRange, used) {
951
+ var _colorRange$colors, _candidates$find;
952
+ var mapped = mappedSeriesColor(colorRange, PLOT_GROUP_OTHERS_NAME);
953
+ if (mapped) {
954
+ return mapped;
955
+ }
956
+ var usedSet = new Set(used.map(function (color) {
957
+ return color.toLowerCase();
958
+ }));
959
+ var candidates = [].concat(_toConsumableArray((_colorRange$colors = colorRange === null || colorRange === void 0 ? void 0 : colorRange.colors) !== null && _colorRange$colors !== void 0 ? _colorRange$colors : []), _toConsumableArray(defaultQualitativeColors()), FALLBACK_SERIES_COLORS, [OTHERS_SERIES_COLOR]);
960
+ return (_candidates$find = candidates.find(function (color) {
961
+ return !usedSet.has(color.toLowerCase());
962
+ })) !== null && _candidates$find !== void 0 ? _candidates$find : OTHERS_SERIES_COLOR;
963
+ }
964
+ function groupValueAccessor(dataset, fieldName) {
965
+ var _dataset$fields;
966
+ var field = dataset === null || dataset === void 0 || (_dataset$fields = dataset.fields) === null || _dataset$fields === void 0 ? void 0 : _dataset$fields.find(function (item) {
967
+ return item.name === fieldName;
968
+ });
969
+ if (!(field !== null && field !== void 0 && field.valueAccessor)) {
970
+ return null;
971
+ }
972
+ return function (index) {
973
+ return field.valueAccessor({
974
+ index: index
975
+ });
976
+ };
977
+ }
978
+ function groupLimit(numGroups) {
979
+ if (numGroups === PLOT_NUM_GROUPS_ALL) {
980
+ return MAX_PLOT_NUM_GROUPS;
981
+ }
982
+ if (typeof numGroups !== 'number' || !(numGroups > 0)) {
983
+ return DEFAULT_PLOT_NUM_GROUPS;
984
+ }
985
+ return Math.min(numGroups, MAX_PLOT_NUM_GROUPS);
986
+ }
987
+
988
+ /**
989
+ * Split time bins into one line per group-by value.
990
+ * Groups keep first-seen order, then the list is capped at numGroups.
991
+ * Remaining values fold into an Others series when groupOthers is set.
992
+ */
993
+ function buildGroupedLineSeries(_ref4) {
994
+ var _plotType$groupBy;
995
+ var bins = _ref4.bins,
996
+ dataset = _ref4.dataset,
997
+ plotType = _ref4.plotType,
998
+ getYValue = _ref4.getYValue,
999
+ interval = _ref4.interval;
1000
+ var cache = groupByCacheValue(plotType);
1001
+ if (!cache) {
1002
+ return null;
1003
+ }
1004
+ var getGroup = groupValueAccessor(dataset, cache.fieldName);
1005
+ if (!getGroup) {
1006
+ return null;
1007
+ }
1008
+ var order = [];
1009
+ var seen = new Set();
1010
+ var _iterator4 = _createForOfIteratorHelper(bins),
1011
+ _step4;
1012
+ try {
1013
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1014
+ var bin = _step4.value;
1015
+ var _iterator6 = _createForOfIteratorHelper(bin.indexes || []),
1016
+ _step6;
1017
+ try {
1018
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1019
+ var idx = _step6.value;
1020
+ var key = toGroupKey(getGroup(idx));
1021
+ if (key === null || seen.has(key)) {
1022
+ continue;
1023
+ }
1024
+ seen.add(key);
1025
+ order.push(key);
1026
+ }
1027
+ } catch (err) {
1028
+ _iterator6.e(err);
1029
+ } finally {
1030
+ _iterator6.f();
1031
+ }
1032
+ }
1033
+ } catch (err) {
1034
+ _iterator4.e(err);
1035
+ } finally {
1036
+ _iterator4.f();
1037
+ }
1038
+ if (!order.length) {
1039
+ return null;
1040
+ }
1041
+ var limit = groupLimit(cache.numGroups);
1042
+ var keep = order.slice(0, limit);
1043
+ var rest = order.slice(keep.length);
1044
+ var includeOthers = Boolean(cache.groupOthers) && rest.length > 0;
1045
+ var colorRange = plotType === null || plotType === void 0 || (_plotType$groupBy = plotType.groupBy) === null || _plotType$groupBy === void 0 ? void 0 : _plotType$groupBy.colorRange;
1046
+ var groups = keep.map(function (key, index) {
1047
+ return {
1048
+ name: key,
1049
+ keys: new Set([key]),
1050
+ color: seriesColor(colorRange, key, index)
1051
+ };
1052
+ });
1053
+ if (includeOthers) {
1054
+ groups.push({
1055
+ name: PLOT_GROUP_OTHERS_NAME,
1056
+ keys: new Set(rest),
1057
+ color: othersSeriesColor(colorRange, groups.map(function (group) {
1058
+ return group.color;
1059
+ }))
1060
+ });
1061
+ }
1062
+ var keyToGroup = new Map();
1063
+ groups.forEach(function (group, index) {
1064
+ group.keys.forEach(function (key) {
1065
+ return keyToGroup.set(key, index);
1066
+ });
1067
+ });
1068
+ var lines = [];
1069
+ var colors = [];
1070
+ var names = [];
1071
+ var points = [];
1072
+ groups.forEach(function (group, groupIndex) {
1073
+ var seriesPoints = [];
1074
+ bins.forEach(function (bin) {
1075
+ var indexes = [];
1076
+ var _iterator5 = _createForOfIteratorHelper(bin.indexes || []),
1077
+ _step5;
1078
+ try {
1079
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
1080
+ var idx = _step5.value;
1081
+ var key = toGroupKey(getGroup(idx));
1082
+ if (key !== null && keyToGroup.get(key) === groupIndex) {
1083
+ indexes.push(idx);
1084
+ }
1085
+ }
1086
+ } catch (err) {
1087
+ _iterator5.e(err);
1088
+ } finally {
1089
+ _iterator5.f();
1090
+ }
1091
+ var y = indexes.length ? getYValue(_objectSpread(_objectSpread({}, bin), {}, {
1092
+ indexes: indexes,
1093
+ count: indexes.length
1094
+ })) : undefined;
1095
+ var delta = getDelta(seriesPoints, y, interval);
1096
+ var point = _objectSpread({
1097
+ x: bin.x0,
1098
+ y: y
1099
+ }, delta);
1100
+ seriesPoints.push(point);
1101
+ points.push(point);
1102
+ });
1103
+ var split = splitSeries(seriesPoints);
1104
+ split.lines.forEach(function (line) {
1105
+ lines.push(line);
1106
+ colors.push(group.color);
1107
+ names.push(group.name);
1108
+ });
1109
+ });
1110
+ return {
1111
+ series: {
1112
+ lines: lines,
1113
+ markers: [],
1114
+ colors: colors,
1115
+ names: names
1116
+ },
1117
+ points: points
1118
+ };
1119
+ }
1120
+ export function lineChartSeriesLegend(lineChart) {
1121
+ var series = lineChart === null || lineChart === void 0 ? void 0 : lineChart.series;
1122
+ if (!series || Array.isArray(series) || !series.names || !series.colors) {
1123
+ return [];
1124
+ }
1125
+ var seen = new Map();
1126
+ series.names.forEach(function (name, index) {
1127
+ if (name && !seen.has(name)) {
1128
+ var _series$colors;
1129
+ seen.set(name, ((_series$colors = series.colors) === null || _series$colors === void 0 ? void 0 : _series$colors[index]) || FALLBACK_SERIES_COLORS[0]);
1130
+ }
1131
+ });
1132
+ return Array.from(seen, function (_ref5) {
1133
+ var _ref6 = _slicedToArray(_ref5, 2),
1134
+ name = _ref6[0],
1135
+ color = _ref6[1];
1136
+ return {
1137
+ name: name,
1138
+ color: color
1139
+ };
1140
+ });
1141
+ }
1142
+
1143
+ /**
1144
+ *
1145
+ * @param datasets
1146
+ * @param filter
1147
+ */
1148
+ export function getLineChart(datasets, filter) {
1149
+ var _plotType$numericInte, _bins, _timeBins, _lineChart$groupBy;
1150
+ var dataId = filter.dataId,
1151
+ yAxis = filter.yAxis,
1152
+ plotType = filter.plotType,
1153
+ lineChart = filter.lineChart;
1154
+ var interval = plotType.interval;
1155
+ var aggregation = plotType.aggregation || AGGREGATION_TYPES.average;
1156
+ var seriesDataId = dataId[0];
1157
+ var isNumericFilter = filter.type === FILTER_TYPES.range;
1158
+ var binning = isNumericFilter ? (_plotType$numericInte = plotType.numericInterval) !== null && _plotType$numericInte !== void 0 ? _plotType$numericInte : null : interval;
1159
+ var bins = isNumericFilter ? (_bins = filter.bins) === null || _bins === void 0 ? void 0 : _bins[seriesDataId] : (_timeBins = filter.timeBins) === null || _timeBins === void 0 || (_timeBins = _timeBins[seriesDataId]) === null || _timeBins === void 0 ? void 0 : _timeBins[interval];
1160
+ var groupBy = groupByCacheValue(plotType);
1161
+ if (lineChart && lineChart.aggregation === aggregation && lineChart.interval === binning && lineChart.yAxis === (yAxis === null || yAxis === void 0 ? void 0 : yAxis.name) && isEqual((_lineChart$groupBy = lineChart.groupBy) !== null && _lineChart$groupBy !== void 0 ? _lineChart$groupBy : null, groupBy) &&
1162
+ // we need to make sure we validate bins because of cross filter data changes
1163
+ isEqual(bins, lineChart === null || lineChart === void 0 ? void 0 : lineChart.bins)) {
1164
+ // don't update lineChart if plotType hasn't change
1165
+ return lineChart;
1166
+ }
1167
+ var dataset = datasets[seriesDataId];
1168
+ var getYValue = getValueAggrFunc(yAxis, aggregation, dataset);
1169
+ var grouped = groupBy && bins !== null && bins !== void 0 && bins.length ? buildGroupedLineSeries({
1170
+ bins: bins,
1171
+ dataset: dataset,
1172
+ plotType: plotType,
1173
+ getYValue: getYValue,
1174
+ interval: binning
1175
+ }) : null;
1176
+ var init = [];
1177
+ var series = grouped ? grouped.points : (bins || []).reduce(function (accu, bin) {
1178
+ var y = getYValue(bin);
1179
+ var delta = getDelta(accu, y, binning);
1180
+ accu.push(_objectSpread({
1181
+ x: bin.x0,
1182
+ y: y
1183
+ }, delta));
1184
+ return accu;
1185
+ }, init);
1186
+ var yDomain = extent(series, function (d) {
1187
+ return d.y;
1188
+ });
1189
+ var xDomain = bins !== null && bins !== void 0 && bins.length ? [bins[0].x0, bins[bins.length - 1].x1] : [];
1190
+
1191
+ // treat missing data as another series
1192
+ var split = grouped ? grouped.series : splitSeries(series);
1193
+ var aggrName = AGGREGATION_NAME[aggregation];
1194
+ return _objectSpread({
1195
+ // @ts-ignore
1196
+ yDomain: yDomain,
1197
+ // @ts-ignore
1198
+ xDomain: xDomain,
1199
+ interval: binning,
1200
+ aggregation: aggregation,
1201
+ // @ts-ignore
1202
+ series: split,
1203
+ title: "".concat(aggrName, ' of ').concat(yAxis ? yAxis.name : 'Count'),
1204
+ fieldType: yAxis ? yAxis.type : 'integer',
1205
+ yAxis: yAxis ? yAxis.name : null,
1206
+ allTime: {
1207
+ title: isNumericFilter ? "All Range Average" : "All Time Average",
1208
+ value: aggregate(series, AGGREGATION_TYPES.average, function (d) {
1209
+ return d.y;
1210
+ })
1211
+ },
1212
+ bins: bins
1213
+ }, groupBy ? {
1214
+ groupBy: groupBy
1215
+ } : {});
1216
+ }
1217
+
1218
+ // split into multiple series when see missing data
1219
+ export function splitSeries(series) {
1220
+ var lines = [];
1221
+ var temp = [];
1222
+ for (var i = 0; i < series.length; i++) {
1223
+ var d = series[i];
1224
+ if (!notNullorUndefined(d.y) && temp.length) {
1225
+ // ends temp
1226
+ lines.push(temp);
1227
+ temp = [];
1228
+ } else if (notNullorUndefined(d.y)) {
1229
+ temp.push(d);
1230
+ }
1231
+ if (i === series.length - 1 && temp.length) {
1232
+ lines.push(temp);
1233
+ }
1234
+ }
1235
+ var markers = lines.length > 1 ? series.filter(function (d) {
1236
+ return notNullorUndefined(d.y);
1237
+ }) : [];
1238
+ return {
1239
+ lines: lines,
1240
+ markers: markers
1241
+ };
1242
+ }
1243
+ export function adjustValueToAnimationWindow(state, filter, plotBaseIndexByDataId) {
1244
+ var plotType = filter.plotType,
1245
+ _filter$value = _slicedToArray(filter.value, 2),
1246
+ value0 = _filter$value[0],
1247
+ value1 = _filter$value[1],
1248
+ animationWindow = filter.animationWindow;
1249
+ var isTimeFilter = filter.type === FILTER_TYPES.timeRange;
1250
+ var timePlotType = isTimeFilter ? normalizeTimePlotType(_objectSpread(_objectSpread({}, plotType), {}, {
1251
+ interval: plotType.interval || getInitialInterval(filter, state.datasets)
1252
+ }), filter.domain) : plotType;
1253
+ var interval = isTimeFilter ? timePlotType.interval : undefined;
1254
+ var bins = isTimeFilter ? getTimeBins(filter, state.datasets, interval, plotBaseIndexByDataId) : getRangeFilterBins(filter, state.datasets, BINS, plotBaseIndexByDataId);
1255
+ var firstBins = bins && Object.keys(bins).length ? Object.values(bins)[0] : null;
1256
+ var datasetBins = isTimeFilter ? firstBins === null || firstBins === void 0 ? void 0 : firstBins[interval] : firstBins;
1257
+ var thresholds = (datasetBins || []).map(function (b) {
1258
+ return b.x0;
1259
+ });
1260
+ var numericIntervalMarks = datasetBins !== null && datasetBins !== void 0 && datasetBins.length ? [].concat(_toConsumableArray(thresholds), [datasetBins[datasetBins.length - 1].x1]) : thresholds;
1261
+ var val0 = value0;
1262
+ var val1 = value1;
1263
+ var idx;
1264
+ if (animationWindow === ANIMATION_WINDOW.interval) {
1265
+ val0 = snapToMarks(value1, thresholds);
1266
+ idx = thresholds.indexOf(val0);
1267
+ if (isTimeFilter) {
1268
+ var _datasetBins$idx;
1269
+ // Time histograms discard empty bins. Use the selected cached bin's
1270
+ // actual end instead of the next non-empty bin's start so sparse
1271
+ // calendar intervals do not absorb the empty gap between them.
1272
+ var binEnd = idx > -1 ? datasetBins === null || datasetBins === void 0 || (_datasetBins$idx = datasetBins[idx]) === null || _datasetBins$idx === void 0 ? void 0 : _datasetBins$idx.x1 : NaN;
1273
+ val1 = Number.isFinite(binEnd) && binEnd > val0 ? Math.max(val0, binEnd - Math.min(1, binEnd - val0)) : binEnd;
1274
+ } else {
1275
+ var _intervalBinFromMarks = intervalBinFromMarks(numericIntervalMarks, val0, 0);
1276
+ var _intervalBinFromMarks2 = _slicedToArray(_intervalBinFromMarks, 2);
1277
+ val1 = _intervalBinFromMarks2[1];
1278
+ }
1279
+ } else {
1280
+ // fit current value to window
1281
+ val0 = snapToMarks(value0, thresholds);
1282
+ val1 = snapToMarks(value1, thresholds);
1283
+ if (val0 === val1) {
1284
+ idx = thresholds.indexOf(val0);
1285
+ if (idx === thresholds.length - 1) {
1286
+ val0 = thresholds[idx - 1];
1287
+ } else {
1288
+ val1 = thresholds[idx + 1];
1289
+ }
1290
+ }
1291
+ }
1292
+ return _objectSpread(_objectSpread(_objectSpread({}, filter), isTimeFilter ? {
1293
+ plotType: timePlotType,
1294
+ timeBins: bins
1295
+ } : {
1296
+ bins: bins
1297
+ }), {}, {
1298
+ value: [val0, val1]
1299
+ });
1300
+ }
1301
+
1302
+ /**
1303
+ * Create or update colors for a filter plot
1304
+ * @param filter
1305
+ * @param datasets
1306
+ * @param oldColorsByDataId
1307
+ */
1308
+ function getFilterPlotColorsByDataId(filter, datasets, oldColorsByDataId) {
1309
+ var colorsByDataId = oldColorsByDataId || {};
1310
+ var _iterator7 = _createForOfIteratorHelper(filter.dataId),
1311
+ _step7;
1312
+ try {
1313
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
1314
+ var dataId = _step7.value;
1315
+ if (!colorsByDataId[dataId] && datasets[dataId]) {
1316
+ colorsByDataId = _objectSpread(_objectSpread({}, colorsByDataId), {}, _defineProperty({}, dataId, rgbToHex(datasets[dataId].color)));
1317
+ }
1318
+ }
1319
+ } catch (err) {
1320
+ _iterator7.e(err);
1321
+ } finally {
1322
+ _iterator7.f();
1323
+ }
1324
+ return colorsByDataId;
1325
+ }
1326
+
1327
+ /**
1328
+ *
1329
+ * @param filter
1330
+ * @param plotType
1331
+ * @param datasets
1332
+ * @param dataId
1333
+ */
1334
+ export function updateTimeFilterPlotType(filter, plotType, datasets, _dataId, plotBaseIndexByDataId) {
1335
+ var nextFilter = filter;
1336
+ var nextPlotType = plotType;
1337
+ if (_typeof(nextPlotType) !== 'object' || !nextPlotType.aggregation || !nextPlotType.interval) {
1338
+ nextPlotType = getDefaultPlotType(filter, datasets);
1339
+ }
1340
+ var normalizedPlotType = normalizeTimePlotType(nextPlotType, filter.domain);
1341
+ if (normalizedPlotType.interval !== nextPlotType.interval) {
1342
+ nextFilter = _objectSpread(_objectSpread({}, filter), {}, {
1343
+ timeBins: undefined,
1344
+ lineChart: undefined
1345
+ });
1346
+ }
1347
+ nextPlotType = normalizedPlotType;
1348
+ if (filter.dataId.length > 1) {
1349
+ nextPlotType = _objectSpread(_objectSpread({}, nextPlotType), {}, {
1350
+ colorsByDataId: getFilterPlotColorsByDataId(filter, datasets, nextPlotType.colorsByDataId)
1351
+ });
1352
+ }
1353
+ nextFilter = _objectSpread(_objectSpread({}, nextFilter), {}, {
1354
+ plotType: nextPlotType
1355
+ });
1356
+ var bins = getTimeBins(nextFilter, datasets, nextPlotType.interval, plotBaseIndexByDataId);
1357
+ nextFilter = _objectSpread(_objectSpread({}, nextFilter), {}, {
1358
+ timeBins: bins
1359
+ });
1360
+ if (plotType.type === PLOT_TYPES.histogram) {
1361
+ // Histogram is calculated and memoized in the chart itself
1362
+ } else if (plotType.type === PLOT_TYPES.lineChart) {
1363
+ // we should be able to move this into its own component so react will do the shallow comparison for us.
1364
+ nextFilter = _objectSpread(_objectSpread({}, nextFilter), {}, {
1365
+ lineChart: getLineChart(datasets, nextFilter)
1366
+ });
1367
+ }
1368
+ return nextFilter;
1369
+ }
1370
+ export function getRangeFilterBins(filter, datasets, numBins, plotBaseIndexByDataId) {
1371
+ var domain = filter.domain;
1372
+ if (!filter.dataId) return null;
1373
+ return filter.dataId.reduce(function (acc, dataId, datasetIdx) {
1374
+ var _filter$bins;
1375
+ if ((_filter$bins = filter.bins) !== null && _filter$bins !== void 0 && _filter$bins[dataId]) {
1376
+ // don't recalculate bins
1377
+ acc[dataId] = filter.bins[dataId];
1378
+ return acc;
1379
+ }
1380
+ var fieldName = filter.name[datasetIdx];
1381
+ if (dataId && fieldName) {
1382
+ var dataset = datasets[dataId];
1383
+ var field = dataset === null || dataset === void 0 ? void 0 : dataset.getColumnField(fieldName);
1384
+ if (dataset && field) {
1385
+ var _filter$plotType4;
1386
+ var indexes = runGpuFilterForPlot(dataset, filter, undefined, plotBaseIndexByDataId === null || plotBaseIndexByDataId === void 0 ? void 0 : plotBaseIndexByDataId[dataId]);
1387
+ var valueAccessor = function valueAccessor(index) {
1388
+ return field.valueAccessor({
1389
+ index: index
1390
+ });
1391
+ };
1392
+ var numericInterval = (_filter$plotType4 = filter.plotType) === null || _filter$plotType4 === void 0 ? void 0 : _filter$plotType4.numericInterval;
1393
+ acc[dataId] = Number.isFinite(numericInterval) && numericInterval > 0 ? histogramFromThreshold(getNumericBinThresholds(domain, numericInterval, numBins), indexes, valueAccessor, false) : histogramFromDomain(domain, indexes, numBins, valueAccessor);
1394
+ }
1395
+ }
1396
+ return acc;
1397
+ }, {});
1398
+ }
1399
+ export function updateRangeFilterPlotType(filter, plotType, datasets, _dataId, plotBaseIndexByDataId) {
1400
+ // if (dataId) {
1401
+ // // clear bins
1402
+ // nextFilter = {
1403
+ // ...nextFilter,
1404
+ // bins: {
1405
+ // ...nextFilter.bins,
1406
+ // [dataId]: null
1407
+ // }
1408
+ // };
1409
+ // }
1410
+
1411
+ var configuredNumericInterval = plotType === null || plotType === void 0 ? void 0 : plotType.numericInterval;
1412
+ var numericInterval = normalizeNumericInterval(filter.domain, configuredNumericInterval);
1413
+ var shouldUseAutomaticBins = configuredNumericInterval !== undefined && numericInterval === undefined;
1414
+ var nextPlotType = plotType;
1415
+ if (shouldUseAutomaticBins) {
1416
+ var _ref7 = nextPlotType || {},
1417
+ _numericInterval = _ref7.numericInterval,
1418
+ automaticPlotType = _objectWithoutProperties(_ref7, _excluded);
1419
+ nextPlotType = automaticPlotType;
1420
+ }
1421
+ if (filter.dataId.length > 1) {
1422
+ nextPlotType = _objectSpread(_objectSpread({}, nextPlotType), {}, {
1423
+ colorsByDataId: getFilterPlotColorsByDataId(filter, datasets, nextPlotType.colorsByDataId)
1424
+ });
1425
+ }
1426
+ var nextFilter = _objectSpread(_objectSpread(_objectSpread({}, filter), shouldUseAutomaticBins ? {
1427
+ bins: undefined,
1428
+ lineChart: undefined
1429
+ } : {}), {}, {
1430
+ plotType: nextPlotType
1431
+ });
1432
+ var updatedFilter = _objectSpread(_objectSpread({}, nextFilter), {}, {
1433
+ bins: getRangeFilterBins(nextFilter, datasets, BINS, plotBaseIndexByDataId)
1434
+ });
1435
+ if (nextPlotType.type === PLOT_TYPES.lineChart) {
1436
+ updatedFilter = _objectSpread(_objectSpread({}, updatedFilter), {}, {
1437
+ lineChart: getLineChart(datasets, updatedFilter)
1438
+ });
1439
+ }
1440
+ return updatedFilter;
1441
+ }
1442
+ export function getChartTitle(yAxis, plotType) {
1443
+ var yAxisName = yAxis === null || yAxis === void 0 ? void 0 : yAxis.displayName;
1444
+ var aggregation = plotType.aggregation;
1445
+ if (yAxisName) {
1446
+ return capitalizeFirstLetter("".concat(aggregation, " ").concat(yAxisName, " over Time"));
1447
+ }
1448
+ return "Count of Rows over Time";
1449
+ }
1450
+ export function getDefaultPlotType(filter, datasets) {
1451
+ var interval = getInitialInterval(filter, datasets);
1452
+ var defaultTimeFormat = getDefaultTimeFormat(interval);
1453
+ return {
1454
+ interval: interval,
1455
+ defaultTimeFormat: defaultTimeFormat,
1456
+ type: PLOT_TYPES.histogram,
1457
+ aggregation: AGGREGATION_TYPES.average
1458
+ };
1459
+ }
1460
+ //# sourceMappingURL=plot.js.map