Files
supabase/apps/studio/state/shortcuts/useShortcut.tsx
Ali WaseemandDanny White 712cf7e60b feat(storage): add keyboard shortcuts for storage screens (#45837)
## Summary

Adds keyboard shortcuts to the Storage section, mirroring the
conventions already established for Auth Users and Database pages:

- **Storage navigation chords** (`S, F` / `S, A` / `S, V` / `S, 3`)
active only inside `StorageLayout`.
- **Files (bucket list) page** shortcuts for search, create, refresh,
reset filters, reset sort.
- **Storage Explorer** shortcuts for upload, new folder, view toggle,
refresh, search, multi-select download/move/delete, and an Escape
ladder.
- `ShortcutTooltip` wired into the relevant buttons so users can
discover keybinds on hover.
- Reload spinner is now driven by a shared store flag, so it shows
whether you click the button or fire the shortcut.

## Test plan

### Storage navigation chords
Active anywhere under `/project/<ref>/storage/*`.

| Keybind | Action |
|---------|--------|
| `S` then `F` | Go to Files |
| `S` then `A` | Go to Analytics buckets (platform + feature-flagged) |
| `S` then `V` | Go to Vector buckets (platform + feature-flagged) |
| `S` then `3` | Go to S3 settings (platform only) |

### Files (bucket list) page
At `/project/<ref>/storage/files`.

| Keybind | Action | Notes |
|---------|--------|-------|
| `Shift+F` | Focus search ("Search buckets") | Selects existing text |
| `Shift+N` | Create new bucket | Opens the create-bucket modal |
| `F` then `C` | Reset filters | Clears the search string |
| `Shift+R` | Refresh buckets | Refetches the bucket list |
| `S` then `C` | Reset bucket sort | Only fires when sort ≠ default
(Created at) |

### Storage Explorer (inside a bucket)
At `/project/<ref>/storage/files/buckets/<bucketId>`.

| Keybind | Action | Notes |
|---------|--------|-------|
| `Shift+F` | Focus search ("Search files") | Opens the search input if
hidden, then focuses |
| `Shift+R` | Refresh | Refetches all opened folders; spinner reflects
state |
| `I` then `F` | Upload files | Disabled w/o ` STORAGE_WRITE ` or at
bucket root with no folder |
| `I` then `N` | Create folder | Same permission gates as Upload |
| `V` then `C` | View as columns | |
| `V` then `L` | View as list | |
| `Shift+D` | Download selected | Only fires when ≥1 item selected;
single vs many handled |
| `Shift+M` | Move selected | Only fires when ≥1 item selected AND `
STORAGE_WRITE ` granted |
| `Mod+Backspace` | Delete selected | Only fires when ≥1 item selected
(` Mod ` = ⌘ on macOS / ` Ctrl ` on Win/Linux) |
| `Escape` | Clear selection | If ≥1 item selected |
| `Escape` | Close file preview | If no selection and preview pane open
|
| `Escape` | Close search | If no selection, no preview, and search is
open |

### Tips while testing
- [x] Chords (two-key sequences): press the first key, release, then
press the second key within ~1s
- [x] Hover any wired button (search, Refresh, Upload, Create folder,
View, Download, Move, Delete, the bucket Create button, sidebar items)
to see the keybind in a tooltip
- [x] Most actions also appear under "Shortcuts" in `Cmd+P`
- [x] Chords starting with a plain letter (` S, F ` / ` I, F ` / ` V, C
` / ` F, C ` / ` S, C `) won't fire while typing in an input — click out
first
- [x] `Escape` does fire from inside the search field (closes the
search)
- [x] `Cmd+/` opens the full shortcuts reference

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Keyboard shortcuts added across Storage: buckets (refresh, clear sort,
create, search), explorer (upload, create folder, refresh, download,
move, delete, clear search), and navigation shortcuts for
Files/Analytics/Vectors/S3.
* **UI**
* Shortcut keytips/tooltips added to relevant buttons and menu items for
discoverability.
* **Documentation/Tests**
  * Shortcut reference sheet labels updated and covered by a new test.

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/45837)
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Danny White <3104761+dnywh@users.noreply.github.com>
2026-05-13 08:26:04 -06:00

147 lines
5.7 KiB
TypeScript

