From 1286d5d6357a3bff871f864a9a1808251f5d17fc Mon Sep 17 00:00:00 2001 From: nicktytarenko Date: Sat, 1 Aug 2026 16:34:02 +0300 Subject: [PATCH 1/3] Add financial activity feed types and redesigned activity cards. Introduce related-work/funding activity transformers and rebuild activity cards around work previews and header messaging so financial events render correctly. Co-authored-by: Cursor --- app/activity/page.tsx | 5 +- app/grant/[id]/[slug]/page.tsx | 7 +- components/Activity/ActivityCardFull.tsx | 200 ++++++------ components/Activity/ActivityCardHeader.tsx | 95 ++++++ components/Activity/ActivityCardSkeleton.tsx | 52 ++-- .../Activity/ActivityHeaderActionText.tsx | 43 +++ components/Activity/AmountBadge.tsx | 27 ++ components/Activity/BountyAmount.tsx | 32 ++ components/Activity/ContributionAmount.tsx | 12 +- components/Activity/FeedEntryIcon.tsx | 43 ++- components/Activity/GrantFundingAmount.tsx | 4 +- components/Activity/ReviewScoreStars.tsx | 38 +++ components/Activity/WorkCardActions.tsx | 37 +++ components/Activity/WorkPreviewCard.tsx | 177 +++++++++++ .../Activity/lib/activityWorkContext.ts | 287 ++++++++++++++++++ .../Activity/lib/deriveActivityContext.ts | 40 +++ components/Activity/lib/feedEntryAdapters.ts | 184 ++++++++++- components/Comment/CommentReadOnly.tsx | 6 +- components/Comment/lib/TipTapRenderer.tsx | 27 +- components/Feed/FeedItemActions.tsx | 209 +++++++------ components/Funding/ActivityCard.tsx | 111 ++++--- components/Funding/GrantContentSwitcher.tsx | 29 +- .../work/WorkHeader/WorkHeaderGrant.tsx | 4 +- hooks/useActivityFeed.ts | 7 +- services/activity.service.ts | 13 +- types/feed.ts | 213 ++++++++++++- types/work.ts | 10 + 27 files changed, 1586 insertions(+), 326 deletions(-) create mode 100644 components/Activity/ActivityCardHeader.tsx create mode 100644 components/Activity/ActivityHeaderActionText.tsx create mode 100644 components/Activity/AmountBadge.tsx create mode 100644 components/Activity/BountyAmount.tsx create mode 100644 components/Activity/ReviewScoreStars.tsx create mode 100644 components/Activity/WorkCardActions.tsx create mode 100644 components/Activity/WorkPreviewCard.tsx create mode 100644 components/Activity/lib/activityWorkContext.ts create mode 100644 components/Activity/lib/deriveActivityContext.ts diff --git a/app/activity/page.tsx b/app/activity/page.tsx index 4cb34ccd5..00bc7dfae 100644 --- a/app/activity/page.tsx +++ b/app/activity/page.tsx @@ -8,7 +8,7 @@ import { PageLayout } from '@/app/layouts/PageLayout'; import { HeroHeader } from '@/components/ui/HeroHeader'; import { PillTabs } from '@/components/ui/PillTabs'; import { ActivityCardFull } from '@/components/Activity/ActivityCardFull'; -import { ActivityCardSkeletonList } from '@/components/Activity/ActivityCardSkeleton'; +import { ActivityCardSkeleton } from '@/components/Activity/ActivityCardSkeleton'; import { useActivityFeed, ActivityTab } from '@/hooks/useActivityFeed'; import { ActivityScope } from '@/services/activity.service'; import { GrantService } from '@/services/grant.service'; @@ -106,7 +106,8 @@ export default function ActivityPage() { ))} - {(isLoading || isLoadingMore) && } + {(isLoading || isLoadingMore) && + [...Array(6)].map((_, i) => )} {!isLoading && !isLoadingMore && entries.length === 0 && (
diff --git a/app/grant/[id]/[slug]/page.tsx b/app/grant/[id]/[slug]/page.tsx index f8150136e..a6e010542 100644 --- a/app/grant/[id]/[slug]/page.tsx +++ b/app/grant/[id]/[slug]/page.tsx @@ -41,12 +41,7 @@ export default async function GrantSlugPage({ params }: Props) { const grantId = grant?.id ?? undefined; return ( - + {grant?.description && } diff --git a/components/Activity/ActivityCardFull.tsx b/components/Activity/ActivityCardFull.tsx index 48a0d1da8..3583df8a9 100644 --- a/components/Activity/ActivityCardFull.tsx +++ b/components/Activity/ActivityCardFull.tsx @@ -1,24 +1,21 @@ 'use client'; import { FC, useState } from 'react'; -import Link from 'next/link'; -import { Star, ChevronDown, ChevronUp } from 'lucide-react'; +import { useRouter } from 'next/navigation'; +import { ArrowRight } from 'lucide-react'; import { Avatar } from '@/components/ui/Avatar'; import { AuthorTooltip } from '@/components/ui/AuthorTooltip'; +import { Button } from '@/components/ui/Button'; import { CommentReadOnly } from '@/components/Comment/CommentReadOnly'; -import { ContributionAmount } from './ContributionAmount'; -import { FeedEntryIcon } from './FeedEntryIcon'; -import { GrantFundingAmount } from './GrantFundingAmount'; -import { - getActionIcon, - getActionLabel, - getCommentPreview, - getContribution, - getEntryMeta, - getGrantAmount, - getReviewScore, -} from './lib/feedEntryAdapters'; -import { formatTimeAgo } from '@/utils/date'; +import { ContributeToFundraiseModal } from '@/components/modals/ContributeToFundraiseModal'; +import { useCurrencyPreference } from '@/contexts/CurrencyPreferenceContext'; +import { useExchangeRate } from '@/contexts/ExchangeRateContext'; +import { useShareModalContext } from '@/contexts/ShareContext'; +import { ActivityCardHeader } from './ActivityCardHeader'; +import { WorkCardActions } from './WorkCardActions'; +import { WorkPreviewCard } from './WorkPreviewCard'; +import { getActivityHeaderMessage, getCommentPreview } from './lib/feedEntryAdapters'; +import { getActivityWorkContext, getWorkCardPresentation } from './lib/activityWorkContext'; import type { FeedEntry } from '@/types/feed'; interface ActivityCardFullProps { @@ -26,96 +23,125 @@ interface ActivityCardFullProps { } export const ActivityCardFull: FC = ({ entry }) => { - const { title, author, href } = getEntryMeta(entry); - const [reviewExpanded, setReviewExpanded] = useState(false); + const work = getActivityWorkContext(entry); + const router = useRouter(); + const { showUSD } = useCurrencyPreference(); + const { exchangeRate } = useExchangeRate(); + const { showShareModal } = useShareModalContext(); + const [isContributeModalOpen, setIsContributeModalOpen] = useState(false); - if (!title) return null; + if (!work) return null; - const actionLabel = getActionLabel(entry); - const actionIcon = getActionIcon(entry); - const reviewScore = getReviewScore(entry); - const grantAmount = getGrantAmount(entry); - const contribution = getContribution(entry); + const message = getActivityHeaderMessage(entry); const commentPreview = getCommentPreview(entry); + const presentation = getWorkCardPresentation(entry, work, { + showUSD, + exchangeRate, + isReview: commentPreview?.isReview, + }); - const titleEl = href ? ( - - {title} - - ) : ( - {title} - ); + const showComment = presentation.showComment && !!commentPreview; + const voteCount = entry.metrics?.adjustedScore ?? entry.metrics?.votes ?? 0; + const isReviewOfProposal = !!commentPreview?.isReview && work.documentType === 'preregistration'; + + const handleFundClick = () => { + setIsContributeModalOpen(true); + }; + + const handleContributeSuccess = () => { + setIsContributeModalOpen(false); + showShareModal({ + url: window.location.href, + docTitle: work.title, + action: 'USER_FUNDED_PROPOSAL', + }); + router.refresh(); + }; + + const action = (() => { + const cta = presentation.cta; + if (!cta) return undefined; + + return ( + + ); + })(); return ( -
-
-
- - - -
-
- {author?.fullName || 'Unknown'} - {actionLabel} - - {reviewScore != null && ( - - - {reviewScore.toFixed(1)} - - )} - {grantAmount && } - {contribution && ( - - )} +
+
+
+
+ + + +
- {titleEl} -
- {commentPreview && !commentPreview.isReview && ( -
- -
- )} +
+ - {commentPreview && commentPreview.isReview && ( -
- - {reviewExpanded && ( + {showComment && commentPreview && (
)} + +
+ + } + /> +
- )} +
- - {formatTimeAgo(entry.timestamp)} - -
+ {work.fundraise && ( + setIsContributeModalOpen(false)} + onContributeSuccess={handleContributeSuccess} + fundraise={work.fundraise} + proposalTitle={work.title} + /> + )} + ); }; diff --git a/components/Activity/ActivityCardHeader.tsx b/components/Activity/ActivityCardHeader.tsx new file mode 100644 index 000000000..98bc2b8e3 --- /dev/null +++ b/components/Activity/ActivityCardHeader.tsx @@ -0,0 +1,95 @@ +'use client'; + +import { FC } from 'react'; +import { ActivityHeaderActionText } from './ActivityHeaderActionText'; +import { BountyAmount } from './BountyAmount'; +import { ContributionAmount } from './ContributionAmount'; +import { FeedEntryIcon } from './FeedEntryIcon'; +import { GrantFundingAmount } from './GrantFundingAmount'; +import { ReviewScoreStars } from './ReviewScoreStars'; +import { + getActionIcon, + getActivityHeaderMessage, + getContribution, + getGrantAmount, + getReviewEarning, + getReviewScore, +} from './lib/feedEntryAdapters'; +import { getActivityBounty } from './lib/activityWorkContext'; +import { formatTimeAgo } from '@/utils/date'; +import { Tooltip } from '@/components/ui/Tooltip'; +import type { FeedEntry } from '@/types/feed'; + +interface ActivityCardHeaderProps { + entry: FeedEntry; +} + +export const ActivityCardHeader: FC = ({ entry }) => { + const message = getActivityHeaderMessage(entry); + const actionIcon = getActionIcon(entry); + const reviewScore = getReviewScore(entry); + const reviewEarning = getReviewEarning(entry); + const grantAmount = getGrantAmount(entry); + const contribution = getContribution(entry); + const bounty = entry.activityContext === 'bounty_opened' ? getActivityBounty(entry) : undefined; + + const hasAmount = Boolean( + grantAmount || contribution || reviewEarning || bounty || reviewScore != null + ); + + return ( +
+
+ + {grantAmount && ( + <> + {' '} + + + )} + {contribution && ( + <> + {' '} + + + )} + {reviewEarning && ( + <> + {' '} + + + )} + {bounty && ( + <> + {' '} + + + )} + {reviewScore != null && reviewScore > 0 && ( + <> + {' '} + + + )} + +
+ + + + {formatTimeAgo(entry.timestamp)} + + +
+ ); +}; diff --git a/components/Activity/ActivityCardSkeleton.tsx b/components/Activity/ActivityCardSkeleton.tsx index ff83e5d26..5f02667f7 100644 --- a/components/Activity/ActivityCardSkeleton.tsx +++ b/components/Activity/ActivityCardSkeleton.tsx @@ -1,41 +1,31 @@ 'use client'; import { FC } from 'react'; -import { cn } from '@/utils/styles'; -const TITLE_WIDTHS = ['w-3/4', 'w-2/3', 'w-5/6'] as const; +export const ActivityCardSkeleton: FC = () => ( +
+
+
-interface ActivityCardSkeletonProps { - titleWidth?: (typeof TITLE_WIDTHS)[number]; -} +
+
+
+
+
+
-export const ActivityCardSkeleton: FC = ({ titleWidth = 'w-2/3' }) => ( -
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-); - -interface ActivityCardSkeletonListProps { - count?: number; - className?: string; -} - -export const ActivityCardSkeletonList: FC = ({ - count = 15, - className, -}) => ( -
- {Array.from({ length: count }, (_, i) => ( - - ))}
); diff --git a/components/Activity/ActivityHeaderActionText.tsx b/components/Activity/ActivityHeaderActionText.tsx new file mode 100644 index 000000000..58d0bd51f --- /dev/null +++ b/components/Activity/ActivityHeaderActionText.tsx @@ -0,0 +1,43 @@ +'use client'; + +import { FC } from 'react'; +import Link from 'next/link'; +import { AuthorTooltip } from '@/components/ui/AuthorTooltip'; +import type { ActivityHeaderMessage } from './lib/feedEntryAdapters'; + +interface ActivityHeaderActionTextProps { + message: ActivityHeaderMessage; + className?: string; +} + +export const ActivityHeaderActionText: FC = ({ + message, + className, +}) => { + const { actor, verb, target } = message; + + return ( + + + + {actor.fullName || 'Unknown'} + + + {verb} + {target && ( + <> + {' '} + + + {target.author.fullName || 'Unknown'} + + + {target.suffix && {target.suffix}} + + )} + + ); +}; diff --git a/components/Activity/AmountBadge.tsx b/components/Activity/AmountBadge.tsx new file mode 100644 index 000000000..b9297fb49 --- /dev/null +++ b/components/Activity/AmountBadge.tsx @@ -0,0 +1,27 @@ +'use client'; + +import { FC, ReactNode } from 'react'; +import { cn } from '@/utils/styles'; + +const TONES = { + green: 'bg-green-100 text-green-800', + orange: 'bg-orange-100 text-orange-700', +} as const; + +interface AmountBadgeProps { + tone?: keyof typeof TONES; + className?: string; + children: ReactNode; +} + +export const AmountBadge: FC = ({ tone = 'green', className, children }) => ( + + {children} + +); diff --git a/components/Activity/BountyAmount.tsx b/components/Activity/BountyAmount.tsx new file mode 100644 index 000000000..0945aab73 --- /dev/null +++ b/components/Activity/BountyAmount.tsx @@ -0,0 +1,32 @@ +'use client'; + +import { FC } from 'react'; +import { useCurrencyPreference } from '@/contexts/CurrencyPreferenceContext'; +import { useExchangeRate } from '@/contexts/ExchangeRateContext'; +import { getBountyDisplayAmount } from '@/components/Bounty/lib/bountyUtil'; +import { formatCurrency } from '@/utils/currency'; +import { AmountBadge } from './AmountBadge'; +import type { Bounty } from '@/types/bounty'; + +interface BountyAmountProps { + bounty: Bounty; + className?: string; +} + +export const BountyAmount: FC = ({ bounty, className }) => { + const { showUSD } = useCurrencyPreference(); + const { exchangeRate } = useExchangeRate(); + const { amount } = getBountyDisplayAmount(bounty, exchangeRate, showUSD); + + return ( + + {formatCurrency({ + amount: Math.round(amount), + showUSD, + exchangeRate, + skipConversion: true, + shorten: true, + })} + + ); +}; diff --git a/components/Activity/ContributionAmount.tsx b/components/Activity/ContributionAmount.tsx index 9eb3493fe..1ea82a025 100644 --- a/components/Activity/ContributionAmount.tsx +++ b/components/Activity/ContributionAmount.tsx @@ -4,15 +4,21 @@ import { FC } from 'react'; import { useCurrencyPreference } from '@/contexts/CurrencyPreferenceContext'; import { useExchangeRate } from '@/contexts/ExchangeRateContext'; import { formatCurrency } from '@/utils/currency'; -import { cn } from '@/utils/styles'; +import { AmountBadge } from './AmountBadge'; import { resolveDisplayedContribution, type FeedContribution } from './lib/feedEntryAdapters'; interface ContributionAmountProps { contribution: FeedContribution; className?: string; + /** Prefix with "+" (default). Set false for earnings like "earned $150". */ + showSign?: boolean; } -export const ContributionAmount: FC = ({ contribution, className }) => { +export const ContributionAmount: FC = ({ + contribution, + className, + showSign = true, +}) => { const { showUSD } = useCurrencyPreference(); const { exchangeRate } = useExchangeRate(); const { amount, inUSD } = resolveDisplayedContribution(contribution, showUSD, exchangeRate); @@ -25,5 +31,5 @@ export const ContributionAmount: FC = ({ contribution, shorten: true, }); - return +{formatted}; + return {showSign ? `+${formatted}` : formatted}; }; diff --git a/components/Activity/FeedEntryIcon.tsx b/components/Activity/FeedEntryIcon.tsx index 29fdb1e6d..b984e4493 100644 --- a/components/Activity/FeedEntryIcon.tsx +++ b/components/Activity/FeedEntryIcon.tsx @@ -1,9 +1,16 @@ +'use client'; + import { FC } from 'react'; -import { Bell, Coins, MessageCircle, type LucideIcon } from 'lucide-react'; +import { Bell, MessageCircle, type LucideIcon } from 'lucide-react'; +import Icon from '@/components/ui/icons/Icon'; +import { ResearchCoinIcon, RSC_COLORS } from '@/components/ui/icons/ResearchCoinIcon'; +import { useCurrencyPreference } from '@/contexts/CurrencyPreferenceContext'; import type { FeedEntryIconName } from './lib/feedEntryAdapters'; -const ICONS: Record, LucideIcon> = { - coins: Coins, +const ICONS: Record< + Exclude, + LucideIcon +> = { bell: Bell, message: MessageCircle, }; @@ -13,7 +20,33 @@ interface FeedEntryIconProps { } export const FeedEntryIcon: FC = ({ name }) => { + const { showUSD } = useCurrencyPreference(); + if (!name) return null; - const Icon = ICONS[name]; - return ; + if (name === 'coins') { + if (showUSD) return null; + return ; + } + if (name === 'fund') { + return ( + + ); + } + if (name === 'earn') { + return ( + + ); + } + if (name === 'proposal') { + return ( + + ); + } + const IconComponent = ICONS[name]; + return ; }; diff --git a/components/Activity/GrantFundingAmount.tsx b/components/Activity/GrantFundingAmount.tsx index 5ae5b4a5e..c1067a5be 100644 --- a/components/Activity/GrantFundingAmount.tsx +++ b/components/Activity/GrantFundingAmount.tsx @@ -3,7 +3,7 @@ import { FC } from 'react'; import { useCurrencyPreference } from '@/contexts/CurrencyPreferenceContext'; import { formatCurrency } from '@/utils/currency'; -import { cn } from '@/utils/styles'; +import { AmountBadge } from './AmountBadge'; import type { FeedGrantAmount } from './lib/feedEntryAdapters'; interface GrantFundingAmountProps { @@ -21,5 +21,5 @@ export const GrantFundingAmount: FC = ({ amount, classN shorten: true, }); - return {formatted}; + return {formatted}; }; diff --git a/components/Activity/ReviewScoreStars.tsx b/components/Activity/ReviewScoreStars.tsx new file mode 100644 index 000000000..d77d38c0d --- /dev/null +++ b/components/Activity/ReviewScoreStars.tsx @@ -0,0 +1,38 @@ +'use client'; + +import { FC } from 'react'; +import { Star } from 'lucide-react'; +import { cn } from '@/utils/styles'; + +interface ReviewScoreStarsProps { + score: number; + size?: 'sm' | 'md'; + className?: string; +} + +const SIZES = { + sm: 13, + md: 14, +} as const; + +/** Five-star score display; filled up to the rounded score. */ +export const ReviewScoreStars: FC = ({ score, size = 'sm', className }) => { + const rounded = Math.round(score); + + return ( + + {[1, 2, 3, 4, 5].map((i) => ( + + ))} + + ); +}; diff --git a/components/Activity/WorkCardActions.tsx b/components/Activity/WorkCardActions.tsx new file mode 100644 index 000000000..e26767465 --- /dev/null +++ b/components/Activity/WorkCardActions.tsx @@ -0,0 +1,37 @@ +'use client'; + +import { FC, ReactNode } from 'react'; +import { FeedItemActions } from '@/components/Feed/FeedItemActions'; +import type { UserVoteType } from '@/types/reaction'; +import type { FeedContentType } from '@/types/feed'; +import type { ActivityWorkContext } from './lib/activityWorkContext'; + +interface WorkCardActionsProps { + work: ActivityWorkContext; + voteCount: number; + userVote?: UserVoteType; + cta?: ReactNode; +} + +function toFeedContentType(documentType: ActivityWorkContext['documentType']): FeedContentType { + return documentType === 'paper' ? 'PAPER' : 'POST'; +} + +export const WorkCardActions: FC = ({ work, voteCount, userVote, cta }) => ( + +); diff --git a/components/Activity/WorkPreviewCard.tsx b/components/Activity/WorkPreviewCard.tsx new file mode 100644 index 000000000..9b8587f01 --- /dev/null +++ b/components/Activity/WorkPreviewCard.tsx @@ -0,0 +1,177 @@ +'use client'; + +import { FC, ReactNode } from 'react'; +import Link from 'next/link'; +import Image from 'next/image'; +import { Star } from 'lucide-react'; +import { cn } from '@/utils/styles'; +import type { WorkCardAuthor, WorkCardStat } from './lib/activityWorkContext'; + +interface WorkPreviewCardProps { + title: string; + href?: string; + imageSrc?: string; + /** Render a gradient placeholder when no image is available. */ + showPlaceholder?: boolean; + authors?: WorkCardAuthor[]; + /** Funding organization; takes precedence over authors on the meta line. */ + organization?: string | null; + institution?: string | null; + /** Average peer-review score shown next to the authors. */ + score?: number | null; + /** Extra stats on the right of the frosted bar (label + value). */ + stats?: WorkCardStat[]; + /** Fundraise progress in the 0–1 range. */ + progress?: number; + /** Full footer row (typically vote/save/share + CTA). */ + actions?: ReactNode; + className?: string; +} + +/** + * Full-bleed frosted-image card for activity feed rows. + * Image fills the card; metadata sits in a translucent bar at the bottom. + */ +export const WorkPreviewCard: FC = ({ + title, + href, + imageSrc, + showPlaceholder = true, + authors = [], + organization, + institution, + score, + stats, + progress, + actions, + className, +}) => { + const showFooter = !!actions; + + const authorLine = + organization || + (authors.length > 0 + ? authors + .slice(0, 2) + .map((a) => a.name) + .join(', ') + (authors.length > 2 ? ` +${authors.length - 2}` : '') + : institution || null); + + const imageBlock = ( +
+ {imageSrc ? ( + {title} + ) : showPlaceholder ? ( +
+ ) : ( +
+ )} + +
+
+
+
+ {title} +
+ {authorLine && ( +
{authorLine}
+ )} +
+ + {(score != null || stats?.length) && ( +
+ {score != null && ( +
+
+ Rating +
+
+ + {score.toFixed(1)} +
+
+ )} + {stats?.map((s) => ( +
+
+ {s.label} +
+
+ {s.value} +
+
+ ))} +
+ )} +
+ + {progress != null && ( +
+
+
+ )} +
+
+ ); + + return ( +
+ {href ? ( + + {imageBlock} + + ) : ( + imageBlock + )} + + {showFooter && ( +
+
{actions}
+
+ )} +
+ ); +}; diff --git a/components/Activity/lib/activityWorkContext.ts b/components/Activity/lib/activityWorkContext.ts new file mode 100644 index 000000000..3b127e939 --- /dev/null +++ b/components/Activity/lib/activityWorkContext.ts @@ -0,0 +1,287 @@ +import { buildWorkUrl } from '@/utils/url'; +import { isFundraiseActive } from '@/components/Fund/lib/fundraiseUtils'; +import { getBountyDisplayAmount, isOpenBounty } from '@/components/Bounty/lib/bountyUtil'; +import { formatCurrency } from '@/utils/currency'; +import { isDeadlineInFuture } from '@/utils/date'; +import type { ContentType } from '@/types/work'; +import type { + ActivityContext, + FeedBountyContent, + FeedCommentContent, + FeedEntry, + FeedGrantContent, +} from '@/types/feed'; +import type { Bounty } from '@/types/bounty'; +import type { Fundraise } from '@/types/funding'; +import type { AuthorProfile } from '@/types/authorProfile'; +import type { WorkGrantSummary } from '@/types/work'; + +type ActivityBodySlot = 'fundraise' | 'bounty' | 'grant' | 'default'; + +export interface ActivityWorkContext { + id: number; + slug: string; + title: string; + href: string; + imageUrl?: string; + documentType: ContentType; + unifiedDocumentId?: number | null; + fundraise?: Fundraise; + grant?: WorkGrantSummary; + bounty?: Bounty; + authors?: AuthorProfile[]; + tab?: 'reviews' | 'bounties' | 'conversation'; +} + +export interface WorkCardAuthor { + name: string; + verified?: boolean; + authorUrl?: string; +} + +export interface WorkCardStat { + label: string; + value: string; + accent?: boolean; +} + +export type WorkCardCta = + | { kind: 'fund-modal'; label: 'Fund' } + | { kind: 'link'; label: string; href: string }; + +export interface WorkCardPresentation { + authors: WorkCardAuthor[]; + /** Funding organization, shown in place of authors when present. */ + organization?: string | null; + institution?: string | null; + score?: number | null; + stats?: WorkCardStat[]; + progress?: number; + cta?: WorkCardCta; + showComment: boolean; +} + +export function getActivityBounty(entry: FeedEntry): Bounty | undefined { + if (entry.contentType === 'COMMENT') { + return (entry.content as FeedCommentContent).bounties?.[0]; + } + if (entry.contentType === 'BOUNTY') { + return (entry.content as FeedBountyContent).bounty; + } + return undefined; +} + +function resolveTabFromContext(activityContext?: ActivityContext): ActivityWorkContext['tab'] { + switch (activityContext) { + case 'tip_review': + case 'peer_review_published': + return 'reviews'; + case 'bounty_opened': + case 'bounty_contributed': + case 'bounty_payout': + return 'bounties'; + case 'comment_published': + return 'conversation'; + default: + return undefined; + } +} + +function resolveActivityBodySlot( + activityContext?: ActivityContext, + work?: Pick, + options?: { isReview?: boolean } +): ActivityBodySlot { + if (activityContext === 'bounty_opened' || activityContext === 'bounty_contributed') { + return work?.bounty ? 'bounty' : 'default'; + } + if (activityContext === 'grant_opened') { + return work?.grant ? 'grant' : 'default'; + } + if ( + activityContext === 'tip_review' || + activityContext === 'bounty_payout' || + activityContext === 'fundraise_contribution' || + activityContext === 'proposal_submitted' + ) { + return work?.fundraise ? 'fundraise' : 'default'; + } + if (activityContext === 'peer_review_published' || options?.isReview) { + return work?.fundraise ? 'fundraise' : 'default'; + } + if (activityContext === 'comment_published' && work?.fundraise) { + return 'fundraise'; + } + return 'default'; +} + +function toCardAuthors(authors?: AuthorProfile[]): WorkCardAuthor[] { + if (!authors?.length) return []; + return authors + .filter((author) => !!author.fullName?.trim()) + .map((author) => ({ + name: author.fullName, + verified: author.user?.isVerified ?? author.isVerified, + authorUrl: author.id === 0 ? undefined : author.profileUrl, + })); +} + +/** Funding organization, from related work when present and the entry itself otherwise. */ +function resolveOrganization(entry: FeedEntry, work: ActivityWorkContext): string | null { + if (work.grant?.organization) return work.grant.organization; + if (entry.contentType === 'GRANT') { + return (entry.content as FeedGrantContent).grant?.organization || null; + } + return null; +} + +function formatAmount( + amount: number, + showUSD: boolean, + exchangeRate: number, + skipConversion = false +): string { + return formatCurrency({ + amount: Math.round(amount), + showUSD, + exchangeRate, + skipConversion, + shorten: true, + }); +} + +export function getWorkCardPresentation( + entry: FeedEntry, + work: ActivityWorkContext, + options: { showUSD: boolean; exchangeRate: number; isReview?: boolean } +): WorkCardPresentation { + const { showUSD, exchangeRate, isReview } = options; + const slot = resolveActivityBodySlot(entry.activityContext, work, { isReview }); + + // Prefer real document score; omit when absent (no mocks). + const score = + entry.metrics?.reviewScore && entry.metrics.reviewScore > 0 + ? entry.metrics.reviewScore + : work.fundraise?.reviewMetrics?.avg && work.fundraise.reviewMetrics.avg > 0 + ? work.fundraise.reviewMetrics.avg + : null; + + const authors = toCardAuthors(work.authors); + const institution = entry.nonprofit?.name ?? null; + const base: WorkCardPresentation = { + authors, + organization: resolveOrganization(entry, work), + institution, + score, + // Caller ANDs with commentPreview presence; here we only gate by slot. + showComment: slot !== 'bounty' && slot !== 'grant', + }; + + if (slot === 'fundraise' && work.fundraise) { + const fundraise = work.fundraise; + const goalAmount = showUSD ? fundraise.goalAmount.usd : fundraise.goalAmount.rsc; + const goalUsd = fundraise.goalAmount.usd; + const raisedUsd = fundraise.amountRaised.usd; + + return { + ...base, + stats: [ + { + label: 'Raising', + value: formatAmount(goalAmount, showUSD, exchangeRate, true), + accent: true, + }, + ], + progress: goalUsd > 0 ? raisedUsd / goalUsd : undefined, + cta: isFundraiseActive(fundraise) ? { kind: 'fund-modal', label: 'Fund' } : undefined, + }; + } + + if (slot === 'grant' && work.grant) { + const grant = work.grant; + const isActive = + grant.status === 'OPEN' && (grant.endDate ? isDeadlineInFuture(grant.endDate) : true); + const budgetAmount = showUSD ? grant.amount.usd : (grant.amount.rsc ?? 0); + const hasBudget = grant.amount.usd > 0 || (grant.amount.rsc ?? 0) > 0; + const stats: WorkCardStat[] = []; + + if (hasBudget) { + stats.push({ + label: 'Available', + value: formatAmount(budgetAmount, showUSD, exchangeRate, showUSD), + accent: true, + }); + } + stats.push({ + label: 'Proposals', + value: String(grant.numApplicants), + }); + + return { + ...base, + stats: stats.length ? stats : undefined, + cta: isActive ? { kind: 'link', label: 'Apply', href: work.href } : undefined, + }; + } + + if (slot === 'bounty' && work.bounty) { + const bounty = work.bounty; + const { amount } = getBountyDisplayAmount(bounty, exchangeRate, showUSD); + const isReviewBounty = bounty.bountyType === 'REVIEW'; + const href = `${buildWorkUrl({ + id: work.id, + slug: work.slug, + contentType: work.documentType, + tab: 'bounties', + })}?focus=true`; + const active = + bounty.status === 'OPEN' + ? bounty.expirationDate + ? isDeadlineInFuture(bounty.expirationDate) + : true + : bounty.status === 'ASSESSMENT' || isOpenBounty(bounty); + + return { + ...base, + stats: [ + { + label: isReviewBounty ? 'Peer Review' : 'Bounty', + value: formatAmount(amount, showUSD, exchangeRate, true), + accent: true, + }, + ], + cta: active ? { kind: 'link', label: isReviewBounty ? 'Review' : 'Solve', href } : undefined, + }; + } + + return base; +} + +export function getActivityWorkContext(entry: FeedEntry): ActivityWorkContext | null { + const related = entry.relatedWork; + if (!related?.title) return null; + + const tab = resolveTabFromContext(entry.activityContext); + const documentType = related.contentType; + const href = buildWorkUrl({ + id: related.id, + slug: related.slug, + contentType: documentType, + tab, + }); + + return { + id: related.id, + slug: related.slug, + title: related.title, + href, + imageUrl: related.image, + documentType, + unifiedDocumentId: related.unifiedDocumentId, + fundraise: related.fundraise, + grant: related.grantSummary, + bounty: getActivityBounty(entry), + authors: related.authors?.map((authorship) => authorship.authorProfile), + tab, + }; +} diff --git a/components/Activity/lib/deriveActivityContext.ts b/components/Activity/lib/deriveActivityContext.ts new file mode 100644 index 000000000..880fd4052 --- /dev/null +++ b/components/Activity/lib/deriveActivityContext.ts @@ -0,0 +1,40 @@ +import type { ActivityContext, RawApiFeedEntry } from '@/types/feed'; + +const REVIEW_COMMENT_TYPES = new Set(['PEER_REVIEW', 'REVIEW']); + +export function deriveActivityContext(feedEntry: RawApiFeedEntry): ActivityContext | undefined { + const contentType = feedEntry.content_type?.toUpperCase(); + const obj = feedEntry.content_object; + if (!contentType || !obj) return undefined; + + switch (contentType) { + case 'RHCOMMENTMODEL': { + const commentType = obj.comment_type as string | undefined; + if (commentType && REVIEW_COMMENT_TYPES.has(commentType)) { + return 'peer_review_published'; + } + if (Array.isArray(obj.bounties) && obj.bounties.length > 0) { + return 'bounty_opened'; + } + return 'comment_published'; + } + case 'RESEARCHHUBPOST': { + if (obj.type === 'GRANT') return 'grant_opened'; + if (obj.type === 'PREREGISTRATION') return 'proposal_submitted'; + return undefined; + } + case 'PURCHASE': + case 'USDFUNDRAISECONTRIBUTION': + return 'fundraise_contribution'; + case 'FUNDINGACTIVITY': { + const sourceType = obj.source_type as string | undefined; + if (sourceType === 'BOUNTY_PAYOUT') return 'bounty_payout'; + if (sourceType === 'TIP_REVIEW') return 'tip_review'; + return undefined; + } + case 'BOUNTY': + return 'bounty_contributed'; + default: + return undefined; + } +} diff --git a/components/Activity/lib/feedEntryAdapters.ts b/components/Activity/lib/feedEntryAdapters.ts index f8e4e558a..be97f4138 100644 --- a/components/Activity/lib/feedEntryAdapters.ts +++ b/components/Activity/lib/feedEntryAdapters.ts @@ -1,8 +1,10 @@ import { buildWorkUrl } from '@/utils/url'; +import { isFoundationUser } from '@/components/Bounty/lib/bountyUtil'; import type { FeedCommentContent, FeedContentType, FeedEntry, + FeedFundingActivityContent, FeedGrantContent, FeedPaperContent, FeedPostContent, @@ -15,13 +17,13 @@ import type { ContentType } from '@/types/work'; const COMMENT_ACTION_LABELS: Record = { GENERIC_COMMENT: 'commented on', REVIEW: 'peer reviewed', - AUTHOR_UPDATE: 'posted an update on', + AUTHOR_UPDATE: 'posted an update', ANSWER: 'answered on', BOUNTY: 'contributed to', }; const DOC_ACTION_LABELS: Partial> = { - GRANT: 'opened funding', + GRANT: 'opened an RFP for', PREREGISTRATION: 'submitted proposal', POST: 'posted discussion', PAPER: 'published preprint', @@ -34,17 +36,106 @@ const FEED_TO_CONTENT_TYPE: Partial> = { PAPER: 'paper', }; -export function getActionLabel(entry: FeedEntry): string { +export interface ActivityHeaderTarget { + author: AuthorProfile; + suffix?: string; +} + +export interface ActivityHeaderMessage { + actor: AuthorProfile; + verb: string; + target?: ActivityHeaderTarget; + /** Payout rather than contribution — the amount renders without a "+". */ + isEarning?: boolean; +} + +/** + * True when the profile belongs to the ResearchHub Foundation account. + * + * Feed payloads are inconsistent about which id they expose for an actor, so we + * prefer the explicit user fields and only fall back to `id` when the profile + * carries no user reference at all (funder objects are serialized that way). + */ +function isFoundationProfile(profile?: AuthorProfile): boolean { + if (!profile) return false; + if (profile.userId != null) return isFoundationUser(profile.userId); + if (profile.user?.id != null) return isFoundationUser(profile.user.id); + return isFoundationUser(profile.id); +} + +function getFundingActivityMessage(content: FeedFundingActivityContent): ActivityHeaderMessage { + const actor = content.createdBy; + const recipient = content.recipient; + + // Bounty payouts and Foundation tips read as the recipient earning — the + // person who received the money is the interesting subject. + if (recipient && (content.sourceType === 'BOUNTY_PAYOUT' || isFoundationProfile(actor))) { + return { actor: recipient, verb: 'earned', isEarning: true }; + } + + if (content.sourceType === 'BOUNTY_PAYOUT') { + return { actor, verb: 'awarded bounty', isEarning: true }; + } + + if (!recipient) { + return { actor, verb: 'tipped review' }; + } + return { + actor, + verb: 'tipped', + target: { + author: recipient, + suffix: ' on peer review', + }, + }; +} + +function getDefaultActivityMessage(entry: FeedEntry): ActivityHeaderMessage { + const actor = entry.content.createdBy; + if (entry.contentType === 'COMMENT') { const commentContent = entry.content as FeedCommentContent; - if (commentContent.hasBounties) return 'opened a bounty'; - return COMMENT_ACTION_LABELS[commentContent.comment?.commentType] ?? 'commented on'; + const bounty = commentContent.bounties?.[0]; + if (bounty) { + const isReviewBounty = bounty.bountyType === 'REVIEW'; + return { + actor, + verb: isReviewBounty ? 'opened a peer review bounty for' : 'opened a bounty for', + }; + } + + const commentType = commentContent.comment?.commentType; + if (commentType === 'REVIEW') { + if (getReviewEarning(entry)) return { actor, verb: 'earned', isEarning: true }; + const score = commentContent.review?.score ?? commentContent.comment.reviewScore; + return { actor, verb: score ? 'peer reviewed and scored' : 'peer reviewed' }; + } + + return { + actor, + verb: COMMENT_ACTION_LABELS[commentType] ?? 'commented on', + }; } - if (entry.contentType === 'BOUNTY') return 'contributed to'; + + if (entry.contentType === 'BOUNTY') { + return { actor, verb: 'contributed to' }; + } + if (entry.contentType === 'USDFUNDRAISECONTRIBUTION' || entry.contentType === 'PURCHASE') { - return 'Funded Proposal'; + return { actor, verb: 'funded proposal' }; } - return DOC_ACTION_LABELS[entry.contentType] ?? 'contributed'; + + return { + actor, + verb: DOC_ACTION_LABELS[entry.contentType] ?? 'contributed to', + }; +} + +export function getActivityHeaderMessage(entry: FeedEntry): ActivityHeaderMessage { + if (entry.contentType === 'FUNDINGACTIVITY') { + return getFundingActivityMessage(entry.content as FeedFundingActivityContent); + } + return getDefaultActivityMessage(entry); } export interface FeedEntryMeta { @@ -60,12 +151,45 @@ function resolveCommentWorkTab( comment: FeedCommentContent | null ): CommentWorkTab { if (comment?.comment?.commentType === 'REVIEW') return 'reviews'; - if (entry.contentType === 'BOUNTY' || comment?.hasBounties) return 'bounties'; + if (entry.contentType === 'BOUNTY' || (comment?.bounties?.length ?? 0) > 0) return 'bounties'; if (entry.contentType === 'COMMENT') return 'conversation'; return undefined; } +function resolveRelatedWorkTab(entry: FeedEntry): CommentWorkTab { + if (entry.contentType === 'FUNDINGACTIVITY') { + const funding = entry.content as FeedFundingActivityContent; + return funding.sourceType === 'BOUNTY_PAYOUT' ? 'bounties' : 'reviews'; + } + if (entry.contentType === 'COMMENT') { + return resolveCommentWorkTab(entry, entry.content as FeedCommentContent); + } + if (entry.contentType === 'BOUNTY') return 'bounties'; + return undefined; +} + +function getRelatedWorkMeta(entry: FeedEntry): FeedEntryMeta | null { + const related = entry.relatedWork; + if (!related?.title) return null; + + const tab = resolveRelatedWorkTab(entry); + + return { + title: related.title, + author: entry.content.createdBy, + href: buildWorkUrl({ + id: related.id, + slug: related.slug, + contentType: related.contentType, + tab, + }), + }; +} + export function getEntryMeta(entry: FeedEntry): FeedEntryMeta { + const relatedMeta = getRelatedWorkMeta(entry); + if (relatedMeta) return relatedMeta; + const content = entry.content; const author = content.createdBy; @@ -117,17 +241,30 @@ export function getEntryMeta(entry: FeedEntry): FeedEntryMeta { }; } -export type FeedEntryIconName = 'coins' | 'bell' | 'message' | null; +export type FeedEntryIconName = 'coins' | 'fund' | 'earn' | 'proposal' | 'bell' | 'message' | null; export function getActionIcon(entry: FeedEntry): FeedEntryIconName { - if (entry.contentType === 'USDFUNDRAISECONTRIBUTION' || entry.contentType === 'PURCHASE') { + if (entry.contentType === 'GRANT' || entry.activityContext === 'grant_opened') { + return 'fund'; + } + if (entry.activityContext === 'bounty_opened') { + return 'earn'; + } + if (entry.activityContext === 'proposal_submitted' || entry.contentType === 'PREREGISTRATION') { + return null; + } + if ( + entry.contentType === 'USDFUNDRAISECONTRIBUTION' || + entry.contentType === 'PURCHASE' || + entry.contentType === 'FUNDINGACTIVITY' + ) { return 'coins'; } if (entry.contentType === 'BOUNTY') return 'coins'; if (entry.contentType !== 'COMMENT') return null; const commentContent = entry.content as FeedCommentContent; - if (commentContent.hasBounties) return 'coins'; + if ((commentContent.bounties?.length ?? 0) > 0) return 'coins'; const commentType = commentContent.comment?.commentType; if (commentType === 'AUTHOR_UPDATE') return 'bell'; @@ -136,18 +273,40 @@ export function getActionIcon(entry: FeedEntry): FeedEntryIconName { } export function getReviewScore(entry: FeedEntry): number | undefined { + if (entry.contentType === 'FUNDINGACTIVITY') return undefined; if (entry.contentType !== 'COMMENT') return undefined; const commentContent = entry.content as FeedCommentContent; if (commentContent.comment?.commentType !== 'REVIEW') return undefined; + // When the header leads with an earning, the score stays on the document card. + if (getReviewEarning(entry)) return undefined; return commentContent.review?.score ?? commentContent.comment.reviewScore; } +/** Bounty payout shown on the header line for awarded peer reviews. */ +export function getReviewEarning(entry: FeedEntry): FeedContribution | undefined { + if (entry.contentType !== 'COMMENT') return undefined; + const commentContent = entry.content as FeedCommentContent; + if (commentContent.comment?.commentType !== 'REVIEW') return undefined; + + const awarded = entry.awardedBountyAmount; + if (awarded == null || awarded <= 0) return undefined; + + return { amount: awarded, currency: 'RSC' }; +} + export interface FeedContribution { amount: number; currency: 'USD' | 'RSC'; } export function getContribution(entry: FeedEntry): FeedContribution | undefined { + if (entry.contentType === 'FUNDINGACTIVITY') { + const funding = entry.content as FeedFundingActivityContent; + if (funding.totalUsdCents > 0) { + return { amount: funding.totalUsd, currency: 'USD' }; + } + return { amount: funding.totalAmount, currency: 'RSC' }; + } if (entry.contentType !== 'USDFUNDRAISECONTRIBUTION' && entry.contentType !== 'PURCHASE') { return undefined; } @@ -199,6 +358,7 @@ export interface FeedCommentPreview { } export function getCommentPreview(entry: FeedEntry): FeedCommentPreview | null { + if (entry.contentType === 'FUNDINGACTIVITY') return null; if (entry.contentType !== 'COMMENT') return null; const { comment } = entry.content as FeedCommentContent; if (!comment?.content) return null; diff --git a/components/Comment/CommentReadOnly.tsx b/components/Comment/CommentReadOnly.tsx index 9dcab35ff..b60b8d073 100644 --- a/components/Comment/CommentReadOnly.tsx +++ b/components/Comment/CommentReadOnly.tsx @@ -25,6 +25,7 @@ interface CommentReadOnlyProps { maxLength?: number; initiallyExpanded?: boolean; showReadMoreButton?: boolean; + showLinkPreviews?: boolean; createdDate?: string | Date; updatedDate?: string | Date; className?: string; @@ -68,6 +69,7 @@ export const CommentReadOnly = ({ maxLength = 1000, initiallyExpanded = false, showReadMoreButton = true, + showLinkPreviews = true, createdDate, updatedDate, className, @@ -79,7 +81,8 @@ export const CommentReadOnly = ({ // Embeds derived from the comment doc — surfaced as a carousel below the // body so a single saved comment can show multiple link previews without // breaking the prose flow. Only meaningful for TipTap content. - const carouselEmbeds = contentFormat === 'TIPTAP' ? extractDocEmbeds(parsedContent) : []; + const carouselEmbeds = + showLinkPreviews && contentFormat === 'TIPTAP' ? extractDocEmbeds(parsedContent) : []; const textContent = contentFormat === 'TIPTAP' @@ -147,6 +150,7 @@ export const CommentReadOnly = ({ truncate={shouldTruncate && !isExpanded} maxLength={maxLength} debug={debugEnabled} + showLinkPreviews={showLinkPreviews} />, ]; } catch (error) { diff --git a/components/Comment/lib/TipTapRenderer.tsx b/components/Comment/lib/TipTapRenderer.tsx index 4debe84d2..cd6164db8 100644 --- a/components/Comment/lib/TipTapRenderer.tsx +++ b/components/Comment/lib/TipTapRenderer.tsx @@ -15,6 +15,7 @@ interface TipTapRendererProps { renderSectionHeader?: (props: SectionHeaderProps) => ReactNode; truncate?: boolean; maxLength?: number; + showLinkPreviews?: boolean; } /** @@ -67,6 +68,25 @@ export const renderTextWithMarks = (text: string, marks: any[]): ReactNode => { return result; }; +function demoteRichLinks(node: any): any { + if (!node || typeof node !== 'object') return node; + + if (node.type === 'richLink' && node.attrs?.url) { + const url = String(node.attrs.url); + return { + type: 'text', + text: url, + marks: [{ type: 'link', attrs: { href: url, target: '_blank' } }], + }; + } + + if (Array.isArray(node.content)) { + return { ...node, content: node.content.map(demoteRichLinks) }; + } + + return node; +} + /** * Helper function to extract plain text from TipTap JSON */ @@ -107,6 +127,7 @@ const TipTapRenderer: React.FC = ({ renderSectionHeader, truncate = false, maxLength = 300, + showLinkPreviews = true, }) => { if (debug) { console.log('||TipTapRenderer props received:', { @@ -146,7 +167,11 @@ const TipTapRenderer: React.FC = ({ // whose anchor text equals the href become `richLink` nodes so they // render with the same inline preview + hover surface as freshly pasted // links. Idempotent — already-converted docs pass through unchanged. - documentContent = normalizeRichLinks(documentContent); + // Skip when link previews are disabled (e.g. activity feed) and demote + // any existing richLink atoms back to plain anchors. + documentContent = showLinkPreviews + ? normalizeRichLinks(documentContent) + : demoteRichLinks(documentContent); // If truncation is enabled, extract the full text to check length let shouldTruncate = false; diff --git a/components/Feed/FeedItemActions.tsx b/components/Feed/FeedItemActions.tsx index 5107b1c3c..f5d251fa9 100644 --- a/components/Feed/FeedItemActions.tsx +++ b/components/Feed/FeedItemActions.tsx @@ -169,6 +169,11 @@ interface FeedItemActionsProps { isExpanded?: boolean; className?: string; variant?: 'default' | 'inline'; + /** + * When true, render share + save next to the vote control (left) so the + * trailing side can hold only `rightSideActionButton` (e.g. Fund / Review). + */ + leadingUtilityActions?: boolean; } // Define interface for avatar items used in local state @@ -207,6 +212,7 @@ export const FeedItemActions: FC = ({ isExpanded = false, className, variant = 'default', + leadingUtilityActions = false, }) => { const { executeAuthenticatedAction } = useAuthenticatedAction(); const { showUSD } = useCurrencyPreference(); @@ -407,6 +413,58 @@ export const FeedItemActions: FC = ({ const tipAmount = tips.reduce((total, tip) => total + (tip.amount || 0), 0); const totalAwarded = tipAmount + (awardedBountyAmount || 0); + const canSave = + !!relatedDocumentUnifiedDocumentId && + feedContentType !== 'COMMENT' && + feedContentType !== 'BOUNTY' && + feedContentType !== 'APPLICATION' && + showPeerReviews; + + const showShare = leadingUtilityActions || variant !== 'inline'; + const showMoreMenu = + !!(listDetailContext && relatedDocumentUnifiedDocumentId) || + menuItems.length > 0 || + !hideReportButton; + + const shareButton = showShare ? ( + + ) : null; + + const saveButton = canSave ? ( + + ) : null; + return ( <>
= ({ /> )} {children} + {leadingUtilityActions && ( + <> + {saveButton} + {shareButton} + + )}
{rightSideActionButton} - { - e.stopPropagation(); - }} - onClick={(e) => { - e.stopPropagation(); - }} - variant="ghost" - size="sm" - className="flex h-8 w-8 !p-0 items-center justify-center rounded-full text-gray-700 transition-all hover:bg-white hover:text-gray-900 hover:shadow-sm" - > - - - } - align="end" - open={isMenuOpen} - onOpenChange={setIsMenuOpen} - > - {listDetailContext && relatedDocumentUnifiedDocumentId && ( - - - Remove from list - - )} - - {menuItems.map((item, index) => ( - { - setIsMenuOpen(false); - item.onClick(e); - }} - className={cn('flex items-center gap-2', item.className)} - > - {item.icon && } - {item.label} - - ))} - - {showSeparator &&
} - - {!hideReportButton && ( - - - {actionLabels?.report || 'Report'} - - )} - - {variant !== 'inline' && ( - + } + align="end" + open={isMenuOpen} + onOpenChange={setIsMenuOpen} > - - + {listDetailContext && relatedDocumentUnifiedDocumentId && ( + + + Remove from list + + )} + + {menuItems.map((item, index) => ( + { + setIsMenuOpen(false); + item.onClick(e); + }} + className={cn('flex items-center gap-2', item.className)} + > + {item.icon && } + {item.label} + + ))} + + {showSeparator &&
} + + {!hideReportButton && ( + + + {actionLabels?.report || 'Report'} + + )} + + )} + {!leadingUtilityActions && ( + <> + {shareButton} + {saveButton} + )} - {relatedDocumentUnifiedDocumentId && - feedContentType !== 'COMMENT' && - feedContentType !== 'BOUNTY' && - feedContentType !== 'APPLICATION' && - showPeerReviews && ( - - )}
diff --git a/components/Funding/ActivityCard.tsx b/components/Funding/ActivityCard.tsx index 6fe9303ef..80db42d48 100644 --- a/components/Funding/ActivityCard.tsx +++ b/components/Funding/ActivityCard.tsx @@ -2,37 +2,49 @@ import { FC } from 'react'; import Link from 'next/link'; -import { Star } from 'lucide-react'; import { Avatar } from '@/components/ui/Avatar'; import { AuthorTooltip } from '@/components/ui/AuthorTooltip'; -import { formatTimeAgo } from '@/utils/date'; -import type { FeedEntry } from '@/types/feed'; +import { ActivityHeaderActionText } from '@/components/Activity/ActivityHeaderActionText'; +import { BountyAmount } from '@/components/Activity/BountyAmount'; +import { ContributionAmount } from '@/components/Activity/ContributionAmount'; +import { FeedEntryIcon } from '@/components/Activity/FeedEntryIcon'; +import { GrantFundingAmount } from '@/components/Activity/GrantFundingAmount'; +import { ReviewScoreStars } from '@/components/Activity/ReviewScoreStars'; import { getActionIcon, - getActionLabel, + getActivityHeaderMessage, getContribution, getEntryMeta, getGrantAmount, + getReviewEarning, getReviewScore, } from '@/components/Activity/lib/feedEntryAdapters'; -import { ContributionAmount } from '@/components/Activity/ContributionAmount'; -import { FeedEntryIcon } from '@/components/Activity/FeedEntryIcon'; -import { GrantFundingAmount } from '@/components/Activity/GrantFundingAmount'; +import { getActivityBounty } from '@/components/Activity/lib/activityWorkContext'; +import { formatTimeAgo } from '@/utils/date'; +import { Tooltip } from '@/components/ui/Tooltip'; +import type { FeedEntry } from '@/types/feed'; interface ActivityCardProps { entry: FeedEntry; } +/** Compact activity row used in the funding sidebar. */ export const ActivityCard: FC = ({ entry }) => { - const { title, author, href } = getEntryMeta(entry); + const { title, href } = getEntryMeta(entry); if (!title) return null; - const actionLabel = getActionLabel(entry); + const message = getActivityHeaderMessage(entry); const actionIcon = getActionIcon(entry); const reviewScore = getReviewScore(entry); + const reviewEarning = getReviewEarning(entry); const grantAmount = getGrantAmount(entry); const contribution = getContribution(entry); + const bounty = entry.activityContext === 'bounty_opened' ? getActivityBounty(entry) : undefined; + + const hasAmount = Boolean( + grantAmount || contribution || reviewEarning || bounty || reviewScore != null + ); const titleEl = href ? ( @@ -45,51 +57,66 @@ export const ActivityCard: FC = ({ entry }) => { return (
-
- +
+
- {author?.id ? ( - - - {author.fullName || 'Unknown'} - - - ) : ( - - {author?.fullName || 'Unknown'} - - )} - - {actionLabel} - - {reviewScore != null && ( - - - {reviewScore.toFixed(1)} - + + + {grantAmount && ( + <> + {' '} + + )} - {grantAmount && } {contribution && ( - + <> + {' '} + + )} + {reviewEarning && ( + <> + {' '} + + + )} + {bounty && ( + <> + {' '} + + + )} + {reviewScore != null && reviewScore > 0 && ( + <> + {' '} + + + )} + {titleEl}
- - {formatTimeAgo(entry.timestamp)} - + + + {formatTimeAgo(entry.timestamp)} + +
); }; diff --git a/components/Funding/GrantContentSwitcher.tsx b/components/Funding/GrantContentSwitcher.tsx index 706f1dd22..e29e8100a 100644 --- a/components/Funding/GrantContentSwitcher.tsx +++ b/components/Funding/GrantContentSwitcher.tsx @@ -5,22 +5,15 @@ import { useInView } from 'react-intersection-observer'; import { useGrantTab } from '@/components/Funding/GrantPageContent'; import { GrantDetailsInline } from '@/components/Funding/GrantDetailsInline'; import { ActivityCardFull } from '@/components/Activity/ActivityCardFull'; +import { ActivityCardSkeleton } from '@/components/Activity/ActivityCardSkeleton'; interface GrantContentSwitcherProps { children: ReactNode; content?: string; imageUrl?: string; - hasDescription: boolean; - grantId?: number | string; } -export function GrantContentSwitcher({ - children, - content, - imageUrl, - hasDescription, - grantId, -}: GrantContentSwitcherProps) { +export function GrantContentSwitcher({ children, content, imageUrl }: GrantContentSwitcherProps) { const { activeTab, activity } = useGrantTab(); const { entries, isLoading, isLoadingMore, hasMore, loadMore } = activity; @@ -46,22 +39,8 @@ export function GrantContentSwitcher({ ))} - {(isLoading || isLoadingMore) && ( -
- {[...Array(8)].map((_, i) => ( -
-
-
-
-
-
-
-
-
-
- ))} -
- )} + {(isLoading || isLoadingMore) && + [...Array(8)].map((_, i) => )} {!isLoading && !isLoadingMore && entries.length === 0 && (
diff --git a/components/work/WorkHeader/WorkHeaderGrant.tsx b/components/work/WorkHeader/WorkHeaderGrant.tsx index ca791ab23..5ff1a72a3 100644 --- a/components/work/WorkHeader/WorkHeaderGrant.tsx +++ b/components/work/WorkHeader/WorkHeaderGrant.tsx @@ -84,6 +84,8 @@ export function WorkHeaderGrant({ ) : undefined; const activityCount = activity.count; + const activityCountLabel = + activityCount > 0 && activity.hasMore ? `${activityCount}+` : activityCount; const grantTabs = [ { id: 'details' as const, label: 'Details' }, @@ -119,7 +121,7 @@ export function WorkHeaderGrant({ : 'bg-gray-100 text-gray-600' }`} > - {activityCount} + {activityCountLabel} )}
diff --git a/hooks/useActivityFeed.ts b/hooks/useActivityFeed.ts index cb45a3176..a663c3b45 100644 --- a/hooks/useActivityFeed.ts +++ b/hooks/useActivityFeed.ts @@ -56,9 +56,12 @@ export function useActivityFeed({ scope, grantId }: UseActivityFeedOptions = {}) scope, grantId, }); - setEntries((prev) => [...prev, ...result.entries]); + setEntries((prev) => { + const next = [...prev, ...result.entries]; + setCount(next.length); + return next; + }); setHasMore(result.hasMore); - setCount(result.count); pageRef.current = nextPage; } catch (error) { console.error('Error loading more activity:', error); diff --git a/services/activity.service.ts b/services/activity.service.ts index 9e8543825..8f34eaf7e 100644 --- a/services/activity.service.ts +++ b/services/activity.service.ts @@ -1,5 +1,10 @@ import { ApiClient } from './client'; -import { FeedEntry, FeedApiResponse, transformFeedEntry, RawApiFeedEntry } from '@/types/feed'; +import { + FeedEntry, + ActivityFeedApiResponse, + transformFeedEntry, + RawApiFeedEntry, +} from '@/types/feed'; export type ActivityDocumentType = 'PREREGISTRATION' | 'GRANT' | 'DISCUSSION'; @@ -17,7 +22,7 @@ export interface GetActivityParams { export class ActivityService { private static readonly BASE_PATH = '/api/activity_feed'; - private static readonly DEFAULT_PAGE_SIZE = 25; + private static readonly DEFAULT_PAGE_SIZE = 20; static async getActivity(params?: GetActivityParams): Promise<{ entries: FeedEntry[]; @@ -37,7 +42,7 @@ export class ActivityService { const qs = queryParams.toString(); const url = `${this.BASE_PATH}/${qs ? `?${qs}` : ''}`; try { - const response = await ApiClient.get(url); + const response = await ApiClient.get(url); const entries = response.results .map((entry: RawApiFeedEntry) => { @@ -49,7 +54,7 @@ export class ActivityService { }) .filter((e): e is FeedEntry => e !== null); - return { entries, hasMore: !!response.next, count: response.count ?? entries.length }; + return { entries, hasMore: !!response.next, count: entries.length }; } catch (error) { console.error('Error fetching activity feed:', error); return { entries: [], hasMore: false, count: 0 }; diff --git a/types/feed.ts b/types/feed.ts index 7c022574f..cbecf756d 100644 --- a/types/feed.ts +++ b/types/feed.ts @@ -2,17 +2,25 @@ import { AuthorProfile, transformAuthorProfile } from './authorProfile'; import { ContentMetrics } from './metrics'; import { Topic, transformTopic } from './topic'; import { createTransformer, BaseTransformed } from './transformer'; -import { Work, transformPaper, transformPost, FundingRequest, ContentType } from './work'; +import { + Work, + transformPaper, + transformPost, + FundingRequest, + ContentType, + type WorkGrantSummary, +} from './work'; +import { mapApiDocumentTypeToClientType, type ApiDocumentType } from '@/utils/contentTypeMapping'; import { Bounty, BountyWithComment, transformBounty } from './bounty'; import { Comment, CommentType, ContentFormat, transformComment } from './comment'; import { Fundraise, transformFundraise, Application, transformApplication } from './funding'; import { Journal } from './journal'; import { UserVoteType } from './reaction'; -import { User } from './user'; import { stripHtml } from '@/utils/stringUtils'; import { Tip } from './tip'; import { FOUNDATION_USER_ID } from '@/config/constants'; import { GrantStatus } from './grant'; +import { deriveActivityContext } from '@/components/Activity/lib/deriveActivityContext'; export type FeedActionType = 'contribute' | 'open' | 'publish' | 'post'; @@ -28,6 +36,29 @@ export interface ParentCommentPreview { parentComment?: ParentCommentPreview | undefined; // Add recursive field } +function transformFundingActivityRecipient(recipients: unknown): AuthorProfile | undefined { + const first = Array.isArray(recipients) ? recipients[0] : undefined; + if (!first || typeof first !== 'object') return undefined; + + const recipientUser = (first as { recipient_user?: Record }).recipient_user; + if (!recipientUser || typeof recipientUser !== 'object') return undefined; + + try { + return transformAuthorProfile(recipientUser); + } catch { + return undefined; + } +} + +function transformFundingActivityFunder(funder: unknown): AuthorProfile | undefined { + if (!funder || typeof funder !== 'object') return undefined; + try { + return transformAuthorProfile(funder as Record); + } catch { + return undefined; + } +} + // Recursive helper function to transform nested parent comments const transformNestedParentComment = (rawParent: any): ParentCommentPreview | undefined => { if (!rawParent) { @@ -141,7 +172,6 @@ export interface FeedCommentContent extends BaseFeedContent { objectId: number; }; }; - hasBounties?: boolean; isRemoved?: boolean; relatedDocumentId?: number | string; relatedDocumentContentType?: ContentType; @@ -205,6 +235,18 @@ export interface FeedGrantContent extends BaseFeedContent { isExpired?: boolean; } +export type FundingActivitySourceType = 'BOUNTY_PAYOUT' | 'TIP_REVIEW'; + +export interface FeedFundingActivityContent extends BaseFeedContent { + contentType: 'FUNDINGACTIVITY'; + sourceType: FundingActivitySourceType; + totalAmount: number; + totalUsdCents: number; + totalUsd: number; + activityDate?: string; + recipient?: AuthorProfile; +} + // Update the Content union type to include the base interface export type Content = | FeedPostContent @@ -212,7 +254,8 @@ export type Content = | FeedBountyContent | FeedCommentContent | FeedApplicationContent - | FeedGrantContent; + | FeedGrantContent + | FeedFundingActivityContent; export type FeedContentType = | 'PAPER' @@ -223,7 +266,8 @@ export type FeedContentType = | 'APPLICATION' | 'GRANT' | 'USDFUNDRAISECONTRIBUTION' - | 'PURCHASE'; + | 'PURCHASE' + | 'FUNDINGACTIVITY'; export interface ExternalMetrics { score: number; @@ -280,6 +324,17 @@ export interface AssociatedGrant { numApplicants: number; } +export type ActivityContext = + | 'tip_review' + | 'bounty_payout' + | 'fundraise_contribution' + | 'bounty_opened' + | 'bounty_contributed' + | 'peer_review_published' + | 'comment_published' + | 'grant_opened' + | 'proposal_submitted'; + export interface JournalPostIds { grantPostId: number | null; proposalPostId: number | null; @@ -307,6 +362,7 @@ export interface FeedEntry { externalMetrics?: ExternalMetrics; nonprofit?: Nonprofit; associatedGrants?: AssociatedGrant[]; + activityContext?: ActivityContext; journalPostIds?: JournalPostIds; searchMetadata?: { highlightedTitle?: string; @@ -344,6 +400,7 @@ export interface RawApiFeedEntry { base_wallet_address: string; }; hot_score_v2?: number; + related_work?: any; risk_score?: number | null; associated_grants?: Array<{ id: number; @@ -442,6 +499,12 @@ export interface FeedApiResponse { results: RawApiFeedEntry[]; } +export interface ActivityFeedApiResponse { + next: string | null; + previous: string | null; + results: RawApiFeedEntry[]; +} + /** * Safely extracts the unified document ID from a content object. * @@ -471,6 +534,78 @@ export function getUnifiedDocumentId(content_object: any): string | undefined { export type TransformedContent = Content & BaseTransformed; export type TransformedFeedEntry = FeedEntry & BaseTransformed; +function transformActivityRelatedWorkGrant(rawGrant: unknown): WorkGrantSummary | undefined { + if (!rawGrant || typeof rawGrant !== 'object') return undefined; + + const grant = rawGrant as { + status?: string; + organization?: string; + amount?: { usd?: number; rsc?: number | null }; + application_count?: number; + end_date?: string | null; + }; + + if (typeof grant.amount !== 'object' || grant.amount === null) { + return undefined; + } + + return { + status: grant.status ?? '', + organization: grant.organization ?? '', + amount: { + usd: grant.amount.usd ?? 0, + rsc: grant.amount.rsc ?? null, + }, + numApplicants: grant.application_count ?? 0, + endDate: grant.end_date ?? undefined, + }; +} + +function transformActivityRelatedWork(raw: any): Work | undefined { + if (!raw) return undefined; + + const contentType = + mapApiDocumentTypeToClientType(raw.document_type as ApiDocumentType) ?? 'post'; + + let fundraise: Fundraise | undefined; + if (raw.fundraise) { + try { + fundraise = transformFundraise(raw.fundraise); + } catch (error) { + console.error('Error transforming activity related_work fundraise:', error); + } + } + + const hubTopic = raw.hub + ? raw.hub.id + ? transformTopic(raw.hub) + : { id: 0, name: raw.hub.name || '', slug: raw.hub.slug || '' } + : undefined; + + return { + id: raw.id, + slug: raw.slug || '', + title: stripHtml(raw.title || ''), + contentType, + createdDate: raw.created_date || '', + abstract: '', + authors: Array.isArray(raw.authors) + ? raw.authors.map((author: unknown) => ({ + authorProfile: transformAuthorProfile(author), + isCorresponding: false, + position: 'middle' as const, + })) + : [], + topics: hubTopic ? [hubTopic] : [], + formats: [], + figures: [], + unifiedDocumentId: raw.unified_document_id, + image: raw.image_url ?? undefined, + fundraise, + grantSummary: raw.grant ? transformActivityRelatedWorkGrant(raw.grant) : undefined, + }; +} + // Updated transformFeedEntry function to use the simplified Content type export const transformFeedEntry = (feedEntry: RawApiFeedEntry): FeedEntry => { if (!feedEntry) { @@ -743,8 +878,16 @@ export const transformFeedEntry = (feedEntry: RawApiFeedEntry): FeedEntry => { // Transform the comment to get score and other properties const transformedComment = transformComment(commentData); - const hasBounties = - Array.isArray(content_object.bounties) && content_object.bounties.length > 0; + const bounties = Array.isArray(content_object.bounties) + ? content_object.bounties.map((bounty: Record) => + transformBounty(bounty, { ignoreBaseAmount: true }) + ) + : undefined; + + const rawCommentType = content_object.comment_type as string | undefined; + const normalizedCommentType = ( + rawCommentType === 'PEER_REVIEW' ? 'REVIEW' : rawCommentType + ) as CommentType; // Create a FeedCommentContent object const commentContent: FeedCommentContent = { @@ -755,12 +898,12 @@ export const transformFeedEntry = (feedEntry: RawApiFeedEntry): FeedEntry => { updatedDate: content_object.updated_date || action_date || created_date, createdBy: transformAuthorProfile(author || content_object.author), isRemoved: content_object.is_removed, - hasBounties, + ...(bounties?.length ? { bounties } : {}), comment: { id: content_object.id, content: content_object.comment_content_json, contentFormat: (content_object.comment_content_type as ContentFormat) || 'QUILL_EDITOR', - commentType: content_object.comment_type as CommentType, + commentType: normalizedCommentType, score: transformedComment.score || 0, reviewScore: transformedComment.reviewScore || 0, isAssessed: transformedComment.isAssessed ?? false, @@ -961,14 +1104,16 @@ export const transformFeedEntry = (feedEntry: RawApiFeedEntry): FeedEntry => { case 'USDFUNDRAISECONTRIBUTION': contentType = content_type as 'PURCHASE' | 'USDFUNDRAISECONTRIBUTION'; try { + const relatedWorkRaw = feedEntry.related_work; const contributionEntry: FeedPostContent = { - id: content_object.post_id ?? content_object.id ?? id, - unifiedDocumentId: content_object.unified_document_id, + id: content_object.post_id ?? relatedWorkRaw?.id ?? id, + unifiedDocumentId: + content_object.unified_document_id ?? relatedWorkRaw?.unified_document_id, contentType: 'PREREGISTRATION', createdDate: action_date || created_date, textPreview: '', - slug: content_object.proposal_slug || '', - title: stripHtml(content_object.proposal_title || ''), + slug: content_object.proposal_slug || relatedWorkRaw?.slug || '', + title: stripHtml(content_object.proposal_title || relatedWorkRaw?.title || ''), authors: [transformAuthorProfile(author)], topics: content_object.hub ? [ @@ -994,6 +1139,42 @@ export const transformFeedEntry = (feedEntry: RawApiFeedEntry): FeedEntry => { } break; + case 'FUNDINGACTIVITY': + contentType = 'FUNDINGACTIVITY'; + try { + const relatedWorkRaw = feedEntry.related_work; + + const totalAmountRaw = content_object.total_amount; + const totalAmount = + typeof totalAmountRaw === 'string' + ? parseFloat(totalAmountRaw) || 0 + : totalAmountRaw || 0; + + const funder = transformFundingActivityFunder(content_object.funder); + + const fundingActivityContent: FeedFundingActivityContent = { + id: content_object.id ?? id, + unifiedDocumentId: + content_object.unified_document_id ?? relatedWorkRaw?.unified_document_id, + contentType: 'FUNDINGACTIVITY', + createdDate: action_date || created_date, + createdBy: funder ?? transformAuthorProfile(author), + sourceType: content_object.source_type as FundingActivitySourceType, + totalAmount, + totalUsdCents: content_object.total_usd_cents || 0, + totalUsd: + content_object.total_usd ?? + (content_object.total_usd_cents ? content_object.total_usd_cents / 100 : 0), + activityDate: content_object.activity_date, + recipient: transformFundingActivityRecipient(content_object.recipients), + }; + content = fundingActivityContent; + } catch (error) { + console.error('Error transforming FUNDINGACTIVITY:', error); + throw new Error(`Failed to transform FUNDINGACTIVITY: ${error}`); + } + break; + default: // For unsupported types, try to transform to a Work console.warn( @@ -1036,6 +1217,11 @@ export const transformFeedEntry = (feedEntry: RawApiFeedEntry): FeedEntry => { } // Complete the feed entry + const activityRelatedWork = transformActivityRelatedWork(feedEntry.related_work); + if (activityRelatedWork) { + relatedWork = activityRelatedWork; + } + return { ...baseFeedEntry, content, @@ -1106,6 +1292,7 @@ export const transformFeedEntry = (feedEntry: RawApiFeedEntry): FeedEntry => { baseWalletAddress: nonprofit.base_wallet_address, } : undefined, + activityContext: deriveActivityContext(feedEntry), } as FeedEntry; }; diff --git a/types/work.ts b/types/work.ts index 054e373c1..f9dae199c 100644 --- a/types/work.ts +++ b/types/work.ts @@ -133,6 +133,7 @@ export interface Work { aiPeerReview?: ProposalReview | null; enrichments?: Enrichment[]; linkedGrant?: LinkedGrant | null; + grantSummary?: WorkGrantSummary; moderationStatus?: ModerationStatus; isPublic?: boolean; } @@ -151,6 +152,15 @@ export interface LinkedGrant { applicantCount: number; } +/** Slim grant metadata attached to activity feed related_work */ +export interface WorkGrantSummary { + status: string; + organization: string; + amount: { usd: number; rsc: number | null }; + numApplicants: number; + endDate?: string; +} + export interface FundingRequest extends Work { type: 'funding_request'; contentType: 'funding_request'; From b2f88a50b8e71a6e0cd34263646c06ab36e9c544 Mon Sep 17 00:00:00 2001 From: nicktytarenko Date: Sun, 2 Aug 2026 15:31:20 +0300 Subject: [PATCH 2/3] Refactor activity work context handling to support new content types. --- .../Activity/lib/activityWorkContext.ts | 137 ++++++++++++++++-- types/work.ts | 1 - utils/number.ts | 16 ++ 3 files changed, 140 insertions(+), 14 deletions(-) diff --git a/components/Activity/lib/activityWorkContext.ts b/components/Activity/lib/activityWorkContext.ts index 3b127e939..f2360511e 100644 --- a/components/Activity/lib/activityWorkContext.ts +++ b/components/Activity/lib/activityWorkContext.ts @@ -3,18 +3,20 @@ import { isFundraiseActive } from '@/components/Fund/lib/fundraiseUtils'; import { getBountyDisplayAmount, isOpenBounty } from '@/components/Bounty/lib/bountyUtil'; import { formatCurrency } from '@/utils/currency'; import { isDeadlineInFuture } from '@/utils/date'; -import type { ContentType } from '@/types/work'; +import { toOptionalNumber } from '@/utils/number'; import type { ActivityContext, FeedBountyContent, FeedCommentContent, FeedEntry, FeedGrantContent, + FeedPaperContent, + FeedPostContent, } from '@/types/feed'; import type { Bounty } from '@/types/bounty'; import type { Fundraise } from '@/types/funding'; import type { AuthorProfile } from '@/types/authorProfile'; -import type { WorkGrantSummary } from '@/types/work'; +import type { ContentType, Work, WorkGrantSummary } from '@/types/work'; type ActivityBodySlot = 'fundraise' | 'bounty' | 'grant' | 'default'; @@ -257,24 +259,124 @@ export function getWorkCardPresentation( return base; } -export function getActivityWorkContext(entry: FeedEntry): ActivityWorkContext | null { - const related = entry.relatedWork; - if (!related?.title) return null; +function grantSummaryFromFeedGrant(content: FeedGrantContent): WorkGrantSummary | undefined { + const grant = content.grant; + if (!grant) return undefined; + return { + status: grant.status, + organization: grant.organization, + amount: { usd: grant.amount.usd, rsc: grant.amount.rsc ?? null }, + numApplicants: grant.applicants?.length ?? 0, + endDate: grant.endDate, + }; +} +/** + * Build work context from a top-level document payload when `related_work` is + * absent (PAPER / POST / GRANT / proposal / contribution events). + */ +function getWorkContextFromContent(entry: FeedEntry): ActivityWorkContext | null { const tab = resolveTabFromContext(entry.activityContext); - const documentType = related.contentType; - const href = buildWorkUrl({ - id: related.id, - slug: related.slug, - contentType: documentType, - tab, - }); + const bounty = getActivityBounty(entry); + + if (entry.contentType === 'PAPER') { + const paper = entry.content as FeedPaperContent; + if (!paper.title) return null; + const documentType: ContentType = 'paper'; + return { + id: paper.id, + slug: paper.slug, + title: paper.title, + href: buildWorkUrl({ + id: paper.id, + slug: paper.slug, + contentType: documentType, + tab, + }), + imageUrl: paper.previewImage || paper.previewThumbnail, + documentType, + unifiedDocumentId: toOptionalNumber(paper.unifiedDocumentId), + bounty, + authors: paper.authors, + tab, + }; + } + + if (entry.contentType === 'GRANT') { + const grantContent = entry.content as FeedGrantContent; + if (!grantContent.title) return null; + const documentType: ContentType = 'funding_request'; + return { + id: grantContent.id, + slug: grantContent.slug, + title: grantContent.title, + href: buildWorkUrl({ + id: grantContent.id, + slug: grantContent.slug, + contentType: documentType, + tab, + }), + imageUrl: grantContent.previewImage, + documentType, + unifiedDocumentId: toOptionalNumber(grantContent.unifiedDocumentId), + grant: grantSummaryFromFeedGrant(grantContent), + bounty, + authors: grantContent.authors, + tab, + }; + } + + if ( + entry.contentType === 'POST' || + entry.contentType === 'PREREGISTRATION' || + entry.contentType === 'PURCHASE' || + entry.contentType === 'USDFUNDRAISECONTRIBUTION' + ) { + const post = entry.content as FeedPostContent; + if (!post.title) return null; + const documentType: ContentType = + entry.contentType === 'PREREGISTRATION' || + entry.contentType === 'PURCHASE' || + entry.contentType === 'USDFUNDRAISECONTRIBUTION' || + post.contentType === 'PREREGISTRATION' + ? 'preregistration' + : 'post'; + return { + id: post.id, + slug: post.slug, + title: post.title, + href: buildWorkUrl({ + id: post.id, + slug: post.slug || undefined, + contentType: documentType, + tab, + }), + imageUrl: post.previewImage, + documentType, + unifiedDocumentId: toOptionalNumber(post.unifiedDocumentId), + fundraise: post.fundraise, + bounty, + authors: post.authors, + tab, + }; + } + + return null; +} +function workContextFromRelatedWork(entry: FeedEntry, related: Work): ActivityWorkContext { + const tab = resolveTabFromContext(entry.activityContext); + const documentType = related.contentType; return { id: related.id, slug: related.slug, title: related.title, - href, + href: buildWorkUrl({ + id: related.id, + slug: related.slug, + contentType: documentType, + tab, + }), imageUrl: related.image, documentType, unifiedDocumentId: related.unifiedDocumentId, @@ -285,3 +387,12 @@ export function getActivityWorkContext(entry: FeedEntry): ActivityWorkContext | tab, }; } + +export function getActivityWorkContext(entry: FeedEntry): ActivityWorkContext | null { + const related = entry.relatedWork; + if (related?.title) { + return workContextFromRelatedWork(entry, related); + } + + return getWorkContextFromContent(entry); +} diff --git a/types/work.ts b/types/work.ts index f9dae199c..cacfb22ea 100644 --- a/types/work.ts +++ b/types/work.ts @@ -152,7 +152,6 @@ export interface LinkedGrant { applicantCount: number; } -/** Slim grant metadata attached to activity feed related_work */ export interface WorkGrantSummary { status: string; organization: string; diff --git a/utils/number.ts b/utils/number.ts index 36ba7d32d..fe4e24dad 100644 --- a/utils/number.ts +++ b/utils/number.ts @@ -80,6 +80,22 @@ export function formatBadgeCount(count: number): string { return count > 9 ? '9+' : count.toString(); } +/** + * Coerce a string/number id-like value to a finite number, or undefined. + * + * @example + * toOptionalNumber('42') // 42 + * toOptionalNumber(7) // 7 + * toOptionalNumber('') // undefined + * toOptionalNumber(null) // undefined + * toOptionalNumber('abc') // undefined + */ +export function toOptionalNumber(value: string | number | null | undefined): number | undefined { + if (value == null || value === '') return undefined; + const parsed = typeof value === 'number' ? value : Number(value); + return Number.isFinite(parsed) ? parsed : undefined; +} + /** * Returns the number of decimal places in a number * @example From 24625b2f6b0d7f0a811a9a93387f41c57537aeb4 Mon Sep 17 00:00:00 2001 From: nicktytarenko Date: Sun, 2 Aug 2026 17:16:58 +0300 Subject: [PATCH 3/3] small refactoring and cleanup --- app/grant/[id]/[slug]/page.tsx | 1 - components/Activity/ActivityCardFull.tsx | 37 ++-- components/Activity/ContributionAmount.tsx | 1 - components/Activity/WorkCardActions.tsx | 37 ---- .../Activity/lib/activityWorkContext.ts | 209 +++++++++++------- .../Activity/lib/deriveActivityContext.ts | 4 +- components/Activity/lib/feedEntryAdapters.ts | 8 - components/Comment/lib/TipTapRenderer.tsx | 3 +- components/Feed/FeedItemActions.tsx | 4 - components/Funding/ActivityCard.tsx | 16 +- 10 files changed, 153 insertions(+), 167 deletions(-) delete mode 100644 components/Activity/WorkCardActions.tsx diff --git a/app/grant/[id]/[slug]/page.tsx b/app/grant/[id]/[slug]/page.tsx index a6e010542..01982cdce 100644 --- a/app/grant/[id]/[slug]/page.tsx +++ b/app/grant/[id]/[slug]/page.tsx @@ -38,7 +38,6 @@ export default async function GrantSlugPage({ params }: Props) { const work = await getGrant(id); const grant = work.note?.post?.grant; - const grantId = grant?.id ?? undefined; return ( diff --git a/components/Activity/ActivityCardFull.tsx b/components/Activity/ActivityCardFull.tsx index 3583df8a9..a6cec1011 100644 --- a/components/Activity/ActivityCardFull.tsx +++ b/components/Activity/ActivityCardFull.tsx @@ -4,15 +4,14 @@ import { FC, useState } from 'react'; import { useRouter } from 'next/navigation'; import { ArrowRight } from 'lucide-react'; import { Avatar } from '@/components/ui/Avatar'; -import { AuthorTooltip } from '@/components/ui/AuthorTooltip'; import { Button } from '@/components/ui/Button'; import { CommentReadOnly } from '@/components/Comment/CommentReadOnly'; +import { FeedItemActions } from '@/components/Feed/FeedItemActions'; import { ContributeToFundraiseModal } from '@/components/modals/ContributeToFundraiseModal'; import { useCurrencyPreference } from '@/contexts/CurrencyPreferenceContext'; import { useExchangeRate } from '@/contexts/ExchangeRateContext'; import { useShareModalContext } from '@/contexts/ShareContext'; import { ActivityCardHeader } from './ActivityCardHeader'; -import { WorkCardActions } from './WorkCardActions'; import { WorkPreviewCard } from './WorkPreviewCard'; import { getActivityHeaderMessage, getCommentPreview } from './lib/feedEntryAdapters'; import { getActivityWorkContext, getWorkCardPresentation } from './lib/activityWorkContext'; @@ -43,6 +42,7 @@ export const ActivityCardFull: FC = ({ entry }) => { const showComment = presentation.showComment && !!commentPreview; const voteCount = entry.metrics?.adjustedScore ?? entry.metrics?.votes ?? 0; const isReviewOfProposal = !!commentPreview?.isReview && work.documentType === 'preregistration'; + const feedContentType = work.documentType === 'paper' ? 'PAPER' : 'POST'; const handleFundClick = () => { setIsContributeModalOpen(true); @@ -80,15 +80,12 @@ export const ActivityCardFull: FC = ({ entry }) => {
- - - +
@@ -121,11 +118,21 @@ export const ActivityCardFull: FC = ({ entry }) => { stats={presentation.stats} progress={presentation.progress} actions={ - } /> diff --git a/components/Activity/ContributionAmount.tsx b/components/Activity/ContributionAmount.tsx index 1ea82a025..67b200fef 100644 --- a/components/Activity/ContributionAmount.tsx +++ b/components/Activity/ContributionAmount.tsx @@ -10,7 +10,6 @@ import { resolveDisplayedContribution, type FeedContribution } from './lib/feedE interface ContributionAmountProps { contribution: FeedContribution; className?: string; - /** Prefix with "+" (default). Set false for earnings like "earned $150". */ showSign?: boolean; } diff --git a/components/Activity/WorkCardActions.tsx b/components/Activity/WorkCardActions.tsx deleted file mode 100644 index e26767465..000000000 --- a/components/Activity/WorkCardActions.tsx +++ /dev/null @@ -1,37 +0,0 @@ -'use client'; - -import { FC, ReactNode } from 'react'; -import { FeedItemActions } from '@/components/Feed/FeedItemActions'; -import type { UserVoteType } from '@/types/reaction'; -import type { FeedContentType } from '@/types/feed'; -import type { ActivityWorkContext } from './lib/activityWorkContext'; - -interface WorkCardActionsProps { - work: ActivityWorkContext; - voteCount: number; - userVote?: UserVoteType; - cta?: ReactNode; -} - -function toFeedContentType(documentType: ActivityWorkContext['documentType']): FeedContentType { - return documentType === 'paper' ? 'PAPER' : 'POST'; -} - -export const WorkCardActions: FC = ({ work, voteCount, userVote, cta }) => ( - -); diff --git a/components/Activity/lib/activityWorkContext.ts b/components/Activity/lib/activityWorkContext.ts index f2360511e..11bf025fa 100644 --- a/components/Activity/lib/activityWorkContext.ts +++ b/components/Activity/lib/activityWorkContext.ts @@ -152,108 +152,145 @@ function formatAmount( }); } -export function getWorkCardPresentation( +function resolveReviewScore(entry: FeedEntry, work: ActivityWorkContext): number | null { + const entryScore = entry.metrics?.reviewScore; + if (entryScore && entryScore > 0) return entryScore; + + const fundraiseAvg = work.fundraise?.reviewMetrics?.avg; + if (fundraiseAvg && fundraiseAvg > 0) return fundraiseAvg; + + return null; +} + +function buildBasePresentation( entry: FeedEntry, work: ActivityWorkContext, - options: { showUSD: boolean; exchangeRate: number; isReview?: boolean } + slot: ActivityBodySlot ): WorkCardPresentation { - const { showUSD, exchangeRate, isReview } = options; - const slot = resolveActivityBodySlot(entry.activityContext, work, { isReview }); - - // Prefer real document score; omit when absent (no mocks). - const score = - entry.metrics?.reviewScore && entry.metrics.reviewScore > 0 - ? entry.metrics.reviewScore - : work.fundraise?.reviewMetrics?.avg && work.fundraise.reviewMetrics.avg > 0 - ? work.fundraise.reviewMetrics.avg - : null; - - const authors = toCardAuthors(work.authors); - const institution = entry.nonprofit?.name ?? null; - const base: WorkCardPresentation = { - authors, + return { + authors: toCardAuthors(work.authors), organization: resolveOrganization(entry, work), - institution, - score, + institution: entry.nonprofit?.name ?? null, + score: resolveReviewScore(entry, work), // Caller ANDs with commentPreview presence; here we only gate by slot. showComment: slot !== 'bounty' && slot !== 'grant', }; +} - if (slot === 'fundraise' && work.fundraise) { - const fundraise = work.fundraise; - const goalAmount = showUSD ? fundraise.goalAmount.usd : fundraise.goalAmount.rsc; - const goalUsd = fundraise.goalAmount.usd; - const raisedUsd = fundraise.amountRaised.usd; - - return { - ...base, - stats: [ - { - label: 'Raising', - value: formatAmount(goalAmount, showUSD, exchangeRate, true), - accent: true, - }, - ], - progress: goalUsd > 0 ? raisedUsd / goalUsd : undefined, - cta: isFundraiseActive(fundraise) ? { kind: 'fund-modal', label: 'Fund' } : undefined, - }; - } +function presentFundraise( + base: WorkCardPresentation, + fundraise: NonNullable, + showUSD: boolean, + exchangeRate: number +): WorkCardPresentation { + const goalAmount = showUSD ? fundraise.goalAmount.usd : fundraise.goalAmount.rsc; + const goalUsd = fundraise.goalAmount.usd; + const raisedUsd = fundraise.amountRaised.usd; - if (slot === 'grant' && work.grant) { - const grant = work.grant; - const isActive = - grant.status === 'OPEN' && (grant.endDate ? isDeadlineInFuture(grant.endDate) : true); - const budgetAmount = showUSD ? grant.amount.usd : (grant.amount.rsc ?? 0); - const hasBudget = grant.amount.usd > 0 || (grant.amount.rsc ?? 0) > 0; - const stats: WorkCardStat[] = []; - - if (hasBudget) { - stats.push({ - label: 'Available', - value: formatAmount(budgetAmount, showUSD, exchangeRate, showUSD), + return { + ...base, + stats: [ + { + label: 'Raising', + value: formatAmount(goalAmount, showUSD, exchangeRate, true), accent: true, - }); - } + }, + ], + progress: goalUsd > 0 ? raisedUsd / goalUsd : undefined, + cta: isFundraiseActive(fundraise) ? { kind: 'fund-modal', label: 'Fund' } : undefined, + }; +} + +function isGrantActive(grant: NonNullable): boolean { + if (grant.status !== 'OPEN') return false; + return grant.endDate ? isDeadlineInFuture(grant.endDate) : true; +} + +function presentGrant( + base: WorkCardPresentation, + work: ActivityWorkContext, + grant: NonNullable, + showUSD: boolean, + exchangeRate: number +): WorkCardPresentation { + const budgetAmount = showUSD ? grant.amount.usd : (grant.amount.rsc ?? 0); + const hasBudget = grant.amount.usd > 0 || (grant.amount.rsc ?? 0) > 0; + const stats: WorkCardStat[] = []; + + if (hasBudget) { stats.push({ - label: 'Proposals', - value: String(grant.numApplicants), + label: 'Available', + value: formatAmount(budgetAmount, showUSD, exchangeRate, showUSD), + accent: true, }); + } + stats.push({ + label: 'Proposals', + value: String(grant.numApplicants), + }); - return { - ...base, - stats: stats.length ? stats : undefined, - cta: isActive ? { kind: 'link', label: 'Apply', href: work.href } : undefined, - }; + return { + ...base, + stats, + cta: isGrantActive(grant) ? { kind: 'link', label: 'Apply', href: work.href } : undefined, + }; +} + +function isBountyActive(bounty: Bounty): boolean { + if (bounty.status === 'OPEN') { + return bounty.expirationDate ? isDeadlineInFuture(bounty.expirationDate) : true; } + return bounty.status === 'ASSESSMENT' || isOpenBounty(bounty); +} - if (slot === 'bounty' && work.bounty) { - const bounty = work.bounty; - const { amount } = getBountyDisplayAmount(bounty, exchangeRate, showUSD); - const isReviewBounty = bounty.bountyType === 'REVIEW'; - const href = `${buildWorkUrl({ - id: work.id, - slug: work.slug, - contentType: work.documentType, - tab: 'bounties', - })}?focus=true`; - const active = - bounty.status === 'OPEN' - ? bounty.expirationDate - ? isDeadlineInFuture(bounty.expirationDate) - : true - : bounty.status === 'ASSESSMENT' || isOpenBounty(bounty); +function presentBounty( + base: WorkCardPresentation, + work: ActivityWorkContext, + bounty: Bounty, + showUSD: boolean, + exchangeRate: number +): WorkCardPresentation { + const { amount } = getBountyDisplayAmount(bounty, exchangeRate, showUSD); + const isReviewBounty = bounty.bountyType === 'REVIEW'; + const href = `${buildWorkUrl({ + id: work.id, + slug: work.slug, + contentType: work.documentType, + tab: 'bounties', + })}?focus=true`; - return { - ...base, - stats: [ - { - label: isReviewBounty ? 'Peer Review' : 'Bounty', - value: formatAmount(amount, showUSD, exchangeRate, true), - accent: true, - }, - ], - cta: active ? { kind: 'link', label: isReviewBounty ? 'Review' : 'Solve', href } : undefined, - }; + return { + ...base, + stats: [ + { + label: isReviewBounty ? 'Peer Review' : 'Bounty', + value: formatAmount(amount, showUSD, exchangeRate, true), + accent: true, + }, + ], + cta: isBountyActive(bounty) + ? { kind: 'link', label: isReviewBounty ? 'Review' : 'Solve', href } + : undefined, + }; +} + +export function getWorkCardPresentation( + entry: FeedEntry, + work: ActivityWorkContext, + options: { showUSD: boolean; exchangeRate: number; isReview?: boolean } +): WorkCardPresentation { + const { showUSD, exchangeRate, isReview } = options; + const slot = resolveActivityBodySlot(entry.activityContext, work, { isReview }); + const base = buildBasePresentation(entry, work, slot); + + if (slot === 'fundraise' && work.fundraise) { + return presentFundraise(base, work.fundraise, showUSD, exchangeRate); + } + if (slot === 'grant' && work.grant) { + return presentGrant(base, work, work.grant, showUSD, exchangeRate); + } + if (slot === 'bounty' && work.bounty) { + return presentBounty(base, work, work.bounty, showUSD, exchangeRate); } return base; diff --git a/components/Activity/lib/deriveActivityContext.ts b/components/Activity/lib/deriveActivityContext.ts index 880fd4052..cd2295ae7 100644 --- a/components/Activity/lib/deriveActivityContext.ts +++ b/components/Activity/lib/deriveActivityContext.ts @@ -1,7 +1,5 @@ import type { ActivityContext, RawApiFeedEntry } from '@/types/feed'; -const REVIEW_COMMENT_TYPES = new Set(['PEER_REVIEW', 'REVIEW']); - export function deriveActivityContext(feedEntry: RawApiFeedEntry): ActivityContext | undefined { const contentType = feedEntry.content_type?.toUpperCase(); const obj = feedEntry.content_object; @@ -10,7 +8,7 @@ export function deriveActivityContext(feedEntry: RawApiFeedEntry): ActivityConte switch (contentType) { case 'RHCOMMENTMODEL': { const commentType = obj.comment_type as string | undefined; - if (commentType && REVIEW_COMMENT_TYPES.has(commentType)) { + if (commentType === 'PEER_REVIEW') { return 'peer_review_published'; } if (Array.isArray(obj.bounties) && obj.bounties.length > 0) { diff --git a/components/Activity/lib/feedEntryAdapters.ts b/components/Activity/lib/feedEntryAdapters.ts index be97f4138..83418177d 100644 --- a/components/Activity/lib/feedEntryAdapters.ts +++ b/components/Activity/lib/feedEntryAdapters.ts @@ -45,16 +45,11 @@ export interface ActivityHeaderMessage { actor: AuthorProfile; verb: string; target?: ActivityHeaderTarget; - /** Payout rather than contribution — the amount renders without a "+". */ isEarning?: boolean; } /** * True when the profile belongs to the ResearchHub Foundation account. - * - * Feed payloads are inconsistent about which id they expose for an actor, so we - * prefer the explicit user fields and only fall back to `id` when the profile - * carries no user reference at all (funder objects are serialized that way). */ function isFoundationProfile(profile?: AuthorProfile): boolean { if (!profile) return false; @@ -67,8 +62,6 @@ function getFundingActivityMessage(content: FeedFundingActivityContent): Activit const actor = content.createdBy; const recipient = content.recipient; - // Bounty payouts and Foundation tips read as the recipient earning — the - // person who received the money is the interesting subject. if (recipient && (content.sourceType === 'BOUNTY_PAYOUT' || isFoundationProfile(actor))) { return { actor: recipient, verb: 'earned', isEarning: true }; } @@ -277,7 +270,6 @@ export function getReviewScore(entry: FeedEntry): number | undefined { if (entry.contentType !== 'COMMENT') return undefined; const commentContent = entry.content as FeedCommentContent; if (commentContent.comment?.commentType !== 'REVIEW') return undefined; - // When the header leads with an earning, the score stays on the document card. if (getReviewEarning(entry)) return undefined; return commentContent.review?.score ?? commentContent.comment.reviewScore; } diff --git a/components/Comment/lib/TipTapRenderer.tsx b/components/Comment/lib/TipTapRenderer.tsx index cd6164db8..fb2197e4e 100644 --- a/components/Comment/lib/TipTapRenderer.tsx +++ b/components/Comment/lib/TipTapRenderer.tsx @@ -167,8 +167,7 @@ const TipTapRenderer: React.FC = ({ // whose anchor text equals the href become `richLink` nodes so they // render with the same inline preview + hover surface as freshly pasted // links. Idempotent — already-converted docs pass through unchanged. - // Skip when link previews are disabled (e.g. activity feed) and demote - // any existing richLink atoms back to plain anchors. + // Skip when link previews are disabled. documentContent = showLinkPreviews ? normalizeRichLinks(documentContent) : demoteRichLinks(documentContent); diff --git a/components/Feed/FeedItemActions.tsx b/components/Feed/FeedItemActions.tsx index f5d251fa9..b9614dfd1 100644 --- a/components/Feed/FeedItemActions.tsx +++ b/components/Feed/FeedItemActions.tsx @@ -169,10 +169,6 @@ interface FeedItemActionsProps { isExpanded?: boolean; className?: string; variant?: 'default' | 'inline'; - /** - * When true, render share + save next to the vote control (left) so the - * trailing side can hold only `rightSideActionButton` (e.g. Fund / Review). - */ leadingUtilityActions?: boolean; } diff --git a/components/Funding/ActivityCard.tsx b/components/Funding/ActivityCard.tsx index 80db42d48..32a2469c6 100644 --- a/components/Funding/ActivityCard.tsx +++ b/components/Funding/ActivityCard.tsx @@ -3,7 +3,6 @@ import { FC } from 'react'; import Link from 'next/link'; import { Avatar } from '@/components/ui/Avatar'; -import { AuthorTooltip } from '@/components/ui/AuthorTooltip'; import { ActivityHeaderActionText } from '@/components/Activity/ActivityHeaderActionText'; import { BountyAmount } from '@/components/Activity/BountyAmount'; import { ContributionAmount } from '@/components/Activity/ContributionAmount'; @@ -58,15 +57,12 @@ export const ActivityCard: FC = ({ entry }) => {
- - - +