Files
supabase/apps/studio/components/interfaces/SQLEditor/RenameQueryModal.tsx
T
df52ea7ee0 feat: Replace all toasts with sonner (#28250)
* Update the design of the sonner toasts. Add the close button by default.

* Migrate studio and www apps to use the SonnerToaster.

* Migrate all toasts from studio.

* Migrate all leftover toasts in studio.

* Add a new toast component with progress. Use it in studio.

* Migrate the design-system app.

* Refactor the consent toast to use sonner.

* Switch docs to use the new sonner toasts.

* Remove toast examples from the design-system app.

* Remove all toast-related components and old code.

* Fix the progress bar in the toast progress component. Also make the bottom components vertically centered.

* Fix the width of the toast progress.

* Use text-foreground-lighter instead of muted for ToastProgress text

* Rename ToastProgress to SonnerProgress.

* Shorten the text in sonner progress.

* Use the correct classes for the close button. Add a const var for the default toast duration. Remove the custom width class from sonner.

* Set the position for all progress toasts to bottom right. Set the duration for all toasts to the default (when reusing a toast id from loading/progress toast, the duration is set to infinity).

* Fix the playwright tests.

* Refactor imports to use ui instead of @ui.

* Change all imports of react-hot-toast with sonner. These components were merged since the last commit to this branch.

* Remove react-hot-toast lib.

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Jonathan Summers-Muir <MildTomato@users.noreply.github.com>
2024-08-31 07:50:51 +08:00

178 lines
6.2 KiB
TypeScript

import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
import { useSqlTitleGenerateMutation } from 'data/ai/sql-title-mutation'
import { getContentById } from 'data/content/content-id-query'
import { Snippet } from 'data/content/sql-folders-query'
import type { SqlSnippet } from 'data/content/sql-snippets-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useFlag } from 'hooks/ui/useFlag'
import { useSqlEditorStateSnapshot } from 'state/sql-editor'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
import { AiIconAnimation, Button, Form, Input, Modal } from 'ui'
import { subscriptionHasHipaaAddon } from '../Billing/Subscription/Subscription.utils'
export interface RenameQueryModalProps {
snippet?: SqlSnippet | Snippet
visible: boolean
onCancel: () => void
onComplete: () => void
}
const RenameQueryModal = ({
snippet = {} as any,
visible,
onCancel,
onComplete,
}: RenameQueryModalProps) => {
const { ref } = useParams()
const organization = useSelectedOrganization()
const snap = useSqlEditorStateSnapshot()
const snapV2 = useSqlEditorV2StateSnapshot()
const enableFolders = useFlag('sqlFolderOrganization')
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
const isSQLSnippet = snippet.type === 'sql'
// Customers on HIPAA plans should not have access to Supabase AI
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
const { id, name, description } = snippet
const [nameInput, setNameInput] = useState(name)
const [descriptionInput, setDescriptionInput] = useState(description)
const { mutate: titleSql, isLoading: isTitleGenerationLoading } = useSqlTitleGenerateMutation({
onSuccess: (data) => {
const { title, description } = data
setNameInput(title)
if (!descriptionInput) setDescriptionInput(description)
},
onError: (error) => {
toast.error(`Failed to rename query: ${error.message}`)
},
})
const isAiButtonVisible = enableFolders ? true : isSQLSnippet
const generateTitle = async () => {
if (enableFolders) {
if ('content' in snippet && isSQLSnippet) {
titleSql({ sql: snippet.content.sql })
} else {
try {
const { content } = await getContentById({ projectRef: ref, id: snippet.id })
titleSql({ sql: content.sql })
} catch (error) {
toast.error('Unable to generate title based on query contents')
}
}
} else {
if ('content' in snippet && isSQLSnippet) titleSql({ sql: snippet.content.sql })
}
}
const validate = () => {
const errors: any = {}
if (!nameInput) errors.name = 'Please enter a query name'
return errors
}
const onSubmit = async (values: any, { setSubmitting }: any) => {
if (!ref) return console.error('Project ref is required')
if (!id) return console.error('Snippet ID is required')
setSubmitting(true)
try {
if (enableFolders) {
// [Joshen] For SQL V2 - content is loaded on demand so we need to fetch the data if its not already loaded in the valtio state
if (!('content' in snippet)) {
// [Joshen] I feel like there's definitely some optimization we can do here but will involve changes to API
const snippet = await getContentById({ projectRef: ref, id })
snapV2.addSnippet({ projectRef: ref, snippet })
}
snapV2.renameSnippet({ id, name: nameInput, description: descriptionInput })
} else {
snap.renameSnippet(id, nameInput, descriptionInput)
}
if (onComplete) onComplete()
} catch (error: any) {
// [Joshen] We probably need some rollback cause all the saving is async
toast.error(`Failed to rename query: ${error.message}`)
}
}
useEffect(() => {
setNameInput(name)
setDescriptionInput(description)
}, [snippet.id])
return (
<Modal visible={visible} onCancel={onCancel} hideFooter header="Rename" size="small">
<Form
onReset={onCancel}
validateOnBlur
initialValues={{
name: name ?? '',
description: description ?? '',
}}
validate={validate}
onSubmit={onSubmit}
>
{({ isSubmitting }: { isSubmitting: boolean }) => (
<>
<Modal.Content className="space-y-4">
<Input
label="Name"
id="name"
name="name"
value={nameInput}
onChange={(e) => setNameInput(e.target.value)}
/>
<div className="flex w-full justify-end mt-2">
{!hasHipaaAddon && isAiButtonVisible && (
<Button
type="default"
onClick={() => generateTitle()}
size="tiny"
disabled={isTitleGenerationLoading}
>
<div className="flex items-center gap-1">
<div className="scale-75">
<AiIconAnimation loading={isTitleGenerationLoading} />
</div>
<span>Rename with Supabase AI</span>
</div>
</Button>
)}
</div>
<Input.TextArea
label="Description"
id="description"
placeholder="Describe query"
size="medium"
textAreaClassName="resize-none"
value={descriptionInput}
onChange={(e) => setDescriptionInput(e.target.value)}
/>
</Modal.Content>
<Modal.Separator />
<Modal.Content className="flex items-center justify-end gap-2">
<Button htmlType="reset" type="default" onClick={onCancel} disabled={isSubmitting}>
Cancel
</Button>
<Button htmlType="submit" loading={isSubmitting} disabled={isSubmitting}>
Rename query
</Button>
</Modal.Content>
</>
)}
</Form>
</Modal>
)
}
export default RenameQueryModal