import _ from "lodash"; import { useEffect, useState, useRef } from "react"; import { Button, MenuItem, TextField } from "@mui/material"; import { Flow, useAppContext } from "../../contexts/AppContext"; import { useChatContext } from "../../contexts/ChatContext"; import Preferences, { formValidator } from "./Preferences"; import StyledModal from "../Base/StyledModal"; type SessionEditorModalProps = {}; export default function SessionEditorModal({}: SessionEditorModalProps) { const { flows, isSessionEditorOpen, setIsSessionEditorOpen, } = useAppContext(); const { selectedChat, createChat } = useChatContext(); const [draftFlow, setDraftFlow] = useState(null); const [flowPreference, setFlowPreference] = useState>(); const preferencesEl = useRef(null); const bottomRef = useRef(null); const canCloseModal = !!selectedChat; const [isScrollToBottom, setIsScrollToBottom] = useState(false); useEffect(() => { if (isScrollToBottom) { const timer = setTimeout(() => { if (bottomRef.current) { bottomRef.current.scrollIntoView({ behavior: "smooth" }); } setIsScrollToBottom(false); }, 150); return () => clearTimeout(timer); // Clean up the timeout } }, [isScrollToBottom]); useEffect(() => { const flow = flows?.find((f) => f.id === selectedChat?.flow.id); setDraftFlow(flow ?? null); handleFlowChange(selectedChat?.flow.id || ""); return () => { setDraftFlow(null); }; }, [selectedChat]); // Auto-select flow if there's only one option available useEffect(() => { if (isSessionEditorOpen && flows && flows.length === 1 && !draftFlow) { handleFlowChange(flows[0].id); } }, [flows, isSessionEditorOpen, draftFlow]); const handleFlowChange = (flowId: string) => { const flow = flows?.find((flow) => flow.id === flowId) ?? null; if (flow) { setDraftFlow(flow); setFlowPreference(flow.preferences); } }; const handleClose = () => { if (!canCloseModal) return; setIsSessionEditorOpen(false); }; const handlePreferencesChange = (preferences: { [key: string]: any }) => { setDraftFlow( (d) => d && { ...d, preferences: { ...d.preferences, ...preferences, }, } ); }; const handleSubmit = () => { if (!preferencesEl.current?.validate()) { setIsScrollToBottom(true); return; } if (!draftFlow) return; createChat(draftFlow); setIsSessionEditorOpen(false); }; return ( } > <>
{ handleFlowChange(e.target.value); }} > {flows?.map((option) => ( {option.id} - {option.description} ))}
{draftFlow ? ( ) : (

Please select a flow to continue

)}
); }