import { useState } from 'react' import Operate from './Operate' import KeyInput from './KeyInput' import { useValidate } from './hooks' import type { Form, KeyFrom, Status, ValidateValue } from './declarations' import { useEventEmitterContextContext } from '@/context/event-emitter' import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general' export type KeyValidatorProps = { type: string title: React.ReactNode status: Status forms: Form[] keyFrom: KeyFrom onSave: (v: ValidateValue) => Promise disabled?: boolean } const KeyValidator = ({ type, title, status, forms, keyFrom, onSave, disabled, }: KeyValidatorProps) => { const triggerKey = `plugins/${type}` const { eventEmitter } = useEventEmitterContextContext() const [isOpen, setIsOpen] = useState(false) const prevValue = forms.reduce((prev: ValidateValue, next: Form) => { prev[next.key] = next.value return prev }, {}) const [value, setValue] = useState(prevValue) const [validate, validating, validatedStatusState] = useValidate(value) eventEmitter?.useSubscription((v) => { if (v !== triggerKey) { setIsOpen(false) setValue(prevValue) validate({ before: () => false }) } }) const handleCancel = () => { eventEmitter?.emit('') } const handleSave = async () => { if (await onSave(value)) eventEmitter?.emit('') } const handleAdd = () => { setIsOpen(true) eventEmitter?.emit(triggerKey) } const handleEdit = () => { setIsOpen(true) eventEmitter?.emit(triggerKey) } const handleChange = (form: Form, val: string) => { setValue({ ...value, [form.key]: val }) if (form.validate) validate(form.validate) } const handleFocus = (form: Form) => { if (form.handleFocus) form.handleFocus(value, setValue) } return (
{title}
{ isOpen && !disabled && (
{ forms.map(form => ( handleChange(form, v)} onFocus={() => handleFocus(form)} validating={validating} validatedStatusState={validatedStatusState} /> )) } {keyFrom.text}
) }
) } export default KeyValidator