SchemaTableNode.tsx 14 KB

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