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.5 KB
Raw Blame
'use client';

import type { AcceptanceCommentItem } from '@lobechat/types';
import type { DropdownItem } from '@lobehub/ui';
import {
  ActionIcon,
  Avatar,
  confirmModal,
  DropdownMenu,
  Flexbox,
  Icon,
  Tag,
  Text,
  toast,
} from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
import { Link2, MoreHorizontal, Trash2 } from 'lucide-react';
import { memo, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useAcceptanceOrigin } from '@/features/Acceptance/origin';
import { useActivityTime } from '@/hooks/useActivityTime';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';

import { commentAnchorUrl } from './anchor';
import CommentContent from './CommentContent';
import CommentReactions from './CommentReactions';
import { styles, TIMELINE_NODE } from './styles';

export const commentAuthorName = (author: AcceptanceCommentItem['author']) =>
  author.fullName || author.username || 'β€”';

/**
 * The author's face, plain. No ring: colour identifies the marks someone drew
 * on the evidence, and wrapping it around their avatar here said nothing while
 * making a quiet list look decorated.
 *
 * With no picture the fallback draws the name as text, and a two-character CJK
 * name wraps inside a small circle β€” so only the first character is handed over.
 */
export const CommentAvatar = memo<{ comment: AcceptanceCommentItem; size?: number }>(
  ({ comment, size = 20 }) => {
    const name = commentAuthorName(comment.author);
    return <Avatar avatar={comment.author.avatar || name.slice(0, 1)} size={size} />;
  },
);

CommentAvatar.displayName = 'AcceptanceCommentAvatar';

interface CommentCardProps {
  /** Present where the row is addressable β€” enables "copy link" in the menu. */
  anchored?: boolean;
  /** Rendered after the author line β€” anchor chip, round tag, resolved tag. */
  badges?: ReactNode;
  comment: AcceptanceCommentItem;
  /**
   * Replaces the author line for a row that is not a remark. A round's note
   * says "<agent> completed round N" β€” the landing and who did it in one line,
   * instead of an event row above a message that repeats the author.
   */
  nameOverride?: string;
  onDelete?: (id: string) => Promise<void>;
  /** Absent where reactions do not belong: a region note is a working thread. */
  onReact?: (id: string, emoji: string, on: boolean) => Promise<void>;
  /** True where the reader may write; the chips render for everyone else too. */
  reactable?: boolean;
  /**
   * `boxed` is the discussion message: a header strip over the body.
   * `plain` is the floating note: the same content with no frame of its own.
   * `feed` is the discussion feed: an author line, the words indented under it.
   */
  variant?: 'boxed' | 'feed' | 'plain';
}

