-
Notifications
You must be signed in to change notification settings - Fork 394
Expand file tree
/
Copy pathDBEditTimeChartForm.tsx
More file actions
1792 lines (1709 loc) · 56.6 KB
/
DBEditTimeChartForm.tsx
File metadata and controls
1792 lines (1709 loc) · 56.6 KB
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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Control,
Controller,
FieldErrors,
Path,
useFieldArray,
useForm,
UseFormClearErrors,
UseFormSetValue,
useWatch,
} from 'react-hook-form';
import { NativeSelect, NumberInput } from 'react-hook-form-mantine';
import z from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { tcFromSource } from '@hyperdx/common-utils/dist/core/metadata';
import {
isBuilderChartConfig,
isRawSqlChartConfig,
isRawSqlSavedChartConfig,
} from '@hyperdx/common-utils/dist/guards';
import {
ChartAlertBaseSchema,
ChartConfigWithDateRange,
ChartConfigWithOptTimestamp,
DateRange,
DisplayType,
Filter,
MetricsDataType,
SavedChartConfig,
SelectList,
SourceKind,
TSource,
validateAlertScheduleOffsetMinutes,
} from '@hyperdx/common-utils/dist/types';
import {
Accordion,
ActionIcon,
Box,
Button,
Center,
Divider,
Flex,
Group,
List,
Menu,
Paper,
SegmentedControl,
Stack,
Switch,
Tabs,
Text,
Textarea,
} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import { notifications } from '@mantine/notifications';
import {
IconArrowDown,
IconArrowUp,
IconBell,
IconChartLine,
IconChartPie,
IconCirclePlus,
IconCode,
IconDotsVertical,
IconLayoutGrid,
IconList,
IconMarkdown,
IconNumbers,
IconPlayerPlay,
IconTable,
IconTrash,
IconX,
} from '@tabler/icons-react';
import { SortingState } from '@tanstack/react-table';
import {
AGG_FNS,
buildTableRowSearchUrl,
convertToNumberChartConfig,
convertToPieChartConfig,
convertToTableChartConfig,
convertToTimeChartConfig,
getPreviousDateRange,
} from '@/ChartUtils';
import { AlertChannelForm, getAlertReferenceLines } from '@/components/Alerts';
import ChartSQLPreview from '@/components/ChartSQLPreview';
import DBTableChart from '@/components/DBTableChart';
import { DBTimeChart } from '@/components/DBTimeChart';
import SearchWhereInput, {
getStoredLanguage,
} from '@/components/SearchInput/SearchWhereInput';
import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor';
import { TimePicker } from '@/components/TimePicker';
import { IS_LOCAL_MODE } from '@/config';
import { GranularityPickerControlled } from '@/GranularityPicker';
import { useFetchMetricMetadata } from '@/hooks/useFetchMetricMetadata';
import {
parseAttributeKeysFromSuggestions,
useFetchMetricResourceAttrs,
} from '@/hooks/useFetchMetricResourceAttrs';
import { getFirstTimestampValueExpression, useSource } from '@/source';
import {
getMetricTableName,
optionsToSelectData,
orderByStringToSortingState,
sortingStateToOrderByString,
} from '@/utils';
import {
ALERT_CHANNEL_OPTIONS,
DEFAULT_TILE_ALERT,
extendDateRangeToInterval,
intervalToGranularity,
intervalToMinutes,
normalizeNoOpAlertScheduleFields,
TILE_ALERT_INTERVAL_OPTIONS,
TILE_ALERT_THRESHOLD_TYPE_OPTIONS,
} from '@/utils/alerts';
import HDXMarkdownChart from '../HDXMarkdownChart';
import RawSqlChartEditor from './ChartEditor/RawSqlChartEditor';
import {
ChartEditorFormState,
SavedChartConfigWithSelectArray,
} from './ChartEditor/types';
import {
convertFormStateToChartConfig,
convertFormStateToSavedChartConfig,
convertSavedChartConfigToFormState,
isRawSqlDisplayType,
validateChartForm,
} from './ChartEditor/utils';
import { ErrorBoundary } from './Error/ErrorBoundary';
import MVOptimizationIndicator from './MaterializedViews/MVOptimizationIndicator';
import { AggFnSelectControlled } from './AggFnSelect';
import { AlertScheduleFields } from './AlertScheduleFields';
import ChartDisplaySettingsDrawer, {
ChartConfigDisplaySettings,
} from './ChartDisplaySettingsDrawer';
import DBNumberChart from './DBNumberChart';
import { DBPieChart } from './DBPieChart';
import DBSqlRowTableWithSideBar from './DBSqlRowTableWithSidebar';
import {
CheckBoxControlled,
InputControlled,
TextInputControlled,
} from './InputControlled';
import { MetricAttributeHelperPanel } from './MetricAttributeHelperPanel';
import { MetricNameSelect } from './MetricNameSelect';
import SaveToDashboardModal from './SaveToDashboardModal';
import SourceSchemaPreview from './SourceSchemaPreview';
import { SourceSelectControlled } from './SourceSelect';
const isQueryReady = (queriedConfig: ChartConfigWithDateRange | undefined) => {
if (!queriedConfig) return false;
if (isRawSqlChartConfig(queriedConfig)) {
return !!(queriedConfig.sqlTemplate && queriedConfig.connection);
}
return (
((queriedConfig.select?.length ?? 0) > 0 ||
typeof queriedConfig.select === 'string') &&
queriedConfig.from?.databaseName &&
// tableName is empty for metric sources
(queriedConfig.from?.tableName || queriedConfig.metricTables) &&
queriedConfig.timestampValueExpression
);
};
type SeriesItem = NonNullable<
SavedChartConfigWithSelectArray['select']
>[number];
function ChartSeriesEditorComponent({
control,
databaseName,
dateRange,
connectionId,
index,
namePrefix,
onRemoveSeries,
onSwapSeries,
onSubmit,
setValue,
showGroupBy,
showHaving,
tableName: _tableName,
parentRef,
length,
tableSource,
errors,
clearErrors,
}: {
control: Control<ChartEditorFormState>;
databaseName: string;
dateRange?: DateRange['dateRange'];
connectionId?: string;
index: number;
namePrefix: `series.${number}.`;
parentRef?: HTMLElement | null;
onRemoveSeries: (index: number) => void;
onSwapSeries: (from: number, to: number) => void;
onSubmit: () => void;
setValue: UseFormSetValue<ChartEditorFormState>;
showGroupBy: boolean;
showHaving: boolean;
tableName: string;
length: number;
tableSource?: TSource;
errors?: FieldErrors<SeriesItem>;
clearErrors: UseFormClearErrors<ChartEditorFormState>;
}) {
const aggFn = useWatch({ control, name: `${namePrefix}aggFn` });
const aggConditionLanguage = useWatch({
control,
name: `${namePrefix}aggConditionLanguage`,
defaultValue: 'lucene',
});
const metricType = useWatch({ control, name: `${namePrefix}metricType` });
// Initialize metricType to 'gauge' when switching to a metric source
// and reset 'custom' aggFn to 'count' since custom is not supported for metrics
useEffect(() => {
if (tableSource?.kind === SourceKind.Metric) {
if (!metricType) {
setValue(`${namePrefix}metricType`, MetricsDataType.Gauge);
}
if (aggFn === 'none') {
setValue(`${namePrefix}aggFn`, 'count');
}
}
}, [tableSource?.kind, metricType, aggFn, namePrefix, setValue]);
const tableName =
tableSource?.kind === SourceKind.Metric
? getMetricTableName(tableSource, metricType)
: _tableName;
const metricName = useWatch({ control, name: `${namePrefix}metricName` });
const aggCondition = useWatch({
control,
name: `${namePrefix}aggCondition`,
});
const groupBy = useWatch({ control, name: 'groupBy' });
const metricTableSource =
tableSource?.kind === SourceKind.Metric ? tableSource : undefined;
const { data: attributeSuggestions, isLoading: isLoadingAttributes } =
useFetchMetricResourceAttrs({
databaseName,
metricType,
metricName,
tableSource: metricTableSource,
isSql: aggConditionLanguage === 'sql',
});
const attributeKeys = useMemo(
() => parseAttributeKeysFromSuggestions(attributeSuggestions ?? []),
[attributeSuggestions],
);
const { data: metricMetadata } = useFetchMetricMetadata({
databaseName,
metricType,
metricName,
tableSource: metricTableSource,
});
const handleAddToWhere = useCallback(
(clause: string) => {
const currentValue = aggCondition || '';
const newValue = currentValue ? `${currentValue} AND ${clause}` : clause;
setValue(`${namePrefix}aggCondition`, newValue);
onSubmit();
},
[aggCondition, namePrefix, setValue, onSubmit],
);
const handleAddToGroupBy = useCallback(
(clause: string) => {
const currentValue = groupBy || '';
const newValue = currentValue ? `${currentValue}, ${clause}` : clause;
setValue('groupBy', newValue);
onSubmit();
},
[groupBy, setValue, onSubmit],
);
const showWhere = aggFn !== 'none';
const tableConnection = useMemo(
() => ({
databaseName,
tableName: tableName ?? '',
connectionId: connectionId ?? '',
metricName:
tableSource?.kind === SourceKind.Metric ? metricName : undefined,
}),
[databaseName, tableName, connectionId, metricName, tableSource],
);
return (
<>
<Divider
label={
<Group gap="xs">
<Text size="xxs">Alias</Text>
<div style={{ width: 150 }}>
<TextInputControlled
name={`${namePrefix}alias`}
control={control}
placeholder="Series alias"
onChange={() => onSubmit()}
size="xs"
data-testid="series-alias-input"
/>
</div>
{(index ?? -1) > 0 && (
<Button
variant="subtle"
color="gray"
size="xxs"
onClick={() => onSwapSeries(index, index - 1)}
title="Move up"
>
<IconArrowUp size={14} />
</Button>
)}
{(index ?? -1) < length - 1 && (
<Button
variant="subtle"
color="gray"
size="xxs"
onClick={() => onSwapSeries(index, index + 1)}
title="Move down"
>
<IconArrowDown size={14} />
</Button>
)}
{((index ?? -1) > 0 || length > 1) && (
<Button
variant="subtle"
color="gray"
size="xs"
onClick={() => onRemoveSeries(index)}
>
<IconTrash size={14} className="me-2" />
Remove Series
</Button>
)}
</Group>
}
labelPosition="right"
mb={8}
mt="sm"
/>
<Flex gap="sm" mt="xs" align="start">
<div
style={{
minWidth: 200,
}}
>
<AggFnSelectControlled
aggFnName={`${namePrefix}aggFn`}
quantileLevelName={`${namePrefix}level`}
defaultValue={AGG_FNS[0]?.value ?? 'avg'}
control={control}
hideCustom={tableSource?.kind === SourceKind.Metric}
/>
</div>
{tableSource?.kind === SourceKind.Metric && metricType && (
<div style={{ minWidth: 220 }}>
<MetricNameSelect
metricName={metricName}
dateRange={dateRange}
metricType={metricType}
setMetricName={value => {
setValue(`${namePrefix}metricName`, value);
setValue(`${namePrefix}valueExpression`, 'Value');
}}
setMetricType={value =>
setValue(`${namePrefix}metricType`, value)
}
metricSource={tableSource}
data-testid="metric-name-selector"
error={errors?.metricName?.message}
onFocus={() => clearErrors(`${namePrefix}metricName`)}
/>
{metricType === 'gauge' && (
<Flex justify="end">
<CheckBoxControlled
control={control}
name={`${namePrefix}isDelta`}
label="Delta"
size="xs"
className="mt-2"
/>
</Flex>
)}
</div>
)}
{tableSource?.kind !== SourceKind.Metric && aggFn !== 'count' && (
<div
style={{
minWidth: 220,
...(aggFn === 'none' && { flexGrow: 2 }),
}}
>
<SQLInlineEditorControlled
tableConnection={tableConnection}
control={control}
name={`${namePrefix}valueExpression`}
placeholder="SQL Column"
onSubmit={onSubmit}
/>
</div>
)}
{(showWhere || showGroupBy || showHaving) && (
<div
className="flex-grow-1 gap-2 align-items-center"
style={{
display: 'grid',
gridTemplateColumns: 'auto 1fr auto 1fr',
}}
>
{showWhere && (
<>
<Text size="sm">Where</Text>
<div
style={{
gridColumn:
showHaving === showGroupBy ? 'span 3' : undefined,
}}
>
<SearchWhereInput
tableConnection={tableConnection}
control={control}
name={`${namePrefix}aggCondition`}
onSubmit={onSubmit}
showLabel={false}
additionalSuggestions={attributeSuggestions}
/>
</div>
</>
)}
{showGroupBy && (
<>
<Text size="sm" style={{ whiteSpace: 'nowrap' }}>
Group By
</Text>
<div
style={{
minWidth: 200,
maxWidth: '100%',
gridColumn:
!showHaving && !showWhere ? 'span 3' : undefined,
}}
>
<SQLInlineEditorControlled
parentRef={parentRef}
tableConnection={tableConnection}
control={control}
name={`groupBy`}
placeholder="SQL Columns"
disableKeywordAutocomplete
onSubmit={onSubmit}
/>
</div>
{showHaving && (
<>
<Text size="sm" style={{ whiteSpace: 'nowrap' }}>
Having
</Text>
<div style={{ minWidth: 300, maxWidth: '100%' }}>
<SQLInlineEditorControlled
tableConnection={tableConnection}
control={control}
name="having"
placeholder="SQL HAVING clause (ex. count() > 100)"
disableKeywordAutocomplete
onSubmit={onSubmit}
/>
</div>
</>
)}
</>
)}
</div>
)}
</Flex>
{tableSource?.kind === SourceKind.Metric && metricName && metricType && (
<MetricAttributeHelperPanel
databaseName={databaseName}
metricType={metricType}
metricName={metricName}
tableSource={tableSource}
attributeKeys={attributeKeys}
isLoading={isLoadingAttributes}
language={aggConditionLanguage === 'sql' ? 'sql' : 'lucene'}
metricMetadata={metricMetadata}
onAddToWhere={handleAddToWhere}
onAddToGroupBy={showGroupBy ? handleAddToGroupBy : undefined}
/>
)}
</>
);
}
const ChartSeriesEditor = ChartSeriesEditorComponent;
const ErrorNotificationMessage = ({
errors,
}: {
errors: { path: Path<ChartEditorFormState>; message: string }[];
}) => {
return (
<List
size="sm"
icon={<IconX size={14} style={{ verticalAlign: 'middle' }} />}
>
{errors.map(({ message }, index) => (
<List.Item key={index}>{message}</List.Item>
))}
</List>
);
};
const zSavedChartConfig = z
.object({
// TODO: Chart
alert: ChartAlertBaseSchema.superRefine(
validateAlertScheduleOffsetMinutes,
).optional(),
})
.passthrough();
export default function EditTimeChartForm({
dashboardId,
chartConfig,
displayedTimeInputValue,
dateRange,
isSaving,
onTimeRangeSearch,
setChartConfig,
setDisplayedTimeInputValue,
onSave,
onTimeRangeSelect,
onClose,
onDirtyChange,
'data-testid': dataTestId,
submitRef,
isDashboardForm = false,
autoRun = false,
}: {
dashboardId?: string;
chartConfig: SavedChartConfig;
displayedTimeInputValue?: string;
dateRange: [Date, Date];
isSaving?: boolean;
onTimeRangeSearch?: (value: string) => void;
setChartConfig?: (chartConfig: SavedChartConfig) => void;
setDisplayedTimeInputValue?: (value: string) => void;
onSave?: (chart: SavedChartConfig) => void;
onClose?: () => void;
onDirtyChange?: (isDirty: boolean) => void;
onTimeRangeSelect?: (start: Date, end: Date) => void;
'data-testid'?: string;
submitRef?: React.MutableRefObject<(() => void) | undefined>;
isDashboardForm?: boolean;
autoRun?: boolean;
}) {
const formValue: ChartEditorFormState = useMemo(
() => convertSavedChartConfigToFormState(chartConfig),
[chartConfig],
);
const {
control,
setValue,
handleSubmit,
register,
setError,
clearErrors,
formState: { errors, isDirty, dirtyFields },
} = useForm<ChartEditorFormState>({
defaultValues: formValue,
values: formValue,
resolver: zodResolver(zSavedChartConfig),
});
const {
fields,
append,
remove: removeSeries,
swap: swapSeries,
} = useFieldArray({
control,
name: 'series',
});
useEffect(() => {
onDirtyChange?.(isDirty);
}, [isDirty, onDirtyChange]);
const [isSampleEventsOpen, setIsSampleEventsOpen] = useState(false);
const select = useWatch({ control, name: 'select' });
const sourceId = useWatch({ control, name: 'source' });
const alert = useWatch({ control, name: 'alert' });
const seriesReturnType = useWatch({ control, name: 'seriesReturnType' });
const groupBy = useWatch({ control, name: 'groupBy' });
const displayType =
useWatch({ control, name: 'displayType' }) ?? DisplayType.Line;
const markdown = useWatch({ control, name: 'markdown' });
const alertChannelType = useWatch({ control, name: 'alert.channel.type' });
const alertScheduleOffsetMinutes = useWatch({
control,
name: 'alert.scheduleOffsetMinutes',
});
const granularity = useWatch({ control, name: 'granularity' });
const maxAlertScheduleOffsetMinutes = alert?.interval
? Math.max(intervalToMinutes(alert.interval) - 1, 0)
: 0;
const alertIntervalLabel = alert?.interval
? TILE_ALERT_INTERVAL_OPTIONS[alert.interval]
: undefined;
const configType = useWatch({ control, name: 'configType' });
const chartConfigAlert = !isRawSqlSavedChartConfig(chartConfig)
? chartConfig.alert
: undefined;
const isRawSqlInput =
configType === 'sql' && isRawSqlDisplayType(displayType);
const { data: tableSource } = useSource({ id: sourceId });
const databaseName = tableSource?.from.databaseName;
const tableName = tableSource?.from.tableName;
const activeTab = useMemo(() => {
switch (displayType) {
case DisplayType.Search:
return 'search';
case DisplayType.Markdown:
return 'markdown';
case DisplayType.Table:
return 'table';
case DisplayType.Pie:
return 'pie';
case DisplayType.Number:
return 'number';
default:
return 'time';
}
}, [displayType]);
useEffect(() => {
if (
displayType !== DisplayType.Line &&
displayType !== DisplayType.Number
) {
setValue('alert', undefined);
}
}, [displayType, setValue]);
const showGeneratedSql = ['table', 'time', 'number', 'pie'].includes(
activeTab,
);
const showSampleEvents =
tableSource?.kind !== SourceKind.Metric && !isRawSqlInput;
const [
alignDateRangeToGranularity,
fillNulls,
compareToPreviousPeriod,
numberFormat,
] = useWatch({
control,
name: [
'alignDateRangeToGranularity',
'fillNulls',
'compareToPreviousPeriod',
'numberFormat',
],
});
const displaySettings: ChartConfigDisplaySettings = useMemo(
() => ({
alignDateRangeToGranularity,
fillNulls,
compareToPreviousPeriod,
numberFormat,
}),
[
alignDateRangeToGranularity,
fillNulls,
compareToPreviousPeriod,
numberFormat,
],
);
const [
displaySettingsOpened,
{ open: openDisplaySettings, close: closeDisplaySettings },
] = useDisclosure(false);
// Only update this on submit, otherwise we'll have issues
// with using the source value from the last submit
// (ex. ignoring local custom source updates)
const [queriedConfig, setQueriedConfig] = useState<
ChartConfigWithDateRange | undefined
>(undefined);
const [queriedSource, setQueriedSource] = useState<TSource | undefined>(
undefined,
);
const setQueriedConfigAndSource = useCallback(
(config: ChartConfigWithDateRange, source: TSource | undefined) => {
setQueriedConfig(config);
setQueriedSource(source);
},
[],
);
const dbTimeChartConfig = useMemo(() => {
if (!queriedConfig) {
return undefined;
}
return {
...queriedConfig,
granularity: alert
? intervalToGranularity(alert.interval)
: queriedConfig.granularity,
dateRange: alert
? extendDateRangeToInterval(queriedConfig.dateRange, alert.interval)
: queriedConfig.dateRange,
};
}, [queriedConfig, alert]);
const [saveToDashboardModalOpen, setSaveToDashboardModalOpen] =
useState(false);
const onSubmit = useCallback(
(suppressErrorNotification: boolean = false) => {
handleSubmit(form => {
const isRawSqlChart =
form.configType === 'sql' && isRawSqlDisplayType(form.displayType);
const errors = validateChartForm(form, tableSource, setError);
if (errors.length > 0) {
if (!suppressErrorNotification) {
notifications.show({
id: 'chart-error',
title: 'Invalid Chart',
message: <ErrorNotificationMessage errors={errors} />,
color: 'red',
});
}
return;
}
const savedConfig = convertFormStateToSavedChartConfig(
form,
tableSource,
);
const queriedConfig = convertFormStateToChartConfig(
form,
dateRange,
tableSource,
);
if (savedConfig && queriedConfig) {
const normalizedSavedConfig = isRawSqlSavedChartConfig(savedConfig)
? savedConfig
: {
...savedConfig,
alert: normalizeNoOpAlertScheduleFields(
savedConfig.alert,
chartConfigAlert,
{
preserveExplicitScheduleOffsetMinutes:
dirtyFields.alert?.scheduleOffsetMinutes === true,
preserveExplicitScheduleStartAt:
dirtyFields.alert?.scheduleStartAt === true,
},
),
};
setChartConfig?.(normalizedSavedConfig);
setQueriedConfigAndSource(
queriedConfig,
isRawSqlChart ? undefined : tableSource,
);
}
})();
},
[
chartConfigAlert,
dirtyFields.alert?.scheduleOffsetMinutes,
dirtyFields.alert?.scheduleStartAt,
handleSubmit,
setChartConfig,
setQueriedConfigAndSource,
tableSource,
dateRange,
setError,
],
);
const onTableSortingChange = useCallback(
(sortState: SortingState | null) => {
setValue('orderBy', sortingStateToOrderByString(sortState) ?? '');
onSubmit();
},
[setValue, onSubmit],
);
const tableSortState = useMemo(
() =>
queriedConfig != null &&
isBuilderChartConfig(queriedConfig) &&
queriedConfig.orderBy &&
typeof queriedConfig.orderBy === 'string'
? orderByStringToSortingState(queriedConfig.orderBy)
: undefined,
[queriedConfig],
);
useEffect(() => {
if (submitRef) {
submitRef.current = onSubmit;
}
}, [onSubmit, submitRef]);
const autoRunFired = useRef(false);
useEffect(() => {
if (autoRun && !autoRunFired.current && tableSource) {
autoRunFired.current = true;
onSubmit(true);
}
}, [autoRun, tableSource, onSubmit]);
const handleSave = useCallback(
(form: ChartEditorFormState) => {
const errors = validateChartForm(form, tableSource, setError);
if (errors.length > 0) {
notifications.show({
id: 'chart-error',
title: 'Invalid Chart',
message: <ErrorNotificationMessage errors={errors} />,
color: 'red',
});
return;
}
const savedChartConfig = convertFormStateToSavedChartConfig(
form,
tableSource,
);
if (savedChartConfig) {
const normalizedSavedConfig = isRawSqlSavedChartConfig(savedChartConfig)
? savedChartConfig
: {
...savedChartConfig,
alert: normalizeNoOpAlertScheduleFields(
savedChartConfig.alert,
chartConfigAlert,
{
preserveExplicitScheduleOffsetMinutes:
dirtyFields.alert?.scheduleOffsetMinutes === true,
preserveExplicitScheduleStartAt:
dirtyFields.alert?.scheduleStartAt === true,
},
),
};
onSave?.(normalizedSavedConfig);
}
},
[
onSave,
tableSource,
setError,
chartConfigAlert,
dirtyFields.alert?.scheduleOffsetMinutes,
dirtyFields.alert?.scheduleStartAt,
],
);
// Track previous values for detecting changes
const prevGranularityRef = useRef(granularity);
const prevDisplayTypeRef = useRef(displayType);
const prevConfigTypeRef = useRef(configType);
useEffect(() => {
// Emulate the granularity picker auto-searching similar to dashboards
if (granularity !== prevGranularityRef.current) {
prevGranularityRef.current = granularity;
onSubmit();
}
}, [granularity, onSubmit]);
useEffect(() => {
const displayTypeChanged = displayType !== prevDisplayTypeRef.current;
const configTypeChanged = configType !== prevConfigTypeRef.current;
if (displayTypeChanged || configTypeChanged) {
prevDisplayTypeRef.current = displayType;
prevConfigTypeRef.current = configType;
if (displayType === DisplayType.Search && typeof select !== 'string') {
setValue('select', '');
setValue('series', []);
}
if (displayType !== DisplayType.Search && !Array.isArray(select)) {
const defaultSeries: SavedChartConfigWithSelectArray['select'] = [
{
aggFn: 'count',
aggCondition: '',
aggConditionLanguage: getStoredLanguage() ?? 'lucene',
valueExpression: '',
},
];
setValue('where', '');
setValue('select', defaultSeries);
setValue('series', defaultSeries);
}
// Don't auto-submit when config type changes, to avoid clearing form state (like source)
if (displayTypeChanged) {
// true = Suppress error notification (because we're auto-submitting)
onSubmit(true);
}
}
}, [displayType, select, setValue, onSubmit, configType]);
// Emulate the date range picker auto-searching similar to dashboards
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
setQueriedConfig((config: ChartConfigWithDateRange | undefined) => {
if (config == null) {
return config;
}
return {
...config,
dateRange,
};
});
}, [dateRange]);
const queryReady = isQueryReady(queriedConfig);
// The chart config to use when showing the user the generated SQL
// and explaining whether a MV can be used.
const chartConfigForExplanations: ChartConfigWithOptTimestamp | undefined =
useMemo(() => {
if (queriedConfig && isRawSqlChartConfig(queriedConfig))
return { ...queriedConfig, dateRange };
if (chartConfig && isRawSqlSavedChartConfig(chartConfig))
return { ...chartConfig, dateRange };
const userHasSubmittedQuery = !!queriedConfig;
const queriedSourceMatchesSelectedSource =
queriedSource?.id === tableSource?.id;
const urlParamsSourceMatchesSelectedSource =
chartConfig.source === tableSource?.id;
const effectiveQueriedConfig =
activeTab === 'time' ? dbTimeChartConfig : queriedConfig;
const config =
userHasSubmittedQuery && queriedSourceMatchesSelectedSource
? effectiveQueriedConfig
: chartConfig && urlParamsSourceMatchesSelectedSource && tableSource
? {
...chartConfig,
dateRange,
timestampValueExpression: tableSource.timestampValueExpression,
from: tableSource.from,
connection: tableSource.connection,
}
: undefined;
if (!config || isRawSqlChartConfig(config)) {
return undefined;
}
// Apply the transformations that child components will apply,
// so that the MV optimization explanation and generated SQL preview
// are accurate.
if (activeTab === 'time') {
return convertToTimeChartConfig(config);