Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

3.9 KB
Raw Blame
import { FolderDto } from '@activepieces/shared';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation } from '@tanstack/react-query';
import { HttpStatusCode } from 'axios';
import { t } from 'i18next';
import { FormProvider, useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { FormField, FormItem, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { internalErrorToast } from '@/components/ui/sonner';
import { foldersApi } from '@/features/folders/api/folders-api';
import { api } from '@/lib/api';
import { authenticationSession } from '@/lib/authentication-session';

type CreateFolderDialogProps = {
  updateSearchParams: (_folderId?: string) => void;
  refetchFolders: () => void;
  className?: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
};

const CreateFolderFormSchema = z.object({
  displayName: z
    .string({ message: t('Please enter folder name') })
    .regex(/.*\S.*/, t('Please enter folder name')),
});

type CreateFolderFormSchema = z.infer<typeof CreateFolderFormSchema>;

export const CreateFolderDialog = ({
  updateSearchParams,
  refetchFolders,
  open,
  onOpenChange,
}: CreateFolderDialogProps) => {
  const form = useForm<CreateFolderFormSchema>({
    resolver: zodResolver(CreateFolderFormSchema),
  });

  const { mutate, isPending } = useMutation<
    FolderDto,
    Error,
    CreateFolderFormSchema
  >({
    mutationFn: async (data) => {
      return await foldersApi.create({
        displayName: data.displayName.trim(),
        projectId: authenticationSession.getProjectId()!,
      });
    },
    onSuccess: (folder) => {
      form.reset();
      onOpenChange(false);
      updateSearchParams(folder.id);
      refetchFolders();
      toast.success(t('Added folder successfully'));
    },
    onError: (error) => {
      if (api.isError(error)) {
        switch (error.response?.status) {
          case HttpStatusCode.Conflict: {
            form.setError('root.serverError', {
              message: t('The folder name already exists.'),
            });
            break;
          }
          default: {
            internalErrorToast();
            break;
          }
        }
      }
    },
  });

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('Create Folder')}</DialogTitle>
          <DialogDescription>
            {t('Organize your automations by grouping them into folders.')}
          </DialogDescription>
        </DialogHeader>
        <FormProvider {...form}>
          <form onSubmit={form.handleSubmit((data) => mutate(data))}>
            <FormField
              control={form.control}
              name="displayName"
              render={({ field }) => (
                <FormItem>
                  <Input
                    {...field}
                    required
                    id="folder"
                    placeholder={t('Folder Name')}
                  />
                  <FormMessage />
                </FormItem>
              )}
            />
            {form?.formState?.errors?.root?.serverError && (
              <FormMessage>
                {form.formState.errors.root.serverError.message}
              </FormMessage>
            )}
            <DialogFooter>
              <Button
                variant={'outline'}
                onClick={() => onOpenChange(false)}
                type="button"
              >
                {t('Cancel')}
              </Button>
              <Button type="submit" loading={isPending}>
                {t('Create')}
              </Button>
            </DialogFooter>
          </form>
        </FormProvider>
      </DialogContent>
    </Dialog>
  );
};