@redsift/dashboard 11.5.0 → 11.6.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,17 +1,11 @@
1
- import { ColorTheme, useColor, scheme } from '@redsift/charts';
2
1
  export { ChartSize, ColorTheme } from '@redsift/charts';
3
- import React, { forwardRef, useRef, useState, useReducer, useMemo, useContext, useEffect, isValidElement } from 'react';
4
- import { mdiRefresh } from '@redsift/icons';
5
- import styled, { css } from 'styled-components';
6
- import { Button, Spinner, RedsiftColorBlueD1, Flexbox, useId, useTheme, isComponent } from '@redsift/design-system';
7
- import classNames from 'classnames';
8
- import { useGridApiRef, gridFilteredSortedRowEntriesSelector, gridVisibleColumnDefinitionsSelector, gridColumnsTotalWidthSelector } from '@mui/x-data-grid-pro';
9
- import crossfilter from 'crossfilter2';
10
- import { saveAs } from 'file-saver';
11
- import { Font, StyleSheet, Document, Page, View, Image, Text, pdf } from '@react-pdf/renderer';
12
- import domToImage from 'dom-to-image';
13
- import { config, barChart, filters, redrawAll, filterAll } from 'dc';
14
- import { utcParse, timeFormat, isoParse, timeMonth, scaleTime, timeMonths, timeYear, timeYears, timeWeek, timeWeeks, timeDay, timeDays, timeHour, timeHours } from 'd3';
2
+ export { C as ChartEmptyState } from './_internal/ChartEmptyState2.js';
3
+ export { D as Dashboard, a as DashboardReducer } from './_internal/Dashboard2.js';
4
+ export { D as DashboardContext, i as initialState } from './_internal/context.js';
5
+ export { D as DashboardReducerActionType } from './_internal/types.js';
6
+ export { P as PdfExportButton } from './_internal/PdfExportButton2.js';
7
+ export { T as TimeSeriesBarChart, a as TimeSeriesBarChartSize, b as TimeSeriesBarChartTheme } from './_internal/TimeSeriesBarChart2.js';
8
+ export { W as WithFilters } from './_internal/WithFilters2.js';
15
9
 
16
10
  const groupReduceCount = d => d.group().reduceCount();
17
11
  const COUNT = groupReduceCount;
@@ -19,1940 +13,5 @@ const COUNT = groupReduceCount;
19
13
  const groupReduceSum = field => d => d.group().reduceSum(d => d[field]);
20
14
  const SUM = groupReduceSum;
21
15
 
