mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Rebind the studio's keys from a settings dialog
The studio's keys were a fixed table, so the views, map toggles, zoom and node editor undo and redo could not be changed. The keys now come from a store the user rebinds in a settings dialog, saved to studio.json in the app's user data folder; tooltips, the view list, the hover card and the help dialog read the live keys, and a new key that another shortcut already uses is warned about. v3: 8930afbb3
This commit is contained in:
1 parent
eb2113b835
commit
a8aaa3c3cf
16 files changed
+698
-75
No files matched your search
@@ -1,10 +1,13 @@
|
||||
import { app, BrowserWindow, clipboard, ipcMain, nativeTheme, shell } from 'electron'
|
||||
import { readdir, readFile } from 'node:fs/promises'
|
||||
import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { BridgeConnection, ThemeChoice } from '../shared/bridge'
|
||||
import { dirname, join } from 'node:path'
|
||||
import type { BridgeConnection, StoredShortcuts, ThemeChoice } from '../shared/bridge'
|
||||
|
||||
const CONNECTION_FOLDER = join(homedir(), '.iris', 'studio', 'bridges')
|
||||
const SETTINGS_FILE = 'studio.json'
|
||||
const SHORTCUTS_KEY = 'shortcuts'
|
||||
const SETTINGS_INDENT = 2
|
||||
const LINK_PREFIX = 'iris-studio://'
|
||||
const DARK_BACKGROUND = '#1e1f22'
|
||||
const WINDOW_SIZE = { width: 1440, height: 880, minWidth: 820, minHeight: 520 }
|
||||
@@ -54,6 +57,29 @@ async function readConnection(name: string): Promise<BridgeConnection | null> {
|
||||
}
|
||||
}
|
||||
|
||||
function settingsPath(): string {
|
||||
return join(app.getPath('userData'), SETTINGS_FILE)
|
||||
}
|
||||
|
||||
async function readSettings(): Promise<Record<string, unknown>> {
|
||||
try {
|
||||
const settings: unknown = JSON.parse(await readFile(settingsPath(), 'utf8'))
|
||||
return typeof settings === 'object' && settings !== null && !Array.isArray(settings) ? (settings as Record<string, unknown>) : {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
async function saveShortcuts(shortcuts: StoredShortcuts): Promise<void> {
|
||||
try {
|
||||
const settings = { ...(await readSettings()), [SHORTCUTS_KEY]: shortcuts }
|
||||
await mkdir(dirname(settingsPath()), { recursive: true })
|
||||
await writeFile(settingsPath(), JSON.stringify(settings, null, SETTINGS_INDENT))
|
||||
} catch (failure) {
|
||||
console.error(`Could not save the studio shortcuts to ${settingsPath()}`, failure)
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow(): void {
|
||||
window = new BrowserWindow({
|
||||
...WINDOW_SIZE,
|
||||
@@ -117,6 +143,8 @@ if (!app.requestSingleInstanceLock()) {
|
||||
ipcMain.on('studio:set-theme', (_event, theme: ThemeChoice) => {
|
||||
nativeTheme.themeSource = theme
|
||||
})
|
||||
ipcMain.handle('studio:load-shortcuts', async () => (await readSettings())[SHORTCUTS_KEY] ?? {})
|
||||
ipcMain.on('studio:save-shortcuts', (_event, shortcuts: StoredShortcuts) => void saveShortcuts(shortcuts))
|
||||
ipcMain.on('studio:copy-text', (_event, text: string) => clipboard.writeText(text))
|
||||
|
||||
void app.whenReady().then(createWindow)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'
|
||||
import type { StudioHost, ThemeChoice } from '../shared/bridge'
|
||||
import type { StoredShortcuts, StudioHost, ThemeChoice } from '../shared/bridge'
|
||||
|
||||
const host: StudioHost = {
|
||||
listBridges: () => ipcRenderer.invoke('studio:list-bridges'),
|
||||
@@ -10,7 +10,9 @@ const host: StudioHost = {
|
||||
return () => ipcRenderer.removeListener('studio:link', forward)
|
||||
},
|
||||
setTheme: (theme: ThemeChoice) => ipcRenderer.send('studio:set-theme', theme),
|
||||
copyText: (text: string) => ipcRenderer.send('studio:copy-text', text)
|
||||
copyText: (text: string) => ipcRenderer.send('studio:copy-text', text),
|
||||
loadShortcuts: () => ipcRenderer.invoke('studio:load-shortcuts'),
|
||||
saveShortcuts: (shortcuts: StoredShortcuts) => ipcRenderer.send('studio:save-shortcuts', shortcuts)
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('studio', host)
|
||||
@@ -5,6 +5,7 @@ import type { WorldInfo } from './bridge/types'
|
||||
import { ConnectScreen } from './studio/ConnectScreen'
|
||||
import { MapStudio } from './studio/MapStudio'
|
||||
import { useTheme } from './studio/theme'
|
||||
import { shortcutStore } from './studio/useBindings'
|
||||
|
||||
interface Session {
|
||||
client: BridgeClient
|
||||
@@ -43,6 +44,10 @@ export function App(): React.JSX.Element {
|
||||
[connect]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void shortcutStore.load()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void window.studio.initialLink().then((link) => link !== null && connectLink(link))
|
||||
return window.studio.onLink(connectLink)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import type { ViewInfo } from '../bridge/types'
|
||||
import { MOUSE_HINTS, SHORTCUTS, VIEW_KEYS } from './shortcuts'
|
||||
import { MOUSE_HINTS, keyTextOf, shortcutRows, type ShortcutGroup } from './shortcuts'
|
||||
import { useBindings } from './useBindings'
|
||||
|
||||
interface HelpDialogProps {
|
||||
open: boolean
|
||||
@@ -9,13 +10,17 @@ interface HelpDialogProps {
|
||||
views: ViewInfo[]
|
||||
}
|
||||
|
||||
/** Every key and mouse gesture of the map. */
|
||||
const KEY_GROUPS: ShortcutGroup[] = ['Views', 'Everywhere', 'Map', 'Node editor']
|
||||
|
||||
/** Every key and mouse gesture of the map, with the keys as they are set now. */
|
||||
export function HelpDialog({ open, onOpenChange, views }: HelpDialogProps): React.JSX.Element {
|
||||
const viewRows = views.filter((view) => VIEW_KEYS[view.id] !== undefined).map((view) => ({ key: VIEW_KEYS[view.id], label: view.label }))
|
||||
const bindings = useBindings()
|
||||
const rows = shortcutRows(views)
|
||||
const groups = [
|
||||
{ title: 'Views', rows: [...viewRows, ...rowsOf('Views')] },
|
||||
{ title: 'Everywhere', rows: rowsOf('Everywhere') },
|
||||
{ title: 'Map', rows: rowsOf('Map') },
|
||||
...KEY_GROUPS.map((group) => ({
|
||||
title: group,
|
||||
rows: rows.filter((row) => row.group === group).map((row) => ({ key: keyTextOf(row.id, bindings), label: row.label })).filter((row) => row.key !== '')
|
||||
})),
|
||||
{ title: 'Mouse', rows: MOUSE_HINTS.map((hint) => ({ key: hint.gesture, label: hint.label })) }
|
||||
]
|
||||
return (
|
||||
@@ -43,7 +48,3 @@ export function HelpDialog({ open, onOpenChange, views }: HelpDialogProps): Reac
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function rowsOf(group: 'Views' | 'Everywhere' | 'Map'): { key: string; label: string }[] {
|
||||
return SHORTCUTS.filter((shortcut) => shortcut.group === group).map((shortcut) => ({ key: shortcut.keyText, label: shortcut.label }))
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import type { MapHover, MapLabel } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
import type { CanvasPoint } from './MapCanvas'
|
||||
import { PickRows, replacedParent } from './PickRows'
|
||||
import { shortcutFor } from './shortcuts'
|
||||
import { useKeyText } from './useBindings'
|
||||
|
||||
interface HoverCardProps {
|
||||
hover: MapHover
|
||||
@@ -28,6 +28,7 @@ interface Row {
|
||||
/** The spot under the cursor: its biome and ground, and with Shift held, the rest of what the server knows. */
|
||||
export function HoverCard({ hover, point, viewId, previewing, detailed, minY }: HoverCardProps): React.JSX.Element {
|
||||
const card = useRef<HTMLDivElement>(null)
|
||||
const highlightKey = useKeyText()('highlight')
|
||||
const [position, setPosition] = useState({ left: point.x + CURSOR_GAP_PIXELS, top: point.y + CURSOR_GAP_PIXELS })
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -73,7 +74,7 @@ export function HoverCard({ hover, point, viewId, previewing, detailed, minY }:
|
||||
))}
|
||||
<div className="mt-2.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
|
||||
{!detailed && <Hint keyText="Shift" label="More" />}
|
||||
<Hint keyText={shortcutFor('highlight').keyText} label="Highlight" />
|
||||
{highlightKey !== '' && <Hint keyText={highlightKey} label="Highlight" />}
|
||||
<Hint keyText="Alt+Click" label="Open file" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -16,9 +16,11 @@ import { PatternStudio } from './PatternStudio'
|
||||
import { SavedWorldStudio } from './SavedWorldStudio'
|
||||
import { SceneStudio } from './SceneStudio'
|
||||
import { WorldStudio3D } from './WorldStudio3D'
|
||||
import { actionForKey, isTypingInto, viewForKey, type ShortcutAction } from './shortcuts'
|
||||
import { isTypingInto, shortcutRows, viewOfShortcutId, windowShortcutFor, type ShortcutAction } from './shortcuts'
|
||||
import { ShortcutSettings } from './ShortcutSettings'
|
||||
import { StatusBar } from './StatusBar'
|
||||
import { StudioToolbar } from './StudioToolbar'
|
||||
import { useBindings } from './useBindings'
|
||||
import { usePickInspection } from './usePickInspection'
|
||||
import { ViewList } from './ViewList'
|
||||
|
||||
@@ -55,6 +57,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
const [hover, setHover] = useState<MapHover | null>(null)
|
||||
const [detailed, setDetailed] = useState(false)
|
||||
const [helpOpen, setHelpOpen] = useState(false)
|
||||
const [settingsOpen, setSettingsOpen] = useState(false)
|
||||
const [notice, setNotice] = useState<string | null>(null)
|
||||
const [connected, setConnected] = useState(true)
|
||||
const [preview, setPreview] = useState<string | null>(null)
|
||||
@@ -175,7 +178,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
[views, viewId, selectView, toggle, highlightUnderCursor, tell]
|
||||
)
|
||||
|
||||
useKeyboard(runShortcut, selectView, setDetailed, world)
|
||||
useKeyboard(runShortcut, selectView, setDetailed, views)
|
||||
|
||||
const teleport = useCallback(
|
||||
(point: CanvasPoint) => {
|
||||
@@ -218,6 +221,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
onRefresh={() => runShortcut('refresh')}
|
||||
onResetZoom={() => runShortcut('resetZoom')}
|
||||
onHelp={() => setHelpOpen(true)}
|
||||
onSettings={() => setSettingsOpen(true)}
|
||||
onDisconnect={onDisconnect}
|
||||
/>
|
||||
<div className="flex min-h-0 flex-1">
|
||||
@@ -288,6 +292,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
</div>
|
||||
<StatusBar viewLabel={statusLabel(view.label, previewName, showsMap ? null : sceneSummary)} status={showsMap ? status : null} notice={notice} usage={usage} />
|
||||
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={views} />
|
||||
<ShortcutSettings open={settingsOpen} onOpenChange={setSettingsOpen} views={views} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -463,25 +468,28 @@ function useKeyboard(
|
||||
runShortcut: (action: ShortcutAction) => void,
|
||||
selectView: (view: string) => void,
|
||||
setDetailed: (detailed: boolean) => void,
|
||||
world: WorldInfo
|
||||
views: ViewInfo[]
|
||||
): void {
|
||||
const bindings = useBindings()
|
||||
useEffect(() => {
|
||||
const rows = shortcutRows(views)
|
||||
const down = (event: KeyboardEvent): void => {
|
||||
if (event.key === 'Shift') {
|
||||
setDetailed(true)
|
||||
}
|
||||
if (event.ctrlKey || event.metaKey || event.altKey || isTypingInto(event.target)) {
|
||||
if (isTypingInto(event.target)) {
|
||||
return
|
||||
}
|
||||
const viewId = viewForKey(event.key)
|
||||
if (viewId !== null && world.views.some((view) => view.id === viewId)) {
|
||||
const id = windowShortcutFor(event, rows, bindings)
|
||||
if (id === null) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
const viewId = viewOfShortcutId(id)
|
||||
if (viewId === null) {
|
||||
runShortcut(id as ShortcutAction)
|
||||
} else {
|
||||
selectView(viewId)
|
||||
return
|
||||
}
|
||||
const action = actionForKey(event.key)
|
||||
if (action !== null) {
|
||||
event.preventDefault()
|
||||
runShortcut(action)
|
||||
}
|
||||
}
|
||||
const up = (event: KeyboardEvent): void => {
|
||||
@@ -498,5 +506,5 @@ function useKeyboard(
|
||||
window.removeEventListener('keyup', up)
|
||||
window.removeEventListener('blur', blur)
|
||||
}
|
||||
}, [runShortcut, selectView, setDetailed, world])
|
||||
}, [runShortcut, selectView, setDetailed, views, bindings])
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import { Button } from '@/components/ui/button'
|
||||
import type { GraphNode } from '../bridge/types'
|
||||
import type { NodeEditor } from '../editor/useNodeEditor'
|
||||
import { NodeCanvas } from './NodeCanvas'
|
||||
import { isTypingInto } from './shortcuts'
|
||||
import { isTypingInto, matches } from './shortcuts'
|
||||
import { useBindings } from './useBindings'
|
||||
|
||||
interface NodePaneProps {
|
||||
editor: NodeEditor
|
||||
@@ -65,6 +66,7 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps
|
||||
|
||||
function useEditorKeys(editor: NodeEditor, selected: GraphNode | null, locked: boolean): void {
|
||||
const { undo, redo, edit } = editor
|
||||
const bindings = useBindings()
|
||||
useEffect(() => {
|
||||
if (locked) {
|
||||
return
|
||||
@@ -73,15 +75,10 @@ function useEditorKeys(editor: NodeEditor, selected: GraphNode | null, locked: b
|
||||
if (isTypingInto(event.target)) {
|
||||
return
|
||||
}
|
||||
const command = event.ctrlKey || event.metaKey
|
||||
if (command && event.key.toLowerCase() === 'z') {
|
||||
if (matches(event, 'undo', bindings)) {
|
||||
event.preventDefault()
|
||||
if (event.shiftKey) {
|
||||
redo()
|
||||
} else {
|
||||
undo()
|
||||
}
|
||||
} else if (command && event.key.toLowerCase() === 'y') {
|
||||
undo()
|
||||
} else if (matches(event, 'redo', bindings)) {
|
||||
event.preventDefault()
|
||||
redo()
|
||||
} else if (event.key === 'Delete' && selected !== null && selected.duplicable) {
|
||||
@@ -91,5 +88,5 @@ function useEditorKeys(editor: NodeEditor, selected: GraphNode | null, locked: b
|
||||
}
|
||||
window.addEventListener('keydown', down)
|
||||
return () => window.removeEventListener('keydown', down)
|
||||
}, [undo, redo, edit, selected, locked])
|
||||
}, [undo, redo, edit, selected, locked, bindings])
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { ViewInfo } from '../bridge/types'
|
||||
import { chordOf, chordText, chordsOf, chordsText, clashesWith, defaultChords, shortcutRows, type ShortcutGroup, type ShortcutRow } from './shortcuts'
|
||||
import { shortcutStore, useBindings } from './useBindings'
|
||||
|
||||
interface ShortcutSettingsProps {
|
||||
open: boolean
|
||||
onOpenChange(open: boolean): void
|
||||
views: ViewInfo[]
|
||||
}
|
||||
|
||||
interface Note {
|
||||
text: string
|
||||
warning: boolean
|
||||
}
|
||||
|
||||
const GROUPS: ShortcutGroup[] = ['Views', 'Everywhere', 'Map', 'Node editor']
|
||||
const RECORDING_TEXT = 'Press a key…'
|
||||
const NO_KEYS_TEXT = 'None'
|
||||
|
||||
/** Every shortcut with its keys, rebound by clicking its keys and pressing the new one. Changes are saved at once. */
|
||||
export function ShortcutSettings({ open, onOpenChange, views }: ShortcutSettingsProps): React.JSX.Element {
|
||||
const bindings = useBindings()
|
||||
const rows = useMemo(() => shortcutRows(views), [views])
|
||||
const [recording, setRecording] = useState<ShortcutRow | null>(null)
|
||||
const [note, setNote] = useState<Note | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setRecording(null)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (recording === null) {
|
||||
return
|
||||
}
|
||||
const record = (event: KeyboardEvent): void => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const chord = chordOf(event)
|
||||
if (chord === null) {
|
||||
return
|
||||
}
|
||||
const clashes = clashesWith(recording, chord, rows, shortcutStore.snapshot())
|
||||
shortcutStore.rebind(recording.id, [chord])
|
||||
setRecording(null)
|
||||
setNote(
|
||||
clashes.length === 0
|
||||
? { text: `${recording.label} is now ${chordText(chord)}`, warning: false }
|
||||
: { text: `${chordText(chord)} is also ${clashes.map((clash) => clash.label).join(', ')}`, warning: true }
|
||||
)
|
||||
}
|
||||
window.addEventListener('keydown', record, true)
|
||||
return () => window.removeEventListener('keydown', record, true)
|
||||
}, [recording, rows])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[560px] bg-card">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-[15px]">Shortcuts</DialogTitle>
|
||||
<DialogDescription>Click a shortcut's keys, then press the new key. Esc can be chosen too; click the keys again to cancel.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex max-h-[60vh] flex-col gap-3 overflow-y-auto pr-1">
|
||||
{GROUPS.map((group) => (
|
||||
<section key={group}>
|
||||
<h3 className="mb-1 text-[11px] font-semibold text-muted-foreground">{group}</h3>
|
||||
{rows
|
||||
.filter((row) => row.group === group)
|
||||
.map((row) => (
|
||||
<ShortcutRowView
|
||||
key={row.id}
|
||||
row={row}
|
||||
keys={chordsOf(row.id, bindings)}
|
||||
changed={bindings[row.id] !== undefined}
|
||||
recording={recording?.id === row.id}
|
||||
onRecord={() => setRecording((current) => (current?.id === row.id ? null : row))}
|
||||
onReset={() => {
|
||||
setRecording(null)
|
||||
shortcutStore.reset(row.id)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
<DialogFooter className="items-center sm:justify-between">
|
||||
<span className={cn('min-w-0 flex-1 truncate text-[12px]', note?.warning ? 'text-warning' : 'text-secondary-text')}>{note?.text}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setRecording(null)
|
||||
setNote(null)
|
||||
shortcutStore.resetAll()
|
||||
}}
|
||||
>
|
||||
Reset all
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
interface ShortcutRowViewProps {
|
||||
row: ShortcutRow
|
||||
keys: string[]
|
||||
changed: boolean
|
||||
recording: boolean
|
||||
onRecord(): void
|
||||
onReset(): void
|
||||
}
|
||||
|
||||
function ShortcutRowView({ row, keys, changed, recording, onRecord, onReset }: ShortcutRowViewProps): React.JSX.Element {
|
||||
return (
|
||||
<div className="flex items-center gap-2 py-0.5">
|
||||
<span className="min-w-0 flex-1 truncate text-secondary-text" title={row.label}>
|
||||
{row.label}
|
||||
</span>
|
||||
<Button variant="outline" size="xs" className={cn('w-36', recording && 'border-ring')} onClick={onRecord} title="Click, then press the new key">
|
||||
{recording ? RECORDING_TEXT : keys.length === 0 ? NO_KEYS_TEXT : chordsText(keys)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="link"
|
||||
size="xs"
|
||||
className={cn('w-14 text-link', !changed && 'invisible')}
|
||||
onClick={onReset}
|
||||
title={chordsText(defaultChords(row.id)) || NO_KEYS_TEXT}
|
||||
>
|
||||
Default
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CircleHelp, Grid3x3, LocateFixed, LogOut, Monitor, Moon, Mountain, PawPrint, RefreshCw, Spline, Sun, ZoomIn } from 'lucide-react'
|
||||
import { CircleHelp, Grid3x3, LocateFixed, LogOut, Monitor, Moon, Mountain, PawPrint, RefreshCw, Settings, Spline, Sun, ZoomIn } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
@@ -8,7 +8,8 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
import type { WorldInfo } from '../bridge/types'
|
||||
import type { StudioToggles } from './MapStudio'
|
||||
import { shortcutFor, type ShortcutAction } from './shortcuts'
|
||||
import type { ShortcutAction } from './shortcuts'
|
||||
import { useKeyText } from './useBindings'
|
||||
|
||||
interface StudioToolbarProps {
|
||||
title: string
|
||||
@@ -22,6 +23,7 @@ interface StudioToolbarProps {
|
||||
onRefresh(): void
|
||||
onResetZoom(): void
|
||||
onHelp(): void
|
||||
onSettings(): void
|
||||
onDisconnect(): void
|
||||
}
|
||||
|
||||
@@ -46,6 +48,11 @@ export function StudioToolbar(props: StudioToolbarProps): React.JSX.Element {
|
||||
<ToolButton action="help" hint="Show every mouse and key shortcut" onClick={props.onHelp}>
|
||||
<CircleHelp />
|
||||
</ToolButton>
|
||||
<IconHint hint="Change the studio's keys">
|
||||
<Button variant="ghost" size="icon-sm" onClick={props.onSettings}>
|
||||
<Settings />
|
||||
</Button>
|
||||
</IconHint>
|
||||
<IconHint hint="Back to the world list">
|
||||
<Button variant="ghost" size="icon-sm" onClick={props.onDisconnect}>
|
||||
<LogOut />
|
||||
@@ -91,15 +98,16 @@ function IconHint({ hint, keyText, children }: { hint: string; keyText?: string;
|
||||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||||
<TooltipContent className="flex items-center gap-2">
|
||||
{hint}
|
||||
{keyText !== undefined && <Kbd>{keyText}</Kbd>}
|
||||
{keyText !== undefined && keyText !== '' && <Kbd>{keyText}</Kbd>}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function ToolButton({ action, hint, onClick, children }: { action: ShortcutAction; hint: string; onClick(): void; children: ReactNode }): React.JSX.Element {
|
||||
const keyText = useKeyText()
|
||||
return (
|
||||
<IconHint hint={hint} keyText={shortcutFor(action).keyText}>
|
||||
<IconHint hint={hint} keyText={keyText(action)}>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onClick}>
|
||||
{children}
|
||||
</Button>
|
||||
@@ -117,8 +125,9 @@ interface ToolToggleProps {
|
||||
}
|
||||
|
||||
function ToolToggle({ action, hint, pressed, disabled, onPressed, children }: ToolToggleProps): React.JSX.Element {
|
||||
const keyText = useKeyText()
|
||||
return (
|
||||
<IconHint hint={disabled ? 'This server has no players to show' : hint} keyText={shortcutFor(action).keyText}>
|
||||
<IconHint hint={disabled ? 'This server has no players to show' : hint} keyText={keyText(action)}>
|
||||
<span>
|
||||
<Toggle
|
||||
size="sm"
|
||||
|
||||
@@ -3,7 +3,8 @@ import { Kbd } from '@/components/ui/kbd'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { ViewInfo } from '../bridge/types'
|
||||
import { VIEW_KEYS } from './shortcuts'
|
||||
import { viewShortcutId } from './shortcuts'
|
||||
import { useKeyText } from './useBindings'
|
||||
|
||||
const VIEW_ICONS: Record<string, LucideIcon> = {
|
||||
biomes: Trees,
|
||||
@@ -54,6 +55,7 @@ export function ViewList({ views, current, onSelect, children }: ViewListProps):
|
||||
|
||||
function ViewRow({ view, selected, onSelect }: { view: ViewInfo; selected: boolean; onSelect(): void }): React.JSX.Element {
|
||||
const Icon = VIEW_ICONS[view.id] ?? MapIcon
|
||||
const keyText = useKeyText()(viewShortcutId(view.id))
|
||||
return (
|
||||
<button
|
||||
onClick={onSelect}
|
||||
@@ -64,7 +66,7 @@ function ViewRow({ view, selected, onSelect }: { view: ViewInfo; selected: boole
|
||||
<span className="block font-medium">{view.label}</span>
|
||||
<span className="block text-[11.5px] leading-snug text-secondary-text">{view.description}</span>
|
||||
</span>
|
||||
{VIEW_KEYS[view.id] !== undefined && <Kbd className="mt-0.5">{VIEW_KEYS[view.id]}</Kbd>}
|
||||
{keyText !== '' && <Kbd className="mt-0.5">{keyText}</Kbd>}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createShortcutStore, type ShortcutStorage } from './shortcutStore'
|
||||
import type { Bindings } from './shortcuts'
|
||||
|
||||
function storageHolding(stored: unknown): ShortcutStorage & { saved: Bindings[] } {
|
||||
const saved: Bindings[] = []
|
||||
return { saved, load: () => Promise.resolve(stored), save: (bindings) => void saved.push(bindings) }
|
||||
}
|
||||
|
||||
describe('createShortcutStore', () => {
|
||||
it('starts with the defaults and reads the saved keys on load', async () => {
|
||||
const store = createShortcutStore(storageHolding({ grid: ['x'], help: 'nonsense' }))
|
||||
expect(store.snapshot()).toEqual({})
|
||||
|
||||
await store.load()
|
||||
|
||||
expect(store.snapshot()).toEqual({ grid: ['x'] })
|
||||
})
|
||||
|
||||
it('keeps the defaults when the saved keys cannot be read', async () => {
|
||||
const store = createShortcutStore({ load: () => Promise.reject(new Error('unreadable')), save: () => undefined })
|
||||
await store.load()
|
||||
expect(store.snapshot()).toEqual({})
|
||||
})
|
||||
|
||||
it('saves and announces every change', () => {
|
||||
const storage = storageHolding({})
|
||||
const store = createShortcutStore(storage)
|
||||
let announced = 0
|
||||
store.subscribe(() => announced++)
|
||||
|
||||
store.rebind('grid', ['x'])
|
||||
store.rebind('redo', [])
|
||||
|
||||
expect(store.snapshot()).toEqual({ grid: ['x'], redo: [] })
|
||||
expect(storage.saved).toEqual([{ grid: ['x'] }, { grid: ['x'], redo: [] }])
|
||||
expect(announced).toBe(2)
|
||||
})
|
||||
|
||||
it('drops a binding that is the default again, and resets one or all', () => {
|
||||
const storage = storageHolding({})
|
||||
const store = createShortcutStore(storage)
|
||||
store.rebind('grid', ['x'])
|
||||
store.rebind('zoomIn', ['z'])
|
||||
|
||||
store.rebind('grid', ['g'])
|
||||
expect(store.snapshot()).toEqual({ zoomIn: ['z'] })
|
||||
|
||||
store.reset('zoomIn')
|
||||
store.reset('zoomIn')
|
||||
expect(store.snapshot()).toEqual({})
|
||||
expect(storage.saved).toHaveLength(4)
|
||||
|
||||
store.rebind('grid', ['x'])
|
||||
store.resetAll()
|
||||
expect(store.snapshot()).toEqual({})
|
||||
})
|
||||
|
||||
it('stops announcing to a listener that unsubscribed', () => {
|
||||
const store = createShortcutStore(storageHolding({}))
|
||||
let announced = 0
|
||||
const unsubscribe = store.subscribe(() => announced++)
|
||||
unsubscribe()
|
||||
store.rebind('grid', ['x'])
|
||||
expect(announced).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { defaultChords, sanitizeBindings, type Bindings, type Chord } from './shortcuts'
|
||||
|
||||
/** Where the rebound keys are kept between runs. */
|
||||
export interface ShortcutStorage {
|
||||
load(): Promise<unknown>
|
||||
save(bindings: Bindings): void
|
||||
}
|
||||
|
||||
export interface ShortcutStore {
|
||||
snapshot(): Bindings
|
||||
subscribe(listener: () => void): () => void
|
||||
/** Reads the saved keys; the defaults stay when there are none or they cannot be read. */
|
||||
load(): Promise<void>
|
||||
rebind(id: string, chords: Chord[]): void
|
||||
reset(id: string): void
|
||||
resetAll(): void
|
||||
}
|
||||
|
||||
/** The keys the user rebound, saved at each change and shared with every component that shows or reads a key. */
|
||||
export function createShortcutStore(storage: ShortcutStorage): ShortcutStore {
|
||||
let bindings: Bindings = {}
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
const publish = (next: Bindings): void => {
|
||||
bindings = next
|
||||
listeners.forEach((listener) => listener())
|
||||
}
|
||||
const change = (next: Bindings): void => {
|
||||
publish(next)
|
||||
storage.save(next)
|
||||
}
|
||||
const rebind = (id: string, chords: Chord[]): void => {
|
||||
if (sameChords(chords, defaultChords(id))) {
|
||||
reset(id)
|
||||
return
|
||||
}
|
||||
change({ ...bindings, [id]: chords })
|
||||
}
|
||||
const reset = (id: string): void => {
|
||||
if (bindings[id] === undefined) {
|
||||
return
|
||||
}
|
||||
const rest = { ...bindings }
|
||||
delete rest[id]
|
||||
change(rest)
|
||||
}
|
||||
|
||||
return {
|
||||
snapshot: () => bindings,
|
||||
subscribe(listener) {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
},
|
||||
async load() {
|
||||
try {
|
||||
publish(sanitizeBindings(await storage.load()))
|
||||
} catch {
|
||||
publish({})
|
||||
}
|
||||
},
|
||||
rebind,
|
||||
reset,
|
||||
resetAll: () => change({})
|
||||
}
|
||||
}
|
||||
|
||||
function sameChords(first: Chord[], second: Chord[]): boolean {
|
||||
return first.length === second.length && first.every((chord, index) => chord === second[index])
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
SHORTCUTS,
|
||||
chordOf,
|
||||
chordText,
|
||||
clashesWith,
|
||||
defaultChords,
|
||||
isChord,
|
||||
keyTextOf,
|
||||
matches,
|
||||
sanitizeBindings,
|
||||
shortcutRows,
|
||||
viewShortcutId,
|
||||
windowShortcutFor,
|
||||
type KeyPress
|
||||
} from './shortcuts'
|
||||
|
||||
const DEFAULT_VIEWS = ['biomes', 'regions', 'height', 'landBiomes', 'seaBiomes', 'caveBiomes'].map((id) => ({ id, label: id }))
|
||||
const ROWS = shortcutRows(DEFAULT_VIEWS)
|
||||
|
||||
function press(key: string, modifiers: Partial<Omit<KeyPress, 'key'>> = {}): KeyPress {
|
||||
return { key, ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, ...modifiers }
|
||||
}
|
||||
|
||||
describe('shortcuts', () => {
|
||||
it('never gives two shortcuts that work together the same default key', () => {
|
||||
for (const row of ROWS) {
|
||||
for (const chord of defaultChords(row.id)) {
|
||||
expect(clashesWith(row, chord, ROWS, {}).map((clash) => clash.id), `${row.id} ${chord}`).toEqual([])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('writes every default key as a chord that reads back as itself', () => {
|
||||
for (const row of ROWS) {
|
||||
for (const chord of defaultChords(row.id)) {
|
||||
expect(isChord(chord), `${row.id} ${chord}`).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('makes a chord of a key press, folding Cmd into Ctrl and keeping shift for letters only', () => {
|
||||
expect(chordOf(press('Z', { ctrlKey: true, shiftKey: true }))).toBe('ctrl+shift+z')
|
||||
expect(chordOf(press('z', { metaKey: true }))).toBe('ctrl+z')
|
||||
expect(chordOf(press('M'))).toBe('m')
|
||||
expect(chordOf(press('?', { shiftKey: true }))).toBe('?')
|
||||
expect(chordOf(press('ArrowLeft', { shiftKey: true, altKey: true }))).toBe('alt+shift+ArrowLeft')
|
||||
expect(chordOf(press('Shift', { shiftKey: true }))).toBeNull()
|
||||
})
|
||||
|
||||
it('shows chords as people write them', () => {
|
||||
expect(chordText('ctrl+shift+z')).toBe('Ctrl+Shift+Z')
|
||||
expect(chordText('Escape')).toBe('Esc')
|
||||
expect(chordText('=')).toBe('=')
|
||||
expect(chordText('ctrl++')).toBe('Ctrl++')
|
||||
expect(chordText('ArrowUp')).toBe('Up')
|
||||
expect(chordText(' ')).toBe('Space')
|
||||
})
|
||||
|
||||
it('finds the window shortcut a key press triggers, by default and once rebound', () => {
|
||||
expect(windowShortcutFor(press('g'), ROWS, {})).toBe('grid')
|
||||
expect(windowShortcutFor(press('1'), ROWS, {})).toBe(viewShortcutId('biomes'))
|
||||
expect(windowShortcutFor(press('z', { ctrlKey: true }), ROWS, {})).toBeNull()
|
||||
expect(windowShortcutFor(press('g'), ROWS, { grid: ['x'] })).toBeNull()
|
||||
expect(windowShortcutFor(press('x'), ROWS, { grid: ['x'] })).toBe('grid')
|
||||
expect(windowShortcutFor(press('4'), ROWS, { [viewShortcutId('biomes')]: ['4'] })).toBe(viewShortcutId('biomes'))
|
||||
})
|
||||
|
||||
it('leaves a shortcut with no keys unreachable', () => {
|
||||
expect(windowShortcutFor(press('g'), ROWS, { grid: [] })).toBeNull()
|
||||
expect(keyTextOf('grid', { grid: [] })).toBe('')
|
||||
})
|
||||
|
||||
it('shows the first key of a shortcut', () => {
|
||||
expect(keyTextOf('redo', {})).toBe('Ctrl+Y')
|
||||
expect(keyTextOf('redo', { redo: ['ctrl+shift+z'] })).toBe('Ctrl+Shift+Z')
|
||||
expect(keyTextOf(viewShortcutId('noise'), {})).toBe('')
|
||||
})
|
||||
|
||||
it('matches the node editor keys by the live bindings', () => {
|
||||
expect(matches(press('z', { ctrlKey: true }), 'undo', {})).toBe(true)
|
||||
expect(matches(press('z', { ctrlKey: true, shiftKey: true }), 'redo', {})).toBe(true)
|
||||
expect(matches(press('z', { ctrlKey: true }), 'undo', { undo: ['ctrl+u'] })).toBe(false)
|
||||
expect(matches(press('Control', { ctrlKey: true }), 'undo', {})).toBe(false)
|
||||
})
|
||||
|
||||
it('reports the shortcuts a new key would clash with, only where both work together', () => {
|
||||
const grid = ROWS.find((row) => row.id === 'grid')!
|
||||
const undo = ROWS.find((row) => row.id === 'undo')!
|
||||
expect(clashesWith(grid, 'h', ROWS, {}).map((clash) => clash.id)).toEqual(['highlight'])
|
||||
expect(clashesWith(grid, 'ctrl+z', ROWS, {})).toEqual([])
|
||||
expect(clashesWith(undo, 'Escape', ROWS, {}).map((clash) => clash.id)).toEqual(['dismiss'])
|
||||
expect(clashesWith(undo, 'g', ROWS, {})).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps only lists of chords from a settings file', () => {
|
||||
expect(sanitizeBindings({ grid: ['x', 'ctrl+x'], zoomIn: 'x', help: ['ctrl+Z'], undo: [], redo: ['a', 'a'] })).toEqual({
|
||||
grid: ['x', 'ctrl+x'],
|
||||
undo: [],
|
||||
redo: ['a']
|
||||
})
|
||||
expect(sanitizeBindings(null)).toEqual({})
|
||||
expect(sanitizeBindings(['grid'])).toEqual({})
|
||||
})
|
||||
|
||||
it('gives every shortcut a label and a default key', () => {
|
||||
expect(SHORTCUTS.every((shortcut) => shortcut.label !== '' && shortcut.chords.length > 0)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -13,34 +13,53 @@ export type ShortcutAction =
|
||||
| 'shading'
|
||||
| 'borders'
|
||||
| 'help'
|
||||
| 'undo'
|
||||
| 'redo'
|
||||
|
||||
export interface Shortcut {
|
||||
action: ShortcutAction
|
||||
export type ShortcutGroup = 'Views' | 'Everywhere' | 'Map' | 'Node editor'
|
||||
|
||||
/**
|
||||
* A key press as text: the modifiers in the order ctrl, alt, shift, then the key as {@code KeyboardEvent.key} names it,
|
||||
* lowercase when it is a letter. Ctrl stands for Cmd too, and shift is only kept for letters and named keys, as a
|
||||
* symbol such as ? already says it.
|
||||
*/
|
||||
export type Chord = string
|
||||
|
||||
/** The keys a user set, by shortcut id; a shortcut missing here keeps its default keys. */
|
||||
export type Bindings = Record<string, Chord[]>
|
||||
|
||||
/** What the settings and help dialogs list: a studio shortcut, or the key that opens one view. */
|
||||
export interface ShortcutRow {
|
||||
id: string
|
||||
label: string
|
||||
group: 'Views' | 'Everywhere' | 'Map'
|
||||
/** The key as shown, then every KeyboardEvent.key that triggers it. */
|
||||
keyText: string
|
||||
keys: string[]
|
||||
group: ShortcutGroup
|
||||
}
|
||||
|
||||
export const SHORTCUTS: Shortcut[] = [
|
||||
{ action: 'nextView', label: 'Next view', group: 'Views', keyText: 'M', keys: ['m'] },
|
||||
{ action: 'refresh', label: 'Redraw the map with the latest pack files', group: 'Everywhere', keyText: 'R', keys: ['r'] },
|
||||
{ action: 'zoomIn', label: 'Zoom in', group: 'Everywhere', keyText: '=', keys: ['=', '+'] },
|
||||
{ action: 'zoomOut', label: 'Zoom out', group: 'Everywhere', keyText: '-', keys: ['-'] },
|
||||
{ action: 'resetZoom', label: 'Reset zoom', group: 'Everywhere', keyText: '\\', keys: ['\\'] },
|
||||
{ action: 'dismiss', label: 'Clear the highlight', group: 'Everywhere', keyText: 'Esc', keys: ['Escape'] },
|
||||
{ action: 'follow', label: 'Follow your player', group: 'Map', keyText: 'F', keys: ['f'] },
|
||||
{ action: 'grid', label: 'Chunk and region grid', group: 'Map', keyText: 'G', keys: ['g'] },
|
||||
{ action: 'entities', label: 'Show entities', group: 'Map', keyText: 'E', keys: ['e'] },
|
||||
{ action: 'highlight', label: 'Highlight what is under the cursor', group: 'Map', keyText: 'H', keys: ['h'] },
|
||||
{ action: 'shading', label: 'Terrain shading', group: 'Map', keyText: 'S', keys: ['s'] },
|
||||
{ action: 'borders', label: 'Region borders', group: 'Map', keyText: 'B', keys: ['b'] },
|
||||
{ action: 'help', label: 'Show the shortcuts', group: 'Map', keyText: '/', keys: ['/', '?'] }
|
||||
interface ShortcutDefinition extends ShortcutRow {
|
||||
id: ShortcutAction
|
||||
chords: Chord[]
|
||||
}
|
||||
|
||||
export const SHORTCUTS: ShortcutDefinition[] = [
|
||||
{ id: 'nextView', label: 'Next view', group: 'Views', chords: ['m'] },
|
||||
{ id: 'refresh', label: 'Redraw the map with the latest pack files', group: 'Everywhere', chords: ['r'] },
|
||||
{ id: 'zoomIn', label: 'Zoom in', group: 'Everywhere', chords: ['=', '+'] },
|
||||
{ id: 'zoomOut', label: 'Zoom out', group: 'Everywhere', chords: ['-'] },
|
||||
{ id: 'resetZoom', label: 'Reset zoom', group: 'Everywhere', chords: ['\\'] },
|
||||
{ id: 'dismiss', label: 'Clear the highlight', group: 'Everywhere', chords: ['Escape'] },
|
||||
{ id: 'follow', label: 'Follow your player', group: 'Map', chords: ['f'] },
|
||||
{ id: 'grid', label: 'Chunk and region grid', group: 'Map', chords: ['g'] },
|
||||
{ id: 'entities', label: 'Show entities', group: 'Map', chords: ['e'] },
|
||||
{ id: 'highlight', label: 'Highlight what is under the cursor', group: 'Map', chords: ['h'] },
|
||||
{ id: 'shading', label: 'Terrain shading', group: 'Map', chords: ['s'] },
|
||||
{ id: 'borders', label: 'Region borders', group: 'Map', chords: ['b'] },
|
||||
{ id: 'help', label: 'Show the shortcuts', group: 'Map', chords: ['/', '?'] },
|
||||
{ id: 'undo', label: 'Undo', group: 'Node editor', chords: ['ctrl+z'] },
|
||||
{ id: 'redo', label: 'Redo', group: 'Node editor', chords: ['ctrl+y', 'ctrl+shift+z'] }
|
||||
]
|
||||
|
||||
/** The key of each view; 4 stays free for the 3D world, as in v3e. */
|
||||
export const VIEW_KEYS: Record<string, string> = {
|
||||
const VIEW_KEYS: Record<string, Chord> = {
|
||||
biomes: '1',
|
||||
regions: '2',
|
||||
height: '3',
|
||||
@@ -58,20 +77,162 @@ export const MOUSE_HINTS: { gesture: string; label: string }[] = [
|
||||
{ gesture: 'Right click', label: 'Highlight, teleport, open or copy' }
|
||||
]
|
||||
|
||||
export function shortcutFor(action: ShortcutAction): Shortcut {
|
||||
return SHORTCUTS.find((shortcut) => shortcut.action === action)!
|
||||
/**
|
||||
* The window's own keys work anywhere in it, while the node editor takes its keys first while it is shown, so two
|
||||
* shortcuts only clash when both are window keys or both are node editor keys.
|
||||
*/
|
||||
const GROUP_SCOPES: Record<ShortcutGroup, { windowWide: boolean; nodeEditor: boolean }> = {
|
||||
Views: { windowWide: true, nodeEditor: false },
|
||||
Everywhere: { windowWide: true, nodeEditor: true },
|
||||
Map: { windowWide: true, nodeEditor: false },
|
||||
'Node editor': { windowWide: false, nodeEditor: true }
|
||||
}
|
||||
|
||||
export function actionForKey(key: string): ShortcutAction | null {
|
||||
const pressed = key.length === 1 ? key.toLowerCase() : key
|
||||
return SHORTCUTS.find((shortcut) => shortcut.keys.includes(pressed))?.action ?? null
|
||||
const VIEW_ID_PREFIX = 'view:'
|
||||
const MODIFIER_PREFIXES = ['ctrl+', 'alt+', 'shift+'] as const
|
||||
const MODIFIER_KEYS = new Set(['Control', 'Shift', 'Alt', 'Meta', 'AltGraph', 'CapsLock', 'Dead', 'Unidentified'])
|
||||
const KEY_NAMES: Record<string, string> = { Escape: 'Esc', ' ': 'Space' }
|
||||
const ARROW_PREFIX = 'Arrow'
|
||||
|
||||
export interface KeyPress {
|
||||
key: string
|
||||
ctrlKey: boolean
|
||||
metaKey: boolean
|
||||
altKey: boolean
|
||||
shiftKey: boolean
|
||||
}
|
||||
|
||||
export function viewForKey(key: string): string | null {
|
||||
return Object.entries(VIEW_KEYS).find(([, viewKey]) => viewKey === key)?.[0] ?? null
|
||||
export function viewShortcutId(viewId: string): string {
|
||||
return VIEW_ID_PREFIX + viewId
|
||||
}
|
||||
|
||||
export function viewOfShortcutId(id: string): string | null {
|
||||
return id.startsWith(VIEW_ID_PREFIX) ? id.slice(VIEW_ID_PREFIX.length) : null
|
||||
}
|
||||
|
||||
/** Every shortcut to list, the views first as they head the Views group. */
|
||||
export function shortcutRows(views: { id: string; label: string }[]): ShortcutRow[] {
|
||||
return [...views.map((view) => ({ id: viewShortcutId(view.id), label: view.label, group: 'Views' as const })), ...SHORTCUTS]
|
||||
}
|
||||
|
||||
export function defaultChords(id: string): Chord[] {
|
||||
const viewId = viewOfShortcutId(id)
|
||||
if (viewId !== null) {
|
||||
return VIEW_KEYS[viewId] === undefined ? [] : [VIEW_KEYS[viewId]]
|
||||
}
|
||||
return SHORTCUTS.find((shortcut) => shortcut.id === id)?.chords ?? []
|
||||
}
|
||||
|
||||
export function chordsOf(id: string, bindings: Bindings): Chord[] {
|
||||
return bindings[id] ?? defaultChords(id)
|
||||
}
|
||||
|
||||
/** The chord of a key press; null for a modifier alone, which names no key yet. */
|
||||
export function chordOf(press: KeyPress): Chord | null {
|
||||
if (MODIFIER_KEYS.has(press.key) || press.key === '') {
|
||||
return null
|
||||
}
|
||||
const key = press.key.length === 1 ? press.key.toLowerCase() : press.key
|
||||
const keepsShift = press.shiftKey && (key.length > 1 || key !== key.toUpperCase())
|
||||
const modifiers = [press.ctrlKey || press.metaKey ? 'ctrl+' : '', press.altKey ? 'alt+' : '', keepsShift ? 'shift+' : '']
|
||||
return modifiers.join('') + key
|
||||
}
|
||||
|
||||
/** Whether a text is a chord in the form {@link chordOf} makes. */
|
||||
export function isChord(text: unknown): text is Chord {
|
||||
if (typeof text !== 'string') {
|
||||
return false
|
||||
}
|
||||
const parsed = splitChord(text)
|
||||
if (parsed === null) {
|
||||
return false
|
||||
}
|
||||
return chordOf({ key: parsed.key, ctrlKey: parsed.modifiers.includes('ctrl+'), metaKey: false, altKey: parsed.modifiers.includes('alt+'), shiftKey: parsed.modifiers.includes('shift+') }) === text
|
||||
}
|
||||
|
||||
/** A chord as people write it, like Ctrl+Shift+Z or Esc. */
|
||||
export function chordText(chord: Chord): string {
|
||||
const parsed = splitChord(chord)
|
||||
if (parsed === null) {
|
||||
return chord
|
||||
}
|
||||
const modifiers = parsed.modifiers.map((prefix) => prefix[0].toUpperCase() + prefix.slice(1))
|
||||
return modifiers.join('') + keyName(parsed.key)
|
||||
}
|
||||
|
||||
export function chordsText(chords: Chord[]): string {
|
||||
return chords.map(chordText).join(', ')
|
||||
}
|
||||
|
||||
/** The first key of a shortcut as shown beside it, empty when it has none. */
|
||||
export function keyTextOf(id: string, bindings: Bindings): string {
|
||||
const chords = chordsOf(id, bindings)
|
||||
return chords.length === 0 ? '' : chordText(chords[0])
|
||||
}
|
||||
|
||||
/** Whether the key press is one of the keys of the shortcut. */
|
||||
export function matches(press: KeyPress, id: string, bindings: Bindings): boolean {
|
||||
const chord = chordOf(press)
|
||||
return chord !== null && chordsOf(id, bindings).includes(chord)
|
||||
}
|
||||
|
||||
/** The window shortcut a key press triggers, if any. */
|
||||
export function windowShortcutFor(press: KeyPress, rows: ShortcutRow[], bindings: Bindings): string | null {
|
||||
const chord = chordOf(press)
|
||||
if (chord === null) {
|
||||
return null
|
||||
}
|
||||
return rows.filter((row) => GROUP_SCOPES[row.group].windowWide).find((row) => chordsOf(row.id, bindings).includes(chord))?.id ?? null
|
||||
}
|
||||
|
||||
/** The other shortcuts the chord already triggers where {@code row} works too. */
|
||||
export function clashesWith(row: ShortcutRow, chord: Chord, rows: ShortcutRow[], bindings: Bindings): ShortcutRow[] {
|
||||
return rows.filter((other) => other.id !== row.id && sharesKeys(row.group, other.group) && chordsOf(other.id, bindings).includes(chord))
|
||||
}
|
||||
|
||||
/** The bindings a settings file holds, without what is not a list of chords. */
|
||||
export function sanitizeBindings(stored: unknown): Bindings {
|
||||
if (typeof stored !== 'object' || stored === null || Array.isArray(stored)) {
|
||||
return {}
|
||||
}
|
||||
const bindings: Bindings = {}
|
||||
for (const [id, chords] of Object.entries(stored)) {
|
||||
if (Array.isArray(chords) && chords.every(isChord)) {
|
||||
bindings[id] = [...new Set<Chord>(chords)]
|
||||
}
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
|
||||
/** Whether a key press goes to a field being typed into, so the studio's keys leave it alone. */
|
||||
export function isTypingInto(target: EventTarget | null): boolean {
|
||||
return target instanceof HTMLInputElement || target instanceof HTMLSelectElement || target instanceof HTMLTextAreaElement
|
||||
}
|
||||
|
||||
function sharesKeys(first: ShortcutGroup, second: ShortcutGroup): boolean {
|
||||
const a = GROUP_SCOPES[first]
|
||||
const b = GROUP_SCOPES[second]
|
||||
return (a.windowWide && b.windowWide) || (a.nodeEditor && b.nodeEditor)
|
||||
}
|
||||
|
||||
function splitChord(chord: Chord): { modifiers: string[]; key: string } | null {
|
||||
let key = chord
|
||||
const modifiers: string[] = []
|
||||
for (const prefix of MODIFIER_PREFIXES) {
|
||||
if (key.startsWith(prefix) && key.length > prefix.length) {
|
||||
modifiers.push(prefix)
|
||||
key = key.slice(prefix.length)
|
||||
}
|
||||
}
|
||||
return key === '' ? null : { modifiers, key }
|
||||
}
|
||||
|
||||
function keyName(key: string): string {
|
||||
if (KEY_NAMES[key] !== undefined) {
|
||||
return KEY_NAMES[key]
|
||||
}
|
||||
if (key.length === 1) {
|
||||
return key.toUpperCase()
|
||||
}
|
||||
return key.startsWith(ARROW_PREFIX) ? key.slice(ARROW_PREFIX.length) : key
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useCallback, useSyncExternalStore } from 'react'
|
||||
import { createShortcutStore } from './shortcutStore'
|
||||
import { keyTextOf, type Bindings } from './shortcuts'
|
||||
|
||||
export const shortcutStore = createShortcutStore({
|
||||
load: () => window.studio.loadShortcuts(),
|
||||
save: (bindings) => window.studio.saveShortcuts(bindings)
|
||||
})
|
||||
|
||||
/** The keys the user rebound; components read them through here so a rebound key shows and works at once. */
|
||||
export function useBindings(): Bindings {
|
||||
return useSyncExternalStore(shortcutStore.subscribe, shortcutStore.snapshot)
|
||||
}
|
||||
|
||||
/** The first key of a shortcut as shown beside it, empty when it has none. */
|
||||
export function useKeyText(): (id: string) => string {
|
||||
const bindings = useBindings()
|
||||
return useCallback((id) => keyTextOf(id, bindings), [bindings])
|
||||
}
|
||||
@@ -6,6 +6,9 @@ export interface BridgeConnection {
|
||||
startedMillis?: number
|
||||
}
|
||||
|
||||
/** The keys the user rebound, by shortcut id, each a list of key chords. */
|
||||
export type StoredShortcuts = Record<string, string[]>
|
||||
|
||||
export type ThemeChoice = 'system' | 'light' | 'dark'
|
||||
|
||||
/** What the preload script hands the renderer. */
|
||||
@@ -16,6 +19,9 @@ export interface StudioHost {
|
||||
onLink(listener: (link: string) => void): () => void
|
||||
setTheme(theme: ThemeChoice): void
|
||||
copyText(text: string): void
|
||||
/** The rebound shortcuts from the studio settings, as the file holds them, for the caller to check. */
|
||||
loadShortcuts(): Promise<unknown>
|
||||
saveShortcuts(shortcuts: StoredShortcuts): void
|
||||
}
|
||||
|
||||
const LINK_PROTOCOL = 'iris-studio:'
|
||||
|
||||
Reference in new issue
Block a user