forked from cjpais/Handy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandyShortcut.tsx
More file actions
351 lines (318 loc) · 11 KB
/
HandyShortcut.tsx
File metadata and controls
351 lines (318 loc) · 11 KB
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
import React, { useEffect, useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { type } from "@tauri-apps/plugin-os";
import {
getKeyName,
formatKeyCombination,
normalizeKey,
type OSType,
} from "../../lib/utils/keyboard";
import { ResetButton } from "../ui/ResetButton";
import { SettingContainer } from "../ui/SettingContainer";
import { useSettings } from "../../hooks/useSettings";
import { commands } from "@/bindings";
import { toast } from "sonner";
interface HandyShortcutProps {
descriptionMode?: "inline" | "tooltip";
grouped?: boolean;
shortcutId: string;
disabled?: boolean;
}
export const HandyShortcut: React.FC<HandyShortcutProps> = ({
descriptionMode = "tooltip",
grouped = false,
shortcutId,
disabled = false,
}) => {
const { t } = useTranslation();
const { getSetting, updateBinding, resetBinding, isUpdating, isLoading } =
useSettings();
const [keyPressed, setKeyPressed] = useState<string[]>([]);
const [recordedKeys, setRecordedKeys] = useState<string[]>([]);
const [editingShortcutId, setEditingShortcutId] = useState<string | null>(
null,
);
const [originalBinding, setOriginalBinding] = useState<string>("");
const [osType, setOsType] = useState<OSType>("unknown");
const shortcutRefs = useRef<Map<string, HTMLDivElement | null>>(new Map());
const bindings = getSetting("bindings") || {};
// Detect and store OS type
useEffect(() => {
const detectOsType = async () => {
try {
const detectedType = type();
let normalizedType: OSType;
switch (detectedType) {
case "macos":
normalizedType = "macos";
break;
case "windows":
normalizedType = "windows";
break;
case "linux":
normalizedType = "linux";
break;
default:
normalizedType = "unknown";
}
setOsType(normalizedType);
} catch (error) {
console.error("Error detecting OS type:", error);
setOsType("unknown");
}
};
detectOsType();
}, []);
useEffect(() => {
// Only add event listeners when we're in editing mode
if (editingShortcutId === null) return;
let cleanup = false;
// Keyboard event listeners
const handleKeyDown = async (e: KeyboardEvent) => {
if (cleanup) return;
if (e.repeat) return; // ignore auto-repeat
if (e.key === "Escape") {
// Cancel recording and restore original binding
if (editingShortcutId && originalBinding) {
try {
await updateBinding(editingShortcutId, originalBinding);
} catch (error) {
console.error("Failed to restore original binding:", error);
toast.error(t("settings.general.shortcut.errors.restore"));
}
} else if (editingShortcutId) {
await commands.resumeBinding(editingShortcutId).catch(console.error);
}
setEditingShortcutId(null);
setKeyPressed([]);
setRecordedKeys([]);
setOriginalBinding("");
return;
}
e.preventDefault();
// Get the key with OS-specific naming and normalize it
const rawKey = getKeyName(e, osType);
const key = normalizeKey(rawKey);
if (!keyPressed.includes(key)) {
setKeyPressed((prev) => [...prev, key]);
// Also add to recorded keys if not already there
if (!recordedKeys.includes(key)) {
setRecordedKeys((prev) => [...prev, key]);
}
}
};
const handleKeyUp = async (e: KeyboardEvent) => {
if (cleanup) return;
e.preventDefault();
// Get the key with OS-specific naming and normalize it
const rawKey = getKeyName(e, osType);
const key = normalizeKey(rawKey);
// Remove from currently pressed keys
setKeyPressed((prev) => prev.filter((k) => k !== key));
// If no keys are pressed anymore, commit the shortcut
const updatedKeyPressed = keyPressed.filter((k) => k !== key);
if (updatedKeyPressed.length === 0 && recordedKeys.length > 0) {
// Create the shortcut string from all recorded keys
// Sort keys so modifiers come first, then the main key
const modifiers = [
"ctrl",
"control",
"shift",
"alt",
"option",
"meta",
"command",
"cmd",
"super",
"win",
"windows",
];
const sortedKeys = recordedKeys.sort((a, b) => {
const aIsModifier = modifiers.includes(a.toLowerCase());
const bIsModifier = modifiers.includes(b.toLowerCase());
if (aIsModifier && !bIsModifier) return -1;
if (!aIsModifier && bIsModifier) return 1;
return 0;
});
const newShortcut = sortedKeys.join("+");
if (editingShortcutId && bindings[editingShortcutId]) {
try {
await updateBinding(editingShortcutId, newShortcut);
} catch (error) {
console.error("Failed to change binding:", error);
toast.error(
t("settings.general.shortcut.errors.set", {
error: String(error),
}),
);
// Reset to original binding on error
if (originalBinding) {
try {
await updateBinding(editingShortcutId, originalBinding);
} catch (resetError) {
console.error("Failed to reset binding:", resetError);
toast.error(t("settings.general.shortcut.errors.reset"));
}
}
}
// Exit editing mode and reset states
setEditingShortcutId(null);
setKeyPressed([]);
setRecordedKeys([]);
setOriginalBinding("");
}
}
};
// Add click outside handler
const handleClickOutside = async (e: MouseEvent) => {
if (cleanup) return;
const activeElement = shortcutRefs.current.get(editingShortcutId);
if (activeElement && !activeElement.contains(e.target as Node)) {
// Cancel shortcut recording and restore original binding
if (editingShortcutId && originalBinding) {
try {
await updateBinding(editingShortcutId, originalBinding);
} catch (error) {
console.error("Failed to restore original binding:", error);
toast.error(t("settings.general.shortcut.errors.restore"));
}
} else if (editingShortcutId) {
commands.resumeBinding(editingShortcutId).catch(console.error);
}
setEditingShortcutId(null);
setKeyPressed([]);
setRecordedKeys([]);
setOriginalBinding("");
}
};
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);
window.addEventListener("click", handleClickOutside);
return () => {
cleanup = true;
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
window.removeEventListener("click", handleClickOutside);
};
}, [
keyPressed,
recordedKeys,
editingShortcutId,
bindings,
originalBinding,
updateBinding,
osType,
]);
// Start recording a new shortcut
const startRecording = async (id: string) => {
if (editingShortcutId === id) return; // Already editing this shortcut
// Suspend current binding to avoid firing while recording
await commands.suspendBinding(id).catch(console.error);
// Store the original binding to restore if canceled
setOriginalBinding(bindings[id]?.current_binding || "");
setEditingShortcutId(id);
setKeyPressed([]);
setRecordedKeys([]);
};
// Format the current shortcut keys being recorded
const formatCurrentKeys = (): string => {
if (recordedKeys.length === 0)
return t("settings.general.shortcut.pressKeys");
// Use the same formatting as the display to ensure consistency
return formatKeyCombination(recordedKeys.join("+"), osType);
};
// Store references to shortcut elements
const setShortcutRef = (id: string, ref: HTMLDivElement | null) => {
shortcutRefs.current.set(id, ref);
};
// If still loading, show loading state
if (isLoading) {
return (
<SettingContainer
title={t("settings.general.shortcut.title")}
description={t("settings.general.shortcut.description")}
descriptionMode={descriptionMode}
grouped={grouped}
>
<div className="text-sm text-mid-gray">
{t("settings.general.shortcut.loading")}
</div>
</SettingContainer>
);
}
// If no bindings are loaded, show empty state
if (Object.keys(bindings).length === 0) {
return (
<SettingContainer
title={t("settings.general.shortcut.title")}
description={t("settings.general.shortcut.description")}
descriptionMode={descriptionMode}
grouped={grouped}
>
<div className="text-sm text-mid-gray">
{t("settings.general.shortcut.none")}
</div>
</SettingContainer>
);
}
const binding = bindings[shortcutId];
if (!binding) {
return (
<SettingContainer
title={t("settings.general.shortcut.title")}
description={t("settings.general.shortcut.notFound")}
descriptionMode={descriptionMode}
grouped={grouped}
>
<div className="text-sm text-mid-gray">
{t("settings.general.shortcut.none")}
</div>
</SettingContainer>
);
}
// Get translated name and description for the binding
const translatedName = t(
`settings.general.shortcut.bindings.${shortcutId}.name`,
binding.name,
);
const translatedDescription = t(
`settings.general.shortcut.bindings.${shortcutId}.description`,
binding.description,
);
return (
<SettingContainer
title={translatedName}
description={translatedDescription}
descriptionMode={descriptionMode}
grouped={grouped}
disabled={disabled}
layout="horizontal"
>
<div className="flex items-center space-x-1">
{editingShortcutId === shortcutId ? (
<div
ref={(ref) => setShortcutRef(shortcutId, ref)}
className="px-2 py-1 text-sm font-semibold border border-logo-primary bg-logo-primary/30 rounded min-w-[120px] text-center"
>
{formatCurrentKeys()}
</div>
) : (
<div
className={`px-2 py-1 text-sm bg-mid-gray/10 border border-mid-gray/80 hover:bg-logo-primary/10 rounded cursor-pointer hover:border-logo-primary ${
binding.current_binding ? "font-semibold" : "text-mid-gray italic"
}`}
onClick={() => startRecording(shortcutId)}
>
{binding.current_binding
? formatKeyCombination(binding.current_binding, osType)
: t("settings.general.shortcut.notSet", "Not set")}
</div>
)}
<ResetButton
onClick={() => resetBinding(shortcutId)}
disabled={isUpdating(`binding_${shortcutId}`)}
/>
</div>
</SettingContainer>
);
};