2025-01-06 07:28:34 +00:00
|
|
|
import { useCallback } from "react";
|
2024-10-14 08:05:38 +00:00
|
|
|
import {
|
|
|
|
|
ACTION_INVALID_NAME_ERROR,
|
|
|
|
|
ACTION_NAME_CONFLICT_ERROR,
|
|
|
|
|
createMessage,
|
|
|
|
|
} from "ee/constants/messages";
|
2024-10-28 09:32:58 +00:00
|
|
|
import { shallowEqual, useSelector } from "react-redux";
|
|
|
|
|
import type { AppState } from "ee/reducers";
|
|
|
|
|
import { getUsedActionNames } from "selectors/actionSelectors";
|
2025-01-06 07:28:34 +00:00
|
|
|
import { isNameValid } from "utils/helpers";
|
2024-10-14 08:05:38 +00:00
|
|
|
|
2025-01-06 07:28:34 +00:00
|
|
|
interface UseValidateEntityNameProps {
|
2025-01-13 08:24:30 +00:00
|
|
|
entityName?: string;
|
2024-10-14 08:05:38 +00:00
|
|
|
nameErrorMessage?: (name: string) => string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2025-01-06 07:28:34 +00:00
|
|
|
* Provides a unified way to validate entity names.
|
2024-10-14 08:05:38 +00:00
|
|
|
*/
|
2025-01-06 07:28:34 +00:00
|
|
|
export function useValidateEntityName(props: UseValidateEntityNameProps) {
|
2024-10-28 09:32:58 +00:00
|
|
|
const { entityName, nameErrorMessage = ACTION_NAME_CONFLICT_ERROR } = props;
|
2024-10-14 08:05:38 +00:00
|
|
|
|
|
|
|
|
const usedEntityNames = useSelector(
|
|
|
|
|
(state: AppState) => getUsedActionNames(state, ""),
|
|
|
|
|
shallowEqual,
|
|
|
|
|
);
|
|
|
|
|
|
2025-01-06 07:28:34 +00:00
|
|
|
return useCallback(
|
2025-01-13 08:24:30 +00:00
|
|
|
(name: string, oldName: string | undefined = entityName): string | null => {
|
2024-10-31 11:55:04 +00:00
|
|
|
if (!name || name.trim().length === 0) {
|
|
|
|
|
return createMessage(ACTION_INVALID_NAME_ERROR);
|
2025-01-13 08:24:30 +00:00
|
|
|
} else if (name !== oldName && !isNameValid(name, usedEntityNames)) {
|
2024-10-31 11:55:04 +00:00
|
|
|
return createMessage(nameErrorMessage, name);
|
|
|
|
|
}
|
2024-10-14 08:05:38 +00:00
|
|
|
|
2024-10-31 11:55:04 +00:00
|
|
|
return null;
|
|
|
|
|
},
|
|
|
|
|
[entityName, nameErrorMessage, usedEntityNames],
|
|
|
|
|
);
|
2024-10-14 08:05:38 +00:00
|
|
|
}
|