Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import { confirm } from "@humansignal/ui/lib/modal";
import { ToastType, useToast } from "@humansignal/ui/lib/toast/toast";
// @ts-ignore
import { useAPI } from "@humansignal/core";
import { useCallback, useEffect, useState } from "react";
import {
  type ApiResponse,
  type ExportData,
  getTypedDefaultHotkeys,
  type Hotkey,
  type HotkeySettings,
  type ImportData,
  type SaveResult,
} from "../sections/Hotkeys/utils";
 
// Type the imported defaults and convert numeric ids to strings
const typedDefaultHotkeys: Hotkey[] = getTypedDefaultHotkeys();
 
export const useHotkeys = () => {
  const toast = useToast();
  const [hotkeys, setHotkeys] = useState<Hotkey[]>([]);
  const [hotkeySettings, setHotkeySettings] = useState<HotkeySettings>({});
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const api = useAPI();
 
  // Update hotkeys with custom settings
  const updateHotkeysWithCustomSettings = useCallback(
    (
      defaultHotkeys: Hotkey[],
      customHotkeys: Record<string, { key: string; active: boolean; description?: string }>,
    ): Hotkey[] => {
      return defaultHotkeys.map((hotkey: Hotkey) => {
        // Create the lookup key format used in the API response (section:element)
        const lookupKey = `${hotkey.section}:${hotkey.element}`;
 
        // Check if there's a custom setting for this hotkey
        if (customHotkeys[lookupKey]) {
          const customSetting = customHotkeys[lookupKey];
          // Create a new object with the default properties and override with custom ones
          return {
            ...hotkey,
            key: customSetting.key,
            active: customSetting.active,
            // Preserve the original label, only update description if provided
            ...(customSetting.description && {
              description: customSetting.description,
            }),
          };
        }
 
        // If no custom setting exists, return the default hotkey unchanged
        return hotkey;
      });
    },
    [],
  );
 
  // Simple hotkey reload - just update global state and call setKeymap
  const reloadHotkeysInRuntime = useCallback(
    (customHotkeys: Record<string, { key: string; active: boolean; description?: string }>) => {
      // Update APP_SETTINGS.user.customHotkeys (for Help modal and fallback)
      if (window.APP_SETTINGS?.user) {
        window.APP_SETTINGS.user.customHotkeys = customHotkeys;
      }
 
      const EditorHotkey = window.Htx?.Hotkey;
 
      // Transform custom hotkeys to editor format (same logic as base.html)
      const editorCustomHotkeys: Record<string, any> = {};
      const prefixRegex = /^(annotation|timeseries|audio|regions|video|image_gallery|tools):(.*)/;
 
      for (const key in customHotkeys) {
        const match = key.match(prefixRegex);
        if (match) {
          const [, , shortKey] = match;
          const value = customHotkeys[key];
 
          if (value && value.active === false) {
            editorCustomHotkeys[shortKey] = { ...value, key: null };
          } else {
            editorCustomHotkeys[shortKey] = value;
          }
        }
      }
 
      // Get current keymap and merge with custom hotkeys
      const currentKeymap = EditorHotkey?.keymap ? { ...EditorHotkey.keymap } : {};
      const mergedKeymap = Object.assign({}, currentKeymap, editorCustomHotkeys);
 
      // Update APP_SETTINGS.editor_keymap (for DataManager/Explorer)
      if (window.APP_SETTINGS) {
        window.APP_SETTINGS.editor_keymap = mergedKeymap;
      }
 
      // Call Hotkey.setKeymap() - the main propagation path
      try {
        EditorHotkey?.setKeymap(mergedKeymap as any);
      } catch (error) {
        console.warn("Failed to update hotkeys:", error);
      }
    },
    [],
  );
 
  // Load hotkeys from API
  const loadHotkeysFromAPI = useCallback(async () => {
    try {
      setIsLoading(true);
 
      // Use proper API endpoint name from the config
      const response = await api.callApi("hotkeys" as any);
 
      if (response && (response as ApiResponse).custom_hotkeys) {
        // Use API data
        const apiResponse = response as ApiResponse;
        const updatedHotkeys = updateHotkeysWithCustomSettings(typedDefaultHotkeys, apiResponse.custom_hotkeys || {});
        setHotkeys(updatedHotkeys);
        // Store current settings from API response
        setHotkeySettings(apiResponse.hotkey_settings || {});
      } else {
        // Fallback to window.APP_SETTINGS
        const customHotkeys = window.APP_SETTINGS?.user?.customHotkeys || {};
        const updatedHotkeys = updateHotkeysWithCustomSettings(typedDefaultHotkeys, customHotkeys);
        setHotkeys(updatedHotkeys);
        // No settings available in fallback
        setHotkeySettings({});
      }
    } catch (error) {
      console.error("Error loading hotkeys from API:", error);
 
      // Fallback to window.APP_SETTINGS on error
      const customHotkeys = window.APP_SETTINGS?.user?.customHotkeys || {};
      const updatedHotkeys = updateHotkeysWithCustomSettings(typedDefaultHotkeys, customHotkeys);
      setHotkeys(updatedHotkeys);
      // No settings available in fallback
      setHotkeySettings({});
 
      // Show non-blocking error notification
      if (toast) {
        toast.show({
          message: "Could not load custom hotkeys from server, using cached settings",
          type: ToastType.error,
        });
      }
    } finally {
      setIsLoading(false);
    }
  }, [api, toast, updateHotkeysWithCustomSettings]);
 
  // Save hotkeys to API function (handles both save and reset operations)
  const saveHotkeysToAPI = useCallback(
    async (currentHotkeys: Hotkey[], currentSettings: HotkeySettings): Promise<SaveResult> => {
      // Convert current hotkeys to API format - INCLUDE description to maintain API compatibility
      const customHotkeys: Record<string, { key: string; active: boolean; description?: string }> = {};
 
      // Process all current hotkeys (if empty, this results in reset)
      currentHotkeys.forEach((hotkey: Hotkey) => {
        const keyId = `${hotkey.section}:${hotkey.element}`;
        customHotkeys[keyId] = {
          key: hotkey.key,
          active: hotkey.active,
          ...(hotkey.description && { description: hotkey.description }),
        };
      });
 
      const requestBody = {
        custom_hotkeys: customHotkeys,
        hotkey_settings: currentSettings,
      };
 
      try {
        // Use proper API endpoint name from the config
        const response = await api.callApi("updateHotkeys" as any, {
          body: requestBody,
        });
 
        // Check for API-level errors
        if (response?.error) {
          return {
            ok: false,
            error: response.error,
            data: response,
          };
        }
 
        // Apply hotkeys immediately without page refresh
        reloadHotkeysInRuntime(customHotkeys);
 
        return {
          ok: true,
          error: undefined,
          data: response,
        };
      } catch (error: unknown) {
        const isReset = currentHotkeys.length === 0;
        const operation = isReset ? "resetting" : "saving";
        console.error(`Error ${operation} hotkeys:`, error);
 
        // Provide more specific error messages
        let errorMessage = `Failed to ${isReset ? "reset" : "save"} hotkeys`;
        if (error && typeof error === "object" && "response" in error) {
          const err = error as any;
          // Server responded with error status
          if (err.response?.status === 400) {
            errorMessage = err.response.data?.error || `Invalid ${isReset ? "reset request" : "hotkeys configuration"}`;
          } else if (err.response?.status === 401) {
            errorMessage = "Authentication required";
          } else if (err.response?.status >= 500) {
            errorMessage = "Server error - please try again later";
          }
        } else if (error && typeof error === "object" && "request" in error) {
          // Network error
          errorMessage = "Network error - please check your connection";
        }
 
        return {
          ok: false,
          error: errorMessage,
        };
      }
    },
    [api],
  );
 
  // Handle resetting all hotkeys to defaults
  const handleResetToDefaults = useCallback(() => {
    confirm({
      title: "Reset Hotkeys to Defaults?",
      body: "Are you sure you want to reset all hotkeys and settings to their default values? This action cannot be undone.",
      okText: "Reset to Defaults",
      buttonLook: "negative",
      style: { width: 500 },
      onOk: async () => {
        setIsLoading(true);
 
        try {
          // Reset hotkeys to defaults in the backend API (sets custom_hotkeys to {})
          const result = await saveHotkeysToAPI([], {});
 
          if (result.ok) {
            if (toast) {
              toast.show({
                message: "All hotkeys and settings have been reset to defaults and saved",
                type: ToastType.info,
              });
            }
            // Update local state to reflect the reset
            setHotkeys([...typedDefaultHotkeys]);
          } else {
            if (toast) {
              toast.show({
                message: `Failed to save reset hotkeys: ${result.error || "Unknown error"}`,
                type: ToastType.error,
              });
            }
          }
        } catch (error: unknown) {
          if (toast) {
            const errorMessage = error instanceof Error ? error.message : "Unknown error";
            toast.show({
              message: `Error resetting hotkeys: ${errorMessage}`,
              type: ToastType.error,
            });
          }
        } finally {
          setIsLoading(false);
        }
      },
    });
  }, [saveHotkeysToAPI, toast]);
 
  // Handle exporting hotkeys
  const handleExportHotkeys = useCallback(() => {
    // Create export data including current settings
    const exportData: ExportData = {
      hotkeys: hotkeys,
      settings: hotkeySettings,
      exportedAt: new Date().toISOString(),
      version: "1.0",
    };
 
    // Create a JSON string of the export data
    const exportJson = JSON.stringify(exportData, null, 2);
 
    // Create a blob with the JSON
    const blob = new Blob([exportJson], { type: "application/json" });
    const url = URL.createObjectURL(blob);
 
    // Create a temporary link and click it to download the file
    const link = document.createElement("a");
    link.href = url;
    link.download = "hotkeys-export.json";
    document.body.appendChild(link);
    link.click();
 
    // Clean up
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
 
    if (toast) {
      toast.show({
        message: "Hotkeys exported successfully",
        type: ToastType.info,
      });
    }
  }, [hotkeys, hotkeySettings, toast]);
 
  // Handle importing hotkeys
  const handleImportHotkeys = useCallback(
    async (importedData: ImportData | Hotkey[]) => {
      try {
        setIsLoading(true);
 
        // Handle both old format (just hotkeys array) and new format (with settings)
        const importedHotkeys = Array.isArray(importedData) ? importedData : importedData.hotkeys || [];
        const importedSettings: HotkeySettings = Array.isArray(importedData) ? {} : importedData.settings || {};
 
        // Save all imported data to API
        const result = await saveHotkeysToAPI(importedHotkeys, importedSettings);
 
        if (!result.ok) {
          throw new Error(result.error || "Failed to save imported hotkeys");
        }
 
        // Update local state
        setHotkeys(importedHotkeys);
 
        if (toast) {
          toast.show({
            message: "Hotkeys imported successfully",
            type: ToastType.info,
          });
        }
 
        // Reload from API to ensure consistency
        await loadHotkeysFromAPI();
      } catch (error: unknown) {
        if (toast) {
          const errorMessage = error instanceof Error ? error.message : "Unknown error";
          toast.show({
            message: `Error importing hotkeys: ${errorMessage}`,
            type: ToastType.error,
          });
        }
      } finally {
        setIsLoading(false);
      }
    },
    [saveHotkeysToAPI, loadHotkeysFromAPI, toast],
  );
 
  // Load hotkeys on hook mount
  useEffect(() => {
    loadHotkeysFromAPI();
  }, [loadHotkeysFromAPI]);
 
  return {
    hotkeys,
    setHotkeys,
    hotkeySettings,
    setHotkeySettings,
    isLoading,
    setIsLoading,
    loadHotkeysFromAPI,
    saveHotkeysToAPI,
    handleResetToDefaults,
    handleExportHotkeys,
    handleImportHotkeys,
  };
};