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.9 KB
Raw Blame
import type {
  DeviceGitPullRequestAction,
  DeviceGitPullRequestActivity,
  DeviceGitPullRequestDetail,
} from '@lobechat/types';
// oxlint-disable-next-line stylex-migration/no-emotion-styles -- Markdown output gets no className
import { createStaticStyles, Flexbox, Markdown } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { FolderOpenIcon, GitCommitHorizontalIcon } from 'lucide-react';
import { memo, type ReactNode, useId, useState } from 'react';
import { useTranslation } from 'react-i18next';

import AsyncError from '@/components/AsyncError';
import type { GitReplicaReadResult } from '@/store/device';
import { useDensityTokens } from '@/styles/density';
import { sx } from '@/styles/sx';

import { SidebarRowSkeleton } from '../DeferredSkeleton';
import { ChevronRight, OverviewRow, rowStyles } from '../Overview/OverviewRow';
import { SectionHeader } from '../Overview/SectionHeader';
import { sectionProps } from '../Overview/sectionStyles';
import ActivityTimeline from './ActivityTimeline';
import ChecksList from './ChecksList';
import { timeAgo } from './prVisual';
import type { PullRequestBusy } from './usePullRequestActions';

const styles = stylex.create({
  body: {
    overflow: 'hidden',
    minWidth: 0,
    paddingBlockStart: '2px',
    paddingBlockEnd: '6px',
    paddingInline: '6px',
    overflowWrap: 'anywhere',
  },
  sha: { fontFamily: cssVar.fontFamilyCode },
});

const fallback = createStaticStyles(({ css }) => ({
  body: css`
    table {
      overflow-x: auto;
      display: block;
      max-width: 100%;
    }

    img,
    video {
      max-width: 100%;
    }

    pre {
      overflow-x: auto;
      max-width: 100%;
    }
  `,
}));

interface SectionProps {
  children: ReactNode;
  count?: ReactNode;
  onToggle?: () => void;
  open?: boolean;
  title: string;
}

const Section = memo<SectionProps>(({ children, count, onToggle, open = true, title }) => {
  const bodyId = useId();
  return (
    <Flexbox {...sectionProps(true)}>
      <SectionHeader
        collapsed={!open}
        controls={onToggle ? bodyId : undefined}
        count={count}
        title={title}
        onToggle={onToggle}
      />
      {open && (
        <Flexbox gap={1} id={bodyId}>
          {children}
        </Flexbox>
      )}
    </Flexbox>
  );
});

Section.displayName = 'PullRequestSection';

interface SectionsProps {
  actionsDisabled?: boolean;
  activity: Pick<
    GitReplicaReadResult<DeviceGitPullRequestActivity>,
    'data' | 'error' | 'isValidating' | 'mutate'
  >;
  busy?: PullRequestBusy;
  detail: DeviceGitPullRequestDetail;
  onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;
  onOpenTab: (tab: string) => void;
}

const Sections = memo<SectionsProps>(
  ({ actionsDisabled, activity, busy, detail, onAction, onOpenTab }) => {
    const { t } = useTranslation('chat');
    const density = useDensityTokens();
    const activityPlaceholder = activity.error ? (
      <AsyncError
        align={'start'}
        error={activity.error}
        retrying={activity.isValidating}
        title={t('workingPanel.pr.error.load')}
        variant={'inline'}
        onRetry={() => void activity.mutate()}
      />
    ) : (
      <SidebarRowSkeleton rows={3} />
    );
    const [open, setOpen] = useState({
      activity: true,
      checks: false,
      commits: false,
      description: true,
    });
    const toggle = (key: keyof typeof open) => () => setOpen((o) => ({ ...o, [key]: !o[key] }));

    // Older devices (and persisted rows) may omit the list fields.
    const checks = detail.checks ?? [];
    const commits = detail.commits ?? [];
    const activityCount = (detail.comments?.length ?? 0) + (detail.reviews?.length ?? 0);
    const failing = checks.filter(
      (check) => check.status === 'failure' || check.status === 'cancelled',
    ).length;
    const running = checks.filter((check) => check.status === 'pending').length;
    const checksCount = failing ? (
      <span style={{ color: cssVar.colorError }}>
        {t('workingPanel.pr.checks.failing', { count: failing })}
      </span>
    ) : running ? (
      <span style={{ color: cssVar.colorWarning }}>
        {t('workingPanel.pr.checks.running', { count: running })}
      </span>
    ) : (
      checks.length
    );

    return (
      <>
        {detail.body && (
          <Section
            open={open.description}
            title={t('workingPanel.pr.section.description')}
            onToggle={toggle('description')}
          >
            <Markdown
              fontSize={density.fontSize}
              variant={'chat'}
              {...sx(styles.body, fallback.body)}
            >
              {detail.body}
            </Markdown>
          </Section>
        )}
        <Section count={detail.changedFiles} title={t('workingPanel.pr.section.files')}>
          <OverviewRow
            icon={FolderOpenIcon}
            value={t('workingPanel.pr.files.openReview')}
            trailing={
              <>
                <span {...stylex.props(rowStyles.changeAdditions)}>+{detail.additions}</span>
                <span {...stylex.props(rowStyles.changeDeletions)}>−{detail.deletions}</span>
                <ChevronRight />
              </>
            }
            onClick={() => onOpenTab('review')}
          />
        </Section>
        {checks.length > 0 && (
          <Section
            count={checksCount}
            open={open.checks}
            title={t('workingPanel.pr.section.checks')}
            onToggle={toggle('checks')}
          >
            <ChecksList checks={checks} />
          </Section>
        )}
        <Section
          count={activity.data ? commits.length : undefined}
          open={open.commits}
          title={t('workingPanel.pr.section.commits')}
          onToggle={toggle('commits')}
        >
          {!activity.data
            ? activityPlaceholder
            : commits.map((commit) => (
                <OverviewRow
                  icon={GitCommitHorizontalIcon}
                  key={commit.sha}
                  title={commit.message}
                  value={commit.message.split('\n')[0]}
                  trailing={
                    <>
                      <span {...stylex.props(styles.sha)}>{commit.sha.slice(0, 7)}</span>
                      {timeAgo(commit.committedAt)}
                    </>
                  }
                />
              ))}
        </Section>
        <Section
          count={activity.data ? activityCount : undefined}
          open={open.activity}
          title={t('workingPanel.pr.section.activity')}
          onToggle={toggle('activity')}
        >
          {activity.data ? (
            <ActivityTimeline
              actionsDisabled={actionsDisabled}
              busy={busy}
              detail={detail}
              onAction={onAction}
            />
          ) : (
            activityPlaceholder
          )}
        </Section>
      </>
    );
  },
);

Sections.displayName = 'PullRequestSections';

export default Sections;