| 1 | "use client"; |
| 2 | |
| 3 | import { Star } from |
| 4 | import { useRouter } |
| 5 | import { useState } |
| 6 | import { toast } |
| 7 | |
| 8 | import { Button } |
| 9 | import { apiClient } |
| 10 | |
| 11 | export function StarButton({ |
| 12 | username, |
| 13 | slug, |
| 14 | starCount, |
| 15 | viewerHasStarred, |
| 16 | signedIn, |
| 17 | }: { |
| 18 | username: string |
| 19 | slug: string |
| 20 | starCount: number |
| 21 | viewerHasStarred: boolean |
| 22 | signedIn: boolean |
| 23 | }) { |
| 24 | const router = |
| 25 | const [pending, |
| 26 | starCount: number |
| 27 | viewerHasStarred: boolean |
| 28 | }>(); |
| 29 | |
| 30 | const state = |
| 31 | |
| 32 | async function toggle |
| 33 | if (!signedIn) |
| 34 | router.push( |
| 35 | `/auth/sign-in?redirectTo=${encodeURIComponent(`/ |
| 36 | ); |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | const starred = |
| 41 | setPending({ |
| 42 | starCount: state.starCount |
| 43 | viewerHasStarred: starred, |
| 44 | }); |
| 45 | |
| 46 | const request = |
| 47 | const { data, |
| 48 | "/api/repositories/{username}/{slug}/star", |
| 49 | { params: { path: |
| 50 | ); |
| 51 | |
| 52 | if (error || |
| 53 | setPending(undefined); |
| 54 | toast.error(`Could not |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | setPending(data); |
| 59 | // Anything else showing the count - the owner's repository list - is stale now. |
| 60 | router.refresh(); |
| 61 | } |
| 62 | |
| 63 | return ( |
| 64 | <Button variant=" |
| 65 | <Star |
| 66 | data-icon="inline-start" |
| 67 | className={state.viewerHasStarred |
| 68 | /> |
| 69 | {state.viewerHasStarred ? |
| 70 | <span className="ml-1 text-muted-foreground tabular-nums |
| 71 | {state.starCount} |
| 72 | </span> |
| 73 | </Button> |
| 74 | ); |
| 75 | } |