-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathwidgetViewerModal.tsx
1228 lines (1162 loc) · 41.5 KB
/
widgetViewerModal.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Fragment, memo, useEffect, useMemo, useRef, useState} from 'react';
import {components} from 'react-select';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/react';
import {truncate} from '@sentry/utils';
import type {DataZoomComponentOption} from 'echarts';
import {Location} from 'history';
import cloneDeep from 'lodash/cloneDeep';
import isEqual from 'lodash/isEqual';
import trimStart from 'lodash/trimStart';
import moment from 'moment';
import {fetchTotalCount} from 'sentry/actionCreators/events';
import {ModalRenderProps} from 'sentry/actionCreators/modal';
import {Client} from 'sentry/api';
import {Alert} from 'sentry/components/alert';
import {Button} from 'sentry/components/button';
import ButtonBar from 'sentry/components/buttonBar';
import SelectControl from 'sentry/components/forms/controls/selectControl';
import Option from 'sentry/components/forms/controls/selectOption';
import GridEditable, {
COL_WIDTH_UNDEFINED,
GridColumnOrder,
} from 'sentry/components/gridEditable';
import Pagination from 'sentry/components/pagination';
import QuestionTooltip from 'sentry/components/questionTooltip';
import {parseSearch} from 'sentry/components/searchSyntax/parser';
import HighlightQuery from 'sentry/components/searchSyntax/renderer';
import {t, tct} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import {Organization, PageFilters, SelectValue} from 'sentry/types';
import {Series} from 'sentry/types/echarts';
import {defined} from 'sentry/utils';
import {trackAnalytics} from 'sentry/utils/analytics';
import {getUtcDateString} from 'sentry/utils/dates';
import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
import EventView from 'sentry/utils/discover/eventView';
import {
AggregationOutputType,
isAggregateField,
isEquation,
isEquationAlias,
} from 'sentry/utils/discover/fields';
import {createOnDemandFilterWarning} from 'sentry/utils/onDemandMetrics';
import {hasOnDemandMetricWidgetFeature} from 'sentry/utils/onDemandMetrics/features';
import parseLinkHeader from 'sentry/utils/parseLinkHeader';
import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
import {MEPSettingProvider} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
import {decodeInteger, decodeList, decodeScalar} from 'sentry/utils/queryString';
import useApi from 'sentry/utils/useApi';
import {useLocation} from 'sentry/utils/useLocation';
import useProjects from 'sentry/utils/useProjects';
import useRouter from 'sentry/utils/useRouter';
import withPageFilters from 'sentry/utils/withPageFilters';
import {
DashboardFilters,
DisplayType,
Widget,
WidgetType,
} from 'sentry/views/dashboards/types';
import {
dashboardFiltersToString,
eventViewFromWidget,
getColoredWidgetIndicator,
getFieldsFromEquations,
getNumEquations,
getWidgetDiscoverUrl,
getWidgetIssueUrl,
getWidgetReleasesUrl,
} from 'sentry/views/dashboards/utils';
import {
SESSION_DURATION_ALERT,
WidgetDescription,
} from 'sentry/views/dashboards/widgetCard';
import WidgetCardChart, {
AugmentedEChartDataZoomHandler,
SLIDER_HEIGHT,
} from 'sentry/views/dashboards/widgetCard/chart';
import {
DashboardsMEPConsumer,
DashboardsMEPProvider,
useDashboardsMEPContext,
} from 'sentry/views/dashboards/widgetCard/dashboardsMEPContext';
import {GenericWidgetQueriesChildrenProps} from 'sentry/views/dashboards/widgetCard/genericWidgetQueries';
import IssueWidgetQueries from 'sentry/views/dashboards/widgetCard/issueWidgetQueries';
import ReleaseWidgetQueries from 'sentry/views/dashboards/widgetCard/releaseWidgetQueries';
import {WidgetCardChartContainer} from 'sentry/views/dashboards/widgetCard/widgetCardChartContainer';
import WidgetQueries from 'sentry/views/dashboards/widgetCard/widgetQueries';
import {decodeColumnOrder} from 'sentry/views/discover/utils';
import {OrganizationContext} from 'sentry/views/organizationContext';
import {MetricsDataSwitcher} from 'sentry/views/performance/landing/metricsDataSwitcher';
import {WidgetViewerQueryField} from './widgetViewerModal/utils';
import {
renderDiscoverGridHeaderCell,
renderGridBodyCell,
renderIssueGridHeaderCell,
renderReleaseGridHeaderCell,
} from './widgetViewerModal/widgetViewerTableCell';
export interface WidgetViewerModalOptions {
organization: Organization;
widget: Widget;
dashboardFilters?: DashboardFilters;
onEdit?: () => void;
pageLinks?: string;
seriesData?: Series[];
seriesResultsType?: Record<string, AggregationOutputType>;
tableData?: TableDataWithTitle[];
totalIssuesCount?: string;
}
interface Props extends ModalRenderProps, WidgetViewerModalOptions {
organization: Organization;
selection: PageFilters;
}
const FULL_TABLE_ITEM_LIMIT = 20;
const HALF_TABLE_ITEM_LIMIT = 10;
const HALF_CONTAINER_HEIGHT = 300;
const EMPTY_QUERY_NAME = '(Empty Query Condition)';
const shouldWidgetCardChartMemo = (prevProps, props) => {
const selectionMatches = props.selection === prevProps.selection;
const sortMatches =
props.location.query[WidgetViewerQueryField.SORT] ===
prevProps.location.query[WidgetViewerQueryField.SORT];
const chartZoomOptionsMatches = isEqual(
props.chartZoomOptions,
prevProps.chartZoomOptions
);
const isNotTopNWidget =
props.widget.displayType !== DisplayType.TOP_N && !defined(props.widget.limit);
return selectionMatches && chartZoomOptionsMatches && (sortMatches || isNotTopNWidget);
};
// WidgetCardChartContainer and WidgetCardChart rerenders if selection was changed.
// This is required because we want to prevent ECharts interactions from causing
// unnecessary rerenders which can break legends and zoom functionality.
const MemoizedWidgetCardChartContainer = memo(
WidgetCardChartContainer,
shouldWidgetCardChartMemo
);
const MemoizedWidgetCardChart = memo(WidgetCardChart, shouldWidgetCardChartMemo);
async function fetchDiscoverTotal(
api: Client,
organization: Organization,
location: Location,
eventView: EventView
): Promise<string | undefined> {
if (!eventView.isValid()) {
return undefined;
}
try {
const total = await fetchTotalCount(
api,
organization.slug,
eventView.getEventsAPIPayload(location)
);
return total.toLocaleString();
} catch (err) {
Sentry.captureException(err);
return undefined;
}
}
function WidgetViewerModal(props: Props) {
const {
organization,
widget,
selection,
Footer,
Body,
Header,
closeModal,
onEdit,
seriesData,
tableData,
totalIssuesCount,
pageLinks: defaultPageLinks,
seriesResultsType,
dashboardFilters,
} = props;
const location = useLocation();
const {projects} = useProjects();
const router = useRouter();
const shouldShowSlider = organization.features.includes('widget-viewer-modal-minimap');
// TODO(Tele-Team): Re-enable this when we have a better way to determine if the data is transaction only
// let widgetContentLoadingStatus: boolean | undefined = undefined;
// Get widget zoom from location
// We use the start and end query params for just the initial state
const start = decodeScalar(location.query[WidgetViewerQueryField.START]);
const end = decodeScalar(location.query[WidgetViewerQueryField.END]);
const isTableWidget = widget.displayType === DisplayType.TABLE;
const hasSessionDuration = widget.queries.some(query =>
query.aggregates.some(aggregate => aggregate.includes('session.duration'))
);
const locationPageFilter = useMemo(
() =>
start && end
? {
...selection,
datetime: {start, end, period: null, utc: null},
}
: selection,
[start, end, selection]
);
const [chartUnmodified, setChartUnmodified] = useState<boolean>(true);
const [chartZoomOptions, setChartZoomOptions] = useState<DataZoomComponentOption>({
start: 0,
end: 100,
});
// We wrap the modalChartSelection in a useRef because we do not want to recalculate this value
// (which would cause an unnecessary rerender on calculation) except for the initial load.
// We use this for when a user visit a widget viewer url directly.
const [modalTableSelection, setModalTableSelection] =
useState<PageFilters>(locationPageFilter);
const modalChartSelection = useRef(modalTableSelection);
// Detect when a user clicks back and set the PageFilter state to match the location
// We need to use useEffect to prevent infinite looping rerenders due to the setModalTableSelection call
useEffect(() => {
if (location.action === 'POP') {
setModalTableSelection(locationPageFilter);
if (start && end) {
setChartZoomOptions({
startValue: moment.utc(start).unix() * 1000,
endValue: moment.utc(end).unix() * 1000,
});
} else {
setChartZoomOptions({start: 0, end: 100});
}
}
}, [end, location, locationPageFilter, start]);
// Get legends toggle settings from location
// We use the legend query params for just the initial state
const [disabledLegends, setDisabledLegends] = useState<{[key: string]: boolean}>(
decodeList(location.query[WidgetViewerQueryField.LEGEND]).reduce((acc, legend) => {
acc[legend] = false;
return acc;
}, {})
);
const [totalResults, setTotalResults] = useState<string | undefined>();
// Get query selection settings from location
const selectedQueryIndex =
decodeInteger(location.query[WidgetViewerQueryField.QUERY]) ?? 0;
// Get pagination settings from location
const page = decodeInteger(location.query[WidgetViewerQueryField.PAGE]) ?? 0;
const cursor = decodeScalar(location.query[WidgetViewerQueryField.CURSOR]);
// Get table column widths from location
const widths = decodeList(location.query[WidgetViewerQueryField.WIDTH]);
// Get table sort settings from location
const sort = decodeScalar(location.query[WidgetViewerQueryField.SORT]);
const sortedQueries = cloneDeep(
sort ? widget.queries.map(query => ({...query, orderby: sort})) : widget.queries
);
// Top N widget charts (including widgets with limits) results rely on the sorting of the query
// Set the orderby of the widget chart to match the location query params
const primaryWidget =
widget.displayType === DisplayType.TOP_N || widget.limit !== undefined
? {...widget, queries: sortedQueries}
: widget;
const api = useApi();
// Create Table widget
const tableWidget = {
...cloneDeep({...widget, queries: [sortedQueries[selectedQueryIndex]]}),
displayType: DisplayType.TABLE,
};
const {aggregates, columns} = tableWidget.queries[0];
const {orderby} = widget.queries[0];
const order = orderby.startsWith('-');
const rawOrderby = trimStart(orderby, '-');
const fields = defined(tableWidget.queries[0].fields)
? tableWidget.queries[0].fields
: [...columns, ...aggregates];
// Some Discover Widgets (Line, Area, Bar) allow the user to specify an orderby
// that is not explicitly selected as an aggregate or column. We need to explicitly
// include the orderby in the table widget aggregates and columns otherwise
// eventsv2 will complain about sorting on an unselected field.
if (
widget.widgetType === WidgetType.DISCOVER &&
orderby &&
!isEquationAlias(rawOrderby) &&
!fields.includes(rawOrderby)
) {
fields.push(rawOrderby);
[tableWidget, primaryWidget].forEach(aggregatesAndColumns => {
if (isAggregateField(rawOrderby) || isEquation(rawOrderby)) {
aggregatesAndColumns.queries.forEach(query => {
if (!query.aggregates.includes(rawOrderby)) {
query.aggregates.push(rawOrderby);
}
});
} else {
aggregatesAndColumns.queries.forEach(query => {
if (!query.columns.includes(rawOrderby)) {
query.columns.push(rawOrderby);
}
});
}
});
}
// Need to set the orderby of the eventsv2 query to equation[index] format
// since eventsv2 does not accept the raw equation as a valid sort payload
if (isEquation(rawOrderby) && tableWidget.queries[0].orderby === orderby) {
tableWidget.queries[0].orderby = `${order ? '-' : ''}equation[${
getNumEquations(fields) - 1
}]`;
}
// Default table columns for visualizations that don't have a column setting
const shouldReplaceTableColumns =
[
DisplayType.AREA,
DisplayType.LINE,
DisplayType.BIG_NUMBER,
DisplayType.BAR,
].includes(widget.displayType) &&
widget.widgetType &&
[WidgetType.DISCOVER, WidgetType.RELEASE].includes(widget.widgetType) &&
!defined(widget.limit);
// Updates fields by adding any individual terms from equation fields as a column
if (!isTableWidget) {
const equationFields = getFieldsFromEquations(fields);
equationFields.forEach(term => {
if (isAggregateField(term) && !aggregates.includes(term)) {
aggregates.unshift(term);
}
if (!isAggregateField(term) && !columns.includes(term)) {
columns.unshift(term);
}
});
}
// Add any group by columns into table fields if missing
columns.forEach(column => {
if (!fields.includes(column)) {
fields.unshift(column);
}
});
if (shouldReplaceTableColumns) {
switch (widget.widgetType) {
case WidgetType.DISCOVER:
if (fields.length === 1) {
tableWidget.queries[0].orderby =
tableWidget.queries[0].orderby || `-${fields[0]}`;
}
fields.unshift('title');
columns.unshift('title');
break;
case WidgetType.RELEASE:
fields.unshift('release');
columns.unshift('release');
break;
default:
break;
}
}
const eventView = eventViewFromWidget(
tableWidget.title,
tableWidget.queries[0],
modalTableSelection
);
let columnOrder = decodeColumnOrder(
fields.map(field => ({
field,
}))
);
const columnSortBy = eventView.getSorts();
columnOrder = columnOrder.map((column, index) => ({
...column,
width: parseInt(widths[index], 10) || -1,
}));
const getOnDemandFilterWarning = createOnDemandFilterWarning(
t(
'We don’t routinely collect metrics from this property. As such, historical data may be limited.'
)
);
const queryOptions = sortedQueries.map(({name, conditions}, index) => {
// Creates the highlighted query elements to be used in the Query Select
const dashboardFiltersString = dashboardFiltersToString(dashboardFilters);
const parsedQuery =
!name && !!conditions
? parseSearch(
conditions +
(dashboardFiltersString === '' ? '' : ` ${dashboardFiltersString}`),
{
getFilterTokenWarning: hasOnDemandMetricWidgetFeature(organization)
? getOnDemandFilterWarning
: undefined,
}
)
: null;
const getHighlightedQuery = (
highlightedContainerProps: React.ComponentProps<typeof HighlightContainer>
) => {
return parsedQuery !== null ? (
<HighlightContainer {...highlightedContainerProps}>
<HighlightQuery parsedQuery={parsedQuery} />
</HighlightContainer>
) : undefined;
};
return {
label: truncate(name || conditions, 120),
value: index,
getHighlightedQuery,
};
});
const onResizeColumn = (columnIndex: number, nextColumn: GridColumnOrder) => {
const newWidth = nextColumn.width ? Number(nextColumn.width) : COL_WIDTH_UNDEFINED;
const newWidths: number[] = new Array(Math.max(columnIndex, widths.length)).fill(
COL_WIDTH_UNDEFINED
);
widths.forEach((width, index) => (newWidths[index] = parseInt(width, 10)));
newWidths[columnIndex] = newWidth;
router.replace({
pathname: location.pathname,
query: {
...location.query,
[WidgetViewerQueryField.WIDTH]: newWidths,
},
});
};
// Get discover result totals
useEffect(() => {
const getDiscoverTotals = async () => {
if (widget.widgetType === WidgetType.DISCOVER) {
setTotalResults(await fetchDiscoverTotal(api, organization, location, eventView));
}
};
getDiscoverTotals();
// Disabling this for now since this effect should only run on initial load and query index changes
// Including all exhaustive deps would cause fetchDiscoverTotal on nearly every update
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedQueryIndex]);
function onLegendSelectChanged({selected}: {selected: Record<string, boolean>}) {
setDisabledLegends(selected);
router.replace({
pathname: location.pathname,
query: {
...location.query,
[WidgetViewerQueryField.LEGEND]: Object.keys(selected).filter(
key => !selected[key]
),
},
});
trackAnalytics('dashboards_views.widget_viewer.toggle_legend', {
organization,
widget_type: widget.widgetType ?? WidgetType.DISCOVER,
display_type: widget.displayType,
});
}
function DiscoverTable({
tableResults,
loading,
pageLinks,
}: GenericWidgetQueriesChildrenProps) {
const {isMetricsData} = useDashboardsMEPContext();
const links = parseLinkHeader(pageLinks ?? null);
const isFirstPage = links.previous?.results === false;
return (
<Fragment>
<GridEditable
isLoading={loading}
data={tableResults?.[0]?.data ?? []}
columnOrder={columnOrder}
columnSortBy={columnSortBy}
grid={{
renderHeadCell: renderDiscoverGridHeaderCell({
...props,
location,
widget: tableWidget,
tableData: tableResults?.[0],
onHeaderClick: () => {
if (
[DisplayType.TOP_N, DisplayType.TABLE].includes(widget.displayType) ||
defined(widget.limit)
) {
setChartUnmodified(false);
}
},
isMetricsData,
}) as (column: GridColumnOrder, columnIndex: number) => React.ReactNode,
renderBodyCell: renderGridBodyCell({
...props,
location,
tableData: tableResults?.[0],
isFirstPage,
projects,
eventView,
}),
onResizeColumn,
}}
location={location}
/>
{(links?.previous?.results || links?.next?.results) && (
<Pagination
pageLinks={pageLinks}
onCursor={newCursor => {
router.replace({
pathname: location.pathname,
query: {
...location.query,
[WidgetViewerQueryField.CURSOR]: newCursor,
},
});
if (widget.displayType === DisplayType.TABLE) {
setChartUnmodified(false);
}
trackAnalytics('dashboards_views.widget_viewer.paginate', {
organization,
widget_type: WidgetType.DISCOVER,
display_type: widget.displayType,
});
}}
/>
)}
</Fragment>
);
}
const renderIssuesTable = ({
tableResults,
loading,
pageLinks,
totalCount,
}: GenericWidgetQueriesChildrenProps) => {
if (totalResults === undefined && totalCount) {
setTotalResults(totalCount);
}
const links = parseLinkHeader(pageLinks ?? null);
return (
<Fragment>
<GridEditable
isLoading={loading}
data={tableResults?.[0]?.data ?? []}
columnOrder={columnOrder}
columnSortBy={columnSortBy}
grid={{
renderHeadCell: renderIssueGridHeaderCell({
location,
organization,
selection,
widget: tableWidget,
onHeaderClick: () => {
setChartUnmodified(false);
},
}) as (column: GridColumnOrder, columnIndex: number) => React.ReactNode,
renderBodyCell: renderGridBodyCell({
location,
organization,
selection,
widget: tableWidget,
}),
onResizeColumn,
}}
location={location}
/>
{(links?.previous?.results || links?.next?.results) && (
<Pagination
pageLinks={pageLinks}
onCursor={(nextCursor, _path, _query, delta) => {
let nextPage = isNaN(page) ? delta : page + delta;
let newCursor = nextCursor;
// unset cursor and page when we navigate back to the first page
// also reset cursor if somehow the previous button is enabled on
// first page and user attempts to go backwards
if (nextPage <= 0) {
newCursor = undefined;
nextPage = 0;
}
router.replace({
pathname: location.pathname,
query: {
...location.query,
[WidgetViewerQueryField.CURSOR]: newCursor,
[WidgetViewerQueryField.PAGE]: nextPage,
},
});
if (widget.displayType === DisplayType.TABLE) {
setChartUnmodified(false);
}
trackAnalytics('dashboards_views.widget_viewer.paginate', {
organization,
widget_type: WidgetType.ISSUE,
display_type: widget.displayType,
});
}}
/>
)}
</Fragment>
);
};
const renderReleaseTable: ReleaseWidgetQueries['props']['children'] = ({
tableResults,
loading,
pageLinks,
}) => {
const links = parseLinkHeader(pageLinks ?? null);
const isFirstPage = links.previous?.results === false;
return (
<Fragment>
<GridEditable
isLoading={loading}
data={tableResults?.[0]?.data ?? []}
columnOrder={columnOrder}
columnSortBy={columnSortBy}
grid={{
renderHeadCell: renderReleaseGridHeaderCell({
...props,
location,
widget: tableWidget,
tableData: tableResults?.[0],
onHeaderClick: () => {
if (
[DisplayType.TOP_N, DisplayType.TABLE].includes(widget.displayType) ||
defined(widget.limit)
) {
setChartUnmodified(false);
}
},
}) as (column: GridColumnOrder, columnIndex: number) => React.ReactNode,
renderBodyCell: renderGridBodyCell({
...props,
location,
tableData: tableResults?.[0],
isFirstPage,
}),
onResizeColumn,
}}
location={location}
/>
{!tableWidget.queries[0].orderby.match(/^-?release$/) &&
(links?.previous?.results || links?.next?.results) && (
<Pagination
pageLinks={pageLinks}
onCursor={newCursor => {
router.replace({
pathname: location.pathname,
query: {
...location.query,
[WidgetViewerQueryField.CURSOR]: newCursor,
},
});
trackAnalytics('dashboards_views.widget_viewer.paginate', {
organization,
widget_type: WidgetType.RELEASE,
display_type: widget.displayType,
});
}}
/>
)}
</Fragment>
);
};
const onZoom: AugmentedEChartDataZoomHandler = (evt, chart) => {
// @ts-expect-error getModel() is private but we need this to retrieve datetime values of zoomed in region
const model = chart.getModel();
const {seriesStart, seriesEnd} = evt;
let startValue, endValue;
startValue = model._payload.batch?.[0].startValue;
endValue = model._payload.batch?.[0].endValue;
const seriesStartTime = seriesStart ? new Date(seriesStart).getTime() : undefined;
const seriesEndTime = seriesEnd ? new Date(seriesEnd).getTime() : undefined;
// Slider zoom events don't contain the raw date time value, only the percentage
// We use the percentage with the start and end of the series to calculate the adjusted zoom
if (startValue === undefined || endValue === undefined) {
if (seriesStartTime && seriesEndTime) {
const diff = seriesEndTime - seriesStartTime;
startValue = diff * model._payload.start * 0.01 + seriesStartTime;
endValue = diff * model._payload.end * 0.01 + seriesStartTime;
} else {
return;
}
}
setChartZoomOptions({startValue, endValue});
const newStart = getUtcDateString(moment.utc(startValue));
const newEnd = getUtcDateString(moment.utc(endValue));
setModalTableSelection({
...modalTableSelection,
datetime: {
...modalTableSelection.datetime,
start: newStart,
end: newEnd,
period: null,
},
});
router.push({
pathname: location.pathname,
query: {
...location.query,
[WidgetViewerQueryField.START]: newStart,
[WidgetViewerQueryField.END]: newEnd,
},
});
trackAnalytics('dashboards_views.widget_viewer.zoom', {
organization,
widget_type: widget.widgetType ?? WidgetType.DISCOVER,
display_type: widget.displayType,
});
};
function renderWidgetViewerTable() {
switch (widget.widgetType) {
case WidgetType.ISSUE:
if (tableData && chartUnmodified && widget.displayType === DisplayType.TABLE) {
return renderIssuesTable({
tableResults: tableData,
loading: false,
errorMessage: undefined,
pageLinks: defaultPageLinks,
totalCount: totalIssuesCount,
});
}
return (
<IssueWidgetQueries
api={api}
organization={organization}
widget={tableWidget}
selection={modalTableSelection}
limit={
widget.displayType === DisplayType.TABLE
? FULL_TABLE_ITEM_LIMIT
: HALF_TABLE_ITEM_LIMIT
}
cursor={cursor}
dashboardFilters={dashboardFilters}
>
{renderIssuesTable}
</IssueWidgetQueries>
);
case WidgetType.RELEASE:
if (tableData && chartUnmodified && widget.displayType === DisplayType.TABLE) {
return renderReleaseTable({
tableResults: tableData,
loading: false,
pageLinks: defaultPageLinks,
});
}
return (
<ReleaseWidgetQueries
api={api}
organization={organization}
widget={tableWidget}
selection={modalTableSelection}
limit={
widget.displayType === DisplayType.TABLE
? FULL_TABLE_ITEM_LIMIT
: HALF_TABLE_ITEM_LIMIT
}
cursor={cursor}
dashboardFilters={dashboardFilters}
>
{renderReleaseTable}
</ReleaseWidgetQueries>
);
case WidgetType.DISCOVER:
default:
if (tableData && chartUnmodified && widget.displayType === DisplayType.TABLE) {
return (
<DiscoverTable
tableResults={tableData}
loading={false}
pageLinks={defaultPageLinks}
/>
);
}
return (
<WidgetQueries
api={api}
organization={organization}
widget={tableWidget}
selection={modalTableSelection}
limit={
widget.displayType === DisplayType.TABLE
? FULL_TABLE_ITEM_LIMIT
: HALF_TABLE_ITEM_LIMIT
}
cursor={cursor}
dashboardFilters={dashboardFilters}
>
{({tableResults, loading, pageLinks}) => {
// TODO(Tele-Team): Re-enable this when we have a better way to determine if the data is transaction only
// small hack that improves the concurrency render of the warning triangle
// widgetContentLoadingStatus = loading;
return (
<DiscoverTable
tableResults={tableResults}
loading={loading}
pageLinks={pageLinks}
/>
);
}}
</WidgetQueries>
);
}
}
function renderWidgetViewer() {
return (
<Fragment>
{hasSessionDuration && SESSION_DURATION_ALERT}
{widget.displayType !== DisplayType.TABLE && (
<Container
height={
widget.displayType !== DisplayType.BIG_NUMBER
? HALF_CONTAINER_HEIGHT +
(shouldShowSlider &&
[
DisplayType.AREA,
DisplayType.LINE,
DisplayType.BAR,
DisplayType.TOP_N,
].includes(widget.displayType)
? SLIDER_HEIGHT
: 0)
: null
}
>
{(!!seriesData || !!tableData) && chartUnmodified ? (
<MemoizedWidgetCardChart
timeseriesResults={seriesData}
timeseriesResultsTypes={seriesResultsType}
tableResults={tableData}
errorMessage={undefined}
loading={false}
location={location}
widget={widget}
selection={selection}
router={router}
organization={organization}
onZoom={onZoom}
onLegendSelectChanged={onLegendSelectChanged}
legendOptions={{selected: disabledLegends}}
expandNumbers
showSlider={shouldShowSlider}
noPadding
chartZoomOptions={chartZoomOptions}
/>
) : (
<MemoizedWidgetCardChartContainer
location={location}
api={api}
organization={organization}
selection={modalChartSelection.current}
dashboardFilters={dashboardFilters}
// Top N charts rely on the orderby of the table
widget={primaryWidget}
onZoom={onZoom}
onLegendSelectChanged={onLegendSelectChanged}
legendOptions={{selected: disabledLegends}}
expandNumbers
showSlider={shouldShowSlider}
noPadding
chartZoomOptions={chartZoomOptions}
/>
)}
</Container>
)}
{widget.queries.length > 1 && (
<Alert type="info" showIcon>
{t(
'This widget was built with multiple queries. Table data can only be displayed for one query at a time. To edit any of the queries, edit the widget.'
)}
</Alert>
)}
{(widget.queries.length > 1 || widget.queries[0].conditions) && (
<QueryContainer>
<SelectControl
value={selectedQueryIndex}
options={queryOptions}
onChange={(option: SelectValue<number>) => {
router.replace({
pathname: location.pathname,
query: {
...location.query,
[WidgetViewerQueryField.QUERY]: option.value,
[WidgetViewerQueryField.PAGE]: undefined,
[WidgetViewerQueryField.CURSOR]: undefined,
},
});
trackAnalytics('dashboards_views.widget_viewer.select_query', {
organization,
widget_type: widget.widgetType ?? WidgetType.DISCOVER,
display_type: widget.displayType,
});
}}
components={{
// Replaces the displayed selected value
SingleValue: containerProps => {
return (
<components.SingleValue
{...containerProps}
// Overwrites some of the default styling that interferes with highlighted query text
getStyles={() => ({
wordBreak: 'break-word',
flex: 1,
display: 'flex',
padding: `0 ${space(0.5)}`,
})}
>
{queryOptions[selectedQueryIndex].getHighlightedQuery({
display: 'block',
}) ??
(queryOptions[selectedQueryIndex].label || (
<EmptyQueryContainer>{EMPTY_QUERY_NAME}</EmptyQueryContainer>
))}
</components.SingleValue>
);
},
// Replaces the dropdown options
Option: containerProps => {
const highlightedQuery = containerProps.data.getHighlightedQuery({
display: 'flex',
});
return (
<Option
{...(highlightedQuery
? {
...containerProps,
label: highlightedQuery,
}
: containerProps.label
? containerProps
: {
...containerProps,
label: (
<EmptyQueryContainer>
{EMPTY_QUERY_NAME}
</EmptyQueryContainer>
),
})}
/>
);
},
// Hide the dropdown indicator if there is only one option
...(widget.queries.length < 2 ? {IndicatorsContainer: _ => null} : {}),
}}
isSearchable={false}
isDisabled={widget.queries.length < 2}
/>
{widget.queries.length === 1 && (
<StyledQuestionTooltip
title={t('To edit this query, you must edit the widget.')}
size="sm"
/>
)}
</QueryContainer>
)}
{renderWidgetViewerTable()}
</Fragment>
);
}
return (
<Fragment>
<OrganizationContext.Provider value={organization}>
<DashboardsMEPProvider>
<MetricsCardinalityProvider organization={organization} location={location}>
<MetricsDataSwitcher
organization={organization}
eventView={eventView}
location={location}
hideLoadingIndicator
>