Skip to content

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

chore(studio): migrate useHotKey to useShortcut (#45099)

Ali Waseem40791f984625
diff --git a/apps/studio/components/grid/hooks/useOperationQueueShortcuts.ts b/apps/studio/components/grid/hooks/useOperationQueueShortcuts.ts
index 0ea7a3384d6..bbde506e96c 100644
--- a/apps/studio/components/grid/hooks/useOperationQueueShortcuts.ts
+++ b/apps/studio/components/grid/hooks/useOperationQueueShortcuts.ts
@@ -4,7 +4,8 @@ import { useOperationQueueActions } from './useOperationQueueActions'
import { useIsQueueOperationsEnabled } from '@/components/interfaces/Account/Preferences/useDashboardSettings'
import { tableRowKeys } from '@/data/table-rows/keys'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
import { useTableEditorStateSnapshot } from '@/state/table-editor'
/**
@@ -28,44 +29,36 @@ export function useOperationQueueShortcuts() {
const hasOperations = snap.hasPendingOperations
const isEnabled = isQueueOperationsEnabled && hasOperations
- useHotKey(
- (event) => {
- event.preventDefault()
- event.stopPropagation()
+ useShortcut(
+ SHORTCUT_IDS.OPERATION_QUEUE_SAVE,
+ () => {
if (!isSaving && hasOperations) {
handleSave()
}
},
- 's',
{ enabled: isEnabled }
)
- useHotKey(
- (event) => {
- event.preventDefault()
- event.stopPropagation()
+ useShortcut(
+ SHORTCUT_IDS.OPERATION_QUEUE_TOGGLE,
+ () => {
snap.toggleViewOperationQueue()
},
- '.',
{ enabled: isEnabled }
)
- useHotKey(
- (event) => {
- event.preventDefault()
- event.stopPropagation()
-
+ useShortcut(
+ SHORTCUT_IDS.OPERATION_QUEUE_UNDO,
+ () => {
const tableIdLatestOperation = snap.operationQueue.operations.at(-1)?.tableId
snap.undoLatestOperation()
- // Invalidate the query to revert the optimistic update
if (project && tableIdLatestOperation) {
queryClient.invalidateQueries({
queryKey: tableRowKeys.tableRowsAndCount(project.ref, tableIdLatestOperation),
})
}
},
- 'z',
{ enabled: isEnabled }
)
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
index b50ed0d54c0..43b26fd838b 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ActionBar.tsx
@@ -2,7 +2,8 @@ import { noop } from 'lodash'
import { PropsWithChildren, useCallback, useState } from 'react'
import { Button, KeyboardShortcut } from 'ui'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
interface ActionBarProps {
loading?: boolean
@@ -37,36 +38,20 @@ export const ActionBar = ({
setIsRunning(false)
}, [applyFunction])
- const handleSave = useCallback(
- (event: KeyboardEvent) => {
- // Don't trigger if already running/loading, or if apply is disabled/hidden
- if (isRunning || loading || disableApply || hideApply) return
+ const handleSave = useCallback(() => {
+ if (isRunning || loading || disableApply || hideApply) return
- // Don't trigger if the user is in a textarea (allow multi-line entry)
- // unless they explicitly press CMD+Enter
- const activeElement = document.activeElement
- const isTextarea = activeElement?.tagName === 'TEXTAREA'
-
- // If in a textarea and this is just an Enter key (not CMD+Enter), don't submit
- if (isTextarea && !event.metaKey && !event.ctrlKey) return
-
- event.preventDefault()
- event.stopPropagation()
-
- if (formId) {
- // Form-based submission - programmatically submit the form
- const form = document.getElementById(formId) as HTMLFormElement | null
- if (form) {
- form.requestSubmit()
- }
- } else if (applyFunction) {
- onSelectApply()
+ if (formId) {
+ const form = document.getElementById(formId) as HTMLFormElement | null
+ if (form) {
+ form.requestSubmit()
}
- },
- [isRunning, loading, disableApply, hideApply, formId, applyFunction, onSelectApply]
- )
+ } else if (applyFunction) {
+ onSelectApply()
+ }
+ }, [isRunning, loading, disableApply, hideApply, formId, applyFunction, onSelectApply])
- useHotKey(handleSave, 'Enter', { enabled: visible })
+ useShortcut(SHORTCUT_IDS.ACTION_BAR_SAVE, handleSave, { enabled: visible })
return (
<div className="flex w-full items-center gap-3 border-t border-default px-3 py-4">
diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.hooks.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.hooks.ts
index c8ef733224c..af67d64f4f0 100644
--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.hooks.ts
+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.hooks.ts
@@ -2,17 +2,18 @@ import { useQueryState } from 'nuqs'
import { useEffect, useMemo, useRef } from 'react'
import { SEARCH_PARAMS_PARSER } from './UnifiedLogs.constants'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
export const useResetFocus = () => {
- useHotKey(() => {
+ useShortcut(SHORTCUT_IDS.UNIFIED_LOGS_RESET_FOCUS, () => {
// FIXME: some dedicated div[tabindex="0"] do not auto-unblur (e.g. the DataTableFilterResetButton)
// REMINDER: we cannot just document.activeElement?.blur(); as the next tab will focus the next element in line,
// which is not what we want. We want to reset entirely.
document.body.setAttribute('tabindex', '0')
document.body.focus()
document.body.removeAttribute('tabindex')
- }, '.')
+ })
}
export const useLiveMode = <TData extends { date: Date }>(data: TData[]) => {
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index 6c3dabef41c..04b994a3fcd 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -35,7 +35,6 @@ import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
import { useOrgAiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useHotKey } from '@/hooks/ui/useHotKey'
import {
DEFAULT_ASSISTANT_BASE_MODEL_ID,
defaultAssistantModelId,
@@ -47,6 +46,8 @@ import { uuidv4 } from '@/lib/helpers'
import { useTrack } from '@/lib/telemetry/track'
import type { AssistantModel } from '@/state/ai-assistant-state'
import { useAiAssistantState, useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
@@ -64,7 +65,7 @@ export const AIAssistant = ({ className }: AIAssistantProps) => {
const { data: selectedOrganization, isPending: isLoadingOrganization } =
useSelectedOrganizationQuery()
- useHotKey(() => cancelEdit(), 'Escape')
+ useShortcut(SHORTCUT_IDS.AI_ASSISTANT_CANCEL_EDIT, () => cancelEdit())
const disablePrompts = useFlag('disableAssistantPrompts')
const { snippets } = useSqlEditorV2StateSnapshot()
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCommand.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCommand.tsx
index 16d87c701e7..4fa114167bf 100644
--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCommand.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterCommand.tsx
@@ -66,9 +66,6 @@ export function DataTableFilterCommand({
(x) => typeof x.value === 'string' && currentWord.includes(`${x.value}:`)
)
- // [Joshen] Temporarily disabling as this conflicts with our current CMD K behaviour
- // useHotKey(() => setOpen((open) => !open), 'k')
-
useEffect(() => {
// TODO: we could check for ARRAY_DELIMITER or SLIDER_DELIMITER to auto-set filter when typing
if (currentWord !== '' && open) return
diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControlsDrawer.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControlsDrawer.tsx
index ec2ae977248..90ba86a9119 100644
--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControlsDrawer.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControlsDrawer.tsx
@@ -19,15 +19,16 @@ import {
import { useMediaQuery } from '../hooks/useMediaQuery'
import { Kbd } from '../primitives/Kbd'
import { DataTableFilterControls } from './DataTableFilterControls'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
export function DataTableFilterControlsDrawer() {
const triggerButtonRef = useRef<HTMLButtonElement>(null)
const isMobile = useMediaQuery('(max-width: 640px)')
- useHotKey(() => {
+ useShortcut(SHORTCUT_IDS.DATA_TABLE_TOGGLE_FILTERS, () => {
triggerButtonRef.current?.click()
- }, 'b')
+ })
return (
<Drawer>
diff --git a/apps/studio/components/ui/DataTable/DataTableInfinite.tsx b/apps/studio/components/ui/DataTable/DataTableInfinite.tsx
index 5da20eb0918..824cdfc4aa3 100644
--- a/apps/studio/components/ui/DataTable/DataTableInfinite.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableInfinite.tsx
@@ -9,7 +9,8 @@ import { Button, cn } from 'ui'
import { formatCompactNumber } from './DataTable.utils'
import { useDataTable } from './providers/DataTableProvider'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './Table'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
// TODO: add a possible chartGroupBy
export interface DataTableInfiniteProps<TData, TValue, TMeta> {
@@ -64,10 +65,10 @@ export function DataTableInfinite<TData, TValue, TMeta>({
[fetchNextPage, isFetching, totalRows, totalRowsFetched]
)
- useHotKey(() => {
+ useShortcut(SHORTCUT_IDS.DATA_TABLE_RESET_COLUMNS, () => {
setColumnOrder([])
setColumnVisibility(defaultColumnVisibility)
- }, 'u')
+ })
return (
<Table ref={tableRef} onScroll={onScroll}>
diff --git a/apps/studio/components/ui/DataTable/DataTableResetButton.tsx b/apps/studio/components/ui/DataTable/DataTableResetButton.tsx
index a2a2b379e1d..17ca6c33af1 100644
--- a/apps/studio/components/ui/DataTable/DataTableResetButton.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableResetButton.tsx
@@ -3,11 +3,12 @@ import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { Kbd } from './primitives/Kbd'
import { useDataTable } from './providers/DataTableProvider'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
export function DataTableResetButton() {
const { table } = useDataTable()
- useHotKey(() => table.resetColumnFilters(), 'Escape')
+ useShortcut(SHORTCUT_IDS.DATA_TABLE_RESET_FILTERS, () => table.resetColumnFilters())
return (
<Tooltip>
diff --git a/apps/studio/components/ui/DataTable/DataTableToolbar.tsx b/apps/studio/components/ui/DataTable/DataTableToolbar.tsx
index e61f15f4722..8862e008ded 100644
--- a/apps/studio/components/ui/DataTable/DataTableToolbar.tsx
+++ b/apps/studio/components/ui/DataTable/DataTableToolbar.tsx
@@ -8,7 +8,8 @@ import { DataTableResetButton } from './DataTableResetButton'
import { DataTableViewOptions } from './DataTableViewOptions'
import { Kbd } from './primitives/Kbd'
import { useDataTable } from './providers/DataTableProvider'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
interface DataTableToolbarProps {
renderActions?: () => ReactNode
@@ -24,7 +25,7 @@ export function DataTableToolbar({
const { table, isLoading, columnFilters } = useDataTable()
const filters = table.getState().columnFilters
- useHotKey(() => setIsFilterBarOpen((prev) => !prev), 'b')
+ useShortcut(SHORTCUT_IDS.DATA_TABLE_TOGGLE_FILTERS, () => setIsFilterBarOpen((prev) => !prev))
const rows = useMemo(
() => ({
diff --git a/apps/studio/components/ui/DataTable/LiveButton.tsx b/apps/studio/components/ui/DataTable/LiveButton.tsx
index e361c591b53..247a379a319 100644
--- a/apps/studio/components/ui/DataTable/LiveButton.tsx
+++ b/apps/studio/components/ui/DataTable/LiveButton.tsx
@@ -5,7 +5,8 @@ import { useEffect } from 'react'
import { Button, cn } from 'ui'
import { useDataTable } from './providers/DataTableProvider'
-import { useHotKey } from '@/hooks/ui/useHotKey'
+import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
+import { useShortcut } from '@/state/shortcuts/useShortcut'
const REFRESH_INTERVAL = 10_000
@@ -17,7 +18,7 @@ interface LiveButtonProps {
export function LiveButton({ fetchPreviousPage, searchParamsParser }: LiveButtonProps) {
const [{ live, date, sort }, setSearch] = useQueryStates(searchParamsParser)
const { table } = useDataTable()
- useHotKey(handleClick, 'j')
+ useShortcut(SHORTCUT_IDS.DATA_TABLE_TOGGLE_LIVE, handleClick)
useEffect(() => {
let timeoutId: NodeJS.Timeout
diff --git a/apps/studio/hooks/ui/useHotKey.ts b/apps/studio/hooks/ui/useHotKey.ts
deleted file mode 100644
index cedb801e180..00000000000
--- a/apps/studio/hooks/ui/useHotKey.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useEffect } from 'react'
-import { useLatest } from 'react-use'
-
-/**
- * @deprecated Use `useShortcut` from `state/shortcuts/useShortcut` instead.
- * It reads from a central shortcut registry (`SHORTCUT_DEFINITIONS`) and
- * integrates with the user's enable/disable preferences + the Cmd+P command menu.
- *
- * Migration:
- * 1. Add an entry to `state/shortcuts/registry.ts` with a unique ID, label, and sequence.
- * 2. Replace `useHotKey(cb, 'k', { shift: true })` with
- * `useShortcut(SHORTCUT_IDS.YOUR_ID, cb)`.
- */
-function useHotKey(
- callback: (e: KeyboardEvent) => void,
- key: string,
- options?: { enabled?: boolean; shift?: boolean }
-): void
-/**
- * @deprecated Use `useShortcut` from `state/shortcuts/useShortcut` instead.
- * The `dependencies` parameter is also deprecated in this legacy hook.
- */
-function useHotKey(
- callback: (e: KeyboardEvent) => void,
- key: string,
- dependencies: unknown[],
- options?: { enabled?: boolean; shift?: boolean }
-): void
-function useHotKey(
- callback: (e: KeyboardEvent) => void,
- key: string,
- dependenciesOrOptions?: unknown[] | { enabled?: boolean; shift?: boolean },
- options?: { enabled?: boolean; shift?: boolean }
-): void {
- // Determine which overload was called
- const isDepsArray = Array.isArray(dependenciesOrOptions)
- const resolvedOptions = isDepsArray ? options : dependenciesOrOptions
- const enabled = resolvedOptions?.enabled ?? true
- const shift = resolvedOptions?.shift ?? false
-
- const enabledRef = useLatest(enabled)
- const callbackRef = useLatest(callback)
- const keyRef = useLatest(key)
- const shiftRef = useLatest(shift)
-
- useEffect(() => {
- function handler(e: KeyboardEvent) {
- if (!enabledRef.current) return
- if (
- (e.metaKey || e.ctrlKey) &&
- e.key.toLowerCase() === keyRef.current.toLowerCase() &&
- !e.altKey &&
- (shiftRef.current ? e.shiftKey : !e.shiftKey)
- ) {
- callbackRef.current(e)
- }
- }
-
- window.addEventListener('keydown', handler, true)
- return () => {
- window.removeEventListener('keydown', handler, true)
- }
- }, [callbackRef, enabledRef, keyRef, shiftRef])
-}
-
-export { useHotKey }
diff --git a/apps/studio/state/shortcuts/registry.ts b/apps/studio/state/shortcuts/registry.ts
index 542c01c5117..3d33e4dd102 100644
--- a/apps/studio/state/shortcuts/registry.ts
+++ b/apps/studio/state/shortcuts/registry.ts
@@ -10,11 +10,21 @@ import { ShortcutDefinition } from './types'
export const SHORTCUT_IDS = {
COMMAND_MENU_OPEN: 'command-menu.open',
AI_ASSISTANT_TOGGLE: 'ai-assistant.toggle',
+ AI_ASSISTANT_CANCEL_EDIT: 'ai-assistant.cancel-edit',
INLINE_EDITOR_TOGGLE: 'inline-editor.toggle',
RESULTS_COPY_MARKDOWN: 'results.copy-markdown',
RESULTS_COPY_JSON: 'results.copy-json',
RESULTS_COPY_CSV: 'results.copy-csv',
RESULTS_DOWNLOAD_CSV: 'results.download-csv',
+ DATA_TABLE_TOGGLE_FILTERS: 'data-table.toggle-filters',
+ DATA_TABLE_RESET_FILTERS: 'data-table.reset-filters',
+ DATA_TABLE_RESET_COLUMNS: 'data-table.reset-columns',
+ DATA_TABLE_TOGGLE_LIVE: 'data-table.toggle-live',
+ ACTION_BAR_SAVE: 'action-bar.save',
+ OPERATION_QUEUE_SAVE: 'operation-queue.save',
+ OPERATION_QUEUE_TOGGLE: 'operation-queue.toggle',
+ OPERATION_QUEUE_UNDO: 'operation-queue.undo',
+ UNIFIED_LOGS_RESET_FOCUS: 'unified-logs.reset-focus',
} as const
/**
@@ -79,4 +89,64 @@ export const SHORTCUT_DEFINITIONS: Record<ShortcutId, ShortcutDefinition> = {
label: 'Download results as CSV',
sequence: ['Mod+Shift+D'],
},
+ [SHORTCUT_IDS.AI_ASSISTANT_CANCEL_EDIT]: {
+ id: SHORTCUT_IDS.AI_ASSISTANT_CANCEL_EDIT,
+ label: 'Cancel AI Assistant edit',
+ sequence: ['Mod+Escape'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.DATA_TABLE_TOGGLE_FILTERS]: {
+ id: SHORTCUT_IDS.DATA_TABLE_TOGGLE_FILTERS,
+ label: 'Toggle data table filter controls',
+ sequence: ['Mod+B'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.DATA_TABLE_RESET_FILTERS]: {
+ id: SHORTCUT_IDS.DATA_TABLE_RESET_FILTERS,
+ label: 'Reset data table filters',
+ sequence: ['Mod+Escape'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.DATA_TABLE_RESET_COLUMNS]: {
+ id: SHORTCUT_IDS.DATA_TABLE_RESET_COLUMNS,
+ label: 'Reset data table columns',
+ sequence: ['Mod+U'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.DATA_TABLE_TOGGLE_LIVE]: {
+ id: SHORTCUT_IDS.DATA_TABLE_TOGGLE_LIVE,
+ label: 'Toggle live mode',
+ sequence: ['Mod+J'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.ACTION_BAR_SAVE]: {
+ id: SHORTCUT_IDS.ACTION_BAR_SAVE,
+ label: 'Save form',
+ sequence: ['Mod+Enter'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.OPERATION_QUEUE_SAVE]: {
+ id: SHORTCUT_IDS.OPERATION_QUEUE_SAVE,
+ label: 'Save pending table edits',
+ sequence: ['Mod+S'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.OPERATION_QUEUE_TOGGLE]: {
+ id: SHORTCUT_IDS.OPERATION_QUEUE_TOGGLE,
+ label: 'Toggle operation queue panel',
+ sequence: ['Mod+.'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.OPERATION_QUEUE_UNDO]: {
+ id: SHORTCUT_IDS.OPERATION_QUEUE_UNDO,
+ label: 'Undo latest table edit',
+ sequence: ['Mod+Z'],
+ showInSettings: false,
+ },
+ [SHORTCUT_IDS.UNIFIED_LOGS_RESET_FOCUS]: {
+ id: SHORTCUT_IDS.UNIFIED_LOGS_RESET_FOCUS,
+ label: 'Reset focus in logs',
+ sequence: ['Mod+.'],
+ showInSettings: false,
+ },
}