Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(feedback): generate image urls on backend (#39559)

Charis1b8c8b7398f2
diff --git a/apps/studio/components/interfaces/Organization/ProjectClaim/layout.tsx b/apps/studio/components/interfaces/Organization/ProjectClaim/layout.tsx
index a0157648749..51856178540 100644
--- a/apps/studio/components/interfaces/Organization/ProjectClaim/layout.tsx
+++ b/apps/studio/components/interfaces/Organization/ProjectClaim/layout.tsx
@@ -2,7 +2,7 @@ import Image from 'next/image'
import { PropsWithChildren, ReactNode } from 'react'
import { UserDropdown } from 'components/interfaces/UserDropdown'
-import { FeedbackDropdown } from 'components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown'
+import { FeedbackDropdown } from 'components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown'
import { BASE_PATH } from 'lib/constants'
import { cn, Separator } from 'ui'
diff --git a/apps/studio/components/interfaces/Support/AttachmentUpload.tsx b/apps/studio/components/interfaces/Support/AttachmentUpload.tsx
index d875d3ee46c..36cd6ea6d41 100644
--- a/apps/studio/components/interfaces/Support/AttachmentUpload.tsx
+++ b/apps/studio/components/interfaces/Support/AttachmentUpload.tsx
@@ -21,8 +21,6 @@ import { createSupportStorageClient } from './support-storage-client'
const MAX_ATTACHMENTS = 5
const uploadAttachments = async ({ userId, files }: { userId: string; files: File[] }) => {
- if (files.length === 0) return []
-
const supportSupabaseClient = createSupportStorageClient()
const filesToUpload = Array.from(files)
@@ -104,11 +102,13 @@ export function useAttachmentUpload() {
return []
}
+ if (uploadedFiles.length === 0) return
+
const filenames = await uploadAttachments({ userId: profile.gotrue_id, files: uploadedFiles })
- const urls = await generateAttachmentURLs({ filenames })
+ const urls = await generateAttachmentURLs({ bucket: 'support-attachments', filenames })
return urls
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [uploadedFiles])
+ }, [profile, uploadedFiles])
return useMemo(
() => ({
diff --git a/apps/studio/components/interfaces/Support/SupportForm.utils.tsx b/apps/studio/components/interfaces/Support/SupportForm.utils.tsx
index f22daad621d..e33793c126d 100644
--- a/apps/studio/components/interfaces/Support/SupportForm.utils.tsx
+++ b/apps/studio/components/interfaces/Support/SupportForm.utils.tsx
@@ -24,12 +24,12 @@ export const NO_ORG_MARKER = 'no-org'
export const formatMessage = ({
message,
- attachments,
+ attachments = [],
error,
commit,
}: {
message: string
- attachments: string[]
+ attachments?: string[]
error: string | null | undefined
commit: string | undefined
}) => {
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.tsx
index 3602fb585b9..54e30a670a7 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.tsx
@@ -5,10 +5,8 @@ import { useState } from 'react'
import { Button, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Popover_Shadcn_ } from 'ui'
import { FeedbackWidget } from './FeedbackWidget'
-const FeedbackDropdown = ({ className }: { className?: string }) => {
+export const FeedbackDropdown = ({ className }: { className?: string }) => {
const [isOpen, setIsOpen] = useState(false)
- const [feedback, setFeedback] = useState('')
- const [screenshot, setScreenshot] = useState<string>()
const [stage, setStage] = useState<'select' | 'widget'>('select')
return (
@@ -17,7 +15,6 @@ const FeedbackDropdown = ({ className }: { className?: string }) => {
open={isOpen}
onOpenChange={(e) => {
setIsOpen(e)
- if (!e) setScreenshot(undefined)
if (!e) setStage('select')
}}
>
@@ -63,15 +60,7 @@ const FeedbackDropdown = ({ className }: { className?: string }) => {
</div>
</div>
)}
- {stage === 'widget' && (
- <FeedbackWidget
- onClose={() => setIsOpen(false)}
- feedback={feedback}
- setFeedback={setFeedback}
- screenshot={screenshot}
- setScreenshot={setScreenshot}
- />
- )}
+ {stage === 'widget' && <FeedbackWidget onClose={() => setIsOpen(false)} />}
</PopoverContent_Shadcn_>
</Popover_Shadcn_>
)
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.utils.ts b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.utils.ts
index 2cabae9c7bc..497c8cca550 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.utils.ts
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackDropdown.utils.ts
@@ -1,9 +1,7 @@
-import { createClient } from '@supabase/supabase-js'
+import { createSupportStorageClient } from 'components/interfaces/Support/support-storage-client'
+import { generateAttachmentURLs } from 'data/support/generate-attachment-urls-mutation'
import { uuidv4 } from 'lib/helpers'
-const SUPPORT_API_URL = process.env.NEXT_PUBLIC_SUPPORT_API_URL || ''
-const SUPPORT_API_KEY = process.env.NEXT_PUBLIC_SUPPORT_ANON_KEY || ''
-
export const convertB64toBlob = (image: string) => {
const contentType = 'image/png'
const byteCharacters = atob(image.substr(`data:${contentType};base64,`.length))
@@ -25,40 +23,37 @@ export const convertB64toBlob = (image: string) => {
return blob
}
-export const uploadAttachment = async (ref: string, image: string) => {
- const supabaseClient = createClient(SUPPORT_API_URL, SUPPORT_API_KEY, {
- auth: {
- persistSession: false,
- autoRefreshToken: false,
- // @ts-ignore
- multiTab: false,
- detectSessionInUrl: false,
- localStorage: {
- getItem: (key: string) => undefined,
- setItem: (key: string, value: string) => {},
- removeItem: (key: string) => {},
- },
- },
- })
+type UploadAttachmentArgs = {
+ image: string
+ userId?: string
+}
+
+export const uploadAttachment = async ({ image, userId }: UploadAttachmentArgs) => {
+ if (!userId) {
+ console.error(
+ '[FeedbackWidget > uploadAttachment] Unable to upload screenshot, missing user ID'
+ )
+ return undefined
+ }
+
+ const supabaseClient = createSupportStorageClient()
const blob = convertB64toBlob(image)
- const name = `${ref || 'no-project'}/${uuidv4()}.png`
+ const filename = `${userId}/${uuidv4()}.png`
const options = { cacheControl: '3600' }
+
const { data: file, error: uploadError } = await supabaseClient.storage
.from('feedback-attachments')
- .upload(name, blob, options)
+ .upload(filename, blob, options)
- if (uploadError) {
- console.error('Failed to upload:', uploadError)
+ if (uploadError || !file) {
+ console.error('Failed to upload screenshot attachment:', uploadError)
return undefined
}
- if (file) {
- const { data } = await supabaseClient.storage
- .from('feedback-attachments')
- .createSignedUrls([file.path], 10 * 365 * 24 * 60 * 60)
- return data?.[0].signedUrl
- }
-
- return undefined
+ const signedUrls = await generateAttachmentURLs({
+ bucket: 'feedback-attachments',
+ filenames: [file.path],
+ })
+ return signedUrls[0]
}
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackWidget.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackWidget.tsx
index 8ad7b313a3e..8d11bf84f55 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackWidget.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/FeedbackWidget.tsx
@@ -1,3 +1,4 @@
+import { useDebounce } from '@uidotdev/usehooks'
import { AnimatePresence, motion } from 'framer-motion'
import { toPng } from 'html-to-image'
import { Camera, CircleCheck, Image as ImageIcon, Upload, X } from 'lucide-react'
@@ -5,16 +6,17 @@ import Link from 'next/link'
import { useRouter } from 'next/router'
import { ChangeEvent, useEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
-import { useDebounce } from 'use-debounce'
-import { useParams } from 'common'
+import { LOCAL_STORAGE_KEYS, useParams } from 'common'
import { InlineLink } from 'components/ui/InlineLink'
import { useFeedbackCategoryQuery } from 'data/feedback/feedback-category'
import { useSendFeedbackMutation } from 'data/feedback/feedback-send'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
+import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { DOCS_URL } from 'lib/constants'
import { timeout } from 'lib/helpers'
+import { useProfile } from 'lib/profile'
import {
Button,
DropdownMenu,
@@ -29,47 +31,40 @@ import { Admonition } from 'ui-patterns'
import { convertB64toBlob, uploadAttachment } from './FeedbackDropdown.utils'
interface FeedbackWidgetProps {
- feedback: string
- screenshot: string | undefined
onClose: () => void
- setFeedback: (value: string) => void
- setScreenshot: (value: string | undefined) => void
}
-export const FeedbackWidget = ({
- feedback,
- screenshot,
- onClose,
- setFeedback,
- setScreenshot,
-}: FeedbackWidgetProps) => {
- const FEEDBACK_STORAGE_KEY = 'feedback_content'
- const SCREENSHOT_STORAGE_KEY = 'screenshot'
-
+export const FeedbackWidget = ({ onClose }: FeedbackWidgetProps) => {
const router = useRouter()
+ const { profile } = useProfile()
const { ref, slug } = useParams()
const { data: org } = useSelectedOrganizationQuery()
- const uploadButtonRef = useRef(null)
+ const uploadButtonRef = useRef(null)
+ const [feedback, setFeedback] = useState('')
const [isSending, setSending] = useState(false)
const [isSavingScreenshot, setIsSavingScreenshot] = useState(false)
const [isFeedbackSent, setIsFeedbackSent] = useState(false)
- const [debouncedFeedback] = useDebounce(feedback, 450)
- const { data: category } = useFeedbackCategoryQuery({
- prompt: debouncedFeedback,
- })
+ const debouncedFeedback = useDebounce(feedback, 500)
- const { mutate: sendEvent } = useSendEventMutation()
+ const [storedFeedback, setStoredFeedback] = useLocalStorageQuery<string | null>(
+ LOCAL_STORAGE_KEYS.FEEDBACK_WIDGET_CONTENT,
+ null
+ )
+ const [screenshot, setScreenshot, { isSuccess }] = useLocalStorageQuery<string | null>(
+ LOCAL_STORAGE_KEYS.FEEDBACK_WIDGET_SCREENSHOT,
+ null
+ )
+ const { data: category } = useFeedbackCategoryQuery({ prompt: debouncedFeedback })
+
+ const { mutate: sendEvent } = useSendEventMutation()
const { mutate: submitFeedback } = useSendFeedbackMutation({
onSuccess: () => {
setIsFeedbackSent(true)
setFeedback('')
- setScreenshot(undefined)
- localStorage.removeItem(FEEDBACK_STORAGE_KEY)
- localStorage.removeItem(SCREENSHOT_STORAGE_KEY)
-
+ setScreenshot(null)
setSending(false)
},
onError: (error) => {
@@ -78,28 +73,6 @@ export const FeedbackWidget = ({
},
})
- useEffect(() => {
- const storedFeedback = localStorage.getItem(FEEDBACK_STORAGE_KEY)
- if (storedFeedback) {
- setFeedback(storedFeedback)
- }
-
- const storedScreenshot = localStorage.getItem(SCREENSHOT_STORAGE_KEY)
- if (storedScreenshot) {
- setScreenshot(storedScreenshot)
- }
- }, [])
-
- useEffect(() => {
- localStorage.setItem(FEEDBACK_STORAGE_KEY, feedback)
- }, [feedback])
-
- useEffect(() => {
- if (screenshot) {
- localStorage.setItem(SCREENSHOT_STORAGE_KEY, screenshot)
- }
- }, [screenshot])
-
const captureScreenshot = async () => {
setIsSavingScreenshot(true)
@@ -113,14 +86,9 @@ export const FeedbackWidget = ({
// Give time for dropdown to close
await timeout(100)
toPng(document.body, { filter })
- .then((dataUrl: any) => {
- localStorage.setItem(SCREENSHOT_STORAGE_KEY, dataUrl)
- setScreenshot(dataUrl)
- })
+ .then((dataUrl: any) => setScreenshot(dataUrl))
.catch(() => toast.error('Failed to capture screenshot'))
- .finally(() => {
- setIsSavingScreenshot(false)
- })
+ .finally(() => setIsSavingScreenshot(false))
}
const onFilesUpload = async (event: ChangeEvent<HTMLInputElement>) => {
@@ -130,10 +98,7 @@ export const FeedbackWidget = ({
const reader = new FileReader()
reader.onload = function (event) {
const dataUrl = event.target?.result
- if (typeof dataUrl === 'string') {
- setScreenshot(dataUrl)
- localStorage.setItem(SCREENSHOT_STORAGE_KEY, dataUrl)
- }
+ if (typeof dataUrl === 'string') setScreenshot(dataUrl)
}
reader.readAsDataURL(file)
event.target.value = ''
@@ -148,10 +113,7 @@ export const FeedbackWidget = ({
const reader = new FileReader()
reader.onload = function (event) {
const dataUrl = event.target?.result
- if (typeof dataUrl === 'string') {
- setScreenshot(dataUrl)
- localStorage.setItem(SCREENSHOT_STORAGE_KEY, dataUrl)
- }
+ if (typeof dataUrl === 'string') setScreenshot(dataUrl)
}
reader.readAsDataURL(blob)
}
@@ -163,9 +125,13 @@ export const FeedbackWidget = ({
} else if (feedback.length > 0) {
setSending(true)
- const attachmentUrl = screenshot
- ? await uploadAttachment(ref as string, screenshot)
- : undefined
+ const attachmentUrl =
+ screenshot && profile?.gotrue_id
+ ? await uploadAttachment({
+ image: screenshot,
+ userId: profile.gotrue_id,
+ })
+ : undefined
const formattedFeedback =
attachmentUrl !== undefined ? `${feedback}\n\nAttachments:\n${attachmentUrl}` : feedback
@@ -178,6 +144,15 @@ export const FeedbackWidget = ({
}
}
+ useEffect(() => {
+ if (storedFeedback) setFeedback(storedFeedback)
+ if (screenshot) setScreenshot(screenshot)
+ }, [isSuccess])
+
+ useEffect(() => {
+ if (debouncedFeedback.length > 0) setStoredFeedback(debouncedFeedback)
+ }, [debouncedFeedback])
+
return isFeedbackSent ? (
<ThanksMessage onClose={onClose} />
) : (
@@ -246,7 +221,7 @@ export const FeedbackWidget = ({
</p>
</div>
<div className="flex items-center gap-2 flex-row">
- {screenshot !== undefined ? (
+ {!!screenshot ? (
<div
style={{ backgroundImage: `url("${screenshot}")` }}
onClick={() => {
@@ -254,7 +229,7 @@ export const FeedbackWidget = ({
const blobUrl = URL.createObjectURL(blob)
window.open(blobUrl, '_blank')
}}
- className="cursor-pointer rounded h-[26px] w-[30px] border border-control relative bg-cover bg-center bg-no-repeat"
+ className="cursor-pointer rounded h-[26px] w-[26px] border border-control relative bg-cover bg-center bg-no-repeat"
>
<button
className={[
@@ -263,7 +238,7 @@ export const FeedbackWidget = ({
].join(' ')}
onClick={(event) => {
event.stopPropagation()
- setScreenshot(undefined)
+ setScreenshot(null)
}}
>
<X size={8} strokeWidth={3} />
@@ -276,10 +251,9 @@ export const FeedbackWidget = ({
type="default"
disabled={isSavingScreenshot}
loading={isSavingScreenshot}
- className="px-2"
- >
- <ImageIcon size={14} />
- </Button>
+ className="w-7"
+ icon={<ImageIcon size={14} />}
+ />
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="end" className="w-fit">
<DropdownMenuItem
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/index.ts b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/index.ts
deleted file mode 100644
index 5b5e5bc0e4d..00000000000
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/FeedbackDropdown/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { default as FeedbackDropdown } from './FeedbackDropdown'
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
index 1b8f39e782c..004c7343fc5 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
@@ -24,7 +24,7 @@ import { useRouter } from 'next/router'
import { useAppStateSnapshot } from 'state/app-state'
import { Badge, cn } from 'ui'
import { BreadcrumbsView } from './BreadcrumbsView'
-import { FeedbackDropdown } from './FeedbackDropdown'
+import { FeedbackDropdown } from './FeedbackDropdown/FeedbackDropdown'
import { HelpPopover } from './HelpPopover'
import { HomeIcon } from './HomeIcon'
import { LocalVersionPopover } from './LocalVersionPopover'
diff --git a/apps/studio/data/support/generate-attachment-urls-mutation.ts b/apps/studio/data/support/generate-attachment-urls-mutation.ts
index e8144fd7be5..cf6cfc4ec99 100644
--- a/apps/studio/data/support/generate-attachment-urls-mutation.ts
+++ b/apps/studio/data/support/generate-attachment-urls-mutation.ts
@@ -12,16 +12,22 @@ export type GenerateAttachmentURLsResponse = {
export type GenerateAttachmentURLsVariables = {
filenames: string[]
+ bucket?: 'support-attachments' | 'feedback-attachments'
}
-export async function generateAttachmentURLs({ filenames }: GenerateAttachmentURLsVariables) {
+export async function generateAttachmentURLs({
+ bucket,
+ filenames,
+}: GenerateAttachmentURLsVariables) {
const headers = await constructHeaders()
+ const body = bucket ? JSON.stringify({ filenames, bucket }) : JSON.stringify({ filenames })
+
try {
const response = await fetch(`${BASE_PATH}/api/generate-attachment-url`, {
method: 'POST',
headers,
- body: JSON.stringify({ filenames }),
+ body,
})
if (!response.ok) {
diff --git a/apps/studio/pages/api/generate-attachment-url.ts b/apps/studio/pages/api/generate-attachment-url.ts
index 371aaecbf3f..87c3b892117 100644
--- a/apps/studio/pages/api/generate-attachment-url.ts
+++ b/apps/studio/pages/api/generate-attachment-url.ts
@@ -9,6 +9,7 @@ export const maxDuration = 120
const GenerateAttachmentUrlSchema = z.object({
filenames: z.array(z.string()),
+ bucket: z.enum(['support-attachments', 'feedback-attachments']).default('support-attachments'),
})
async function handlePost(req: NextApiRequest, res: NextApiResponse) {
@@ -51,9 +52,10 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
}
)
+ const bucket = parseResult.data.bucket
// Create signed URLs for 10 years
const { data, error: signedUrlError } = await adminSupabase.storage
- .from('support-attachments')
+ .from(bucket)
.createSignedUrls(filenames, 10 * 365 * 24 * 60 * 60)
if (signedUrlError) {
console.error('Failed to sign URLs for attachments', signedUrlError)
diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.ts
index c6a13084208..4a3b4673d70 100644
--- a/packages/common/constants/local-storage.ts
+++ b/packages/common/constants/local-storage.ts
@@ -7,6 +7,8 @@ export const LOCAL_STORAGE_KEYS = {
SIDEBAR_BEHAVIOR: 'supabase-sidebar-behavior',
EDITOR_PANEL_STATE: 'supabase-editor-panel-state',
PROJECTS_VIEW: 'projects-view',
+ FEEDBACK_WIDGET_CONTENT: 'feedback-widget-content',
+ FEEDBACK_WIDGET_SCREENSHOT: 'feedback-widget-screenshot',
UI_PREVIEW_API_SIDE_PANEL: 'supabase-ui-api-side-panel',
UI_PREVIEW_CLS: 'supabase-ui-cls',