feat: integrate useFieldArray for dynamic pattern management in TriggersForm

This commit is contained in:
medchedli 2025-06-08 23:27:39 +01:00
parent b81fdd71da
commit d53906750b
3 changed files with 150 additions and 166 deletions

View File

@ -7,7 +7,7 @@
*/ */
import { Divider } from "@mui/material"; import { Divider } from "@mui/material";
import { Controller, useFormContext } from "react-hook-form"; import { Controller, useFieldArray, useFormContext } from "react-hook-form";
import { ContentContainer, ContentItem } from "@/app-components/dialogs"; import { ContentContainer, ContentItem } from "@/app-components/dialogs";
import AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect"; import AutoCompleteEntitySelect from "@/app-components/inputs/AutoCompleteEntitySelect";
@ -24,21 +24,21 @@ export const TriggersForm = () => {
const block = useBlock(); const block = useBlock();
const { t } = useTranslate(); const { t } = useTranslate();
const { control } = useFormContext<IBlockAttributes>(); const { control } = useFormContext<IBlockAttributes>();
const { fields, append, remove } = useFieldArray({
control,
name: "patterns",
keyName: "fieldId",
});
return ( return (
<ContentContainer> <ContentContainer>
<ContentItem> <ContentItem>
<Controller <PatternsInput
name="patterns"
control={control} control={control}
defaultValue={block?.patterns || []} name="patterns"
render={({ field }) => ( fields={fields}
<PatternsInput append={append}
value={field?.value || []} remove={remove}
onChange={field.onChange}
minInput={1}
/>
)}
/> />
</ContentItem> </ContentItem>
<Divider orientation="horizontal" flexItem /> <Divider orientation="horizontal" flexItem />

View File

@ -6,17 +6,15 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/ */
import { Box, TextFieldProps } from "@mui/material"; import { Box } from "@mui/material";
import { FC, useEffect, useState } from "react"; import { FC } from "react";
import { RegisterOptions, useFormContext } from "react-hook-form"; import { Control, Controller } from "react-hook-form";
import { Input } from "@/app-components/inputs/Input"; import { Input } from "@/app-components/inputs/Input";
import NlpPatternSelect from "@/app-components/inputs/NlpPatternSelect"; import NlpPatternSelect from "@/app-components/inputs/NlpPatternSelect";
import { RegexInput } from "@/app-components/inputs/RegexInput"; import { RegexInput } from "@/app-components/inputs/RegexInput";
import { useTranslate } from "@/hooks/useTranslate"; import { useTranslate } from "@/hooks/useTranslate";
import { import {
IBlockAttributes,
IBlockFull,
NlpPattern, NlpPattern,
Pattern, Pattern,
PatternType, PatternType,
@ -33,119 +31,122 @@ import { OutcomeInput } from "./OutcomeInput";
import { PostbackInput } from "./PostbackInput"; import { PostbackInput } from "./PostbackInput";
const getPatternType = (pattern: Pattern): PatternType => { const getPatternType = (pattern: Pattern): PatternType => {
if (isRegexString(pattern)) { if (typeof pattern === "string") {
return "regex"; return isRegexString(pattern) ? "regex" : "text";
} else if (Array.isArray(pattern)) {
return "nlp";
} else if (typeof pattern === "object") {
if (pattern?.type === "menu") {
return "menu";
} else if (pattern?.type === "content") {
return "content";
} else if (pattern?.type === "outcome") {
return "outcome";
} else {
return "payload";
}
} else {
return "text";
} }
if (Array.isArray(pattern)) {
return "nlp";
}
if (pattern && typeof pattern === "object") {
switch (pattern.type) {
case "menu":
return "menu";
case "content":
return "content";
case "outcome":
return "outcome";
default:
return "payload";
}
}
return "text";
}; };
type PatternInputProps = { type PatternInputProps = {
value: Pattern; control: Control<any>;
onChange: (pattern: Pattern) => void; basePath: string;
block?: IBlockFull;
idx: number;
getInputProps?: (index: number) => TextFieldProps;
}; };
const PatternInput: FC<PatternInputProps> = ({ const PatternInput: FC<PatternInputProps> = ({ control, basePath }) => {
value,
onChange,
idx,
getInputProps,
}) => {
const { t } = useTranslate(); const { t } = useTranslate();
const {
register,
formState: { errors },
} = useFormContext<IBlockAttributes>();
const [pattern, setPattern] = useState<Pattern>(value);
const patternType = getPatternType(value);
const registerInput = (
errorMessage: string,
idx: number,
additionalOptions?: RegisterOptions<IBlockAttributes>,
) => {
return {
...register(`patterns.${idx}`, {
required: errorMessage,
...additionalOptions,
}),
helperText: errors.patterns?.[idx]
? errors.patterns[idx].message
: undefined,
error: !!errors.patterns?.[idx],
};
};
useEffect(() => {
if (pattern || pattern === "") {
onChange(pattern);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pattern]);
return ( return (
<Box display="flex" flexGrow={1}> <Controller
{patternType === "nlp" && ( name={basePath}
<NlpPatternSelect control={control}
patterns={pattern as NlpPattern[]} rules={{
onChange={setPattern} validate: (currentPatternValue: Pattern) => {
/> const type = getPatternType(currentPatternValue);
)}
{["payload", "content", "menu"].includes(patternType) ? ( if (type === "regex") {
<PostbackInput const regexString = currentPatternValue as string;
onChange={(payload) => {
payload && setPattern(payload); if (!regexString || extractRegexBody(regexString).trim() === "") {
}} return t("message.regex_is_empty");
defaultValue={pattern as PayloadPattern} }
/> if (!isRegex(extractRegexBody(regexString))) {
) : null} return t("message.regex_is_invalid");
{patternType === "outcome" ? ( }
<OutcomeInput } else if (type === "text") {
onChange={(payload) => { const textString = currentPatternValue as string;
payload && setPattern(payload);
}} if (!textString || textString.trim() === "") {
defaultValue={pattern as PayloadPattern} return t("message.text_is_required");
/> }
) : null} }
{typeof value === "string" && patternType === "regex" ? (
<RegexInput return true;
{...registerInput(t("message.regex_is_empty"), idx, { },
validate: (pattern) => { }}
return isRegex(extractRegexBody(pattern)) render={({ field, fieldState }) => {
? true const patternForPath = field.value as Pattern;
: t("message.regex_is_invalid"); const currentPatternType = getPatternType(patternForPath);
},
setValueAs: (v) => (isRegexString(v) ? v : formatWithSlashes(v)), return (
})} <Box display="flex" flexGrow={1}>
value={extractRegexBody(value)} {currentPatternType === "nlp" && (
label={t("label.regex")} <NlpPatternSelect
onChange={(e) => onChange(formatWithSlashes(e.target.value))} patterns={patternForPath as NlpPattern[]}
required onChange={field.onChange}
/> />
) : null} )}
{typeof value === "string" && patternType === "text" ? ( {["payload", "content", "menu"].includes(currentPatternType) ? (
<Input <PostbackInput
{...(getInputProps ? getInputProps(idx) : null)} onChange={(payload) => {
label={t("label.text")} payload && field.onChange(payload);
value={value} }}
onChange={(e) => onChange(e.target.value)} defaultValue={patternForPath as PayloadPattern}
/> />
) : null} ) : null}
</Box> {currentPatternType === "outcome" ? (
<OutcomeInput
onChange={(payload) => {
payload && field.onChange(payload);
}}
defaultValue={patternForPath as PayloadPattern}
/>
) : null}
{typeof patternForPath === "string" &&
currentPatternType === "regex" ? (
<RegexInput
value={extractRegexBody(patternForPath as string)}
label={t("label.regex")}
onChange={(e) =>
field.onChange(formatWithSlashes(e.target.value))
}
required
error={fieldState.invalid}
helperText={fieldState.error?.message}
/>
) : null}
{typeof patternForPath === "string" &&
currentPatternType === "text" ? (
<Input
label={t("label.text")}
value={patternForPath as string}
onChange={(e) => field.onChange(e.target.value)}
error={fieldState.invalid}
helperText={fieldState.error?.message}
required
/>
) : null}
</Box>
);
}}
/>
); );
}; };

View File

@ -1,5 +1,5 @@
/* /*
* Copyright © 2024 Hexastack. All rights reserved. * Copyright © 2025 Hexastack. All rights reserved.
* *
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
@ -14,8 +14,13 @@ import PsychologyAltIcon from "@mui/icons-material/PsychologyAlt";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline"; import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import SpellcheckIcon from "@mui/icons-material/Spellcheck"; import SpellcheckIcon from "@mui/icons-material/Spellcheck";
import { Box, Chip, IconButton, styled, useTheme } from "@mui/material"; import { Box, Chip, IconButton, styled, useTheme } from "@mui/material";
import { FC, useEffect, useMemo, useState } from "react"; import { FC, useMemo } from "react";
import { useFormContext } from "react-hook-form"; import {
Control,
FieldArrayWithId,
UseFieldArrayAppend,
UseFieldArrayRemove,
} from "react-hook-form";
import DropdownButton, { import DropdownButton, {
DropdownButtonAction, DropdownButtonAction,
@ -24,9 +29,6 @@ import { useTranslate } from "@/hooks/useTranslate";
import { Pattern } from "@/types/block.types"; import { Pattern } from "@/types/block.types";
import { PayloadType } from "@/types/message.types"; import { PayloadType } from "@/types/message.types";
import { SXStyleOptions } from "@/utils/SXStyleOptions"; import { SXStyleOptions } from "@/utils/SXStyleOptions";
import { createValueWithId, ValueWithId } from "@/utils/valueWithId";
import { getInputControls } from "../../utils/inputControls";
import PatternInput from "./PatternInput"; import PatternInput from "./PatternInput";
@ -41,41 +43,28 @@ const StyledNoPatternsDiv = styled("div")(
); );
type PatternsInputProps = { type PatternsInputProps = {
value: Pattern[]; control: Control<any>;
onChange: (patterns: Pattern[]) => void; name: string;
minInput: number; fields: FieldArrayWithId<any, string, "fieldId">[];
append: UseFieldArrayAppend<any, string>;
remove: UseFieldArrayRemove;
}; };
const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => { const PatternsInput: FC<PatternsInputProps> = ({
control,
name,
fields,
append,
remove,
}) => {
const { t } = useTranslate(); const { t } = useTranslate();
const theme = useTheme(); const theme = useTheme();
const [patterns, setPatterns] = useState<ValueWithId<Pattern>[]>(
value.map((pattern) => createValueWithId(pattern)),
);
const {
register,
formState: { errors },
} = useFormContext<any>();
const addInput = (defaultValue: Pattern) => { const addInput = (defaultValue: Pattern) => {
setPatterns([...patterns, createValueWithId<Pattern>(defaultValue)]); append(defaultValue);
}; };
const removeInput = (index: number) => { const removeInput = (index: number) => {
const updatedPatterns = [...patterns]; remove(index);
updatedPatterns.splice(index, 1);
setPatterns(updatedPatterns);
}; };
const updateInput = (index: number) => (p: Pattern) => {
patterns[index].value = p;
setPatterns([...patterns]);
};
useEffect(() => {
onChange(patterns.map(({ value }) => value));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [patterns]);
const actions: DropdownButtonAction[] = useMemo( const actions: DropdownButtonAction[] = useMemo(
() => [ () => [
{ {
@ -87,7 +76,7 @@ const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => {
{ {
icon: <PsychologyAltIcon />, icon: <PsychologyAltIcon />,
name: t("label.intent_match"), name: t("label.intent_match"),
defaultValue: [], defaultValue: [[]],
}, },
{ {
icon: <MouseIcon />, icon: <MouseIcon />,
@ -117,11 +106,11 @@ const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => {
return ( return (
<Box display="flex" flexDirection="column"> <Box display="flex" flexDirection="column">
<Box display="flex" flexDirection="column"> <Box display="flex" flexDirection="column">
{patterns.length == 0 ? ( {fields.length === 0 ? (
<StyledNoPatternsDiv>{t("label.no_patterns")}</StyledNoPatternsDiv> <StyledNoPatternsDiv>{t("label.no_patterns")}</StyledNoPatternsDiv>
) : ( ) : (
patterns.map(({ value, id }, idx) => ( fields.map((field, idx) => (
<Box display="flex" alignItems="center" mt={2} key={id}> <Box display="flex" alignItems="center" mt={2} key={field.fieldId}>
{idx > 0 && ( {idx > 0 && (
<Chip <Chip
sx={{ m: 1, color: theme.palette.grey[600] }} sx={{ m: 1, color: theme.palette.grey[600] }}
@ -131,15 +120,9 @@ const PatternsInput: FC<PatternsInputProps> = ({ value, onChange }) => {
/> />
)} )}
<PatternInput <PatternInput
idx={idx} control={control}
value={value} basePath={`${name}.${idx}`}
onChange={updateInput(idx)} //idx={idx}
getInputProps={getInputControls(
"label",
errors,
register,
t("message.text_is_required"),
)}
/> />
<IconButton <IconButton
size="small" size="small"