-
Notifications
You must be signed in to change notification settings - Fork 91
/
helpers.js
69 lines (60 loc) · 2.15 KB
/
helpers.js
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
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
import React from 'react';
import { EuiText } from '@elastic/eui';
import { htmlIdGenerator } from '@elastic/eui/lib/services';
export const makeId = htmlIdGenerator();
// A helper function that wraps an event handler and filters out ESCAPE keys
export const ignoreEscape = (eventHandler) => (event) => {
if (!(event.keyCode === 27)) {
eventHandler();
}
};
// A helper function that shows toast messages for backend errors.
export const backendErrorNotification = (notifications, actionName, objectName, errorMessage) => {
notifications.toasts.addDanger({
title: `Failed to ${actionName} the ${objectName}`,
text: errorMessage,
toastLifeTimeMs: 20000, // the default lifetime for toasts is 10 sec
});
};
// A helper function to generate a simple string explaining how many elements a user can add to a list.
export const inputLimitText = (
currCount = 0,
limit = 0,
singularKeyword = '',
pluralKeyword = '',
styleProps = {}
) => {
const difference = limit - currCount;
const remainingLimit = `You can add up to ${difference} ${limit === 1 ? '' : 'more'} ${
difference === 1 ? singularKeyword : pluralKeyword
}.`;
const reachedLimit = `You have reached the limit of ${limit} ${
limit === 1 ? singularKeyword : pluralKeyword
}.`;
return (
<EuiText color={'subdued'} size={'xs'} style={styleProps}>
{difference > 0 ? remainingLimit : reachedLimit}
</EuiText>
);
};
export const getDigitId = (length = 6) =>
Math.floor(Date.now() * Math.random())
.toString()
.slice(-length);
// Assumes that values is an array of objects with "name" inside
export const getUniqueName = (values, prefix) => {
const lastValue = values.at(-1);
const lastName = lastValue ? lastValue.name : '';
const lastDigit = Number.parseInt(lastName.match(/\d+$/)?.[0] || 0, 10);
// Checks if value is already in use
const getUniqueName = (digit) => {
const name = `${prefix}${digit + 1}`;
const duplicate = values.find((value) => value.name === name);
return duplicate ? getUniqueName(digit + 1) : name;
};
return getUniqueName(lastDigit);
};