Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions src/components/bounty/BountyStatus.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
'use client';

import React from 'react';
import { useBountyStatus } from '@/hooks/useBountyStatus';
import type { Bounty, BountyStatus } from '@/types/bounty';

interface BountyStatusProps {
bountyId: string;
fallbackBounty?: Bounty;
onStatusChange?: (status: BountyStatus) => void;
className?: string;
}

const statusColors: Record<BountyStatus, string> = {
open: 'text-green-600 bg-green-50 border-green-200',
'in-progress': 'text-yellow-600 bg-yellow-50 border-yellow-200',
claimed: 'text-blue-600 bg-blue-50 border-blue-200',
completed: 'text-purple-600 bg-purple-50 border-purple-200',
cancelled: 'text-red-600 bg-red-50 border-red-200',
};

const statusLabels: Record<BountyStatus, string> = {
open: 'Open',
'in-progress': 'In Progress',
claimed: 'Claimed',
completed: 'Completed',
cancelled: 'Cancelled',
};

export function BountyStatus({
bountyId,
fallbackBounty,
onStatusChange,
className = ''
}: BountyStatusProps) {
const {
bounty,
isLoading,
error,
isPolling,
isLive,
status,
source,
refetch,
} = useBountyStatus({
bountyId,
fallbackBounty,
interval: 5000,
onStatusChange,
});

if (isLoading && !bounty) {
return (
<div className={`animate-pulse ${className}`}>
<div className="h-6 w-32 bg-gray-200 rounded"></div>
<div className="h-4 w-48 bg-gray-200 rounded mt-2"></div>
</div>
);
}

if (error) {
return (
<div className={`p-4 bg-red-50 border border-red-200 rounded-lg ${className}`}>
<p className="text-red-600 text-sm">Failed to load status</p>
<button
onClick={refetch}
className="mt-2 text-sm text-red-500 hover:text-red-700 underline"
>
Retry
</button>
</div>
);
}

if (!bounty) {
return <div className={className}>Bounty not found</div>;
}

const colorClass = status ? statusColors[status] || 'text-gray-600 bg-gray-50' : 'text-gray-600 bg-gray-50';
const label = status ? statusLabels[status] || status : 'Unknown';

return (
<div className={`${className}`}>
<div className="flex items-center gap-3 flex-wrap">
<span className={`px-3 py-1 rounded-full text-sm font-medium border ${colorClass}`}>
{label}
</span>

<span className="text-xs text-gray-400 flex items-center gap-1">
<span
className={`inline-block w-2 h-2 rounded-full ${
isLive ? 'bg-green-500 animate-pulse' :
isPolling ? 'bg-yellow-500' :
'bg-gray-400'
}`}
/>
{isLive ? 'Live' : isPolling ? 'Polling' : 'Paused'}
</span>

{source === 'mock' && (
<span className="text-xs text-yellow-600 bg-yellow-50 px-2 py-0.5 rounded">
Mock Data
</span>
)}
</div>

{bounty.claimedBy && (
<div className="mt-2 text-sm text-blue-600">
Claimed by: <span className="font-medium">{bounty.claimedBy}</span>
</div>
)}

<div className="mt-1 text-xs text-gray-400">
Updated: {new Date(bounty.updatedAt).toLocaleTimeString()}
</div>
</div>
);
}
192 changes: 192 additions & 0 deletions src/components/bounty/ClaimButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
'use client';

import React, { useState, useEffect, useRef, useReducer } from 'react';
import { useClaimRace } from '@/hooks/useClaimRace';
import { useBountyStatus } from '@/hooks/useBountyStatus';
import type { Bounty } from '@/types/bounty';

interface ClaimButtonProps {
bountyId: string;
fallbackBounty?: Bounty;
onClaimSuccess?: () => void;
className?: string;
}

type ClaimState = {
showRaceMessage: boolean;
claimSuccess: boolean;
};

type ClaimAction =
| { type: 'SHOW_RACE_MESSAGE' }
| { type: 'HIDE_RACE_MESSAGE' }
| { type: 'SHOW_CLAIM_SUCCESS' }
| { type: 'HIDE_CLAIM_SUCCESS' }
| { type: 'RESET' };

const initialState: ClaimState = {
showRaceMessage: false,
claimSuccess: false,
};

function claimReducer(state: ClaimState, action: ClaimAction): ClaimState {
switch (action.type) {
case 'SHOW_RACE_MESSAGE':
return { ...state, showRaceMessage: true };
case 'HIDE_RACE_MESSAGE':
return { ...state, showRaceMessage: false };
case 'SHOW_CLAIM_SUCCESS':
return { ...state, claimSuccess: true };
case 'HIDE_CLAIM_SUCCESS':
return { ...state, claimSuccess: false };
case 'RESET':
return initialState;
default:
return state;
}
}