/** One remark: who, when, what β€” and the author's own actions behind a menu. */
const CommentCard = memo<CommentCardProps>(
  ({
    anchored,
    badges,
    comment,
    nameOverride,
    onDelete,
    onReact,
    reactable,
    variant = 'boxed',
  }) => {
    const { t } = useTranslation('verify');
    const time = useActivityTime(comment.createdAt);
    const appOrigin = useAcceptanceOrigin();
    const [deleting, setDeleting] = useState(false);
    const name = nameOverride ?? commentAuthorName(comment.author);
    const viewerId = useUserStore(userProfileSelectors.userId);
    const own = Boolean(viewerId) && comment.authorUserId === viewerId;

    const copyAnchor = async () => {
      try {
        await navigator.clipboard.writeText(commentAnchorUrl(comment.id, appOrigin));
        toast.success(t('acceptance.comments.linkCopied'));
      } catch (cause) {
        console.error('[acceptance:comments]', cause);
        toast.error(t('acceptance.comments.updateFailed'));
      }
    };

    const menuItems: DropdownItem[] = [
      ...(anchored
        ? [
            {
              icon: <Icon icon={Link2} />,
              key: 'copy-link',
              label: t('acceptance.comments.copyLink'),
              onClick: copyAnchor,
            } satisfies DropdownItem,
          ]
        : []),
      ...(comment.canDelete && onDelete
        ? [
            {
              danger: true,
              icon: <Icon icon={Trash2} />,
              key: 'delete',
              // Taking down someone else's remark is a different act from
              // deleting your own, and the confirm says which one this is.
              label: own ? t('acceptance.comments.delete') : t('acceptance.comments.removeOthers'),
              onClick: () =>
                confirmModal({
                  content: own
                    ? t('acceptance.comments.deleteConfirm')
                    : t('acceptance.comments.removeOthersConfirm'),
                  okButtonProps: { danger: true },
                  okText: own
                    ? t('acceptance.comments.delete')
                    : t('acceptance.comments.removeOthers'),
                  onOk: async () => {
                    setDeleting(true);
                    try {
                      await onDelete(comment.id);
                    } catch (cause) {
                      console.error('[acceptance:comments]', cause);
                      toast.error(t('acceptance.comments.deleteFailed'));
                    } finally {
                      setDeleting(false);
                    }
                  },
                }),
            } satisfies DropdownItem,
          ]
        : []),
    ];

    return (
      <>
        <Flexbox
          horizontal
          align={'center'}
          gap={8}
          wrap={'wrap'}
          {...stylex.props(variant === 'boxed' && styles.boxHeader)}
        >
          {variant === 'plain' && <CommentAvatar comment={comment} size={18} />}
          {variant === 'feed' && <CommentAvatar comment={comment} size={TIMELINE_NODE} />}
          <Text
            fontSize={14}
            weight={600}
            {...stylex.props(nameOverride ? styles.headline : styles.authorName)}
          >
            {name}
          </Text>
          {comment.author.type === 'agent' && (
            <Tag size={'small'}>{t('acceptance.comments.author.agent')}</Tag>
          )}
          {comment.author.status !== 'active' && (
            <Tag size={'small'}>{t(`acceptance.comments.author.${comment.author.status}`)}</Tag>
          )}
          {anchored ? (
            /*
             * The timestamp IS the permalink, the way every threaded discussion
             * has trained people to expect: it is the one part of a remark that
             * belongs to that remark alone. Clicking copies its address instead
             * of navigating β€” the reader is already looking at it, and what they
             * want is the link to paste somewhere else.
             */
            <button
              {...stylex.props(styles.meta, styles.timeLink)}
              title={t('acceptance.comments.copyLinkHint', { time: time.title })}
              type={'button'}
              onClick={(event) => {
                event.stopPropagation();
                void copyAnchor();
              }}
            >
              {nameOverride ? time.text : t('acceptance.comments.commented', { time: time.text })}
            </button>
          ) : (
            <span {...stylex.props(styles.meta)} title={time.title}>
              {nameOverride ? time.text : t('acceptance.comments.commented', { time: time.text })}
            </span>
          )}
          {badges}
          {menuItems.length > 0 && (
            <div {...stylex.props(styles.rowActions)}>
              <DropdownMenu
                items={menuItems}
                placement={'bottomRight'}
                popupProps={{ style: { minWidth: 140 } }}
              >
                <ActionIcon
                  icon={MoreHorizontal}
                  loading={deleting}
                  size={'small'}
                  title={t('acceptance.comments.moreActions')}
                />
              </DropdownMenu>
            </div>
          )}
        </Flexbox>
        <div
          {...stylex.props(
            variant === 'boxed'
              ? styles.body
              : variant === 'feed'
                ? styles.feedBody
                : styles.panelBody,
          )}
        >
          <CommentContent comment={comment} />
          {onReact && (
            <CommentReactions
              reactions={comment.reactions}
              onReact={reactable ? (emoji, on) => onReact(comment.id, emoji, on) : undefined}
            />
          )}
        </div>
      </>
    );
  },
);

CommentCard.displayName = 'AcceptanceCommentCard';

export default CommentCard;