The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix: Delay the autofocus of the input in a treeview (#35270)
Ivan Vasilova915f3d7e73b
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxindex e518e86627f..4a10fc3ad7c 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx@@ -670,217 +670,208 @@ export const SQLEditor = () => {}}/>- <ResizablePanelGroup- className="flex h-full"- direction="horizontal"- autoSaveId={LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_PANEL_SPLIT_SIZE}- >- <ResizablePanel minSize={30}>- <ResizablePanelGroup- className="relative"- direction="vertical"- autoSaveId={LOCAL_STORAGE_KEYS.SQL_EDITOR_SPLIT_SIZE}- >- <ResizablePanel maxSize={70}>- <div className="flex-grow overflow-y-auto border-b h-full">- {isLoading ? (- <div className="flex h-full w-full items-center justify-center">- <Loader2 className="animate-spin text-brand" />- </div>- ) : (- <>- {isDiffOpen && (- <div className="w-full h-full">- <DiffEditor- theme="supabase"- language="pgsql"- original={defaultSqlDiff.original}- modified={defaultSqlDiff.modified}- onMount={(editor) => {- diffEditorRef.current = editor- setIsDiffEditorMounted(true)- }}- options={{- fontSize: 13,- renderSideBySide: false,- minimap: { enabled: false },- wordWrap: 'on',- lineNumbers: 'on',- folding: false,- padding: { top: 4 },- lineNumbersMinChars: 3,- }}- />- {showWidget && (- <ResizableAIWidget- editor={diffEditorRef.current!}- id="ask-ai-diff"- value={promptInput}- onChange={setPromptInput}- onSubmit={(prompt: string) => {- handlePrompt(prompt, {- beforeSelection: promptState.beforeSelection,- selection: promptState.selection || defaultSqlDiff.modified,- afterSelection: promptState.afterSelection,- })- }}- onAccept={acceptAiHandler}- onReject={discardAiHandler}- onCancel={resetPrompt}- isDiffVisible={true}- isLoading={isCompletionLoading}- startLineNumber={Math.max(0, promptState.startLineNumber)}- endLineNumber={promptState.endLineNumber}- />- )}- </div>- )}- <div key={id} className="w-full h-full relative">- <MonacoEditor- autoFocus- id={id}- className={cn(isDiffOpen && 'hidden')}- editorRef={editorRef}- monacoRef={monacoRef}- executeQuery={executeQuery}- onHasSelection={setHasSelection}- onMount={onMount}- onPrompt={({- selection,- beforeSelection,- afterSelection,- startLineNumber,- endLineNumber,- }) => {- setPromptState((prev) => ({- ...prev,- isOpen: true,- selection,- beforeSelection,- afterSelection,- startLineNumber,- endLineNumber,- }))+ <div className="flex h-full">+ <ResizablePanelGroup+ className="relative"+ direction="vertical"+ autoSaveId={LOCAL_STORAGE_KEYS.SQL_EDITOR_SPLIT_SIZE}+ >+ <ResizablePanel maxSize={70}>+ <div className="flex-grow overflow-y-auto border-b h-full">+ {isLoading ? (+ <div className="flex h-full w-full items-center justify-center">+ <Loader2 className="animate-spin text-brand" />+ </div>+ ) : (+ <>+ {isDiffOpen && (+ <div className="w-full h-full">+ <DiffEditor+ theme="supabase"+ language="pgsql"+ original={defaultSqlDiff.original}+ modified={defaultSqlDiff.modified}+ onMount={(editor) => {+ diffEditorRef.current = editor+ setIsDiffEditorMounted(true)+ }}+ options={{+ fontSize: 13,+ renderSideBySide: false,+ minimap: { enabled: false },+ wordWrap: 'on',+ lineNumbers: 'on',+ folding: false,+ padding: { top: 4 },+ lineNumbersMinChars: 3,}}/>- {editorRef.current && promptState.isOpen && !isDiffOpen && (+ {showWidget && (<ResizableAIWidget- editor={editorRef.current}- id="ask-ai"+ editor={diffEditorRef.current!}+ id="ask-ai-diff"value={promptInput}onChange={setPromptInput}onSubmit={(prompt: string) => {handlePrompt(prompt, {beforeSelection: promptState.beforeSelection,- selection: promptState.selection,+ selection: promptState.selection || defaultSqlDiff.modified,afterSelection: promptState.afterSelection,})}}+ onAccept={acceptAiHandler}+ onReject={discardAiHandler}onCancel={resetPrompt}- isDiffVisible={false}+ isDiffVisible={true}isLoading={isCompletionLoading}startLineNumber={Math.max(0, promptState.startLineNumber)}endLineNumber={promptState.endLineNumber}/>)}- <AnimatePresence>- {!promptState.isOpen && !editorRef.current?.getValue() && (- <motion.p- initial={{ y: 5, opacity: 0 }}- animate={{ y: 0, opacity: 1 }}- exit={{ y: 5, opacity: 0 }}- className="text-foreground-lighter absolute bottom-4 left-4 z-10 font-mono text-xs flex items-center gap-1"- >- Hit {os === 'macos' ? <Command size={12} /> : `CTRL+`}K to edit with the- Assistant- </motion.p>- )}- </AnimatePresence></div>- </>- )}- </div>- </ResizablePanel>-- <ResizableHandle withHandle />-- <ResizablePanel maxSize={70}>- {isLoading ? (- <div className="flex h-full w-full items-center justify-center">- <Loader2 className="animate-spin text-brand" />- </div>- ) : (- <UtilityPanel- id={id}- isExecuting={isExecuting}- isDisabled={isDiffOpen}- hasSelection={hasSelection}- prettifyQuery={prettifyQuery}- executeQuery={executeQuery}- onDebug={onDebug}- />- )}- </ResizablePanel>-- <ResizablePanel maxSize={10} minSize={10} className="max-h-9">- {results?.rows !== undefined && !isExecuting && (- <GridFooter className="flex items-center justify-between gap-2">- <Tooltip>- <TooltipTrigger>- <p className="text-xs">- <span className="text-foreground">- {results.rows.length} row{results.rows.length > 1 ? 's' : ''}- </span>- <span className="text-foreground-lighter ml-1">- {results.autoLimit !== undefined &&- ` (Limited to only ${results.autoLimit} rows)`}- </span>- </p>- </TooltipTrigger>- <TooltipContent className="max-w-xs">- <p className="flex flex-col gap-y-1">- <span>- Results are automatically limited to preserve browser performance, in- particular if your query returns an exceptionally large number of rows.- </span>-- <span className="text-foreground-light">- You may change or remove this limit from the dropdown on the right- </span>- </p>- </TooltipContent>- </Tooltip>- {results.autoLimit !== undefined && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button type="default" iconRight={<ChevronUp size={14} />}>- Limit results to:{' '}- {ROWS_PER_PAGE_OPTIONS.find((opt) => opt.value === snapV2.limit)?.label}- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="w-40" align="end">- <DropdownMenuRadioGroup- value={snapV2.limit.toString()}- onValueChange={(val) => snapV2.setLimit(Number(val))}- >- {ROWS_PER_PAGE_OPTIONS.map((option) => (- <DropdownMenuRadioItem- key={option.label}- value={option.value.toString()}- >- {option.label}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>)}- </GridFooter>+ <div key={id} className="w-full h-full relative">+ <MonacoEditor+ autoFocus+ id={id}+ className={cn(isDiffOpen && 'hidden')}+ editorRef={editorRef}+ monacoRef={monacoRef}+ executeQuery={executeQuery}+ onHasSelection={setHasSelection}+ onMount={onMount}+ onPrompt={({+ selection,+ beforeSelection,+ afterSelection,+ startLineNumber,+ endLineNumber,+ }) => {+ setPromptState((prev) => ({+ ...prev,+ isOpen: true,+ selection,+ beforeSelection,+ afterSelection,+ startLineNumber,+ endLineNumber,+ }))+ }}+ />+ {editorRef.current && promptState.isOpen && !isDiffOpen && (+ <ResizableAIWidget+ editor={editorRef.current}+ id="ask-ai"+ value={promptInput}+ onChange={setPromptInput}+ onSubmit={(prompt: string) => {+ handlePrompt(prompt, {+ beforeSelection: promptState.beforeSelection,+ selection: promptState.selection,+ afterSelection: promptState.afterSelection,+ })+ }}+ onCancel={resetPrompt}+ isDiffVisible={false}+ isLoading={isCompletionLoading}+ startLineNumber={Math.max(0, promptState.startLineNumber)}+ endLineNumber={promptState.endLineNumber}+ />+ )}+ <AnimatePresence>+ {!promptState.isOpen && !editorRef.current?.getValue() && (+ <motion.p+ initial={{ y: 5, opacity: 0 }}+ animate={{ y: 0, opacity: 1 }}+ exit={{ y: 5, opacity: 0 }}+ className="text-foreground-lighter absolute bottom-4 left-4 z-10 font-mono text-xs flex items-center gap-1"+ >+ Hit {os === 'macos' ? <Command size={12} /> : `CTRL+`}K to edit with the+ Assistant+ </motion.p>+ )}+ </AnimatePresence>+ </div>+ </>)}- </ResizablePanel>- </ResizablePanelGroup>- </ResizablePanel>- </ResizablePanelGroup>+ </div>+ </ResizablePanel>++ <ResizableHandle withHandle />++ <ResizablePanel maxSize={70}>+ {isLoading ? (+ <div className="flex h-full w-full items-center justify-center">+ <Loader2 className="animate-spin text-brand" />+ </div>+ ) : (+ <UtilityPanel+ id={id}+ isExecuting={isExecuting}+ isDisabled={isDiffOpen}+ hasSelection={hasSelection}+ prettifyQuery={prettifyQuery}+ executeQuery={executeQuery}+ onDebug={onDebug}+ />+ )}+ </ResizablePanel>++ <div className="max-h-9">+ {results?.rows !== undefined && !isExecuting && (+ <GridFooter className="flex items-center justify-between gap-2">+ <Tooltip>+ <TooltipTrigger>+ <p className="text-xs">+ <span className="text-foreground">+ {results.rows.length} row{results.rows.length > 1 ? 's' : ''}+ </span>+ <span className="text-foreground-lighter ml-1">+ {results.autoLimit !== undefined &&+ ` (Limited to only ${results.autoLimit} rows)`}+ </span>+ </p>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ <p className="flex flex-col gap-y-1">+ <span>+ Results are automatically limited to preserve browser performance, in+ particular if your query returns an exceptionally large number of rows.+ </span>++ <span className="text-foreground-light">+ You may change or remove this limit from the dropdown on the right+ </span>+ </p>+ </TooltipContent>+ </Tooltip>+ {results.autoLimit !== undefined && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="default" iconRight={<ChevronUp size={14} />}>+ Limit results to:{' '}+ {ROWS_PER_PAGE_OPTIONS.find((opt) => opt.value === snapV2.limit)?.label}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-40" align="end">+ <DropdownMenuRadioGroup+ value={snapV2.limit.toString()}+ onValueChange={(val) => snapV2.setLimit(Number(val))}+ >+ {ROWS_PER_PAGE_OPTIONS.map((option) => (+ <DropdownMenuRadioItem key={option.label} value={option.value.toString()}>+ {option.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </GridFooter>+ )}+ </div>+ </ResizablePanelGroup>+ </div></>)}diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.tsindex 01897488056..3ca7d99257d 100644--- a/apps/studio/lib/constants/index.ts+++ b/apps/studio/lib/constants/index.ts@@ -59,7 +59,6 @@ export const LOCAL_STORAGE_KEYS = {SQL_EDITOR_INTELLISENSE: 'supabase_sql-editor-intellisense-enabled',SQL_EDITOR_SPLIT_SIZE: 'supabase_sql-editor-split-size',- SQL_EDITOR_AI_PANEL_SPLIT_SIZE: 'supabase_sql-editor-ai-panel-split-size',// Key to track which schemas are ok to be sent to AI. The project ref is intentionally put at the end for easier search in the browser console.SQL_EDITOR_AI_SCHEMA: (ref: string) => `supabase_sql-editor-ai-schema-enabled-${ref}`,SQL_EDITOR_AI_OPEN: 'supabase_sql-editor-ai-open',diff --git a/apps/studio/state/sql-editor-v2.ts b/apps/studio/state/sql-editor-v2.tsindex 0f85816801b..94046904784 100644--- a/apps/studio/state/sql-editor-v2.ts+++ b/apps/studio/state/sql-editor-v2.ts@@ -178,14 +178,15 @@ export const sqlEditorState = proxy({saveFolder: ({ id, name }: { id: string; name: string }) => {let storeFolder = sqlEditorState.folders[id]+ const isNewFolder = id === 'new-folder'const hasChanges = storeFolder.folder.name !== name- if (id === 'new-folder' && sqlEditorState.allFolderNames.includes(name)) {+ if (isNewFolder && sqlEditorState.allFolderNames.includes(name)) {sqlEditorState.removeFolder(id)- return toast.error('This folder name already exists')+ return toast.error('Unable to create new folder: This folder name already exists')} else if (hasChanges && sqlEditorState.allFolderNames.includes(name)) {storeFolder.status = 'idle'- return toast.error('This folder name already exists')+ return toast.error('Unable to update folder: This folder name already exists')}const originalFolderName = storeFolder.folder.name.slice()diff --git a/packages/ui/src/components/TreeView/TreeView.tsx b/packages/ui/src/components/TreeView/TreeView.tsxindex 7ecc3435566..d8003cf382d 100644--- a/packages/ui/src/components/TreeView/TreeView.tsx+++ b/packages/ui/src/components/TreeView/TreeView.tsx@@ -2,7 +2,15 @@import { cva, VariantProps } from 'class-variance-authority'import { ChevronRight, FolderClosed, FolderOpen, Loader2 } from 'lucide-react'-import { ComponentPropsWithoutRef, forwardRef, ReactNode, useEffect, useRef, useState } from 'react'+import {+ ComponentPropsWithoutRef,+ FocusEvent,+ forwardRef,+ ReactNode,+ useEffect,+ useRef,+ useState,+} from 'react'import TreeViewPrimitive, { flattenTree } from 'react-accessible-treeview'import { cn } from '../../lib/utils'import { Input } from '../shadcn/ui/input'@@ -90,41 +98,44 @@ const TreeViewItem = forwardRef<) => {const [localValueState, setLocalValueState] = useState(name)const inputRef = useRef<HTMLInputElement>(null)-- useEffect(() => {- const handleClickOutside = (event: MouseEvent) => {- if (inputRef.current && !inputRef.current.contains(event.target as Node)) {- onEditSubmit?.(localValueState)- }- }- if (isEditing) document.addEventListener('mousedown', handleClickOutside)- return () => {- if (isEditing) document.removeEventListener('mousedown', handleClickOutside)- }- }, [isEditing])+ const timeRef = useRef<number>(0)useEffect(() => {if (isEditing) {- inputRef.current?.focus()+ // [Ivan] This component is supposed to focus on its input when it's rendered. The focus doesn't work every time because+ // the initial render is triggered by a dropdown menu which at the end of the closing animation, steals focus from the input+ // and triggers the blur event (which closes the input). The issue is reported at https://github.com/radix-ui/primitives/issues/3106.- // When editing starts, select text up to the last dot- if (inputRef.current) {+ // [Joshen] This is to prevent accidental onBlur callbacks by checking that the onBlur event is being triggered+ // within 400ms of the input field being in an edit state. 400ms is just an arbitary value which I think+ // represents an "accidental" on blur+ timeRef.current = Number(new Date())++ // The focus will be attempted after a slight delay to ensure that the dropdown closing animations are complete.+ setTimeout(() => {const input = inputRef.current+ if (input) {+ // If the input is not the active element, focus it+ if (document.activeElement !== input) {+ input.focus()+ }- // Need a slight delay to ensure focus is established- setTimeout(() => {- const fileName = input.value- const lastDotIndex = fileName.lastIndexOf('.')- const startPos = 0- const endPos = lastDotIndex > 0 ? lastDotIndex : fileName.length+ // Need a slight delay to ensure focus is established. When editing starts, select text up to the last dot+ // When editing starts, select text up to the last dot+ setTimeout(() => {+ const fileName = input.value+ const lastDotIndex = fileName.lastIndexOf('.')+ const startPos = 0+ const endPos = lastDotIndex > 0 ? lastDotIndex : fileName.length- try {- input.setSelectionRange(startPos, endPos)- } catch (e) {- console.error('Could not set selection range', e)- }- }, 50)- }+ try {+ input.setSelectionRange(startPos, endPos)+ } catch (e) {+ console.error('Could not set selection range', e)+ }+ }, 50)+ }+ }, 200)} else {setLocalValueState(name)}@@ -136,8 +147,16 @@ const TreeViewItem = forwardRef<}}, [isLoading])- const handleBlur = () => {- onEditSubmit?.(localValueState)+ const handleBlur = (e: FocusEvent<HTMLInputElement, Element>) => {+ const timestamp = Number(new Date())+ const timeDiff = timestamp - timeRef.current++ if (timeDiff < 400) {+ e.preventDefault()+ inputRef.current?.focus()+ } else {+ onEditSubmit?.(localValueState)+ }}const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {@@ -228,8 +247,9 @@ const TreeViewItem = forwardRef<<span className={cn(isEditing && 'hidden', 'truncate text-sm')} title={name}>{name}</span>- <form autoFocus onSubmit={handleSubmit} className={cn(!isEditing && 'hidden')}>+ <form onSubmit={handleSubmit} className={cn(!isEditing && 'hidden')}><Input+ autoFocusref={inputRef}onChange={(e) => {setLocalValueState(e.target.value)@@ -239,7 +259,7 @@ const TreeViewItem = forwardRef<// stop keyboard down bubbling up to TreeView.root// on enter key, send onEditSubmit callbackif (e.key === 'Enter') {- onEditSubmit?.(localValueState)+ inputRef.current?.blur()} else if (e.key === 'Escape') {setLocalValueState(name)onEditSubmit?.(name)@@ -247,7 +267,7 @@ const TreeViewItem = forwardRef<e.stopPropagation()}}}- className="block w-full text-sm px-2 py-1 h-7 w"+ className="block w-full text-sm px-2 py-1 h-7"value={localValueState}/></form>