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.

8.1 KB
Raw Blame
import type {
  DeviceGitPullRequestAction,
  DeviceGitPullRequestDetail,
  DeviceGitPullRequestReview,
} from '@lobechat/types';
// oxlint-disable-next-line stylex-migration/no-emotion-styles -- Markdown output gets no className
import { Avatar, Button, createStaticStyles, Flexbox, Icon, Markdown, TextArea } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import type { LucideIcon } from 'lucide-react';
import { CheckIcon, CircleSlashIcon, EyeIcon, GitCommitHorizontalIcon, XIcon } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useDensityTokens } from '@/styles/density';
import { sidebarRow } from '@/styles/density.stylex';
import { sx } from '@/styles/sx';
import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';

import type { Tone } from './mergeDockData';
import { timeAgo, TONE_COLOR, type TranslateKey } from './prVisual';
import type { PullRequestBusy } from './usePullRequestActions';

const styles = stylex.create({
  comment: {
    paddingBlock: '6px',
    paddingInline: '8px',
    borderRadius: sidebarRow.radius,
    backgroundColor: { 'default': null, ':hover': cssVar.colorFillQuaternary },
    backgroundImage: { 'default': null, ':hover': 'none' },
  },
  commentBody: {
    overflow: 'hidden',
    minWidth: 0,
    fontSize: sidebarRow.textFontSize,
    lineHeight: sidebarRow.textLineHeight,
    overflowWrap: 'anywhere',
  },
  commentBodyWrap: { overflow: 'hidden', minWidth: 0, paddingInlineStart: '26px' },
  commentHead: { fontSize: '12px', color: cssVar.colorTextTertiary },
  commentHeadAuthor: { fontWeight: 500, color: cssVar.colorText },
  composer: { paddingBlockStart: '4px', paddingBlockEnd: 0, paddingInline: '4px' },
  event: {
    minHeight: sidebarRow.height,
    paddingBlock: '2px',
    paddingInline: '8px',
    fontSize: '12px',
    color: cssVar.colorTextTertiary,
  },
  eventAuthor: { fontWeight: 500, color: cssVar.colorTextSecondary },
  eventCode: { fontFamily: cssVar.fontFamilyCode, fontSize: '11px' },
  sha: {
    cursor: 'pointer',
    textDecorationLine: 'underline',
    textDecorationStyle: 'dotted',
    textUnderlineOffset: '2px',
    color: { 'default': null, ':hover': cssVar.colorText },
  },
});

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

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

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

const githubAvatar = (login: string) => `https://github.com/${login}.png?size=36`;

const REVIEW_VISUAL: Record<
  DeviceGitPullRequestReview['state'],
  { icon: LucideIcon; labelKey: string; tone: Tone }
> = {
  APPROVED: { icon: CheckIcon, labelKey: 'workingPanel.pr.activity.approved', tone: 'success' },
  CHANGES_REQUESTED: {
    icon: XIcon,
    labelKey: 'workingPanel.pr.activity.changesRequested',
    tone: 'error',
  },
  COMMENTED: { icon: EyeIcon, labelKey: 'workingPanel.pr.activity.commented', tone: 'neutral' },
  DISMISSED: {
    icon: CircleSlashIcon,
    labelKey: 'workingPanel.pr.activity.dismissed',
    tone: 'neutral',
  },
  PENDING: { icon: EyeIcon, labelKey: 'workingPanel.pr.activity.commented', tone: 'neutral' },
};

type Entry =
  | { at: string; kind: 'comment'; author: string; body: string; id: string }
  | { at: string; kind: 'commit'; author: string; sha: string }
  | { at: string; kind: 'review'; author: string; state: DeviceGitPullRequestReview['state'] };

const buildTimeline = (detail: DeviceGitPullRequestDetail): Entry[] =>
  [
    ...detail.comments.map<Entry>((comment) => ({
      at: comment.createdAt,
      author: comment.author,
      body: comment.body,
      id: comment.id,
      kind: 'comment',
    })),
    ...detail.commits.map<Entry>((commit) => ({
      at: commit.committedAt,
      author: commit.author,
      kind: 'commit',
      sha: commit.sha,
    })),
    ...detail.reviews.map<Entry>((review) => ({
      at: review.submittedAt,
      author: review.author,
      kind: 'review',
      state: review.state,
    })),
  ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));

