SchemaTableNode.tsx360 lines · main
1import { PermissionAction } from '@supabase/shared-types/out/constants'
2import { Handle, Node, NodeProps } from '@xyflow/react'
3import { TableEditor } from 'icons'
4import {
5 Copy,
6 DiamondIcon,
7 Edit,
8 Fingerprint,
9 Hash,
10 InfoIcon,
11 Key,
12 MoreVertical,
13 Table2,
14} from 'lucide-react'
15import { useRouter } from 'next/router'
16import { toast } from 'sonner'
17import {
18 Button,
19 cn,
20 copyToClipboard,
21 DropdownMenu,
22 DropdownMenuContent,
23 DropdownMenuItem,
24 DropdownMenuSeparator,
25 DropdownMenuTrigger,
26 Tooltip,
27 TooltipContent,
28 TooltipTrigger,
29} from 'ui'
30
31import { useSchemaGraphContext } from './SchemaGraphContext'
32import { TableNodeData } from './Schemas.constants'
33import { getTableDefinitionAsMarkdown } from './Schemas.utils'
34import { buildTableEditorUrl } from '@/components/grid/BrivenGrid.utils'
35import { getTableDefinition } from '@/data/database/table-definition-query'
36import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
37import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
38import { formatSql } from '@/lib/formatSql'
39
40// ReactFlow is scaling everything by the factor of 2
41export const TABLE_NODE_WIDTH = 320
42export const TABLE_NODE_ROW_HEIGHT = 40
43
44export const TableNode = ({
45 id,
46 data,
47 targetPosition,
48 sourcePosition,
49 placeholder,
50}: NodeProps<Node<TableNodeData>> & { placeholder?: boolean }) => {
51 // Important styles is a nasty hack to use Handles (required for edges calculations), but do not show them in the UI.
52 // ref: https://github.com/wbkd/react-flow/discussions/2698
53 const hiddenNodeConnector = 'h-px! w-px! min-w-0! min-h-0! cursor-grab! border-0! opacity-0!'
54 const schemaGraphContext = useSchemaGraphContext()
55 const { data: project } = useSelectedProjectQuery()
56 const { can: canUpdateColumns } = useAsyncCheckPermissions(
57 PermissionAction.TENANT_SQL_ADMIN_WRITE,
58 'columns'
59 )
60 const router = useRouter()
61 const itemHeight = 'h-[22px]'
62
63 const hasEdgesSelected =
64 schemaGraphContext.selectedEdge?.source === id || schemaGraphContext.selectedEdge?.target === id
65
66 return (
67 <article>
68 {data.isForeign ? (
69 <header
70 className={cn(
71 'text-[0.55rem] px-2 py-1 border-[0.5px] rounded-[4px] bg-alternative flex gap-1 items-center',
72 hasEdgesSelected ? 'outline outline-1 outline-brand' : undefined
73 )}
74 >
75 {data.name}
76 {targetPosition && (
77 <Handle
78 type="target"
79 id={data.name}
80 position={targetPosition}
81 className={cn(hiddenNodeConnector)}
82 />
83 )}
84 </header>
85 ) : (
86 <div
87 className={cn(
88 'border-[0.5px] overflow-hidden rounded-[4px] shadow-xs',
89 hasEdgesSelected ? 'outline outline-1 outline-brand' : undefined
90 )}
91 style={{ width: TABLE_NODE_WIDTH / 2 }}
92 >
93 <header
94 className={cn(
95 'text-[0.55rem] pl-2 pr-1 bg-alternative flex gap-2 items-center justify-between',
96 itemHeight
97 )}
98 >
99 <div className="min-w-0 flex shrink gap-x-1 items-center">
100 <Table2 strokeWidth={1} size={12} className="text-light" />
101 <span className="whitespace-nowrap overflow-hidden text-ellipsis" title={data.name}>
102 {data.name}
103 </span>
104 </div>
105 {
106 // Hide the actions while downloading the schema as png/svg
107 !schemaGraphContext.isDownloading ? (
108 <div className="flex shrink-0 items-center gap-2">
109 {data.description && (
110 <Tooltip>
111 <TooltipTrigger asChild className="cursor-default ">
112 <InfoIcon size={10} className="text-light" />
113 </TooltipTrigger>
114 <TooltipContent side="top">{data.description}</TooltipContent>
115 </Tooltip>
116 )}
117
118 {!placeholder && (
119 <DropdownMenu>
120 <DropdownMenuTrigger asChild>
121 <Button
122 type="text"
123 className="px-0 w-[16px] h-[16px] rounded-sm nodrag nopan"
124 >
125 <MoreVertical size={10} />
126 <span className="sr-only">{data.name} actions</span>
127 </Button>
128 </DropdownMenuTrigger>
129 <DropdownMenuContent side="bottom" align="end" className="w-40">
130 <DropdownMenuItem
131 className="flex items-center space-x-2 whitespace-nowrap"
132 onClick={() => schemaGraphContext.onEditTable(data.id)}
133 >
134 <Edit size={12} />
135 <p>Edit table</p>
136 </DropdownMenuItem>
137 <DropdownMenuItem
138 className="flex items-center space-x-2 whitespace-nowrap"
139 onClick={() =>
140 router.push(
141 buildTableEditorUrl({
142 projectRef: project?.ref,
143 tableId: data.id,
144 schema: data.schema,
145 })
146 )
147 }
148 >
149 <TableEditor size={12} />
150 <p>View in Table Editor</p>
151 </DropdownMenuItem>
152 <DropdownMenuSeparator />
153 <DropdownMenuItem
154 className="flex items-center space-x-2 whitespace-nowrap"
155 onClick={(e) => {
156 e.stopPropagation()
157 copyToClipboard(data.name)
158 }}
159 >
160 <Copy size={12} />
161 <span>Copy name</span>
162 </DropdownMenuItem>
163 <DropdownMenuItem
164 key="copy-schema-sql"
165 className="space-x-2"
166 onClick={async (e) => {
167 e.stopPropagation()
168 const toastId = toast.loading('Getting table schema...')
169
170 const formattedSchema = getTableDefinition({
171 id: data.id,
172 projectRef: project?.ref,
173 connectionString: project?.connectionString,
174 }).then((tableDefinition) => {
175 if (!tableDefinition) {
176 throw new Error('Failed to get table schema')
177 }
178 return formatSql(tableDefinition)
179 })
180
181 try {
182 await copyToClipboard(formattedSchema, () => {
183 toast.success('Table schema copied to clipboard', { id: toastId })
184 })
185 } catch (err) {
186 toast.error(
187 'Failed to copy schema: ' + ((err as Error).message || err),
188 {
189 id: toastId,
190 }
191 )
192 }
193 }}
194 >
195 <Copy size={12} />
196 <span>Copy as SQL</span>
197 </DropdownMenuItem>
198 <DropdownMenuItem
199 key="copy-schema-markdown"
200 className="space-x-2"
201 onClick={async (e) => {
202 e.stopPropagation()
203 const markdown = getTableDefinitionAsMarkdown(data)
204
205 try {
206 await copyToClipboard(markdown, () => {
207 toast.success('Table schema copied to clipboard')
208 })
209 } catch (err) {
210 toast.error(
211 'Failed to copy schema: ' + ((err as Error).message || err)
212 )
213 }
214 }}
215 >
216 <Copy size={12} />
217 <span>Copy as Markdown</span>
218 </DropdownMenuItem>
219 </DropdownMenuContent>
220 </DropdownMenu>
221 )}
222 </div>
223 ) : null
224 }
225 </header>
226
227 {data.columns.map((column) => (
228 <div
229 className={cn(
230 'text-[8px] leading-5 relative flex flex-row justify-items-start',
231 'bg-surface-100',
232 'border-t',
233 'border-t-[0.5px]',
234 'hover:bg-scale-500 transition cursor-default',
235 'group',
236 'pr-1',
237 itemHeight
238 )}
239 data-testid={`${data.name}/${column.name}`}
240 key={column.id}
241 >
242 <div
243 className={cn(
244 'gap-[0.24rem] flex mx-2 align-middle items-center justify-start',
245 column.isPrimary && 'basis-1/5'
246 )}
247 >
248 {column.isPrimary && (
249 <Key
250 size={8}
251 strokeWidth={1}
252 className={cn(
253 // 'sb-grid-column-header__inner__primary-key'
254 'shrink-0',
255 'text-light'
256 )}
257 />
258 )}
259 {column.isNullable && (
260 <DiamondIcon size={8} strokeWidth={1} className="shrink-0 text-light" />
261 )}
262 {!column.isNullable && (
263 <DiamondIcon
264 size={8}
265 strokeWidth={1}
266 fill="currentColor"
267 className="shrink-0 text-light"
268 />
269 )}
270 {column.isUnique && (
271 <Fingerprint size={8} strokeWidth={1} className="shrink-0 text-light" />
272 )}
273 {column.isIdentity && (
274 <Hash size={8} strokeWidth={1} className="shrink-0 text-light" />
275 )}
276 </div>
277 <div className="flex w-full justify-between min-w-0">
278 <span
279 className={cn(
280 'text-ellipsis overflow-hidden whitespace-nowrap min-w-0 max-w-[80%]',
281 schemaGraphContext.selectedEdge?.sourceHandle === column.id ||
282 schemaGraphContext.selectedEdge?.targetHandle === column.id
283 ? 'text-brand'
284 : undefined
285 )}
286 title={column.name}
287 >
288 {column.name}
289 </span>
290 <span className="shrink-0 pl-2 pr-1 inline-flex justify-end font-mono text-lighter text-[0.4rem] group-hover:hidden">
291 {column.format}
292 </span>
293 </div>
294 {targetPosition && (
295 <Handle
296 type="target"
297 id={column.id}
298 position={targetPosition}
299 className={cn(hiddenNodeConnector)}
300 />
301 )}
302 {sourcePosition && (
303 <Handle
304 type="source"
305 id={column.id}
306 position={sourcePosition}
307 className={cn(hiddenNodeConnector)}
308 />
309 )}
310 <DropdownMenu>
311 <DropdownMenuTrigger asChild>
312 <Button
313 type="text"
314 // Use opacity to hide the button so that it remains accessible (users can tab to it)
315 className="opacity-0 focus:opacity-100 group-hover:opacity-100 data-open:opacity-100 absolute right-0 top-1/2 -translate-y-1/2 px-0 mr-1 w-[16px] h-[16px] rounded-sm"
316 >
317 <MoreVertical size={10} />
318 <span className="sr-only">
319 {data.name} {column.name} actions
320 </span>
321 </Button>
322 </DropdownMenuTrigger>
323 <DropdownMenuContent side="bottom" align="end" className="w-32">
324 <Tooltip>
325 <TooltipTrigger asChild>
326 <DropdownMenuItem
327 disabled={!canUpdateColumns}
328 onClick={() => schemaGraphContext.onEditColumn(data.id, column.id)}
329 className="space-x-2"
330 >
331 <Edit size={12} />
332 <p>Edit column</p>
333 </DropdownMenuItem>
334 </TooltipTrigger>
335 {!canUpdateColumns && (
336 <TooltipContent side="bottom">
337 Additional permissions required to edit column
338 </TooltipContent>
339 )}
340 </Tooltip>
341
342 <DropdownMenuItem
343 className="space-x-2"
344 onClick={(e) => {
345 e.stopPropagation()
346 copyToClipboard(column.name)
347 }}
348 >
349 <Copy size={12} />
350 <span>Copy name</span>
351 </DropdownMenuItem>
352 </DropdownMenuContent>
353 </DropdownMenu>
354 </div>
355 ))}
356 </div>
357 )}
358 </article>
359 )
360}