This repository was archived by the owner on Mar 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProposalCard.tsx
More file actions
492 lines (455 loc) · 19.1 KB
/
ProposalCard.tsx
File metadata and controls
492 lines (455 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
"use client";
import type React from "react";
import { Clock, Building2, ExternalLinkIcon, ExternalLink } from "lucide-react";
import type { Proposal, ProposalWithDAO } from "@/types";
import { format } from "date-fns";
import { truncateString, getExplorerLink, formatAction } from "@/utils/format";
import Link from "next/link";
import { useRouter } from "next/navigation";
import VoteStatusChart from "./VoteStatusChart";
import { useMemo } from "react";
import { TokenBalance } from "../reusables/BalanceDisplay";
import { ProposalStatusBadge } from "./ProposalBadge";
import { useProposalStatus } from "@/hooks/useProposalStatus";
import { useProposalVote } from "@/hooks/useProposalVote";
import { Button } from "@/components/ui/button";
import { RefreshCw, AlertCircle } from "lucide-react";
import { motion } from "framer-motion";
import { safeNumberFromBigInt } from "@/utils/proposal";
import { cn } from "@/lib/utils";
interface ProposalCardProps {
proposal: Proposal | ProposalWithDAO;
tokenSymbol?: string;
showDAOInfo?: boolean;
}
export default function ProposalCard({
proposal,
tokenSymbol = "",
showDAOInfo = false,
}: ProposalCardProps) {
const router = useRouter();
// Use the unified status system
const { status, statusConfig, isActive } = useProposalStatus(proposal);
// Use centralized vote hook for consistent data fetching
const {
voteDisplayData,
calculations,
error: hasVoteDataError,
refreshVoteData,
isLoading: isLoadingVotes,
vetoCheck,
} = useProposalVote({
proposal,
contractPrincipal: proposal.contract_principal,
});
// Extract vote data with fallback to proposal props
const voteSummary = useMemo(() => {
// Use hook data if available, otherwise fallback to proposal props
if (voteDisplayData && !hasVoteDataError) {
const votesForNum = Number(voteDisplayData.rawVotesFor);
const votesAgainstNum = Number(voteDisplayData.rawVotesAgainst);
return {
votesFor: votesForNum,
votesAgainst: votesAgainstNum,
totalVotes: votesForNum + votesAgainstNum,
hasVoteData: true,
};
}
// Fallback to proposal props if hook data unavailable
const hasVoteData =
proposal.votes_for !== null &&
proposal.votes_for !== undefined &&
proposal.votes_against !== null &&
proposal.votes_against !== undefined;
if (!hasVoteData) {
return {
votesFor: null,
votesAgainst: null,
totalVotes: null,
hasVoteData: false,
};
}
const votesFor = Number(proposal.votes_for);
const votesAgainst = Number(proposal.votes_against);
const totalVotes = votesFor + votesAgainst;
return { votesFor, votesAgainst, totalVotes, hasVoteData: true };
}, [
voteDisplayData,
hasVoteDataError,
proposal.votes_for,
proposal.votes_against,
]);
// Parse liquid_tokens as a number for use in percentage calculations
// const liquidTokens = Number(proposal.liquid_tokens);
const { totalVotes, hasVoteData } = voteSummary;
// Enhanced calculations for quorum and threshold display
const enhancedCalculations = useMemo(() => {
if (!calculations) return null;
const quorumPercentage = safeNumberFromBigInt(proposal.voting_quorum);
const thresholdPercentage = safeNumberFromBigInt(proposal.voting_threshold);
// Calculate if requirements are met
const metQuorum = calculations.participationRate >= quorumPercentage;
const metThreshold =
calculations.totalVotes > 0
? calculations.approvalRate >= thresholdPercentage
: false;
return {
...calculations,
quorumPercentage,
thresholdPercentage,
metQuorum,
metThreshold,
};
}, [calculations, proposal]);
// Helper function for status display
const getStatusText = (met: boolean, percentage?: number) => {
// If voting hasn't started (PENDING, DRAFT), show "Pending"
if (status === "PENDING" || status === "DRAFT") {
return "Pending";
}
if (isActive) {
return percentage !== undefined ? `${percentage.toFixed(1)}%` : "0%";
}
return met ? "Passed" : "Failed";
};
// Memoize DAO info
const daoInfo = useMemo(() => {
const proposalWithDAO = proposal as ProposalWithDAO;
if (proposalWithDAO.daos?.name) {
return proposalWithDAO.daos.name;
}
return proposal.contract_principal
? formatAction(proposal.contract_principal)
: "Unknown DAO";
}, [proposal]);
// Memoize DAO link for navigation
const daoLink = useMemo(() => {
const proposalWithDAO = proposal as ProposalWithDAO;
if (proposalWithDAO.daos?.name) {
return `/aidaos/${encodeURIComponent(proposalWithDAO.daos.name)}`;
}
return null;
}, [proposal]);
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: false, margin: "0px 0px -100px 0px", amount: 0.3 }}
transition={{ duration: 0.5, ease: "easeOut" }}
>
<Link
href={`/proposals/${proposal.id}`}
className="block group cursor-pointer"
>
<div className="py-4 px-8 rounded-sm mb-3 bg-background group-hover:bg-black transition-colors duration-300 max-w-full overflow-hidden">
{/* Header */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between mb-3 sm:mb-4 gap-3">
<div className="flex-1 min-w-0">
<h3 className="text-base sm:text-lg font-semibold text-foreground group-hover:text-primary transition-colors duration-200 line-clamp-2 mb-2">
{proposal.proposal_id
? `#${proposal.proposal_id}: ${proposal.title}`
: proposal.title}
</h3>
<div className="flex flex-wrap items-center gap-2 mb-2">
<ProposalStatusBadge
proposal={proposal}
size="sm"
className="flex-shrink-0"
/>
{/* Quorum and Threshold Badges */}
{enhancedCalculations &&
statusConfig.label !== "Pending" &&
statusConfig.label !== "Draft" && (
<>
{/* Quorum Badge */}
<div
className={cn(
"px-2 py-0.5 rounded-sm text-xs font-medium border flex-shrink-0",
isActive
? enhancedCalculations.metQuorum
? "bg-success/10 border-success/20"
: "bg-primary/10 border-primary/20"
: enhancedCalculations.metQuorum
? "bg-success/10 border-success/20"
: "bg-destructive/10 border-destructive/20"
)}
>
<span className="text-muted-foreground">Quorum:</span>{" "}
<span
className={cn(
isActive
? enhancedCalculations.metQuorum
? "text-success"
: "text-primary"
: enhancedCalculations.metQuorum
? "text-success"
: "text-destructive"
)}
>
{getStatusText(
enhancedCalculations.metQuorum,
enhancedCalculations.participationRate
)}
</span>
</div>
{/* Threshold Badge */}
<div
className={cn(
"px-2 py-0.5 rounded-sm text-xs font-medium border flex-shrink-0",
isActive
? enhancedCalculations.metThreshold
? "bg-success/10 border-success/20"
: "bg-primary/10 border-primary/20"
: enhancedCalculations.metThreshold
? "bg-success/10 border-success/20"
: "bg-destructive/10 border-destructive/20"
)}
>
<span className="text-muted-foreground">
Threshold:
</span>{" "}
<span
className={cn(
isActive
? enhancedCalculations.metThreshold
? "text-success"
: "text-primary"
: enhancedCalculations.metThreshold
? "text-success"
: "text-destructive"
)}
>
{getStatusText(
enhancedCalculations.metThreshold,
enhancedCalculations.approvalRate
)}
</span>
</div>
</>
)}
{/* Veto Override Warning Badge */}
{vetoCheck?.vetoExceedsForVote && !isActive && (
<div className="px-2 py-0.5 rounded-sm text-xs font-medium border flex-shrink-0 bg-destructive/10 border-destructive/20">
<span className="text-destructive">⚠️ Vetoed</span>
</div>
)}
<div className="flex items-center gap-1 text-xs text-foreground/75 flex-shrink-0">
<Clock className="h-3 w-3 flex-shrink-0" />
<span className="whitespace-nowrap">
{format(
new Date(proposal.created_at),
"MMM d, yyyy h:mm a"
)}
</span>
</div>
</div>
{/* Reference Links - Extract from content and display below title */}
{(() => {
if (!proposal.content) return null;
const referenceRegex = /Reference:\s*(https?:\/\/\S+)/i;
const airdropReferenceRegex =
/Airdrop Transaction ID:\s*(0x[a-fA-F0-9]+)/i;
const referenceMatch = proposal.content.match(referenceRegex);
const airdropMatch = proposal.content.match(
airdropReferenceRegex
);
const referenceLink = referenceMatch?.[1];
const airdropTxId = airdropMatch?.[1];
if (!referenceLink && !airdropTxId) return null;
return (
<div className="space-y-3 mb-4">
{referenceLink && (
<div className="rounded-sm ">
<div className="text-xs text-muted-foreground mb-1">
Reference
</div>
<span
role="link"
className="text-sm text-primary hover:text-primary/80 transition-colors break-all cursor-pointer flex items-center gap-2"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
window.open(
referenceLink,
"_blank",
"noopener,noreferrer"
);
}}
>
<span className="inline-block max-w-full break-all">
{referenceLink}
</span>
<ExternalLinkIcon className="h-4 w-4" />
</span>
</div>
)}
{airdropTxId && (
<div className="p-3 bg-background/50 rounded-sm border border-border/50">
<div className="text-xs text-muted-foreground mb-1">
Airdrop Transaction ID
</div>
<span
role="link"
className="text-sm text-primary hover:text-primary/80 transition-colors break-all cursor-pointer flex items-center gap-2"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
window.open(
`https://explorer.hiro.so/txid/${airdropTxId}?chain=${process.env.NEXT_PUBLIC_STACKS_NETWORK || "mainnet"}`,
"_blank",
"noopener,noreferrer"
);
}}
>
<svg
className="h-4 w-4 flex-shrink-0"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
/>
</svg>
<span className="inline-block max-w-full break-all">
{airdropTxId}
</span>
</span>
</div>
)}
</div>
);
})()}
{proposal.summary && (
<div className="text-base text-foreground/75 mb-3 break-words overflow-hidden">
{(() => {
if (!proposal.content) return proposal.summary;
// Remove reference links from summary since we show them separately
const referenceRegex = /Reference:\s*(https?:\/\/\S+)/i;
const airdropReferenceRegex =
/Airdrop Transaction ID:\s*(0x[a-fA-F0-9]+)/i;
let cleanedSummary = proposal.summary
.replace(referenceRegex, "")
.replace(airdropReferenceRegex, "")
.trim();
// Remove any remaining URLs from summary
cleanedSummary = cleanedSummary
.replace(/(https?:\/\/\S+)/g, "")
.trim();
return (
<span className="break-words">{cleanedSummary}</span>
);
})()}
</div>
)}
</div>
</div>
{/* Metadata */}
<div className="flex flex-wrap items-center gap-2 sm:gap-3 md:gap-4 text-xs text-foreground/75 mb-4">
{showDAOInfo && (
<div className="flex items-center gap-1 min-w-0 max-w-[120px] sm:max-w-none">
<Building2 className="h-3 w-3 flex-shrink-0" />
{daoLink ? (
<span
className="truncate hover:text-foreground transition-colors duration-300 font-medium cursor-pointer"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
router.push(daoLink);
}}
>
{daoInfo}
</span>
) : (
<span className="truncate">{daoInfo}</span>
)}
</div>
)}
<div className="flex items-center gap-1 min-w-0 sm:max-w-none">
<span className="text-xs text-muted-foreground">Creator:</span>
<span
className="hover:text-foreground transition-colors duration-300 truncate cursor-pointer flex items-center gap-1"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
window.open(
getExplorerLink("address", proposal.creator),
"_blank",
"noopener,noreferrer"
);
}}
>
{truncateString(proposal.creator, 4, 4)}
<ExternalLink className="h-3 w-3 flex-shrink-0" />
</span>
</div>
{hasVoteData && totalVotes !== null && totalVotes > 0 && (
<div className="flex items-center gap-1 min-w-0 sm:max-w-none">
<span className="text-xs text-muted-foreground">
Total Votes:
</span>
<TokenBalance
variant="abbreviated"
value={totalVotes.toString()}
/>
</div>
)}
{/* {liquidTokens > 0 && (
<div className="flex items-center gap-1 min-w-0 sm:max-w-none">
<span className="text-xs text-muted-foreground">Liquid Token:</span>
<TokenBalance
variant="abbreviated"
value={liquidTokens.toString()}
/>
</div>
)} */}
</div>
{/* Vote Data Error Handling */}
{hasVoteDataError && !voteDisplayData && (
<div className="flex items-center justify-between p-3 bg-destructive/10 border border-destructive/20 rounded-sm">
<div className="flex items-center gap-2 text-destructive">
<AlertCircle className="h-4 w-4" />
<span className="text-sm">Failed to fetch vote data</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
refreshVoteData();
}}
disabled={isLoadingVotes}
className="h-8 px-2 text-destructive hover:text-destructive"
>
<RefreshCw
className={`h-3 w-3 mr-1 ${isLoadingVotes ? "animate-spin" : ""}`}
/>
Refresh
</Button>
</div>
)}
{/* Vote Status Chart - Show for active, veto period, execution window, passed, and failed proposals */}
{(isActive ||
statusConfig.label === "Veto Period" ||
statusConfig.label === "Execution Window" ||
statusConfig.label === "Passed" ||
statusConfig.label === "Failed") &&
statusConfig.label !== "Pending" && (
<div className="">
<VoteStatusChart
proposalId={proposal.proposal_id?.toString()}
tokenSymbol={tokenSymbol}
liquidTokens={proposal.liquid_tokens}
proposal={proposal}
/>
</div>
)}
</div>
</Link>
</motion.div>
);
}