22
- /**
23
- * Component style.
24
- */
25
- const StyledChartEmptyState = styled.div`
26
- display: flex;
27
- flex-direction: column;
28
- justify-content: center;
29
- align-items: center;
30
- margin-top: 16px;
31
-
32
- .redsift-chart-empty-state__title {
33
- font-family: var(--redsift-typography-h4-font-family);
34
- font-size: var(--redsift-typography-h4-font-size);
35
- font-weight: var(--redsift-typography-h4-font-weight);
36
- line-height: var(--redsift-typography-h4-line-height);
37
- }
38
-
39
- .redsift-chart-empty-state__subtitle {
40
- font-family: var(--redsift-typography-body-font-family);
41
- font-size: var(--redsift-typography-body-font-size);
42
- font-weight: var(--redsift-typography-body-font-weight);
43
- line-height: var(--redsift-typography-body-line-height);
44
- margin-top: 8px;
45
- text-align: center;
46
- }
47
- `;
48
- const StyledResetButton = styled(Button)`
49
- margin-top: 8px;
50
- `;
51
-
52
- const COMPONENT_NAME$3 = 'ChartEmptyState';
53
- const CLASSNAME$3 = 'redsift-chart-empty-state';
54
- const ChartEmptyState = /*#__PURE__*/forwardRef((props, ref) => {
55
- const {
56
- onReset,
57
- title = 'No Data Available',
58
- subtitle = 'Please check the applied filters',
59
- resetLabel = 'Reset all filters'
60
- } = props;
61
- return /*#__PURE__*/React.createElement(StyledChartEmptyState, {
62
- ref: ref,
63
- className: "redsift-chart-empty-state"
64
- }, /*#__PURE__*/React.createElement("div", {
65
- className: `${ChartEmptyState.className}__img`
66
- }, /*#__PURE__*/React.createElement("svg", {
67
- width: "86",
68
- height: "86",
69
- viewBox: "0 0 86 86",
70
- fill: "none",
71
- xmlns: "http://www.w3.org/2000/svg"
72
- }, /*#__PURE__*/React.createElement("path", {
73
- opacity: "0.2",
74
- d: "M43 86C66.7482 86 86 66.7482 86 43C86 19.2518 66.7482 0 43 0C19.2518 0 0 19.2518 0 43C0 66.7482 19.2518 86 43 86Z",
75
- fill: "#4285F4"
76
- }), /*#__PURE__*/React.createElement("path", {
77
- opacity: "0.4",
78
- d: "M13.4479 45.9299C13.4479 44.8254 14.3434 43.9299 15.4479 43.9299H29.3785C30.4831 43.9299 31.3785 44.8254 31.3785 45.9299V60.0675H13.4479V45.9299Z",
79
- fill: "#4285F4"
80
- }), /*#__PURE__*/React.createElement("path", {
81
- opacity: "0.4",
82
- d: "M34.0681 27.9993C34.0681 26.8948 34.9636 25.9993 36.0681 25.9993H49.9987C51.1033 25.9993 51.9987 26.8948 51.9987 27.9993V60.0675H34.0681V27.9993Z",
83
- fill: "#4285F4"
84
- }), /*#__PURE__*/React.createElement("path", {
85
- opacity: "0.4",
86
- d: "M54.6883 53.1022C54.6883 51.9976 55.5837 51.1022 56.6883 51.1022H70.6189C71.7235 51.1022 72.6189 51.9976 72.6189 53.1022V60.0675H54.6883V53.1022Z",
87
- fill: "#4285F4"
88
- }), /*#__PURE__*/React.createElement("line", {
89
- x1: "10.3618",
90
- y1: "60.464",
91
- x2: "75.705",
92
- y2: "60.464",
93
- stroke: "#305AA2",
94
- strokeLinecap: "round"
95
- }), /*#__PURE__*/React.createElement("path", {
96
- d: "M48.7345 25.9993H46.9414L51.9987 28.9192V27.8839L48.7345 25.9993Z",
97
- fill: "#4285F4"
98
- }), /*#__PURE__*/React.createElement("path", {
99
- d: "M41.5622 25.9993L51.9987 32.0249V30.9896L43.3553 25.9993H41.5622Z",
100
- fill: "#4285F4"
101
- }), /*#__PURE__*/React.createElement("path", {
102
- d: "M36.183 25.9993L51.9987 35.1305V34.0953L37.9761 25.9993H36.183Z",
103
- fill: "#4285F4"
104
- }), /*#__PURE__*/React.createElement("path", {
105
- d: "M34.0771 27.622C34.0681 27.6758 34.0681 27.7296 34.0681 27.7924V27.8839L51.9987 38.2362V37.201L34.281 26.9716C34.1776 27.171 34.097 27.3834 34.0771 27.622Z",
106
- fill: "#4285F4"
107
- }), /*#__PURE__*/React.createElement("path", {
108
- d: "M34.0681 30.9896L51.9987 41.3418V40.3066L34.0681 29.9544V30.9896Z",
109
- fill: "#4285F4"
110
- }), /*#__PURE__*/React.createElement("path", {
111
- d: "M34.0681 34.0953L51.9987 44.4475V43.4123L34.0681 33.06V34.0953Z",
112
- fill: "#4285F4"
113
- }), /*#__PURE__*/React.createElement("path", {
114
- d: "M34.0681 37.2009L51.9987 47.5531V46.518L34.0681 36.1657V37.2009Z",
115
- fill: "#4285F4"
116
- }), /*#__PURE__*/React.createElement("path", {
117
- d: "M34.0681 40.3066L51.9987 50.6588V49.6236L34.0681 39.2714V40.3066Z",
118
- fill: "#4285F4"
119
- }), /*#__PURE__*/React.createElement("path", {
120
- d: "M34.0681 43.4123L51.9987 53.7645V52.7293L34.0681 42.377V43.4123Z",
121
- fill: "#4285F4"
122
- }), /*#__PURE__*/React.createElement("path", {
123
- d: "M34.0681 46.518L51.9987 56.8702V55.835L34.0681 45.4827V46.518Z",
124
- fill: "#4285F4"
125
- }), /*#__PURE__*/React.createElement("path", {
126
- d: "M34.0681 49.6236L51.9987 59.9759V58.9407L34.0681 48.5884V49.6236Z",
127
- fill: "#4285F4"
128
- }), /*#__PURE__*/React.createElement("path", {
129
- d: "M34.0681 52.7293L46.7782 60.0675H48.5712L34.0681 51.6941V52.7293Z",
130
- fill: "#4285F4"
131
- }), /*#__PURE__*/React.createElement("path", {
132
- d: "M34.0681 55.835L41.399 60.0675H43.192L34.0681 54.7997V55.835Z",
133
- fill: "#4285F4"
134
- }), /*#__PURE__*/React.createElement("path", {
135
- d: "M34.0681 58.9406L36.0198 60.0675H37.8129L34.0681 57.9054V58.9406Z",
136
- fill: "#4285F4"
137
- }), /*#__PURE__*/React.createElement("circle", {
138
- opacity: "0.6",
139
- cx: "50.5506",
140
- cy: "29.9304",
141
- r: "10.1549",
142
- transform: "rotate(-45 50.5506 29.9304)",
143
- fill: "white",
144
- stroke: "#305AA2",
145
- strokeWidth: "3"
146
- }), /*#__PURE__*/React.createElement("circle", {
147
- cx: "50.5506",
148
- cy: "29.9304",
149
- r: "10.1549",
150
- transform: "rotate(-45 50.5506 29.9304)",
151
- stroke: "#305AA2",
152
- strokeWidth: "3"
153
- }), /*#__PURE__*/React.createElement("path", {
154
- d: "M59.2186 36.4771L58.1579 35.4164L56.0366 37.5377L57.0973 38.5984L59.2186 36.4771ZM65.9725 47.4736C66.5582 48.0594 67.508 48.0594 68.0938 47.4736C68.6796 46.8878 68.6796 45.938 68.0938 45.3522L65.9725 47.4736ZM57.0973 38.5984L65.9725 47.4736L68.0938 45.3522L59.2186 36.4771L57.0973 38.5984Z",
155
- fill: "#305AA2"
156
- }))), /*#__PURE__*/React.createElement("div", {
157
- className: `${ChartEmptyState.className}__title`
158
- }, title), /*#__PURE__*/React.createElement("div", {
159
- className: `${ChartEmptyState.className}__subtitle`
160
- }, subtitle), onReset ? /*#__PURE__*/React.createElement(StyledResetButton, {
161
- variant: "unstyled",
162
- leftIcon: mdiRefresh,
163
- onClick: onReset
164
- }, resetLabel) : null);
165
- });
166
- ChartEmptyState.className = CLASSNAME$3;
167
- ChartEmptyState.displayName = COMPONENT_NAME$3;
168
-
169
- function ownKeys(object, enumerableOnly) {
170
- var keys = Object.keys(object);
171
- if (Object.getOwnPropertySymbols) {
172
- var symbols = Object.getOwnPropertySymbols(object);
173
- enumerableOnly && (symbols = symbols.filter(function (sym) {
174
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
175
- })), keys.push.apply(keys, symbols);
176
- }
177
- return keys;
178
- }
179
- function _objectSpread2(target) {
180
- for (var i = 1; i < arguments.length; i++) {
181
- var source = null != arguments[i] ? arguments[i] : {};
182
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
183
- _defineProperty(target, key, source[key]);
184
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
185
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
186
- });
187
- }
188
- return target;
189
- }
190
- function _defineProperty(obj, key, value) {
191
- key = _toPropertyKey(key);
192
- if (key in obj) {
193
- Object.defineProperty(obj, key, {
194
- value: value,
195
- enumerable: true,
196
- configurable: true,
197
- writable: true
198
- });
199
- } else {
200
- obj[key] = value;
201
- }
202
- return obj;
203
- }
204
- function _extends() {
205
- _extends = Object.assign ? Object.assign.bind() : function (target) {
206
- for (var i = 1; i < arguments.length; i++) {
207
- var source = arguments[i];
208
- for (var key in source) {
209
- if (Object.prototype.hasOwnProperty.call(source, key)) {
210
- target[key] = source[key];
211
- }
212
- }
213
- }
214
- return target;
215
- };
216
- return _extends.apply(this, arguments);
217
- }
218
- function _objectWithoutPropertiesLoose(source, excluded) {
219
- if (source == null) return {};
220
- var target = {};
221
- var sourceKeys = Object.keys(source);
222
- var key, i;
223
- for (i = 0; i < sourceKeys.length; i++) {
224
- key = sourceKeys[i];
225
- if (excluded.indexOf(key) >= 0) continue;
226
- target[key] = source[key];
227
- }
228
- return target;
229
- }
230
- function _objectWithoutProperties(source, excluded) {
231
- if (source == null) return {};
232
- var target = _objectWithoutPropertiesLoose(source, excluded);
233
- var key, i;
234
- if (Object.getOwnPropertySymbols) {
235
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
236
- for (i = 0; i < sourceSymbolKeys.length; i++) {
237
- key = sourceSymbolKeys[i];
238
- if (excluded.indexOf(key) >= 0) continue;
239
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
240
- target[key] = source[key];
241
- }
242
- }
243
- return target;
244
- }
245
- function _toPrimitive(input, hint) {
246
- if (typeof input !== "object" || input === null) return input;
247
- var prim = input[Symbol.toPrimitive];
248
- if (prim !== undefined) {
249
- var res = prim.call(input, hint || "default");
250
- if (typeof res !== "object") return res;
251
- throw new TypeError("@@toPrimitive must return a primitive value.");
252
- }
253
- return (hint === "string" ? String : Number)(input);
254
- }
255
- function _toPropertyKey(arg) {
256
- var key = _toPrimitive(arg, "string");
257
- return typeof key === "symbol" ? key : String(key);
258
- }
259
-
260
- const initialState = {
261
- tableFilters: []
262
- };
263
- const DashboardContext = /*#__PURE__*/React.createContext({
264
- state: initialState
265
- });
266
-
267
- /**
268
- * Context props.
269
- */
270
-
271
- /**
272
- * Reducer props.
273
- */
274
-
275
- let DashboardReducerActionType = /*#__PURE__*/function (DashboardReducerActionType) {
276
- DashboardReducerActionType["ResetFilter"] = "reset-filter";
277
- DashboardReducerActionType["ResetFilters"] = "reset-filters";
278
- DashboardReducerActionType["FilterTable"] = "filter-table";
279
- DashboardReducerActionType["FilterTableBatch"] = "filter-table-batch";
280
- DashboardReducerActionType["AppendFilterTableBatch"] = "append-filter-table-batch";
281
- return DashboardReducerActionType;
282
- }({});
283
-
284
- /**
285
- * Component props.
286
- */
287
-
288
- const areEquals = (tableFilter, actionFilter) => {
289
- return tableFilter.field === actionFilter.field && tableFilter.operator === actionFilter.operator;
290
- };
291
- const addOrUpdateFilter = (oldFilters, newFilter) => {
292
- if (oldFilters.find(f => areEquals(f, newFilter))) {
293
- return oldFilters.map(f => {
294
- if (areEquals(f, newFilter)) {
295
- return newFilter;
296
- }
297
- return f;
298
- });
299
- } else {
300
- return [...oldFilters, newFilter];
301
- }
302
- };
303
- const addOrUpdateFilters = (oldFilters, newFilters) => {
304
- let updatedFilters = oldFilters;
305
- for (let i = 0; i < newFilters.length; i++) {
306
- updatedFilters = addOrUpdateFilter(updatedFilters, newFilters[i]);
307
- }
308
- return updatedFilters;
309
- };
310
- const replaceFilters = newFilters => {
311
- return Array.isArray(newFilters) ? newFilters : [newFilters];
312
- };
313
- const removeFilter = (oldFilters, newFilter) => {
314
- return oldFilters.filter(f => !areEquals(f, newFilter));
315
- };
316
- const removeAllFilters = () => {
317
- return [];
318
- };
319
- const DashboardReducer = (state, action) => {
320
- switch (action.type) {
321
- case DashboardReducerActionType.ResetFilter:
322
- return _objectSpread2(_objectSpread2({}, state), {}, {
323
- tableFilters: removeFilter(state.tableFilters, action.filter)
324
- });
325
- case DashboardReducerActionType.ResetFilters:
326
- return _objectSpread2(_objectSpread2({}, state), {}, {
327
- tableFilters: removeAllFilters()
328
- });
329
- case DashboardReducerActionType.FilterTable:
330
- return _objectSpread2(_objectSpread2({}, state), {}, {
331
- tableFilters: addOrUpdateFilter(state.tableFilters, action.filter)
332
- });
333
- case DashboardReducerActionType.FilterTableBatch:
334
- return _objectSpread2(_objectSpread2({}, state), {}, {
335
- tableFilters: replaceFilters(action.filter)
336
- });
337
- case DashboardReducerActionType.AppendFilterTableBatch:
338
- return _objectSpread2(_objectSpread2({}, state), {}, {
339
- tableFilters: addOrUpdateFilters(state.tableFilters, action.filter)
340
- });
341
- }
342
- };
343
-
344
- const CrossfilterRegistry = (() => {
345
- const instances = new WeakMap();
346
- const get = data => {
347
- let instance = instances.get(data);
348
- if (!instance) {
349
- instance = crossfilter(data);
350
- instances.set(data, instance);
351
- }
352
- return instance;
353
- };
354
- const remove = data => {
355
- instances.delete(data);
356
- };
357
- return {
358
- get,
359
- remove
360
- };
361
- })();
362
-
363
- const _excluded$2 = ["children", "className", "data", "dataGridApiRef"];
364
- const COMPONENT_NAME$2 = 'Dashboard';
365
- const CLASSNAME$2 = 'redsift-dashboard-container';
366
- const Dashboard = /*#__PURE__*/forwardRef((props, ref) => {
367
- const {
368
- children,
369
- className,
370
- data,
371
- dataGridApiRef: propsDataGridApiRef
372
- } = props,
373
- forwardedProps = _objectWithoutProperties(props, _excluded$2);
374
- const providerRef = ref || useRef();
375
- const dataGridApiRef = propsDataGridApiRef || useGridApiRef();
376
- const [updateContext, setUpdateContext] = useState(false);
377
- const [state, dispatch] = useReducer(DashboardReducer, {
378
- tableFilters: []
379
- });
380
- const value = useMemo(() => ({
381
- dashboardRef: providerRef,
382
- data,
383
- dataGridApiRef,
384
- dispatch,
385
- ndx: CrossfilterRegistry.get(data),
386
- state,
387
- toggleUpdateContext: () => setUpdateContext(!updateContext)
388
- }), [data, state, updateContext]);
389
- return /*#__PURE__*/React.createElement("div", _extends({}, forwardedProps, {
390
- className: classNames(Dashboard.className, className),
391
- ref: providerRef
392
- }), /*#__PURE__*/React.createElement(DashboardContext.Provider, {
393
- value: value
394
- }, children));
395
- });
396
- Dashboard.className = CLASSNAME$2;
397
- Dashboard.displayName = COMPONENT_NAME$2;
398
-
399
- // istanbul ignore file
400
- const BACKGROUND_COLOR = '#F8F8F8';
401
- const GREY_1 = '#E2E6EA';
402
- const GREY_2 = '#bff0fd';
403
- const getPdfStyles = primaryColor => {
404
- Font.register({
405
- family: 'Source Code Pro',
406
- fonts: [{
407
- src: 'https://fonts.gstatic.com/s/sourcecodepro/v7/HI_SiYsKILxRpg3hIP6sJ7fM7PqlM-vT.ttf'
408
- }]
409
- });
410
- Font.register({
411
- family: 'Roboto',
412
- fonts: [{
413
- fontWeight: 700,
414
- src: 'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/fonts/roboto/Roboto-Regular.ttf'
415
- }, {
416
- fontWeight: 400,
417
- src: 'https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf'
418
- }]
419
- });
420
- return StyleSheet.create({
421
- page: {
422
- borderTopStyle: 'solid',
423
- borderTopWidth: 32,
424
- borderTopColor: primaryColor,
425
- borderBottomStyle: 'solid',
426
- borderBottomWidth: 6,
427
- borderBottomColor: primaryColor,
428
- backgroundColor: BACKGROUND_COLOR,
429
- paddingTop: 20,
430
- paddingBottom: 40
431
- },
432
- logoContainer: {
433
- margin: 0,
434
- paddingBottom: 10,
435
- alignItems: 'center',
436
- width: '100%'
437
- },
438
- logo: {
439
- width: 'auto',
440
- height: 30
441
- },
442
- introductionContainer: {
443
- lineHeight: 1.4,
444
- textAlign: 'center',
445
- marginHorizontal: 40,
446
- marginVertical: 10
447
- },
448
- introductionText: {
449
- fontSize: 8,
450
- fontFamily: 'Roboto',
451
- fontWeight: 400,
452
- color: 'black'
453
- },
454
- pageNumber: {
455
- fontFamily: 'Source Code Pro',
456
- position: 'absolute',
457
- fontSize: 6,
458
- bottom: 5,
459
- right: 20,
460
- left: 0,
461
- textAlign: 'right',
462
- color: 'black'
463
- },
464
- pageContinue: {
465
- fontSize: 8,
466
- fontFamily: 'Roboto',
467
- fontWeight: 400,
468
- top: -10,
469
- left: 20
470
- },
471
- tableContainer: {
472
- backgroundColor: 'white',
473
- marginHorizontal: 20,
474
- marginVertical: 10,
475
- paddingTop: 10,
476
- paddingLeft: 10,
477
- borderRightWidth: 1,
478
- borderBottomWidth: 1,
479
- borderRightColor: BACKGROUND_COLOR,
480
- borderBottomColor: GREY_1,
481
- width: 'auto'
482
- },
483
- tableRowContainer: {
484
- flexDirection: 'row',
485
- borderBottomColor: GREY_2,
486
- alignItems: 'flex-start',
487
- fontSize: 8,
488
- marginLeft: 16,
489
- marginRight: 24,
490
- height: 'auto'
491
- },
492
- tableHeaderContainer: {
493
- flexDirection: 'row',
494
- alignItems: 'flex-start',
495
- fontSize: 7,
496
- fontFamily: 'Roboto',
497
- fontWeight: 700,
498
- marginLeft: 16,
499
- marginRight: 24,
500
- marginBottom: 12,
501
- paddingTop: 12,
502
- paddingBottom: 12,
503
- borderBottomWidth: 2,
504
- borderBottomColor: primaryColor
505
- },
506
- tableCellHeaderText: {
507
- fontSize: 7,
508
- fontFamily: 'Roboto',
509
- fontWeight: 700,
510
- color: 'black',
511
- overflow: 'hidden'
512
- },
513
- tableCellText: {
514
- fontSize: 6,
515
- lineHeight: 1.5,
516
- fontFamily: 'Roboto',
517
- fontWeight: 400,
518
- color: 'black',
519
- overflow: 'hidden'
520
- },
521
- dashboardImageContainer: {
522
- marginHorizontal: 20,
523
- marginTop: 0,
524
- marginBottom: 10
525
- },
526
- constraintsContainer: {
527
- width: 'auto',
528
- height: 'auto',
529
- paddingVertical: 30,
530
- textAlign: 'center'
531
- },
532
- constraints: {
533
- fontSize: 6,
534
- fontFamily: 'Roboto',
535
- fontWeight: 700,
536
- color: 'black'
537
- }
538
- });
539
- };
540
-
541
- // istanbul ignore file
542
- const DEFAULT_COLUMN_WIDTH = 100;
543
- const getWidthColumn = (width, totalW, nrColumns) => {
544
- // calculation width column where the 7px margin between the columns is included
545
- return `${Math.round(width * 100 / (totalW - 7 * (nrColumns - 1)))}%`;
546
- };
547
- const PdfTableRow = _ref => {
548
- let {
549
- rowIndex,
550
- rowData,
551
- columns,
552
- styles,
553
- totalWidth
554
- } = _ref;
555
- return /*#__PURE__*/React.createElement(View, {
556
- style: styles.tableRowContainer,
557
- key: `row-${rowIndex}`
558
- }, columns.map((column, index) => {
559
- const {
560
- field,
561
- width
562
- } = column;
563
- let totalW = totalWidth;
564
- let nrColumns = columns.length;
565
-
566
- // The checkbox in the table will not be printed
567
- if (field === '__check__') {
568
- totalW = totalW - (width || 50);
569
- nrColumns = nrColumns - 1;
570
- return;
571
- }
572
- const widthColumn = getWidthColumn(width || DEFAULT_COLUMN_WIDTH, totalW, nrColumns);
573
-
574
- // Empty value will print '-'
575
- if (!rowData[field]) {
576
- return /*#__PURE__*/React.createElement(View, {
577
- style: {
578
- width: widthColumn,
579
- paddingVertical: 2,
580
- marginRight: 7
581
- },
582
- key: `cell-${rowIndex}-${index}`
583
- }, /*#__PURE__*/React.createElement(Text, {
584
- style: styles.tableCellText
585
- }, '-'));
586
- }
587
- return /*#__PURE__*/React.createElement(View, {
588
- style: {
589
- width: widthColumn,
590
- paddingVertical: 2,
591
- marginRight: 7
592
- },
593
- key: `cell-${rowIndex}-${index}`
594
- }, /*#__PURE__*/React.createElement(Text, {
595
- style: styles.tableCellText
596
- }, Array.isArray(rowData[field]) ? rowData[field].join(', ') : rowData[field]));
597
- }));
598
- };
599
- const PdfTable = _ref2 => {
600
- let {
601
- dataTable,
602
- styles,
603
- localeText
604
- } = _ref2;
605
- const {
606
- data,
607
- columns,
608
- totalWidth
609
- } = dataTable;
610
- return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(View, {
611
- style: styles.tableHeaderContainer
612
- }, columns.map(column => {
613
- let totalW = totalWidth;
614
- let nrColumns = columns.length;
615
- const {
616
- field,
617
- headerName,
618
- width
619
- } = column;
620
-
621
- // The checkbox in the table will not be printed
622
- if (field === '__check__') {
623
- totalW = totalW - (width || 50);
624
- nrColumns = nrColumns - 1;
625
- return;
626
- }
627
- const widthColumn = getWidthColumn(width || DEFAULT_COLUMN_WIDTH, totalW, nrColumns);
628
- return /*#__PURE__*/React.createElement(View, {
629
- style: {
630
- width: widthColumn,
631
- paddingVertical: 2,
632
- marginRight: 7
633
- },
634
- key: `heading-${field}`
635
- }, /*#__PURE__*/React.createElement(Text, {
636
- style: styles.tableCellHeaderText
637
- }, headerName));
638
- })), /*#__PURE__*/React.createElement(View, null, data.map((row, index) => {
639
- if (index < 1000) {
640
- return /*#__PURE__*/React.createElement(PdfTableRow, {
641
- key: index,
642
- rowIndex: index,
643
- rowData: data[index],
644
- columns: columns,
645
- styles: styles,
646
- totalWidth: totalWidth
647
- });
648
- }
649
- })), data.length >= 1000 ? /*#__PURE__*/React.createElement(View, {
650
- style: styles.constraintsContainer
651
- }, /*#__PURE__*/React.createElement(Text, {
652
- style: styles.constraints
653
- }, (localeText === null || localeText === void 0 ? void 0 : localeText.maxSizeDisclaimer) || 'Due to processing constraints this pdf is limited to the first 1000 rows of data.')) : null);
654
- };
655
- const Pagination = _ref3 => {
656
- let {
657
- styles
658
- } = _ref3;
659
- return /*#__PURE__*/React.createElement(Text, {
660
- style: styles.pageNumber,
661
- render: _ref4 => {
662
- let {
663
- pageNumber,
664
- totalPages
665
- } = _ref4;
666
- return `${pageNumber}/${totalPages}`;
667
- },
668
- fixed: true
669
- });
670
- };
671
- const PdfDocument = _ref5 => {
672
- let {
673
- dashboardImage,
674
- introduction,
675
- localeText,
676
- logo,
677
- dataTable,
678
- primaryColor
679
- } = _ref5;
680
- const styles = getPdfStyles(primaryColor);
681
- return /*#__PURE__*/React.createElement(Document, null, /*#__PURE__*/React.createElement(Page, {
682
- size: "A4",
683
- style: styles.page
684
- }, /*#__PURE__*/React.createElement(React.Fragment, null, logo ? /*#__PURE__*/React.createElement(View, {
685
- style: styles.logoContainer
686
- }, /*#__PURE__*/React.createElement(Image, {
687
- src: logo,
688
- style: styles.logo
689
- })) : null, introduction ? /*#__PURE__*/React.createElement(View, {
690
- style: styles.introductionContainer
691
- }, /*#__PURE__*/React.createElement(Text, {
692
- style: styles.introductionText
693
- }, introduction)) : null, dashboardImage ? /*#__PURE__*/React.createElement(View, {
694
- style: styles.dashboardImageContainer
695
- }, /*#__PURE__*/React.createElement(Image, {
696
- src: dashboardImage
697
- })) : null, dataTable ? /*#__PURE__*/React.createElement(View, {
698
- style: styles.tableContainer
699
- }, /*#__PURE__*/React.createElement(PdfTable, {
700
- dataTable: dataTable,
701
- styles: styles,
702
- localeText: localeText
703
- })) : null, /*#__PURE__*/React.createElement(Pagination, {
704
- styles: styles
705
- }))));
706
- };
707
-
708
- const _excluded$1 = ["children", "className", "componentRef", "fileName", "introduction", "localeText", "logo", "onClick", "primaryColor"];
709
- const COMPONENT_NAME$1 = 'PdfExportButton';
710
- const CLASSNAME$1 = 'redsift-pdf-export-button';
711
- const getDashboardImage = async componentRef => {
712
- var _componentRef$current, _componentRef$current2, _componentRef$current3, _componentRef$current4;
713
- const filter = el => {
714
- const classList = el.classList;
715
- return !(classList !== null && classList !== void 0 && classList.contains('redsift-datagrid') || classList !== null && classList !== void 0 && classList.contains('redsift-button'));
716
- };
717
- const dashboardHeight = componentRef.current.getBoundingClientRect().height;
718
- const datagridHeight = ((_componentRef$current = componentRef.current) === null || _componentRef$current === void 0 ? void 0 : (_componentRef$current2 = _componentRef$current.getElementsByClassName('redsift-datagrid')) === null || _componentRef$current2 === void 0 ? void 0 : (_componentRef$current3 = _componentRef$current2[0]) === null || _componentRef$current3 === void 0 ? void 0 : (_componentRef$current4 = _componentRef$current3.getBoundingClientRect()) === null || _componentRef$current4 === void 0 ? void 0 : _componentRef$current4.height) || 0;
719
- return new Promise(resolve => {
720
- domToImage.toPng(componentRef.current, {
721
- filter,
722
- height: dashboardHeight - datagridHeight
723
- }).then(function (dataUrl) {
724
- resolve(dataUrl);
725
- }).catch(() => {
726
- resolve('');
727
- });
728
- });
729
- };
730
- const PdfExportButton = /*#__PURE__*/forwardRef((props, ref) => {
731
- const {
732
- children,
733
- className,
734
- componentRef: propComponentRef,
735
- fileName,
736
- introduction,
737
- localeText,
738
- logo,
739
- onClick,
740
- primaryColor
741
- } = props,
742
- forwardedProps = _objectWithoutProperties(props, _excluded$1);
743
- const [componentRef, setComponentRef] = useState(propComponentRef);
744
- const [isLoading, setIsLoading] = useState(false);
745
- const {
746
- dashboardRef,
747
- dataGridApiRef
748
- } = useContext(DashboardContext);
749
- useEffect(() => {
750
- if (!componentRef || !componentRef.current) {
751
- setComponentRef(dashboardRef);
752
- }
753
- }, [dashboardRef]);
754
- const exportPdf = async () => {
755
- if (onClick) {
756
- onClick();
757
- }
758
- setIsLoading(true);
759
- try {
760
- const dashboardImage = await getDashboardImage(componentRef || dashboardRef);
761
- let dataTable;
762
- if (dataGridApiRef && dataGridApiRef.current && Object.keys(dataGridApiRef.current).length) {
763
- dataTable = {
764
- data: gridFilteredSortedRowEntriesSelector(dataGridApiRef.current.state, dataGridApiRef.current.instanceId).slice(0, 1000).map(_ref => {
765
- let {
766
- model
767
- } = _ref;
768
- return model;
769
- }),
770
- columns: gridVisibleColumnDefinitionsSelector(dataGridApiRef.current.state, dataGridApiRef.current.instanceId),
771
- totalWidth: gridColumnsTotalWidthSelector(dataGridApiRef.current.state, dataGridApiRef.current.instanceId)
772
- };
773
- }
774
- const doc = /*#__PURE__*/React.createElement(PdfDocument, {
775
- localeText: localeText,
776
- dashboardImage: dashboardImage,
777
- introduction: introduction,
778
- logo: logo,
779
- primaryColor: primaryColor || RedsiftColorBlueD1,
780
- dataTable: dataTable
781
- });
782
- const asPdf = pdf([]);
783
- asPdf.updateContainer(doc);
784
- const blob = await asPdf.toBlob();
785
- saveAs(blob, fileName || 'redsift-dashboard.pdf');
786
- } catch (e) {
787
- console.log('error:', e);
788
- }
789
- setIsLoading(false);
790
- };
791
- return /*#__PURE__*/React.createElement(Button, _extends({
792
- className: classNames(PdfExportButton.className, className),
793
- onClick: exportPdf,
794
- isDisabled: isLoading
795
- }, forwardedProps, {
796
- ref: ref
797
- }), isLoading ? /*#__PURE__*/React.createElement(Spinner, {
798
- size: "xsmall",
799
- isColored: false
800
- }) : null, " ", children);
801
- });
802
- PdfExportButton.className = CLASSNAME$1;
803
- PdfExportButton.displayName = COMPONENT_NAME$1;
804
-
805
- // istanbul ignore file
806
- /**
807
- * Component size.
808
- */
809
- const TimeSeriesBarChartSize = {
810
- large: 'large',
811
- medium: 'medium',
812
- small: 'small'
813
- };
814
- /**
815
- * Component theme.
816
- */
817
- const TimeSeriesBarChartTheme = ColorTheme;
818
-
819
- /**
820
- * Component props.
821
- */
822
-
823
- // istanbul ignore file
824
- /**
825
- * Component style.
826
- */
827
- const StyledTimeSeriesBarChart = styled.div`
828
- margin: 16px;
829
- padding: 16px;
830
-
831
- text {
832
- fill: ${_ref => {
833
- let {
834
- $theme
835
- } = _ref;
836
- return `var(--redsift-color-${$theme}-components-text-primary)`;
837
- }};
838
- }
839
-
840
- .redsift-timeseries-barchart__chart {
841
- display: flex;
842
- font-family: var(--redsift-typography-font-family-poppins);
843
- font-size: 12px;
844
- justify-content: center;
845
- margin: 8px 0;
846
- }
847
-
848
- svg > g {
849
- margin: 8px;
850
- }
851
-
852
- .grid-line,
853
- .axis .grid-line,
854
- .grid-line line,
855
- .axis .grid-line line {
856
- fill: none;
857
- stroke: #ccc;
858
- shape-rendering: crispEdges;
859
- }
860
-
861
- .axis text {
862
- font-family: var(--redsift-typography-font-family-poppins);
863
- font-size: 10px;
864
- }
865
-
866
- g.stack rect.bar.deselected {
867
- fill-opacity: 0.5;
868
- fill: var(--redsift-color-neutral-mid-grey);
869
- }
870
-
871
- .brush .custom-brush-handle {
872
- fill: #eee;
873
- stroke: #666;
874
- cursor: ew-resize;
875
- }
876
-
877
- text {
878
- user-select: none;
879
- }
880
- `;
881
- const StyledTimeSeriesBarChartTitle = styled(Flexbox)`
882
- font-family: var(--redsift-typography-h4-font-family);
883
- font-size: var(--redsift-typography-h4-font-size);
884
- font-weight: var(--redsift-typography-h4-font-weight);
885
- line-height: var(--redsift-typography-h4-line-height);
886
- `;
887
- const StyledTimeSeriesBarChartCaption = styled.p`
888
- font-family: var(--redsift-typography-caption-font-family);
889
- font-size: var(--redsift-typography-caption-font-size);
890
- font-weight: var(--redsift-typography-caption-font-weight);
891
- line-height: var(--redsift-typography-caption-line-height);
892
- `;
893
- const StyledTimeSeriesBarChartContainer = styled.div`
894
- display: flex;
895
- align-items: center;
896
- gap: 16px;
897
- font-family: var(--redsift-typography-font-family-poppins);
898
- font-size: 11px;
899
- justify-content: center;
900
- margin: 8px 0;
901
- position: relative;
902
-
903
- .redsift-timeseries-barchart-container__chart {
904
- position: relative;
905
- ${_ref2 => {
906
- let {
907
- $isEmpty
908
- } = _ref2;
909
- return $isEmpty ? css`
910
- display: none;
911
- ` : '';
912
- }};
913
- }
914
- `;
915
-
916
- const _excluded = ["areXLabelsRotated", "caption", "className", "colorTheme", "columnToFilter", "data", "dateTimeFieldName", "dateTimeFormat", "dateTimeGroup", "dimension", "isResetable", "localeText", "onFilter", "size", "stackedCategory", "title", "xAxisLabel", "yAxisLabel"];
917
- const COMPONENT_NAME = 'TimeSeriesBarChart';
918
- const CLASSNAME = 'redsift-timeseries-barchart';
919
- const getStartDate = dates => new Date(Math.min(...dates.map(Number)));
920
- const getEndDate = dates => new Date(Math.max(...dates.map(Number)));
921
- const sizeToDimension = size => {
922
- switch (size) {
923
- case TimeSeriesBarChartSize.small:
924
- return {
925
- width: 400,
926
- height: 200,
927
- marginLeft: 16,
928
- marginTop: 16,
929
- marginRight: 16,
930
- marginBottom: 32
931
- };
932
- case TimeSeriesBarChartSize.large:
933
- return {
934
- width: 1000,
935
- height: 300,
936
- marginLeft: 16,
937
- marginTop: 16,
938
- marginRight: 16,
939
- marginBottom: 32
940
- };
941
- case TimeSeriesBarChartSize.medium:
942
- default:
943
- return {
944
- width: 600,
945
- height: 250,
946
- marginLeft: 16,
947
- marginTop: 16,
948
- marginRight: 16,
949
- marginBottom: 32
950
- };
951
- }
952
- };
953
- const parseDateTimeGroup = (data, dateTimeGroup, dateTimeFieldName) => {
954
- const dates = [...data.map(d => new Date(d[dateTimeFieldName]))];
955
- const startDate = getStartDate(dates);
956
- const endDate = getEndDate(dates);
957
- switch (dateTimeGroup) {
958
- case 'hour':
959
- return {
960
- group: g => timeHour(g),
961
- round: x => timeHour(x),
962
- x: scaleTime().domain([timeHour.offset(startDate, -1), timeHour.offset(endDate, 2)]),
963
- xUnits: timeHours
964
- };
965
- case 'day':
966
- return {
967
- group: g => timeDay(g),
968
- round: x => timeDay(x),
969
- x: scaleTime().domain([timeDay.offset(startDate, -1), timeDay.offset(endDate, 2)]),
970
- xUnits: timeDays
971
- };
972
- case 'week':
973
- return {
974
- group: g => timeWeek(g),
975
- round: x => timeWeek(x),
976
- x: scaleTime().domain([timeWeek.offset(startDate, -1), timeWeek.offset(endDate, 2)]),
977
- xUnits: timeWeeks
978
- };
979
- case 'year':
980
- return {
981
- group: g => timeYear(g),
982
- round: x => timeYear(x),
983
- x: scaleTime().domain([timeYear.offset(startDate, -2), timeYear.offset(endDate, 2)]),
984
- xUnits: timeYears
985
- };
986
- case 'month':
987
- default:
988
- return {
989
- group: g => timeMonth(g),
990
- round: x => timeMonth(x),
991
- x: scaleTime().domain([timeMonth.offset(startDate, -1), timeMonth.offset(endDate, 2)]),
992
- xUnits: timeMonths
993
- };
994
- }
995
- };
996
- const TimeSeriesBarChart = /*#__PURE__*/forwardRef((props, ref) => {
997
- const containerRef = ref || useRef();
998
- const chartRef = useRef();
999
- const [id] = useId();
1000
- const [chart, setChart] = useState();
1001
- const {
1002
- areXLabelsRotated,
1003
- caption,
1004
- className,
1005
- colorTheme = props.stackedCategory ? TimeSeriesBarChartTheme.default : TimeSeriesBarChartTheme.monochrome,
1006
- columnToFilter,
1007
- data: propsData,
1008
- dateTimeFieldName,
1009
- dateTimeFormat = '%Y-%m-%d %H:%M:%S',
1010
- dateTimeGroup = 'month',
1011
- dimension,
1012
- isResetable = true,
1013
- localeText,
1014
- onFilter,
1015
- size = TimeSeriesBarChartSize.medium,
1016
- stackedCategory,
1017
- title,
1018
- xAxisLabel,
1019
- yAxisLabel
1020
- } = props,
1021
- forwardedProps = _objectWithoutProperties(props, _excluded);
1022
- const theme = useTheme();
1023
-
1024
- // Get overriden labels and texts.
1025
- const {
1026
- emptyChartTitle,
1027
- emptyChartSubtitle,
1028
- emptyChartResetLabel,
1029
- resetLabel
1030
- } = _objectSpread2({
1031
- resetLabel: 'Reset'
1032
- }, localeText);
1033
-
1034
- // Get charts dimensions based on the selected size.
1035
- const chartDimensions = sizeToDimension(size);
1036
-
1037
- // Get ndx from context or initialize it.
1038
- const {
1039
- dispatch,
1040
- state,
1041
- data
1042
- } = useContext(DashboardContext);
1043
- const {
1044
- tableFilters
1045
- } = state;
1046
-
1047
- // Set color scheme.
1048
- const colorScale = useColor({
1049
- data: propsData !== null && propsData !== void 0 ? propsData : data,
1050
- colorTheme: colorTheme,
1051
- category: stackedCategory !== null && stackedCategory !== void 0 ? stackedCategory : '',
1052
- theme
1053
- });
1054
- const ndx = CrossfilterRegistry.get(propsData ? propsData : data);
1055
-
1056
- // useEffect called only once to initialize the chart.
1057
- useEffect(() => {
1058
- if (chartRef.current) {
1059
- config.defaultColors(scheme.default);
1060
- const parseTime = utcParse(dateTimeFormat);
1061
- const barChart$1 = barChart(chartRef.current);
1062
- const dataset = ndx.all();
1063
-
1064
- // Get time methods based on props
1065
- const {
1066
- group,
1067
- round,
1068
- x,
1069
- xUnits
1070
- } = parseDateTimeGroup(dataset, dateTimeGroup, dateTimeFieldName);
1071
-
1072
- // Compute dimension and group.
1073
- const computedDimension = ndx.dimension(d => parseTime(dimension(d)));
1074
- const timeGroup = computedDimension.group(group);
1075
-
1076
- // Initialize the chart.
1077
- barChart$1.width(chartDimensions.width).height(chartDimensions.height - (areXLabelsRotated ? 30 : 0)).dimension(computedDimension).x(x).xUnits(xUnits).round(round).centerBar(true).alwaysUseRounding(true).renderHorizontalGridLines(true).margins({
1078
- left: chartDimensions.marginLeft + (yAxisLabel ? 24 : 0),
1079
- top: chartDimensions.marginTop,
1080
- right: chartDimensions.marginRight,
1081
- bottom: chartDimensions.marginBottom
1082
- }).barPadding(0.2);
1083
- barChart$1.yAxis().ticks(5);
1084
-
1085
- // Add label to axis.
1086
- if (xAxisLabel) {
1087
- barChart$1.xAxisLabel(xAxisLabel);
1088
- }
1089
- if (yAxisLabel) {
1090
- barChart$1.yAxisLabel(yAxisLabel);
1091
- }
1092
-
1093
- // Rotate labels and reset the height, if asked for.
1094
- if (areXLabelsRotated) {
1095
- barChart$1.on('pretransition', rowChart => {
1096
- barChart$1.select('.axis').attr('text-anchor', 'end').selectAll('text').attr('transform', 'translate(-6,5) rotate(-45)');
1097
- rowChart.select('svg').attr('height', chartDimensions.height);
1098
- });
1099
- }
1100
-
1101
- // Set group whether the chart is stacked or not.
1102
- if (!stackedCategory) {
1103
- barChart$1.group(timeGroup).colors(colorScale);
1104
- } else if (dataset.length) {
1105
- if (!Array.isArray(dataset[0][stackedCategory])) {
1106
- const categories = dataset.reduce((acc, curr) => {
1107
- if (acc.indexOf(curr[stackedCategory]) === -1) {
1108
- acc.push(curr[stackedCategory]);
1109
- }
1110
- return acc;
1111
- }, []);
1112
- const stackedTimeGroup = timeGroup.reduce((p, v) => {
1113
- p[v[stackedCategory]] = (p[v[stackedCategory]] || 0) + 1;
1114
- return p;
1115
- }, (p, v) => {
1116
- p[v[stackedCategory]] = (p[v[stackedCategory]] || 0) - 1;
1117
- return p;
1118
- }, () => ({}));
1119
- barChart$1.group(stackedTimeGroup, categories[0],
1120
- // @ts-expect-error
1121
- (cat => d => d.value[cat])(categories[0])).colors(colorScale);
1122
- for (var i = 1; i < categories.length; ++i) {
1123
- barChart$1.stack(stackedTimeGroup, categories[i], (cat => d => d.value[cat])(categories[i]));
1124
- }
1125
- } else {
1126
- const categories = dataset.reduce((acc, curr) => {
1127
- curr[stackedCategory].forEach(val => {
1128
- if (acc.indexOf(val) === -1) {
1129
- acc.push(val);
1130
- }
1131
- });
1132
- return acc;
1133
- }, []);
1134
- const stackedTimeGroup = timeGroup.reduce((p, v) => {
1135
- v[stackedCategory].forEach(val => {
1136
- p[val] = (p[val] || 0) + 1;
1137
- });
1138
- return p;
1139
- }, (p, v) => {
1140
- v[stackedCategory].forEach(val => {
1141
- p[val] = (p[val] || 0) - 1;
1142
- });
1143
- return p;
1144
- }, () => ({}));
1145
- barChart$1.group(stackedTimeGroup, categories[0],
1146
- // @ts-expect-error
1147
- (cat => d => d.value[cat])(categories[0])).colors(colorScale);
1148
- for (var i = 1; i < categories.length; ++i) {
1149
- barChart$1.stack(stackedTimeGroup, categories[i], (cat => d => d.value[cat])(categories[i]));
1150
- }
1151
- }
1152
- }
1153
-
1154
- // Dispatch filters to datagrid when a value is selected or unselected.
1155
- const formatTime = timeFormat('%Y-%m-%dT%H:%M');
1156
- barChart$1.on('filtered', () => {
1157
- if (columnToFilter) {
1158
- var _barChart$filters;
1159
- const dateArray = (_barChart$filters = barChart$1.filters()) === null || _barChart$filters === void 0 ? void 0 : _barChart$filters[0];
1160
- if (Array.isArray(dateArray) && dateArray.length === 2) {
1161
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1162
- type: DashboardReducerActionType.FilterTableBatch,
1163
- filter: [{
1164
- id: `${barChart$1.anchorName()}-start`,
1165
- field: columnToFilter,
1166
- operator: 'after',
1167
- value: formatTime(dateArray[0])
1168
- }, {
1169
- id: `${barChart$1.anchorName()}-end`,
1170
- field: columnToFilter,
1171
- operator: 'onOrBefore',
1172
- value: formatTime(dateArray[1])
1173
- }]
1174
- });
1175
- }
1176
- }
1177
- onFilter === null || onFilter === void 0 ? void 0 : onFilter(barChart$1.filters(), ndx.allFiltered());
1178
- });
1179
-
1180
- // Render the chart.
1181
- barChart$1.render();
1182
-
1183
- // Store chart for further use.
1184
- setChart(barChart$1);
1185
- }
1186
- }, [propsData, data]);
1187
-
1188
- // Filter chart if context is updated by an external component.
1189
- const filterStart = tableFilters.find(filter => filter.field === columnToFilter && filter.operator === 'after');
1190
- const filterEnd = tableFilters.find(filter => filter.field === columnToFilter && filter.operator === 'onOrBefore');
1191
- useEffect(() => {
1192
- if (chart && filterStart && filterEnd && filterStart.value && filterEnd.value) {
1193
- const chartFiltersObj = chart.filters();
1194
- const chartFilters = chartFiltersObj === null || chartFiltersObj === void 0 ? void 0 : chartFiltersObj[0];
1195
- const chartFilterStart = chartFilters === null || chartFilters === void 0 ? void 0 : chartFilters[0];
1196
- const chartFilterEnd = chartFilters === null || chartFilters === void 0 ? void 0 : chartFilters[1];
1197
- if (chartFilterStart !== isoParse(filterStart.value) && chartFilterEnd !== isoParse(filterEnd.value)) {
1198
- var _d3isoParse, _d3isoParse2;
1199
- chart.filter(null);
1200
- chart.filter(filters.RangedFilter(((_d3isoParse = isoParse(filterStart.value)) === null || _d3isoParse === void 0 ? void 0 : _d3isoParse.getTime()) || 0, ((_d3isoParse2 = isoParse(filterEnd.value)) === null || _d3isoParse2 === void 0 ? void 0 : _d3isoParse2.getTime()) || 0));
1201
- redrawAll();
1202
- }
1203
- }
1204
- }, [filterStart === null || filterStart === void 0 ? void 0 : filterStart.value, filterEnd === null || filterEnd === void 0 ? void 0 : filterEnd.value]);
1205
- return /*#__PURE__*/React.createElement(StyledTimeSeriesBarChart, _extends({}, forwardedProps, {
1206
- className: classNames(TimeSeriesBarChart.className, className),
1207
- ref: containerRef,
1208
- $theme: theme
1209
- }), /*#__PURE__*/React.createElement(StyledTimeSeriesBarChartTitle, {
1210
- className: `${TimeSeriesBarChart.className}__title`,
1211
- alignItems: "center",
1212
- $theme: theme
1213
- }, title ? /*#__PURE__*/React.createElement("div", {
1214
- id: `id${id}__title`
1215
- }, title) : null, chart && isResetable ? /*#__PURE__*/React.createElement(Button, {
1216
- variant: "unstyled",
1217
- onClick: () => {
1218
- chart.filter(null);
1219
- redrawAll();
1220
- if (columnToFilter) {
1221
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1222
- type: DashboardReducerActionType.ResetFilter,
1223
- filter: {
1224
- id: `${chart.anchorName()}-start`,
1225
- field: columnToFilter,
1226
- operator: 'after'
1227
- }
1228
- });
1229
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1230
- type: DashboardReducerActionType.ResetFilter,
1231
- filter: {
1232
- id: `${chart.anchorName()}-end`,
1233
- field: columnToFilter,
1234
- operator: 'onOrBefore'
1235
- }
1236
- });
1237
- }
1238
- }
1239
- }, resetLabel) : null), /*#__PURE__*/React.createElement(StyledTimeSeriesBarChartContainer, {
1240
- className: `${TimeSeriesBarChart.className}__container`,
1241
- $isEmpty: ndx.all().length === 0
1242
- }, /*#__PURE__*/React.createElement("div", {
1243
- className: `${TimeSeriesBarChart.className}-container__chart`,
1244
- ref: chartRef
1245
- }), ndx.all().length === 0 ? /*#__PURE__*/React.createElement(ChartEmptyState, {
1246
- title: emptyChartTitle,
1247
- subtitle: emptyChartSubtitle,
1248
- resetLabel: emptyChartResetLabel,
1249
- onReset: () => {
1250
- filterAll();
1251
- redrawAll();
1252
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1253
- type: DashboardReducerActionType.ResetFilters
1254
- });
1255
- }
1256
- }) : null), caption ? /*#__PURE__*/React.createElement(StyledTimeSeriesBarChartCaption, {
1257
- className: `${TimeSeriesBarChart.className}__caption`,
1258
- id: `id${id}__caption`,
1259
- $theme: theme
1260
- }, caption) : null);
1261
- });
1262
- TimeSeriesBarChart.className = CLASSNAME;
1263
- TimeSeriesBarChart.displayName = COMPONENT_NAME;
1264
-
1265
- /**
1266
- * Hook to give to a chart the roles, events and attributes of a listbox.
1267
- */
1268
- const useCategoricalChartAsListbox = _ref => {
1269
- let {
1270
- id,
1271
- ref,
1272
- type,
1273
- ndxGroup,
1274
- orientation = 'horizontal'
1275
- } = _ref;
1276
- const currentIndexRef = useRef(0);
1277
- const props = useMemo(() => {
1278
- const numberOfGroups = ndxGroup === null || ndxGroup === void 0 ? void 0 : ndxGroup.all().filter(datum => datum.value).length;
1279
- if (ref && numberOfGroups) {
1280
- const getCurrentOption = () => ref.current.querySelector(`._${currentIndexRef.current}`);
1281
- const next = () => {
1282
- getCurrentOption().classList.remove('focused');
1283
- const index = currentIndexRef.current === numberOfGroups - 1 ? 0 : currentIndexRef.current + 1;
1284
- currentIndexRef.current = index;
1285
- ref.current.setAttribute('aria-activedescendant', `id${id}__${type}-${currentIndexRef.current}`);
1286
- getCurrentOption().classList.add('focused');
1287
- };
1288
- const previous = () => {
1289
- getCurrentOption().classList.remove('focused');
1290
- const index = currentIndexRef.current === 0 ? numberOfGroups - 1 : currentIndexRef.current - 1;
1291
- currentIndexRef.current = index;
1292
- ref.current.setAttribute('aria-activedescendant', `id${id}__${type}-${currentIndexRef.current}`);
1293
- getCurrentOption().classList.add('focused');
1294
- };
1295
- const focus = () => {
1296
- ref.current.setAttribute('aria-activedescendant', `id${id}__${type}-0`);
1297
- getCurrentOption().classList.add('focused');
1298
- };
1299
- const blur = () => {
1300
- getCurrentOption().classList.remove('focused');
1301
- currentIndexRef.current = 0;
1302
- ref.current.setAttribute('aria-activedescendant', '');
1303
- };
1304
- const keydown = e => {
1305
- e.stopPropagation();
1306
- switch (e.code) {
1307
- case 'ArrowRight':
1308
- if (orientation === 'horizontal') {
1309
- e.preventDefault();
1310
- next();
1311
- }
1312
- break;
1313
- case 'ArrowLeft':
1314
- if (orientation === 'horizontal') {
1315
- e.preventDefault();
1316
- previous();
1317
- }
1318
- break;
1319
- case 'ArrowDown':
1320
- if (orientation === 'vertical') {
1321
- e.preventDefault();
1322
- next();
1323
- }
1324
- break;
1325
- case 'ArrowUp':
1326
- if (orientation === 'vertical') {
1327
- e.preventDefault();
1328
- previous();
1329
- }
1330
- break;
1331
- case 'Enter':
1332
- case 'Space':
1333
- e.preventDefault();
1334
- getCurrentOption().dispatchEvent(new Event('click'));
1335
- break;
1336
- }
1337
- };
1338
- return {
1339
- 'aria-activedescendant': '',
1340
- 'aria-multiselectable': 'true',
1341
- 'aria-orientation': orientation,
1342
- role: 'listbox',
1343
- tabIndex: 0,
1344
- onFocus: focus,
1345
- onBlur: blur,
1346
- onMouseDown: event => event.preventDefault(),
1347
- onMouseLeave: blur,
1348
- onKeyDown: keydown
1349
- };
1350
- }
1351
- }, [ref, ref.current, ndxGroup, JSON.parse(JSON.stringify((ndxGroup === null || ndxGroup === void 0 ? void 0 : ndxGroup.all()) || ''))]);
1352
- return props;
1353
- };
1354
-
1355
- const FilterableBarChart = props => {
1356
- const {
1357
- children,
1358
- datagridCategoryDimFilter,
1359
- dimension,
1360
- group,
1361
- id: propsId,
1362
- isDimensionArray,
1363
- isResetable,
1364
- localeText,
1365
- onFilter
1366
- } = props;
1367
- const [_id] = useId();
1368
- const id = propsId !== null && propsId !== void 0 ? propsId : _id;
1369
- const ref = useRef();
1370
- const {
1371
- emptyChartTitle,
1372
- emptyChartSubtitle,
1373
- emptyChartResetLabel
1374
- } = _objectSpread2({}, localeText);
1375
- const {
1376
- data,
1377
- dispatch,
1378
- toggleUpdateContext,
1379
- state: {
1380
- tableFilters
1381
- }
1382
- } = useContext(DashboardContext);
1383
- const [ndxDimension, setNdxDimension] = useState();
1384
- const [ndxGroup, setNdxGroup] = useState();
1385
- useEffect(() => {
1386
- const computedNdxDimension = CrossfilterRegistry.get(data).dimension(dimension, isDimensionArray);
1387
- const computedNdxGroup = group ? group(computedNdxDimension) : computedNdxDimension.group();
1388
- setNdxDimension(computedNdxDimension);
1389
- setNdxGroup(computedNdxGroup);
1390
- return function cleanup() {
1391
- computedNdxDimension.filterAll();
1392
- };
1393
- }, [dimension, data, group]);
1394
- const [filters, setFilters] = useState([]);
1395
- const handleFilter = category => {
1396
- let newFilters;
1397
- if (filters.includes(category)) {
1398
- newFilters = filters.filter(f => f !== category);
1399
- } else {
1400
- newFilters = [...filters, category];
1401
- }
1402
- setFilters(newFilters);
1403
- if (newFilters.length) {
1404
- ndxDimension.filter(d => newFilters.includes(d));
1405
- } else {
1406
- ndxDimension.filterAll();
1407
- }
1408
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1409
- if (datagridCategoryDimFilter) {
1410
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1411
- type: DashboardReducerActionType.FilterTable,
1412
- filter: {
1413
- id: id,
1414
- field: datagridCategoryDimFilter.field,
1415
- operator: datagridCategoryDimFilter.operator,
1416
- value: newFilters
1417
- }
1418
- });
1419
- }
1420
- if (onFilter) {
1421
- onFilter(newFilters);
1422
- }
1423
- };
1424
- const resetFilters = () => {
1425
- setFilters([]);
1426
- ndxDimension.filterAll();
1427
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1428
- if (datagridCategoryDimFilter) {
1429
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1430
- type: DashboardReducerActionType.ResetFilter,
1431
- filter: {
1432
- id: id,
1433
- field: datagridCategoryDimFilter.field,
1434
- operator: datagridCategoryDimFilter.operator
1435
- }
1436
- });
1437
- }
1438
- if (onFilter) {
1439
- onFilter();
1440
- }
1441
- };
1442
- useEffect(() => {
1443
- var _tableFilters$find;
1444
- if (!datagridCategoryDimFilter) {
1445
- return;
1446
- }
1447
- const updatedFilters = (_tableFilters$find = tableFilters.find(filter => filter.field === datagridCategoryDimFilter.field && filter.operator === datagridCategoryDimFilter.operator)) === null || _tableFilters$find === void 0 ? void 0 : _tableFilters$find.value;
1448
- if (updatedFilters && updatedFilters !== filters && ndxDimension) {
1449
- setFilters(updatedFilters);
1450
- if (updatedFilters.length) {
1451
- ndxDimension.filter(d => updatedFilters.includes(d));
1452
- } else {
1453
- ndxDimension.filterAll();
1454
- }
1455
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1456
- }
1457
- }, [tableFilters]);
1458
- const emptyComponent = /*#__PURE__*/React.createElement(ChartEmptyState, {
1459
- title: emptyChartTitle,
1460
- subtitle: emptyChartSubtitle,
1461
- resetLabel: emptyChartResetLabel,
1462
- onReset: resetFilters
1463
- });
1464
- const chartProps = useCategoricalChartAsListbox({
1465
- id,
1466
- ref: ref,
1467
- type: 'bar',
1468
- ndxGroup,
1469
- orientation: 'vertical'
1470
- });
1471
- const filterProps = {
1472
- barProps: {
1473
- tabIndex: -1
1474
- },
1475
- barRole: 'option',
1476
- role: 'listbox',
1477
- chartProps: chartProps,
1478
- chartRef: ref,
1479
- data: ndxGroup ? JSON.parse(JSON.stringify(ndxGroup.all())) : undefined,
1480
- emptyComponent,
1481
- id,
1482
- isBarSelected: datum => {
1483
- return filters.length === 0 || filters.includes(Array.isArray(datum.data.key) ? datum.data.key[1] : datum.data.key);
1484
- },
1485
- onBarClick: datum => {
1486
- handleFilter(Array.isArray(datum.data.key) ? datum.data.key[1] : datum.data.key);
1487
- },
1488
- onReset: isResetable ? resetFilters : undefined
1489
- };
1490
- if ( /*#__PURE__*/isValidElement(children)) {
1491
- return /*#__PURE__*/React.cloneElement(children, _objectSpread2({}, filterProps));
1492
- }
1493
- return null;
1494
- };
1495
-
1496
- const FilterableDataGrid = props => {
1497
- const {
1498
- children,
1499
- onFilter
1500
- } = props;
1501
- const {
1502
- state,
1503
- data,
1504
- dispatch,
1505
- dataGridApiRef
1506
- } = useContext(DashboardContext);
1507
- const {
1508
- tableFilters
1509
- } = state;
1510
- const [filterModel, setFilterModel] = useState();
1511
- useEffect(() => {
1512
- setFilterModel(_objectSpread2(_objectSpread2({}, filterModel), {}, {
1513
- items: tableFilters
1514
- }));
1515
- }, [tableFilters]);
1516
- const updateChartFilters = filterModel => {
1517
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1518
- type: DashboardReducerActionType.FilterTableBatch,
1519
- filter: filterModel.items
1520
- });
1521
- };
1522
- if ( /*#__PURE__*/isValidElement(children)) {
1523
- var _children$props$apiRe;
1524
- const filterProps = {
1525
- apiRef: (_children$props$apiRe = children.props.apiRef) !== null && _children$props$apiRe !== void 0 ? _children$props$apiRe : dataGridApiRef,
1526
- rows: data || [],
1527
- filterModel,
1528
- onFilterModelChange: filterModel => {
1529
- if (onFilter) {
1530
- onFilter(filterModel);
1531
- }
1532
- updateChartFilters(filterModel);
1533
- }
1534
- };
1535
- return /*#__PURE__*/React.cloneElement(children, _objectSpread2({}, filterProps));
1536
- }
1537
- return null;
1538
- };
1539
-
1540
- const FilterablePieChart = props => {
1541
- var _tableFilters$find;
1542
- const {
1543
- children,
1544
- datagridCategoryDimFilter,
1545
- dimension,
1546
- group,
1547
- id: propsId,
1548
- isDimensionArray,
1549
- isResetable,
1550
- localeText,
1551
- onFilter
1552
- } = props;
1553
- const [_id] = useId();
1554
- const id = propsId !== null && propsId !== void 0 ? propsId : _id;
1555
- const ref = useRef();
1556
- const {
1557
- emptyChartTitle,
1558
- emptyChartSubtitle,
1559
- emptyChartResetLabel
1560
- } = _objectSpread2({}, localeText);
1561
- const {
1562
- data,
1563
- dispatch,
1564
- toggleUpdateContext,
1565
- state: {
1566
- tableFilters
1567
- }
1568
- } = useContext(DashboardContext);
1569
- const [ndxDimension, setNdxDimension] = useState();
1570
- const [ndxGroup, setNdxGroup] = useState();
1571
- useEffect(() => {
1572
- const computedNdxDimension = CrossfilterRegistry.get(data).dimension(dimension, isDimensionArray);
1573
- const computedNdxGroup = group ? group(computedNdxDimension) : computedNdxDimension.group();
1574
- setNdxDimension(computedNdxDimension);
1575
- setNdxGroup(computedNdxGroup);
1576
- return function cleanup() {
1577
- computedNdxDimension.filterAll();
1578
- };
1579
- }, [dimension, data, group]);
1580
- const [filters, setFilters] = useState([]);
1581
- const handleFilter = category => {
1582
- let newFilters;
1583
- if (filters.includes(category)) {
1584
- newFilters = filters.filter(f => f !== category);
1585
- } else {
1586
- newFilters = [...filters, category];
1587
- }
1588
- setFilters(newFilters);
1589
- if (newFilters.length) {
1590
- ndxDimension.filter(d => newFilters.includes(d));
1591
- } else {
1592
- ndxDimension.filterAll();
1593
- }
1594
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1595
- if (datagridCategoryDimFilter) {
1596
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1597
- type: DashboardReducerActionType.FilterTable,
1598
- filter: {
1599
- id: id,
1600
- field: datagridCategoryDimFilter.field,
1601
- operator: datagridCategoryDimFilter.operator,
1602
- value: newFilters
1603
- }
1604
- });
1605
- }
1606
- if (onFilter) {
1607
- onFilter(newFilters);
1608
- }
1609
- };
1610
- const resetFilters = () => {
1611
- setFilters([]);
1612
- ndxDimension.filterAll();
1613
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1614
- if (datagridCategoryDimFilter) {
1615
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1616
- type: DashboardReducerActionType.ResetFilter,
1617
- filter: {
1618
- id: id,
1619
- field: datagridCategoryDimFilter.field,
1620
- operator: datagridCategoryDimFilter.operator
1621
- }
1622
- });
1623
- }
1624
- if (onFilter) {
1625
- onFilter();
1626
- }
1627
- };
1628
- const updatedFilters = datagridCategoryDimFilter ? (_tableFilters$find = tableFilters.find(filter => filter.field === datagridCategoryDimFilter.field && filter.operator === datagridCategoryDimFilter.operator)) === null || _tableFilters$find === void 0 ? void 0 : _tableFilters$find.value : null;
1629
- useEffect(() => {
1630
- if (updatedFilters && updatedFilters !== filters && ndxDimension) {
1631
- setFilters(updatedFilters);
1632
- if (updatedFilters.length) {
1633
- ndxDimension.filter(d => updatedFilters.includes(d));
1634
- } else {
1635
- ndxDimension.filterAll();
1636
- }
1637
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1638
- }
1639
- }, [updatedFilters]);
1640
- const emptyComponent = /*#__PURE__*/React.createElement(ChartEmptyState, {
1641
- title: emptyChartTitle,
1642
- subtitle: emptyChartSubtitle,
1643
- resetLabel: emptyChartResetLabel,
1644
- onReset: resetFilters
1645
- });
1646
- const chartProps = useCategoricalChartAsListbox({
1647
- id,
1648
- ref: ref,
1649
- type: 'bar',
1650
- ndxGroup,
1651
- orientation: 'horizontal'
1652
- });
1653
- const legendProps = {
1654
- onLegendItemClick: datum => {
1655
- handleFilter(datum.data.key);
1656
- },
1657
- isLegendItemSelected: datum => {
1658
- return filters.length === 0 || filters.includes(datum.data.key);
1659
- },
1660
- legendItemRole: 'option',
1661
- role: 'group'
1662
- };
1663
- const filterProps = {
1664
- sliceProps: {
1665
- tabIndex: -1
1666
- },
1667
- sliceRole: 'option',
1668
- role: 'listbox',
1669
- chartProps,
1670
- legendProps,
1671
- chartRef: ref,
1672
- data: ndxGroup ? JSON.parse(JSON.stringify(ndxGroup.all())) : undefined,
1673
- emptyComponent,
1674
- id,
1675
- isSliceSelected: datum => {
1676
- return filters.length === 0 || filters.includes(datum.data.key);
1677
- },
1678
- onSliceClick: datum => {
1679
- handleFilter(datum.data.key);
1680
- },
1681
- onReset: isResetable ? resetFilters : undefined
1682
- };
1683
- if ( /*#__PURE__*/isValidElement(children)) {
1684
- return /*#__PURE__*/React.cloneElement(children, _objectSpread2({}, filterProps));
1685
- }
1686
- return null;
1687
- };
1688
-
1689
- const filter = (legendFilters, brushFilters) => d => {
1690
- if (legendFilters && legendFilters.length && brushFilters) {
1691
- return d[0] >= brushFilters.minX && d[0] <= brushFilters.maxX && d[1] >= brushFilters.minY && d[1] <= brushFilters.maxY && legendFilters.includes(d[2]);
1692
- } else if (legendFilters && legendFilters.length) {
1693
- return legendFilters.includes(d[2]);
1694
- } else if (brushFilters) {
1695
- return d[0] >= brushFilters.minX && d[0] <= brushFilters.maxX && d[1] >= brushFilters.minY && d[1] <= brushFilters.maxY;
1696
- } else {
1697
- return true;
1698
- }
1699
- };
1700
- const isFiltered = (legendFilters, brushFilters) => datum => {
1701
- if (legendFilters && legendFilters.length && brushFilters) {
1702
- return datum.data.key[0] >= brushFilters.minX && datum.data.key[0] <= brushFilters.maxX && datum.data.key[1] >= brushFilters.minY && datum.data.key[1] <= brushFilters.maxY && legendFilters.includes(datum.data.key[2]);
1703
- } else if (legendFilters && legendFilters.length) {
1704
- return legendFilters.includes(datum.data.key[2]);
1705
- } else if (brushFilters) {
1706
- return datum.data.key[0] >= brushFilters.minX && datum.data.key[0] <= brushFilters.maxX && datum.data.key[1] >= brushFilters.minY && datum.data.key[1] <= brushFilters.maxY;
1707
- } else {
1708
- return true;
1709
- }
1710
- };
1711
- const FilterableScatterPlot = props => {
1712
- const {
1713
- children,
1714
- datagridCoordinatesCategoryDimFilter,
1715
- dimension,
1716
- group,
1717
- id: propsId,
1718
- isDimensionArray,
1719
- isResetable,
1720
- localeText,
1721
- onFilter
1722
- } = props;
1723
- const [_id] = useId();
1724
- const id = propsId !== null && propsId !== void 0 ? propsId : _id;
1725
- const {
1726
- emptyChartTitle,
1727
- emptyChartSubtitle,
1728
- emptyChartResetLabel
1729
- } = _objectSpread2({}, localeText);
1730
- const {
1731
- data,
1732
- dispatch,
1733
- toggleUpdateContext
1734
- // state: { tableFilters },
1735
- } = useContext(DashboardContext);
1736
- const [ndxDimension, setNdxDimension] = useState();
1737
- const [ndxGroup, setNdxGroup] = useState();
1738
- useEffect(() => {
1739
- const computedNdxDimension = CrossfilterRegistry.get(data).dimension(dimension, isDimensionArray);
1740
- const computedNdxGroup = group ? group(computedNdxDimension) : computedNdxDimension.group();
1741
- setNdxDimension(computedNdxDimension);
1742
- setNdxGroup(computedNdxGroup);
1743
- return function cleanup() {
1744
- computedNdxDimension.filterAll();
1745
- };
1746
- }, [dimension, data, group]);
1747
- const [brushFilters, setBrushFilters] = useState();
1748
- const [legendFilters, setLegendFilters] = useState([]);
1749
- const handleBrushFilter = newFilters => {
1750
- setBrushFilters(newFilters);
1751
- ndxDimension.filter(d => filter(legendFilters, newFilters)(d));
1752
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1753
- if (datagridCoordinatesCategoryDimFilter) {
1754
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1755
- type: DashboardReducerActionType.FilterTable,
1756
- filter: {
1757
- id: `${id}-x`,
1758
- field: datagridCoordinatesCategoryDimFilter[0].field,
1759
- operator: datagridCoordinatesCategoryDimFilter[0].operator,
1760
- value: [newFilters.minX, newFilters.maxX]
1761
- }
1762
- });
1763
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1764
- type: DashboardReducerActionType.FilterTable,
1765
- filter: {
1766
- id: `${id}-y`,
1767
- field: datagridCoordinatesCategoryDimFilter[1].field,
1768
- operator: datagridCoordinatesCategoryDimFilter[1].operator,
1769
- value: [newFilters.minY, newFilters.maxY]
1770
- }
1771
- });
1772
- }
1773
- if (onFilter) {
1774
- onFilter(newFilters);
1775
- }
1776
- };
1777
- const handleLegendFilter = category => {
1778
- let newFilters;
1779
- if (legendFilters.includes(category)) {
1780
- newFilters = legendFilters.filter(f => f !== category);
1781
- } else {
1782
- newFilters = [...legendFilters, category];
1783
- }
1784
- setLegendFilters(newFilters);
1785
- ndxDimension.filter(d => filter(newFilters, brushFilters)(d));
1786
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1787
- if ((datagridCoordinatesCategoryDimFilter === null || datagridCoordinatesCategoryDimFilter === void 0 ? void 0 : datagridCoordinatesCategoryDimFilter.length) === 3) {
1788
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1789
- type: DashboardReducerActionType.FilterTable,
1790
- filter: {
1791
- id: `${id}-category`,
1792
- field: datagridCoordinatesCategoryDimFilter[2].field,
1793
- operator: datagridCoordinatesCategoryDimFilter[2].operator,
1794
- value: newFilters
1795
- }
1796
- });
1797
- }
1798
- if (onFilter) {
1799
- onFilter(newFilters);
1800
- }
1801
- };
1802
- const resetFilters = function () {
1803
- let brush = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
1804
- let legend = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1805
- if (brush) {
1806
- setBrushFilters(undefined);
1807
- }
1808
- if (legend) {
1809
- setLegendFilters([]);
1810
- }
1811
- ndxDimension.filter(d => filter(legend ? [] : legendFilters, brush ? undefined : brushFilters)(d));
1812
- toggleUpdateContext === null || toggleUpdateContext === void 0 ? void 0 : toggleUpdateContext();
1813
- if (datagridCoordinatesCategoryDimFilter) {
1814
- if (brush) {
1815
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1816
- type: DashboardReducerActionType.ResetFilter,
1817
- filter: {
1818
- id: `${id}-x`,
1819
- field: datagridCoordinatesCategoryDimFilter[0].field,
1820
- operator: datagridCoordinatesCategoryDimFilter[0].operator
1821
- }
1822
- });
1823
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1824
- type: DashboardReducerActionType.ResetFilter,
1825
- filter: {
1826
- id: `${id}-y`,
1827
- field: datagridCoordinatesCategoryDimFilter[1].field,
1828
- operator: datagridCoordinatesCategoryDimFilter[1].operator
1829
- }
1830
- });
1831
- }
1832
- if (legend && datagridCoordinatesCategoryDimFilter.length === 3) {
1833
- dispatch === null || dispatch === void 0 ? void 0 : dispatch({
1834
- type: DashboardReducerActionType.ResetFilter,
1835
- filter: {
1836
- id: `${id}-category`,
1837
- field: datagridCoordinatesCategoryDimFilter[2].field,
1838
- operator: datagridCoordinatesCategoryDimFilter[2].operator
1839
- }
1840
- });
1841
- }
1842
- }
1843
- if (onFilter) {
1844
- onFilter();
1845
- }
1846
- };
1847
-
1848
- // useEffect(() => {
1849
- // if (!datagridCoordinatesCategoryDimFilter) {
1850
- // return;
1851
- // }
1852
-
1853
- // const updatedXFilters = tableFilters.find(
1854
- // (filter) =>
1855
- // filter.field === datagridCoordinatesCategoryDimFilter[0].field &&
1856
- // filter.operator ===
1857
- // datagridCoordinatesCategoryDimFilter[0].operator
1858
- // )?.value;
1859
- // const updatedYFilters = tableFilters.find(
1860
- // (filter) =>
1861
- // filter.field === datagridCoordinatesCategoryDimFilter[1].field &&
1862
- // filter.operator ===
1863
- // datagridCoordinatesCategoryDimFilter[1].operator
1864
- // )?.value;
1865
- // console.log(updatedXFilters, updatedYFilters, brushFilters);
1866
- // const updatedFilters = {
1867
- // minX: Number(updatedXFilters[0]),
1868
- // maxX: Number(updatedXFilters[0]),
1869
- // minY: Number(updatedYFilters[1]),
1870
- // maxY: Number(updatedYFilters[1]),
1871
- // }
1872
- // if (updatedFilters && JSON.stringify(updatedFilters) !== JSON.stringify(brushFilters)) {
1873
- // }
1874
- // }, [tableFilters]);
1875
-
1876
- const emptyComponent = /*#__PURE__*/React.createElement(ChartEmptyState, {
1877
- title: emptyChartTitle,
1878
- subtitle: emptyChartSubtitle,
1879
- resetLabel: emptyChartResetLabel,
1880
- onReset: resetFilters
1881
- });
1882
- const legendProps = {
1883
- onLegendItemClick: datum => {
1884
- handleLegendFilter(datum.data.key);
1885
- },
1886
- isLegendItemSelected: datum => {
1887
- return legendFilters.length === 0 || legendFilters.includes(datum.data.key);
1888
- },
1889
- legendItemRole: 'option',
1890
- role: 'group'
1891
- };
1892
- const filterProps = {
1893
- isBrushable: true,
1894
- data: ndxGroup ? JSON.parse(JSON.stringify(ndxGroup.all())) : undefined,
1895
- dotRole: 'option',
1896
- role: 'listbox',
1897
- emptyComponent,
1898
- id,
1899
- legendProps,
1900
- onBrush: (selection, scaleX, scaleY) => {
1901
- if (selection) {
1902
- setBrushFilters({
1903
- minX: scaleX.invert(selection[0][0]),
1904
- minY: scaleY.invert(selection[1][1]),
1905
- maxX: scaleX.invert(selection[1][0]),
1906
- maxY: scaleY.invert(selection[0][1])
1907
- });
1908
- }
1909
- },
1910
- onBrushEnd: (selection, scaleX, scaleY) => {
1911
- if (selection && scaleX && scaleY) {
1912
- handleBrushFilter({
1913
- minX: scaleX.invert(selection[0][0]),
1914
- minY: scaleY.invert(selection[1][1]),
1915
- maxX: scaleX.invert(selection[1][0]),
1916
- maxY: scaleY.invert(selection[0][1])
1917
- });
1918
- } else {
1919
- resetFilters(true, false);
1920
- }
1921
- },
1922
- onReset: isResetable ? resetFilters : undefined,
1923
- isDotSelected: datum => isFiltered(legendFilters, brushFilters)(datum)
1924
- };
1925
- if ( /*#__PURE__*/isValidElement(children)) {
1926
- return /*#__PURE__*/React.cloneElement(children, _objectSpread2({}, filterProps));
1927
- }
1928
- return null;
1929
- };
1930
-
1931
- const WithFilters = props => {
1932
- if (isComponent('DataGrid')(props.children)) {
1933
- return /*#__PURE__*/React.createElement(FilterableDataGrid, props);
1934
- }
1935
- const {
1936
- dimension
1937
- } = props;
1938
- if (!dimension) {
1939
- return null;
1940
- }
1941
- if (isComponent('BarChart')(props.children)) {
1942
- return /*#__PURE__*/React.createElement(FilterableBarChart, _extends({}, props, {
1943
- dimension: dimension
1944
- }));
1945
- } else if (isComponent('PieChart')(props.children)) {
1946
- return /*#__PURE__*/React.createElement(FilterablePieChart, _extends({}, props, {
1947
- dimension: dimension
1948
- }));
1949
- } else if (isComponent('ScatterPlot')(props.children)) {
1950
- return /*#__PURE__*/React.createElement(FilterableScatterPlot, _extends({}, props, {
1951
- dimension: dimension
1952
- }));
1953
- }
1954
- return /*#__PURE__*/React.isValidElement(props.children) ? props.children : null;
1955
- };
1956
-
1957
- export { COUNT, ChartEmptyState, Dashboard, DashboardContext, DashboardReducer, DashboardReducerActionType, PdfExportButton, SUM, TimeSeriesBarChart, TimeSeriesBarChartSize, TimeSeriesBarChartTheme, WithFilters, groupReduceSum, initialState };
16
+ export { COUNT, SUM, groupReduceSum };
1958
17
  //# sourceMappingURL=index.js.map