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

13.5 KB
Raw Blame
import { Permission } from '@activepieces/core-utils';
import {
  Template,
  TemplateType,
  UncategorizedFolderId,
} from '@activepieces/shared';
import { t } from 'i18next';
import {
  Bot,
  ChevronRight,
  Plus,
  Sparkles,
  Table2,
  Upload,
  Workflow,
} from 'lucide-react';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';
import { TagWithBright } from '@/components/custom/tag-with-bright';
import { useEmbedding } from '@/components/providers/embed-provider';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { ImportFlowDialog } from '@/features/flows/components/import-flow-dialog';
import { flowHooks } from '@/features/flows/hooks/flow-hooks';
import { PieceIconList } from '@/features/pieces/components/piece-icon-list';
import { ImportTableDialog } from '@/features/tables/components/import-table-dialog';
import { tableHooks } from '@/features/tables/hooks/table-hooks';
import { TemplatesBrowseDialog } from '@/features/templates';
import { UseTemplateDialog } from '@/features/templates/components/use-template-dialog';
import { templatesHooks } from '@/features/templates/hooks/templates-hook';
import { useGradientFromPieces } from '@/features/templates/hooks/use-gradient-from-pieces';
import { useAuthorization } from '@/hooks/authorization-hooks';
import { flagsHooks } from '@/hooks/flags-hooks';
import { platformHooks } from '@/hooks/platform-hooks';

type ActionRowProps = {
  icon: React.ReactNode;
  label: string;
  onClick?: () => void;
  disabled?: boolean;
  hasPermission?: boolean;
};

const ActionRow = ({
  icon,
  label,
  onClick,
  disabled,
  hasPermission = true,
}: ActionRowProps) => {
  const content = (
    <button
      onClick={onClick}
      disabled={disabled || !hasPermission}
      className="flex items-center justify-between w-full px-4 py-3 text-left hover:bg-gray-3/50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed border-t first:border-t-0"
    >
      <div className="flex items-center gap-3">
        <span className="text-gray-11">{icon}</span>
        <span className="text-sm font-medium">{label}</span>
      </div>
      <ChevronRight className="h-4 w-4 text-gray-11" />
    </button>
  );

  if (!hasPermission) {
    return (
      <PermissionNeededTooltip hasPermission={hasPermission}>
        {content}
      </PermissionNeededTooltip>
    );
  }

  return content;
};

type GetStartedCardProps = {
  icon: React.ReactNode;
  iconBgClass: string;
  title: string;
  description: string;
  children: React.ReactNode;
};

const GetStartedCard = ({
  icon,
  iconBgClass,
  title,
  description,
  children,
}: GetStartedCardProps) => {
  return (
    <Card className="flex-1 overflow-hidden">
      <CardContent className="p-0">
        <div className="flex items-center gap-3 px-4 py-4">
          <div
            className={`w-10 h-10 shrink-0 rounded-xl flex items-center justify-center ${iconBgClass}`}
          >
            {icon}
          </div>
          <div>
            <h3 className="font-semibold text-base">{title}</h3>
            <p className="text-sm text-gray-11">{description}</p>
          </div>
        </div>
        <div className="flex flex-col">{children}</div>
      </CardContent>
    </Card>
  );
};

type SuggestedTemplateCardProps = {
  template: Template;
  onSelect: (template: Template) => void;
};

const SuggestedTemplateCard = ({
  template,
  onSelect,
}: SuggestedTemplateCardProps) => {
  const hasFlows = template.flows && template.flows.length > 0;
  const { gradient } = useGradientFromPieces(
    hasFlows ? template.flows![0]?.trigger : undefined,
  );

  const displayTags = template.tags.slice(0, 1);

  return (
    <Card
      onClick={() => onSelect(template)}
      variant="interactive"
      className="h-[220px] flex flex-col"
    >
      <CardContent className="py-4 px-4 flex flex-col gap-1 flex-1 min-h-0">
        <div className="h-12 flex flex-col justify-start flex-shrink-0">
          <h3 className="font-semibold text-base leading-tight line-clamp-2">
            {template.name}
          </h3>
        </div>

        <p className="text-gray-11 text-sm line-clamp-2 mt-1 flex-shrink-0">
          {template.summary || (
            <span className="italic">{t('No summary')}</span>
          )}
        </p>

        <div className="h-8 flex gap-2 flex-wrap overflow-hidden mt-2 flex-shrink-0">
          {displayTags.length > 0 &&
            displayTags.map((tag, index) => (
              <TagWithBright
                key={index}
                index={index}
                prefix={t('Save')}
                title={tag.title}
                color={tag.color}
                size="sm"
              />
            ))}
        </div>
      </CardContent>

      <div
        className="h-14 flex items-center px-4 rounded-b-xl transition-all duration-300"
        style={{
          background: gradient || 'var(--gray-2)',
        }}
      >
        {hasFlows && template.flows![0]?.trigger && (
          <PieceIconList
            trigger={template.flows![0]?.trigger}
            maxNumberOfIconsToShow={4}
            size="md"
            className="flex gap-0.5"
            excludeCore={true}
          />
        )}
      </div>
    </Card>
  );
};

