mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
Part 1 of a 6-PR stack migrating all `next/link` imports in `apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known external URLs) and removing `compat/next/link.tsx`. | Part | PR | Scope | | --- | --- | --- | | **1** | **#54304 ← this PR** | **`data/prefetchers/PrefetchableLink.tsx` and `components/ui/**`** | | 2 | #54305 | `components/layouts/**` and top-level shell components | | 3 | #54306 | Database, TableGridEditor, Storage, SQLEditor, BranchManagement, Branching, Functions, Realtime | | 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues, Linter, Reports, QueryPerformance, QuerySources, ConfigDrift, DiskManagement, Compute | | 5 | #54308 | Remaining `components/interfaces/**` (Org, Billing, Auth, Support, Home, SignIn, ConnectSheet, etc.) | | 6 | #54309 | Remove `compat/next/link.tsx` shim, Vite alias, and update basePath tests/docs | Migrates `data/prefetchers/PrefetchableLink.tsx` and all shared `components/ui/**` components off `next/link`. **Added:** - `apps/studio/components/ui/DynamicLink.tsx` (with unit tests) — shared `forwardRef` link wrapper for dynamic URL strings that runs `splitInternalUrl` and renders a plain `<a>` for external URLs (or same-origin URLs outside the app's `basePath`) vs TanStack `<Link>` for internal paths **Changed:** - Replaced `next/link` in `apps/studio/data/prefetchers/PrefetchableLink.tsx` and all 30 importing components under `apps/studio/components/ui/**` (`InlineLink`, `CardButton`, `CommandItemLink`, `ObservabilityLink`, `ProductMenuItem`, `ResourceItem`, `UpgradePlanButton`, `ToggleSpendCapButton`, banners, AI assistant panel links, etc.) - Used typed `<Link to="..." params={...} search={...} hash="..." />` for known internal routes, `<DynamicLink href={...} />` for dynamic/untyped URL strings (whether internal with query/hash or external), and plain `<a>` for known external links - Updated `apps/studio/routes/index.tsx` `validateSearch` return type to `{ next?: string }` so `<Link to="/">` compiles without requiring `search={{ next: undefined }}` - Updated `hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx`, `PolicyTableRow.utils.test.ts`, `SupportAssistantSuccessCard.test.tsx`, and `useOrganizationRestrictions.test.tsx` to render inside a TanStack Router context (`customRender` / `RouterContextProvider`) Addresses [FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link) ## To test - [ ] Click internal and external `InlineLink`, `CardButton`, `ProductMenuItem`, and `PrefetchableLink` targets and verify client-side navigation vs external anchors - [ ] Verify banner links (upgrade, resource exhaustion, queue operations) preserve query params and hashes - [ ] Confirm Studio typecheck, lint, and unit tests pass --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
266 lines
8.1 KiB
TypeScript
266 lines
8.1 KiB
TypeScript
import React, {
|
|
isValidElement,
|
|
lazy,
|
|
memo,
|
|
ReactNode,
|
|
Suspense,
|
|
useMemo,
|
|
type ReactElement,
|
|
} from 'react'
|
|
import {
|
|
Button,
|
|
cn,
|
|
Dialog,
|
|
DialogClose,
|
|
DialogContent,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogSection,
|
|
DialogTitle,
|
|
DialogTrigger,
|
|
} from 'ui'
|
|
import { CodeBlock, type CodeBlockLang } from 'ui-patterns/CodeBlock'
|
|
import { markdownComponents } from 'ui-patterns/Markdown'
|
|
|
|
import { EdgeFunctionBlock } from '../EdgeFunctionBlock/EdgeFunctionBlock'
|
|
import { AssistantSnippetProps } from './AIAssistant.types'
|
|
import { AssistantQueryCell } from './AssistantQueryCell'
|
|
import { CollapsibleCodeBlock } from './CollapsibleCodeBlock'
|
|
import { defaultUrlTransform, wrapPlaceholderUrls } from './Message.utils'
|
|
import { DynamicLink } from '@/components/ui/DynamicLink'
|
|
|
|
const Streamdown = lazy(() => import('streamdown').then((mod) => ({ default: mod.Streamdown })))
|
|
|
|
// Streamdown splits ordered lists with complex content (e.g. code blocks) into
|
|
// separate <ol> elements. The `start` attribute preserves semantics for screen
|
|
// readers, while `counterReset` is what actually fixes the visible numbering —
|
|
// the prose config (tailwind.config.ts) uses a custom CSS counter named "item"
|
|
// with `listStyleType: 'none'`, so the `start` attribute alone has no visual effect.
|
|
export const OrderedList = memo(({ children, start }: { children?: ReactNode; start?: number }) => (
|
|
<ol
|
|
className="flex flex-col gap-y-4"
|
|
start={start}
|
|
style={start !== undefined ? { counterReset: `item ${start - 1}` } : undefined}
|
|
>
|
|
{children}
|
|
</ol>
|
|
))
|
|
OrderedList.displayName = 'OrderedList'
|
|
|
|
export const ListItem = memo(({ children }: { children?: ReactNode }) => (
|
|
<li className="[&>pre]:mt-2">{children}</li>
|
|
))
|
|
ListItem.displayName = 'ListItem'
|
|
|
|
export const Heading3 = memo(({ children }: { children?: ReactNode }) => (
|
|
<h3 className="underline">{children}</h3>
|
|
))
|
|
Heading3.displayName = 'Heading3'
|
|
|
|
export const InlineCode = memo(
|
|
({ className, children }: { className?: string; children?: ReactNode }) => (
|
|
<code className={cn('text-xs', className)}>{children}</code>
|
|
)
|
|
)
|
|
InlineCode.displayName = 'InlineCode'
|
|
|
|
export const Hyperlink = memo(({ href, children }: { href?: string; children?: ReactNode }) => {
|
|
const isExternalURL = !href?.startsWith('https://supabase.com/dashboard')
|
|
const safeUrl = defaultUrlTransform(href ?? '')
|
|
const isSafeUrl = safeUrl.length > 0
|
|
|
|
if (!isSafeUrl) {
|
|
return <span className="text-foreground">{children}</span>
|
|
}
|
|
|
|
return (
|
|
<Dialog>
|
|
<DialogTrigger asChild>
|
|
<span
|
|
className={cn(
|
|
'm-0! text-foreground cursor-pointer transition',
|
|
'underline underline-offset-2 decoration-foreground-muted hover:decoration-foreground-lighter'
|
|
)}
|
|
>
|
|
{children}
|
|
</span>
|
|
</DialogTrigger>
|
|
<DialogContent size="small">
|
|
<DialogHeader className="border-b">
|
|
<DialogTitle>Verify the link before navigating</DialogTitle>
|
|
</DialogHeader>
|
|
|
|
<DialogSection className="flex flex-col">
|
|
<p className="text-sm text-foreground-light">
|
|
This link will take you to the following URL:
|
|
</p>
|
|
<p className="text-sm text-foreground">{safeUrl}</p>
|
|
<p className="text-sm text-foreground-light mt-2">Are you sure you want to head there?</p>
|
|
</DialogSection>
|
|
|
|
<DialogFooter>
|
|
<DialogClose asChild>
|
|
<Button className="opacity-100">Cancel</Button>
|
|
</DialogClose>
|
|
<DialogClose asChild>
|
|
<Button asChild variant="primary" className="opacity-100">
|
|
{isExternalURL ? (
|
|
<a href={safeUrl} target="_blank" rel="noreferrer noopener">
|
|
Head to link
|
|
</a>
|
|
) : (
|
|
<DynamicLink href={safeUrl}>Head to link</DynamicLink>
|
|
)}
|
|
</Button>
|
|
</DialogClose>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
})
|
|
Hyperlink.displayName = 'Hyperlink'
|
|
|
|
const baseMarkdownComponents = {
|
|
ol: OrderedList,
|
|
li: ListItem,
|
|
h3: Heading3,
|
|
code: InlineCode,
|
|
a: Hyperlink,
|
|
img: ({ src }: React.JSX.IntrinsicElements['img']) => (
|
|
<span className="text-foreground-light font-mono">[Image: {src?.toString()}]</span>
|
|
),
|
|
}
|
|
|
|
export const MessageMarkdown = memo(function MessageMarkdown({
|
|
id,
|
|
isLoading,
|
|
readOnly,
|
|
className,
|
|
children,
|
|
}: {
|
|
id: string
|
|
isLoading: boolean
|
|
readOnly?: boolean
|
|
className?: string
|
|
children: ReactNode
|
|
}) {
|
|
const markdownSource = useMemo(() => {
|
|
if (typeof children === 'string') {
|
|
return wrapPlaceholderUrls(children)
|
|
}
|
|
if (Array.isArray(children)) {
|
|
return wrapPlaceholderUrls(
|
|
children.filter((child): child is string => typeof child === 'string').join('')
|
|
)
|
|
}
|
|
return ''
|
|
}, [children])
|
|
|
|
const allMarkdownComponents = useMemo(
|
|
() => ({
|
|
...markdownComponents,
|
|
...baseMarkdownComponents,
|
|
pre: (props: React.JSX.IntrinsicElements['pre']) => (
|
|
<MarkdownPre id={id} isLoading={isLoading} readOnly={readOnly}>
|
|
{props.children}
|
|
</MarkdownPre>
|
|
),
|
|
}),
|
|
[id, isLoading, readOnly]
|
|
)
|
|
|
|
return (
|
|
<Suspense fallback={null}>
|
|
<Streamdown className={className} components={allMarkdownComponents}>
|
|
{markdownSource}
|
|
</Streamdown>
|
|
</Suspense>
|
|
)
|
|
})
|
|
|
|
export const MarkdownPre = ({
|
|
children,
|
|
id,
|
|
isLoading,
|
|
readOnly,
|
|
}: {
|
|
children: any
|
|
id: string
|
|
isLoading: boolean
|
|
readOnly?: boolean
|
|
}) => {
|
|
const childArray = Array.isArray(children) ? children : [children]
|
|
const codeElement = childArray.find(
|
|
(child): child is ReactElement<{ className?: string; children: ReactNode }> =>
|
|
isValidElement<{ className?: string; children: ReactNode }>(child)
|
|
)
|
|
const codeProps = codeElement?.props || ({} as { className?: string; children: ReactNode })
|
|
const language = codeProps.className?.replace('language-', '') || 'sql'
|
|
const codeChildren = codeProps.children
|
|
const rawContent = Array.isArray(codeChildren)
|
|
? codeChildren.map((node) => (typeof node === 'string' ? node : '')).join('')
|
|
: typeof codeChildren === 'string'
|
|
? codeChildren
|
|
: ''
|
|
const propsMatch = rawContent.match(/(?:--|\/\/)\s*props:\s*(\{[^}]+\})/)
|
|
|
|
const snippetProps: AssistantSnippetProps = useMemo(() => {
|
|
try {
|
|
if (propsMatch) {
|
|
return JSON.parse(propsMatch[1])
|
|
}
|
|
} catch {}
|
|
return {}
|
|
}, [propsMatch])
|
|
|
|
const { xAxis, yAxis } = snippetProps
|
|
const snippetId = snippetProps.id
|
|
const title = snippetProps.title || (language === 'edge' ? 'Edge Function' : 'SQL query')
|
|
const isChart = snippetProps.isChart === 'true'
|
|
// Strip props from the content for both SQL and edge functions
|
|
const cleanContent = rawContent.replace(/(?:--|\/\/)\s*props:\s*\{[^}]+\}/, '').trim()
|
|
|
|
const toolCallId = String(snippetId ?? id)
|
|
|
|
if (!codeElement) {
|
|
return <pre className="w-auto overflow-x-auto not-prose my-4">{children}</pre>
|
|
}
|
|
|
|
return (
|
|
<div className="w-auto overflow-x-hidden not-prose my-4 ">
|
|
{language === 'edge' ? (
|
|
<EdgeFunctionBlock
|
|
label={title}
|
|
code={cleanContent}
|
|
functionName={snippetProps.name || 'my-function'}
|
|
showCode={!readOnly}
|
|
/>
|
|
) : language === 'sql' ? (
|
|
readOnly ? (
|
|
<CollapsibleCodeBlock value={cleanContent} language="sql" hideLineNumbers />
|
|
) : (
|
|
<AssistantQueryCell
|
|
id={toolCallId}
|
|
sql={cleanContent}
|
|
title={title}
|
|
view={isChart ? 'chart' : 'table'}
|
|
xAxis={xAxis}
|
|
yAxis={yAxis}
|
|
isStreaming={isLoading}
|
|
/>
|
|
)
|
|
) : (
|
|
<CodeBlock
|
|
hideLineNumbers
|
|
value={cleanContent}
|
|
language={language as CodeBlockLang}
|
|
className={cn(
|
|
'my-4 max-h-96 max-w-none block border rounded-sm bg-transparent! py-3! px-3.5! prose dark:prose-dark text-foreground',
|
|
'[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap [&>code]:block [&>code>span]:text-foreground'
|
|
)}
|
|
/>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|