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.

4.0 KB
Raw Blame
'use client';

import type { WidgetLevelFilter } from '@lobechat/types';
import {
  Button,
  createModal,
  Flexbox,
  Input,
  ModalFooter,
  Text,
  TextArea,
  useModalContext,
} from '@lobehub/ui';
import { t as translate } from 'i18next';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';

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

interface DashboardFormProps {
  onSubmit: (value: { description?: string; title: string }) => Promise<void>;
  submitText: string;
}

const DashboardForm = memo<DashboardFormProps>(({ onSubmit, submitText }) => {
  const { t } = useTranslation(['dashboard', 'common']);
  const { close } = useModalContext();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [loading, setLoading] = useState(false);
  /** Submit failure, shown above the footer buttons: the modal stays open with the user's input. */
  const [error, setError] = useState<InlineErrorState | null>(null);
  const trimmed = title.trim();

  const handleSubmit = async () => {
    if (!trimmed || loading) return;
    setError(null);
    setLoading(true);
    try {
      await onSubmit({ description: description.trim() || undefined, title: trimmed });
      close();
    } catch (err) {
      console.error('[dashboard] form submit failed', err);
      setError(toInlineError(t('form.saveFailedRetry'), err));
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Flexbox gap={16} padding={16}>
        <Flexbox gap={6}>
          <Text fontSize={13} weight={500}>
            {t('form.titleLabel')}
          </Text>
          <Input
            autoFocus
            data-dashboard-title-input
            maxLength={200}
            placeholder={t('form.titlePlaceholder')}
            value={title}
            onPressEnter={() => void handleSubmit()}
            onChange={(event) => {
              setTitle(event.target.value);
              setError(null);
            }}
          />
        </Flexbox>
        <Flexbox gap={6}>
          <Text fontSize={13} weight={500}>
            {t('form.descriptionLabel')}
          </Text>
          <TextArea
            autoSize={{ maxRows: 6, minRows: 2 }}
            maxLength={2000}
            placeholder={t('form.descriptionPlaceholder')}
            value={description}
            onChange={(event) => setDescription(event.target.value)}
          />
        </Flexbox>
        {error && <InlineErrorText detail={error.detail}>{error.summary}</InlineErrorText>}
      </Flexbox>
      <ModalFooter>
        <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
        <Button
          disabled={!trimmed}
          loading={loading}
          type={'primary'}
          onClick={() => void handleSubmit()}
        >
          {submitText}
        </Button>
      </ModalFooter>
    </>
  );
});

DashboardForm.displayName = 'DashboardForm';

/**
 * Create a board at `level` (personal when empty) and hand the new row to
 * `onCreated`. With `widgetId`, the widget is placed on the board in the same
 * server write: a failed placement creates no board and keeps the modal open.
 */
export const openCreateDashboardModal = ({
  level = {},
  onCreated,
  widgetId,
}: {
  level?: WidgetLevelFilter;
  onCreated?: (dashboard: { id: string; title: string }) => void;
  widgetId?: string;
} = {}) =>
  createModal({
    content: (
      <DashboardForm
        submitText={translate('create.submit', { ns: 'dashboard' })}
        onSubmit={async ({ description, title }) => {
          const dashboard = await useDashboardStore
            .getState()
            .createDashboard({ ...level, description, title, widgetId });
          if (dashboard) onCreated?.(dashboard);
        }}
      />
    ),
    footer: null,
    styles: { content: { padding: 0 } },
    title: translate('create.title', { ns: 'dashboard' }),
    width: 460,
  });