import * as React from 'react' import {__, _x} from '@wordpress/i18n' import { useState, } from '@wordpress/element' import { Modal, __experimentalVStack as VStack, } from '@wordpress/components' import { Chat, OpenRouterErrorNotice, useAI, type ChatProps, } from '../..' import type { AISession, OpenRouterErrorResponse, } from '../../types' import type { ModalProps, } from '@wordpress/components/build-types/modal/types' const noop = () => {} export interface AIModalProps extends Omit { /** AI session context. */ session: AISession /** Modal is open. */ isOpen: boolean /** Current prompt. */ prompt: string /** Update prompt. */ setPrompt: (nextPrompt: string) => void /** Custom model. */ model: string /** Update custom model. */ setModel: (nextModel: string) => void /** Triggers closing of the modal (_not_ the network request). */ onRequestClose: () => void /** Close the modal when sending a request (default: false). */ closeOnSend?: boolean /** Called when a request to AI has been made. */ onRequestBegin?: () => void /** Called when a request to AI has been resolved. */ onRequestFinish?: () => void /** Called when the request is aborted. */ onRequestAbort?: () => void /** Called when AI session is terminated. */ onEndSession?: () => void /** Props for Chat component. */ chatProps?: Partial } const AIModal: React.FC = ({ session, isOpen, prompt, setPrompt, model, setModel, onRequestClose, closeOnSend = false, onRequestBegin = noop, onRequestFinish = noop, onRequestAbort = noop, onEndSession = noop, chatProps = {}, ...modalProps }) => { const [error, setError] = useState(null) const { onResponse = noop, } = session const { isLoading, messages, sendMessage, abort, } = useAI({ ...session, model, onRequestBegin: () => { setError(null) onRequestBegin() if(closeOnSend) { onRequestClose() } }, onResponse, onError: setError, onRequestFinish, }) if(!isOpen) { return null } return <> { sendMessage(prompt) }} onAbort={() => { abort() onRequestAbort() }} onEndSession={() => { abort() onEndSession() }} {...chatProps} /> {error && <> setError(null)} /> } } export default AIModal