Skip to content

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

15.7 KB
Raw Blame
import { keepPreviousData } from '@tanstack/react-query'
import { IS_PLATFORM } from 'common'
import { useParams } from 'common/hooks/useParams'
import {
  CopyIcon,
  DownloadIcon,
  EditIcon,
  ExternalLinkIcon,
  HeartIcon,
  LockIcon,
  MoveIcon,
  PlusIcon,
  ShareIcon,
  TrashIcon,
} from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { ComponentProps, useEffect } from 'react'
import {
  Button,
  cn,
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuTrigger,
  TreeViewItem,
} from 'ui'

import { getSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
import { createSqlSnippetSkeletonV2 } from '@/components/interfaces/SQLEditor/SQLEditor.utils'
import { LogsSnippetIcon } from '@/components/ui/EntityTypeIcon'
import { getContentById, getSqlSnippetById } from '@/data/content/content-id-query'
import { useSQLSnippetFolderContentsQuery } from '@/data/content/sql-folder-contents-query'
import { Snippet } from '@/data/content/sql-folders-query'
import {
  FGA_PERMISSIONS,
  useAsyncCheckUserContentPermissions,
} from '@/hooks/misc/useCheckPermissionsV2'
import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { useProfile } from '@/lib/profile'
import {
  isFolderEditing,
  isFolderSaving,
  type FolderStatus,
} from '@/state/sql-editor/sql-editor-lifecycle'
import { useSqlEditorSaveCoordinator } from '@/state/sql-editor/sql-editor-save-coordinator'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'

interface SQLEditorTreeViewItemProps extends Omit<
  ComponentProps<typeof TreeViewItem>,
  'name' | 'xPadding'
> {
  element: any
  isMultiSelected?: boolean
  status?: FolderStatus
  getNodeProps: () => any
  onSelectCreate?: () => void
  onSelectDelete?: () => void
  onSelectRename?: () => void
  onSelectMove?: () => void
  onSelectShare?: () => void
  onSelectUnshare?: () => void
  onSelectDownload?: () => void
  onSelectDeleteFolder?: () => void
  onEditSave?: (name: string) => void
  onMultiSelect?: (id: string) => void

  // Pagination/filtering options
  isLastItem: boolean
  hasNextPage?: boolean
  fetchNextPage?: () => void
  isFetchingNextPage?: boolean
  sort?: 'inserted_at' | 'name'
  name?: string
  onFolderContentsChange?: (info: { isLoading: boolean; snippets?: Snippet[] }) => void
}

export const SQLEditorTreeViewItem = ({
  element,
  isBranch,
  isExpanded,
  level,
  status,
  isSelected,
  isMultiSelected,
  getNodeProps,
  onSelectCreate,
  onSelectDelete,
  onSelectRename,
  onSelectMove,
  onSelectShare,
  onSelectUnshare,
  onSelectDownload,
  onEditSave,
  onMultiSelect,
  isLastItem,
  hasNextPage: _hasNextPage,
  fetchNextPage: _fetchNextPage,
  isFetchingNextPage: _isFetchingNextPage,
  sort,
  name,
  onFolderContentsChange,
  ...props
}: SQLEditorTreeViewItemProps) => {
  const router = useRouter()
  const { id, ref: projectRef } = useParams()
  const { profile } = useProfile()
  const { data: project } = useSelectedProjectQuery()
  const { className, onClick } = getNodeProps()
  const snapV2 = useSqlEditorV2StateSnapshot()
  const { saveFavorite } = useSqlEditorSaveCoordinator()

  const isOwner = profile?.id === element?.metadata.owner_id
  const isSharedSnippet = element.metadata.visibility === 'project'
  const isFavorite = element.metadata.favorite

  const isLogsSnippet = getSnippetSource(element.metadata) === 'logs'

  const isEditing = isFolderEditing(status)
  const isSaving = isFolderSaving(status)

  const { can: canCreateSQLSnippet } = useAsyncCheckUserContentPermissions(
    FGA_PERMISSIONS.PROJECT.SNIPPETS_WRITE,
    {
      mode: 'create',
      type: 'sql',
    }
  )

  const parentId = element.parent === 0 ? undefined : element.parent

  const isEnabled = isBranch && isExpanded

  const {
    data,
    isSuccess,
    isLoading,
    isFetchingNextPage: isFetchingNextPageInFolder,
    hasNextPage: hasNextPageInFolder,
    fetchNextPage: fetchNestPageInFolder,
    isPlaceholderData,
    isFetching,
  } = useSQLSnippetFolderContentsQuery(
    {
      projectRef,
      folderId: parentId ?? element.id,
      name,
      sort,
    },
    {
      enabled: isEnabled,
      placeholderData: keepPreviousData,
    }
  )
  useEffect(() => {
    if (projectRef && isSuccess) {
      data.pages.forEach((page) => {
        page.contents?.forEach((snippet) => {
          snapV2.addSnippet({
            projectRef,
            snippet,
          })
        })
      })
    }
  }, [projectRef, data?.pages])

  const onFolderContentsChangeRef = useLatest(onFolderContentsChange)
  useEffect(() => {
    if (isEnabled) {
      onFolderContentsChangeRef.current?.({
        isLoading: isLoading || (isPlaceholderData && isFetching),
        snippets: data?.pages.flatMap((page) => page.contents ?? []),
      })
    }
  }, [data?.pages, isFetching, isLoading, isPlaceholderData, isEnabled])

  const isInFolder = parentId !== undefined

  const hasNextPage = isInFolder ? hasNextPageInFolder : _hasNextPage

  function fetchNextPage() {
    if (isInFolder) {
      fetchNestPageInFolder()
    } else if (typeof _fetchNextPage === 'function') {
      _fetchNextPage()
    }
  }

  const onToggleFavorite = async () => {
    const snippetId = element.metadata.id
    if (!snippetId) return
    if (!projectRef) return console.error('Project ref is required')

    // Persisting a favorite goes through the full content upsert, so the
    // snippet's content must be loaded first — otherwise the PUT endpoint
    // rejects the update. Snippets listed in the nav that have never been
    // opened have no content loaded yet, so fetch it before toggling.
    const storeSnippet = snapV2.snippets[snippetId]
    if (!storeSnippet?.snippet.content) {
      const snippet = await getSqlSnippetById({ projectRef, id: snippetId })
      snapV2.setSnippet(projectRef, snippet)
    }

    saveFavorite(snippetId, !isFavorite)
  }

  const onSelectDuplicate = async () => {
    if (!profile) return console.error('Profile is required')
    if (!project) return console.error('Project is required')
    if (!projectRef) return console.error('Project ref is required')
    if (!id) return console.error('Snippet ID is required')

    const snippet = element.metadata
    let sql: string = ''

    if (snippet.content && snippet.content.unchecked_sql) {
      sql = snippet.content.unchecked_sql
    } else {
      // Fetch the content first
      const { content } = await getContentById({ projectRef, id: snippet.id })
      if ('unchecked_sql' in content) {
        sql = content.unchecked_sql
      }
    }

    const snippetCopy = createSqlSnippetSkeletonV2({
      name: `${snippet.name} (Duplicate)`,
      sql,
      owner_id: profile?.id,
      project_id: project?.id,
      source: getSnippetSource(snippet),
    })

    snapV2.addSnippet({ projectRef, snippet: snippetCopy })
    snapV2.addNeedsSaving(snippetCopy.id!)
    router.push(`/project/${projectRef}/sql/${snippetCopy.id}`)
  }

  return (
    <>
      <ContextMenu modal={false}>
        <ContextMenuTrigger asChild>
          <TreeViewItem
            className={className}
            level={level}
            isExpanded={isExpanded}
            isBranch={isBranch}
            isSelected={isSelected}
            isPreview={props.isPreview}
            isEditing={isEditing}
            isLoading={(isEnabled && isLoading) || isSaving}
            icon={
              isLogsSnippet ? (
                <LogsSnippetIcon
                  size={16}
                  className="w-5 h-5 shrink-0 text-foreground-muted group-aria-selected:text-foreground"
                />
              ) : undefined
            }
            onEditSubmit={(value) => {
              if (onEditSave !== undefined) onEditSave(value)
            }}
            onClick={(e) => {
              if (!isBranch) {
                if (!e.shiftKey) {
                  router.push(`/project/${projectRef}/sql/${element.id}`)
                } else if (id !== 'new') {
                  onMultiSelect?.(element.id)
                } else {
                  router.push(`/project/${projectRef}/sql/${element.id}`)
                }
              } else {
                // Prevent expanding folder while editing text
                // as the user may double click to select etc
                if (isEditing) {
                  return
                }
                // When the item is a folder, we want to expand/close it
                onClick(e)
              }
            }}
            {...props}
            name={element.name}
            nameForTitle={props.nameForTitle}
            description={element.metadata?.description || undefined}
            xPadding={16}
          />
        </ContextMenuTrigger>
        <ContextMenuContent onCloseAutoFocus={(e) => e.stopPropagation()}>
          {isBranch ? (
            <>
              {onSelectCreate !== undefined && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectCreate()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <PlusIcon size={14} />
                  Create new snippet
                </ContextMenuItem>
              )}
              {onSelectRename !== undefined && isOwner && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectRename()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <EditIcon size={14} />
                  Rename folder
                </ContextMenuItem>
              )}
              {onSelectDelete !== undefined && isOwner && (
                <>
                  <ContextMenuSeparator />
                  <ContextMenuItem
                    className="gap-x-2"
                    onSelect={() => onSelectDelete()}
                    onFocusCapture={(e) => e.stopPropagation()}
                  >
                    <TrashIcon size={14} />
                    Delete folder
                  </ContextMenuItem>
                </>
              )}
            </>
          ) : isMultiSelected ? (
            <>
              {onSelectMove !== undefined && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectMove()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <MoveIcon size={14} />
                  Move selected queries
                </ContextMenuItem>
              )}
              <ContextMenuSeparator />
              {onSelectDelete !== undefined && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectDelete()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <TrashIcon size={14} />
                  Delete selected queries
                </ContextMenuItem>
              )}
            </>
          ) : (
            <>
              <ContextMenuItem
                asChild
                className="gap-x-2"
                onFocusCapture={(e) => e.stopPropagation()}
              >
                <Link
                  target="_self"
                  rel="noreferrer"
                  href={`/project/${projectRef}/sql/${element.id}`}
                >
                  <ExternalLinkIcon size={14} />
                  Open in new tab
                </Link>
              </ContextMenuItem>
              <ContextMenuSeparator />
              {onSelectRename !== undefined && isOwner && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectRename()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <EditIcon size={14} />
                  Rename query
                </ContextMenuItem>
              )}
              {onSelectMove !== undefined && isOwner && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectMove()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <MoveIcon size={14} />
                  Move query
                </ContextMenuItem>
              )}
              {onSelectShare !== undefined &&
                !isSharedSnippet &&
                canCreateSQLSnippet &&
                IS_PLATFORM && (
                  <ContextMenuItem
                    className="gap-x-2"
                    onSelect={() => onSelectShare()}
                    onFocusCapture={(e) => e.stopPropagation()}
                  >
                    <ShareIcon size={14} />
                    Share query with team
                  </ContextMenuItem>
                )}
              {onSelectUnshare !== undefined && isSharedSnippet && isOwner && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectUnshare()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <LockIcon size={14} />
                  Unshare query with team
                </ContextMenuItem>
              )}
              {onSelectDuplicate !== undefined && canCreateSQLSnippet && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onSelectDuplicate()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <CopyIcon size={14} />
                  Duplicate query
                </ContextMenuItem>
              )}
              {IS_PLATFORM && (
                <ContextMenuItem
                  className="gap-x-2"
                  onSelect={() => onToggleFavorite()}
                  onFocusCapture={(e) => e.stopPropagation()}
                >
                  <HeartIcon
                    size={14}
                    className={cn(
                      isFavorite
                        ? 'fill-primary-bright stroke-none'
                        : 'fill-none stroke-foreground-light'
                    )}
                  />
                  {isFavorite ? 'Remove from' : 'Add to'} favorites
                </ContextMenuItem>
              )}
              {onSelectDownload !== undefined &&
                IS_PLATFORM &&
                getSnippetSource(element.metadata) !== 'logs' && (
                  <ContextMenuItem
                    className="gap-x-2"
                    onSelect={() => onSelectDownload()}
                    onFocusCapture={(e) => e.stopPropagation()}
                  >
                    <DownloadIcon size={14} />
                    Export query
                  </ContextMenuItem>
                )}
              {onSelectDelete !== undefined && isOwner && (
                <>
                  <ContextMenuSeparator />
                  <ContextMenuItem className="gap-x-2" onSelect={() => onSelectDelete()}>
                    <TrashIcon size={14} />
                    Delete query
                  </ContextMenuItem>
                </>
              )}
            </>
          )}
        </ContextMenuContent>
      </ContextMenu>

      {hasNextPage && typeof element.id === 'string' && isLastItem && (
        <div
          className="px-4 py-1"
          style={{
            paddingLeft:
              !element.isBranch && element.level > 1 ? 48 * (element.level - 1) : undefined,
          }}
        >
          <Button
            variant="outline"
            size="tiny"
            block
            loading={isInFolder ? isFetchingNextPageInFolder : _isFetchingNextPage}
            disabled={isInFolder ? isFetchingNextPageInFolder : _isFetchingNextPage}
            onClick={fetchNextPage}
          >
            Load More
          </Button>
        </div>
      )}
    </>
  )
}