interface ActivityTimelineProps {
  actionsDisabled?: boolean;
  busy?: PullRequestBusy;
  detail: DeviceGitPullRequestDetail;
  onAction: (action: DeviceGitPullRequestAction) => Promise<boolean>;
}

const ActivityTimeline = memo<ActivityTimelineProps>(
  ({ actionsDisabled, busy, detail, onAction }) => {
    const { t } = useTranslation('chat');
    const tr = t as unknown as TranslateKey;
    const density = useDensityTokens();
    const [draft, setDraft] = useState('');
    const timeline = useMemo(() => buildTimeline(detail), [detail]);

    const submit = async () => {
      const body = draft.trim();
      if (!body) return;
      if (await onAction({ body, type: 'comment' })) setDraft('');
    };

    return (
      <>
        {timeline.map((entry) => {
          if (entry.kind === 'comment')
            return (
              <div {...stylex.props(styles.comment)} key={entry.id}>
                <Flexbox horizontal align={'center'} {...stylex.props(styles.commentHead)} gap={8}>
                  <Avatar avatar={githubAvatar(entry.author)} size={18} />
                  <strong {...stylex.props(styles.commentHeadAuthor)}>{entry.author}</strong>
                  <span>{timeAgo(entry.at)}</span>
                </Flexbox>
                <div {...stylex.props(styles.commentBodyWrap)}>
                  <Markdown
                    fontSize={density.fontSize}
                    variant={'chat'}
                    {...sx(styles.commentBody, fallback.commentBody)}
                  >
                    {entry.body}
                  </Markdown>
                </div>
              </div>
            );
          const visual =
            entry.kind === 'review'
              ? REVIEW_VISUAL[entry.state]
              : {
                  icon: GitCommitHorizontalIcon,
                  labelKey: 'workingPanel.pr.activity.committed',
                  tone: 'neutral' as Tone,
                };
          return (
            <Flexbox
              horizontal
              align={'center'}
              {...stylex.props(styles.event)}
              gap={12}
              key={entry.kind === 'commit' ? entry.sha : `review:${entry.author}:${entry.at}`}
            >
              <Icon
                icon={visual.icon}
                size={density.iconSize}
                style={visual.tone === 'neutral' ? undefined : { color: TONE_COLOR[visual.tone] }}
              />
              <span>
                <strong {...stylex.props(styles.eventAuthor)}>{entry.author}</strong>{' '}
                {tr(visual.labelKey)}{' '}
                {entry.kind === 'commit' && (
                  <code
                    {...stylex.props(styles.eventCode, styles.sha)}
                    onClick={() =>
                      openTrustedExternalUrl(
                        `https://github.com/${detail.repo.owner}/${detail.repo.name}/pull/${detail.number}/commits/${entry.sha}`,
                      )
                    }
                  >
                    {entry.sha.slice(0, 7)}
                  </code>
                )}{' '}
                · {timeAgo(entry.at)}
              </span>
            </Flexbox>
          );
        })}
        <Flexbox {...stylex.props(styles.composer)} gap={6}>
          <TextArea
            autoSize={{ minRows: 1 }}
            placeholder={t('workingPanel.pr.composer.placeholder')}
            value={draft}
            variant={'filled'}
            onChange={(e) => setDraft(e.target.value)}
          />
          <Flexbox horizontal justify={'flex-end'}>
            <Button
              disabled={!draft.trim() || !!busy || actionsDisabled}
              loading={busy === 'comment'}
              size={'small'}
              onClick={() => void submit()}
            >
              {t('workingPanel.pr.composer.submit')}
            </Button>
          </Flexbox>
        </Flexbox>
      </>
    );
  },
);

ActivityTimeline.displayName = 'PullRequestActivityTimeline';

export default ActivityTimeline;