mirror of
https://github.com/supabase/supabase.git
synced 2026-10-05 09:25:06 +03:00
Refactor NewAccessTokenButton to use shadcn components (#36972)
* chore: Refactor `NewAccessTokenButton` to use shadcn components This brings `NewAccessTokenButton` into conformance with the latest UI patterns of using shadcn based components, zod schemas, and react-hook-form for form submission. I based this refactor on the implementation of `CreateSecretAPIKeyDialog`, which already made use of the above. * add success and failure toasts * add smoke test for `NewAccessTokenButton`, fix vitest config This adds a minimal test for `NewAccessTokenButton` but more importantly fixes a critical bug in the vitest configuration for `studio`. Because `restoreMocks: true` was set in the config, this meant that the mock implementation for `window.matchMedia` defined in the `tests/vitestSetup.ts` file was being **reset** to an empty function before each test suite was run. While this didn't appear to be a problem before, that appears to be because none of the existing tests had `motion.div` in their component trees. Since `motion.div` calls `addListener` on a media query as part of it's lifecycle, that meant that any test which included it would fail as `addListener` would be undefined in this situation. Removing `restoreMocks: true` from the config results in the desired mocking behavior. This change is necessary in order to test any component that has the `FormItemLayout` component, as it uses `framer-motion` to animate in error messages for input elements. * add warning comment in case of future config regression * update test cases, reset form on dialog close, testing setup fixes This fixes an issue with the polyfills for the testing environment, where a call to `useMutation` would fail as a result of `TransformStream` being set to `null`. Basic tests for access token creation and form resetting added. Adds `@faker-js/faker` to the studio app devDependencies to generate mock data for `msw` endpoint response. Adds `shx` to the docs app devDependencies to ensure that the `codegen:examples` script runs cross-platform. * ensure mocked date is a string * update testing setup, pollyfills and add rich type support to addAPIMock * Update studio testing setup files Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components * chore: Refactor `NewAccessTokenButton` to use shadcn components This brings `NewAccessTokenButton` into conformance with the latest UI patterns of using shadcn based components, zod schemas, and react-hook-form for form submission. I based this refactor on the implementation of `CreateSecretAPIKeyDialog`, which already made use of the above. * add success and failure toasts * add smoke test for `NewAccessTokenButton`, fix vitest config This adds a minimal test for `NewAccessTokenButton` but more importantly fixes a critical bug in the vitest configuration for `studio`. Because `restoreMocks: true` was set in the config, this meant that the mock implementation for `window.matchMedia` defined in the `tests/vitestSetup.ts` file was being **reset** to an empty function before each test suite was run. While this didn't appear to be a problem before, that appears to be because none of the existing tests had `motion.div` in their component trees. Since `motion.div` calls `addListener` on a media query as part of it's lifecycle, that meant that any test which included it would fail as `addListener` would be undefined in this situation. Removing `restoreMocks: true` from the config results in the desired mocking behavior. This change is necessary in order to test any component that has the `FormItemLayout` component, as it uses `framer-motion` to animate in error messages for input elements. * update test cases, reset form on dialog close, testing setup fixes This fixes an issue with the polyfills for the testing environment, where a call to `useMutation` would fail as a result of `TransformStream` being set to `null`. Basic tests for access token creation and form resetting added. Adds `@faker-js/faker` to the studio app devDependencies to generate mock data for `msw` endpoint response. Adds `shx` to the docs app devDependencies to ensure that the `codegen:examples` script runs cross-platform. * ensure mocked date is a string * update testing setup, pollyfills and add rich type support to addAPIMock * fix imports * fix missing listen call for msw, resolve test type error * fix imports * Update studio testing setup files Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components * fix missing listen call for msw, resolve test type error * fix imports * Shift test file * Smol fix * Nit --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
This commit is contained in:
1 parent
2bec311971
commit
af5e591b84
6 files changed
+377
-126
No files matched your search
@@ -9,7 +9,7 @@
|
||||
"build:llms": "tsx ./scripts/llms.ts",
|
||||
"build:sitemap": "tsx ./internals/generate-sitemap.ts",
|
||||
"clean": "rimraf .next .turbo node_modules features/docs/generated examples __generated__",
|
||||
"codegen:examples": "cp -r ../../examples ./examples",
|
||||
"codegen:examples": "shx cp -r ../../examples ./examples",
|
||||
"codegen:graphql": "tsx --conditions=react-server ./scripts/graphqlSchema.ts && graphql-codegen --config codegen.ts",
|
||||
"codegen:references": "tsx features/docs/Reference.generated.script.ts",
|
||||
"codemod:frontmatter": "node ./scripts/codemod/mdx-meta.mjs && prettier --cache --write \"content/**/*.mdx\"",
|
||||
@@ -149,6 +149,7 @@
|
||||
"openapi-types": "^12.1.3",
|
||||
"postcss": "^8.5.3",
|
||||
"shiki": "^3.2.1",
|
||||
"shx": "^0.4.0",
|
||||
"simple-git": "^3.24.0",
|
||||
"slugify": "^1.6.6",
|
||||
"smol-toml": "^1.3.1",
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { faker } from '@faker-js/faker'
|
||||
import { screen, waitFor } from '@testing-library/dom'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { render } from 'tests/helpers'
|
||||
import { addAPIMock } from 'tests/lib/msw'
|
||||
import NewAccessTokenButton from './NewAccessTokenButton'
|
||||
|
||||
describe(`NewAccessTokenButton`, () => {
|
||||
beforeEach(() => {
|
||||
addAPIMock({
|
||||
method: `post`,
|
||||
path: `/platform/profile/access-tokens`,
|
||||
response: {
|
||||
name: faker.lorem.word(),
|
||||
scope: faker.helpers.arrayElement(['V0', undefined]),
|
||||
created_at: faker.date.past().toISOString(),
|
||||
id: faker.number.int(),
|
||||
token_alias: faker.lorem.words(),
|
||||
token: faker.lorem.words(),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it(`generates regular tokens`, async () => {
|
||||
const onCreateToken = vi.fn()
|
||||
render(<NewAccessTokenButton onCreateToken={onCreateToken} />)
|
||||
|
||||
const dialogTrigger = screen.getByRole(`button`, { name: `Generate new token` })
|
||||
await userEvent.click(dialogTrigger)
|
||||
|
||||
const nameInput = screen.getByLabelText(`Name`)
|
||||
await userEvent.type(nameInput, `test{enter}`)
|
||||
|
||||
await waitFor(() => expect(onCreateToken).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it(`generates experimental tokens`, async () => {
|
||||
const onCreateToken = vi.fn()
|
||||
render(<NewAccessTokenButton onCreateToken={onCreateToken} />)
|
||||
|
||||
const dropdownTrigger = screen.getByTitle(`Choose token scope`)
|
||||
await userEvent.click(dropdownTrigger)
|
||||
|
||||
const experimentalMenuItem = await screen.findByRole(`menuitem`, {
|
||||
name: `Generate token for experimental API`,
|
||||
})
|
||||
await userEvent.click(experimentalMenuItem)
|
||||
|
||||
await waitFor(async () => {
|
||||
await expect(
|
||||
screen.findByRole(`heading`, { name: `Generate token for experimental API` })
|
||||
).resolves.toBeInTheDocument()
|
||||
await expect(screen.findByRole(`alert`)).resolves.toBeInTheDocument()
|
||||
})
|
||||
|
||||
const nameInput = screen.getByLabelText(`Name`)
|
||||
await userEvent.type(nameInput, `test{enter}`)
|
||||
|
||||
await waitFor(() => expect(onCreateToken).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it(`resets the form on close/cancel`, async () => {
|
||||
render(<NewAccessTokenButton onCreateToken={vi.fn()} />)
|
||||
|
||||
// pass 1: open dialog and fill form
|
||||
const dialogTrigger = screen.getByRole(`button`, { name: `Generate new token` })
|
||||
await userEvent.click(dialogTrigger)
|
||||
|
||||
let nameInput = screen.getByLabelText(`Name`)
|
||||
await userEvent.type(nameInput, `cancel button test`)
|
||||
expect(nameInput).toHaveValue(`cancel button test`)
|
||||
|
||||
// reset the form by pressing the cancel button
|
||||
const cancelButton = screen.getByRole(`button`, { name: `Cancel` })
|
||||
await userEvent.click(cancelButton)
|
||||
|
||||
// pass 2: check that the form is reset, then fill it again
|
||||
await userEvent.click(dialogTrigger)
|
||||
|
||||
nameInput = screen.getByLabelText(`Name`)
|
||||
expect(nameInput).not.toHaveValue(`cancel button test`)
|
||||
|
||||
await userEvent.type(nameInput, `close modal test`)
|
||||
expect(nameInput).toHaveValue(`close modal test`)
|
||||
|
||||
// reset the form by closing the dialog
|
||||
await userEvent.keyboard(`{Escape}`)
|
||||
|
||||
// pass 3: check that the form has been rest again
|
||||
await userEvent.click(dialogTrigger)
|
||||
|
||||
nameInput = screen.getByLabelText(`Name`)
|
||||
expect(nameInput).not.toHaveValue(`close modal test`)
|
||||
})
|
||||
})
|
||||
@@ -1,157 +1,187 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { ChevronDown, ExternalLink } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import { type SubmitHandler, useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { useAccessTokenCreateMutation } from 'data/access-tokens/access-tokens-create-mutation'
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogSection,
|
||||
DialogSectionSeparator,
|
||||
DialogTitle,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Form_Shadcn_,
|
||||
FormControl_Shadcn_,
|
||||
FormField_Shadcn_,
|
||||
Input_Shadcn_,
|
||||
} from 'ui'
|
||||
import { Admonition } from 'ui-patterns'
|
||||
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
|
||||
|
||||
export interface NewAccessTokenButtonProps {
|
||||
onCreateToken: (token: any) => void
|
||||
}
|
||||
|
||||
const TokenSchema = z.object({
|
||||
tokenName: z.string().min(1, 'Please enter a name for the token'),
|
||||
})
|
||||
|
||||
const formId = 'new-access-token-form'
|
||||
|
||||
const NewAccessTokenButton = ({ onCreateToken }: NewAccessTokenButtonProps) => {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [visible, setVisible] = useState(false)
|
||||
const [tokenScope, setTokenScope] = useState<'V0' | undefined>(undefined)
|
||||
|
||||
const validate = (values: any) => {
|
||||
const errors: any = {}
|
||||
if (!values.tokenName) errors.tokenName = 'Please enter a name for the token'
|
||||
return errors
|
||||
}
|
||||
|
||||
const { mutate: createAccessToken, isLoading } = useAccessTokenCreateMutation({
|
||||
onSuccess: (res) => {
|
||||
onCreateToken(res)
|
||||
setIsOpen(false)
|
||||
},
|
||||
const form = useForm<z.infer<typeof TokenSchema>>({
|
||||
resolver: zodResolver(TokenSchema),
|
||||
defaultValues: { tokenName: '' },
|
||||
mode: 'onSubmit',
|
||||
})
|
||||
const { mutate: createAccessToken, isLoading } = useAccessTokenCreateMutation()
|
||||
|
||||
const onFormSubmit = async (values: any) => {
|
||||
createAccessToken({ name: values.tokenName, scope: tokenScope })
|
||||
const onSubmit: SubmitHandler<z.infer<typeof TokenSchema>> = async (values) => {
|
||||
createAccessToken(
|
||||
{ name: values.tokenName, scope: tokenScope },
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
toast.success(`Your access token "${data.name}" is ready.`)
|
||||
form.reset()
|
||||
onCreateToken(data)
|
||||
setVisible(false)
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="container max-w-7xl">
|
||||
<div className="flex justify-between">
|
||||
<div className="flex items-center">
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
className="rounded-r-none px-3"
|
||||
onClick={() => {
|
||||
setTokenScope(undefined)
|
||||
setVisible(true)
|
||||
}}
|
||||
>
|
||||
Generate new token
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
className="rounded-r-none px-3"
|
||||
type="primary"
|
||||
title="Choose token scope"
|
||||
className="rounded-l-none px-[4px] py-[5px]"
|
||||
icon={<ChevronDown />}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" side="bottom">
|
||||
<DropdownMenuItem
|
||||
key="experimental-token"
|
||||
onClick={() => {
|
||||
setTokenScope(undefined)
|
||||
setIsOpen(true)
|
||||
setTokenScope('V0')
|
||||
setVisible(true)
|
||||
}}
|
||||
>
|
||||
Generate new token
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="primary"
|
||||
className="rounded-l-none px-[4px] py-[5px]"
|
||||
icon={<ChevronDown />}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" side="bottom">
|
||||
<DropdownMenuItem
|
||||
key="experimental-token"
|
||||
onClick={() => {
|
||||
setTokenScope('V0')
|
||||
setIsOpen(true)
|
||||
}}
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<p className="block text-foreground">Generate token for experimental API</p>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="block text-foreground">Generate token for experimental API</p>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
hideFooter
|
||||
size="small"
|
||||
visible={isOpen}
|
||||
onCancel={() => setIsOpen(!isOpen)}
|
||||
header={
|
||||
<div className="flex items-baseline gap-2">
|
||||
<h5 className="text-sm text-foreground">
|
||||
{tokenScope === 'V0' ? 'Generate token for experimental API' : 'Generate New Token'}
|
||||
</h5>
|
||||
</div>
|
||||
}
|
||||
<Dialog
|
||||
open={visible}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) form.reset()
|
||||
setVisible(open)
|
||||
}}
|
||||
>
|
||||
<Form
|
||||
validateOnBlur
|
||||
initialValues={{ tokenName: '' }}
|
||||
onSubmit={onFormSubmit}
|
||||
validate={validate}
|
||||
>
|
||||
{() => (
|
||||
<>
|
||||
{tokenScope === 'V0' && (
|
||||
<Modal.Content>
|
||||
<Admonition
|
||||
type="warning"
|
||||
title="The experimental API provides additional endpoints which allows you to manage
|
||||
your organizations and projects."
|
||||
description={
|
||||
<>
|
||||
<p>
|
||||
These include deleting organizations and projects which cannot be undone.
|
||||
As such, be very careful when using this API.
|
||||
</p>
|
||||
<div className="mt-4">
|
||||
<Button asChild type="default" icon={<ExternalLink />}>
|
||||
<Link
|
||||
href="https://api.supabase.com/api/v0"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Experimental API documentation
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Modal.Content>
|
||||
)}
|
||||
<Modal.Content>
|
||||
<Input
|
||||
id="tokenName"
|
||||
label="Name"
|
||||
placeholder="Provide a name for your token"
|
||||
className="w-full"
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{tokenScope === 'V0' ? 'Generate token for experimental API' : 'Generate New Token'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogSectionSeparator />
|
||||
<DialogSection className="flex flex-col gap-4">
|
||||
{tokenScope === 'V0' && (
|
||||
<Admonition
|
||||
type="warning"
|
||||
title="The experimental API provides additional endpoints which allows you to manage your organizations and projects."
|
||||
description={
|
||||
<>
|
||||
<p>
|
||||
These include deleting organizations and projects which cannot be undone. As
|
||||
such, be very careful when using this API.
|
||||
</p>
|
||||
<div className="mt-4">
|
||||
<Button asChild type="default" icon={<ExternalLink />}>
|
||||
<Link
|
||||
href="https://api.supabase.com/api/v0"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Experimental API documentation
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<Form_Shadcn_ {...form}>
|
||||
<form
|
||||
id={formId}
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
>
|
||||
<FormField_Shadcn_
|
||||
key="tokenName"
|
||||
name="tokenName"
|
||||
control={form.control}
|
||||
render={({ field }) => (
|
||||
<FormItemLayout name="tokenName" label="Name">
|
||||
<FormControl_Shadcn_>
|
||||
<Input_Shadcn_
|
||||
id="tokenName"
|
||||
{...field}
|
||||
placeholder="Provide a name for your token"
|
||||
/>
|
||||
</FormControl_Shadcn_>
|
||||
</FormItemLayout>
|
||||
)}
|
||||
/>
|
||||
</Modal.Content>
|
||||
<DialogFooter>
|
||||
<div className="flex items-center space-x-2 justify-end">
|
||||
<Button type="default" disabled={isLoading} onClick={() => setIsOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button htmlType="submit" loading={isLoading} disabled={isLoading}>
|
||||
Generate token
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
</Modal>
|
||||
</form>
|
||||
</Form_Shadcn_>
|
||||
</DialogSection>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="default"
|
||||
disabled={isLoading}
|
||||
onClick={() => {
|
||||
form.reset()
|
||||
setVisible(false)
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button form={formId} htmlType="submit" loading={isLoading}>
|
||||
Generate token
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@
|
||||
"zxcvbn": "^4.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@faker-js/faker": "^9.9.0",
|
||||
"@graphql-codegen/cli": "5.0.5",
|
||||
"@graphql-typed-document-node/core": "^3.2.0",
|
||||
"@radix-ui/react-use-escape-keydown": "^1.0.3",
|
||||
|
||||
@@ -40,10 +40,11 @@ beforeAll(() => {
|
||||
routerMock.useParser(createDynamicRouteParser(['/projects/[ref]']))
|
||||
})
|
||||
|
||||
afterAll(() => mswServer.close())
|
||||
|
||||
afterEach(() => mswServer.resetHandlers())
|
||||
|
||||
afterEach(() => {
|
||||
mswServer.resetHandlers()
|
||||
cleanup()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
mswServer.close()
|
||||
})
|
||||
Reference in new issue
Block a user