import { useHotkeySequence, type HotkeyMeta } from '@tanstack/react-hotkeys'
import { Fragment, useCallback, useMemo } from 'react'
import { KeyboardShortcut } from 'ui'
import { useRegisterCommands, useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
import type { ICommand } from 'ui-patterns/CommandMenu/api/types'
import { SHORTCUT_DEFINITIONS, SHORTCUT_IDS, type ShortcutId } from './registry'
import type { ShortcutOptions } from './types'
import { useIsShortcutEnabled } from './useIsShortcutEnabled'
import { COMMAND_MENU_SECTIONS } from '@/components/interfaces/App/CommandMenu/CommandMenu.utils'
import useLatest from '@/hooks/misc/useLatest'
/**
* Shape we store on each registration's `options.meta` so the Keyboard
* shortcuts reference sheet can read it back via `useHotkeyRegistrations()`.
* The library's `HotkeyMeta` is open for declaration merging, but we don't
* own a direct dep on `@tanstack/hotkeys`, so we keep the extension local.
*/
export interface ShortcutHotkeyMeta extends HotkeyMeta {
id: ShortcutId
referenceGroup?: string
}
const hotkeyToKeys = (hotkey: string): string[] =>
hotkey.split('+').map((part) => (part === 'Mod' ? 'Meta' : part))
const orderShortcutCommands = (commands: ICommand[], commandsToInsert: ICommand[]): ICommand[] => {
const mergedCommands = [...commands, ...commandsToInsert]
return mergedCommands.sort((a, b) => {
if (a.id === SHORTCUT_IDS.SHORTCUTS_OPEN_REFERENCE) return 1
if (b.id === SHORTCUT_IDS.SHORTCUTS_OPEN_REFERENCE) return -1
return 0
})
}
/**
* Subscribe to a registered keyboard shortcut.
*
* Looks up the shortcut's `sequence` and `label` from `SHORTCUT_DEFINITIONS`,
* wires up a global hotkey listener via `@tanstack/react-hotkeys`, and
* (optionally) registers the shortcut as an entry in the Cmd+P command menu
* under the "Shortcuts" section for as long as the hook is mounted.
*
* Option resolution priority (highest first):
* 1. `options` passed to this hook
* 2. `def.options` from the registry entry
* 3. Hard-coded fallbacks (`enabled: true`, `timeout: undefined`, `registerInCommandMenu: false`)
*
* `enabled` is ANDed with the user's global enable/disable preference — if the
* user has disabled the shortcut in Preferences, it won't fire even if the
* caller or registry say `enabled: true`.
*
* @param id The registered shortcut to bind to. See `SHORTCUT_IDS`.
* @param callback Runs when the sequence matches. Always calls the latest
* reference — no stale closure issues.
* @param options Per-mount overrides. See `ShortcutOptions`.
*
* @example
* useShortcut(SHORTCUT_IDS.RESULTS_COPY_MARKDOWN, handleCopy)
*
* @example
* // Surface in Cmd+P while this component is mounted:
* useShortcut(SHORTCUT_IDS.SQL_EDITOR_RUN, runQuery, {
* registerInCommandMenu: true,
* })
*
* @example
* // Gate on local state — disables hotkey AND hides Cmd+P entry when false:
* useShortcut(SHORTCUT_IDS.SAVE, handleSave, {
* enabled: hasUnsavedChanges,
* registerInCommandMenu: true,
* })
*/
export function useShortcut(id: ShortcutId, callback: () => void, options?: ShortcutOptions) {
const def = SHORTCUT_DEFINITIONS[id]
// Handle override for the shortcut
const globallyEnabled = useIsShortcutEnabled(id)
const callerEnabled = options?.enabled ?? def.options?.enabled ?? true
const enabled = globallyEnabled && callerEnabled
const timeout = options?.timeout ?? def.options?.timeout ?? undefined
const ignoreInputs = options?.ignoreInputs ?? def.options?.ignoreInputs
const registerInCommandMenu =
options?.registerInCommandMenu ?? def.options?.registerInCommandMenu ?? false
const label = options?.label ?? def.label
const conflictBehavior = options?.conflictBehavior ?? def.options?.conflictBehavior
// Stable identity so we don't churn the registration store on every render.
// setOptions in @tanstack/hotkeys notifies subscribers each call, which
// would cascade to every component using useHotkeyRegistrations().
const meta = useMemo<ShortcutHotkeyMeta>(
() => ({ id, name: label, referenceGroup: def.referenceGroup }),
[def.referenceGroup, id, label]
)
// Only include `ignoreInputs` when set. The library resolves it to a concrete
// boolean at register time (false for Meta/Ctrl/Escape, true otherwise), but
// its setOptions does an object spread on every re-render — passing
// `ignoreInputs: undefined` would overwrite the resolved value and re-enable
// the input-focus guard for shortcuts that should always fire.
useHotkeySequence(def.sequence, callback, {
enabled,
timeout,
meta,
...(ignoreInputs !== undefined && { ignoreInputs }),
...(conflictBehavior !== undefined && { conflictBehavior }),
})
// Handle overrides for command menu
const enabledInCommandMenu = enabled && registerInCommandMenu
const depsInCommandMenu = [enabled, label]
const callbackRef = useLatest(callback)
const setCommandMenuOpen = useSetCommandMenuOpen()
const stableAction = useCallback(() => {
setCommandMenuOpen(false)
callbackRef.current()
}, [callbackRef, setCommandMenuOpen])
useRegisterCommands(
COMMAND_MENU_SECTIONS.SHORTCUTS,
[
{
id,
name: label,
action: stableAction,
badge: () => (
<div className="flex items-center gap-1">
{def.sequence.map((step, i) => (
<Fragment key={i}>
{i > 0 && <span className="text-foreground-lighter text-[11px]">then</span>}
<KeyboardShortcut keys={hotkeyToKeys(step)} />
</Fragment>
))}
</div>
),
},
],
{
enabled: enabledInCommandMenu,
deps: depsInCommandMenu,
orderCommands: orderShortcutCommands,
sectionMeta: { priority: 1 },
}
)
}