-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathCampaignDetailPanel.tsx
More file actions
495 lines (455 loc) · 15.5 KB
/
Copy pathCampaignDetailPanel.tsx
File metadata and controls
495 lines (455 loc) · 15.5 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
493
494
495
import { FormEvent, useState, useEffect, useCallback } from 'react';
import { MousePointer2, Download, Link as LinkIcon } from 'lucide-react';
import { Link } from 'react-router-dom';
import { Campaign, AppConfig } from '../types/campaign';
import CopyButton from './CopyButton';
import { AddressAvatar } from './AddressAvatar';
import { EmptyState } from './EmptyState';
import { ContributorSummary } from './ContributorSummary';
import { CampaignImage } from './CampaignImage';
import { Countdown } from './Countdown';
import { useCampaignShareCard } from './CampaignShareCard';
import { useToast } from '../hooks/useToast';
import { ShareButtons } from './ShareButtons';
import { useMinDisplayTime } from '../hooks/useMinDisplayTime';
import type { ToastVariant } from '../hooks/useToast';
interface CampaignDetailPanelProps {
campaign: Campaign | null;
appConfig?: AppConfig | null;
connectedWallet?: string | null;
isConnectingWallet?: boolean;
isLoading?: boolean;
isPledgePending?: boolean;
notFoundCampaignId?: string | null;
onConnectWallet?: () => Promise<void>;
onDisconnectWallet?: () => void;
onPledge?: (campaignId: string, amount: number, assetCode: string) => Promise<void>;
onClaim?: (campaign: Campaign) => Promise<void>;
onSoftDelete?: (campaignId: string) => Promise<void>;
onRefund?: (campaignId: string, contributor: string) => Promise<void>;
onClose?: () => void;
onToast?: (
message: string,
variant?: ToastVariant,
link?: { href: string; label: string },
) => void;
}
const FEE_ESTIMATION_ERROR_CODES = new Set([
'SIMULATION_FAILED',
'SIMULATION_PREPARE_FAILED',
'SOURCE_ACCOUNT_LOAD_FAILED',
'STATE_RESTORE_REQUIRED',
]);
function describePledgeError(error: unknown): string {
const code = (error as { code?: string } | null)?.code;
if (code && FEE_ESTIMATION_ERROR_CODES.has(code)) {
return 'Could not estimate fee. Check your connection and retry.';
}
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
return 'The pledge could not be completed. Please try again.';
}
function networkName(config: AppConfig | null | undefined): string {
const passphrase = config?.networkPassphrase ?? config?.soroban?.networkPassphrase;
if (!passphrase) {
return 'Configured network';
}
if (passphrase === 'Test SDF Network ; September 2015') {
return 'Stellar Testnet';
}
if (passphrase === 'Public Global Stellar Network ; September 2015') {
return 'Stellar Mainnet';
}
return 'Configured network';
}
export function CampaignDetailPanel({
campaign,
appConfig,
connectedWallet = null,
isConnectingWallet = false,
isLoading = false,
isPledgePending = false,
notFoundCampaignId = null,
onConnectWallet = async () => {},
onDisconnectWallet = () => {},
onPledge = async () => {},
onClaim = async () => {},
onRefund = async () => {},
onToast,
}: CampaignDetailPanelProps) {
const [pledgeAmount, setPledgeAmount] = useState('25');
const [pledgeToken, setPledgeToken] = useState('');
const [refundContributor, setRefundContributor] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [pledgeError, setPledgeError] = useState<string | null>(null);
const [bannerImageError, setBannerImageError] = useState(false);
const walletReady = appConfig?.walletIntegrationReady ?? false;
const { downloadPng, toDataUrl } = useCampaignShareCard();
const { addToast } = useToast();
const handleDownloadPng = useCallback(() => {
if (!campaign) return;
downloadPng(campaign, campaign.metadata?.imageUrl);
addToast('Campaign card downloaded as PNG.', 'success');
}, [campaign, downloadPng, addToast]);
const handleCopyLink = useCallback(() => {
if (!campaign) return;
const url = `${window.location.origin}/campaigns/${campaign.id}`;
navigator.clipboard.writeText(url).then(() => {
addToast('Campaign link copied to clipboard.', 'success', { href: url, label: url.slice(0, 40) + '…' });
}).catch(() => {
addToast('Failed to copy link.', 'error');
});
}, [campaign, addToast]);
useEffect(() => {
setBannerImageError(false);
}, [campaign?.id, connectedWallet]);
const showSkeleton = useMinDisplayTime(isLoading);
if (showSkeleton) {
return (
<section className="card detail-panel" aria-busy="true" aria-label="Loading campaign details">
<div className="section-heading">
<h2>
<div className="skeleton skeleton-line" style={{ width: 220 }} />
</h2>
<div className="skeleton skeleton-line" style={{ width: 320, height: 14 }} />
</div>
<div className="detail-grid">
{Array.from({ length: 5 }).map((_, index) => (
<article key={index} className="detail-stat">
<div className="skeleton skeleton-line" style={{ width: 120 }} />
<div
className="skeleton skeleton-line"
style={{ width: 80, height: 18, marginTop: 8 }}
/>
</article>
))}
</div>
</section>
);
}
if (notFoundCampaignId) {
return (
<section className="card detail-panel">
<div className="section-heading">
<h2>Campaign not found</h2>
<p className="muted">
The campaign <code>#{notFoundCampaignId}</code> does not exist or may have been removed.
</p>
</div>
<div style={{ marginTop: 24 }}>
<Link to="/" className="btn-ghost">
Back to campaigns
</Link>
</div>
</section>
);
}
if (!campaign) {
return (
<EmptyState
variant="card"
icon={MousePointer2}
title="Campaign actions"
message="Pick a campaign from the board to manage it."
/>
);
}
const activeCampaign = campaign;
// Simulation is run (and the network fee estimated) before the preview modal
// opens. If that simulation fails, surface a retry-able error next to the
// pledge button instead of only relying on the toast.
const selectedToken = pledgeToken || activeCampaign.assetCode;
async function submitPledge() {
setPledgeError(null);
setIsSubmitting(true);
try {
await onPledge(activeCampaign.id, Number(pledgeAmount), selectedToken);
setPledgeAmount('25');
setPledgeToken('');
} catch (error) {
setPledgeError(describePledgeError(error));
} finally {
setIsSubmitting(false);
}
}
function handlePledge(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
void submitPledge();
}
async function handleRefund() {
setIsSubmitting(true);
try {
await onRefund(activeCampaign.id, refundContributor.trim());
} finally {
setIsSubmitting(false);
}
}
async function handleClaim() {
setIsSubmitting(true);
try {
await onClaim(activeCampaign);
} finally {
setIsSubmitting(false);
}
}
return (
<section className="card detail-panel">
{/* Full-width Campaign Banner */}
<div
style={{
width: 'calc(100% + 2rem)',
marginLeft: '-1rem',
marginRight: '-1rem',
marginTop: '-1rem',
height: '240px',
overflow: 'hidden',
background: 'linear-gradient(135deg, #6366f1 0%, #a855f7 100%)',
position: 'relative',
marginBottom: '1.5rem',
}}
>
{activeCampaign.metadata?.imageUrl && !bannerImageError ? (
<img
src={activeCampaign.metadata.imageUrl}
alt={activeCampaign.title}
onError={() => setBannerImageError(true)}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
display: 'block',
}}
/>
) : null}
</div>
<div className="section-heading">
<h2>{activeCampaign.title}</h2>
<p className="muted">{activeCampaign.description}</p>
</div>
<div className="wallet-status">
<div>
<h3 className="wallet-status-title">Wallet status</h3>
<p className="muted">
{connectedWallet
? `Connected to ${networkName(appConfig)}`
: `Not connected — connect a wallet to take actions`}
</p>
</div>
<div className="wallet-connected">
{connectedWallet ? (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<AddressAvatar address={connectedWallet} size={28} />
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<strong className="mono">{connectedWallet.slice(0, 16)}...</strong>
<CopyButton value={connectedWallet} ariaLabel="Copy connected wallet address" />
</div>
</div>
<button
className="btn-ghost"
type="button"
onClick={onDisconnectWallet}
disabled={isSubmitting}
>
Disconnect
</button>
</>
) : (
<button
className="btn-ghost"
type="button"
onClick={() => {
void onConnectWallet();
}}
disabled={isSubmitting || isConnectingWallet}
>
{isConnectingWallet ? 'Connecting...' : 'Connect Wallet'}
</button>
)}
</div>
</div>
<div className="detail-grid">
<article className="detail-stat">
<span>Campaign ID</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<strong className="mono">{activeCampaign.id}</strong>
<CopyButton value={activeCampaign.id} ariaLabel="Copy campaign ID" />
</div>
</article>
<article className="detail-stat">
<span>Creator</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<AddressAvatar address={activeCampaign.creator} size={28} />
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<strong className="mono">{activeCampaign.creator.slice(0, 16)}...</strong>
<CopyButton value={activeCampaign.creator} ariaLabel="Copy creator address" />
</div>
</div>
</article>
<article className="detail-stat">
<span>Asset</span>
<strong>{activeCampaign.assetCode}</strong>
</article>
<article className="detail-stat">
<span>Remaining</span>
<strong>{activeCampaign.progress.remainingAmount}</strong>
</article>
<article className="detail-stat">
<span>Active pledges</span>
<strong>{activeCampaign.progress.pledgeCount}</strong>
</article>
<article className="detail-stat">
<span>Time left</span>
<strong><Countdown deadline={activeCampaign.deadline} /></strong>
</article>
</div>
<ContributorSummary
campaignId={activeCampaign.id}
assetCode={activeCampaign.assetCode}
isLoading={isLoading}
/>
{!walletReady ? (
<p className="pending-note">
Wallet integration is not fully configured yet. Freighter actions that require Soroban
contract calls may stay disabled until backend config is set.
</p>
) : null}
<form className="form-grid" onSubmit={handlePledge}>
<label className="field-group">
<span>Connected contributor</span>
<input
type="text"
value={connectedWallet ?? ''}
placeholder="Connect a wallet to use the pledge flow"
readOnly
/>
</label>
{activeCampaign.acceptedTokens?.length > 1 && (
<label className="field-group">
<span>Token</span>
<select value={selectedToken} onChange={(e) => setPledgeToken(e.target.value)} required>
{activeCampaign.acceptedTokens.map((token) => (
<option key={token} value={token}>
{token}
</option>
))}
</select>
</label>
)}
<label className="field-group">
<span>Pledge amount</span>
<input
type="number"
min="0.01"
step="0.01"
value={pledgeAmount}
onChange={(event) => setPledgeAmount(event.target.value)}
required
/>
</label>
<div className="action-row">
<button
className="btn-primary"
type="submit"
disabled={
isSubmitting ||
isPledgePending ||
!activeCampaign.progress.canPledge ||
!connectedWallet
}
>
{isPledgePending ? 'Submitting...' : 'Add pledge'}
</button>
<button
className="btn-ghost"
type="button"
disabled={
isSubmitting ||
!activeCampaign.progress.canClaim ||
!connectedWallet ||
connectedWallet !== activeCampaign.creator ||
!walletReady
}
onClick={() => {
void handleClaim();
}}
>
Claim vault
</button>
</div>
{pledgeError ? (
<div className="pledge-error" role="alert">
<p className="error-text">{pledgeError}</p>
<button
className="btn-ghost"
type="button"
disabled={isSubmitting || isPledgePending}
onClick={() => {
void submitPledge();
}}
>
Retry
</button>
</div>
) : null}
</form>
<div className="form-grid" style={{ marginTop: 16 }}>
<label className="field-group">
<span>Refund contributor</span>
<input
type="text"
value={refundContributor}
onChange={(event) => setRefundContributor(event.target.value)}
placeholder="G... contributor public key"
/>
</label>
<div className="action-row">
<button
className="btn-ghost"
type="button"
disabled={
isSubmitting ||
!activeCampaign.progress.canRefund ||
refundContributor.trim().length === 0
}
onClick={() => {
void handleRefund();
}}
>
Refund contributor
</button>
</div>
</div>
{isPledgePending ? (
<p className="pending-note">
The pledge transaction is in flight. Campaign state will refresh after the backend
reconciles the result.
</p>
) : null}
{activeCampaign.metadata?.externalLink ? (
<div className="external-link-container">
<a
href={activeCampaign.metadata.externalLink}
target="_blank"
rel="noopener noreferrer"
className="btn-ghost"
>
Visit project website
</a>
</div>
) : null}
<div className="share-actions">
<button className="btn-ghost" type="button" onClick={handleDownloadPng}>
<Download size={16} />
Download PNG
</button>
<button className="btn-ghost" type="button" onClick={handleCopyLink}>
<LinkIcon size={16} />
Copy link
</button>
</div>
<ShareButtons campaign={activeCampaign} />
</section>
);
}