mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
Part 3 of a 6-PR stack migrating all `next/router` and `next/compat/router` imports in `apps/studio` onto TanStack Router hooks and removing the router shims. | Part | PR | Scope | | --- | --- | --- | | 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`, `data/prefetchers/**` | | 2 | #54054 | `components/ui/**` | | **3** | **#54055 ← this PR** | **`components/layouts/**` and `state/tabs.tsx`** | | 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer, SQL Editor, Storage, Table Editor | | 5 | #54057 | Remaining `components/interfaces/**` and `QueryInsightsTable` router events | | 6 | #54058 | Remove `next/router` & `next/compat/router` shims, `_router-events.ts`, Vite aliases, and test mocks | Migrates all `apps/studio/components/layouts/**` files and the studio tab router integration off `next/router`. **Added:** - `useTabRouter()` in `apps/studio/state/tabs.tsx` so tab state actions navigate via TanStack's `useNavigate` + `navigateToUrl` instead of taking a `NextRouter` instance **Changed:** - Replaced `useRouter` across all layout directories (`AccountLayout`, `AdvisorsLayout`, `AppLayout`, `AuthLayout`, `BranchLayout`, `ComputeLayout`, `DatabaseLayout`, `DefaultLayout`, `EdgeFunctionsLayout`, `ExplorerLayout`, `LogsLayout`, `Navigation/*`, `ObservabilityLayout`, `OrganizationLayout`, `ProjectLayout`, `ProjectNeedsSecuring`, `ProjectSettingsLayout`, `RealtimeLayout`, `SQLEditorLayout`, `SignInLayout`, and `Tabs`) with TanStack Router hooks (`useNavigate`, `useLocation`, `useRoutePattern`) and `useParams` from `common` - Updated `ProjectDropdown.utils.ts` and `ProjectDropdown.test.ts` to work with TanStack `$param` route templates - Updated layout component tests (`AccountLayout.selfhosted.test.tsx`, `AdvisorsNavigationShortcuts.test.tsx`, `BranchLink.test.tsx`, `ExplorerLayout.test.tsx`, `ExplorerNavChats.test.tsx`, `ObservabilityMenu.utils.test.tsx`, `MobileIssuesNavigation.platform.test.tsx`, `ProjectLayout/index.test.tsx`, `ProjectNeedsSecuring.test.tsx`, `ProjectDropdown.test.tsx`) **Simplified:** - `OrganizationLayout` and `SettingsLayout` match against `useRoutePattern()` instead of the real pathname. An org slug ending in a settings segment (e.g. `acmeapps`) no longer gets the settings title. - `ProjectSettings.Commands` opens the Connect sheet through nuqs, the same way `Connect.Commands` does - `OrgMenuContent`, `OrganizationSettingsMenu` and `useTabRouter` read `orgSlug`/`schema` from `useParams` instead of casting `location.search` - Removed the dead `getPathnameWithoutQuery` helpers and their tests - `usePreservedQueryParams` builds its string in the `useLocation` selector (no `useMemo`), and `UnhealthyState` only navigates when `ref` is set - Moved `MobileIssuesNavigation.platform.test.tsx` onto a TanStack test router. It now covers the active-route logic again. - Tests use the shared `createTestRouter` and `customRender` router Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Switching projects, organizations, and branches from the top header dropdowns preserves the current sub-route where supported - [ ] Opening, switching, and closing Table Editor / SQL Editor tabs updates the URL and active tab cleanly - [ ] Active sidebar item highlighting works across Database, Auth, Edge Functions, Observability, Logs, Realtime, Explorer, and Project Settings layouts - [ ] Mobile navigation menu and floating toolbar sheets open and navigate properly --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
341 lines
12 KiB
TypeScript
341 lines
12 KiB
TypeScript
import { useLocation } from '@tanstack/react-router'
|
||
import { useDebounce } from '@uidotdev/usehooks'
|
||
import { LOCAL_STORAGE_KEYS, useParams } from 'common'
|
||
import { toPng } from 'html-to-image'
|
||
import { CameraIcon, CircleCheckIcon, ImageIcon, UploadIcon, XIcon } from 'lucide-react'
|
||
import { AnimatePresence, motion } from 'motion/react'
|
||
import { ChangeEvent, useEffect, useRef, useState } from 'react'
|
||
import { toast } from 'sonner'
|
||
import {
|
||
Button,
|
||
cn,
|
||
DropdownMenu,
|
||
DropdownMenuContent,
|
||
DropdownMenuItem,
|
||
DropdownMenuSeparator,
|
||
DropdownMenuTrigger,
|
||
PopoverSeparator,
|
||
TextArea,
|
||
} from 'ui'
|
||
import { Admonition } from 'ui-patterns/Admonition'
|
||
|
||
import {
|
||
convertB64toBlob,
|
||
isLikelySupportRequest,
|
||
uploadAttachment,
|
||
} from './FeedbackDropdown.utils'
|
||
import { SupportLink } from '@/components/interfaces/Support/SupportLink'
|
||
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
|
||
import { InlineLinkClassName } from '@/components/ui/InlineLink'
|
||
import { useFeedbackCategoryQuery } from '@/data/feedback/feedback-category'
|
||
import { useSendFeedbackMutation } from '@/data/feedback/feedback-send'
|
||
import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
|
||
import { timeout } from '@/lib/helpers'
|
||
import { useProfile } from '@/lib/profile'
|
||
import { useTrack } from '@/lib/telemetry/track'
|
||
|
||
interface FeedbackWidgetProps {
|
||
onClose: () => void
|
||
onSwitchToIssueOptions: () => void
|
||
}
|
||
|
||
const ThanksMessageView = ({
|
||
onClose,
|
||
onSwitchToIssueOptions,
|
||
}: Pick<FeedbackWidgetProps, 'onClose' | 'onSwitchToIssueOptions'>) => (
|
||
<>
|
||
<div className="py-6 px-4 grid gap-4 text-center text-foreground-light">
|
||
<CircleCheckIcon className="mx-auto text-brand-500" size={24} />
|
||
<div className="flex flex-col gap-1">
|
||
<p className="text-foreground text-sm">Your feedback has been sent. Thanks!</p>
|
||
<p className="text-xs text-balance">
|
||
We don’t always respond to feedback. If you need help with your project, use the button
|
||
below.
|
||
</p>
|
||
</div>
|
||
</div>
|
||
<PopoverSeparator />
|
||
<div className="px-4 pt-4 pb-4 flex flex-row items-center justify-between">
|
||
<Button size="tiny" onClick={onSwitchToIssueOptions}>
|
||
Get help
|
||
</Button>
|
||
<Button size="tiny" onClick={onClose}>
|
||
Close
|
||
</Button>
|
||
</div>
|
||
</>
|
||
)
|
||
|
||
export const FeedbackWidget = ({ onClose, onSwitchToIssueOptions }: FeedbackWidgetProps) => {
|
||
const href = useLocation({ select: (location) => location.href })
|
||
const { profile } = useProfile()
|
||
const { ref, slug } = useParams()
|
||
const track = useTrack()
|
||
|
||
const uploadButtonRef = useRef<HTMLInputElement>(null)
|
||
const [feedback, setFeedback] = useState('')
|
||
const [isSending, setSending] = useState(false)
|
||
const [isSavingScreenshot, setIsSavingScreenshot] = useState(false)
|
||
const [isFeedbackSent, setIsFeedbackSent] = useState(false)
|
||
|
||
const debouncedFeedback = useDebounce(feedback, 500)
|
||
|
||
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 })
|
||
|
||
// Use client-side heuristic for immediate feedback, AI result takes precedence when available
|
||
const isLikelySupport = isLikelySupportRequest(feedback)
|
||
const effectiveCategory = category ?? (isLikelySupport ? 'support' : null)
|
||
|
||
const { mutate: submitFeedback } = useSendFeedbackMutation({
|
||
onSuccess: () => {
|
||
setIsFeedbackSent(true)
|
||
setFeedback('')
|
||
setStoredFeedback(null)
|
||
setScreenshot(null)
|
||
setSending(false)
|
||
},
|
||
onError: (error) => {
|
||
toast.error(`Failed to submit feedback: ${error.message}`)
|
||
setSending(false)
|
||
},
|
||
})
|
||
|
||
const captureScreenshot = async () => {
|
||
setIsSavingScreenshot(true)
|
||
|
||
function filter(node: HTMLElement) {
|
||
if ((node?.children ?? []).length > 0) {
|
||
return node.children[0].id !== 'feedback-widget'
|
||
}
|
||
return true
|
||
}
|
||
|
||
// Give time for dropdown to close
|
||
await timeout(100)
|
||
toPng(document.body, {
|
||
filter,
|
||
// the csp blocks fetches to avatar hosts, so a transparent pixel replaces images it cannot read
|
||
imagePlaceholder:
|
||
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
|
||
})
|
||
.then((dataUrl) => setScreenshot(dataUrl))
|
||
.catch((error) => {
|
||
console.error('Failed to capture screenshot:', error)
|
||
toast.error('Failed to capture screenshot')
|
||
})
|
||
.finally(() => setIsSavingScreenshot(false))
|
||
}
|
||
|
||
const onFilesUpload = async (event: ChangeEvent<HTMLInputElement>) => {
|
||
event.persist()
|
||
const file = event.target.files?.[0]
|
||
if (file === undefined) return
|
||
|
||
const reader = new FileReader()
|
||
reader.onload = function (event) {
|
||
const dataUrl = event.target?.result
|
||
if (typeof dataUrl === 'string') setScreenshot(dataUrl)
|
||
}
|
||
reader.readAsDataURL(file)
|
||
event.target.value = ''
|
||
}
|
||
|
||
const handlePasteEvent = async () => {
|
||
// [Joshen] Support pasting images via Cmd / Ctrl + V
|
||
const [data] = await navigator.clipboard.read()
|
||
|
||
if (screenshot === undefined && data.types[0] === 'image/png') {
|
||
const blob = await data.getType('image/png')
|
||
const reader = new FileReader()
|
||
reader.onload = function (event) {
|
||
const dataUrl = event.target?.result
|
||
if (typeof dataUrl === 'string') setScreenshot(dataUrl)
|
||
}
|
||
reader.readAsDataURL(blob)
|
||
}
|
||
}
|
||
|
||
const sendFeedback = async () => {
|
||
if (feedback.length === 0 && screenshot !== undefined) {
|
||
return toast.error('Please include a message in your feedback.')
|
||
} else if (feedback.length > 0) {
|
||
setSending(true)
|
||
|
||
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
|
||
|
||
submitFeedback({
|
||
projectRef: ref,
|
||
organizationSlug: slug,
|
||
message: formattedFeedback,
|
||
pathname: href,
|
||
})
|
||
}
|
||
}
|
||
|
||
// Hydrate form from localStorage once it's ready; deps intentionally omit storedFeedback/screenshot
|
||
// so we don't overwrite user edits when those values change after initial load.
|
||
useEffect(() => {
|
||
if (storedFeedback) setFeedback(storedFeedback)
|
||
if (screenshot) setScreenshot(screenshot)
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps -- hydrate once when localStorage is ready only
|
||
}, [isSuccess])
|
||
|
||
// Persist debounced input to localStorage; only re-run when debounced value changes.
|
||
useEffect(() => {
|
||
if (debouncedFeedback.length > 0) setStoredFeedback(debouncedFeedback)
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps -- setStoredFeedback is stable; only sync on debounced value
|
||
}, [debouncedFeedback])
|
||
|
||
return isFeedbackSent ? (
|
||
<ThanksMessageView onClose={onClose} onSwitchToIssueOptions={onSwitchToIssueOptions} />
|
||
) : (
|
||
<>
|
||
<div className="p-4">
|
||
<TextArea
|
||
placeholder="My idea for improving Supabase is..."
|
||
rows={6}
|
||
value={feedback}
|
||
onChange={(e) => setFeedback(e.target.value)}
|
||
onPaste={handlePasteEvent}
|
||
className="text-sm mb-1 resize-none"
|
||
/>
|
||
</div>
|
||
|
||
<AnimatePresence>
|
||
{effectiveCategory === 'support' && (
|
||
<motion.div
|
||
key="support-alert"
|
||
initial={{ opacity: 0, y: 16 }}
|
||
animate={{ opacity: 1, y: 0 }}
|
||
exit={{ opacity: 0, y: 16 }}
|
||
transition={{ duration: 0.2 }}
|
||
>
|
||
<Admonition
|
||
type="caution"
|
||
title="This looks like an issue that’s better handled by support"
|
||
className="rounded-none border-x-0 border-b-0"
|
||
>
|
||
<p>
|
||
Please{' '}
|
||
<SupportLink
|
||
className={cn(InlineLinkClassName)}
|
||
queryParams={{ projectRef: slug, message: feedback }}
|
||
>
|
||
open a support ticket
|
||
</SupportLink>{' '}
|
||
to get help, as we do not reply to all product feedback.
|
||
</p>
|
||
</Admonition>
|
||
</motion.div>
|
||
)}
|
||
</AnimatePresence>
|
||
|
||
<PopoverSeparator />
|
||
|
||
<div className="px-4 pt-4 pb-4 flex flex-row items-center justify-between">
|
||
<Button size="tiny" onClick={onSwitchToIssueOptions}>
|
||
Get help instead
|
||
</Button>
|
||
<div className="flex items-center gap-2 flex-row">
|
||
{!!screenshot ? (
|
||
<div
|
||
style={{ backgroundImage: `url("${screenshot}")` }}
|
||
onClick={() => {
|
||
const blob = convertB64toBlob(screenshot)
|
||
const blobUrl = URL.createObjectURL(blob)
|
||
window.open(blobUrl, '_blank')
|
||
}}
|
||
className="cursor-pointer rounded-sm h-[26px] w-[26px] border border-control relative bg-cover bg-center bg-no-repeat"
|
||
>
|
||
<button
|
||
type="button"
|
||
tabIndex={0}
|
||
aria-label="Remove screenshot"
|
||
className={[
|
||
'cursor-pointer rounded-full bg-red-900 h-3 w-3',
|
||
'flex items-center justify-center absolute -top-1 -right-1',
|
||
].join(' ')}
|
||
onClick={(event) => {
|
||
event.stopPropagation()
|
||
setScreenshot(null)
|
||
}}
|
||
>
|
||
<XIcon size={8} strokeWidth={3} />
|
||
</button>
|
||
</div>
|
||
) : (
|
||
<DropdownMenu>
|
||
<DropdownMenuTrigger asChild>
|
||
<ButtonTooltip
|
||
disabled={isSavingScreenshot}
|
||
loading={isSavingScreenshot}
|
||
className="w-7"
|
||
icon={<ImageIcon size={14} />}
|
||
tooltip={{ content: { side: 'bottom', text: 'Attach screenshot' } }}
|
||
/>
|
||
</DropdownMenuTrigger>
|
||
<DropdownMenuContent side="bottom" align="end" className="w-fit">
|
||
<DropdownMenuItem
|
||
className="flex gap-2"
|
||
key="upload-screenshot"
|
||
onSelect={() => {
|
||
if (uploadButtonRef.current) uploadButtonRef.current.click()
|
||
}}
|
||
>
|
||
<UploadIcon size={14} />
|
||
Upload screenshot
|
||
</DropdownMenuItem>
|
||
<DropdownMenuSeparator />
|
||
<DropdownMenuItem
|
||
className="flex gap-2"
|
||
key="capture-screenshot"
|
||
onSelect={() => captureScreenshot()}
|
||
>
|
||
<CameraIcon size={14} />
|
||
Capture screenshot
|
||
</DropdownMenuItem>
|
||
</DropdownMenuContent>
|
||
</DropdownMenu>
|
||
)}
|
||
<input
|
||
type="file"
|
||
ref={uploadButtonRef}
|
||
aria-label="Upload screenshot"
|
||
className="hidden"
|
||
accept="image/png"
|
||
onChange={onFilesUpload}
|
||
/>
|
||
<Button
|
||
variant="primary"
|
||
disabled={feedback.length === 0 || isSending}
|
||
loading={isSending}
|
||
onClick={() => {
|
||
sendFeedback()
|
||
track('send_feedback_button_clicked')
|
||
}}
|
||
>
|
||
Send
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
</>
|
||
)
|
||
}
|