Files
supabase/apps/studio/routes/project/$ref/auth/templates/$templateId.tsx
Alaister YoungandAlaister Young 5f282681ef [FE-3106] (part 7) – refactor(studio): move project auth page bodies into routes (#53216)
Moves all `/project/$ref/auth/*` page bodies into their route files and
deletes `pages/project/[ref]/auth/**` (FE-3106). Part 7 of the stack.

**Depends on:** #53215

**Changed:**
- `routes/project/$ref/auth/**` – 18 page bodies inlined. `overview`
redirects with a typed `navigate` when the flag is off and now also
re-runs once flags finish loading (before, a late flag load could skip
the redirect); `templates/$templateId` reads params from
`Route.useParams()` and uses `Link`. `authLayoutTitle` and the
`skipAuthLayout` leaves match the old `getLayout`s

**Removed:**
- 18 page files

Addresses
[FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages).

## To test

- Click through Authentication (Users, Providers, Sessions, Rate Limits,
Emails, SMTP, URL Configuration, Hooks, MFA, Attack Protection,
Third-party, OAuth) – same layout and titles
- Open an email template and use "Back" – returns to the templates list

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-17 16:00:07 +09:00

309 lines
11 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 { createFileRoute, Link } from '@tanstack/react-router'
import { useParams } from 'common'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import {
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
Button,
Card,
CardContent,
CardFooter,
Form,
FormControl,
FormField,
Switch,
} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { PageContainer } from 'ui-patterns/PageContainer'
import {
PageHeader,
PageHeaderAside,
PageHeaderBreadcrumb,
PageHeaderDescription,
PageHeaderMeta,
PageHeaderSummary,
PageHeaderTitle,
} from 'ui-patterns/PageHeader'
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 '@/components/interfaces/Auth/EmailTemplates/AuthTemplatesValidation'
import { CustomEmailTemplateRestrictionAdmonition } from '@/components/interfaces/Auth/EmailTemplates/CustomEmailTemplateRestrictionAdmonition'
import { AUTH_EMAIL_TEMPLATES_DOCS_PATH } from '@/components/interfaces/Auth/EmailTemplates/EmailTemplates.constants'
import {
isCustomEmailTemplateEditingRestricted,
isCustomEmailTemplateRestrictionStatusKnown,
slugifyTitle,
} from '@/components/interfaces/Auth/EmailTemplates/EmailTemplates.utils'
import { SendEmailHookActiveAdmonition } from '@/components/interfaces/Auth/EmailTemplates/SendEmailHookActiveAdmonition'
import { TemplateEditor } from '@/components/interfaces/Auth/EmailTemplates/TemplateEditor'
import { DocsButton } from '@/components/ui/DocsButton'
import { NoPermission } from '@/components/ui/NoPermission'
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'
export const Route = createFileRoute('/project/$ref/auth/templates/$templateId')({
component: TemplatePage,
staticData: {
authLayoutTitle: 'Emails',
},
})
function TemplatePage() {
const { templateId, ref } = useParams()
const { can: canReadAuthSettings, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.AUTH_CONFIG_READ
)
const { can: canUpdateConfig } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.AUTH_CONFIG_WRITE
)
const { data: authConfig, isPending: isLoadingConfig } = useAuthConfigQuery({ projectRef: ref })
const { data: selectedOrganization } = useSelectedOrganizationQuery()
const { data: selectedProject } = useSelectedProjectQuery()
const isTemplateRestrictionStatusKnown = isCustomEmailTemplateRestrictionStatusKnown({
authConfig,
organization: selectedOrganization,
projectInsertedAt: selectedProject?.inserted_at,
})
const isTemplateEditBlocked =
isTemplateRestrictionStatusKnown &&
isCustomEmailTemplateEditingRestricted({
authConfig,
organization: selectedOrganization,
projectInsertedAt: selectedProject?.inserted_at,
})
const isTemplateEditorReadOnly = !isTemplateRestrictionStatusKnown || isTemplateEditBlocked
const hasSendEmailHook = !!(
authConfig?.HOOK_SEND_EMAIL_ENABLED && authConfig?.HOOK_SEND_EMAIL_URI
)
const { mutate: updateAuthConfig, isPending: isUpdatingConfig } = useAuthConfigUpdateMutation({
onError: (error) => {
toast.error(`Failed to update settings: ${error?.message}`)
},
onSuccess: () => {
toast.success('Successfully updated settings')
},
})
// Find template whose slug matches the URL slug
const template =
templateId && typeof templateId === 'string'
? TEMPLATES_SCHEMAS.find((template) => slugifyTitle(template.title) === templateId)
: null
// Determine if this is a security notification template
const isSecurityTemplate = template?.misc?.emailTemplateType === 'security'
// Get the enabled key for security templates
const templateEnabledKey = isSecurityTemplate
? (`MAILER_NOTIFICATIONS_${template.id?.replace('_NOTIFICATION', '')}_ENABLED` as string)
: null
const showConfigurationSection = isSecurityTemplate && templateEnabledKey
// Create form schema for security templates
const TemplateFormSchema = templateEnabledKey
? z.object({
[templateEnabledKey]: z.boolean(),
})
: z.object({})
const defaultValues = templateEnabledKey
? {
[templateEnabledKey]: authConfig
? Boolean(authConfig[templateEnabledKey as keyof typeof authConfig])
: false,
}
: {}
const templateForm = useForm<z.infer<typeof TemplateFormSchema>>({
resolver: zodResolver(TemplateFormSchema),
defaultValues,
})
const onSubmit = (values: z.infer<typeof TemplateFormSchema>) => {
if (!ref) return console.error('Project ref is required')
updateAuthConfig({ projectRef: ref, config: { ...values }, skipInvalidation: true })
}
useEffect(() => {
if (authConfig && templateEnabledKey) {
templateForm.reset({
[templateEnabledKey]: Boolean(authConfig[templateEnabledKey as keyof typeof authConfig]),
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [authConfig, templateEnabledKey])
if (isPermissionsLoaded && !canReadAuthSettings) {
return <NoPermission isFullPage resourceText="access your project's email settings" />
}
if (!templateId) {
return null
}
// Show error if templateId is invalid or template is not found
if (!template) {
return (
<div className="flex h-full w-full items-center justify-center">
<Admonition
className="max-w-md"
type="default"
title="Unable to find template"
description={`${templateId ? `The template "${templateId}"` : 'This template'} doesn’t seem to exist.`}
>
<Button asChild className="mt-2">
<Link to="..">Head back</Link>
</Button>
</Admonition>
</div>
)
}
return (
<>
<PageHeader size="default">
<PageHeaderBreadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink asChild>
<Link to="..">Emails</Link>
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem>
<BreadcrumbPage>{template.title}</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</PageHeaderBreadcrumb>
<PageHeaderMeta>
<PageHeaderSummary>
<PageHeaderTitle>{template.title}</PageHeaderTitle>
<PageHeaderDescription>
{template.purpose || 'Configure and customize email templates.'}
</PageHeaderDescription>
</PageHeaderSummary>
<PageHeaderAside>
<DocsButton href={`${DOCS_URL}${AUTH_EMAIL_TEMPLATES_DOCS_PATH}`} />
</PageHeaderAside>
</PageHeaderMeta>
</PageHeader>
<PageContainer size="default" className="pb-16">
{!isPermissionsLoaded || isLoadingConfig ? (
<PageSection>
<PageSectionContent>
<GenericSkeletonLoader />
</PageSectionContent>
</PageSection>
) : (
<>
{showConfigurationSection && (
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Configuration</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
<PageSectionContent>
<Form {...templateForm}>
<form onSubmit={templateForm.handleSubmit(onSubmit)} className="space-y-4">
<Card>
<CardContent>
<FormField
control={templateForm.control}
name={templateEnabledKey as keyof z.infer<typeof TemplateFormSchema>}
render={({ field }) => (
<FormItemLayout
layout="flex-row-reverse"
label="Enable notification"
description="Send this email to users when triggered"
>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
disabled={!canUpdateConfig}
/>
</FormControl>
</FormItemLayout>
)}
/>
</CardContent>
<CardFooter className="justify-end space-x-2">
{templateForm.formState.isDirty && (
<Button onClick={() => templateForm.reset()}>Cancel</Button>
)}
<Button
variant="primary"
type="submit"
disabled={
!canUpdateConfig ||
isUpdatingConfig ||
!templateForm.formState.isDirty
}
loading={isUpdatingConfig}
>
Save changes
</Button>
</CardFooter>
</Card>
</form>
</Form>
</PageSectionContent>
</PageSection>
)}
<PageSection>
{(showConfigurationSection || isTemplateEditBlocked) && (
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Content</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
)}
<PageSectionContent>
{isTemplateEditBlocked && !hasSendEmailHook && (
<div className="mb-4">
<CustomEmailTemplateRestrictionAdmonition />
</div>
)}
{hasSendEmailHook && (
<div className="mb-4">
<SendEmailHookActiveAdmonition />
</div>
)}
<Card>
<TemplateEditor template={template} isReadOnly={isTemplateEditorReadOnly} />
</Card>
</PageSectionContent>
</PageSection>
</>
)}
</PageContainer>
</>
)
}