/
LabelsField.tsx
349 lines (316 loc) · 10.8 KB
/
LabelsField.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
import { css, cx } from '@emotion/css';
import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';
import { useFieldArray, UseFieldArrayAppend, useFormContext } from 'react-hook-form';
import { GrafanaTheme2, SelectableValue } from '@grafana/data';
import {
Button,
Field,
InlineLabel,
Input,
InputControl,
LoadingPlaceholder,
Stack,
Text,
useStyles2,
} from '@grafana/ui';
import { useDispatch } from 'app/types';
import { useUnifiedAlertingSelector } from '../../hooks/useUnifiedAlertingSelector';
import { fetchRulerRulesIfNotFetchedYet } from '../../state/actions';
import { RuleFormValues } from '../../types/rule-form';
import AlertLabelDropdown from '../AlertLabelDropdown';
import { NeedHelpInfo } from './NeedHelpInfo';
interface Props {
className?: string;
dataSourceName?: string | null;
}
const useGetCustomLabels = (dataSourceName: string): { loading: boolean; labelsByKey: Record<string, Set<string>> } => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchRulerRulesIfNotFetchedYet(dataSourceName));
}, [dispatch, dataSourceName]);
const rulerRuleRequests = useUnifiedAlertingSelector((state) => state.rulerRules);
const rulerRequest = rulerRuleRequests[dataSourceName];
const labelsByKeyResult = useMemo<Record<string, Set<string>>>(() => {
const labelsByKey: Record<string, Set<string>> = {};
const rulerRulesConfig = rulerRequest?.result;
if (!rulerRulesConfig) {
return labelsByKey;
}
const allRules = Object.values(rulerRulesConfig)
.flatMap((groups) => groups)
.flatMap((group) => group.rules);
allRules.forEach((rule) => {
if (rule.labels) {
Object.entries(rule.labels).forEach(([key, value]) => {
if (!value) {
return;
}
const labelEntry = labelsByKey[key];
if (labelEntry) {
labelEntry.add(value);
} else {
labelsByKey[key] = new Set([value]);
}
});
}
});
return labelsByKey;
}, [rulerRequest]);
return { loading: rulerRequest?.loading, labelsByKey: labelsByKeyResult };
};
function mapLabelsToOptions(items: Iterable<string> = []): Array<SelectableValue<string>> {
return Array.from(items, (item) => ({ label: item, value: item }));
}
const RemoveButton: FC<{
remove: (index?: number | number[] | undefined) => void;
className: string;
index: number;
}> = ({ remove, className, index }) => (
<Button
className={className}
aria-label="delete label"
icon="trash-alt"
data-testid={`delete-label-${index}`}
variant="secondary"
onClick={() => {
remove(index);
}}
/>
);
const AddButton: FC<{
append: UseFieldArrayAppend<RuleFormValues, 'labels'>;
className: string;
}> = ({ append, className }) => (
<Button
className={className}
icon="plus-circle"
type="button"
variant="secondary"
onClick={() => {
append({ key: '', value: '' });
}}
>
Add label
</Button>
);
const LabelsWithSuggestions: FC<{ dataSourceName: string }> = ({ dataSourceName }) => {
const styles = useStyles2(getStyles);
const {
control,
watch,
formState: { errors },
} = useFormContext<RuleFormValues>();
const labels = watch('labels');
const { fields, remove, append } = useFieldArray({ control, name: 'labels' });
const { loading, labelsByKey } = useGetCustomLabels(dataSourceName);
const [selectedKey, setSelectedKey] = useState('');
const keys = useMemo(() => {
return mapLabelsToOptions(Object.keys(labelsByKey));
}, [labelsByKey]);
const getValuesForLabel = useCallback(
(key: string) => {
return mapLabelsToOptions(labelsByKey[key]);
},
[labelsByKey]
);
const values = useMemo(() => {
return getValuesForLabel(selectedKey);
}, [selectedKey, getValuesForLabel]);
return (
<>
{loading && <LoadingPlaceholder text="Loading" />}
{!loading && (
<Stack direction="column" gap={0.5}>
{fields.map((field, index) => {
return (
<div key={field.id}>
<div className={cx(styles.flexRow, styles.centerAlignRow)}>
<Field
className={styles.labelInput}
invalid={Boolean(errors.labels?.[index]?.key?.message)}
error={errors.labels?.[index]?.key?.message}
data-testid={`label-key-${index}`}
>
<InputControl
name={`labels.${index}.key`}
control={control}
rules={{ required: Boolean(labels[index]?.value) ? 'Required.' : false }}
render={({ field: { onChange, ref, ...rest } }) => {
return (
<AlertLabelDropdown
{...rest}
defaultValue={field.key ? { label: field.key, value: field.key } : undefined}
options={keys}
onChange={(newValue: SelectableValue) => {
onChange(newValue.value);
setSelectedKey(newValue.value);
}}
type="key"
/>
);
}}
/>
</Field>
<InlineLabel className={styles.equalSign}>=</InlineLabel>
<Field
className={styles.labelInput}
invalid={Boolean(errors.labels?.[index]?.value?.message)}
error={errors.labels?.[index]?.value?.message}
data-testid={`label-value-${index}`}
>
<InputControl
control={control}
name={`labels.${index}.value`}
rules={{ required: Boolean(labels[index]?.value) ? 'Required.' : false }}
render={({ field: { onChange, ref, ...rest } }) => {
return (
<AlertLabelDropdown
{...rest}
defaultValue={field.value ? { label: field.value, value: field.value } : undefined}
options={values}
onChange={(newValue: SelectableValue) => {
onChange(newValue.value);
}}
onOpenMenu={() => {
setSelectedKey(labels[index].key);
}}
type="value"
/>
);
}}
/>
</Field>
<RemoveButton className={styles.deleteLabelButton} index={index} remove={remove} />
</div>
</div>
);
})}
<AddButton className={styles.addLabelButton} append={append} />
</Stack>
)}
</>
);
};
const LabelsWithoutSuggestions: FC = () => {
const styles = useStyles2(getStyles);
const {
register,
control,
watch,
formState: { errors },
} = useFormContext<RuleFormValues>();
const labels = watch('labels');
const { fields, remove, append } = useFieldArray({ control, name: 'labels' });
return (
<>
{fields.map((field, index) => {
return (
<div key={field.id}>
<div className={cx(styles.flexRow, styles.centerAlignRow)} data-testid="alertlabel-input-wrapper">
<Field
className={styles.labelInput}
invalid={!!errors.labels?.[index]?.key?.message}
error={errors.labels?.[index]?.key?.message}
>
<Input
{...register(`labels.${index}.key`, {
required: { value: !!labels[index]?.value, message: 'Required.' },
})}
placeholder="key"
data-testid={`label-key-${index}`}
defaultValue={field.key}
/>
</Field>
<InlineLabel className={styles.equalSign}>=</InlineLabel>
<Field
className={styles.labelInput}
invalid={!!errors.labels?.[index]?.value?.message}
error={errors.labels?.[index]?.value?.message}
>
<Input
{...register(`labels.${index}.value`, {
required: { value: !!labels[index]?.key, message: 'Required.' },
})}
placeholder="value"
data-testid={`label-value-${index}`}
defaultValue={field.value}
/>
</Field>
<RemoveButton className={styles.deleteLabelButton} index={index} remove={remove} />
</div>
</div>
);
})}
<AddButton className={styles.addLabelButton} append={append} />
</>
);
};
const LabelsField: FC<Props> = ({ dataSourceName }) => {
const styles = useStyles2(getStyles);
return (
<div>
<Stack direction="column" gap={1}>
<Text element="h5">Labels</Text>
<Stack direction={'row'} gap={1}>
<Text variant="bodySmall" color="secondary">
Add labels to your rule to annotate your rules, ease searching, or route to a notification policy.
</Text>
<NeedHelpInfo
contentText="The dropdown only displays labels that you have previously used for alerts.
Select a label from the options below or type in a new one."
title="Labels"
/>
</Stack>
</Stack>
<div className={styles.labelsContainer}></div>
{dataSourceName ? <LabelsWithSuggestions dataSourceName={dataSourceName} /> : <LabelsWithoutSuggestions />}
</div>
);
};
const getStyles = (theme: GrafanaTheme2) => {
return {
icon: css({
marginRight: theme.spacing(0.5),
}),
flexColumn: css({
display: 'flex',
flexDirection: 'column',
}),
flexRow: css({
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-start',
'& + button': {
marginLeft: theme.spacing(0.5),
},
}),
deleteLabelButton: css({
marginLeft: theme.spacing(0.5),
alignSelf: 'flex-start',
}),
addLabelButton: css({
flexGrow: 0,
alignSelf: 'flex-start',
}),
centerAlignRow: css({
alignItems: 'baseline',
}),
equalSign: css({
alignSelf: 'flex-start',
width: '28px',
justifyContent: 'center',
marginLeft: theme.spacing(0.5),
}),
labelInput: css({
width: '175px',
marginBottom: `-${theme.spacing(1)}`,
'& + &': {
marginLeft: theme.spacing(1),
},
}),
labelsContainer: css({
marginBottom: theme.spacing(3),
}),
};
};
export default LabelsField;