-
Notifications
You must be signed in to change notification settings - Fork 414
/
Copy pathprofile.connections.tsx
224 lines (215 loc) · 6.21 KB
/
profile.connections.tsx
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
import { invariantResponse } from '@epic-web/invariant'
import { type SEOHandle } from '@nasa-gcn/remix-seo'
import {
json,
type LoaderFunctionArgs,
type ActionFunctionArgs,
type SerializeFrom,
type HeadersFunction,
} from '@remix-run/node'
import { useFetcher, useLoaderData } from '@remix-run/react'
import { useState } from 'react'
import { Icon } from '#app/components/ui/icon.tsx'
import { StatusButton } from '#app/components/ui/status-button.tsx'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '#app/components/ui/tooltip.tsx'
import { requireUserId } from '#app/utils/auth.server.ts'
import { resolveConnectionData } from '#app/utils/connections.server.ts'
import {
ProviderConnectionForm,
type ProviderName,
ProviderNameSchema,
providerIcons,
providerNames,
} from '#app/utils/connections.tsx'
import { prisma } from '#app/utils/db.server.ts'
import { makeTimings } from '#app/utils/timing.server.ts'
import { createToastHeaders } from '#app/utils/toast.server.ts'
import { type BreadcrumbHandle } from './profile.tsx'
export const handle: BreadcrumbHandle & SEOHandle = {
breadcrumb: <Icon name="link-2">Connections</Icon>,
getSitemapEntries: () => null,
}
async function userCanDeleteConnections(userId: string) {
const user = await prisma.user.findUnique({
select: {
password: { select: { userId: true } },
_count: { select: { connections: true } },
},
where: { id: userId },
})
// user can delete their connections if they have a password
if (user?.password) return true
// users have to have more than one remaining connection to delete one
return Boolean(user?._count.connections && user?._count.connections > 1)
}
export async function loader({ request }: LoaderFunctionArgs) {
const userId = await requireUserId(request)
const timings = makeTimings('profile connections loader')
const rawConnections = await prisma.connection.findMany({
select: { id: true, providerName: true, providerId: true, createdAt: true },
where: { userId },
})
const connections: Array<{
providerName: ProviderName
id: string
displayName: string
link?: string | null
createdAtFormatted: string
}> = []
for (const connection of rawConnections) {
const r = ProviderNameSchema.safeParse(connection.providerName)
if (!r.success) continue
const providerName = r.data
const connectionData = await resolveConnectionData(
providerName,
connection.providerId,
{ timings },
)
connections.push({
...connectionData,
providerName,
id: connection.id,
createdAtFormatted: connection.createdAt.toLocaleString(),
})
}
return json(
{
connections,
canDeleteConnections: await userCanDeleteConnections(userId),
},
{ headers: { 'Server-Timing': timings.toString() } },
)
}
export const headers: HeadersFunction = ({ loaderHeaders }) => {
const headers = {
'Server-Timing': loaderHeaders.get('Server-Timing') ?? '',
}
return headers
}
export async function action({ request }: ActionFunctionArgs) {
const userId = await requireUserId(request)
const formData = await request.formData()
invariantResponse(
formData.get('intent') === 'delete-connection',
'Invalid intent',
)
invariantResponse(
await userCanDeleteConnections(userId),
'You cannot delete your last connection unless you have a password.',
)
const connectionId = formData.get('connectionId')
invariantResponse(typeof connectionId === 'string', 'Invalid connectionId')
await prisma.connection.delete({
where: {
id: connectionId,
userId: userId,
},
})
const toastHeaders = await createToastHeaders({
title: 'Deleted',
description: 'Your connection has been deleted.',
})
return json({ status: 'success' } as const, { headers: toastHeaders })
}
export default function Connections() {
const data = useLoaderData<typeof loader>()
return (
<div className="mx-auto max-w-md">
{data.connections.length ? (
<div className="flex flex-col gap-2">
<p>Here are your current connections:</p>
<ul className="flex flex-col gap-4">
{data.connections.map((c) => (
<li key={c.id}>
<Connection
connection={c}
canDelete={data.canDeleteConnections}
/>
</li>
))}
</ul>
</div>
) : (
<p>You don't have any connections yet.</p>
)}
<div className="mt-5 flex flex-col gap-5 border-b-2 border-t-2 border-border py-3">
{providerNames.map((providerName) => (
<ProviderConnectionForm
key={providerName}
type="Connect"
providerName={providerName}
/>
))}
</div>
</div>
)
}
function Connection({
connection,
canDelete,
}: {
connection: SerializeFrom<typeof loader>['connections'][number]
canDelete: boolean
}) {
const deleteFetcher = useFetcher<typeof action>()
const [infoOpen, setInfoOpen] = useState(false)
const icon = providerIcons[connection.providerName]
return (
<div className="flex justify-between gap-2">
<span className={`inline-flex items-center gap-1.5`}>
{icon}
<span>
{connection.link ? (
<a href={connection.link} className="underline">
{connection.displayName}
</a>
) : (
connection.displayName
)}{' '}
({connection.createdAtFormatted})
</span>
</span>
{canDelete ? (
<deleteFetcher.Form method="POST">
<input name="connectionId" value={connection.id} type="hidden" />
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<StatusButton
name="intent"
value="delete-connection"
variant="destructive"
size="sm"
status={
deleteFetcher.state !== 'idle'
? 'pending'
: deleteFetcher.data?.status ?? 'idle'
}
>
<Icon name="cross-1" />
</StatusButton>
</TooltipTrigger>
<TooltipContent>Disconnect this account</TooltipContent>
</Tooltip>
</TooltipProvider>
</deleteFetcher.Form>
) : (
<TooltipProvider>
<Tooltip open={infoOpen} onOpenChange={setInfoOpen}>
<TooltipTrigger onClick={() => setInfoOpen(true)}>
<Icon name="question-mark-circled"></Icon>
</TooltipTrigger>
<TooltipContent>
You cannot delete your last connection unless you have a password.
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
)
}