Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

6.8 KB
Raw Blame
import { ActionIcon, Button, Flexbox, Icon, Input } from '@lobehub/ui';
import { Form, useForm } from '@lobehub/ui/form';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { LucidePlus, LucideTrash } from 'lucide-react';
import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import InlineErrorText from '@/components/InlineErrorText';
import { type InlineErrorState, toInlineError } from '@/components/InlineErrorText/errorDetail';

const styles = stylex.create({
  form: {
    position: 'relative',
    width: '100%',
    minWidth: '600px',
    padding: '8px',
    borderRadius: cssVar.borderRadiusLG,
  },
  error: { fontSize: '12px', color: cssVar.colorError },
  formItem: { marginBlockEnd: '4px' },
  input: { fontFamily: cssVar.fontFamilyCode, fontSize: '12px' },
  row: { position: 'relative' },
  title: { marginBlockEnd: '4px', color: cssVar.colorTextTertiary },
});

interface KeyValueItem {
  id: string;
  key?: string;
  value?: string;
}

interface KeyValueEditorProps {
  initialValue?: Record<string, any>;
  onCancel?: () => void;
  onFinish?: (value: Record<string, any>) => Promise<void>;
}

const recordToFormList = (record: Record<string, any>): KeyValueItem[] =>
  Object.entries(record)
    .map(([key, val], index) => ({
      id: `${key}-${index}`,
      key,
      value: typeof val === 'string' ? val : JSON.stringify(val),
    }))
    .filter((item) => item.key);

const formListToRecord = (list: KeyValueItem[]): Record<string, any> => {
  const record: Record<string, any> = {};
  list.forEach((item) => {
    if (item.key) {
      try {
        record[item.key] = JSON.parse(item.value || '""');
      } catch {
        record[item.key] = item.value || '';
      }
    }
  });
  return record;
};

const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish, onCancel }) => {
  const { t } = useTranslation(['tool', 'common']);
  const form = useForm<{ items: KeyValueItem[] }>({
    initialValues: { items: recordToFormList(initialValue) },
  });

  useEffect(() => {
    form.setValues({ items: recordToFormList(initialValue) });
  }, [initialValue, form]);

  const [updating, setUpdating] = useState(false);
  /** Failure of the save itself, shown above the buttons; validation errors show on their own fields. */
  const [saveError, setSaveError] = useState<InlineErrorState | null>(null);
  const handleFinish = async () => {
    setUpdating(true);
    setSaveError(null);
    try {
      // Invalid fields (empty / duplicate key) render their own error, so nothing else is shown.
      const { valid } = await form.validate();
      if (!valid) return;
      const values = form.getValues();
      const record = formListToRecord(values.items || []);
      await onFinish?.(record);
    } catch (error) {
      console.error('Failed to save tool arguments:', error);
      setSaveError(toInlineError(t('updateArgs.saveFailed'), error));
    } finally {
      setUpdating(false);
    }
  };

  const handleCancel = () => {
    onCancel?.();
  };

  const validateKey = (key: string | undefined, values: { items?: KeyValueItem[] }) => {
    if (!key) return;
    const keys = (values.items ?? []).map((i) => i?.key).filter(Boolean);
    if (keys.filter((k) => k === key).length > 1) return t('updateArgs.duplicateKeyError');
  };

  return (
    <Form autoComplete="off" className={stylex.props(styles.form).className} form={form} gap={0}>
      <Flexbox horizontal className={stylex.props(styles.title).className} gap={8}>
        <Flexbox flex={1}>key</Flexbox>
        <Flexbox flex={4}>value</Flexbox>
      </Flexbox>
      <Form.List name="items">
        {({ fields, add, remove }) => (
          <Flexbox width={'100%'}>
            {fields.map(({ key, name, index }) => (
              <Flexbox
                horizontal
                align="center"
                className={stylex.props(styles.row).className}
                gap={8}
                key={key}
                width={'100%'}
              >
                <Form.Field
                  bare
                  name={`${name}.key`}
                  required={t('updateArgs.keyRequired')}
                  validate={validateKey}
                  validateOn={'change'}
                  render={({ error, onBlur, onChange, value }) => (
                    <Flexbox className={stylex.props(styles.formItem).className} flex={1}>
                      <Input
                        allowClear
                        aria-invalid={error ? true : undefined}
                        className={stylex.props(styles.input).className}
                        placeholder={t('updateArgs.form.key')}
                        value={value}
                        variant={'filled'}
                        onBlur={onBlur}
                        onChange={(e) => onChange(e.target.value)}
                      />
                      {error && <div {...stylex.props(styles.error)}>{error}</div>}
                    </Flexbox>
                  )}
                />
                <Flexbox className={stylex.props(styles.formItem).className} flex={4}>
                  <Form.Field bare name={`${name}.value`}>
                    <Input
                      allowClear
                      className={stylex.props(styles.input).className}
                      placeholder={t('updateArgs.form.value')}
                      variant={'filled'}
                    />
                  </Form.Field>
                </Flexbox>
                <ActionIcon
                  icon={LucideTrash}
                  size={'small'}
                  title={t('delete', { ns: 'common' })}
                  style={{
                    marginBottom: 6,
                  }}
                  onClick={() => remove(index)}
                />
              </Flexbox>
            ))}
            {saveError && (
              <InlineErrorText detail={saveError.detail} style={{ marginTop: 8 }}>
                {saveError.summary}
              </InlineErrorText>
            )}
            <Flexbox horizontal gap={8} justify={'space-between'} style={{ marginTop: 8 }}>
              <Button
                icon={<Icon icon={LucidePlus} />}
                size={'small'}
                type="fill"
                onClick={() => add({ id: `new-${Date.now()}`, key: '', value: '' })}
              >
                {t('updateArgs.form.add')}
              </Button>

              <Flexbox horizontal gap={8}>
                <Button size={'small'} onClick={handleCancel}>
                  {t('cancel', { ns: 'common' })}
                </Button>
                <Button loading={updating} size={'small'} type={'primary'} onClick={handleFinish}>
                  {t('save', { ns: 'common' })}
                </Button>
              </Flexbox>
            </Flexbox>
          </Flexbox>
        )}
      </Form.List>
    </Form>
  );
});

export default KeyValueEditor;