export function ClaimButton({
bountyId,
fallbackBounty,
onClaimSuccess,
className = ''
}: ClaimButtonProps) {
const { claim, isClaiming, lastResult, reset } = useClaimRace(bountyId);
const { bounty, refetch, status, isPolling } = useBountyStatus({
bountyId,
fallbackBounty,
interval: 2000,
});

const [state, dispatch] = useReducer(claimReducer, initialState);
const timerRef = useRef<NodeJS.Timeout | null>(null);

// Handle result changes
useEffect(() => {
// Clear any existing timer
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}

if (lastResult?.success === false && lastResult.error === 'ALREADY_CLAIMED') {
dispatch({ type: 'SHOW_RACE_MESSAGE' });
refetch();
timerRef.current = setTimeout(() => {
dispatch({ type: 'HIDE_RACE_MESSAGE' });
reset();
}, 15000);
} else if (lastResult?.success === true) {
dispatch({ type: 'SHOW_CLAIM_SUCCESS' });
refetch();
if (onClaimSuccess) {
onClaimSuccess();
}
timerRef.current = setTimeout(() => {
dispatch({ type: 'HIDE_CLAIM_SUCCESS' });
reset();
}, 5000);
}

return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
}, [lastResult, refetch, reset, onClaimSuccess]);

const handleClaim = async () => {
dispatch({ type: 'RESET' });
reset();
await claim();
};

const isDisabled = isClaiming || status === 'claimed' || status === 'completed';

if (status === 'claimed' || status === 'completed') {
return (
<div className={`p-4 bg-gray-50 border border-gray-200 rounded-lg ${className}`}>
<p className="text-gray-600">
This bounty has already been <span className="font-medium">{status}</span>
</p>
{bounty?.claimedBy && (
<p className="text-sm text-gray-500 mt-1">
Claimed by: {bounty.claimedBy}
</p>
)}
</div>
);
}

return (
<div className={`space-y-3 ${className}`}>
{state.showRaceMessage && lastResult?.success === false && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
<div className="flex items-start gap-3">
<span className="text-2xl">🏃</span>
<div>
<h4 className="text-red-700 font-semibold">
Someone else claimed this bounty first!
</h4>
<p className="text-red-600 text-sm mt-1">
The bounty has been claimed by another contributor.
The status has been updated below.
</p>
<button
onClick={() => dispatch({ type: 'HIDE_RACE_MESSAGE' })}
className="mt-2 text-sm text-red-500 hover:text-red-700 underline"
>
Dismiss
</button>
</div>
</div>
</div>
)}

{state.claimSuccess && (
<div className="p-4 bg-green-50 border border-green-200 rounded-lg">
<div className="flex items-start gap-3">
<span className="text-2xl">✅</span>
<div>
<h4 className="text-green-700 font-semibold">Successfully claimed!</h4>
<p className="text-green-600 text-sm mt-1">
You have claimed this bounty. Good luck!
</p>
</div>
</div>
</div>
)}

<button
onClick={handleClaim}
disabled={isDisabled}
className={`
w-full py-3 px-4 rounded-lg font-semibold transition-all
${isDisabled
? 'bg-gray-200 text-gray-500 cursor-not-allowed'
: 'bg-blue-600 text-white hover:bg-blue-700 active:scale-[0.98]'}
`}
>
{isClaiming ? (
<span className="flex items-center justify-center gap-2">
<svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
</svg>
Processing claim...
</span>
) : (
'Claim Bounty'
)}
</button>

{isPolling && (
<p className="text-xs text-gray-400 text-center">
🔄 Auto-refreshing status...
</p>
)}
</div>
);
}
70 changes: 70 additions & 0 deletions src/hooks/useBountyStatus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { useSmartPolling } from './useSmartPolling';
import { fetchBounty } from '@/lib/api';
import type { Bounty, BountyStatus } from '@/types/bounty';

interface UseBountyStatusOptions {
bountyId: string;
fallbackBounty?: Bounty;
interval?: number;
enabled?: boolean;
onStatusChange?: (status: BountyStatus) => void;
}

interface UseBountyStatusResult {
bounty: Bounty | null;
isLoading: boolean;
error: Error | null;
refetch: () => Promise<void>;
isPolling: boolean;
isLive: boolean;
status: BountyStatus | null;
source: 'live' | 'mock' | null;
}

export function useBountyStatus({
bountyId,
fallbackBounty,
interval = 5000,
enabled = true,
onStatusChange,
}: UseBountyStatusOptions): UseBountyStatusResult {
const {
data,
isLoading,
error,
refetch,
isPolling,
isBackingOff,
} = useSmartPolling<{ data: Bounty; source: 'live' | 'mock' }>({
fetchFn: async () => {
const result = await fetchBounty(bountyId, fallbackBounty);
return result;
},
interval,
enabled,
backoffMultiplier: 1.5,
maxBackoff: 30000,
unchangedThreshold: 3,
compareFn: (a, b) => {
const aStatus = a?.data?.status;
const bStatus = b?.data?.status;
return aStatus === bStatus && a?.data?.claimedBy === b?.data?.claimedBy;
},
onDataChange: (result) => {
if (onStatusChange && result?.data?.status) {
onStatusChange(result.data.status);
}
},
});

return {
bounty: data?.data || null,
isLoading,
error,
refetch,
isPolling,
isLive: isPolling && !isBackingOff,
status: data?.data?.status || null,
source: data?.source || null,
};
}
Loading