refactor: fixed unsafe roles dialog and hook logic, added tests

This commit is contained in:
Dan Ditomaso
2025-03-10 20:30:04 -04:00
parent 97f2abb582
commit f1a58f0434
15 changed files with 460 additions and 274 deletions
+10 -23
View File
@@ -10,11 +10,12 @@ import {
SelectValue,
} from "@components/UI/Select.tsx";
import { useController, type FieldValues } from "react-hook-form";
import { computeHeadingLevel } from "@core/utils/test.tsx";
export interface SelectFieldProps<T> extends BaseFormBuilderProps<T> {
type: "select";
selectChange?: (e: string, name: string) => void;
onBeforeChange?: (newValue: string, prevValue: string) => Promise<string | false>;
validate?: (newValue: string) => Promise<boolean>;
properties: BaseFormBuilderProps<T>["properties"] & {
enumValue: {
[s: string]: string | number;
@@ -23,8 +24,6 @@ export interface SelectFieldProps<T> extends BaseFormBuilderProps<T> {
};
}
const formatEnumDisplay = (name: string): string => {
return name
.replace(/_/g, " ")
@@ -48,14 +47,12 @@ export function SelectInput<T extends FieldValues>({
const { enumValue, formatEnumName, ...remainingProperties } = field.properties;
const valueToKeyMap: Record<string, string> = {};
const keyToValueMap: Record<string, number> = {};
const optionsEnumValues: [string, number][] = [];
if (enumValue) {
Object.entries(enumValue).forEach(([key, val]) => {
if (typeof val === "number") {
valueToKeyMap[val.toString()] = key; // Map enum value to key
keyToValueMap[key] = val; // Map key to enum value
valueToKeyMap[val.toString()] = key;
optionsEnumValues.push([key, val]);
}
});
@@ -63,27 +60,17 @@ export function SelectInput<T extends FieldValues>({
const handleValueChange = async (newValue: string) => {
const selectedKey = valueToKeyMap[newValue];
if (!selectedKey) return;
if (field.onBeforeChange) {
try {
const result = await field.onBeforeChange(selectedKey, valueToKeyMap[value?.toString()]);
if (result === false) return;
const updatedValue = keyToValueMap[result];
if (updatedValue !== undefined) {
if (field.selectChange) field.selectChange(updatedValue.toString(), result);
onChange(updatedValue);
}
} catch (error) {
console.error("Error in onBeforeChange function:", error);
}
} else {
if (field.selectChange) field.selectChange(newValue, selectedKey);
onChange(Number.parseInt(newValue));
if (field.validate) {
const isValid = await field.validate(selectedKey);
if (!isValid) return;
}
if (field.selectChange) field.selectChange(newValue, selectedKey);
onChange(Number.parseInt(newValue));
};
return (
<Select
onValueChange={handleValueChange}