const TemplateCardSkeleton = () => {
  return (
    <Card className="h-[220px] flex flex-col">
      <CardContent className="py-4 px-4 flex flex-col gap-2 flex-1">
        <Skeleton className="h-6 w-3/4" />
        <Skeleton className="h-4 w-full mt-2" />
        <Skeleton className="h-4 w-2/3" />
        <Skeleton className="h-6 w-24 mt-2" />
      </CardContent>
      <div className="h-14 bg-gray-3/30 rounded-b-xl" />
    </Card>
  );
};

type AutomationsEmptyStateProps = {
  onRefresh: () => void;
  agentsVisible: boolean;
  userHasPermissionToWriteAgent: boolean;
  isCreatingAgent: boolean;
  onCreateAgent: () => void;
};

export const AutomationsEmptyState = ({
  onRefresh,
  agentsVisible,
  userHasPermissionToWriteAgent,
  isCreatingAgent,
  onCreateAgent,
}: AutomationsEmptyStateProps) => {
  const navigate = useNavigate();
  const { embedState } = useEmbedding();
  const [isImportTableDialogOpen, setIsImportTableDialogOpen] = useState(false);
  const [isTemplatesBrowseDialogOpen, setIsTemplatesBrowseDialogOpen] =
    useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(
    null,
  );
  const [useTemplateDialogOpen, setUseTemplateDialogOpen] = useState(false);

  const { checkAccess } = useAuthorization();
  const userHasPermissionToWriteFlow = checkAccess(Permission.WRITE_FLOW);
  const userHasPermissionToWriteTable = checkAccess(Permission.WRITE_TABLE);

  const { platform } = platformHooks.useCurrentPlatform();
  const isShowingOfficialTemplates = !platform.plan.manageTemplatesEnabled;

  const { templates, isLoading: isLoadingTemplates } =
    templatesHooks.useTemplates(
      isShowingOfficialTemplates ? TemplateType.OFFICIAL : TemplateType.CUSTOM,
    );

  const { mutate: createFlow, isPending: isCreateFlowPending } =
    flowHooks.useStartFromScratch(UncategorizedFolderId);

  const { mutate: createTable, isPending: isCreateTablePending } =
    tableHooks.useCreateTable(UncategorizedFolderId);

  const handleTemplateSelect = (template: Template) => {
    if (embedState.isEmbedded) {
      setSelectedTemplate(template);
      setUseTemplateDialogOpen(true);
    } else {
      navigate(`/templates/${template.id}`);
    }
  };

  const handleViewAllTemplates = () => {
    if (embedState.isEmbedded) {
      setIsTemplatesBrowseDialogOpen(true);
    } else {
      navigate('/templates');
    }
  };

  const topTemplates = templates?.slice(0, 3) || [];
  const hasTemplates = topTemplates.length > 0;
  const branding = flagsHooks.useWebsiteBranding();

  return (
    <div className="@container flex flex-col gap-8 py-8 px-4 w-full max-w-5xl mx-auto">
      <div>
        <h2 className="text-sm font-medium text-gray-11 mb-4">
          {t('Get started with {brandName}', {
            brandName: branding.websiteName ?? platform.name,
          })}
        </h2>
        <div className="flex flex-col @2xl:flex-row gap-4">
          <GetStartedCard
            icon={<Workflow className="h-5 w-5 text-accent-11" />}
            iconBgClass="bg-accent-3"
            title={t('Build a Flow')}
            description={t('Create automated workflows')}
          >
            <ActionRow
              icon={<Plus className="h-4 w-4" />}
              label={t('Start from scratch')}
              onClick={() => createFlow()}
              disabled={isCreateFlowPending}
              hasPermission={userHasPermissionToWriteFlow}
            />
            <PermissionNeededTooltip
              hasPermission={userHasPermissionToWriteFlow}
            >
              <ImportFlowDialog
                insideBuilder={false}
                onRefresh={onRefresh}
                folderId={UncategorizedFolderId}
              >
                <button
                  disabled={!userHasPermissionToWriteFlow}
                  className="flex items-center justify-between w-full px-4 py-3 text-left hover:bg-gray-3/50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed border-t"
                >
                  <div className="flex items-center gap-3">
                    <span className="text-gray-11">
                      <Upload className="h-4 w-4" />
                    </span>
                    <span className="text-sm font-medium">{t('Import')}</span>
                  </div>
                  <ChevronRight className="h-4 w-4 text-gray-11" />
                </button>
              </ImportFlowDialog>
            </PermissionNeededTooltip>
            <ActionRow
              icon={<Sparkles className="h-4 w-4" />}
              label={t('Use Templates')}
              onClick={() => {
                if (embedState.isEmbedded) {
                  setIsTemplatesBrowseDialogOpen(true);
                } else {
                  navigate('/templates');
                }
              }}
              hasPermission={userHasPermissionToWriteFlow}
            />
          </GetStartedCard>

          {!embedState.hideTables && (
            <GetStartedCard
              icon={<Table2 className="h-5 w-5 text-accent-11" />}
              iconBgClass="bg-accent-3"
              title={t('Create a Table')}
              description={t('Organize and manage data')}
            >
              <ActionRow
                icon={<Plus className="h-4 w-4" />}
                label={t('Start from scratch')}
                onClick={() => createTable({ name: t('New Table') })}
                disabled={isCreateTablePending}
                hasPermission={userHasPermissionToWriteTable}
              />
              <ActionRow
                icon={<Upload className="h-4 w-4" />}
                label={t('Import')}
                onClick={() => setIsImportTableDialogOpen(true)}
                hasPermission={userHasPermissionToWriteTable}
              />
            </GetStartedCard>
          )}

          {agentsVisible && (
            <GetStartedCard
              icon={<Bot className="h-5 w-5 text-accent-11" />}
              iconBgClass="bg-accent-3"
              title={t('Build an Agent')}
              description={t('Delegate tasks to AI')}
            >
              <ActionRow
                icon={<Plus className="h-4 w-4" />}
                label={t('Start from scratch')}
                onClick={onCreateAgent}
                disabled={isCreatingAgent}
                hasPermission={userHasPermissionToWriteAgent}
              />
            </GetStartedCard>
          )}
        </div>
      </div>

      {(hasTemplates || isLoadingTemplates) && (
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-medium text-gray-11 flex items-center gap-2">
              {t('Templates For You')}
              <Sparkles className="h-4 w-4 text-swatch-6-mark" />
            </h2>
            <button
              onClick={handleViewAllTemplates}
              className="text-sm text-gray-11 hover:text-gray-12 flex items-center gap-1 transition-colors"
            >
              {t('All templates')}
              <ChevronRight className="h-4 w-4" />
            </button>
          </div>
          <div className="grid grid-cols-1 @3xl:grid-cols-3 gap-4">
            {isLoadingTemplates ? (
              <>
                <TemplateCardSkeleton />
                <TemplateCardSkeleton />
                <TemplateCardSkeleton />
              </>
            ) : (
              topTemplates.map((template) => (
                <SuggestedTemplateCard
                  key={template.id}
                  template={template}
                  onSelect={handleTemplateSelect}
                />
              ))
            )}
          </div>
        </div>
      )}

      {!embedState.hideTables && (
        <ImportTableDialog
          open={isImportTableDialogOpen}
          setIsOpen={setIsImportTableDialogOpen}
          showTrigger={false}
        />
      )}
      <TemplatesBrowseDialog
        open={isTemplatesBrowseDialogOpen}
        onOpenChange={setIsTemplatesBrowseDialogOpen}
      />
      {selectedTemplate && (
        <UseTemplateDialog
          key={selectedTemplate.id}
          template={selectedTemplate}
          open={useTemplateDialogOpen}
          onOpenChange={(isOpen) => {
            setUseTemplateDialogOpen(isOpen);
            if (!isOpen) setSelectedTemplate(null);
          }}
        />
      )}
    </div>
  );
};