Files
supabase/apps/studio/components/interfaces/Auth/AuthProvidersForm/ProviderForm.tsx
Alaister Young ca2b50a0a7 chore(ui-patterns): collapse the admonition shim into ui-patterns/Admonition (#48377)
Follow-up to #48344: collapses the two resolution paths for the
Admonition module into one.

`src/admonition.tsx` was a back-compat shim re-exporting
`src/Admonition/`. Two ways to resolve one module is exactly what
produced the macOS self-import bug fixed in #48344, and the local
typecheck errors that #48374 worked around. This removes the shim and
standardizes on the PascalCase subpath, matching every other export in
the package.

**Changed:**

- Codemodded all 246 `ui-patterns/admonition` imports to
`ui-patterns/Admonition` (240 `.tsx`, 5 `.mdx`, 1 `.ts` across studio,
docs, www, design-system, and lite-studio)
- Pointed the 5 internal `'../admonition'` imports back at the
`'../Admonition'` directory

**Removed:**

- `packages/ui-patterns/src/admonition.tsx`, and its `./admonition`
entry in the exports map (regenerated with `pnpm gen:exports`)

## To test

- `grep -r "ui-patterns/admonition" --include='*.ts*'` → no hits
- `pnpm test:case-hazards` → passes
- `pnpm typecheck` → all 15 tasks green
- `pnpm --filter studio run lint:ratchet` → passes
- `pnpm --filter ui-patterns vitest run src/Admonition` → 11 tests pass

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Standardized Admonition component imports across the application and
documentation.
* Improved compatibility with case-sensitive environments by using the
canonical component path.
  * Removed the legacy Admonition import entry point.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-07-29 00:48:56 +08:00

317 lines
11 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { Check } from 'lucide-react'
import { useTheme } from 'next-themes'
import { useQueryState } from 'nuqs'
import { useCallback, useEffect, useId, useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'
import ReactMarkdown from 'react-markdown'
import { toast } from 'sonner'
import {
Button,
Form,
Sheet,
SheetContent,
SheetFooter,
SheetHeader,
SheetSection,
SheetTitle,
} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { Input } from 'ui-patterns/DataInputs/Input'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { NO_REQUIRED_CHARACTERS } from '../Auth.constants'
import { AuthAlert } from './AuthAlert'
import type { Provider } from './AuthProvidersForm.types'
import FormField from './FormField'
import { Markdown } from '@/components/interfaces/Markdown'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { DocsButton } from '@/components/ui/DocsButton'
import { ResourceItem } from '@/components/ui/Resource/ResourceItem'
import type { components } from '@/data/api'
import { useAuthConfigUpdateMutation } from '@/data/auth/auth-config-update-mutation'
import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { useHasEntitlementAccess } from '@/hooks/misc/useCheckEntitlements'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { BASE_PATH } from '@/lib/constants'
interface ProviderFormProps {
config: components['schemas']['GoTrueConfigResponse']
provider: Provider
isActive: boolean
}
const doubleNegativeKeys = ['SMS_AUTOCONFIRM']
export const ProviderForm = ({ config, provider, isActive }: ProviderFormProps) => {
const { resolvedTheme } = useTheme()
const { ref: projectRef } = useParams()
const { data: organization } = useSelectedOrganizationQuery()
const [urlProvider, setUrlProvider] = useQueryState('provider', { defaultValue: '' })
const [open, setOpen] = useState(false)
const { mutate: updateAuthConfig, isPending: isUpdatingConfig } = useAuthConfigUpdateMutation()
const { data: endpoint } = useProjectApiUrl({ projectRef })
const { can: canUpdateConfig } = useAsyncCheckPermissions(
PermissionAction.UPDATE,
'custom_config_gotrue'
)
const shouldDisableField = (field: string): boolean => {
const shouldDisableSmsFields =
config.HOOK_SEND_SMS_ENABLED &&
field.startsWith('SMS_') &&
![
'SMS_AUTOCONFIRM',
'SMS_OTP_EXP',
'SMS_OTP_LENGTH',
'SMS_OTP_LENGTH',
'SMS_TEMPLATE',
'SMS_TEST_OTP',
'SMS_TEST_OTP_VALID_UNTIL',
].includes(field)
return (
['EXTERNAL_SLACK_CLIENT_ID', 'EXTERNAL_SLACK_SECRET'].includes(field) ||
shouldDisableSmsFields
)
}
const hasEntitlementAccess = useHasEntitlementAccess()
const getValuesForProvider = useCallback(
(config: components['schemas']['GoTrueConfigResponse']) => {
const values: { [x: string]: string | boolean } = {}
Object.keys(provider.properties).forEach((key) => {
// This ensures the default value is visibly selected
if (key === 'PASSWORD_REQUIRED_CHARACTERS' && config.PASSWORD_REQUIRED_CHARACTERS === '') {
values[key] = NO_REQUIRED_CHARACTERS
return
}
const isDoubleNegative = doubleNegativeKeys.includes(key)
if (provider.title === 'SAML 2.0') {
const configValue = (config as any)[key]
values[key] = configValue || (provider.properties[key].type === 'boolean' ? false : '')
} else {
if (isDoubleNegative) {
values[key] = !(config as any)[key]
} else {
const configValue = (config as any)[key]
values[key] = configValue
? configValue
: provider.properties[key].type === 'boolean'
? false
: ''
}
}
})
return values
},
[provider]
)
const INITIAL_VALUES = useMemo(() => {
// This check will always be true but let us avoid adding an eslint disable comment on unused memo dependencies
// which could hide real issues in the future.
// Adding the provider in the memo dependencies ensures the INITIAL_VALUES is properly applied
if (!provider) return
return getValuesForProvider(config)
}, [config, getValuesForProvider, provider])
const onSubmit = (values: any) => {
const payload = { ...values }
Object.keys(values).map((x: string) => {
if (doubleNegativeKeys.includes(x)) payload[x] = !values[x]
if (payload[x] === '') payload[x] = null
})
// The backend uses empty string to represent no required characters in the password
if (payload.PASSWORD_REQUIRED_CHARACTERS === NO_REQUIRED_CHARACTERS) {
payload.PASSWORD_REQUIRED_CHARACTERS = ''
}
updateAuthConfig(
{ projectRef: projectRef!, config: payload },
{
onSuccess: (newValues) => {
setOpen(false)
setUrlProvider(null)
form.reset(getValuesForProvider(newValues))
toast.success('Successfully updated settings')
},
}
)
}
// Handle clicking on a provider in the list
const handleProviderClick = () => setUrlProvider(provider.title)
const handleOpenChange = (isOpen: boolean) => {
// Remove provider query param from URL when closed
if (!isOpen) setUrlProvider(null)
}
// Open or close the form based on the query parameter
useEffect(() => {
const isProviderInQuery = urlProvider.toLowerCase() === provider.title.toLowerCase()
setOpen(isProviderInQuery)
}, [urlProvider, provider.title])
const form = useForm({
defaultValues: INITIAL_VALUES,
resolver: zodResolver(provider.validationSchema),
shouldUnregister: false,
})
useEffect(() => {
if (open) {
form.reset(INITIAL_VALUES)
}
}, [open, form, INITIAL_VALUES])
const formId = useId()
return (
<>
<ResourceItem
onClick={handleProviderClick}
media={
<img
src={`${BASE_PATH}/img/icons/${provider.misc.iconKey}${provider.misc.hasLightIcon && !resolvedTheme?.includes('dark') ? '-light' : ''}.svg`}
width={18}
height={18}
alt={`${provider.title} auth icon`}
/>
}
meta={
isActive ? (
<div className="flex items-center gap-1 rounded-full border border-brand-400 bg-brand-200 py-1 px-1 text-xs text-brand">
<span className="rounded-full bg-brand p-0.5 text-xs text-brand-200">
<Check strokeWidth={2} size={12} />
</span>
<span className="px-1">Enabled</span>
</div>
) : (
<div className="rounded-md border border-strong bg-surface-100 py-1 px-3 text-xs text-foreground-lighter">
Disabled
</div>
)
}
>
{provider.title}
</ResourceItem>
<Sheet open={open} onOpenChange={handleOpenChange}>
<SheetContent className="flex flex-col gap-0" size="lg">
<SheetHeader className="shrink-0 flex items-center gap-4">
<img
src={`${BASE_PATH}/img/icons/${provider.misc.iconKey}${provider.misc.hasLightIcon && !resolvedTheme?.includes('dark') ? '-light' : ''}.svg`}
width={18}
height={18}
alt={`${provider.title} auth icon`}
/>
<SheetTitle>{provider.title}</SheetTitle>
</SheetHeader>
<Form {...form}>
<form
id={formId}
name={formId}
className="overflow-y-auto grow px-0"
onSubmit={form.handleSubmit(onSubmit)}
>
<AuthAlert
title={provider.title}
isHookSendSMSEnabled={config.HOOK_SEND_SMS_ENABLED}
/>
{Object.keys(provider.properties).map((x: string) => {
const { entitlementKey } = provider.properties[x]
const hasAccess = entitlementKey == null || hasEntitlementAccess(entitlementKey)
return (
<FormField
key={x}
projectRef={projectRef}
organizationSlug={organization?.slug}
name={x}
properties={provider.properties[x]}
control={form.control}
readOnly={shouldDisableField(x) || !canUpdateConfig}
hasAccess={hasAccess}
/>
)
})}
{provider?.misc?.alert && (
<SheetSection>
<Admonition
type="warning"
title={provider.misc.alert.title}
description={<ReactMarkdown>{provider.misc.alert.description}</ReactMarkdown>}
/>
</SheetSection>
)}
{provider.misc.requiresRedirect && (
<SheetSection>
<FormItemLayout
layout="horizontal"
label="Callback URL (for OAuth)"
description={
<Markdown
content={provider.misc.helper}
className="text-foreground-lighter"
/>
}
>
<Input copy readOnly value={endpoint ? `${endpoint}/auth/v1/callback` : ''} />
</FormItemLayout>
</SheetSection>
)}
</form>
</Form>
<SheetFooter className="shrink-0">
<div className="flex items-center justify-between w-full">
<DocsButton href={provider.link} />
<div className="flex items-center gap-x-3">
<Button
variant="default"
type="reset"
onClick={() => {
setOpen(false)
setUrlProvider(null)
form.reset()
}}
disabled={isUpdatingConfig}
>
Cancel
</Button>
<ButtonTooltip
form={formId}
type="submit"
loading={isUpdatingConfig}
disabled={isUpdatingConfig || !canUpdateConfig || !form.formState.isDirty}
tooltip={{
content: {
side: 'bottom',
text: !canUpdateConfig
? 'You need additional permissions to update provider settings'
: undefined,
},
}}
>
Save
</ButtonTooltip>
</div>
</div>
</SheetFooter>
</SheetContent>
</Sheet>
</>
)
}