Files
Alaister YoungandAlaister Young 680633ee4f [FE-5108] (part 5) refactor(studio): migrate remaining interfaces off next/link (#54308)
Part 5 of a 6-PR stack migrating all `next/link` imports in
`apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known
external URLs) and removing `compat/next/link.tsx`.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54304 | `data/prefetchers/PrefetchableLink.tsx` and
`components/ui/**` |
| 2 | #54305 | `components/layouts/**` and top-level shell components |
| 3 | #54306 | Database, TableGridEditor, Storage, SQLEditor,
BranchManagement, Branching, Functions, Realtime |
| 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues,
Linter, Reports, QueryPerformance, QuerySources, ConfigDrift,
DiskManagement, Compute |
| **5** | **#54308 ← this PR** | **Remaining `components/interfaces/**`
(Org, Billing, Auth, Support, Home, SignIn, ConnectSheet, etc.)** |
| 6 | #54309 | Remove `compat/next/link.tsx` shim, Vite alias, and
update basePath tests/docs |

Migrates the remaining `components/interfaces/**` directories off
`next/link`, leaving zero `next/link` component imports in
`apps/studio`.

**Changed:**

- Replaced `next/link` across all 73 remaining interface files
(`Organization`, `OrganizationInvite`, `Billing`, `Auth`, `Support`,
`ProjectHome`, `Home`, `Project`, `ProjectCreation`, `ProjectAPIDocs`,
`ApiAuthorization`, `App`, `ConnectSheet`, `SignIn`, `APIKeys`,
`Account`, `CliLogin`, `Docs`, `JwtSecrets`, `Platform`)
- Converted the sole remaining `UrlObject` link (`<Link href={{
pathname: '/sign-in-sso', query }}>`) in `SignInSSOForm.tsx` to `<Link
to="/sign-in-sso" search={query}>`
- Migrated `SupportLink.tsx` onto `DynamicLink`
(`createSupportFormUrl(...)`)
- Standardized external `target="_blank"` anchors with `rel="noreferrer
noopener"`, switched `OverviewMetrics.tsx` observability link to typed
`<Link to="/project/$ref/observability/auth">`, and adopted `InlineLink`
/ `InlineLinkClassName` on inline paragraph links per review feedback

Addresses
[FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link)

## To test

- [ ] Check Organization (billing, usage, team, documents, AWS
Marketplace), Auth (providers, templates, rate limits, users, OAuth
apps), Support form/links, Project Home, Connect sheet, and Sign-In/SSO
links
- [ ] Verify `SignInWithSSOButton` preserves query params when
navigating to `/sign-in-sso`
- [ ] Verify `SupportLink` pre-populates support form query parameters
cleanly

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 17:33:03 +08:00

307 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { zodResolver } from '@hookform/resolvers/zod'
import { Link } from '@tanstack/react-router'
import { useParams } from 'common'
import { ChevronRightIcon } from 'lucide-react'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { Button, Card, CardContent, CardFooter, Form, FormControl, FormField, Switch } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import {
PageSection,
PageSectionContent,
PageSectionMeta,
PageSectionSummary,
PageSectionTitle,
} from 'ui-patterns/PageSection'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import * as z from 'zod'
import { TEMPLATES_SCHEMAS } from './AuthTemplatesValidation'
import { CustomEmailTemplateRestrictionAdmonition } from './CustomEmailTemplateRestrictionAdmonition'
import {
hasCustomEmailSender,
isCustomEmailTemplateEditingRestricted,
isCustomEmailTemplateRestrictionStatusKnown,
slugifyTitle,
} from './EmailTemplates.utils'
import { SendEmailHookActiveAdmonition } from './SendEmailHookActiveAdmonition'
import { AlertError } from '@/components/ui/AlertError'
import { InlineLink } from '@/components/ui/InlineLink'
import { useAuthConfigQuery } from '@/data/auth/auth-config-query'
import { useAuthConfigUpdateMutation } from '@/data/auth/auth-config-update-mutation'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { DOCS_URL } from '@/lib/constants'
const notificationEnabledKeys = TEMPLATES_SCHEMAS.filter(
(t) => t.misc?.emailTemplateType === 'security'
).map((template) => {
return `MAILER_NOTIFICATIONS_${template.id?.replace('_NOTIFICATION', '')}_ENABLED`
})
const NotificationsFormSchema = z.object({
...notificationEnabledKeys.reduce(
(acc, key) => {
acc[key] = z.boolean()
return acc
},
{} as Record<string, z.ZodBoolean>
),
})
export const EmailTemplates = () => {
const { ref: projectRef } = useParams()
const { data: selectedOrganization } = useSelectedOrganizationQuery()
const { data: selectedProject } = useSelectedProjectQuery()
const { can: canUpdateConfig } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.AUTH_CONFIG_WRITE
)
const {
data: authConfig,
error: authConfigError,
isPending: isLoading,
isError,
isSuccess,
} = useAuthConfigQuery({ projectRef })
const { mutate: updateAuthConfig, isPending: isUpdatingConfig } = useAuthConfigUpdateMutation({
onError: (error) => {
toast.error(`Failed to update settings: ${error?.message}`)
},
onSuccess: () => {
toast.success('Successfully updated settings')
},
})
const usingBuiltInEmailSender = !hasCustomEmailSender(authConfig)
const hasSendEmailHook = !!(
authConfig?.HOOK_SEND_EMAIL_ENABLED && authConfig?.HOOK_SEND_EMAIL_URI
)
const isTemplateRestrictionStatusKnown = isCustomEmailTemplateRestrictionStatusKnown({
authConfig,
organization: selectedOrganization,
projectInsertedAt: selectedProject?.inserted_at,
})
const isTemplateEditBlocked =
isTemplateRestrictionStatusKnown &&
isCustomEmailTemplateEditingRestricted({
authConfig,
organization: selectedOrganization,
projectInsertedAt: selectedProject?.inserted_at,
})
const defaultValues = notificationEnabledKeys.reduce(
(acc, key) => {
acc[key] = authConfig ? Boolean(authConfig[key as keyof typeof authConfig]) : false
return acc
},
{} as Record<string, boolean>
)
const notificationsForm = useForm<z.infer<typeof NotificationsFormSchema>>({
resolver: zodResolver(NotificationsFormSchema),
defaultValues,
})
const onSubmit = (values: z.infer<typeof NotificationsFormSchema>) => {
if (!projectRef) return console.error('Project ref is required')
updateAuthConfig({ projectRef: projectRef, config: { ...values } })
}
useEffect(() => {
if (authConfig) {
notificationsForm.reset(defaultValues)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [authConfig])
return (
<>
{isError && (
<PageSection>
<PageSectionContent>
<AlertError error={authConfigError} subject="Failed to retrieve auth configuration" />
</PageSectionContent>
</PageSection>
)}
{isLoading && (
<PageSection>
<PageSectionContent>
<GenericSkeletonLoader />
</PageSectionContent>
</PageSection>
)}
{isSuccess && (
<>
{isTemplateEditBlocked && !hasSendEmailHook && (
<PageSection>
<PageSectionContent>
<CustomEmailTemplateRestrictionAdmonition />
</PageSectionContent>
</PageSection>
)}
{hasSendEmailHook && (
<PageSection>
<PageSectionContent>
<SendEmailHookActiveAdmonition />
</PageSectionContent>
</PageSection>
)}
<PageSection>
{usingBuiltInEmailSender && !isTemplateEditBlocked && (
<Admonition
type="warning"
title="Set up custom SMTP"
description={
<p>
You’re using the built-in email service. This service has rate limits and is not
meant to be used for production apps.{' '}
<InlineLink
href={`${DOCS_URL}/guides/platform/going-into-prod#auth-rate-limits`}
>
Learn more
</InlineLink>{' '}
</p>
}
layout="horizontal"
actions={
<Button asChild>
<Link to="/project/$ref/auth/smtp" params={{ ref: projectRef ?? '_' }}>
Set up SMTP
</Link>
</Button>
}
/>
)}
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Authentication</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
<PageSectionContent>
<Card>
{TEMPLATES_SCHEMAS.filter(
(t) => t.misc?.emailTemplateType === 'authentication'
).map((template) => {
const templateSlug = slugifyTitle(template.title)
return (
<CardContent key={`${template.id}`} className="p-0">
<Link
to="/project/$ref/auth/templates/$templateId"
params={{ ref: projectRef ?? '_', templateId: templateSlug }}
className="flex items-center justify-between hover:bg-surface-200 transition-colors py-4 px-6 w-full h-full"
>
<div className="flex flex-col">
<h3 className="text-sm text-foreground">{template.title}</h3>
{template.purpose && (
<p className="text-sm text-foreground-lighter">{template.purpose}</p>
)}
</div>
<div className="flex items-center gap-4">
<ChevronRightIcon size={16} className="text-foreground-muted" />
</div>
</Link>
</CardContent>
)
})}
</Card>
</PageSectionContent>
</PageSection>
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Security</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
<PageSectionContent>
<Form {...notificationsForm}>
<form onSubmit={notificationsForm.handleSubmit(onSubmit)} className="space-y-4">
<Card>
{TEMPLATES_SCHEMAS.filter((t) => t.misc?.emailTemplateType === 'security').map(
(template) => {
const templateSlug = slugifyTitle(template.title)
const templateEnabledKey =
`MAILER_NOTIFICATIONS_${template.id?.replace('_NOTIFICATION', '')}_ENABLED` as keyof typeof authConfig
return (
<CardContent
key={`${template.id}`}
className="p-0 flex items-center justify-between hover:bg-surface-200 transition-colors w-full h-full"
>
<Link
to="/project/$ref/auth/templates/$templateId"
params={{ ref: projectRef ?? '_', templateId: templateSlug }}
className="flex flex-col flex-1 py-4 px-6"
>
<h3 className="text-sm text-foreground">{template.title}</h3>
{template.purpose && (
<p className="text-sm text-foreground-lighter">
{template.purpose}
</p>
)}
</Link>
<div className="flex items-center gap-4 h-full pl-2 relative">
<FormField
control={notificationsForm.control}
name={templateEnabledKey}
render={({ field }) => (
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
disabled={!canUpdateConfig}
/>
</FormControl>
)}
/>
<Link
to="/project/$ref/auth/templates/$templateId"
params={{ ref: projectRef ?? '_', templateId: templateSlug }}
className="py-6 pr-6"
>
<ChevronRightIcon size={16} className="text-foreground-muted" />
</Link>
</div>
</CardContent>
)
}
)}
<CardFooter className="justify-end space-x-2">
{notificationsForm.formState.isDirty && (
<Button onClick={() => notificationsForm.reset()}>Cancel</Button>
)}
<Button
variant="primary"
type="submit"
disabled={
!canUpdateConfig ||
isUpdatingConfig ||
!notificationsForm.formState.isDirty
}
loading={isUpdatingConfig}
>
Save changes
</Button>
</CardFooter>
</Card>
</form>
</Form>
</PageSectionContent>
</PageSection>
</>
)}
</>
)
}